Building a Code Agent from Scratch in Python: Architecture and Implementation

    This article explains how to design and implement a code agent from scratch in Python, covering its core architecture, tool system, agent loop, context management, and security controls. It also discusses engineering practices for moving from a minimal prototype to a usable assistant, including planning, test-driven self-verification, cloud infrastructure integration, and evaluation. Readers will gain a practical understanding of how code agents work and how to build a customized coding assistant for their own scenarios.

    Building a Code Agent from Scratch in Python: Architecture and Implementation

    AI-assisted programming has become an indispensable part of many developers’ daily work. From code completion to automatic bug fixing, intelligent coding tools have greatly improved development efficiency. However, most users remain at the level of “knowing how to use” these tools. When they try to understand the architecture and operating mechanisms of a code agent more deeply, they often run into obstacles: mainstream implementations are either closed source or not primarily written in Python. This makes it difficult for AI developers who use Python as their main language to learn the underlying principles by reading source code.

    This article explains the design philosophy and implementation path of a code agent from scratch. It aims to help readers understand the common technical architecture behind such systems and build their own intelligent coding assistant.

    1. What Is a Code Agent?

    A code agent is an intelligent system that uses a large language model as its core decision engine and can autonomously complete software engineering tasks. Unlike simple one-question-one-answer code generation, a true code agent has the following characteristics:

    1. Autonomous planning: It can break down vague requirements into a series of executable subtasks.
    2. Tool use: It can read and write files, execute commands, search codebases, and interact with a real development environment.
    3. Feedback loops: It adjusts subsequent behavior based on execution results such as error messages and test output, rather than producing a one-shot output.
    4. Context management: It maintains a coherent understanding of project structure and task progress within a limited context window.

    Although mainstream code agents, such as various command-line coding assistants, have different product forms, their underlying architectures are highly similar. They all follow the classic agent loop of “perception—decision—execution—feedback.”

    2. Overall Architecture Design

    A typical code agent can be divided into five core modules:

    • Interaction layer: Receives user input and renders output. It can be a command-line interface or embedded in an editor.
    • Agent loop: The core scheduler that drives the iterative process of “model reasoning → tool execution → result injection.”
    • Tool system: A set of registered functions such as file reading and writing, command execution, and code search.
    • Context manager: Handles trimming, compression, and injection of key information into session history.
    • System prompt and policy layer: Defines the agent’s behavioral boundaries, coding standards, and security constraints.

    The overall workflow can be summarized as follows: the user proposes a task → the agent loop submits the task and context to the large model → the model decides whether to output text or call a tool → the tool executes and appends the result to the conversation history → the model continues reasoning based on the new information until the task is complete or a termination condition is reached.

    3. Core Module Implementation

    3.1 Registered Design of the Tool System

    Tools are the bridge between the agent and the external world. A unified tool description protocol is recommended: each tool includes a name, a functional description, a parameter schema, and an execution function. This allows the model to select tools and parameters based on structured descriptions.

    1. from dataclasses import dataclass
    2. from typing import Callable, Any
    3. @dataclass
    4. class Tool:
    5. name: str
    6. description: str
    7. parameters: dict # JSON Schema description
    8. handler: Callable[..., Any]
    9. class ToolRegistry:
    10. def __init__(self):
    11. self._tools: dict[str, Tool] = {}
    12. def register(self, tool: Tool):
    13. self._tools[tool.name] = tool
    14. def dispatch(self, name: str, args: dict) -> str:
    15. tool = self._tools.get(name)
    16. if tool is None:
    17. return f"Error: unknown tool '{name}'"
    18. try:
    19. return str(tool.handler(**args))
    20. except Exception as e:
    21. return f"Error: {e}" # Errors are also fed back to the model

    A minimal usable toolset usually includes read_file, write_file, run_command, and search_code. These four types of tools are enough to support the closed loop of most programming tasks.

    3.2 Main Agent Loop

    The main loop is the heart of the entire system. Its core logic is to repeatedly call the model and parse the returned result. If the result is plain text, it is presented to the user. If it is a tool call request, the tool is executed and the result is inserted back into the conversation until the model provides a final answer.

    1. def agent_loop(user_task: str, max_turns: int = 30):
    2. messages = build_initial_messages(user_task)
    3. for _ in range(max_turns):
    4. response = call_llm(messages, tools=registry.describe())
    5. messages.append(response.message)
    6. if not response.tool_calls:
    7. return response.message # Task complete
    8. for call in response.tool_calls:
    9. result = registry.dispatch(call.name, call.args)
    10. messages.append(make_tool_result(call.id, result))
    11. return "Reached max turns."

    Two engineering details deserve attention. First, a maximum number of turns or a cost limit must be set to prevent the agent from falling into an infinite loop. Second, tool execution failures should not interrupt the loop. Instead, the error information should be fed back to the model as an observation so that it can correct itself. This is exactly what distinguishes an agent from a traditional pipeline program.

    3.3 Context Management Strategies

    The context window is a scarce resource. The codebase of a medium-sized project far exceeds the model’s context capacity, so careful context engineering is required:

    • Lazy loading: Do not preload the entire codebase. Let the model read files on demand through tools.
    • Summarization and compression: When the conversation history becomes too long, compress earlier turns into summaries while retaining key decisions and conclusions.
    • Structured system prompt: Inject a project overview into the system prompt, including the directory tree, technology stack, and coding standards, to provide the model with global anchors.
    • Result truncation: Truncate extremely long tool outputs such as large files and long logs, and prompt the model to read them in segments.

    3.4 Security and Permission Control

    A code agent can execute commands and modify files, which introduces real security risks. Production-grade implementations must consider the following:

    1. Confirmation for dangerous operations: Require explicit user approval before deleting files or executing commands with side effects.
    2. Sandbox isolation: Run the agent in a containerized environment and restrict its file system and network access.
    3. Permission allowlists: Set allowlists for paths accessible to tools and types of commands that can be executed.
    4. Operation auditing: Record every tool call made by the agent for traceability and accountability.

    4. Engineering Practices from Prototype to Usable System

    After building a minimal prototype, moving toward a truly usable system requires attention to the following engineering issues.

    Task decomposition and planning: For complex requirements, the model can first output a step-by-step plan. After user confirmation, the agent executes the plan step by step and updates the plan status after each step. This “plan—execute—update” pattern is significantly better than letting the model act blindly and continuously.

    Test-driven self-verification: Encourage the agent to proactively run the test suite after modifying code and use test failure information as the basis for the next round of fixes. This gives the agent a habit similar to that of human developers: verify immediately after making changes.

    Integration with cloud infrastructure: When larger-scale concurrent execution or persistent storage is needed, general-purpose cloud services can be used. For example, object storage can save session snapshots and artifact files, container platforms can isolate different tasks, and logging and monitoring services can track the agent’s operating status. Mainstream cloud platforms such as Baidu AI Cloud provide these foundational capabilities, allowing developers to combine them as needed rather than building underlying infrastructure themselves.

    Evaluation and iteration: Build an automated evaluation set with tasks such as “fix a specified bug” and “implement a specified feature.” Quantify the agent’s success rate and average number of turns, and use the data to continuously optimize prompts, tool design, and context strategies.

    5. Suggested Learning Path

    For developers who want to master this field, the following path is recommended. First, implement a minimal loop with a single tool to understand the message structure and tool-calling protocol. Then expand the toolset and introduce context compression. After that, address security controls and long-task planning. Finally, explore advanced forms such as multi-agent collaboration, for example, a “coder + reviewer” division of labor. At every step, adhere to the three standards of “it runs, it is observable, and it is evaluable.” The integration of theory and practice will then follow naturally.

    Conclusion

    A code agent is not a mysterious black box. Its essence is an organic combination of a large language model, a tool system, a feedback loop, and context engineering. By building one from scratch in Python, developers can not only see through the underlying logic of mainstream intelligent coding tools but also customize their own intelligent assistants for their business scenarios. In the wave of AI programming, understanding the principles and implementing them hands-on is the key step from being a user to becoming a creator.