How AI Agents Work and How to Design Multi-Agent Architecture
This article explains how AI agents work and how multi-agent systems are designed. It covers the task loop that connects model decisions with tool calls, the core components of an agent runtime, and why sub-agents are useful. It also describes where sub-agents can run, how real-time event streams and context inheritance work, and how users can intervene in, cancel, and recover tasks. The article ends with criteria for evaluating an agent architecture.
1. AI Agents Are More Than Chat Models
AI agents are generally understood as intelligent software systems that can complete a series of tasks on their own. The main difference from a standard question-answering model is not the size of the model. It is whether the system runs a continuous task loop:
- Understand the user’s goal.
- Make or adjust an execution plan.
- Call external tools to get information or perform actions.
- Observe the results returned by the tools.
- Keep making decisions based on the new information.
- Output the result when the task is completed, fails, or is stopped.
A complete agent is therefore not just a language model. It is a runtime system made up of the model, context, tools, executor, state storage, permission system, and user interface.
This process can be abstracted as follows:
User input↓Task understanding and planning↓Model decision↓Tool call / subtask dispatch↓Observe execution results↓Update context and state↓Continue execution or return result
The model handles reasoning about what to do next. The runtime handles how to execute safely and reliably. The interface handles how to show the user what is happening.
2. Core Components of an Agent
1. Session and Context
Context is the basis for continuous decision-making. It usually includes:
- the user’s original request;
- historical conversation messages;
- the current task goal;
- completed actions;
- tool call parameters and results;
- summaries of files, code, or external data;
- the current execution stage and error information.
Context should not be treated as a text string that simply keeps growing. In practice, systems usually need to structure it. For example, they can store messages, tool calls, execution state, and checkpoints separately. This makes recovery easier and avoids reloading the full history for every request.
When context grows too long, the system can use summarization, layered memory, and on-demand loading. Recent operations keep more detail, while older content is compressed into task summaries. History that is unrelated to the current step can be loaded later, when it is needed.
2. Tool System
Tools are the interfaces that connect an agent to its environment. Common types include:
- file reading and editing;
- command execution;
- search and retrieval;
- database access;
- network requests;
- testing and building;
- log analysis;
- task status queries.
Tool calls must pass explicit parameter validation and permission checks. Model output should not be treated as trusted instructions. The runtime must parse it first. For example, a command execution tool should restrict the working directory, environment variables, network access scope, and the types of files it can operate on. It should also record the caller, the time, the parameters, and the results.
3. Execution Loop
The agent’s execution loop usually looks like the following pseudocode:
while not task.finished:decision = model.decide(context)if decision.type == "tool_call":check_permission(decision)result = executor.run(decision)context.append(decision, result)event_bus.publish(result)elif decision.type == "delegate":child = scheduler.start(decision)context.append(child.summary())else:task.finish(decision.output)
Real systems also need to handle timeouts, retries, cancellation, concurrency limits, tool failures, and context conflicts. The execution loop is therefore essentially a workflow engine with state management and event dispatching.
3. Why Sub-Agents Are Needed
When a task contains several relatively independent work items, it can be split among multiple sub-agents. For example, when modifying a large codebase, different sub-agents can:
- analyze the project structure;
- locate the relevant modules;
- write or modify code;
- run tests;
- check for security risks;
- summarize the impact of the changes.
The main agent handles overall planning, task decomposition, and result integration. Sub-agents carry out the specific execution work. This approach has three benefits.
First, it can shorten overall waiting time. Independent tasks can run in parallel.
Second, it can reduce the complexity of each context. Each sub-agent focuses only on its own goal and does not need to carry unrelated history.
Third, it creates clearer boundaries of responsibility. Analysis, implementation, and verification can each produce separate results, which makes them easier to trace and review.
However, multi-agent does not simply mean starting multiple model instances. The hard part is managing their lifecycle, communication, permissions, resources, and user experience.
4. Where Sub-Agents Should Run
One option is to create a separate operating system process for each sub-agent. This provides strong isolation. If one sub-agent crashes, the main process is not necessarily affected. The costs are also clear:
- inter-process communication is complex;
- real-time output requires additional forwarding;
- session state can easily become scattered;
- users have difficulty viewing the full execution process;
- the interruption and permission control chain is longer.
A more common option is to run sub-agents inside the main process and isolate them through separate tasks, threads, or asynchronous execution units. This makes it possible to share the event bus, configuration, and some resources. It also makes real-time interfaces easier to build.
Whichever approach is used, the key is not the choice between threads and processes. What matters is whether the system has these capabilities:
- Each sub-agent has a unique identifier.
- Each sub-agent has its own independent session record.
- Sub-agent events can be routed accurately.
- Sub-agents can be paused, canceled, and resumed individually.
- Sub-agents have clear resource and permission boundaries.
- The main agent receives structured results, not just a block of text.
For interactive development, asynchronous tasks inside the main process usually make low-latency observation and control easier. For untrusted code, strongly isolated tasks, or high-risk operations, separate processes or containers can provide a stricter security boundary.
5. Real-Time Event Streams as the Foundation of Multi-Agent Interfaces
Users care about the final result, and they also care about what the agent is doing right now. If the interface only shows “Running” or “Completed,” users cannot tell whether a task is stuck or has misunderstood the request. They also cannot stop a dangerous operation in time.
The runtime therefore needs a unified event stream. Each event should contain at least the following fields:
Event type: text delta, tool started, tool result, status change, error, completedAgent identifier: which agent the event belongs toSession identifier: which task session the event belongs toTimestamp or sequence number: when the event was producedPayload: text, tool parameters, result summary, or error details
All events first enter the event bus and are then dispatched to the matching interface based on the agent identifier. When the user switches interfaces, the system should not rerun the task. Instead, it should restore the display by combining a historical snapshot with real-time increments:
- Read the current agent’s session snapshot.
- Get the events generated after the snapshot.
- Merge and deduplicate the events by sequence number.
- Continue subscribing to subsequent events.
This approach avoids two common problems. One is losing intermediate output after switching interfaces. The other is duplicated content when the snapshot and the real-time messages overlap.
For sub-agents that are not currently open, the system can keep only the unread count, recent activity, and current status. The full record is loaded when the user opens that session. This reduces interface load and controls memory use.
6. Context Inheritance and Independent Sessions
Sub-agents usually need to inherit part of the main agent’s context, but they should not copy the entire history. A better approach is to pass a task package that contains:
- the sub-task goal;
- the necessary background summary;
- the scope of relevant files or data;
- the output format;
- the permission boundary;
- the completion conditions;
- the parent task identifier and nesting level.
The detailed process of a sub-agent is stored in its own session. When it returns results to the main agent, it submits only a structured summary, the key changes, and any unresolved issues.
For example:
{"task_id": "child-17","status": "completed","changed_files": ["module_a", "module_b"],"tests": {"passed": 8, "failed": 0},"summary": "Adjusted interface validation logic","risks": ["Boundary inputs not yet covered"]}
This design prevents parent and child sessions from contaminating each other. It also slows the growth of the main context. Sub-agents should not inherit all of the main agent’s permissions by default. Permissions should be passed explicitly in the task package.
7. User Intervention, Cancellation, and Recovery
Intervenability is an important measure of whether an agent is ready for product use. Users should be able to:
- view the real-time process of any sub-agent;
- send additional instructions to a running sub-agent;
- pause or cancel a single sub-agent;
- cancel the entire task tree;
- rerun a sub-agent after it fails;
- return to the main session without affecting other tasks.
Cancellation cannot rely only on a flag set in the interface. The runtime needs to check the cancel signal at points such as model requests, tool execution, wait queues, and concurrent scheduling. For external commands that have already started, the system must decide, based on the execution environment, whether to terminate the process gracefully or force it to stop.
Recovery depends on checkpoints. After each important stage, the system saves the task state, a context summary, and the tool results. If the process fails, the system can continue from the most recent checkpoint instead of starting over.
8. Resource Control and Fault Isolation
Running multiple agents concurrently consumes model request quota, CPU, memory, file handles, and connections to external services. Scheduling policies are therefore required:
- limit the number of agents running at the same time;
- limit
