AI Agent Architecture Explained: Core Loop Design
This article breaks down the architecture of a mature AI Agent runtime, moving beyond the chatbot analogy to treat an agent as a long-running process. It covers layered decoupling with a ports-and-adapters approach, the full lifecycle of a single turn in the core loop, tool registration and dispatch, context compression and persistence, and scheduling with external protocol integration. Readers will learn the key engineering details—interruptible model calls, budget tracking, explicit termination conditions, and metadata quality—that separate a programmable task execution engine from a chat window with an API attached.
1. A Widely Underestimated Misconception: An Agent Is Not a Chatbot
Many developers with a few years of backend experience instinctively treat their first AI Agent project as a very short pipeline: receive user input, forward it to a large language model, and return the resulting text to the user. The problem with this mental model is that it treats the agent as a stateless function, whereas a real agent behaves more like a long-running process.
The difference shows up across four dimensions. First is state: a real system must maintain conversation history across turns and make trade-offs when the context window is about to run out. Second is time: a single user request may trigger background work lasting minutes or even tens of minutes, which a request-response model cannot accommodate. Third is side effects: an agent calls tools, writes files, and sends notifications, so failures must be retryable and observable. Fourth is resource constraints: model calls have rate and budget limits, so the loop needs a clear termination condition.
Once you accept these four points, the architectural complexity is no longer over-engineering but an inevitable outcome. A mature agent runtime typically needs to combine tool registration and dispatch, context compression and persistence, scheduled task execution, and external protocol integration. Stacked together, these turn the system from a chat interface into a programmable task execution engine.
2. Layered Decoupling: Write the Core Logic Only Once
The first design worth borrowing from this kind of project is the separation of the entry layer from the core. Whether a conversation starts from an instant messaging tool, a command-line terminal, or an editor plugin, the request ultimately converges on the same agent core class.
This structure has an established name in software engineering: the ports-and-adapters pattern, often called hexagonal architecture. The business core defines a set of port interfaces, and each external channel implements an adapter responsible for protocol conversion, identity recognition, message format normalization, and streaming responses back.
The benefits are concrete:
- Zero duplication of core logic. System prompt assembly, tool execution, and compression strategy each have a single implementation, so fixing a bug does not require changing N platform branches.
- Linearly controllable integration cost. Adding a channel only requires implementing the adapter contract without touching the core.
- Clear test boundaries. You can drive the core with in-memory fake message objects, fully detached from external platforms, and run unit tests in milliseconds.
In practice, keep the adapter contract narrow enough to include only three capabilities: receiving messages, returning an event stream, and reporting status. This prevents platform-specific features from polluting the core in reverse.
3. The Core Loop: The Full Lifecycle of a Turn
The core is usually concentrated in one very large file, and the official documentation openly admits that it carries heavy responsibilities. It handles at least seven things: assembling the system prompt and tool schema, selecting the appropriate model provider and invocation mode, executing an interruptible model call, running tools serially or concurrently, maintaining conversation history, handling compression retries and model fallback, and tracking the iteration budget while refreshing persistent memory before context is lost.
Once a user message arrives, the main loop goes through roughly the following stages:
- Generate or reuse a task identifier to correlate logs and traces.
- Append the user message to the conversation history.
- Build or reuse a cacheable system prompt.
- Decide whether pre-compression is needed, with a common threshold being context usage exceeding half.
- Build the API message array for this call from the conversation history.
- Inject ephemeral prompt layers, such as budget warnings and context pressure hints.
- If the model supports prompt caching, mark it for caching to reduce cost and latency.
- Issue an interruptible model call.
- Parse the response: if it contains tool calls, execute the tools and return to step 5 to continue the loop; otherwise, output the final result.
Schematically, this loop can be abstracted as:
while budget.remaining():messages = build_messages(history, system_prompt, ephemeral_hints)resp = interruptible_call(provider, messages, cache=True)history.append(resp.assistant_message)if not resp.tool_calls:return finalize(resp)results = run_tools(resp.tool_calls, concurrency=policy)history.extend(results)maybe_compress(history, threshold=0.5)
Three engineering details determine success or failure. Interruptible means the cancellation signal must penetrate the network call, so that pressing stop does not leave orphan tasks behind. Budget tracking requires the loop to have a hard limit; otherwise, a tool error can trigger infinite retries. The termination condition must be declared explicitly rather than relying on the model’s own restraint.
4. Tool Registration and Dispatch: Turn Capabilities into Addressable Interfaces
The key to the tool layer is not quantity but metadata quality. Each tool needs to declare its name, purpose description, parameter schema, and return structure. This information goes into the model context together and directly determines invocation accuracy.
The dispatcher is responsible for validating parameters, enforcing execution timeouts, truncating results, and normalizing errors. It is advisable to default to concurrency with an upper bound while keeping write operations serial to avoid mutual overwrites. All tool calls should log an input summary, duration, and status code to form a traceable audit trail.
5. Context Compression and Persistence: Fighting a Finite Window
Context compression is not simple truncation but a layered strategy: first discard redundant raw tool output, then summarize earlier conversation, while preserving decision conclusions and unfinished items. Persist to disk both before and after compression to ensure a task can resume after a process restart.
Persistence is usually split into two types of storage: structured metadata goes into a relational database, long text and attachments go into object storage, and hot caches go into memory or a cache service. On Baidu AI Cloud, this combination can map to general categories such as cloud databases, object storage, and cache services, working with logging and monitoring/alerting to close the observability loop.
6. Scheduling and Protocol Integration: From Passive Response to Active Operation
Scheduled tasks give an agent initiative and require handling idempotency, staggered timing, and failure retries. External protocol integration is used to unify access to different tool ecosystems; the core is converting descriptions of external capabilities into internal tool schemas, with permission isolation and timeout fallbacks.
7. Conclusion
You can judge whether an agent project is mature by looking at three things: whether the core is decoupled from the entry layer, whether the loop has a budget and a termination condition, and whether the context has compression and persistence. With these three in place, it is a programmable task execution engine rather than a chat window with an interface wrapped around it.
