Building a Python Code Agent in Practice: A Step-by-Step Guide to the Core Loop
This article walks through building a runnable code agent from scratch in Python, using only the standard library. It explains the overall "perceive-decide-act" architecture and covers each core module: the model interaction layer, a tool registry for reading files, writing files, and running commands, the reasoning loop that drives tool calls, context and memory management, and security boundaries such as path constraints and sandboxed execution. It also provides a runnable entry point with a sample call_model wiring, common pitfalls to avoid, and a final checklist. Readers only need to connect their preferred conversational model API in call_model to get the agent running.
1. Why Developers Should Understand Code Agents
AI coding tools built on large language models have become daily assistants for many developers, handling code completion, bug fixing, refactoring, and multi-file changes. However, most people treat them as just a “smarter autocomplete box” and have little understanding of how they work under the hood. To truly master these systems, or even build a usable Code Agent yourself, you need to understand how they combine “model capability” with “engineering capability.”
For developers working primarily in Python, further learning often hits a wall: mainstream code agents are either closed source or implemented in non-Python stacks, making it hard to learn directly from their source code. This article therefore strips away product-specific details and demonstrates, from a general engineering perspective, how to build a code agent in Python end to end—covering requirements analysis, core module development, and a runnable entry point. All the code snippets here can be assembled into a working script; you only need to plug your chosen conversational model interface into call_model.
2. Overall Architecture of a Code Agent
A code agent is not a single model but a system made up of several collaborating modules. At its core, it is a “perceive-decide-act” loop: the model handles understanding and reasoning, tools handle interaction with the real world (the file system, terminal, codebase), and the two repeat through a structured protocol until the task is done.
| Layer | Responsibility | Section |
|---|---|---|
| Model interaction layer | Organize context and user intent, parse model output | Section 4 |
| Tool invocation layer | Define atomic operations like reading files, writing files, running commands | Section 5 |
| Reasoning execution loop | Drive “think—call tool—observe result—think again” | Section 6 |
| Context and memory management | Maintain key task information within a limited window | Section 7 |
| Security and permission boundaries | Confirm and constrain high-risk operations | Section 8 |
| Runtime entry point | Inject a real call_model and start agent_loop | Section 9 |
3. Requirements Analysis and Design Goals
Before writing code, you need to define the agent’s capability boundaries, which determine the complexity of the architecture. A minimal usable code agent should support:
- Understanding a task described in natural language and breaking it into executable steps;
- Reading and modifying files in the project;
- Executing controlled terminal commands (such as running tests or listing directories);
- Maintaining context consistency across multiple turns without forgetting earlier decisions;
- Prompting for or blocking destructive operations.
As for design principles, follow three main lines: “atomic tools, observable loop, least privilege.” Tools should have a single responsibility, making them easy for the model to understand and combine; every step of the loop should be recordable and debuggable; and permission control should follow least privilege—read-only by default, with writes and command execution explicitly enabled.
The dependencies and runtime environment are simple: you only need Python 3.9 or later, with no third-party libraries (the examples below use only standard library modules such as dataclasses, typing, and subprocess). Put the code from each section into a single code_agent.py file in order, and it will run.
4. Core Module One: How to Build the Model Interaction Layer?
The key to the model interaction layer is packaging “conversation history + current request” into a unified structure and defining a stable calling interface. Here an abstract function call_model represents the capability of “given a list of messages, return a model response.” In a real project, you can replace it with any compatible conversational interface; Section 9 gives a runnable wiring example.
Note: The response object must carry a tool_calls field; otherwise the reasoning loop in Section 6 will never read any tool call requests and will exit early at step 0—this is the most common pitfall beginners hit when building their own agent.
from dataclasses import dataclass, fieldfrom typing import List, Dict, Any, Optional@dataclassclass ToolCall:name: strarguments: Dict[str, Any]@dataclassclass Message:role: str # "system" / "user" / "assistant" / "tool"content: Any # a string or a structured tool calltool_calls: Optional[List[ToolCall]] = None@dataclassclass Conversation:messages: List[Message] = field(default_factory=list)def add(self, role: str, content: Any,tool_calls: Optional[List[ToolCall]] = None) -> None:self.messages.append(Message(role=role, content=content,tool_calls=tool_calls))# Abstract interface: the concrete implementation can connect to any conversational modeldef call_model(conversation: Conversation, tools: List[Dict]) -> Message:# In a real scenario this would make a network request and return a structured responseraise NotImplementedError
The system prompt is the agent’s “behavioral constitution.” It needs to clearly describe the agent’s role, available tools, constraints, and output format conventions. The tool list is passed to the model as structured descriptions (name, purpose, parameter schema) so it knows when to call which tool.
5. Core Module Two: How Are Tools Registered and Called by the Model?
Tools are the agent’s hands and feet for interacting with the real world. A good approach is a “registry + unified dispatch” pattern: each tool is described with unified metadata and implemented as a function, then looked up by name and executed at runtime.
from typing import Callable, Dict, Any, Listclass ToolRegistry:def __init__(self):self._tools: Dict[str, Callable] = {}self._schemas: Dict[str, Dict[str, Any]] = {}def register(self, name: str, description: str,func: Callable, schema: Dict[str, Any]) -> None:self._tools[name] = funcself._schemas[name] = {"name": name,"description": description,"parameters": schema}def schemas(self) -> List[Dict]:return list(self._schemas.values())def call(self, name: str, **kwargs) -> Any:if name not in self._tools:raise KeyError(f"Unregistered tool: {name}")return self._tools[name](**kwargs)
With this, you can register several basic tools. To make the “path constraint” promised in Section 8 real, first use os.path.realpath to confine file operations to a specified root directory:
import osimport subprocessregistry = ToolRegistry()PROJECT_ROOT = os.path.realpath("./workspace")def _safe_path(path: str) -> str:real = os.path.realpath(path)if not real.startswith(PROJECT_ROOT + os.sep) and real != PROJECT_ROOT:raise PermissionError(f"Unauthorized access: {path} is outside the project root")return realdef read_file(path: str) -> str:with open(_safe_path(path), "r", encoding="utf-8") as f:return f.read()def write_file(path: str, content: str) -> str:target = _safe_path(path)os.makedirs(os.path.dirname(target), exist_ok=True)with open(target, "w", encoding="utf-8") as f:f.write(content)return f"Wrote {len(content)} characters to {path}"def run_command(cmd: str, timeout: int = 30) -> str:# Security warning: shell=True with a cmd generated by the model carries# command injection and data loss risks (e.g., accidentally deleting files).# Production must run this in a sandbox and only enable it with an# allowlist/manual confirmation, see Section 8.result = subprocess.run(cmd, shell=True, capture_output=True,text=True, timeout=timeout)return result.stdout + result.stderrregistry.register("read_file", "Read the text file at the given path",read_file, {"type": "object","properties": {"path": {"type": "string"}},"required": ["path"]})registry.register("write_file", "Write content to the given file",write_file, {"type": "object","properties": {"path": {"type": "string"},"content": {"type": "string"}},"required": ["path", "content"]})registry.register("run_command", "Execute a terminal command in a controlled environment",run_command, {"type": "object","properties": {"cmd": {"type": "string"}},"required": ["cmd"]})
6. Core Module Three: The Reasoning Execution Loop
The loop is the heart of the agent. It repeatedly performs “let the model decide—execute the tool—feed the result back to the model” until the model considers the task complete or the maximum number of steps is reached.
def agent_loop(task: str, registry: ToolRegistry, max_steps: int = 15):convo = Conversation()convo.add("system", SYSTEM_PROMPT)convo.add("user", task)for step in range(max_steps):response = call_model(convo, registry.schemas())convo.add("assistant", response.content)# If the model no longer requests a tool call, treat the task as finishedtool_calls = response.tool_callsif not tool_calls:return response.content# Execute each tool the model requested, one by onefor call in tool_calls:try:output = registry.call(call.name, **call.arguments)except Exception as e:output = f"Tool execution failed: {e}"convo.add("tool", {"name": call.name, "result": output})return "Reached the maximum number of reasoning steps; the task may be incomplete."
The key to this loop is that the model does not need to see the entire codebase at once. Instead, it completes the task incrementally through “read on demand, modify step by step, run to verify”—which closely resembles how a human programmer works. The step limit and timeouts are necessary guardrails to prevent infinite loops and control cost.
7. Core Module Four: How Is Context Managed?
The context window is a scarce resource. As tool calls increase, the conversation history expands rapidly, exceeding the window limit or driving up costs. So you need a context management strategy:
- Layered retention: always keep the system prompt, the current task description, and the key interactions from the most recent turns;
- Truncation and compression: for earlier, larger tool outputs, apply head-and-tail truncation that keeps only the key information at the beginning and end;
- Structured memory: store key completed decisions (such as “which files have been modified”) separately to avoid duplicated work.
def compress_history(convo: Conversation, keep_recent: int = 6,max_content_len: int = 2000) -> None:# Truncate overly long content at head and tail; system messages are always# kept and do not participate in compressionfor msg in convo.messages:if msg.role == "system":continueif isinstance(msg.content, str) and len(msg.content) > max_content_len:half = max_content_len // 2msg.content = (msg.content[:half] +"\n...[content too long, truncated]...\n" +msg.content[-half:])
Note that what is implemented here is “truncation and compression” rather than semantic summarization—true summarization requires an extra model call to distill conclusions, which costs more and can be swapped in as needed. In engineering practice, you can also maintain “task state” (files involved, pending steps, verified results) as a separate data structure and inject it into the system prompt each round, keeping the task coherent while compressing the conversation.
8. Core Module Five: Security and Permission Boundaries
A code agent can directly read and write files and execute commands. This is both the source of its capability and the source of risk. Security mechanisms must be built in from the start:
- Confirmation for dangerous operations: require explicit confirmation or allowlist constraints for deletion, overwriting, and executing arbitrary commands;
- Path constraints: confine file operations to within the project root to prevent unauthorized access (already implemented with
_safe_pathin Section 5); - Sandboxed execution: run command execution in an isolated environment as much as possible, with timeouts and resource limits;
- Full auditability: log every tool call and its result to make it easy to trace problems.
def is_safe_command(cmd: str, allowlist: List[str]) -> bool:forbidden = ["rm -rf", "shutdown", "mkfs", ":>"]if any(bad in cmd for bad in forbidden):return False# You can also require the command to start with a prefix from the allowlistreturn any(cmd.strip().startswith(prefix) for prefix in allowlist)
Important reminder: This is_safe_command is only illustrative and is not sufficient for production. Blacklists/allowlists based on substring matching and prefix checks are easy to bypass—for example, an attacker can chain commands with a semicolon (ls; rm -rf /), or use wildcards or variable concatenation to evade filtering. The safe approach is to execute in an isolated container/sandbox, run under a least-privilege account, require manual confirmation for write and delete operations, and treat this function only as one layer of defense-in-depth rather than the sole line of defense.
9. How to Run It: A Runnable Entry Point and call_model Wiring
To actually run the code from the previous sections, you still need a main() entry point and a real call_model implementation. Below is a minimal runnable example that uses a “fake model” to show how to inject a real interface and call agent_loop:
SYSTEM_PROMPT = "You are a coding assistant that can call tools to read and write files and execute commands."def call_model(conversation: Conversation, tools: List[Dict]) -> Message:# Fake implementation: in a real project, replace this with any conversational# model API—send conversation.messages and tools in that API's format, then# fill the returned text and tool_calls into a Message and return it.history = [m for m in conversation.messagesif m.role in ("user", "assistant")]last = history[-1].content if history else ""if "hello" in str(last).lower():return Message(role="assistant", content="Hello, I am a coding assistant!")return Message(role="assistant", content="Task complete.")if __name__ == "__main__":# Make sure the working directory existsos.makedirs(PROJECT_ROOT, exist_ok=True)result = agent_loop("Please read hello.txt and tell me its content", registry)print(result)
For a real deployment, you only need to replace call_model with a network request to your chosen model API; agent_loop and ToolRegistry need no changes. This is the benefit of layered design: the model is swappable, tools are extensible, and the loop stays stable.
10. Common Mistakes and Things to Watch Out For
When building your own agent, the following issues most often get people stuck. Check them one by one:
- Tool calls never trigger: The response object has no
tool_callsfield, orcall_modeldoes not correctly parse and populate it, causing the loop to return at step 0. Make sureMessagecarriestool_calls. - Context overflow: Tool output (especially reading large files or test logs) expands rapidly and blows past the window. Use the truncation and compression from Section 7, and prioritize keeping the most recent turns.
- Infinite loops and runaway cost: The model repeatedly calls tools but never converges. Use
max_steps, timeouts, and budget caps as a fallback. - Command injection and data loss: Concatenating model-generated commands with
shell=Trueis extremely risky and must be sandboxed and allowlisted, with manual confirmation for high-risk operations. - Writes not confirmed: Leaving
write_file/run_commandopen by default is dangerous; follow least privilege and default to read-only.
11. Conclusion and Next-Step Checklist
The core of a code agent is not mysterious: it is an organic combination of “the reasoning capability of a large language model” and “an engineering tool system.” Go through the checklist below, and you will have a safe, extensible Python code agent:
- Does
Messagecarrytool_calls, and can the loop actually call tools? - Do tools have a single responsibility, and are their parameter schemas clear?
- Does context compression skip the system prompt and keep key information?
- Are file operations constrained to the root directory, and is command execution sandboxed?
- Are step limits, timeouts, and budget guardrails set?
- Is every tool call logged for easy tracing?
Once you understand this mechanism, you can see the underlying logic of decisions and actions when using any AI coding tool, and you also gain the ability to customize and extend it yourself.
