# How to Build Your Own Coding Agent

> Build a functional coding agent with Python or Go to automate codebase navigation, surgical file editing, and guarded shell command execution in a loop.

Source: https://camnangai.com/en/for/developers/build-your-own-coding-agent  
Published: 2026-08-07

You will finish with a working **coding agent** that reads your files, edits them, and runs shell
  commands on its own, driven by a ReAct (Reason, Act, Observe) loop.

It reads files to see what it is working with, decides what to do next, and runs commands to reach
the goal — without you stepping through each action.

You need Python 3.10 or higher, an Anthropic API key in `ANTHROPIC_API_KEY`, and a terminal. The
examples below use Claude Sonnet 5 as the reasoning model.

The complete sample project for this guide is on GitHub:
[camnangai-public-sources/coding-agent-demo](https://github.com/tuanhadev/camnangai-public-sources/tree/main/coding-agent-demo).

![A minimal coding agent running in a terminal, assembled from three parts: a language model, a loop, and a set of tools](https://camnangai.com/articles/tu-xay-dung-coding-agent/01-infographic-en.webp)

## Step 1 — Build the conversation loop

Pick one — skip the others.

![The conversation loop: the history is sent to the model, the model replies, the reply is appended to the history, and it repeats](https://camnangai.com/articles/tu-xay-dung-coding-agent/02-en.webp)

### Python Implementation

```python
import anthropic
import sys

client = anthropic.Anthropic()
MODEL = "claude-sonnet-5"

def run_agent(user_message, conversation_history=None):
    if conversation_history is None:
        conversation_history = []

    conversation_history.append({"role": "user", "content": user_message})

    while True:
        with client.messages.stream(
            model=MODEL,
            max_tokens=4096,
            system="You are a helpful coding assistant.",
            messages=conversation_history
        ) as stream:
            for event in stream:
                if event.type == "content_block_delta" and event.delta.type == "text_delta":
                    sys.stdout.write(event.delta.text)
                    sys.stdout.flush()

            final_message = stream.get_final_message()
            conversation_history.append({"role": "assistant", "content": final_message.content})

            if final_message.stop_reason != "tool_use":
                break
            # Tool handling logic follows in Step 2
```

### Go Implementation

```go
package main

import (
    "context"
    "fmt"
    "github.com/anthropics/anthropic-sdk-go"
)

func (a *Agent) Run(ctx context.Context) error {
    conversation := []anthropic.MessageParam{}
    for {
        userInput, ok := a.getUserMessage() // Implementation uses bufio.Scanner
        if !ok { break }

        conversation = append(conversation, anthropic.NewUserMessage(anthropic.NewTextBlock(userInput)))

        message, err := a.client.Messages.New(ctx, anthropic.MessageNewParams{
            Model:     "claude-sonnet-5",
            MaxTokens: 4096,
            Messages:  conversation,
        })
        if err != nil { return err }

        conversation = append(conversation, message.ToParam())
        fmt.Printf("Claude: %s\n", message.Content[0].Text)
    }
    return nil
}
```

This loop is the heartbeat of the agent. It keeps multi-turn state by carrying the conversation and
environment across every interaction.

## Step 2 — Define your first tool and handle the tool_use signal

Define a tool schema so the model can interact with the file system.

![The ReAct tool cycle: the model emits a tool_use signal, the client executes the tool, and the tool_result goes back so the model can keep reasoning](https://camnangai.com/articles/tu-xay-dung-coding-agent/03-en.webp)

```json
{
  "name": "read_file",
  "description": "Read the contents of a file at the given path.",
  "input_schema": {
    "type": "object",
    "properties": {
      "path": { "type": "string", "description": "The path to the file to read" }
    },
    "required": ["path"]
  }
}
```

Add a safety function that prevents directory traversal using `.resolve()`:

```python
from pathlib import Path
WORKSPACE = Path.cwd().resolve()

def resolve_workspace_path(path_str: str) -> Path:
    resolved = (WORKSPACE / path_str).resolve()
    if resolved != WORKSPACE and WORKSPACE not in resolved.parents:
        raise ValueError(f"Path escapes workspace: {path_str}")
    return resolved
```

Intercept the `tool_use` signal in your loop to extract the tool metadata:

```python
if final_message.stop_reason == "tool_use":
    for block in final_message.content:
        if block.type == "tool_use":
            tool_id = block.id
            tool_name = block.name
            tool_input = block.input
            # Execute tool_name logic here
```

Explicit schema definitions let the model reason about its environment and work out exactly when it
needs an external function to make progress.

![A terminal printing the executing-tool line for read_file with its path argument, followed by the contents of main.py with line numbers](https://camnangai.com/articles/tu-xay-dung-coding-agent/04-en.webp)

## Step 3 — Complete the file read, write, and edit tools

Implement tools for listing and modifying files. Use surgical editing for existing code.

```python
def list_files(path="."):
    safe_path = resolve_workspace_path(path)
    return [str(p.relative_to(WORKSPACE)) for p in safe_path.rglob("*") if p.is_file()]

def write_file(path, content):
    safe_path = resolve_workspace_path(path)
    safe_path.write_text(content)
    return f"Successfully wrote to {path}"

def edit_file(path, old_string, new_string):
    safe_path = resolve_workspace_path(path)
    content = safe_path.read_text()

    if content.count(old_string) != 1:
        return f"Error: Found {content.count(old_string)} occurrences of target string. Edits must be unique."

    new_content = content.replace(old_string, new_string)
    safe_path.write_text(new_content)
    return f"Successfully edited {path}"
```

Surgical editing cuts token use and prevents accidental code corruption, because the agent makes
precise updates instead of rewriting whole files.

## Step 4 — Give the agent shell access behind an approval gate

Add shell execution so the agent can run tests, install dependencies, and verify the environment.

![The safety boundary for shell access: the agent proposes a command, a human approval gate sits in between, and a subprocess is not a sandbox](https://camnangai.com/articles/tu-xay-dung-coding-agent/05-en.webp)

```python
import subprocess

def run_bash(command):
    # Mandatory Approval Gate
    confirm = input(f"Execute command? [y/N]: {command} ")
    if confirm.lower() != 'y':
        return "Command aborted by user."

    try:
        result = subprocess.run(
            command, shell=True, capture_output=True, text=True, timeout=60
        )
        return result.stdout + result.stderr
    except subprocess.TimeoutExpired:
        return "Error: Command timed out after 60 seconds"
```

> **WARNING:** A subprocess gives you process isolation, not a security sandbox.
> Running untrusted code can corrupt your system or exfiltrate data. Never run this in an
> environment holding sensitive secrets without a restricted container.

## Step 5 — Run the agent on a real repo and verify the result

Give it a task that exercises the full ReAct loop: "Implement a Fibonacci function in a new file and
run the tests."

Update the system prompt to enforce a four-stage verification loop:

1.  **Inspect:** Review existing code and project constraints.
2.  **Plan:** State a brief plan before taking any action.
3.  **Verify:** Review the diff and run the relevant tests or build commands.
4.  **Report:** Declare completion only after every check passes.

The agent reads each `tool_result` to observe its own success or failure. When a test fails, it sees
the error in the history and attempts a fix on its own.

![The agent reads CLAUDE.md and test_main.py, uses edit_file to add a /health endpoint, asks for approval to run pytest, and finishes with both tests passing](https://camnangai.com/articles/tu-xay-dung-coding-agent/06-en.webp)

## Minimal tool set reference

| Tool         | Purpose                          | Logic principle                                                         |
| :----------- | :------------------------------- | :---------------------------------------------------------------------- |
| `read_file`  | Retrieve file content.           | Context discipline: load only the data you need into the window.        |
| `write_file` | Create or overwrite a file.      | Workspace restriction: check the parent path to prevent traversal.      |
| `edit_file`  | Surgical text replacement.       | Precision: require exactly one match to avoid ambiguous corruption.     |
| `list_files` | Map the project structure.       | Stable facts: establish the repo layout as a baseline for reasoning.    |
| `run_bash`   | Execute shell commands or tests. | Environmental feedback: use stdout and stderr to drive the ReAct cycle. |

## Troubleshooting

| Symptom                       | Cause                                                            | Fix                                                                   |
| :---------------------------- | :--------------------------------------------------------------- | :-------------------------------------------------------------------- |
| "Path escapes workspace"      | Malicious or hallucinated relative paths, such as `../../`.      | Use `resolve_workspace_path` with `.resolve()` and parent validation. |
| Agent loops on a failing tool | Vague error messages leave the model unable to spot its mistake. | Return specific "expected X, found Y" strings to guide the next turn. |
| Context bloat or high latency | Full file reads on large sources burn tokens.                    | Add line-range offsets, or prefer surgical edits over full writes.    |

## Next step

Add context compaction to manage large repository state. Without it, a long-running agent
accumulates irrelevant noise until it becomes an expensive typist. Create a
[`CLAUDE.md`](https://camnangai.com/en/for/developers/claude-md-best-practices) memory file in the project root to hold
persistent architectural conventions, and read up on
[context engineering](https://camnangai.com/en/for/developers/context-engineering) before you scale the loop further.

## References

- [How to Build an Agent — Amp](https://ampcode.com/notes/how-to-build-an-agent)
- [Tutorial: Build a Tool-Using Agent — Claude Platform Docs](https://platform.claude.com/docs/en/agents-and-tools/tool-use/build-a-tool-using-agent)
- [How to Build a Coding Agent: Free Workshop — Geoffrey Huntley](https://ghuntley.com/agent/)
- [Build a Coding Agent from Scratch: The Complete Python Tutorial — Sid Bharath](https://sidbharath.com/blog/build-a-coding-agent-python-tutorial/)
- [mini-coding-agent — Sebastian Raschka (GitHub)](https://github.com/rasbt/mini-coding-agent)
- [Components of a Coding Agent — Sebastian Raschka](https://magazine.sebastianraschka.com/p/components-of-a-coding-agent)
- [Pi, Minimal and Performant — Earendil](https://earendil.com/posts/pi-autoresearch-and-databricks/)
- [Designing Agentic Loops — Simon Willison](https://simonwillison.net/2025/Sep/30/designing-agentic-loops/)
- [What You Only Learn by Building a Coding Agent From Scratch — QuillCode](https://max128.substack.com/p/what-i-learned-making-my-own-coding)
