Agent Architecture Deep Dive: Core Loop and Engineering Design
This article breaks down how production AI agents are architected beyond the basic request-response model. It explains the separation between platform-specific entry points and a platform-agnostic core, the agent loop that drives multi-step execution, tool registration and dispatch, context compression and persistence, sub-agent delegation and scheduling, and how to keep the system testable as it evolves.
1. A Common Misconception: An Agent Is Not Request-Response
When developers first work on an agent project, they often assume it is a minimal pipeline: receive user input, pass it to a large language model, get back a piece of text, and finish. This mental model is fine for a demo, but it breaks down quickly in real business scenarios. The reason is straightforward: real tasks are multi-step, interruptible, dependent on external capabilities, and highly sensitive to context length and cost.
A mature agent runtime takes on several responsibilities at once: multi-turn session state management, tool registration and routing, context compression and persistence, multi-channel message ingestion, sub-task delegation, scheduled periodic tasks, and integration with external protocol-based capabilities. Combining these capabilities changes the nature of the system—it is no longer a chatbot, but a programmable task execution engine.
Understanding this shift is the prerequisite for making sense of this kind of architecture. The layers are unpacked below.
2. Overall Layering: Separating the Core from Entry Points
The first key design decision in these systems is to fully separate “platform-related integration logic” from “platform-agnostic execution logic.”
Whether a conversation comes from a command line, a desktop editor plugin, an instant messaging group, or a self-built business console, it all flows into the same agent core class. This yields three direct benefits:
- Core decision logic is implemented only once, avoiding behavior drift across multiple front ends;
- Adding a new channel only requires implementing one adapter that normalizes the external message format into an internal unified event;
- Testing can bypass the platform entirely and run unit and integration checks directly against the core.
In engineering terms, this maps to the well-known ports and adapters pattern, often called hexagonal architecture. The core defines a set of “ports” (such as message input, model invocation, tool execution, and storage read/write), and the outside world connects through “adapters.” The dependency direction always points inward, and the core is unaware of any specific channel.
A sketch of the structure looks like this:
class MessagePort(Protocol):async def receive(self) -> IncomingEvent: ...async def reply(self, event: IncomingEvent, payload: OutgoingMessage) -> None: ...class ModelPort(Protocol):async def complete(self, messages: list[dict], tools: list[dict]) -> ModelResponse: ...class ToolPort(Protocol):def schema(self) -> list[dict]: ...async def run(self, name: str, args: dict) -> ToolResult: ...class AgentCore:def __init__(self, model: ModelPort, tools: ToolPort, store: StorePort): ...async def handle(self, event: IncomingEvent) -> None: ...
3. The Core Loop: The Real Execution Engine
The core logic is usually concentrated in one large file with dense responsibilities, and there is no need to avoid that fact. It handles at least nine things: assembling the system prompt and tool schema descriptions, selecting the appropriate model provider and invocation mode, executing interruptible model calls, running tools serially or concurrently, maintaining conversation history, handling compression, retries, and model fallback, tracking the iteration budget, and refreshing persistent memory before context is lost.
3.1 Lifecycle of a Single Turn
For each user message processed, the main conversation function goes through roughly these steps:
- Generate a session identifier if none exists, used to correlate logs, traces, and persistence;
- Append the user message to the conversation history;
- Build or reuse a cached system prompt;
- Decide whether pre-compression is needed (for example, when context usage exceeds roughly a half threshold);
- Build a message sequence from the conversation history that conforms to the invocation spec;
- Inject ephemeral prompt layers, such as budget warnings and context pressure hints;
- If the model in use supports prompt caching, mark it to reduce cost and latency;
- Issue an interruptible model call;
- Parse the response: if it contains tool calls, execute the tools and then return to step 5 to continue the loop; otherwise, output the final answer and end the turn.
The most valuable part to borrow is the closed loop formed at step 9. The model output is not the endpoint, but a branch in the control flow. After tool results are fed back into the message sequence, they re-enter the model until the model no longer requests tools. The entire loop must set an iteration limit; otherwise, it can easily fall into an infinite loop when tools repeatedly fail and burn through the budget.
3.2 Interruptible Calls and Budget Guardrails
Production environments need two guardrails. First, interruptibility: the call must be able to be canceled by a cancellation signal, avoiding continued background billing after the user gives up. Second, budget tracking: set upper limits on the number of iterations, tool calls, and context growth for each task; when exceeded, degrade to “text-only replies allowed” or return a progress note to the user directly.
async def run_turn(self, event):self.ensure_task_id(event)self.history.append(user_msg(event.text))system = self.get_cached_system_prompt()if self.context_ratio() > 0.5:await self.compress_history()for step in range(self.max_iterations):messages = self.build_messages(system)self.inject_ephemeral_hints(messages)resp = await self.model.complete(messages, self.tools.schema())if not resp.tool_calls:return resp.textfor call in resp.tool_calls:result = await self.tools.run(call.name, call.args)self.history.append(tool_msg(call.id, result))return self.budget_exceeded_message()
4. Tool Registration and Dispatch: The Skeleton of Capability Expansion
The tool mechanism determines the capability boundary of the agent. A good implementation usually contains four parts.
The first is declarative registration. Each tool carries its own name, natural language description, parameter schema, and return convention, collected at startup into a schema list handed to the model. Description quality directly affects selection accuracy; it should state clearly “what it does, when to use it, and when it does not apply.”
The second is unified dispatch. The model returns a structured call intent, and a dispatcher executes it by looking up the name in a table. Parameters must pass schema validation before being applied; on validation failure, return a readable error rather than throwing a stack trace, giving the model a chance to self-correct.
The third is execution policy. Read-only tools can run concurrently to improve throughput; write operations and tools with external side effects should run serially or with locks to keep ordering predictable. All tool calls need timeouts and retry limits, with idempotency clearly distinguished.
The fourth is observability. Each call records an identifier, duration, result, and failure reason, forming a traceable chain—the only reliable basis for later tuning prompts and tool descriptions.
5. Context Compression and Persistence
Context is a finite resource, and compression is a required capability rather than an optimization. Common approaches come in three layers: first, summarize early conversation, keeping conclusions and constraints while discarding pleasantries and intermediate noise; second, trim tool return results, keeping only structured key fields; third, write long-term facts to external storage and retrieve and backfill them by relevance when needed.
Persistence must distinguish two kinds of data: short-term state within a session, used to resume interrupted tasks, and long-term memory across sessions, used to carry user preferences and project background. Write timing is critical—it should proactively refresh before context is about to overflow, rather than remediate after loss. In engineering terms, object storage can hold session snapshots, a message queue can buffer asynchronous writes, and logging services with monitoring and alerting can cover error rates and latency distributions.
6. Sub-Task Delegation and Scheduling
When a task can be decomposed, the main agent can delegate independent sub-goals to sub-agents, each holding its own context and returning only conclusions. This both compresses the main context and isolates the impact of failures. Delegation needs to specify three things: the input contract of the sub-task, the return format, and the timeout and retry policy.
Periodic tasks are handled by a scheduler responsible for trigger conditions, concurrency control, and failure compensation. All triggers should carry a unique identifier to guarantee idempotent results under repeated triggering. If you need to integrate an external protocol-based capability system, it is best to treat it as a special kind of tool under unified management rather than opening a separate branch in the core, thereby keeping the dependency direction from reversing.
7. Testability and Evolution Recommendations
Whether the architecture is healthy can be self-checked with three questions: can the core logic be fully tested without any external platform; does adding a new channel only change the adapter layer; can tools and models be swapped without touching the loop logic. If all answers are yes, the layering is effective.
The recommended rollout order is: first implement a minimal viable core loop and tool dispatch, then add compression and persistence, followed by budget guardrails and observability, and finally extend to multi-channel integration, sub-task delegation, and scheduling. Keeping the core interfaces stable at each stage makes the evolution cost significantly lower than stacking all capabilities at once. If the whole system runs on a container platform, pairing it with externalized configuration and canary releases gives prompt and tool strategy adjustments the ability to roll back quickly.
