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.

12 phút đọcCập nhật 2026-05-23
Nghe bài viết
Để Claude đọc bài cho bạn — vừa nghe vừa làm việc khác
Mục lục bài viết(27)
Sơ đồ utility-based intelligent agent — sensor → state → action evaluation → actuator loop

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ệmVai trò
GoalHigh-level task từ user
PlanList sub-steps achieve goal
ThoughtReasoning step explicit
ActionTool call execute
ObservationTool result feedback
LoopIterate thought → action → observation
StateMemory between turn
TerminationCondition 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-400x

Foundation đã có (Tool Use + MCP + RAG). Implementation 1-2 tuần.

Cost reality check

ArchitectureAvg cost/taskUse case
ReAct simple$0.05-0.20Q&A research, single workflow
Planner-Executor$0.20-1.00Complex multi-step task
Hierarchical (Opus + Haiku workers)$0.30-1.50Production workflow scale
Peer-to-peer multi-agent$0.50-5.00Experimental, 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ứngCách fix
Infinite loopCost spike, max turn reachedAdd dedup + budget cap
Goal driftOff-topic tool callsGoal reminder in system + check progress mỗi turn
Tool result quá lớnContext overflowTruncate + summarize before pass back
Hallucinated tool nameTry call non-existent toolStrict tool list, reject unknown
Cascade failure1 fail → wrong action → fail moreGraceful degradation, isolate failures
Cost blow upMulti-turn × OpusRight-size model + budget cap
Hard to debugNo visibility internalLog every action + thought
Stuck waiting toolTool sync expensiveAsync + 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

Câu hỏi thường gặp

Agent vs chatbot khác nhau gì?
Chatbot: 1 turn = 1 user query + 1 AI response. Single-shot, không tự ra quyết định nhiều bước. Agent: nhận GOAL từ user, tự PLAN steps, EXECUTE tool (multi-turn), OBSERVE result, ITERATE đến khi đạt goal. Example: chatbot 'sản phẩm A giá bao nhiêu' → trả lời. Agent 'tìm 5 sản phẩm dưới 500k + so sánh + recommend' → search DB + compare + apply user preference + return analysis. Agent = autonomous, chatbot = reactive.
ReAct pattern là gì?
ReAct (Reasoning + Acting) — Yao et al. 2022 paper. Pattern: AI thinking explicit → action (tool call) → observation (tool result) → thinking → action → ... loop đến goal. Format: 'Thought: I need to search products → Action: search_products(...) → Observation: [results] → Thought: Now compare prices → Action: ...'. Reasoning explicit help debug + control AI decision. Most production agent dùng ReAct hoặc variant. Anthropic Claude extended thinking native ReAct-like.
Planner-Executor pattern khác ReAct?
ReAct: think + act interleave từng bước. Planner-Executor: 2 phase rõ ràng. Phase 1 PLAN — generate full task list trước. Phase 2 EXECUTE — chạy plan từng step, có thể re-plan nếu fail. Pros Planner-Executor: (1) visibility plan upfront — user approve trước execute; (2) parallelize independent steps; (3) easier debug — failure isolate to specific step. Cons: less flexible nếu mid-execution discover need different approach. Quy tắc: simple task → ReAct. Complex multi-step (10+ step) → Planner-Executor.
Hierarchical agent vs Multi-agent — khác gì?
Hierarchical: 1 'manager agent' + N 'worker agent'. Manager decide route task to worker (similar Claude Code subagent pattern). Pros: cost optimization (Opus manager + Haiku workers), separation of concerns. Multi-agent (peer-to-peer): N agent equal, communicate qua message passing, debate hoặc collaborate. Example: CrewAI multiple agent role (researcher + writer + critic) discuss to produce output. Hierarchical scale tốt hơn, multi-agent emergent behavior tốt cho creative task. Production thường hierarchical (predictable cost + behavior).
5 agent framework — chọn cái nào?
(1) **LangGraph** (LangChain ecosystem) — graph-based state machine, mature, large community. Best cho complex stateful workflow; (2) **Claude Code subagents** — built-in Anthropic, file-based config, dog-fooded by Anthropic team. Best cho dev assistant + research task; (3) **Mastra** — TypeScript-first, modern, growing 2025. Best cho TS/Node.js app; (4) **AutoGen** (Microsoft) — multi-agent conversation focused. Best cho experimental research; (5) **CrewAI** — role-based crew, simple Python. Best cho rapid prototype. Recommendation 2026: production TS → Mastra, production Python → LangGraph, dev assistant → Claude Code subagents.
Cost agent có thể blow up không? Control thế nào?
RẤT có thể. Agent autonomous loop có thể run 100+ turn nếu task complex → cost compound. Control: (1) Max turn cap (vd 20); (2) Budget per task ($1/task) — abort khi exceed; (3) Right-sized model — manager Opus, worker Haiku/Sonnet; (4) Cache aggressive system prompt; (5) Eval cost weekly vs benefit. Bài [Multi-agent + Cost routing](/wiki/ai-coding/multi-agent-cost) cover deep. vietcodex.com pattern: agent cap $0.50/task, escalate human nếu agent fail > 3 turn.
Production agent có thể tin được không? Khi nào fail?
Production agent 2026 reliable cho narrow task (research, code review, data extraction). Fail mode: (1) **Infinite loop** — agent re-try same failed action; (2) **Hallucinate tool args** — gọi tool không tồn tại; (3) **Goal drift** — execute task off-topic; (4) **Cascade failure** — 1 tool fail → wrong observation → wrong next action → fail chain. Mitigation: (a) Strict tool schema; (b) Eval suite cover happy + edge case; (c) Human-in-the-loop critical action; (d) Monitor + alert anomaly. Reliability target 95%+ với narrow scope, drops 60-70% wide-open task.