AI Coding Agent Architecture: Six Core Building Blocks

    This article breaks down the architecture of an AI coding agent into six core modules: context construction, tool design, prompt caching, memory and state, sandboxed execution, and termination checks. It explains why the same base model performs very differently inside an agent harness, how the observe-inspect-choose-act loop works, and offers practical guidance for building and evaluating these systems.

    1. Starting Point: Why the Same Model Behaves So Differently

    A pattern that shows up repeatedly in engineering practice is this: the same generation of base model often struggles with a cross-file refactoring task in a plain chat interface, yet once it is wrapped in a coding tool, it can reliably navigate a repository, apply batch edits, run commands, and verify results. The gap does not come from a sudden jump in model capability. It comes from differences in the system design around the model.

    To understand this, it helps to separate three concepts that are often used interchangeably.

    A base model (LLM) is the core next-token prediction engine. It maps an input sequence to a probability distribution and generates what comes next. It is stateless, has no memory and no tools, and cannot decide what to do next on its own.

    A reasoning model is still a base model, but through training or prompting strategies it spends more computation on reasoning, verification, and candidate answer search before responding. It is stronger, but the compute cost per task is higher.

    The agent layer (often called an agent harness) sits on top. It is a control loop around the model that decides what to inspect next, which tool to call, how to update internal state, and when to declare the task done and stop.

    A useful analogy: the base model is the engine, a reasoning model is an upgraded engine, and the agent harness is the transmission, steering, and braking system that determines how engine output becomes actual movement. The analogy is imperfect (a model can also be used without a harness), but it captures the key point: in real software engineering tasks, the system around the model matters as much as the model itself.

    This also explains the core argument of this article. When people discuss “model coding ability” and conflate model weights, reasoning behavior, and product packaging, they end up in unproductive debates. What really needs to be unpacked is the harness layer.

    2. Overall Shape: An Iterative Loop, Not One-Shot Generation

    The skeleton of a usable coding agent is not “receive a request, output code.” It is a loop that keeps running:

    1. observe → inspect → choose → act → (back to observe)
    • observe: take in the result of the previous action, including command output, test failure messages, and retrieved code snippets;
    • inspect: judge whether the current information is enough to support the next decision and identify gaps;
    • choose: pick one tool from the available set and construct its arguments;
    • act: actually carry out the action and produce a new environment state.

    This loop matters because software engineering tasks are inherently partially observable. Requirements are never fully specified, and the real constraints of a codebase only surface through exploration. One-shot generation cannot handle this uncertainty, while a loop lets the agent trade cheap actions for information and then revise its plan based on what it learns.

    3. Six Core Building Blocks

    Module 1: Context Construction and Repository Navigation

    Context determines what the model “sees.” Key design points include organizing the task description, relevant file contents, directory structure, and dependencies into a compact, information-dense form; providing retrieval and navigation so the agent can pull snippets on demand instead of loading the entire repository at once; and applying layered summarization to very long content while preserving interface signatures and key constraints.

    Practical advice: prioritize “addressability” so the agent can locate specific files and symbols rather than relying on fuzzy matching.

    Module 2: Tool Set Design

    Tools are the agent’s hands and feet. Good tool design follows three principles: single semantics (one tool solves one class of problem), structured returns (easy to parse and act on), and readable errors (failure messages are themselves input for the next decision).

    An illustrative tool description structure:

    1. {
    2. "name": "search_symbol",
    3. "description": "Search for definitions and references by symbol name",
    4. "parameters": {
    5. "symbol": "string, required",
    6. "scope": "string, optional, restricts the directory range"
    7. },
    8. "returns": "structured list: file path, line number, context snippet"
    9. }

    Tools that are too coarse make it hard for the model to control things precisely, while tools that are too fine lengthen the loop and amplify accumulated error. A reasonable compromise is to offer a small number of “composite tools” that cover high-frequency paths.

    Module 3: Prompt and Cache Stability

    This is the most underestimated module, yet it directly affects cost and latency. Most harness prompts consist of a “stable prefix plus a dynamic suffix”: system instructions, tool definitions, and long-term memory go in the prefix, while the current observation goes in the suffix. As long as the prefix stays byte-for-byte identical, the inference side can reuse the cache and significantly reduce repeated computation.

    The engineering implication is straightforward: do not insert timestamps, random identifiers, or per-turn counters into the system prompt; publish tool definition changes in batches rather than tweaking them every turn.

    Module 4: Memory and State Management

    Three kinds of state need to be distinguished: in-session short-term memory (the observation history of the current loop), cross-session long-term memory (project conventions, prior decisions), and externalized state (task lists and notes written to files). Externalizing state to the filesystem is a major advantage of coding agents over conversational interaction: state becomes inspectable, rollback-able, and inheritable by the next session.

    Module 5: Action Execution and Sandbox Isolation

    Execution brings risk, so isolation and tiered authorization cannot be skipped. A common approach is to grade by reversibility: read-only operations pass freely, writes within the workspace are logged, and high-risk actions such as deletion, network access, and permission changes require explicit confirmation. All actions should leave an auditable log so failed chains can be traced back.

    Module 6: Termination Conditions and Self-Verification

    The loop must have a clear exit, or it falls into endless “try one more time.” Usable conditions include: all items on the task list are checked off, the verification command passes, several consecutive turns produce no new information, or a turn or budget limit is reached. Self-verification before termination (running tests, comparing against expected output, checking untouched scope) significantly reduces cases that “look done but did not actually take effect.”

    4. A Minimal Implementation Skeleton

    The illustrative code below shows how the loop and modules fit together (specific tool implementations are omitted):

    1. def run_agent(goal, tools, max_steps=30):
    2. state = load_state() # Module 4: externalized state
    3. for step in range(max_steps):
    4. prompt = build_prompt( # Module 1 + Module 3: stable prefix + dynamic observation
    5. stable_prefix=SYSTEM + tool_specs(tools) + state.long_term,
    6. observation=state.last_observation,
    7. )
    8. action = model.choose(prompt, tools) # Module 2: structured tool selection
    9. if action is None or is_done(state): # Module 6: termination and verification
    10. break
    11. result = execute(action, policy=state.policy) # Module 5: tiered authorization
    12. state.update(action, result) # observe → inspect
    13. return verify(state)

    5. Implementation Advice and Common Pitfalls

    1. Fix context first, then switch models. Most failures come from missing information, not insufficient reasoning.
    2. Treat error messages as first-class citizens. Readable failure output is the cheapest learning signal.
    3. Prioritize a stable prefix. Cache stability improves both latency and cost structure.
    4. Externalize state. A file-based task list makes long sessions recoverable and collaborative.
    5. Watch the hidden cost of turns and budget. Set limits and monitor the information gain per turn.
    6. Do not confuse the layers. When evaluating harness effectiveness, hold the model variable fixed; when evaluating a model, hold the harness variable fixed.

    When deploying on the cloud, these modules can map to general-purpose capabilities: code and state stored in object storage or a code hosting service, tasks and logs connected through message queues and logging services, the execution sandbox running on a container platform, and overall runtime metrics fed into a monitoring and alerting system. General cloud product categories from providers such as Baidu AI Cloud can serve as the underlying foundation for this kind of architecture.

    6. Conclusion

    The capability of an AI coding agent is the product of the model and the harness working together. Breaking the system into six modules (context, tools, caching, memory, execution, termination) and organizing them around the observe → inspect → choose → act loop makes it possible to reliably analyze, evaluate, and improve such systems even without proprietary inside information.