Building a Code Agent from Scratch in Python: Architecture and Practice
This article explains how code agents work and how to build one from scratch in Python. It covers the perception, planning, action, and feedback loop, the main modules of a code agent, a minimal tool-calling loop with approval checks and sandboxed execution, context management strategies, and considerations for production deployment.
1. Why Build Your Own Code Agent
Intelligent coding tools have become an indispensable part of developers’ daily work. However, most developers are only users, and they know little about the internal architecture and runtime mechanisms of these tools. Mature products are either closed source or have core implementations that are not based on Python. This makes it hard for many AI developers who mainly work in Python to understand the underlying principles from source code.
Building a code agent yourself has several benefits. First, you can understand how a large language model (LLM) interacts with tools, the file system, and the terminal environment. Second, you can customize prompt strategies, toolsets, and approval workflows as needed. Third, this knowledge transfers directly to scenarios such as internal R&D efficiency platforms, automated operations, and intelligent testing. When deploying in the cloud, you can also combine object storage, message queues, container platforms, and logging services from general-purpose cloud products to build a more robust production-grade system.
2. How a Code Agent Works
Although products differ, most mainstream code agents follow a perception, planning, action, and feedback loop:
- Perception: Collect context, including the user’s request, the current codebase structure, file contents, and terminal output.
- Planning: The LLM analyzes the task and breaks it down into a sequence of executable steps.
- Action: Carry out concrete operations through tool calling, such as reading and writing files, running commands, and searching code.
- Feedback: Return the execution results to the model, which decides the next action. The loop continues until the task is complete or a termination condition is triggered.
This loop is essentially a state machine driven by an LLM. The core work for developers is to provide the model with structured tool interfaces, reliable context management, and clear logic for deciding when the task is finished.
3. System Design and Module Breakdown
A complete reference implementation of a code agent can typically be divided into the following modules:
- Session manager: Maintains multi-turn conversation history. It trims and compresses the context window to keep the input within the model’s context length.
- Task planner: Breaks natural-language requests into subtasks and tracks the status of each subtask.
- Tool registry: Declares each tool’s name, description, and parameter schema, so the model can call tools as needed.
- Tool executor: Runs file operations, command execution, and other actions in a secure sandbox, and captures standard output and error messages.
- Approval and permission layer: Requires human confirmation for high-risk operations, such as deleting files or running scripts, or blocks them according to policy.
- Memory module: Stores project-level conventions, user preferences, and past decisions to keep long-running tasks coherent.
4. Key Code Implementation Examples
The following is a simplified sketch of the main tool-calling loop:
def agent_loop(user_task: str, tools: dict, max_steps: int = 30):messages = [{"role": "user", "content": user_task}]for _ in range(max_steps):response = llm.chat(messages, tools=tool_schemas(tools))if response.has_tool_calls:for call in response.tool_calls:if is_dangerous(call) and not human_approve(call):result = "Operation rejected by the user"else:result = tools[call.name](**call.arguments)messages.append(tool_result(call.id, result))else:return response.text # The model has given a final answer; the task endsreturn "Maximum number of steps reached; task aborted"
Example tool definitions:
TOOLS = {"read_file": lambda path: open(path, encoding="utf-8").read(),"run_shell": lambda cmd: run_in_sandbox(cmd, timeout=60),}
Command execution must run in a restricted environment, such as a container or an isolated sandbox process. Network access, file system scope, and resource quotas should all be limited. This prevents dangerous instructions generated by the model from damaging the host environment.
5. Context Management: The Key to Agent Success
In long-running tasks, the context window is the scarcest resource. Common strategies include:
- Layered compression: Summarize earlier tool outputs and keep only their conclusions.
- On-demand loading: Instead of loading the entire codebase at once, let the model fetch relevant file snippets through retrieval tools.
- Structured memory: Write the project structure and key conventions to persistent memory files, and inject them into the system prompt at the start of each session.
These strategies directly determine how stable an agent is when it handles large engineering projects.
6. Engineering and Production Deployment Recommendations
When moving from a prototype to production, you also need to consider the following. Logging services can record complete model requests and tool call chains, which makes issues easier to trace. Monitoring and alerting can track core metrics such as task success rate, average number of steps, and token consumption. Container platforms provide multi-tenant isolation and elastic scaling. For asynchronous long-running tasks, message queues can decouple requests from execution and avoid blocking long-lived connections. For example, deploying the agent service on Baidu AI Cloud’s container platform, together with its general-purpose logging and monitoring capabilities, can help you quickly build a stable service.
7. Conclusion
Building a code agent from scratch is not out of reach. By focusing on four core themes, namely the loop-driven design, tool abstraction, context management, and security control, Python developers can build a working prototype with a few hundred lines of core code. They can then gradually add advanced capabilities such as memory, sub-agent collaboration, and approval workflows. Once you understand the underlying principles, you can move from simply using an intelligent coding tool to understanding how it works. You will also be equipped to build the next generation of AI development tools yourself.
