AI Agent Architecture Explained: Core Loop Design
This article breaks down the architecture of an AI Agent, moving beyond the basic request-response model to a programmable task execution engine. It explains a platform-agnostic core with adapters, the full lifecycle of a turn in the core loop, tool registration and dispatch, context engineering through compression and persistence, and reliability patterns such as retry, degradation, and interruption. Readers will find practical Python examples and common anti-patterns to avoid when building their own agents.
1. From “Request-Response” to a Task Execution Engine
Many developers first approach an AI Agent as a very short pipeline: receive user input, assemble a prompt, call the large language model, and return the text. This mental model is not wrong, but it only covers the surface interaction. Once you move to production, problems appear quickly: How do you keep multi-turn conversations consistent? What happens when a tool call fails? How do you handle unbounded context growth? Can a long task resume after interruption?
When a project has accumulated tens of thousands of stars and its documentation approaches textbook quality, the question worth asking is not “Is it popular?” but “Why is it complex?” After reading the source code end to end, the conclusion is usually that the value lies not in the model call itself, but in the engineering shell built around the model. It integrates the following capabilities into a single runtime:
- Multi-turn conversation state management;
- Tool registration, schema description, and dispatch execution;
- Context compression and persistence;
- Subtask delegation and parallel orchestration;
- Scheduled and event-driven task dispatch;
- Integration with external protocols and tool ecosystems.
With these capabilities combined, the nature of the system shifts: it is no longer a chat program, but a programmable task execution engine. This article takes a neutral perspective, abstracts a general layered architecture and core loop model, and uses Python semantics to clarify the responsibility boundaries of each layer.
2. Overall Architecture: Platform-Agnostic Core + Platform-Specific Entrypoints
The first principle of mature design is isolating change. Interaction entrypoints are naturally the most volatile part: CLI, desktop editor plugins, instant messaging bots, and web consoles each have completely different authentication methods, message formats, and rich text capabilities. If these differences leak into the core logic, the code will degrade into a pile of conditional branches within six months.
The recommended structure is “core + adapters”:
Entrypoint Layer (CLI / Editor Plugin / Chatbot / Web Console)│ Unified Message Model▼Adapter Layer (Identity Mapping, Message Normalization, Streaming, Error Presentation)▼Core Layer (AIAgent: Prompt Assembly, Loop Control, Tool Execution, State Maintenance)▼Capability Layer (Model Providers, Tool Implementations, Storage, Scheduler, Protocol Clients)
This structure has a well-established name in software engineering: Ports and Adapters, also known as Hexagonal Architecture. It brings three direct benefits:
- Core logic is implemented only once, and all entrypoints share the same behavioral semantics;
- Adding a new entrypoint only requires implementing one adapter to map external messages to the unified internal structure;
- Testing can completely bypass the platform by injecting fake models and fake tools into the core for deterministic assertions.
In practice, define the “unified message model” as immutable data structures to prevent layers from modifying state privately:
from dataclasses import dataclass, fieldfrom typing import Any@dataclass(frozen=True)class InboundMessage:task_id: str | Nonetext: strmeta: dict[str, Any] = field(default_factory=dict)@dataclass(frozen=True)class AgentEvent:kind: str # text / tool_call / tool_result / error / donepayload: dict[str, Any]
The adapter layer is only responsible for translation and does not carry business logic; once a platform-specific requirement starts polluting the core, the correct approach is to extend the port protocol, not add branches.
3. Core Loop: The Full Lifecycle of a Turn
The key implementation of the core is usually concentrated in a relatively large module. This is reasonable complexity concentration, not a design flaw. It handles at least nine responsibilities: assembling the system prompt and tool schema, selecting the model provider and call mode, initiating an interruptible model request, executing tools serially or concurrently, maintaining conversation history, handling compression, retries, and degradation, tracking the iteration budget, refreshing persistent memory before context loss, and emitting an observable event stream.
One user input corresponds to one turn, recommended to be split into the following phases with clear failure semantics for each:
- Task identification: generate a
task_idif absent, serving as the primary key for logging, storage, and idempotency control; - Push user message: append to conversation history with timestamp and source metadata;
- System prompt construction or reuse: cache the static part, inject the dynamic part in layers;
- Pre-compression check: when context usage exceeds a threshold (commonly 50%), summarize first rather than waiting for overflow;
- Message projection: convert from the history structure to the linear message sequence required by the target call mode;
- Ephemeral prompt injection: short-lived state such as budget warnings, context pressure, and current subgoals;
- Cache marking: for call modes that support prompt caching, mark the stable prefix boundary;
- Interruptible call: the request can be interrupted by a cancellation signal, with timeouts and rate limits handled separately;
- Response parsing and routing: if there are no tool calls, produce the final answer; if there are tool calls, execute them and return to step 5.
The pseudocode skeleton is as follows:
def run_conversation(self, msg: InboundMessage) -> Iterator[AgentEvent]:self.task_id = self.task_id or new_task_id()self.history.append(user_turn(msg))system = self.prompt_cache.get_or_build(self.static_prompt)while self.budget.remaining() > 0:if self.context.usage() > 0.5:self.history = self.compactor.summarize(self.history)payload = self.projector.to_messages(system, self.history)payload = self.ephemeral.inject(payload, self.budget, self.context)if self.provider.supports_prompt_cache:payload = self.mark_cache_boundary(payload)resp = self.interruptible_call(payload)if not resp.tool_calls:self.history.append(assistant_turn(resp.text))yield AgentEvent("done", {"text": resp.text})returnself.history.append(assistant_turn(resp.tool_calls))yield from self.tool_runner.run(resp.tool_calls) # results are written back to history and the loop continuesyield AgentEvent("error", {"reason": "iteration_budget_exhausted"})
The most important point here is the loop formed in step 9: tool results are not a side output, but re-enter the history and trigger the next round of model inference. It is this loop that turns “text generation” into “goal advancement.”
4. Tool Layer: Registration, Description, and Dispatch
Tools are the hands and feet of the execution engine. The design must completely separate three things: the registry (mapping from name to implementation), the schema (name, purpose, parameter constraints for the model to understand), and the executor (validation, invocation, timeout, result normalization).
Practical points:
- Description first. If parameter descriptions are unclear, the model will misuse them; descriptions should include units, value ranges, and failure meanings.
- Front-load input validation. Use structured validation to intercept invalid arguments before real side effects occur, avoiding dirty writes.
- Idempotency and reentrancy. Any tool involving external writes must have an idempotency key to prevent duplicate side effects from loop retries.
- Make concurrency strategy explicit. Read-only tools can run concurrently; write tools default to serial; concurrency must be configurable and constrained by semaphores.
- Bounded results. Truncate and structurally summarize overly long outputs to avoid a single tool return blowing up the context.
class ToolRegistry:def __init__(self) -> None:self._impl: dict[str, Callable[..., Any]] = {}self._schema: list[dict[str, Any]] = []def register(self, spec: dict[str, Any], fn: Callable[..., Any]) -> None:self._schema.append(spec)self._impl[spec["name"]] = fnasync def dispatch(self, call) -> dict[str, Any]:fn = self._impl.get(call.name)if fn is None:return {"error": f"unknown tool: {call.name}"}try:args = validate(call.arguments, schema_of(call.name))return {"result": await maybe_await(fn(**args))}except Exception as exc: # tool failures must be explainable, not abort the whole taskreturn {"error": str(exc)}
5. Context Engineering: Compression, Persistence, and Budget
Context is a finite resource and must be managed like memory. All three mechanisms are indispensable:
- Compression: when approaching the threshold, produce a structured summary of early history, retaining goals, constraints, confirmed facts, and unfinished items; raw tool outputs can be stored externally with only references kept in history.
- Persistence: write task state and key conclusions to external storage (such as object storage, relational databases, or message queues) so the process can recover after restart; persistence writes should be triggered before the risk of context loss rises, not as an afterthought.
- Budget: set limits on the number of turns, token usage, tool call count, and wall-clock time, and report the remaining allowance to the model via the ephemeral prompt layer so the model actively converges its strategy.
Observability is also part of context engineering: structured logs record task_id, phase durations, compression counts, and retry reasons; metrics and alerts integrate with general logging and monitoring systems to help locate “which step the task is stuck at.”
6. Reliability: Retry, Degradation, and Interruption
A production-grade core must assume model calls will fail. It is recommended to distinguish three error types and handle them separately: rate limits and timeouts use exponential backoff with jitter; parameter or mode incompatibilities are not retried meaninglessly but switch call modes directly; capability failures trigger model degradation, falling back to a smaller or more general model, and the degradation fact is annotated in history to avoid misjudgment in subsequent inference.
Interruption capability is often underestimated. Long tasks need cooperative cancellation: the call layer listens for cancellation signals, the tool layer checks cancellation flags and releases resources, partial results are persisted, and recovery resumes with the task_id. Subtask delegation is an extension of the same mechanism: the parent task dispatches subgoals, the subtask has an independent context and budget, and only the conclusion is returned, thereby controlling main context expansion.
7. Implementation Advice and Common Anti-Patterns
- Stabilize the unified message model and port protocol before writing entrypoints;
- Keep the core loop “pausable, resumable, and replayable”; do not rely on the process staying resident in memory;
- Layer prompts: separate static specifications, task context, and ephemeral state to facilitate caching and troubleshooting;
- Keep the number of tools within a recognizable range; too many will significantly reduce selection accuracy;
- Use fake models for unit tests, covering tool loops, compression triggers, budget exhaustion, and degradation paths;
- Anti-patterns include: writing business logic in the adapter layer, free loops without budget limits, write tools without idempotency guarantees, and avoiding compression design by merely expanding the context window indefinitely.
8. Conclusion
The real barrier of such projects lies not in the few dozen lines that call the model, but in encapsulating uncertainty into a controllable loop: unified entrypoint abstraction, explicit turn lifecycle, bounded tool layer, layered context governance, and interruptible and resumable execution semantics. Once you master this structure, whether building an internal automation assistant or setting up your own task execution engine on a cloud environment such as Baidu AI Cloud using container platforms, object storage, and monitoring alerts, you can avoid many detours.
