Building a Code Agent from Scratch: A Python Architecture Guide
This article explains how to build a code agent from the ground up using Python, focusing on the core architecture, state management, tool protocols, sandboxed execution, and iterative feedback loops. It provides a practical reference implementation and discusses engineering practices for security, observability, and evaluation—ideal for developers who want to understand and build their own task-level AI coding assistants.
Building a Code Agent from Scratch: A Python Architecture Guide
Why Understanding the Inner Workings of a Code Agent Matters
AI-powered coding tools are evolving from “code completion” to “task-level collaboration.” A developer gives a natural-language goal, and the agent understands the requirement, retrieves context, plans steps, generates patches, invokes tools, runs verification, and iterates based on error feedback. On the surface, this looks like a single model call. In reality, it is a system engineering challenge that involves state management, tool protocols, an execution sandbox, context engineering, and security policies.
Many Python developers want to learn how code agents work at the source level, but they often hit two obstacles: some implementations are closed-source and hard to inspect internally, while others are not built on the Python stack, making reading and customization costly. This article is not tied to any specific commercial product or framework. Instead, it starts from general architecture and provides a step-by-step reference approach that can be implemented in Python. It covers requirement analysis, system design, core module development, and engineering practices.
The intended audience includes students, developers, and AI beginners with some programming background—especially those interested in Python, agent systems, and intelligent coding assistants. After reading, you will not only understand the key principles behind code agents but also be able to build your own extensible prototype.
The Core Capability Loop of a Code Agent
A code agent is not a wrapper around a model that “generates code once.” It is a closed-loop system. A minimal viable loop typically includes:
- Requirement understanding: Translate a natural-language goal into an executable task, identifying inputs, outputs, constraints, and acceptance criteria.
- Task planning: Break the complex goal into steps, such as locating files, reading context, generating a patch, running tests, and fixing errors.
- Context construction: Select relevant information from the codebase, documentation, conversation history, and tool results—without context overload.
- Tool invocation: Execute retrieval, file read/write, test runs, static checks, etc., through controlled interfaces.
- Code generation and patch management: Produce structured modification suggestions (e.g., diffs) instead of untracked large text blocks.
- Isolated execution and verification: Run tests or code in a constrained environment, capturing exit codes, logs, and diffs.
- Reflection and iteration: Adjust the plan based on verification results, until stop conditions are met or human takeover is triggered.
- Memory and audit: Record key decisions, tool calls, and modification history for later tasks and troubleshooting.
The key to this loop is not the capability of a single model, but how state flows, how tools are controlled, how errors are fed back, and how stop conditions are defined. Without a loop, an agent can only produce code that looks plausible; with a loop, it exhibits verifiable engineering behavior.
Overall Architecture Design: Layering and Decoupling
It is recommended to divide the system into seven layers to avoid coupling between model calls, tool execution, and business logic:
- Interaction layer: Receives natural-language requests, displays plans, diffs, execution logs, and final results.
- Orchestration layer: Maintains the agent state machine and decides whether the next action is planning, tool invocation, patch generation, or requesting human confirmation.
- Model abstraction layer: Encapsulates generic model call interfaces, making it easy to switch between different models or run offline tests.
- Tool layer: Defines a unified tool protocol, including tool name, parameter schema, permission level, and return structure.
- Execution sandbox layer: Provides an isolated runtime environment, restricting resources, network, and file system access.
- Memory and knowledge layer: Stores session summaries, task state, code retrieval results, and historical decisions.
- Security and observability layer: Handles permission control, audit logs, metrics collection, anomaly alerts, and cost statistics.
The data flow can be summarized as follows: user goals enter the orchestration layer, and the planner generates steps; the context manager assembles information for the current step; the model outputs structured actions; the tool layer executes actions and returns observations; the sandbox verifies code; the orchestration layer decides whether to continue, roll back, or stop based on observations. Each layer should communicate through well-defined data structures rather than passing arbitrary strings.
Core Module Implementation Points
1. Requirement Parsing and Task Decomposition
The goal of requirement parsing is to turn a vague description into testable tasks. For example, “fix login failure” needs further clarification: reproduction conditions, involved modules, expected behavior, and acceptance tests. In practice, the model can output structured task objects containing goals, constraints, open questions, and acceptance criteria. Task decomposition should not be too fine-grained—otherwise, tool call counts and context costs grow quickly—nor too coarse—otherwise, single-step failures are hard to localize. A good granularity is “one verifiable code change.”
2. Context and Code Retrieval
The effectiveness of a code agent largely depends on the quality of context. Start with lightweight retrieval: locate candidate files by file name, symbol name, or error-log keywords, then read relevant snippets. If necessary, supplement with call relationships and test cases. Set a context budget and prioritize information directly related to the current step, while summarising earlier conversation turns. Do not stuff the entire codebase into the prompt—this increases cost and introduces noise.
3. Tool Protocol and Invocation
Tools should be uniformly described as “name + parameter schema + permission level + return structure.” For example, read file, apply patch, run tests, and query logs can each be defined separately. The tool layer must perform parameter validation and permission checks: read-only and write tools should be graded differently, and high-risk operations should require human confirmation. The model’s output should be parsed into structured actions, not directly concatenated into shell commands.
4. Code Generation and Patch Management
It is recommended that the model output “patch-style modifications” or “file-level edit plans.” The system then applies the changes and generates diffs. This makes review, rollback, and testing easier. The patch management module should record the before/after content and the application result, avoiding duplicate applications or overwriting user changes. For multi-file changes, dependency order should be checked before applying.
5. Isolated Execution and Verification
Execution is a key differentiator between a code agent and a simple generator. Tests or scripts should run in an isolated environment with limits on runtime, memory, network, and file system access. Verification results should at least include exit code, standard output, error output, and a test summary. If execution fails, the feedback to the orchestration layer should preserve key error snippets rather than the entire log, so the model can localize the issue.
6. Feedback Iteration and Stop Conditions
Iteration must have clear stop conditions: tests pass, maximum round limit reached, no consecutive progress, permission request, or manual termination. Each iteration should compare whether verification results improved, avoiding useless retries. In case of repeated failures, the agent should degrade to “provide diagnostic suggestions and request human confirmation” rather than looping indefinitely.
7. Memory, State, and Audit
The state object should explicitly record the current task, completed steps, pending steps, tool observations, changed files, and error history. The memory layer can use a combination of session summaries and structured state, rather than relying solely on long conversations. Audit logs should record who invoked what tool, when, which files were changed, and what verification was run, providing a basis for troubleshooting and security reviews.
A Minimal Python Reference Implementation
Below is a skeletal reference implementation that focuses on the orchestration layer, tool protocol, and state management. It is intentionally simple and not tied to any commercial framework. In a real project, you would extend it with model calls, retrieval, and sandboxing.
from dataclasses import dataclass, fieldfrom typing import Dict, List, Optional, Protocol@dataclassclass Task:goal: strconstraints: List[str] = field(default_factory=list)acceptance: List[str] = field(default_factory=list)@dataclassclass Observation:tool: strok: boolsummary: strdetail: str = ""@dataclassclass AgentState:task: Taskstep: int = 0max_steps: int = 8observations: List[Observation] = field(default_factory=list)changed_files: List[str] = field(default_factory=list)done: bool = Falseclass Tool(Protocol):name: strrisk_level: strdef run(self, args: Dict[str, str]) -> Observation: ...class Planner:def next_action(self, state: AgentState) -> Dict[str, str]:# Illustrative: choose tool and args based on state.# In practice, this can be driven by a model outputting structured actions.if state.step == 0:return {"tool": "search_code", "query": state.task.goal}if state.step == 1:return {"tool": "apply_patch", "target": "candidate"}return {"tool": "run_tests", "scope": "related"}class Sandbox:def run_tests(self, scope: str) -> Observation:# Illustrative: run tests in a sandbox and return a summary.return Observation(tool="run_tests", ok=True, summary="Related tests passed")class CodeAgent:def __init__(self, tools: Dict[str, Tool], planner: Planner, sandbox: Sandbox):self.tools = toolsself.planner = plannerself.sandbox = sandboxdef run(self, task: Task) -> AgentState:state = AgentState(task=task)while not state.done and state.step < state.max_steps:action = self.planner.next_action(state)tool_name = action["tool"]if tool_name == "run_tests":obs = self.sandbox.run_tests(action.get("scope", "related"))else:tool = self.tools.get(tool_name)if tool is None:obs = Observation(tool=tool_name, ok=False, summary="Unknown tool")else:obs = tool.run(action)state.observations.append(obs)state.step += 1if obs.ok and obs.tool == "run_tests":state.done = Truereturn state
This code is deliberately minimal to illustrate three principles: explicit state, tool protocolization, and separation of execution from orchestration. A real system would require model abstraction, context trimming, permission confirmation, patch diff display, and more granular error classification.
Engineering Practices and Evaluation Methods
First, adhere to the principle of least privilege. Read, write, and execute operations should be graded; write and delete actions should generate diffs and support rollback; high-risk actions must require human confirmation. Second, prioritize observability. Record each planning step, tool arguments, observation summaries, durations, and failure reasons, and integrate with general-purpose logging, monitoring, and dashboards. Third, build test suites and evaluation metrics. Create offline task sets that include typical fixes, refactoring, test completions, and multi-file modifications. Measure effectiveness using pass rate, average iteration count, human takeover rate, and patch rollback rate. Fourth, control costs. Use context budgets, result summaries, cached retrieval outputs, and maximum iteration limits. Fifth, design for human-in-the-loop collaboration. The agent should clearly communicate its plan, risks, and uncertainties, and leave the final merge decision to the developer.
On the deployment side, you can use general object storage to save task artifacts, logging services and monitoring alerts to observe run-time status, and container platforms or isolated execution environments to host the sandbox. Regardless of the infrastructure, always adhere to the principles of “rollbackable, auditable, and restrictable.”
Conclusion
Building a code agent from scratch is not about writing a loop that calls a model—it is about designing a controllable, verifiable, and extensible engineering loop. Python developers can start with a minimal prototype: first implement task state and tool protocols, then add code retrieval, patch management, and sandboxed testing, and finally fill in permissions, auditing, and evaluation. Through continuous iteration, you can gradually build your own intelligent coding assistant and develop a deep understanding of code agent architecture through theory and practice.
