AI agent: từ vòng lặp ReAct tới multi-agent chạy production

- Published on
- 17 mins read
Đưa cùng một ticket bug cho hai công cụ AI. Một cái trả về đoạn hướng dẫn check null. Cái kia mở Jira, sửa code, chạy test rồi để lại một Pull Request chờ review.
Phần lớn khác biệt không nằm ở model. Nó nằm ở phần bọc quanh model: bộ nhớ, bộ tool và một vòng lặp cho phép nó tự đi tiếp khi bước trước hỏng.
# ai agent là gì?
Gặp NullPointerException trên production mà dùng chatbot kiểu cũ, bạn phải tự đọc log, copy stack trace dán vào khung chat, đọc câu trả lời rồi tự mở IDE lên sửa. Giao thẳng ticket đó cho một AI Agent thì nó có thể tự mở Jira đọc mô tả, grep tìm file trong repo, viết bản vá, chạy test rồi tạo luôn Pull Request. Chatbot dừng ở chỗ trả lời câu hỏi. Agent đi tới chỗ giải quyết vấn đề.
Điểm khác biệt nằm ở tính chủ động: chatbot hoạt động bị động (hỏi → trả lời → xong), còn agent nhận mục tiêu rồi tự lên kế hoạch, thực hiện chuỗi hành động qua nhiều bước và tự sửa sai cho đến khi ra kết quả. Khả năng này gọi là agency, tức quyền tự quyết định bước tiếp theo dựa trên phản hồi thực tế từ bước trước đó.
Chatbot:
User: "Cách fix NullPointerException?"
Bot: "Check null trước khi access..." → DONE
AI Agent:
User: "Fix bug PORTAL-123"
Agent: (thinking) "Cần hiểu bug → đọc ticket → xem code → tìm root cause → fix → test → PR"
Step 1: Đọc Jira ticket PORTAL-123 → hiểu symptom
Step 2: Tìm file liên quan trong codebase
Step 3: Đọc code, identify root cause
Step 4: Viết fix
Step 5: Chạy tests
Step 6: Tests fail → đọc error → sửa lại
Step 7: Tests pass → tạo PR
→ DONE (multi-step, self-correcting)
# spectrum of ai autonomy
Level 0: Chatbot → Q&A, no actions
Level 1: Tool-augmented → Answer + call 1 tool khi cần
Level 2: Multi-step agent → Plan + execute sequence of tools
Level 3: Autonomous agent → Self-plan, self-correct, handle errors, create sub-goals
Level 4: Multi-agent → Nhiều agents collaborate, delegate, review nhau
Phần lớn công cụ hỗ trợ code hiện nay (GitHub Copilot, Cursor, Kiro) đang nằm ở Level 2–3. Mô hình Multi-agent (Level 4) đang phát triển nhanh nhưng vẫn kén bài toán trên production vì chi phí token cao và độ trễ điều phối lớn.
# anatomy of an ai agent
Dù phức tạp tới đâu, một AI Agent hoàn chỉnh cũng xoay quanh 4 thành phần chính: bộ não suy luận (Brain), bộ nhớ (Memory), bộ công cụ (Tools) và vòng lặp điều phối.

# brain (llm)
Đây là trung tâm ra quyết định. Ở mỗi bước, LLM nhận vào trạng thái hiện tại gồm lịch sử hội thoại, kết quả quan sát được từ môi trường và danh sách tool khả dụng, sau đó quyết định xem nên gọi tool nào với tham số gì hay đã đủ thông tin để trả lời người dùng.
Chất lượng suy luận của phần "não" này phụ thuộc lớn vào ba yếu tố: năng lực suy luận và bám sát chỉ dẫn (instruction following) của bản thân model, cách viết system prompt để đóng khung vai trò lẫn quy trình làm việc, và thiết lập temperature. temperature thấp (gần 0) cho kết quả ổn định, hợp với tool calling cần đúng JSON schema; để cao thì model sáng tạo hơn nhưng dễ lệch, kể cả bịa ra tham số không tồn tại. Lưu ý vài reasoning model không cho chỉnh temperature, lúc đó chỉ còn model và prompt để điều khiển.
# memory
Nếu chỉ dựa vào một lần gọi API đơn lẻ, LLM sẽ mất toàn bộ ngữ cảnh. Vì vậy bộ nhớ của agent thường được chia thành ba tầng theo thời gian sống của dữ liệu. Tầng Short-term memory lưu lịch sử hội thoại và các lượt gọi tool nằm trực tiếp trong context window hiện tại. Tầng Working memory đóng vai trò như tờ giấy nháp (scratchpad) để agent tự ghi chú tiến độ, danh sách việc cần làm hoặc kết quả trung gian trong lúc giải quyết một task dài. Cuối cùng, Long-term memory lưu trữ tri thức bền vững qua nhiều phiên làm việc bằng vector database hoặc kho tài liệu bên ngoài.
Context window có giới hạn (tuỳ model, thường vài trăm nghìn token, vài model lên tới 1 triệu). Context càng dài thì model càng dễ bỏ sót thông tin, nhất là phần nằm giữa (hiện tượng "lost in the middle"), và khi đầy hẳn thì không nhét thêm được nữa. Lúc này hệ thống phải có cách xoay xở: nén (summarize) các bước cũ đã xong, đẩy thông tin quan trọng ra file nháp bên ngoài, hoặc chẻ task lớn thành các sub-task chạy trong context riêng biệt.
# tools
LLM bản chất chỉ sinh ra văn bản, còn Tools là "tay chân" giúp nó tác động vào thế giới thực. Trong môi trường lập trình, bộ tool thường bao gồm các thao tác đọc/ghi file, chạy lệnh shell, tìm kiếm mã nguồn trong codebase, gọi API ngoài (Jira, Confluence, GitHub), chạy test suite, thao tác với Git (tạo branch, commit, mở PR) và tìm kiếm tài liệu trên web.
Các công cụ này có thể được viết cứng (built-in) ngay trong runtime của agent, hoặc kết nối động từ bên ngoài thông qua chuẩn MCP (Model Context Protocol) để tái sử dụng giữa nhiều công cụ AI khác nhau.
# agent loop: react pattern
Pattern hay gặp nhất là ReAct (Reasoning + Acting). Agent cứ xen kẽ giữa nghĩ (tính xem nên làm gì) và làm (gọi một tool).

Nhìn ví dụ trên thì thấy ReAct có hai điểm đáng chú ý.
Tự giữ trạng thái (state management): mỗi vòng lặp, phần OBSERVATION lấy từ môi trường (codebase, compiler) được nạp thêm vào context window của LLM. Agent dựa vào đó để "nghĩ" (THOUGHT) xem bước tiếp theo làm gì, chứ không chạy theo một kịch bản hard-code sẵn.
Tự khép vòng lặp (convergence): ở vòng 5 và 6, agent không dừng ngay sau khi sửa code (edit_file) mà tự đi kiểm tra lại (run_command để chạy test, get_diagnostics để check linter). Đây là chỗ khác nhau lớn nhất giữa AI agent và một con bot sinh code bình thường: agent tự kiểm chứng kết quả mình làm ra trước khi báo xong.
ReAct đến từ paper ReAct: Synergizing Reasoning and Acting in Language Models (Yao và cộng sự, 2022). Ngày nay các API như OpenAI hay Anthropic hỗ trợ tool calling sẵn, model trả về lời gọi tool có cấu trúc (JSON), nên phần "nghĩ" không còn phải viết thành chữ Thought/Action như trong paper gốc nữa, nhưng vòng lặp thì vẫn y như vậy.
# pseudo-code của agent loop:
def agent_loop(user_request, max_iterations=20):
messages = [system_prompt, user_request]
tools = get_available_tools()
for i in range(max_iterations):
# LLM decides next action
response = llm.generate(messages, tools=tools)
if response.is_final_answer():
return response.text # Done — return to user
if response.has_tool_calls():
# Lưu lại chính message chứa tool call của LLM trước,
# API (OpenAI, Anthropic...) yêu cầu tool result đi ngay sau nó
messages.append(response.message)
for tool_call in response.tool_calls:
# Execute tool
result = execute_tool(tool_call.name, tool_call.arguments)
# Add observation to context, gắn đúng id của tool call
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": result})
# Loop continues — LLM sees observation, decides next step
return "Reached max iterations without completing task"# planning strategies: agent lên kế hoạch kiểu gì
Khi bài toán vượt quá vài ba bước gọi tool đơn lẻ, cách agent lập kế hoạch sẽ quyết định xem nó đi đến đích hay đi lạc giữa chừng. Thực tế có 3 chiến lược phổ biến từ đơn giản đến phức tạp.
# strategy 1: step-by-step (react)
Cách đơn giản nhất là vừa đi vừa dò: ở mỗi vòng lặp, agent chỉ nhìn kết quả trước mắt để quyết định đúng 1 bước tiếp theo chứ không vạch sẵn lộ trình tổng thể. Kiểu này rất linh hoạt vì gặp lỗi gì thì xử lý ngay lỗi đó, tốn ít latency ban đầu. Tuy nhiên, khi đụng các task dài như refactor nhiều module, agent dễ bị cuốn vào việc chữa cháy cục bộ, lặp vòng tại một chỗ mà quên mất mục tiêu ban đầu.
# strategy 2: plan-then-execute
Để khắc phục chuyện mất phương hướng, agent sẽ tách bạch hai pha: lên một danh sách các bước cần làm (Plan) trước, rồi mới tuần tự thực thi từng bước (Execute). Nếu trong lúc chạy phát hiện giả định ban đầu không còn đúng với codebase thực tế, agent sẽ cập nhật lại kế hoạch (Re-plan) thay vì cứ đâm đầu chạy tiếp.
User: "Refactor UserService to use Clean Architecture"
PLAN:
1. Read current UserService and dependencies
2. Create domain layer (entities, ports)
3. Create use case layer
4. Create adapter layer (current service becomes adapter)
5. Update controller to use ports
6. Move tests to match new structure
7. Run tests, fix issues
8. Verify no regressions
EXECUTION:
[Step 1] Reading files... ✓
[Step 2] Creating domain/model/User.java... ✓
[Step 3] Creating domain/port/UserRepository.java... ✓
[Step 4] Oh, UserService also depends on EmailService → revise plan
REVISED PLAN: Add step 3.5: Create NotificationPort
[Step 3.5] Creating domain/port/NotificationPort.java... ✓
...
# strategy 3: hierarchical (decompose → delegate)
Với những yêu cầu quá lớn cho một context window đơn lẻ, bài toán được chẻ nhỏ thành các sub-task độc lập. Một agent điều phối ở tầng trên sẽ giao từng phần cho các sub-agent chuyên biệt xử lý riêng, rồi mới gom kết quả lại.
Main Agent: "Build user registration feature"
├── Sub-task 1: "Design data model" → Research Agent
├── Sub-task 2: "Implement API endpoint" → Coding Agent
├── Sub-task 3: "Write tests" → Testing Agent
└── Sub-task 4: "Update documentation" → Docs Agent
# multi-agent systems
Khi nhồi quá nhiều tool và quy trình vào một super-agent duy nhất, system prompt sẽ phình to, làm loãng sự chú ý của LLM và dễ gây ra hiện tượng tự xác nhận sai lầm (model tự viết code lỗi rồi tự khen code mình đúng trong cùng một luồng hội thoại). Giải pháp là tách thành nhiều agent chuyên trách phối hợp với nhau, mỗi agent giữ một system prompt gọn và một context window riêng:

Trong mô hình này, Orchestrator Agent làm "quản lý": nhận yêu cầu lớn từ người dùng, phân rã bài toán (task decomposition), giao việc cho từng agent chuyên môn và nghiệm thu kết quả cuối cùng. Research Agent chuyên đi thu thập thông tin, đọc tài liệu kỹ thuật hoặc khảo sát cấu trúc hệ thống để gom đủ ngữ cảnh. Dựa trên thông tin đó, Coder Agent chỉ tập trung thiết kế giải pháp và viết code. Cuối cùng, Reviewer Agent hoạt động như một chốt chặn QA/QC độc lập: vì chạy trên một context hoàn toàn mới và không bị thiên kiến bởi quá trình viết code trước đó, nó soi lỗi logic và lỗ hổng bảo mật khách quan hơn trước khi cho merge.
# khi nào multi-agent?
| Scenario | Single Agent | Multi-Agent |
|---|---|---|
| Task đơn giản (sửa typo) | ✓ | Dao mổ trâu giết gà |
| Task vừa (thêm feature) | ✓ | Tuỳ |
| Task phức tạp (cả feature: design + code + test + review) | Đuối | ✓ |
| Task cần nhiều chuyên môn khác nhau | Hạn chế | ✓ (agent chuyên trách) |
| Task cần có người soát chéo | Không tự review được | ✓ (reviewer agent) |
# communication patterns:
1. Sequential Pipeline:
Research → Code → Test → Review → Deploy
(mỗi agent output = input cho agent tiếp)
2. Collaborative:
Coder writes → Reviewer feedback → Coder revises → Reviewer approves
(iterative loop giữa 2 agents)
3. Hierarchical:
Orchestrator delegates subtasks → sub-agents report back
(tree structure)
4. Debate:
Agent A proposes solution → Agent B critiques → Agent A defends/revises
(adversarial — better quality through disagreement)
# các agentic pattern trong lập trình (2025)
# pattern 1: code generation agent
Input: Natural language requirement
Process: Understand → Plan → Generate code → Run tests → Iterate
Output: Working code with tests
Tools needed: file read/write, run tests, search codebase, get diagnostics
# pattern 2: bug investigation agent
Input: Bug report (Jira ticket, error log)
Process: Read report → Find relevant code → Reproduce → Identify root cause → Suggest fix
Output: Root cause analysis + proposed fix
Tools needed: Jira (read ticket), codebase search, file read, run tests
# pattern 3: code review agent
Input: Git diff / Pull Request
Process: Read changes → Check quality → Identify issues → Suggest improvements
Output: Review comments
Tools needed: Git diff, file read, run linter, security scan
# pattern 4: documentation agent
Input: Code changes or feature spec
Process: Read code → Understand intent → Generate/update docs → Verify accuracy
Output: Updated documentation
Tools needed: file read/write, search, Confluence API
# pattern 5: spec-driven development agent
Input: Feature idea
Process:
Phase 1: Generate requirements (ask clarifying questions)
Phase 2: Design architecture
Phase 3: Create task breakdown
Phase 4: Implement tasks (code + test each)
Phase 5: Review implementation
Output: Complete feature with docs and tests
Tools needed: ALL (file ops, tests, git, Jira, Confluence, web search)
# challenges & limitations
Đưa agent từ bản demo lên chạy thực tế thường vấp phải 4 rào cản lớn về độ tin cậy và an toàn.
# hallucination in action
Khác với chatbot chỉ bịa ra chữ, agent có thể "tự tin" gọi tool với tham số sai, truyền đường dẫn file không hề tồn tại, hoặc đọc nhầm log cũ rồi tưởng code mới đã chạy pass:
// Agent thinks test passed but actually read old output
THOUGHT: "Tests pass, I'm done"
REALITY: Tests were from previous run, current code has bug
// Mitigation: ALWAYS re-run, never trust cached results
# infinite loops
Khi gặp một lỗi vượt quá khả năng suy luận hoặc thiếu thông tin môi trường, agent rất dễ rơi vào vòng lặp vô hạn: cứ thử đi thử lại cùng một hướng tiếp cận đã thất bại mà chỉ đổi vài chi tiết nhỏ, gây đốt sạch ngân sách token:
Iteration 5: Try approach A → fails
Iteration 6: Try approach A (slightly different) → fails
Iteration 7: Try approach A (again) → fails
...
// Mitigation: Loop detection, max iterations, escalate after N failures
# context window exhaustion
Với các task kéo dài hàng chục lượt gọi tool, log trả về từ terminal hay nội dung file đọc vào sẽ làm context phình to rất nhanh. Khi chạm ngưỡng giới hạn, model bắt đầu "quên" các ràng buộc ban đầu hoặc làm rơi thông tin ở các bước trước:
// Mitigation strategies:
1. Summarize completed steps (compress context)
2. External memory (write notes to file, read when needed)
3. Task decomposition (smaller subtasks = less context per subtask)
4. Context compaction (automatic in modern systems)
# safety & unintended actions
Khi trao cho agent quyền chạy lệnh shell hay thao tác với Git, một suy luận sai lệch cũng đủ gây hậu quả thật trên môi trường làm việc:
// Dangerous: Agent decides to "clean up" by deleting files
// Dangerous: Agent runs `rm -rf` thinking it's temp directory
// Dangerous: Agent pushes directly to main branch
// Mitigation:
1. Approval gates (human confirms before destructive actions)
2. Sandboxing (agent operates in isolated environment)
3. Guardrails (system prompt: "never delete without confirmation")
4. Reversibility preference (prefer reversible actions)
# xây agent cho tốt: best practices
Muốn bớt mấy rủi ro trên thì có ba chỗ để ra tay: đóng khung hành vi bằng system prompt, thiết kế tool cho rõ, và đo kết quả liên tục.
# system prompt design
Good system prompt includes:
1. Identity: "You are a senior Java developer..."
2. Capabilities: "You can read files, write code, run tests..."
3. Constraints: "Never push to main, always run tests before claiming done"
4. Workflow: "Read before writing, test after coding, verify before reporting"
5. Style: "Match existing code style, follow project conventions"
6. Failure handling: "If stuck after 2 attempts, try different approach"
# tool design for agents
Good tool design:
- Clear, specific descriptions (AI uses description to decide WHEN to use)
- Atomic actions (1 tool = 1 thing)
- Informative return values (agent needs to understand result)
- Error messages that guide next action
- Idempotent where possible
Bad tool design:
- Vague description: "Do stuff with files" (when does AI use this?)
- God tool: "manage_everything(action, params)" (too many options)
- Silent failures: return empty on error (agent thinks success)
# evaluation & improvement
How to measure agent quality:
1. Task completion rate (% tasks fully completed correctly)
2. Iteration efficiency (steps needed vs optimal)
3. Error recovery rate (% of errors self-corrected)
4. Tool usage accuracy (right tool, right params)
5. Safety (0 destructive unintended actions)
Improvement loop:
1. Collect failed tasks
2. Analyze failure patterns (wrong tool? bad reasoning? missing context?)
3. Improve: system prompt, tool descriptions, or add new tools
4. Re-test
# tương lai (2025-2027)
| Trend | Status | Impact |
|---|---|---|
| Context window dài hơn (1M+ tokens) | Đang diễn ra | Bớt phải xoay xở chuyện context |
| Model suy luận tốt hơn (o1, o3) | Đã có | Làm được task nhiều bước phức tạp hơn |
| Model hỗ trợ tool use sẵn | Đang tốt dần | Ít gọi tool bậy hơn |
| Agent đa phương thức (code + hình) | Mới nổi | Test UI, đọc hiểu diagram |
| Giao thức agent-to-agent | Mới nổi (A2A) | Multi-agent phối hợp theo chuẩn chung |
| Học liên tục | Nghiên cứu | Agent giỏi lên từ các task cũ |
| Kiểm chứng hình thức hành động agent | Nghiên cứu | Có bảo đảm về an toàn |
Về giao thức agent-to-agent: Google công bố A2A (Agent2Agent) tháng 4/2025 và tới tháng 6/2025 đã chuyển cho Linux Foundation quản lý. Nó bổ sung cho MCP: MCP nối agent với tool và dữ liệu, còn A2A để các agent (có thể do bên khác viết) tìm và giao việc cho nhau.
Nếu tuần này bạn dựng agent đầu tiên, ba thứ nên có trước khi viết tính năng nào:
max_iterationscùng loop detection, để agent bí thì dừng và báo lại thay vì đốt token.- Approval gate cho mọi lệnh phá huỷ (xoá file, push, chạy migration), và một sandbox để nó nghịch thoải mái.
- Mô tả tool viết kỹ như viết docs cho người, kèm thông báo lỗi chỉ ra bước tiếp theo.
Phần nối agent vào Jira, database hay công cụ nội bộ mình viết riêng ở bài Model Context Protocol.
Chỉ là những ghi chép cá nhân với hy vọng mang lại chút giá trị. Nếu thấy hữu ích, đừng ngại chia sẻ cho bạn bè & đồng nghiệp nhé!
Happy coding 😎 👍🏻 🚀 🔥.
On this page
- # ai agent là gì?
- # spectrum of ai autonomy
- # anatomy of an ai agent
- # brain (llm)
- # memory
- # tools
- # agent loop: react pattern
- # pseudo-code của agent loop:
- # planning strategies: agent lên kế hoạch kiểu gì
- # strategy 1: step-by-step (react)
- # strategy 2: plan-then-execute
- # strategy 3: hierarchical (decompose → delegate)
- # multi-agent systems
- # khi nào multi-agent?
- # communication patterns:
- # các agentic pattern trong lập trình (2025)
- # pattern 1: code generation agent
- # pattern 2: bug investigation agent
- # pattern 3: code review agent
- # pattern 4: documentation agent
- # pattern 5: spec-driven development agent
- # challenges & limitations
- # hallucination in action
- # infinite loops
- # context window exhaustion
- # safety & unintended actions
- # xây agent cho tốt: best practices
- # system prompt design
- # tool design for agents
- # evaluation & improvement
- # tương lai (2025-2027)