Agent Framework Basics — ReAct, Planner-Executor, Autonomous Loops 2026
Agent framework là pattern build AI 'tự làm' từ goal: plan → execute → observe → iterate. Hiểu 4 architecture (ReAct, Planner-Executor, Hierarchical, Multi-agent) + 5 framework phổ biến (LangGraph, Claude Code, Mastra, AutoGen, CrewAI) + 7 gotcha production agent.
Mục lục bài viết(27)

Sơ đồ utility-based intelligent agent (Russell + Norvig textbook) — pattern foundation cho mọi AI agent: sense environment → evaluate state → choose action max utility → actuate → observe result → loop. LLM agent 2026 follow pattern này với LLM = brain decide action, tool calls = actuator, tool results = sensor input. Architecture variants (ReAct/Planner-Executor/Hierarchical) khác nhau cách orchestrate. Nguồn: Wikimedia Commons (CC BY-SA 3.0).
Hiểu đơn giản nhất
Chatbot: User hỏi → AI trả 1 câu → kết thúc.
Agent: User cho GOAL → AI tự PLAN → tự EXECUTE multi-step → tự OBSERVE result → ITERATE đến khi đạt goal.
Ví dụ goal-driven
User: "Tìm 3 customer cao nhất tháng này + send email upgrade offer + log result"
Chatbot: "Tôi không biết cách làm việc đó."
Agent:
Thought: Cần query customer ranking → call tool
Action: query_top_customers(period="this_month", limit=3)
Observation: [
{ id: 1, name: "A", revenue: 50tr },
{ id: 2, name: "B", revenue: 30tr },
{ id: 3, name: "C", revenue: 20tr }
]
Thought: Get email for each customer (parallel)
Action (parallel):
- get_customer_email(id=1) → [email protected]
- get_customer_email(id=2) → [email protected]
- get_customer_email(id=3) → [email protected]
Thought: Send upgrade email với template
Action (parallel):
- send_email([email protected], template="upgrade")
- send_email([email protected], template="upgrade")
- send_email([email protected], template="upgrade")
Thought: Log execution result
Action: log_action(type="bulk_email", count=3, status="success")
Final answer: "Đã gửi upgrade email cho 3 customer cao nhất (A, B, C). Log saved."
Agent thực hiện 5+ tool call autonomous để đạt goal. User không cần micromanage.
| Khái niệm | Vai trò |
|---|---|
| Goal | High-level task từ user |
| Plan | List sub-steps achieve goal |
| Thought | Reasoning step explicit |
| Action | Tool call execute |
| Observation | Tool result feedback |
| Loop | Iterate thought → action → observation |
| State | Memory between turn |
| Termination | Condition end loop (goal done / max turn / error) |
Tại sao bạn cần biết
- 2026 agent trở thành productivity tool mainstream. Cursor Agent, Claude Code, Windsurf — đều agent-based. Founder build product có "AI auto X" feature = competitive advantage.
- Save 10-100x time vs manual. "Generate weekly report" — agent autonomous 10 phút vs human 2 giờ.
- Foundation cho RPA + Workflow automation. AI agent thay thế Zapier/n8n cho 60% workflow 2026.
- Hiểu để defend. Agent attack surface khác chatbot — security pattern khác.
- Cost compound understanding. Agent có thể blow up 100x cost vs simple chatbot nếu không control.
4 Agent Architecture
Architecture 1: ReAct (Reasoning + Acting)
Paper: Yao et al. 2022.
loop:
Thought: [AI reasoning về next step]
Action: [tool call]
Observation: [tool result]
↓
(continue until end_turn)
Code:
async function reactAgent(goal: string, maxTurns = 10) {
const messages = [{ role: "user", content: goal }];
for (let turn = 0; turn < maxTurns; turn++) {
const response = await client.messages.create({
model: "claude-sonnet-4-5",
system: REACT_SYSTEM_PROMPT,
tools: AGENT_TOOLS,
messages
});
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason === "end_turn") {
return extractFinalAnswer(response);
}
if (response.stop_reason === "tool_use") {
const toolResults = await executeAllTools(response.content);
messages.push({ role: "user", content: toolResults });
}
}
throw new Error("Max turns exceeded");
}Pros: simple, AI control flow, easy debug Cons: sequential (no parallel plan), goal drift possible
Best for: Q&A research, code debugging, simple multi-step task.
Architecture 2: Planner-Executor
Phase 1 — PLAN:
Input: goal
Output: ordered list of step (5-20 step)
Phase 2 — EXECUTE:
for each step in plan:
execute step (may use tool)
if step fail: re-plan from current state
Phase 3 — REVIEW:
Verify goal achieved
Code:
async function plannerExecutor(goal: string) {
// Phase 1: Plan
const plan = await client.messages.create({
model: "claude-opus-4-5", // Smart model for planning
system: PLANNER_PROMPT,
messages: [{ role: "user", content: `Goal: ${goal}\n\nGenerate plan as JSON array.` }]
});
const steps = JSON.parse(extractText(plan));
// Phase 2: Execute (Sonnet/Haiku worker)
const results = [];
for (const step of steps) {
const result = await client.messages.create({
model: "claude-sonnet-4-5",
tools: AGENT_TOOLS,
messages: [
{ role: "user", content: `Execute step: ${step.description}` }
]
});
results.push(result);
// Re-plan if step fail
if (result.stop_reason === "error") {
const newPlan = await replan(goal, results, step);
// Continue with new plan
}
}
return synthesize(results);
}Pros: visibility plan upfront, parallelize, easier debug Cons: rigid, mid-execution discovery harder
Best for: complex workflow (10+ step), production critical, audit-required task.
Architecture 3: Hierarchical Multi-agent
Manager Agent (Opus)
├ Worker Agent A (Sonnet) — researcher
├ Worker Agent B (Sonnet) — writer
└ Worker Agent C (Haiku) — validator
Manager decides which worker handle task → cost optimization + specialization.
Code (Claude Code subagent pattern):
// Manager prompt
const MANAGER = `
You orchestrate 3 specialized agents:
- research_agent: gather info, web search
- write_agent: produce written content
- validate_agent: check quality + correctness
For complex task, delegate appropriately.
`;
async function manager(goal: string) {
const plan = await client.messages.create({
model: "claude-opus-4-5",
tools: [
{ name: "call_research", description: "Delegate to research agent" },
{ name: "call_write", description: "Delegate to write agent" },
{ name: "call_validate", description: "Delegate to validate agent" }
],
messages: [{ role: "user", content: goal }]
});
// Manager call workers, synthesize results
}Pros: cost-optimized (cheap workers + smart manager), separation of concerns Cons: harder to debug, overhead delegation
Best for: production multi-step workflow với cost concern.
Architecture 4: Peer-to-peer Multi-agent
Agent A ↔ Agent B ↔ Agent C
(debate, collaborate)
Example CrewAI: 3 agent với role (researcher + writer + critic) debate to produce output.
# CrewAI example
researcher = Agent(role="Researcher", goal="Find data")
writer = Agent(role="Writer", goal="Draft article")
critic = Agent(role="Critic", goal="Improve article")
crew = Crew([researcher, writer, critic], task="Write SEO article")
output = crew.run()Pros: emergent quality from debate, creative Cons: unpredictable cost, hard to control
Best for: experimental research, creative content gen, brainstorming.
5 Framework phổ biến 2026
1. LangGraph (LangChain ecosystem)
Tech: Python + TypeScript, graph-based state machine
from langgraph.graph import StateGraph
graph = StateGraph()
graph.add_node("planner", planner_fn)
graph.add_node("executor", executor_fn)
graph.add_edge("planner", "executor")
graph.add_conditional_edge("executor", route_fn, {
"continue": "executor",
"done": END
})Pros: mature, large community, complex workflow Cons: LangChain dependency heavy, steeper learning curve
Best for: Python production, complex stateful agent.
2. Claude Code Subagents (Anthropic)
Tech: File-based config in .claude/agents/*.md
---
name: researcher
description: Use this agent when you need to research a topic deeply
tools: [web_search, fetch_url, read_file]
---
You are a research specialist. Gather comprehensive info on the topic.
Return structured findings as markdown.Spawn via Task tool. Claude Code orchestrate parent + subagent.
Pros: dog-fooded by Anthropic, simple file config, free with Claude Pro Cons: Claude-only, file-based limit
Best for: dev assistant, research task, code review parallelize.
3. Mastra (TypeScript)
Tech: TypeScript-first, modern API
import { Agent } from "@mastra/core";
const supportAgent = new Agent({
model: "claude-sonnet-4-5",
tools: [searchKnowledgeBase, getOrderStatus],
instructions: "Help customer with order inquiry"
});
const result = await supportAgent.run({
query: "Where's my order VC2026000001?"
});Pros: clean TS API, growing fast 2025 Cons: smaller community, less battle-tested
Best for: TS/Node production app, modern stack.
4. AutoGen (Microsoft)
Tech: Python multi-agent conversation framework
from autogen import AssistantAgent, UserProxyAgent
assistant = AssistantAgent("assistant", llm_config={...})
user_proxy = UserProxyAgent("user_proxy", code_execution_config={...})
user_proxy.initiate_chat(assistant, message="Solve: ...")Pros: multi-agent conversation native, research-grade Cons: Microsoft ecosystem, complex setup
Best for: experimental research, multi-agent debate scenarios.
5. CrewAI (Python)
Tech: Role-based crew, simple Python
from crewai import Agent, Task, Crew
researcher = Agent(role="Researcher", goal="...", backstory="...")
writer = Agent(role="Writer", goal="...", backstory="...")
task1 = Task(description="Research X", agent=researcher)
task2 = Task(description="Write article", agent=writer, context=[task1])
crew = Crew(agents=[researcher, writer], tasks=[task1, task2])
result = crew.kickoff()Pros: intuitive, fast prototype Cons: less flexible cho complex workflow
Best for: rapid prototype, content gen workflow, role-play scenarios.
Production agent — 7 gotcha
Gotcha 1: Infinite loop
Agent retry same failed action infinitely.
// Add deduplication
const seen = new Set<string>();
for (const action of actions) {
const key = `${action.name}:${JSON.stringify(action.input)}`;
if (seen.has(key)) {
console.warn("Duplicate action detected, skipping");
continue;
}
seen.add(key);
// ... execute
}Gotcha 2: Max turn cap
const MAX_TURNS = 20;
const MAX_COST_USD = 0.50;
for (let turn = 0; turn < MAX_TURNS; turn++) {
if (currentCost > MAX_COST_USD) {
throw new Error("Budget exceeded");
}
// ... execute turn
}Gotcha 3: Goal drift
Agent execute off-topic tool. Fix: include goal reminder mỗi turn.
const messages = [
{ role: "system", content: `Goal: ${originalGoal}. Stay focused on this goal.` },
...turnMessages
];Gotcha 4: Cost compound
// Monitor cost per turn
async function trackedTurn(messages) {
const response = await client.messages.create({...});
const cost = calculateCost(response.usage);
totalCost += cost;
if (totalCost > BUDGET) abort();
return response;
}Gotcha 5: Tool result too large
function truncateResult(result: any, maxTokens = 2000): string {
const json = JSON.stringify(result);
if (countTokens(json) > maxTokens) {
return summarizeViaHaiku(json); // Compress with cheap model
}
return json;
}Gotcha 6: Human-in-the-loop critical action
async function executeTool(tool, args) {
if (CRITICAL_TOOLS.has(tool.name)) {
const approval = await requestHumanApproval(tool, args);
if (!approval) return { error: "Rejected by human reviewer" };
}
return await tool.execute(args);
}
const CRITICAL_TOOLS = new Set([
"send_email", "delete_record", "process_payment", "make_api_call"
]);Gotcha 7: Audit log every action
async function audit(agent: string, action: any, result: any) {
await db.insert("agent_audit").values({
agent_id: agent,
timestamp: Date.now(),
tool: action.name,
input: JSON.stringify(action.input),
result_hash: sha256(JSON.stringify(result)),
duration_ms: result.duration,
cost_usd: result.cost
});
}Required cho compliance, debug, replay.
Ví dụ thực tế: vietcodex.com Wiki Gen Agent (proposed Q4 2026)
// Agent that auto-generates wiki article from topic + research
const WIKI_AGENT_SYSTEM = `
You are wiki content writer agent for vietcodex.com.
Goal format: "Write wiki article on topic [X] in cluster [Y]"
Process:
1. Research topic: search Wikipedia, search web for 2026 sources
2. Check existing wiki: find cross-link opportunities
3. Find Wikimedia image: verify URL, get thumbnail
4. Draft MDX following pattern (frontmatter + 7 FAQ + figure + sections + cross-link)
5. Validate: schema check, MDX compile, word count > 2000
6. Submit: write file to content/wiki/<cluster>/<slug>.mdx
Stay focused. Don't generate off-topic content.
`;
const WIKI_AGENT_TOOLS = [
searchWeb,
searchWikipedia,
searchWikimediaImage,
verifyUrl,
readExistingWiki,
writeMdxFile,
validateMdx
];
async function wikiGenAgent(topic: string, cluster: string) {
const goal = `Write wiki article on "${topic}" in cluster "${cluster}"`;
// Planner-Executor pattern
const plan = await planAgent(goal);
// Plan: [research, find_image, draft_mdx, validate, write_file]
const results = [];
for (const step of plan.steps) {
const result = await executeStep(step, WIKI_AGENT_TOOLS);
results.push(result);
if (result.error) {
const replan = await rePlanFromError(plan, step, result);
// Continue with new plan
}
}
return { article_path: results[plan.steps.length - 1].path };
}
// Estimate cost:
// Planner: 5k input + 1k output = $0.030
// Each step execute: avg 8k input + 1.5k output = $0.045 × 5 step = $0.225
// Total: ~$0.26/article
// vs human writer: ~$50-100/article
// Saving: 200-400xFoundation đã có (Tool Use + MCP + RAG). Implementation 1-2 tuần.
Cost reality check
| Architecture | Avg cost/task | Use case |
|---|---|---|
| ReAct simple | $0.05-0.20 | Q&A research, single workflow |
| Planner-Executor | $0.20-1.00 | Complex multi-step task |
| Hierarchical (Opus + Haiku workers) | $0.30-1.50 | Production workflow scale |
| Peer-to-peer multi-agent | $0.50-5.00 | Experimental, creative |
Compare manual human: $20-100/task. Agent ROI 100-1000x cho repetitive task.
Cái gì có thể sai
| Vấn đề | Triệu chứng | Cách fix |
|---|---|---|
| Infinite loop | Cost spike, max turn reached | Add dedup + budget cap |
| Goal drift | Off-topic tool calls | Goal reminder in system + check progress mỗi turn |
| Tool result quá lớn | Context overflow | Truncate + summarize before pass back |
| Hallucinated tool name | Try call non-existent tool | Strict tool list, reject unknown |
| Cascade failure | 1 fail → wrong action → fail more | Graceful degradation, isolate failures |
| Cost blow up | Multi-turn × Opus | Right-size model + budget cap |
| Hard to debug | No visibility internal | Log every action + thought |
| Stuck waiting tool | Tool sync expensive | Async + return job_id pattern |
Tóm tắt 1 dòng
Agent Framework = pattern AI tự PLAN → EXECUTE → OBSERVE → ITERATE từ goal. 4 architecture: ReAct (think+act interleave), Planner-Executor (2 phase rõ), Hierarchical (manager + workers), Peer-to-peer multi-agent. 5 framework: LangGraph (Python mature), Claude Code subagents (Anthropic native), Mastra (TS modern), AutoGen (MS research), CrewAI (role-based simple). Cost compound — cap turn + budget critical. Production reliability 95%+ narrow scope, drops wide-open. Foundation: Tool Use + MCP. ROI 100-1000x manual cho repetitive task.
Đọc tiếp
- Tool Use / Function Calling — foundation primitive cho agent
- MCP (Model Context Protocol) — tool standardization across vendor
- Multi-agent + Cost routing — Hierarchical pattern deep dive cost optimization
- AI Security — 7 mitigation production — agent attack surface lớn hơn chatbot