Programmable AI Agent Architecture: Core Execution Loop and Engineering Design
This article breaks down the architecture of programmable AI agents, explaining why they are stateful runtimes rather than simple request-response systems. It covers a platform-agnostic core with channel adapters, the core execution loop, tool registration and dispatch, model API abstraction, context compression and persistence, observability and security boundaries, and a practical implementation checklist for building testable, operable, and extensible agent engines.
1. A Common Misconception: Agents Are Not Request-Response
Many developers first approach an agent as a linear pipeline: the user submits text, the model returns text, and the session ends. This mental model is fine for a demo, but it breaks down quickly in real production workloads. Tasks require multi-step reasoning, reading and writing to external systems, long-running execution, integration across multiple channels, and staying on target even as the context grows.
A programmable task execution engine must solve at least seven categories of problems at once: multi-turn session state management, tool registration and routing, context compression and persistence, a multi-channel message gateway, subtask delegation, periodic scheduling, and integration with external protocols and ecosystems. Stack these capabilities together and the complexity is no longer “calling a model once”—it is “building a runtime with a state machine.”
2. Overall Architecture: Platform-Agnostic Core + Platform-Specific Entrypoints
Mature designs typically follow a “separate the core from the entrypoints” structure, which maps to the ports and adapters pattern (also known as hexagonal architecture).
- Core layer: concerned only with sessions, reasoning, tools, and state; it does not care where a message came from.
- Adapter layer: converts message protocols, authentication methods, and message formats from different channels into a unified event.
- Unified event model: whether a message comes from a CLI, a desktop plugin, an instant messaging platform, or a code editor, it is normalized into the same structure.
A schematic unified event and adapter interface:
from dataclasses import dataclassfrom typing import Any, Protocol@dataclassclass InboundEvent:session_id: strtext: strattachments: list[Any]meta: dict[str, Any]class ChannelAdapter(Protocol):async def normalize(self, raw: Any) -> InboundEvent: ...async def reply(self, session_id: str, payload: Any) -> None: ...
This design yields three direct benefits: core logic is implemented only once; adding a new channel requires only a new adapter; and unit tests can run entirely independently of external platforms, asserting behavior against the core alone.
3. The Core Execution Loop: Where the Real Engine Lives
The core is usually concentrated in a single, relatively heavy runtime class or module responsible for assembling the system prompt and tool schemas, selecting the model provider and invocation mode, issuing interruptible model calls, executing tools (serially or concurrently), maintaining history, compression and retries, model fallback, tracking the iteration budget, and refreshing persistent memory before context is lost.
The lifecycle of a turn triggered by a user message can be abstracted as:
- Generate or reuse a task identifier;
- Append the user message to the session history;
- Build or reuse a cacheable system prompt;
- Run a pre-compression check (for example, when context usage exceeds a threshold);
- Build model messages from history;
- Inject ephemeral hint layers (budget warnings, context pressure notices, and so on);
- Attach cache markers for providers that support them;
- Issue an interruptible model call;
- Parse the response: if it contains tool calls, execute them and return to step 5; otherwise, produce the final answer.
Expressed as pseudocode:
async def run_turn(session, event):task_id = session.ensure_task_id()session.append_user(event.text)system_prompt = session.get_cached_system_prompt()if session.context_ratio() > 0.5:await session.pre_compress()while budget.remaining():messages = session.build_messages(system_prompt)messages = inject_ephemeral_hints(messages, budget, session)resp = await provider.call(messages, interruptible=True)if not resp.tool_calls:return resp.textfor call in resp.tool_calls:await tool_executor.run(call) # serial or concurrentreturn fallback_answer()
The most valuable idea here is the concept of a “budget”: treat iteration count, context usage, and tool call count as finite resources, model them explicitly, and feed them back to the model through the hint layers. This avoids infinite loops and silent failures.
4. Tool Registration and Dispatch: Turning Capabilities into Addressable Resources
Tools are not scattered functions; they are addressable resources with metadata. A registry typically includes name, description, parameter schema, risk level, timeout, and concurrency policy.
@dataclassclass ToolSpec:name: strdescription: strschema: dictrisk: str # read / write / destructivetimeout_s: intconcurrency: int = 1
Key points at the dispatch stage: validate against the parameter schema; decide whether human confirmation is required based on risk level; allow read-only tools to run concurrently while write operations default to serial; distinguish “retryable” from “non-retryable” failures; and feed structured errors back to the model so it can self-correct instead of throwing a stack trace.
5. API Pattern Abstraction: Hiding Provider Differences
Model providers differ significantly in message structure, tool call formats, cache markers, and streaming protocols. The common engineering approach is “capability description + policy adaptation”: define unified request and response models, then have each provider adapter perform bidirectional conversion; for unsupported capabilities (such as prompt caching), apply graceful degradation rather than scattering conditionals throughout business code.
6. Context Compression and Persistence
Long-running tasks inevitably hit context growth. Common strategies include: a sliding window that keeps recent messages; structured summarization of earlier content; writing key conclusions to external memory and retrieving them back when needed; and forcing a checkpoint to disk before compression. For the persistence layer, you can use general-purpose capabilities such as object storage for session snapshots, message queues for asynchronous tasks, and logging services with monitoring and alerting for observability. If running on a container platform, session state should also be decoupled from compute instances so tasks can resume after an instance restarts.
7. Observability and Security Boundaries
For each turn, it is recommended to record the task identifier, iteration count, context usage, tool calls, and elapsed time; set allowlists and secondary confirmation for high-risk tools; and apply prompt injection defenses and output filtering to external input. If you use general-purpose capabilities such as Baidu AI Cloud’s object storage, message queues, container platform, and monitoring and alerting to carry state and observability, you can further decouple the core from the infrastructure, keeping the architecture neutral and portable.
8. Implementation Checklist
- Layer the core and adapters first, then worry about the number of channels;
- Make budget and compression thresholds configuration items;
- Turn tool metadata into first-class data, classify by risk, and separate concurrent reads from writes;
- Unify request and response models, and degrade gracefully when capabilities are missing;
- Persist to disk before compression so you can recover after failures;
- Instrument the full pipeline, and put security and permissions upfront.
Following this path, an agent can grow from a demo script into a testable, operable, and extensible task execution engine.
