Building a Code Agent From Scratch: Architecture and Implementation Breakdown
This article walks through building a code agent from scratch, focusing on the engineering systems around the model rather than the model itself. It defines what makes a code agent different from a standard coding assistant, breaks down a practical five-layer architecture, and explains context engineering, tool-call loops, security and cost governance, and evaluation. Readers will find implementation-level guidance, sample Python code, common pitfalls, and a transferable methodology for building stable, controllable, and measurable AI coding systems.
1. Why Build a Code Agent From Scratch
Over the past couple of years, AI coding tools have evolved from single-line completion to understanding entire repositories, making cross-file changes, and running verification. Yet for most developers working primarily in Python, reading the underlying implementation often hits a wall: mainstream solutions are either closed source or open source but not written in Python, resulting in a steep learning curve and high migration costs.
The value of building from scratch is not to ship another product, but to turn a black box into a white box. Only when you implement context retrieval, tool dispatch, execution feedback, and termination logic yourself do you truly understand that a code agent’s capability ceiling often depends not on the model itself, but on the design quality of the surrounding engineering system.
2. Clarifying the Concepts: Code Agents vs. Ordinary Coding Assistants
The core of an ordinary coding assistant is “input snippet, output snippet,” with single-turn, stateless interaction. A code agent has four characteristics:
- Autonomy: It plans its own steps instead of waiting for step-by-step human instructions.
- Tool use: It can read and write files, search symbols, run tests, and inspect logs.
- Closed loop: It revises its approach based on execution results, forming a “hypothesize, verify, correct” cycle.
- Boundedness: It operates within clear permission and resource boundaries, and its actions are auditable and rollback-able.
Understanding these four points means all subsequent module design naturally falls along two main lines: how to support autonomy, and how to enforce boundedness.
3. Overall Architecture: Five Layers Define the Capability Ceiling
A practical reference implementation is typically divided into five layers, from top to bottom:
- Interaction layer: Receives natural-language requirements, clarifies ambiguity, and outputs an execution plan and progress.
- Planning layer: Breaks requirements into verifiable subtasks and maintains a task state machine.
- Context layer: Handles code retrieval, dependency graph construction, and context trimming and compression.
- Execution layer: Registers tools, validates parameters, runs in a sandbox, and normalizes results.
- Governance layer: Manages permission policies, audit logs, cost quotas, and evaluation and regression.
It is worth emphasizing that most failures are not caused by insufficient model capability, but by a missing context layer and governance layer: the former leaves the model “unable to see critical code,” while the latter lets the agent “break the repository without anyone knowing.”
4. Context Engineering: The Real Dividing Line Between Success and Failure
The context window is a scarce resource and must be managed like memory.
- Retrieval strategy: Rely primarily on symbol indexing and call relationships, supplemented by text similarity retrieval; first locate entry files, then expand one or two hops along the dependency graph.
- Trimming principles: Prioritize keeping public interfaces, type definitions, configuration, and tests; fold long implementations and keep only signatures and key branches.
- Compression techniques: Produce structured summaries of historical turns, preserving three types of information: confirmed facts, ruled-out hypotheses, and items pending verification.
Illustrative code:
def build_context(repo, entry_symbols, budget=12000):ctx, used = [], 0for sym in entry_symbols:for chunk in repo.neighbors(sym, depth=2):if used + chunk.tokens > budget:breakctx.append(chunk)used += chunk.tokensreturn summarize(ctx) # Keep interfaces and facts, compress implementation details
5. The Tool-Call Loop: A Minimal Design That Lets the Agent Act
Tool design follows three iron rules: clear descriptions, strict parameter validation, and parseable results. A minimal tool base class can be abstracted as:
class Tool:name: strschema: dictdef run(self, **kwargs): ...def dispatch(tool: Tool, args):validate(args, tool.schema) # Validate parameters, reject out-of-bounds inputresult = tool.run(**args) # Execute inside the sandboxreturn normalize(result) # Truncate, denoise, structure
The key to the loop is the termination condition: finish when tests pass, static checks report no new warnings, and the change scope matches the plan; otherwise, carry the failure information into the next round and set a maximum iteration count to prevent infinite loops.
6. Security and Cost Governance: What Enterprise Scenarios Cannot Skip
- Permission sandbox: Limit file writes to a whitelist of directories, disable network access by default, and run command execution in a container or restricted environment.
- Rollback capability: Generate a patch for every change, keep version snapshots, and restore with one click when something goes wrong.
- Observability: Record the input summary, tool calls, and elapsed time of each step in a structured way for later review.
- Quota control: Limit the number of rounds per task, context size, and concurrency to avoid resource runaway.
To scale into a team-level service, you can combine object storage to persist artifacts, a message queue to decouple long-running tasks, a container platform to host sandboxes, and logging and monitoring services to track runtime quality. In cloud environments such as Baidu AI Cloud, these capabilities can be composed on demand as general-purpose service categories.
7. Evaluation: No Evaluation, No Iteration
It is recommended to build three levels of evaluation:
- Unit level: Correctness and exception handling of individual tools.
- Task level: Use real repository issues as samples and measure first-pass rate, average rounds, and average elapsed time.
- Regression level: Fix a baseline set and run the full suite after every change to prevent capability regression.
Beyond metrics, always manually sample failed cases and attribute them to one of four categories: retrieval gaps, planning errors, tool misuse, and permission blocks, forming a sustainable improvement loop.
8. Common Pitfalls and How to Avoid Them
- Pitfall 1: Treating prompts as architecture. Prompts only affect expression; context and tool design determine capability.
- Pitfall 2: Pursuing full automation. High-risk operations should keep a human confirmation checkpoint.
- Pitfall 3: Ignoring repository scale. Large repositories must rely on indexing and incremental updates; otherwise retrieval costs become unacceptable.
- Pitfall 4: No evaluation-driven approach. Without a baseline, no “optimization” can be disproven.
9. Conclusion
The essence of a code agent is to engineer the loop of “understanding code, executing verification, and correcting the approach.” Implementing it from scratch gives you more than a runnable skeleton; it gives you a transferable methodology: context engineering as the foundation, the tool loop as the limbs, and governance and evaluation as the guardrails. Once you master this structure, no matter how the underlying model changes, you can quickly build stable, controllable, and measurable AI coding capabilities.
