Build a Claude Agent Loop from Scratch in Python
๐ In plain words: An agent is a loop: ask Claude what to do next, run the tool it picks, show it the result, repeat. In this lesson you write that loop yourself for a small test-fixing agent, with safety rails, so you understand exactly what frameworks like the Agent SDK do for you.
Building one agent by hand is the fastest way to understand every agent framework, and the exam’s agent-diagnosis questions assume you know what the loop is doing. In this lesson you will give Claude four tools that really run pytest, read and write files in a sandboxed project folder, write the loop with correct stop conditions, add a step limit and a token budget, and print a trace you can debug from.
๐ Key terms
- Agent loop: repeat {call Claude โ run requested tools โ return results} until Claude stops asking for tools.
- Trace: the step-by-step record of an agent run: model calls, tool calls, results, stop reason.
- Path sandboxing: refusing any file path outside an allowed folder, so the agent cannot touch the rest of the machine.
- Budget: a limit on steps, tokens or money for one run.
๐ช The steps at a glance
- Create a small project with a failing test.
- Write the tools.
- Describe the tools to Claude.
- Write the loop with correct stop conditions.
- Add budgets and a trace.
- Run the agent and read the trace.
๐ช Step 1: Create a project with a failing test
The agent’s job will be to make the tests pass:
๐ project/shop.py
def discount(total: float, percent: int) -> float:
"""Return the total after a percentage discount."""
return total - percent # BUG: subtracts the percent as money
๐ project/test_shop.py
from shop import discount
def test_ten_percent():
assert discount(200.0, 10) == 180.0
def test_zero_percent():
assert discount(50.0, 0) == 50.0
๐ช Step 2: Write the tools
Each tool is ordinary Python. File tools refuse paths outside project/: that check is in code, so no model output can bypass it.
๐ agent_tools.py
import subprocess
import sys
from pathlib import Path
ROOT = (Path(__file__).parent / "project").resolve()
def _safe(path: str) -> Path:
p = (ROOT / path).resolve()
if not p.is_relative_to(ROOT):
raise PermissionError(f"path outside the project: {path}")
return p
def run_tests() -> str:
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"],
cwd=ROOT, capture_output=True, text=True, timeout=120)
return (r.stdout + r.stderr)[-2000:] # shape the result: tail only
def read_file(path: str) -> str:
return _safe(path).read_text()
def write_file(path: str, content: str) -> str:
_safe(path).write_text(content)
return f"wrote {len(content)} characters to {path}"
def list_files() -> str:
return "\n".join(sorted(p.name for p in ROOT.iterdir() if p.suffix == ".py"))
๐ช Step 3: Describe the tools to Claude
๐ agent_schema.py
TOOLS = [
{"name": "run_tests", "description": "Run the project's pytest suite and return the last part of the output.",
"input_schema": {"type": "object", "properties": {}}},
{"name": "list_files", "description": "List the Python files in the project.",
"input_schema": {"type": "object", "properties": {}}},
{"name": "read_file", "description": "Read one project file. path is relative to the project, e.g. shop.py.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
{"name": "write_file", "description": "Replace a project file's whole content. Only change source files, never tests.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
"required": ["path", "content"]}},
]
๐ช Step 4: Write the loop
The loop follows the rules from Lesson 23, plus the outcomes an agent must handle:
๐ agent.py
import json
import anthropic
import agent_tools
from agent_schema import TOOLS
client = anthropic.Anthropic()
SYSTEM = """You are a careful test-fixing agent. Run the tests, read the code, make the smallest fix in source files
(never edit tests), and run the tests again. Stop when all tests pass, and summarise what you changed."""
REGISTRY = {"run_tests": agent_tools.run_tests, "list_files": agent_tools.list_files,
"read_file": agent_tools.read_file, "write_file": agent_tools.write_file}
def run_agent(goal: str, max_steps: int = 10, max_output_tokens: int = 20_000) -> str:
messages = [{"role": "user", "content": goal}]
used = 0
for step in range(1, max_steps + 1):
r = client.messages.create(model="claude-opus-5-5", max_tokens=4000, system=SYSTEM,
tools=TOOLS, messages=messages)
used += r.usage.output_tokens
messages.append({"role": "assistant", "content": r.content})
if r.stop_reason == "end_turn":
return "DONE: " + "".join(b.text for b in r.content if b.type == "text")
if r.stop_reason in ("max_tokens", "refusal"):
return f"STOPPED: stop_reason={r.stop_reason}"
if used > max_output_tokens:
return f"STOPPED: output-token budget exceeded ({used})"
results = []
for b in r.content:
if b.type != "tool_use":
continue
try:
output, is_error = REGISTRY[b.name](**b.input), False
except Exception as e:
output, is_error = f"{type(e).__name__}: {e}", True
print(f"step {step}: {b.name}({json.dumps(b.input)[:60]}) -> {str(output).splitlines()[-1][:70]}")
results.append({"type": "tool_result", "tool_use_id": b.id, "content": str(output), "is_error": is_error})
messages.append({"role": "user", "content": results})
return f"STOPPED: reached {max_steps} steps"
- Stop conditions are explicit:
end_turn(done),max_tokensorrefusal(cannot continue), a budget, or the step limit. Each returns a different message so a caller knows why it stopped. pause_turn(from server tools) would be handled by re-sending the turn; this agent uses only client tools.- Tool exceptions, including the sandbox’s
PermissionError, becomeis_errorresults that Claude can react to.
๐ช Step 5: Run it and read the trace
๐ run_agent.py
from agent import run_agent
print(run_agent("Make the failing tests in this project pass."))โจ๏ธ Terminal
python run_agent.py๐ฅ๏ธ Output (sample run)
step 1: run_tests({}) -> 1 failed, 1 passed in 0.42s
step 2: read_file({"path": "shop.py"}) -> return total - percent # BUG: subtracts the percent as money
step 3: write_file({"path": "shop.py", "content": "def discount(total: float, p) -> wrote 148 characters to shop.py
step 4: run_tests({}) -> 2 passed in 0.42s
DONE: All tests pass. I changed discount() in shop.py to subtract a percentage of the total (total * percent / 100) instead of subtracting the percent value itself. Tests were not modified.
The tool calls in this trace really ran: pytest executed against project/, the file was read and rewritten, and the second pytest run passed. Only Claude’s decisions came from the local stand-in API.
๐ check_fix.py
from pathlib import Path
print(Path("project/shop.py").read_text())โจ๏ธ Terminal
python check_fix.py๐ฅ๏ธ Output
def discount(total: float, percent: int) -> float:
"""Return the total after a percentage discount."""
return total - total * percent / 100
๐ช Step 6: Try to escape the sandbox
Agents read untrusted text (logs, files, web pages) that can contain instructions. Check that the guardrail holds regardless of what the model asks for:
๐ escape.py
import agent_tools
for path in ["shop.py", "../agent.py", "C:/Windows/win.ini"]:
try:
agent_tools.read_file(path)
print(f"{path:<20} allowed")
except PermissionError as e:
print(f"{path:<20} blocked: {e}")โจ๏ธ Terminal
python escape.py๐ฅ๏ธ Output
shop.py allowed
../agent.py blocked: path outside the project: ../agent.py
C:/Windows/win.ini blocked: path outside the project: C:/Windows/win.ini
๐ Real-world example: Ravi’s runaway agent
Ravi’s first agent had no step limit and treated tool exceptions as fatal. One night a flaky network made run_tests time out, the agent crashed, and the job retried from scratch 40 times. With is_error results Claude could see the timeout and wait; with a step limit and a token budget, the worst case became a short, cheap, clearly logged stop.
๐งช Practice Questions
Question 1. An agent repeats the same read_file call over and over. Traces show the tool runs each time, but the next request never contains its output. What is wrong?
- A. The tool description is unclear
- B. Tool results are not appended to the messages before the next call
- C. max_tokens is too high
- D. The step limit is too low
Show answer
Answer: B. If Claude never sees the result, it keeps asking for it. Every tool_result must go back in the next user message.
Question 2. Which is the correct primary stop condition for a manual agent loop?
- A. Stop when the reply contains any text
- B. Stop after exactly three steps
- C. Continue while stop_reason is tool_use; stop on end_turn, and handle max_tokens and refusal explicitly
- D. Stop when the model says “done”
Show answer
Answer: C. stop_reason is the reliable signal. Step limits and budgets are backstops, not the main condition.
Question 3. Which two belong in code rather than in the prompt for a file-editing agent? (Choose 2.)
- A. Refusing paths outside the project folder
- B. The tone of the final summary
- C. A maximum number of steps and a token budget
- D. The explanation of what the bug was
Show answer
Answer: A and C. Safety limits must hold regardless of model output, so they are enforced in code.
Question 4. A tool raises an exception and the whole agent run crashes. What is the better design?
- A. Remove the tool
- B. Catch the exception and return a tool_result with is_error true and the message
- C. Retry the tool forever
- D. Ask the user to restart the run
Show answer
Answer: B. Returning the error lets Claude adapt (retry differently, choose another tool, or stop with an explanation).
๐ Assignment
- Task 1: Run the agent with your own key on the project, then add a third failing test (for example a 100% discount) and run it again.
โ Done when: the agent fixes the code and all three tests pass. - Task 2: Save the full
messageslist totrace.jsonat the end of every run.
โ Done when: you can replay the run step by step from the file. - Stretch: Add a rule in code that rejects
write_filefor any file whose name starts withtest_, returning anis_errorresult.
โ Done when: a scripted attempt to edit a test is blocked and the agent explains it could not.
โ Frequently Asked Questions
๐ค How do I build an AI agent in Python with Claude?
Define tools, call the Messages API with them, run each requested tool, return the results in one user message, and loop while stop_reason is tool_use, with budgets and guardrails in code.
๐ค When should an agent loop stop?
On end_turn (finished), on max_tokens or refusal (cannot continue normally), or when a budget or step limit is reached as a safety backstop.
๐ค How do I stop an agent from changing the wrong files?
Enforce allowed paths in the tool code (path sandboxing) and, for risky actions, require approval. Do not rely on the prompt alone.
๐ค Should I write my own loop or use a framework?
Write one once to understand it. In production, use the Tool Runner or the Agent SDK unless you need custom control flow.
๐ Summary
- An agent is a loop of model calls, tool calls and tool results.
- Terminate on
stop_reason; treat step limits and budgets as backstops. - Return tool failures as
is_errorresults instead of crashing. - Enforce safety (path sandboxing, write rules) in code.
- Print and save a trace for every run so you can debug it.
Next, continue with Claude Agent SDK in Python: First Agent, Tools and Hooks.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.