Chia task lớn thành chuỗi bước có gate — pattern nền tảng đầu tiên trong 21 design pattern của Antonio Gulli.
Prompt monolithic vỡ ở đâu — 5 pain point cụ thể
Sequential pipeline, structured output, gate check
Linear, gated, JSON pipeline, self-consistency
Code Python, so sánh 4 framework, anti-pattern
5 điều nhớ + bài tập chuẩn bị S-06
• Instruction neglect — 8 yêu cầu trong 1 prompt, model bỏ 3.
• Context overload — nhồi input dài, quan trọng bị "lost in middle".
• Format drift — đôi khi trả JSON, đôi khi Markdown, đôi khi lẫn text.
• Khó debug — sai ở đâu trong chuỗi lý luận? Không biết.
• Không tái sử dụng — prompt monolithic khoá cứng vào 1 use-case.
• Mỗi bước 1 mục tiêu — model focus, ít sót.
• Output có schema — validate được, gate chặn sai lan xuống.
• Bước sau nhận đầu vào sạch — độ chính xác cộng dồn.
• Debug được từng step — log, replay, cost-per-step.
• Ghép mô-đun — dùng lại step cho use-case khác.
Anthropic (Building Effective Agents): chaining phù hợp khi bạn có thể tách task tuần tự, đổi độ trễ lấy độ tin cậy.
Chia task theo bước tự nhiên của quy trình.
Mỗi step 1 nhiệm vụ, prompt ngắn & rõ.
JSON / Pydantic / Zod schema giữa các bước.
Validate hoặc judge trước khi vào step kế.
Bóc thông tin thô từ input (email, PDF, form).
Chuẩn hoá về JSON schema định trước.
Suy luận, tra dữ liệu bổ sung.
Sinh output cuối theo tone/format mong muốn.
Ví dụ: từ email khách hàng ➔ JSON {intent, entities} ➔ Query CRM ➔ Reply tiếng Việt lịch sự. Gate: JSON schema valid + intent ∈ allowlist.
Chuỗi step tuần tự thuần, không branching. Dùng khi quy trình xác định trước, mỗi step độc lập.
Ví dụ: bóc PDF → tóm tắt → dịch → viết email.
Giữa các step có gate: schema validation, LLM-as-judge, hoặc human approval. Chặn "rác" lan xuống.
Ví dụ: draft → judge cho điểm ≥ 8 → publish. Fail thì retry.
Mọi step in/out đều là JSON theo Pydantic/Zod schema. Type-safe, dễ test, dễ nối tool.
Ví dụ: Instructor lib (Python), Zod-GPT (TS).
Chạy step quan trọng N lần với temperature > 0, chọn majority answer. Đổi cost lấy accuracy.
Ví dụ: math reasoning, code generation critical.
# Step 1: Extract intent + entities → JSON class EmailAnalysis(BaseModel): intent: Literal["billing", "support", "sales"] entities: dict priority: Literal["low", "med", "high"] analysis = llm.extract(email, schema=EmailAnalysis) # structured output # Gate: validate schema + allowlist intent assert analysis.intent in ALLOWED_INTENTS, "unknown intent" # Step 2: Query CRM cho context khách hàng customer = crm.lookup(analysis.entities["customer_id"]) # Step 3: Draft reply với context draft = llm.generate( prompt=DRAFT_PROMPT.format(analysis=analysis, customer=customer), temperature=0.3, ) # Step 4 (gate): LLM-as-judge chấm chất lượng score = judge_llm.score(draft, rubric="tone,accuracy,brevity") if score < 8: draft = llm.retry(feedback=judge_llm.critique) return draft
| Framework | Cấu trúc chain | Structured output | Gate mechanism | Điểm mạnh |
|---|---|---|---|---|
| LangGraph | Graph nodes + edges | Pydantic state | Conditional edge | Debug rõ, visualize được |
| CrewAI | Process.sequential |
Task output_pydantic | Task callback | Role-based, code ngắn |
| Google ADK | SequentialAgent |
Schema per agent | Callback + guardrails | Native Gemini, Vertex |
| Claude Code | Skill + subagent chain | Tool output JSON | TaskUpdate + hooks | Filesystem-first, plan mode |
Cùng 1 pattern, 4 cú pháp. Chọn theo ecosystem đội đang có sẵn (Python vs TS vs GCP vs Anthropic).
>5 step, mỗi step error rate 5% ⇒ end-to-end < 77%. Merge lại thành 3 step.
Trả markdown giữa các step ⇒ regex hack ⇒ vỡ khi model đổi format.
Gate fail ⇒ retry không cap ⇒ chi phí phình, latency tăng phi tuyến.
Không lưu input/output từng step ⇒ không debug được production incident.
/opsx:proposeAI đề xuất ⇒ sinh 4 file cấu trúc.
/opsx:applyAI đọc tasks.md ⇒ viết code từng bước.
/opsx:syncĐồng bộ spec chính, verify.
/opsx:archiveLưu trữ change, merge spec.
Mô tả ý định thay đổi — gate người review.
Spec hành vi hệ thống (structured).
Design decision, alternative đã xét.
Danh sách task — input cho bước 2.
Nguồn: Cẩm nang OpenSpec Framework (VN) · github.com/Fission-AI/OpenSpec
URL/PDF → trích văn bản → tóm tắt → trích thực thể (tên, ngày, địa điểm) → truy vấn KB nội bộ → báo cáo.
Trợ lý nghiên cứu AI — đọc & phân tích content tự động.
Câu hỏi phức → tách subquestion → nghiên cứu song song từng phần → tổng hợp → tinh chỉnh cuối.
Kết hợp Parallelization (S-06) ở bước nghiên cứu.
OCR biểu mẫu PDF → LLM trích văn bản → chuẩn hoá (số chữ → số) → uỷ thác tính toán cho calculator tool.
Ứng dụng invoice, KYC, hồ sơ giấy tờ.
Ý tưởng → dàn ý → viết nháp từng phần (kèm ngữ cảnh phần trước) → review mạch lạc, giọng điệu, ngữ pháp.
Có thể assign vai riêng cho mỗi bước (writer, editor).
Nguồn: Cẩm nang thực hành xây dựng các hệ thống thông minh (bản dịch VN của A. Gulli, Ch.1)
# Skill-based chain mkdir .claude/skills/extract mkdir .claude/skills/structure mkdir .claude/skills/reply # Mỗi SKILL.md = 1 step claude "Đọc email.txt → extract → structure JSON → reply lịch sự" # Plan mode chain tự động claude --permission-mode plan
# Rules file — gate mỗi step mkdir .cursor/rules # 01-extract.mdc # 02-structure-json.mdc # 03-validate-schema.mdc # 04-generate-reply.mdc # Composer đọc tuần tự cursor . # Cmd+I → Composer mode # Prompt: "chain 4 rules" # Background agent cursor-agent
# Shell pipe = chain gemini -p "Trích entities" \ < email.txt \ | gemini -p "JSON schema: {name,email,intent}" \ | gemini -p "Viết reply VN" \ > out.txt # Non-interactive gemini -p "..." -m \ gemini-2.5-pro # Có GEMINI.md context
Setup Linux/macOS: curl -fsSL https://claude.ai/install.sh | sh · npm i -g @google/gemini-cli · Cursor: tải app + cursor vào PATH.
Setup Windows: winget install Anthropic.Claude · npm i -g @google/gemini-cli · Cursor: installer .exe + Enable cursor CLI in PATH trong settings.
Config path: Linux/macOS ~/.claude/ · ~/.cursor/ · ~/.gemini/ — Windows %USERPROFILE%\.claude\ · %APPDATA%\Cursor\ · %USERPROFILE%\.gemini\.
Chaining là đổi latency lấy reliability — pattern nền tảng nhất của Part 1 (Ch.1 sách Gulli).
Structured output (JSON schema) giữa các step là bắt buộc — không có schema thì không có gate.
Giới hạn 3–5 step. Nhiều hơn ⇒ error propagation ăn hết reliability.
4 biến thể: Linear · Gated · JSON Pipeline · Self-Consistency. Chọn theo yêu cầu độ chính xác vs cost.
Log mọi step: input, output, tokens, latency. Nếu không log ⇒ production debug là mò kim.
Buổi 6 — Routing & Parallelization
Khi chuỗi tuyến tính không đủ: chia nhánh và chạy song song.