Python Architecture for an AI Agent Core Loop: Ports, Adapters, Tools, and Context Management
Many production agent systems begin as a simple request-response pipeline, but real workloads require multi-turn state, tool execution, retries, fallback policies, context compression, persistence, and support for channels such as command-line tools, chat platforms, and editors. This article presents a Python-oriented architecture that separates the platform-independent agent execution kernel from entry adapters. It covers layered design, the lifecycle of a conversation turn, tool registration and dispatch, model access abstraction, context compression and persistence, subtask delegation, scheduling, multi-channel support, budgets, observability, and practical implementation boundaries.
Many teams first build an agent as a straight line: a user message arrives, the model is called, and a text response is returned. That path is sufficient for a demo, but it does not hold up under real business workloads. Real requests often span multiple turns, require external capabilities, need retries or graceful degradation when failures occur, need history compaction as context grows, and must serve different entry points such as command-line tools, instant messaging, and editors. If all of these capabilities are packed into one script, the system quickly becomes a giant procedure that is difficult to test.
A more robust approach is to separate the kernel that “converses with the model and executes tools” from the code that decides “where messages come from and where results go.”
1. Correcting a Common Misconception
Request-response is suitable for stateless question answering, not for task execution. Task execution includes at least:
- Conversation state
- The set of available tools
- A per-turn budget
- A failure strategy
- The timing for writing intermediate results back to durable storage
If any of these is missing, the system will lose context during long conversations, tool timeouts, or channel reconnections.
The goal can be defined as a platform-agnostic execution kernel plus platform-specific entry adapters. No matter which channel starts a conversation, the request ultimately enters the same agent object. The kernel is implemented once; adding a channel only adds an adapter. Unit tests can run without starting any real channel by injecting messages into the kernel and using a fake model client. This is how the Ports and Adapters pattern, often called hexagonal architecture, applies to agents: the core depends on abstract ports, while concrete model services, message gateways, and storage implementations are replaceable on the outside.
2. Overall Layering
At a minimum, divide the system into four layers, and avoid overlapping responsibilities.
Entry adaptation layer: Normalize channel events into unified messages. Fields typically include conversation ID, user ID, text or rich text, attachment references, and an idempotency key. Adapters handle authentication, rate limiting, and channel-specific presentation formats. They do not decide whether a tool should be called.
Conversation and state layer: Maintain conversation history, task ID, iteration count, compressed summaries, and long-term memory pending refresh. State reads and writes should be replaceable: an in-memory implementation for tests, and a persistent implementation for production.
Execution kernel: Assemble the system prompt and tool descriptions, choose the model access method, initiate interruptible calls, execute tools, write tool results back to history, and decide whether to continue the loop.
Capability ports: Model invocation, tool execution, object storage, message queues, logging, and monitoring. Ports should be expressed as small interfaces. The kernel should not directly depend on the client types of any particular service provider.
With this separation, the boundary of a “programmable task execution engine” becomes clear: the engine is the loop and state machine, while channels and models are pluggable dependencies. Conversation snapshots, attachments, and large results can be stored in object storage. Cross-process tool callbacks or scheduled triggers can be placed on a message queue. These can be implemented with general managed cloud capabilities such as object storage, message queues, and monitoring and alerting, while keeping provider-specific details out of the kernel.
3. The Lifecycle of a Conversation Turn
When processing a user message, use a fixed and observable sequence of steps instead of scattering branches throughout the code.
- If no task ID exists, create one. This helps logs, billing, and cancellation align with the same execution.
- Append the user message to conversation history, and record the arrival time and channel source.
- Build or reuse the system prompt. Stable parts should be cached to avoid re-concatenating large blocks of unchanged text every turn.
- Before calling the model, check context pressure. In practice, when usage approaches half of the model window, pre-compression should be considered rather than waiting for overflow and failure. The threshold can be configurable, but the strategy should be proactive rather than corrective.
- Convert internal history into the message structure required by the current model access method. Put conversion at the boundary and use the kernel’s own internal message model as much as possible.
- Inject temporary prompts by priority: budget nearly exhausted, context pressure, safety constraints, tools forbidden in this turn, and similar conditions. Keep the temporary layer separate from the stable system prompt so it can be invalidated and audited.
- If the model service supports prefix caching or an equivalent mechanism, mark only the stable prefix. Do not mistakenly mark volatile content such as tool results.
- Start an interruptible model call. It must respond to cancellation, timeout, and client disconnects rather than wrapping the call in an unlimited wait.
- Parse the response. If there are tool calls, execute the tools, write the results back to history, and return to step 5. If there are no tool calls, finalize the answer, persist it, and end the turn.
The essence of this loop is that the model proposes the next action, while the runtime validates, executes, and accounts for it. Do not let the model directly rewrite in-process state.
4. Tool Registration and Dispatch
Tools are the key to moving an agent from chat to execution. A registry should store:
- A stable name
- A structured description of parameters
- An execution function
- A timeout
- Whether concurrent execution is allowed
- Required permissions
- Whether the tool is visible to users
Once a name is published externally, do not change it during refactoring; otherwise, historical conversations cannot be replayed.
Dispatch should do four things:
- Validate arguments against the parameter schema. Reject missing fields, incorrect types, and out-of-range values. Do not pass invalid arguments downstream unchanged.
- Use the declaration to decide between serial execution or limited concurrency. Write operations with side effects should be serial by default. Only read-only queries should be considered for concurrency, and a concurrency limit must be set.
- Normalize errors. Timeouts, insufficient permissions, and downstream failures should all become structured results that can be placed back into the conversation, giving the model a chance to revise its plan instead of crashing the loop with an uncaught exception.
- Record the tool name, elapsed time, success status, and associated task ID for later troubleshooting. Avoid writing secrets or complete private content to logs.
A thin registration and dispatch layer can look like this:
def register(name, schema, handler, *, timeout_s, concurrent=False):registry[name] = ToolSpec(name, schema, handler, timeout_s, concurrent)def dispatch(call, ctx):spec = registry[call.name]spec.schema.validate(call.arguments)return run_with_timeout(spec.handler, call.arguments, ctx, spec.timeout_s)
The kernel depends only on dispatch, not on concrete business functions. Adding a tool is a registration step, not a modification to the loop.
5. Abstracting Model Access
Different model services use different message formats, tool-call fields, streaming events, and error codes. If the loop is full of conditional branches, every new service provider requires changes to the core path. A better approach is to define a small number of modes:
- Non-streaming completion
- Streaming completion
- Tool-enabled invocation
- Text-only fallback invocation
Each mode is implemented by an adapter, and the kernel consumes only unified events: text delta, tool call, completion, retryable error, and non-retryable error.
When selecting a provider, consider whether the current conversation requires tools, the context window length, the latency budget, and the fallback order if the primary path fails. Fallback should be an explicit policy. For example, after a primary model timeout, use a less capable path that does not rely on tools, and state in the response that capability is limited. Do not silently switch to an incompatible message format. Retry only retryable errors, and set limits on retry count and backoff to avoid exhausting the user’s budget on repeated failures.
6. Context Compression and Persistence
Long conversations have two kinds of memory, and they should not be merged into one. Short-term memory consists of messages in the current window. Long-term memory consists of facts, decisions, and unfinished items that must be retained after compression.
Pre-compression can drop or summarize content by priority. Prefer keeping system constraints, the most recent turns, unfinished tool results, and decisions explicitly confirmed by the user. Earlier small talk and completed steps can be summarized into short text. Summarization is itself a model call, so it must count against the budget. If summarization fails, fall back to truncation; compression must not block the main flow.
Persistence should happen before points where context may be lost: after each user message is stored, after each tool result is written back, and after compression completes. A snapshot should include at least the task ID, message version, compressed summary, and iteration count. When recovering, continue the loop from the snapshot rather than relying only on the last displayed text in the channel.
Large tool outputs should not be inserted into messages in full. Store them in object storage and keep only a reference and summary in the message. This makes both context-window usage and storage costs more controllable.
7. Subtask Delegation, Scheduling, and Multiple Entry Points
Complex tasks do not need to be deepened indefinitely inside the same loop. Subtask delegation is a separate controlled execution with:
- An independent budget
- A narrowed toolset
- Clear input and expected output
The parent task receives only the structured result, not all of the subtask’s raw context. This avoids window bloat and permission expansion. Delegation must have a depth limit to prevent recursive calls.
Scheduled and asynchronous triggers should also go through the kernel instead of using private loops inside channel processes. When the scheduler reaches the due time, it delivers an internal message with the task ID and trigger reason, and the same lifecycle handles it. This keeps cancellation, auditing, and compression strategies consistent.
Multiple entry points should perform protocol conversion only. A command-line interface cares about standard input and output. An instant messaging channel cares about conversation threads and rich text. An editor cares about selections and file references. All of them call the same run entry point.
In tests, use fake models and fake tools to assert behavior: given a history and tool results, does the loop stop within budget, does it write a snapshot, and does it reject unauthorized tools?
8. Budgets, Retries, and Observability
An iteration budget includes model call count, tool call count, wall-clock time, and approximate token count. When approaching the limit, inject a temporary prompt requiring the model to converge on a final answer. When the limit is reached, stop tool execution and return current progress and unfinished items. A loop without a budget will run out of control when tools are called back and forth.
Observability should be organized around the task ID. Record the per-turn latency of each stage, whether compression occurred, which access mode was selected, whether tool calls succeeded, and whether fallback was used. Metrics are for alerting; logs are for replay. Replay depends on a stable message model and stable tool names. This is another reason to avoid changing the internal message model and registry along with channel-specific requirements.
9. Boundaries to Preserve During Implementation
- Implement the core loop in one place. Channels, models, and storage enter through ports.
- Validate tools before execution. Write operations are serial by default. All errors are structured.
- Compress context early. Write snapshots immediately after key steps.
- Reuse the same lifecycle for subtasks and scheduled tasks, but give them smaller permissions and budgets.
- Make every threshold—compression watermark, retry count, concurrency level, and delegation depth—configuration and cover it in tests rather than hiding it in prompts.
With this structure, an agent is no longer a one-shot chat completion. It becomes a testable, recoverable, and extensible execution chain. Prompts still matter, but whether the system can run reliably over time depends on whether the loop, registry, access abstraction, and context governance are properly separated and replaceable.
