How AI Agents Work: A Python Architecture Deep Dive
A practical look at what turns a chat interface into a task-execution system: layered architecture, a bounded Python control loop, model adapters, tools and authorization, context, persistence, subtasks, scheduling, untrusted external content, and testing. The focus is reliable state transitions and governance, not a chat window with tool buttons.
1. From a Chat Interface to a Task Execution System: What Actually Changes
The simplest conversational program has three steps: accept input, call a model, and return text. That structure works for single-turn Q&A. It is not enough when a user asks the system to look up information, organize the results, generate a file, and send it at a specified time.
The problem is not that the prompt is too short. The task spans multiple execution stages. The system must store intermediate results, decide whether to call a tool again, handle tool failures, and pause, resume, or stop execution when needed.
An engineered agent therefore needs at least three kinds of capability:
- Reasoning and decision-making: the model chooses the next action from the current context.
- Deterministic execution: application code validates parameters, accesses resources, calls tools, and records results.
- Runtime governance: the system controls permissions, budgets, timeouts, concurrency, persistence, and audit.
These capabilities are not interchangeable. The model may intend to call a tool, but that intent does not automatically grant every permission the tool has. The model may believe the task is finished, while the system should still check that the required artifacts exist.
Architecturally, an agent is closer to a task execution system in which a model participates in decisions than to a chat window with tool buttons attached.
2. Layering: A New Entry Point Should Not Force a Core Rewrite
Command-line interfaces, web apps, messaging channels, and development environments are different entry points. The common failure is to copy a full conversation stack for every new channel.
That is faster in the short term. Over time, retry policy, history, and permission checks diverge, so the same task behaves differently depending on where it was submitted.
A more stable approach uses ports and adapters and splits the architecture into these layers:
Interaction entry points and channel adapters↓Unified request and identity context↓Agent execution core├─ Model invocation adapter├─ Tool registry and execution├─ Session and memory management└─ Task state and scheduling↓Databases, file storage, and external business systems
2.1 The entry layer only converts protocols
Channels differ in message format, identity, and how responses are delivered. An entry adapter should turn those differences into one internal structure: request ID, session ID, user input, and attachment references.
The entry layer may handle message-length limits, reconnects, and segmented output. It should not decide tool-call order or context-compression strategy.
2.2 The core depends on abstract capabilities
The execution core only needs to know how to request a model, how to run a tool, and how to save state. It does not need the request fields of a particular external API.
That makes external dependencies replaceable in tests and lets the underlying implementation change without rewriting task orchestration.
2.3 A shared message format is not shared authority
Message structure can be standardized. Permissions cannot be flattened. Requests from different entry points still need trusted identity, tenant scope, and authorization.
Those facts must come from the authentication system. They must not be changed by user input or model output. Otherwise a “unified entry point” becomes a path around authorization.
3. The Core Loop: Every Model Response Is a State Transition
Agent execution is usually a loop under a finite budget:
- Accept the user task and create an execution record.
- Load the necessary history and task state.
- Build the model input.
- Ask the model for an answer or tool calls.
- Validate and run the tools.
- Write tool results into state.
- Decide whether to continue, pause, or finish.
The simplified Python below shows the control structure. Methods and data structures illustrate the design; they do not match a specific product API.
class AgentRunner:def __init__(self, model, tools, store):self.model = modelself.tools = toolsself.store = storeasync def run(self, task, limits):state = await self.store.load_or_create(task)for _ in range(limits.max_steps):if state.cancel_requested:await self.store.mark_cancelled(state)return Nonemessages = build_context(state, limits)reply = await self.model.generate(messages=messages,tool_specs=self.tools.visible_specs(task.identity),)await self.store.append_reply(state, reply)if not reply.tool_calls:await self.store.mark_completed(state)return reply.textfor call in reply.tool_calls:result = await self.tools.execute_checked(call=call,identity=task.identity,task_id=state.task_id,)await self.store.append_tool_result(state, call.call_id, result)await self.store.mark_paused(state, reason="step_limit")return "The task reached the step limit and needs further confirmation."
A production system also needs timeouts, retries, context cleanup, and recovery of side effects. The skeleton still makes one point clear: model output is not the final ruling on the workflow. The runner controls state transitions.
3.1 Separate session, task, and execution attempt
A session is the long-lived interaction scope. A task is one piece of work with a defined goal. An execution attempt is one actual run of that task.
One session can contain many tasks. One task can have several attempts after failures. Recording them separately is what makes retries, recovery, and cost understandable.
3.2 Give tasks explicit states
Typical states include pending, running, waiting for confirmation, paused, completed, failed, and cancelled.
A task that sends a message externally can enter “waiting for confirmation” instead of blocking an execution thread. After the user approves it, the scheduler wakes the task again.
3.3 A budget is more than a step count
A maximum step count only stops some infinite loops. A full budget should also cover total elapsed time, model input and output size, tool-call count, and external resource use.
When a budget is exhausted, save recoverable state and say what is still unfinished. Do not present a forced stop as success.
4. The Model Adapter: Isolate Format Differences from Call Semantics
Model APIs differ in message format, tool descriptions, streaming events, and error shapes. If those details leak into the execution core, core logic grows quickly.
The adapter should expose stable internal semantics, for example:
- a plain text response;
- tool calls with correlation IDs;
- streaming text fragments;
- retryable and non-retryable errors;
- usage and latency.
Unification must not hide capability differences. If an API does not support a particular tool-calling style, report that limit explicitly. Do not quietly change what the task means.
Switching models also needs care. Before the switch, check whether history is compatible, whether tool calls have finished, and whether the new model can do what the current task requires. Do not change the input format while unpaired tool results are still outstanding.
5. The Tool System: Registration, Execution, and Authorization Stay Separate
The value of tools is not that the model “sees more functions.” It is that uncertain intent becomes a constrained operation.
5.1 Descriptions exist to support decisions
A tool registration usually includes a name, purpose, parameter schema, and a description of the result. The description should state input boundaries and side effects.
Reading a record and deleting a record should be different tools, not one vague “manage data” tool. Clearer boundaries make permissions and audit easier to enforce.
5.2 Do not trust the model to validate parameters
Even when parameters look right, check field types, lengths, enum values, and resource scope before execution.
File operations should verify path boundaries. Network access should restrict targets. Database access should restrict query rights and result size. Parameters produced by the model are always untrusted input.
5.3 Tool visibility is not an authorization mechanism
Hiding sensitive tools reduces accidental calls. Real authorization still happens at execution time.
The system should re-check permission from the current identity, resource ownership, and operation type. A call that originates inside the executor does not skip that check.
5.4 Concurrency depends on dependencies and side effects
Independent read-only queries can usually run concurrently. “Create an object, then update it” must follow dependency order.
Concurrency limits should also cap resource use per task and per tenant so one complex task cannot occupy every execution slot. Writes should prefer conflict detection, transaction boundaries, and compensation.
6. Context Management: Keep Task Facts, Do Not Truncate Mechanically
Model context is finite, while task history can keep growing. Deleting the oldest messages can drop user constraints, authorization conditions, or critical tool results.
A more useful context has four layers:
- Stable rules: role boundaries, safety requirements, and execution constraints.
- Current task state: goal, progress, open items, and blockers.
- Recent interaction: the latest dialogue and tool results.
- Historical summaries and retrieved material: compressed earlier facts, plus content loaded on demand.
6.1 Derive compression thresholds from the budget
A fixed percentage is not a universal best practice. Reserve space from model capacity, expected output length, and the size of later tool results.
Long-document work needs a larger buffer for tool results. Short Q&A may not. Thresholds should change with task type and actual input length.
6.2 A summary does not replace complete evidence
Summaries are suitable for goals, conclusions, constraints, and unfinished steps, but they can omit detail. Raw tool output and operation records should remain in persistent storage and be read by reference when needed.
Records of safety constraints, user approval, and sensitive operations should not survive only as an untraceable natural-language summary.
6.3 Separate session memory from long-term memory
Session memory keeps the current task continuous. Long-term memory may hold preferences or facts that remain valid over time.
A long-term write needs a clear purpose, necessity, and authorization. A model inference is not automatically a user fact, and sensitive information should not be kept indefinitely.
7. Persistence and Failure Recovery: External Side Effects Are the Hard Part
Saving chat history is not task recovery.
Suppose the system has already submitted an external order, then crashes before recording the result. Replaying the tool call on recovery can create a duplicate order.
Operations with side effects need their own recovery design:
- record the intended operation and a correlation ID before execution;
- use an idempotency key when the external system supports it, so the same submission is not applied twice;
- distinguish definite success, definite failure, and unknown outcome;
- for an unknown outcome, query status before deciding to retry;
- add human confirmation and an audit record for irreversible operations.
A local database transaction usually cannot make a remote operation atomic at the same time. In practice you need state reconciliation, compensating actions, and human intervention, not the assumption that one retry fixes everything.
8. Subtasks and Scheduled Runs: More Capability, More Governance
8.1 Use subtasks to isolate well-defined work
Split work when the parent task must research several independent topics at once, or when contexts must stay isolated.
Each subtask needs explicit input, expected output, permission scope, and budget. The parent merges results and handles conflicts or missing items.
More subtasks are not automatically better. Excessive splitting duplicates context, raises aggregation cost, and adds coordination delay, sometimes making the whole run slower.
8.2 Subtasks must not widen permissions
A resource the parent cannot access is also off limits to the child. Permissions may be narrowed further. Delegation must not expand them.
Record the parent-child relationship so that cancelling the parent can, by policy, stop unfinished children.
8.3 The scheduler only triggers and claims work
A scheduler should compute trigger time, create the task, and prevent duplicate runs. Business execution still goes through the same runner.
The schedule must define time zone, behavior after a missed fire time, failure retries, and concurrency limits. With multiple instances, use a claim or lease, and account for the risk that an old worker is still running after its lease expires.
9. External Content and Tool Protocols: A Shared Format Is Not Trust
A common tool protocol can discover tools, read parameter schemas, and call remote services so more external capabilities can be attached.
The protocol standardizes interaction format. It does not make the remote tool trustworthy. Remote tools still need authentication, permission limits, timeouts, and result checks.
Web pages, documents, and tool results may contain text that tries to change system behavior. Treat that text as data, not as new system instructions.
Practical controls include:
- keep instructions and external material in separate regions;
- do not let external content change permissions or the execution budget;
- run an independent policy check on sensitive operations;
- limit credential injection so credentials do not enter the model context;
- redact sensitive fields in logs and tool results.
A prompt that says “ignore malicious content” is not a security boundary. The binding limits have to be enforced in code.
10. Testing and Observability: Every Failure Should Be Explainable
Agent output varies, so tests should not only check whether the final text matches exactly.
Better tests assert behavioral constraints: whether only allowed tools were called, whether the budget was respected, whether recoverable state was saved, and whether sensitive operations waited for confirmation.
A useful test stack has four layers:
- Unit tests: parameter validation, state transitions, and context-budget calculation.
- Protocol contract tests: internal formats of model and tool adapters.
- Flow tests: scripted responses that simulate multi-step tool calls, failures, and cancellation.
- Fault-injection tests: timeouts, disconnects, duplicate triggers, and process crashes.
Observability should cover the task, model calls, and tool execution. At minimum, record correlation IDs, state changes, call latency, retry counts, and budget consumption.
Also separate infrastructure errors, permission denials, parameter errors, and tasks that cannot be completed. A generic “execution failed” neither helps the user decide what to do nor helps a developer find the fault.
11. Implementation Order: A Reliable Loop Before Complex Autonomy
Teams building an agent system for the first time can proceed in this order:
First, one entry point, a limited tool set, and an execution loop with a hard cap, so a task can clearly succeed, fail, or pause.
Second, structured state, permission checks, context management, and trace logs, so a run is explainable and recoverable.
Third, concurrent tools, subtasks, multiple entry points, and scheduled execution, with fault tests that verify the system boundaries.
Throughout, do not let the core runner become an ever-growing god class. Orchestration can stay centralized, but model protocol conversion, tool authorization, persistence, and scheduling should have clear interfaces and their own tests.
Maturity is not how many tools you can connect, or how many steps a demo runs. It is three questions: why this operation ran, how failure is recovered, and who is allowed to approve it. When those questions are answered in code and in the state model, model capability becomes a reliable engineering system.
