ai agentic systems
Tung Bui Thanh (TungDaDev)12 mins read

# ai agent là gì?
Chatbot trả lời câu hỏi. AI Agent giải quyết vấn đề.
Khác nhau ở chỗ: chatbot thì bị động (hỏi → trả lời → xong), còn agent chủ động (nhận mục tiêu → lên kế hoạch → làm nhiều bước → tự sửa sai → trả kết quả). Agent có agency, tức là tự quyết bước tiếp theo dựa trên kết quả của 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 tool hiện nay (GitHub Copilot, Cursor, Kiro) đang ở Level 2-3. Multi-agent (Level 4) đang nổi lên nhưng chưa phổ biến trên production.
# anatomy of an ai agent
Agent nào cũng có 4 thành phần

# brain (llm)
Đây là chỗ quyết định làm gì tiếp. LLM nhận trạng thái hiện tại (hội thoại + những gì quan sát được + danh sách tool) rồi trả ra: "giờ nên gọi tool nào, với tham số gì".
Agent giỏi hay dở phụ thuộc vào:
- Năng lực của model (suy luận, làm theo chỉ dẫn)
- System prompt (tính cách, ràng buộc, quy trình làm việc)
- Temperature (0 = ổn định, cao = sáng tạo nhưng dễ lệch)
# memory
- Short-term: lịch sử hội thoại (giới hạn bởi context window)
- Working memory: ghi chú agent tự viết ra (scratchpad, kết quả trung gian)
- Long-term: knowledge base, vector store, các lần làm việc trước
Khi context window đầy (tuỳ model, thường vài trăm nghìn token, vài model lên tới 1M), agent phải có cách xoay: tóm tắt phần context cũ, ghi các thông tin quan trọng ra ngoài, hoặc chia task thành nhiều task nhỏ hơn.
# tools
Là những việc agent làm được. Trong bối cảnh lập trình thì có:
- Đọc/ghi file
- Chạy lệnh shell
- Tìm trong codebase
- Gọi API (Jira, Confluence, GitHub)
- Chạy test
- Tạo git branch/commit/PR
- Search web tìm tài liệu
Tool có thể là khả năng có sẵn của agent (đọc file, chạy shell...) hoặc lấy từ bên ngoài qua MCP server.
# 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ì
# strategy 1: step-by-step (react)
Đơn giản nhất: mỗi vòng chỉ quyết 1 bước, không lên kế hoạch trước cho cả bài.
- Ưu: linh hoạt, thấy gì xử nấy
- Nhược: dễ bị lặp vòng, mất bức tranh tổng
# strategy 2: plan-then-execute
Agent lập kế hoạch đầy đủ trước, làm từng bước, cần thì sửa kế hoạch.
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)
Task phức tạp được chẻ thành các task con, mỗi cái xử lý riêng (có thể giao cho sub-agent).
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
Thay vì một super-agent ôm hết, chia ra nhiều agent chuyên trách phối hợp với nhau:

Orchestrator Agent (gốc): làm "quản lý". Nó nhận yêu cầu lớn từ người dùng, chẻ nhỏ bài toán (task decomposition), giao việc cho các agent chuyên môn, và là người duyệt kết quả cuối cùng trước khi trả về.
Research Agent: lo đi thu thập thông tin, đọc tài liệu kỹ thuật hoặc tìm hiểu cấu trúc hệ thống.
Coder Agent: chỉ lo làm giải pháp kỹ thuật, viết code dựa trên thông tin tầng trên đưa xuống.
Reviewer Agent: làm QA/QC, soi code một cách độc lập để chắc code ổn, không dính lỗ hổng bảo mật rồi mới 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
# hallucination in action
Agent rất "tự tin" gọi tool với tham số sai, hoặc khẳng định file có tồn tại trong khi không hề có:
// 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
Agent bị kẹt, cứ thử đi thử lại một cách đã fail:
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
Task dài thì context cứ dồn lên → đầy window → agent "quên" mấy 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
Agent cầm tool mạnh thì cũng phá đượ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
# 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.
Chốt lại: AI agent đang chuyển từ "demo cho vui" sang "công cụ chạy production". Dev không cần thành nhà nghiên cứu AI, nhưng cần biết dùng agent cho hiệu quả: thiết kế tool tốt, viết prompt tốt, dựng guardrail, và biết lúc nào tin được, lúc nào phải kiểm lại kết quả của agent.
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 😎 👍🏻 🚀 🔥.