Agent Architecture
Agent Architecture
An Agent is an AI system capable of autonomously perceiving the environment, reasoning, and taking actions to achieve goals.
This article covers the principles, diagrams, and applicable scenarios of six mainstream architectures, from the simplest loop to multi-Agent collaboration, helping you make appropriate technical selections in practical projects.

What is Agent Architecture
In AI application development, an Agent is an AI system capable of perceiving the environment, making autonomous decisions, and taking actions.
Unlike traditional "one-question-one-answer" large model calls, Agents can continuously execute multiple steps, call tools, or even coordinate other Agents to complete complex tasks.
Agent Architecture refers to the organization method of various components within an Agent system, which determines the Agent's capability boundaries, reliability, flexibility, and applicable scenarios.
The essence of an Agent: Perception → Reasoning → Action
The working mechanism of an Agent is essentially a loop: perceive the current state, reason about the next step, execute an action, perceive again... until the task is complete.
The difference between various architectures lies in how this basic loop is organized and extended.
This article assumes you are familiar with the basic concepts of Large Language Models (LLM) and the basic idea of "Function Calling." If you are not familiar with them, you can learn these two foundational concepts first.
Architecture One: Single Agent Loop
Recommended for beginners; simple to implement
The most basic and intuitive architecture, where a single Agent independently completes all tasks from start to finish.
The Single Agent Loop directly embodies the ReAct pattern (Reasoning + Acting): every step is "think first, then act." The LLM acts as the brain, and tool calling is its hands.
Figure 1 — Single Agent Loop Process
Working Principle
Perception: Reading the current state—file content, environment variables, and the output of previous steps—and synthesizing it into the current context.
Reasoning: The LLM decides the next action based on the context—which tool to call, what parameters to pass, or whether the task is complete.
Action: Executing the tool call, such as reading/writing files or searching the web. The execution result of the tool is appended to the context, entering the next loop iteration.
The result of each tool call is written back to the context (Context Window). Therefore, as the task progresses, the context continuously grows until it reaches the LLM's context window limit—this is the main bottleneck of the single Agent loop.
Example
Simplified implementation of the single Agent loop — demonstrating the core logic of the ReAct pattern
class
SimpleAgent:
"""Basic structure for a single Agent loop"""
def
init
(
self
,
model
,
tools
,
max_turns
=
10
)
:
self
.
model
=
model
Large language model
self
.
tools
=
tools
List of available tools
self
.
max_turns
=
max_turns
Maximum number of loop turns to prevent infinite loops
def
run
(
self
,
task:
str
)
str
:
"""Main loop for executing tasks"""
context
=
f
"User task: {task}"
for
turn
in
range
(
self
.
max_turns
)
:
Step 1: Think - Let the model decide the next step
response
=
self
.
model
.
think
(
context
)
If the model believes the task is complete, return the final answer
if
response.
is_final
(
)
:
return
response.
content
Step two: Action -- Call the tool selected by the model
tool_name
=
response.
tool_name
tool_args
=
response.
tool_args
tool_result
=
self
.
tools
[
tool_name
]
(
**tool_args
)
Step 3: Feed the tool results back to the model to enter the next round
context +
=
f
"\nTool {tool_name} returned: {tool_result}"
return
Reached maximum rounds, task not completed
Usage example
agent
=
SimpleAgent
(
model
=
llm
,
tools
=
{
"read_file"
: read_file
,
"search_code"
: search_code
,
"run_test"
: run_test
}
)
result
=
agent.
run
(
"Fix type error in user.py of runoob project"
)
Advantages
- Simplest to implement and easy to debug
- Suitable for scenarios with clear task boundaries
- Supported by almost all Agent frameworks
Disadvantages
- Context window easily gets full
- Prone to "drifting" in complex tasks
- Cannot process multiple subtasks in parallel
Best use cases: fixing a bug, writing a function, answering a specific question. Tasks are clear, complexity is moderate, and parallelization or multi-role collaboration is not needed.
If your task is expected to require more than 15 tool calls, a single Agent loop may not be the best choice. Consider using multi-Agent collaboration or a planning and execution architecture to decompose complexity.
Architecture Two: Plan & Execute
Intuitive and reviewable
Separates "thinking about what to do" from "actually doing it" into two independent stages, improving task predictability and auditability.
The Plan + Execute architecture splits the Agent's work into two distinct phases: Planning (Plan) and Execution (Execute).
In the planning phase, the model does not perform any actions, only generating a detailed list of execution steps. In the execution phase, the system completes each step sequentially. This separation allows users to review the plan before execution, similar to Claude Code's Plan Mode.
Figure 2 — Plan + Execute Architecture (with Dynamic Re-planning)
Two Variants
| Variant | Behavior | Typical Scenario |
|---|---|---|
| Static Planning | Plan once and execute sequentially without intermediate adjustments | Tasks with fixed processes and clear steps, such as data migration scripts |
| Dynamic planning | Re-evaluate after each step and adjust the subsequent plan based on the results | Tasks with uncertain outcomes, such as debugging or exploratory data analysis |
Dynamic planning is more robust, but has higher implementation complexity, and replanning at each step consumes extra tokens.
Claude Code's Plan Mode embodies this architecture—after clicking "Plan," the AI first outputs a detailed plan for you to review, and only executes it after confirmation. This greatly enhances user control.
Example
Simplified implementation of the Plan & Execute architecture
class
PlanExecuteAgent:
"""An Agent that plans first, then executes"""
def
plan
(
self
,
task:
str
)
list
:
"""Phase one: Generate execution plan"""
plan
=
self
.
model
.
generate
(
f
"""
Please break down the following task into a list of executable steps:
Task: {task}
Return a JSON formatted list of steps, with each step containing:
- step_id: Step number
- description: Step description
- tool: Name of the tool to be called
"""
)
return
plan
def
execute
(
self
,
plan:
list
,
dynamic:
bool
=
False
)
str
:
"""Phase Two: Step-by-step plan execution"""
results
=
[
]
remaining_plan
=
plan.
copy
(
)
while
remaining_plan:
step
=
remaining_plan.
pop
(
0
)
output
=
self
.
tools
[
step
[
"tool"
]
]
(
step
[
"description"
]
)
results.
append
(
{
"step"
: step
[
"step_id"
]
,
"output"
: output
}
)
if
dynamic
and
remaining_plan:
Dynamic programming: re-evaluate subsequent plans based on the current result
remaining_plan
=
self
.
replan
(
remaining_plan
,
results
)
return
self
.
summarize
(
results
)
Usage example
agent
=
PlanExecuteAgent
(
)
plan
=
agent.
plan
(
"Add user authentication feature to runoob project"
)
Humans can review the plan first to confirm its rationality before execution
result
=
agent.
execute
(
plan
,
dynamic
=
True
)
Advantages
- Allows manual review of the plan before execution
- Separation of reasoning and execution responsibilities, clear
- Friendly to long tasks
Disadvantages
- Initial plans may not be accurate enough
- Two-stage increases latency
- Static versions are difficult to handle unexpected situations
The cost of Plan & Execute is increased inference rounds, which is wasteful for simple tasks. If a task can be completed in 3 steps, a single Agent loop is more efficient.
Architecture Three: Multi-Agent Collaboration (Multi-Agent)
Production Recommendation Complex Tasks
An Orchestrator is responsible for task decomposition and scheduling, while multiple Subagents perform specific roles, completing subtasks in parallel or series, and aggregating the results back to the Orchestrator for synthesis.
When a single Agent faces context window limitations or overly complex tasks, a multi-Agent architecture provides an elegant solution: having multiple specialized Subagents work in parallel, coordinated by an Orchestrator.
Figure 3 — Multi-Agent Collaboration Architecture (Orchestrator + Subagents)
Independent Context is the Core Advantage
Each Subagent has an independent context window. A code review Agent deeply reading auth.py will not affect the judgment of a performance analysis Agent; the large amount of intermediate output generated by a security detection Agent will not occupy space from other Agents.
Subagents are transient and isolated—they are destroyed after completing a task. Agent Teams, on the other hand, are multiple independent Agent instances that collaborate over a long period and exchange messages, resembling a real team.
Instance
Simplified implementation of multi-agent collaboration
class
Orchestrator:
"""Orchestrator: responsible for task decomposition, distribution, and result aggregation"""
def
init
(
self
)
:
self
.
subagents
=
{
"code_review"
: Subagent
(
name
=
"Code Review"
,
tools
=
[
"read_file"
,
"static_analysis"
]
,
system_prompt
=
"You are a code review expert..."
)
,
"security"
: Subagent
(
name
=
"Security Check"
,
tools
=
[
"scan_vulnerability"
,
"check_deps"
]
,
system_prompt
=
"You are a security detection expert..."
)
,
"performance"
Subagent
(
name
=
"Performance Analysis"
,
tools
=
[
"profile_code"
,
"analyze_complexity"
]
,
system_prompt
=
"You are a performance analysis expert..."
)
}
def
handle_task
(
self
,
task:
str
)
dict
:
Step 1: Analyze the task and decide which Subagent is needed
=
self
.
plan
(
(
task
)
Step two: Parallel distribution (each Subagent works simultaneously with an independent context)
results
=
{
}
for
agent_name
in
needed:
sub_task
=
self
.
decompose
(
task
,
agent_name
)
results
[
agent_name
]
=
self
.
subagents
[
agent_name
]
.
run
(
sub_task
)
Step 3: Aggregate the results of each Subagent and output a synthesis
return
self
.
synthesize
(
task
,
results
)
Usage example: one run, parallel analysis of three dimensions
orch
=
Orchestrator
(
)
report
=
orch.
handle_task
(
"Review runoob project PR #42"
)
Advantages
- Naturally supports parallelism, fast speed
- Child Agents are independent, contexts do not interfere with each other
- Can specialize the role of each child Agent
Disadvantages
- Coordination logic is complex, debugging is difficult
- Token cost is higher when multiple Agents run in parallel
- The Orchestrator itself may become a bottleneck
The main cost of multi-agent collaboration is orchestration overhead. If subtasks are very simple (each requiring only 1-2 steps), the orchestration overhead may exceed the cost of the actual work, in which case a single agent is more suitable.
Architecture Four: Reflection and Self-Correction
High-quality output, easy to integrate
Incorporate quality evaluation into the agent's output stage; if unsatisfied, regenerate or correct, forming an internal iteration loop.
The reflection architecture adds a "quality inspection stage" to the agent: after generating an output, a Critic evaluates its quality, and if it does not meet the standard, it is requested to be corrected until the output meets the standard.
This is like a developer running tests on their own code after writing it—a self-check before delivery.
Figure 4 — Reflection and Self-Correction Architecture
Two implementation methods
| Method | Mechanism | Advantages | Disadvantages |
|---|---|---|---|
| Self-reflection | Execute the same model first and then evaluate its own output | Simple to implement, no extra model cost | The model might "ignore" its own errors |
| Critic Model | Evaluate the output of the execution model with an independent judging model | More objective, capable of discovering blind spots in the execution model | Increases model calling cost and latency |
"Write unit tests -> Run tests -> Observe failure -> Fix code -> Run again" — this is a classic application of the reflection architecture. The test results themselves are the feedback signal for the Critic.
Example
Simplified implementation of the reflection architecture
class
ReflectiveAgent:
"""An Agent with self-reflection capabilities"""
def
init
(
self
,
model
,
tools
,
max_reflections
=
3
)
:
self
.
model
=
model
self
.
tools
=
tools
self
.
max_reflections
=
max_reflections
Maximum number of corrections, prevents infinite loops
def
run
(
self
,
task:
str
)
str
:
Step 1: Normal execution, generate initial output
output
=
self
.
model
.
generate
(
task
)
for
i
in
range
(
self
.
max_reflections
)
:
Step two: Reflection — Evaluate output quality
critique
=
self
.
model
.
generate
(
f
"""
Please strictly evaluate the following output:
Original task: {task}
Current output: {output}
Check: Factual errors? Logical flaws? Missing information? Formatting issues?
If the output is perfect, please reply "PASS".
"""
)
if
"PASS"
in
critique:
break
Output passed review
Step 3: Revision — Improve based on feedback
output
=
self
.
model
.
generate
(
f
"""
Original task: {task}
Last output: {output}
Feedback: {critique}
Please correct the output based on the feedback.
"""
)
return
output
Usage example
agent
=
ReflectiveAgent
(
model
=
llm
,
tools
=
{
}
)
code
=
agent.
run
(
"Write a Python function to implement AES encryption for RUNOOB strings"
)
After generating code, the Agent self-checks the encryption implementation and key handling,
automatically corrects vulnerabilities found, ensuring the output is secure and reliable
Advantages
- Significantly improves output quality
- Allows setting clear quality standards
- Suitable for tasks with objective evaluation criteria
Disadvantages
- Multiple iterations increase latency and cost
- Requires setting a maximum iteration count to prevent infinite loops
- Limited effectiveness when evaluation criteria are difficult to formalize
Each reflection cycle is an additional LLM call, which significantly increases latency. Furthermore, a reflection count limit needs to be set, otherwise the model may fall into an "never satisfied" infinite loop.
Architecture Five: RAG + Agent (Retrieval-Augmented Agent)
Knowledge-Intensive Tasks Large Knowledge Base
Adding vector retrieval capabilities to the Agent's toolset allows the Agent to dynamically query external knowledge bases during inference, overcoming context window limitations.
RAG (Retrieval-Augmented Generation) is a technique that enables LLMs to query external knowledge bases. When combined with an Agent, it becomes more powerful: the Agent can proactively decide when and what to retrieve, instead of being passively retrieved once every time.
Figure 5 — RAG + Agent Retrieval-Augmented Architecture
Key Difference from Standard RAG
Standard RAG is "passive and one-time": it retrieves once when the user asks a question and stuffs the results into the Prompt.
RAG + Agent is different: the Agent autonomously determines at which stage of inference knowledge needs to be supplemented and what needs to be retrieved, and it can query the knowledge base multiple times until enough information is obtained to complete the task.
When the Codebase Q&A Agent is asked, "Why is the singleton pattern used here?", it proactively retrieves project documentation, design decision records, and relevant code files instead of just guessing based on the LLM's training memory.
Instance
Simplified implementation of RAG + Agent
class
RAGAgent:
"""Agent with dynamic retrieval capabilities"""
def
init
(
self
,
model
,
vector_db
,
max_retrievals
=
5
)
:
self
.
model
=
model
self
.
vector_db
=
vector_db
Vector database
self
.
max_retrievals
=
max_retrievals
def
should_retrieve
(
self
,
context:
str
,
question:
str
)
bool
:
"The Agent decides whether it needs to retrieve more information"
decision
=
self
.
model
.
generate
(
f
"""
Current known information: {context}
Current question: {question}
Is the existing information sufficient to answer the question? Answer YES or NO.
"""
)
return
"NO"
in
decision
def
run
(
self
,
task:
str
)
str
:
context
=
""
retrieval_count
=
0
while
retrieval_count
<
self
.
max_retrievals
:
Agent autonomously determines whether retrieval is needed
if
not
self
.
should_retrieve
(
context
,
task
)
:
break
Agent autonomously decides what to retrieve
search_query
=
self
.
model
.
generate
(
f
"""
Task: {task}
Existing information: {context}
To complete the task, what information should be retrieved next?
"""
)
Execute retrieval, and append the results to the context
docs
=
self
.
vector_db
.
search
(
search_query
)
context +
=
"\n"
.
join
(
docs
)
retrieval_count +
=
1
Generate the final answer by synthesizing all information
return
self
.
model
.
generate
(
f
"Task: {task}\nReference: {context}"
)
Usage example
agent
=
RAGAgent
(
model
=
llm
,
vector_db
=
runoob_docs_db
)
answer
=
agent.
run
(
"How to configure the database connection pool in the RUNOOB framework?"
)
Agent first retrieves "connection pool configuration" and finds a mention of "maximum connection count"
If not understood, it will re-search "Maximum Connection Count Best Practices"
Finally, it provides a complete answer based on the results of multi-round retrieval
Advantages
- Overcomes context window limitations
- Output is verifiable, reducing hallucinations
- The knowledge base can be updated independently
Disadvantages
- Retrieval quality affects the overall effect
- Vector database maintenance cost
- Retrieval latency increases response time
Architecture Six: Workflow Orchestration (Workflow / DAG)
Production preferred: High reliability
Solidifying Agent behavior into a Directed Acyclic Graph (DAG), where each node is an LLM call or tool call, and edges represent data dependencies, executed by the framework.
This is the Agent architecture closest to traditional software engineering. The biggest difference from the previous architectures is that the Agent's autonomous decision-making space is restricted within a single node, and the flow between nodes is predefined and unchangeable.
Figure 6 — Workflow DAG Architecture (Directed Acyclic Graph)
Pure Agent vs DAG Workflow
| Features | Pure Agent | DAG Workflow |
|---|---|---|
| Flow Control | Model autonomously decides the next step | Predefined DAG graph determines |
| Predictability | Low, the path may be different each run | High, execution path is determined |
| Debuggability | Difficult, relies on log tracing | Easy, each node has clear input and output |
| Fault tolerance | Relies on the model to recover itself | The framework provides retry and checkpoint continuation |
| Flexibility | High, capable of handling unexpected situations | Low, can only follow predefined paths |
The "Acyclic" characteristic of DAG means the workflow is deterministic—no infinite loops, the execution path can be fully predicted, and failed nodes can be retried independently.
DAG is the extreme of "low autonomy, high predictability." You need to pre-design the entire process. This is not a drawback, but an intentional design trade-off—in production environments, determinism is sometimes more important than flexibility.
Instance
A simplified definition of a DAG workflow (similar to LangGraph style)
from
langgraph
import
StateGraph
Define workflow state — data object passed between nodes
class
PipelineState:
raw_data:
str
=
""
Original input data
cleaned_data:
str
=
""
Cleaned data
analysis_result:
dict
=
{
}
Analysis result
final_report:
str
=
""
Final report
Define DAG nodes — each node is an independent processing unit
def
extract_data
(
state: PipelineState
)
PipelineState:
"""Node 1: Extract raw data from runoob database"""
state.
raw_data
=
query_database
(
"SELECT * FROM logs"
)
return
state
def
clean_data
(
state: PipelineState
)
PipelineState:
"""Node 2: Clean data (deduplication, format standardization)"""
state.
cleaned_data
=
preprocess
(
state.
raw_data
)
return
state
def
analyze_data
(
state: PipelineState
)
PipelineState:
"""Node 3: Statistical Analysis"""
state.
analysis_result
=
statistical_analysis
(
state.
cleaned_data
)
return
state
def
generate_report
(
state: PipelineState
)
PipelineState:
"""Node 4: Generate report using LLM"""
state.
final_report
=
llm.
generate
(
f
"Generate a report based on the following analysis results: {state.analysis_result}"
)
return
state
Build DAG: Define nodes and edges (data flow direction)
workflow
=
StateGraph
(
PipelineState
)
workflow.
add_node
(
"extract"
,
extract_data
)
workflow.
add_node
(
"clean"
,
clean_data
)
workflow.
add_node
(
"analyze"
,
analyze_data
)
workflow.
add_node
(
"report"
,
generate_report
)
Define edges: extract → clean → analyze → report
workflow.
add_edge
(
"extract"
,
"clean"
)
workflow.
add_edge
(
"clean"
,
"analyze"
)
workflow.
add_edge
(
"analyze"
,
"report"
)
workflow.
set_entry_point
(
"extract"
)
workflow.
set_finish_point
(
"report"
)
Compile and run
app
=
workflow.
compile
(
)
result
=
app.
invoke
(
PipelineState
(
)
)
(
result.
final_report
)
Advantages
- Predictable, auditable, and retryable
- Supports parallel acceleration
- High degree of engineering, friendly for operations and maintenance
Disadvantages
- The process needs to be pre-designed, resulting in low flexibility.
- It is difficult to handle unexpected situations.
- Requires learning an orchestration framework.
Horizontal comparison and how to choose.
Compares six architectures from multiple dimensions to help you quickly pinpoint the suitable option.
| Architecture | Autonomy | Predictability | Parallel capabilities | Suitable task complexity | Typical implementation |
|---|---|---|---|---|---|
| Single Agent loop | High | Low | None | Medium-low | Claude Code Default Mode |
| Planning + Execution | Middle | Middle | Partial | Medium-High | Claude Code Plan Mode |
| Multi-Agent Collaboration | High | Low | Strong | High | AutoGen, CrewAI |
| Reflection / Self-correction | Medium | Medium | None | Medium | Reflexion, Self-Refine |
| RAG + Agent | High | Medium | None | Medium-High | LangChain RAG Agent |
| Workflow Orchestration | Low | High | Strong | High (Fixed Flow) | LangGraph, Prefect |
Common Combination Patterns
Actual production systems usually combine multiple architectures; here are several mature combination patterns:
Workflow Orchestration + Multi-Agent: Define the main flow using a DAG, where each node is an independent Agent. For example, in a CI/CD pipeline, the code check node is a Code Review Agent, and the security scan node is a Security Agent.
Multi-Agent + RAG: Multiple Subagents share the same vector knowledge base and retrieve information as needed based on their respective subtasks. For example, in a customer service system, both the order inquiry Agent and the refund processing Agent query the same knowledge base but retrieve different content.
Planning and Execution + Reflection: Plan first, then execute, but add a reflection step after each step to ensure quality. This is suitable for tasks with extremely high quality requirements.
If you are unsure where to start, begin with a single Agent loop. It is the easiest to implement and debug. When you find the context window is insufficient, consider multiple Agents; when you need quality assurance, add a reflection layer; and when the process stabilizes, refactor it into a DAG to improve reliability.
Common Pitfalls
Pitfall One: More complex architecture is always better
Multi-Agent collaboration looks powerful, but if your task can be completed within 5 steps using a single Agent loop, introducing orchestration overhead will actually reduce efficiency. Principle: Use the simplest architecture that meets the requirements.
Misconception Two: Reflection will definitely improve quality
The effectiveness of self-reflection depends on the model's self-evaluation capability. If quality requirements are extremely strict, consider using a Critic model or introducing external validation (such as automated code testing).
Misconception Three: DAG workflows do not require Agents
DAG defines the process skeleton, but each node can still be an Agent call. Workflow orchestration and Agent capabilities are not mutually exclusive, but complementary—DAG provides reliability, and Agents provide flexibility.
Misconception Four: A large context window means RAG is unnecessary
Even if a model supports a 1M token context window, stuffing all documents in is still not the optimal solution. The value of RAG lies not just in "fitting everything," but in precise retrieval—reducing noise, lowering inference costs, and improving answer accuracy.
Summary
The six Agent architectures cover the entire spectrum from highly autonomous to highly controllable.
When choosing an architecture, there are only two core considerations: how much flexibility you need to handle unexpected situations, and how much certainty you need to ensure reliable results.
Start simple and only increase complexity when necessary; this is the first principle for selecting an Agent architecture.