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.

Step 1 — Build the conversation loop
Pick one — skip the others.

Python Implementation
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 2Go Implementation
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.

{
"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():
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 resolvedIntercept the tool_use signal in your loop to extract the tool metadata:
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 hereExplicit schema definitions let the model reason about its environment and work out exactly when it needs an external function to make progress.

Step 3 — Complete the file read, write, and edit tools
Implement tools for listing and modifying files. Use surgical editing for existing code.
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 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.

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 to enforce a four-stage verification loop:
- Inspect: Review existing code and project constraints.
- Plan: State a brief plan before taking any action.
- Verify: Review the diff and run the relevant tests or build commands.
- 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.

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 to manage large repository state. Without it, a long-running agent
accumulates irrelevant noise until it becomes an expensive typist. Create a
CLAUDE.md memory file in the project root to hold
persistent architectural conventions, and read up on
context engineering before you scale the loop further.
References
- How to Build an Agent — Amp
- Tutorial: Build a Tool-Using Agent — Claude Platform Docs
- How to Build a Coding Agent: Free Workshop — Geoffrey Huntley
- Build a Coding Agent from Scratch: The Complete Python Tutorial — Sid Bharath
- mini-coding-agent — Sebastian Raschka (GitHub)
- Components of a Coding Agent — Sebastian Raschka
- Pi, Minimal and Performant — Earendil
- Designing Agentic Loops — Simon Willison
- What You Only Learn by Building a Coding Agent From Scratch — QuillCode