Agent Architecture Explained: Core Loop and Engineering Design
This article breaks down how modern AI agents are built beyond the simple request-response chatbot model. It explains the layered architecture of a platform-agnostic core with thin channel adapters, walks through the turn lifecycle of the core execution loop, and covers tool registration and dispatch, context compaction and persistence, sub-agent delegation, scheduling, external protocol integration, and observability and testing strategies. Readers will learn the four engineering priorities that turn a demo prototype into a production system that can run reliably over the long term.
1. A Common Misconception: An Agent Is Not a Request-Response Chatbot
When developers work on an agent project for the first time, many picture a minimal pipeline: receive user input, pass it to a large language model, get a text reply, and finish. That mental model is fine for a demo, but it quickly shows three weaknesses in real business scenarios: it cannot execute multi-step actions, it cannot maintain context consistency across long tasks, and it cannot connect to external systems.
A programmable task execution engine typically needs all of the following capabilities at once: multi-turn conversation state management, tool registration and routing, context compaction and persistence, multi-channel message ingestion, sub-task delegation, periodic task scheduling, and a standardized protocol for integrating external capabilities. Stack those capabilities together and the system’s complexity is no longer on the scale of a “chatbot”—it approaches the scale of a distributed task runtime.
Understanding this is the prerequisite for making sense of modern agent architecture. The sections below build up layer by layer.
2. Overall Layering: A Platform-Agnostic Core Plus Platform-Specific Entrypoints
The core principle of a mature design is to isolate the parts that have nothing to do with business value. In practice, this means building a platform-agnostic core and then writing a thin adapter for each channel you connect.
Whether a request comes from a command line, a desktop editor plugin, an instant messaging tool, or a custom-built console, it all converges on the same agent core class. This yields three direct benefits:
- The core decision logic is implemented only once, avoiding behavior drift across clients;
- The cost of adding a new channel shrinks to a single adapter, which usually only needs message format conversion, identity mapping, and streaming responses;
- Testing can be done entirely independently of channels, with unit tests and replay tests run directly against the core.
This pattern has an established name in software engineering: the ports and adapters pattern, also known as hexagonal architecture. The core defines the “ports” (interface contracts), and the outside world provides the “adapters” (concrete implementations). Illustrative code:
class MessagePort(Protocol):async def receive(self) -> IncomingMessage: ...async def reply(self, msg: IncomingMessage, chunk: str) -> None: ...class AgentCore:def __init__(self, bus: MessagePort, tools: ToolRegistry): ...async def handle(self, msg: IncomingMessage) -> None:async for chunk in self.run_conversation(msg):await self.bus.reply(msg, chunk)
3. The Core Execution Loop: Breaking Down the Turn Lifecycle
The key implementation of the core usually lives in one fairly large core file that carries orchestration responsibilities. It has to assemble the system prompt and tool schema descriptions, choose the right model provider and invocation mode, issue an interruptible model call, execute tools serially or concurrently, maintain conversation history, handle compaction, retries, and model fallback, track the iteration budget, and refresh persistent memory before context is lost entirely.
Once a single user message arrives, a turn goes through roughly these stages:
- Generate or reuse a task identifier to tie logs and traces together;
- Append the user message to the conversation history;
- Build or reuse a cacheable system prompt;
- Pre-compaction check: tidy things up early when context usage exceeds a threshold (commonly set to half);
- Build a message sequence that conforms to the invocation spec from the conversation history;
- Inject temporary prompt layers, such as budget warnings and context pressure notices;
- If the model in use supports prompt caching, add cache markers to reduce repeated overhead;
- Issue an interruptible call so the user can cancel midway;
- Parse the response: if there are tool calls, execute the tools and go back to step 5; otherwise, output the final reply.
The loop in step 9 is where the “engine” of the whole design lives. It turns a single question-and-answer exchange into a stateful execution process, with termination decided jointly by “no tool calls” and “budget exhausted.”
while budget.remaining():messages = build_messages(history, system_prompt)resp = await interruptible_call(messages, cache_hint=True)if not resp.tool_calls:return resp.textfor call in resp.tool_calls:result = await registry.dispatch(call) # can run concurrentlyhistory.append(tool_result(call.id, result))
4. Tool Registration and Dispatch: Turning Capabilities into Discoverable Assets
The quality of the tool layer determines the agent’s ceiling. The recommended approach is declarative registration: each tool carries its own name, natural-language description, parameter schema, and timeout policy. The registry validates everything at startup and uniformly converts it into schema descriptions the model can understand when building requests.
Dispatch has to handle four engineering problems: first, concurrency—independent read-only tools should run in parallel while write operations stay serial; second, idempotency—attach an idempotency key to each tool call to avoid duplicate side effects from retries; third, timeouts and circuit breaking—slow tools must have an upper bound and support a fallback return; fourth, permissions—enforce a capability allowlist based on task origin and user identity.
@tool(name="search_docs", schema=SearchArgs, concurrency="safe")async def search_docs(args: SearchArgs) -> str:...
5. Context Compaction and Persistence: Keeping Long Tasks Running
The context window is a hard constraint, so a compaction strategy is a must-have. A common combination is: a sliding window that keeps the raw text of the most recent turns, structured summaries of earlier content (goal, completed actions, key conclusions, to-dos), and critical facts that must not be lost written to external persistent storage and re-injected via retrieval when needed.
Three things to watch in engineering: compaction must be traceable, preserving the mapping between summaries and original text; compaction must reserve output space to avoid overflowing again right after compacting; and persistence writes must happen before context is lost, not as an after-the-fact remedy.
6. Sub-Agent Delegation, Scheduling, and External Protocol Integration
Complex tasks should support splitting: the main agent only plans and summarizes, delegating independently completable branches to sub-agents that each have their own context and tool subset, which keeps context from ballooning at a single point. Periodic tasks are driven by a scheduler that is decoupled from the message entrypoints and shares the same core.
When integrating with external systems, it is best to adopt a standardized capability integration protocol that exposes server-side capabilities as tools in a uniform way, avoiding custom glue code for every system. If deployed in the cloud, you can use a container platform to host the runtime, a message queue for task buffering, object storage for session snapshots, and logging and monitoring/alerting services for observability. For example, when using general capabilities from Baidu AI Cloud, the same layering principle applies: the core stays unaware of the specific infrastructure.
7. Observability and Testing Strategy
Use the task identifier as the primary key to string together full-chain logs, recording token consumption, tool latency, and failure reasons for each model call. Use record-and-replay tests for the core loop, validating branch logic against a fixed set of responses. Run contract tests on the tool layer to ensure parameter schemas match implementations. This way, the regression cost stays manageable when you introduce a new model or a new channel.
In summary, the engineering focus of an agent is not “calling the model” but layered decoupling, turn orchestration, tool governance, and context endurance. Master these four points and you can move a demo-grade prototype to a production system that runs reliably for the long haul.
