Advanced about 6 h
The picture
01
Goal
user task
02
Think
decide next step
03
Act
call a tool
04
Observe
tool result
05
Check budget
stop or loop
06
Final answer
with evidence
The loop
ReAct interleaves reasoning (what should I do next, and why) with acting (calling a tool) and observing (reading the result). Modern APIs implement acting natively with tool calls, so the loop is short. What separates a demo from a dependable agent is everything around the loop.
A framework-free agent
import inspect, json, time
from dataclasses import dataclass, field
import anthropic
from pydantic import create_model, ValidationError
client = anthropic.Anthropic()
def tool(fn):
"""Build a JSON schema from the function signature and docstring."""
sig = inspect.signature(fn)
fields = {n: (p.annotation, ... if p.default is p.empty else p.default) for n, p in sig.parameters.items()}
Args = create_model(f"{fn.__name__}_args", **fields)
fn.spec = {"name": fn.__name__, "description": inspect.getdoc(fn) or "", "input_schema": Args.model_json_schema()}
fn.Args = Args
return fn
@dataclass
class Result:
answer: str | None
stop: str # "done" | "max_steps" | "max_tokens" | "timeout"
steps: int
tokens: int
trace: list = field(default_factory=list)
class Agent:
def __init__(self, tools, model="claude-sonnet-5-5", system="", max_steps=10, max_tokens=60_000, timeout_s=120):
self.tools = {t.__name__: t for t in tools}
self.model, self.system = model, system
self.max_steps, self.max_tokens, self.timeout_s = max_steps, max_tokens, timeout_s
def _call(self, name, args):
t = self.tools.get(name)
if t is None:
return True, f"Unknown tool {name!r}. Available: {sorted(self.tools)}"
try:
parsed = t.Args(**args)
except ValidationError as e:
return True, f"Invalid arguments: {e}"
try:
return False, str(t(**parsed.model_dump()))[:8000] # cap what flows back into context
except Exception as e:
return True, f"Tool error: {type(e).__name__}: {e}"
def run(self, goal: str) -> Result:
messages, used, t0, trace = [{"role": "user", "content": goal}], 0, time.time(), []
for step in range(1, self.max_steps + 1):
if time.time() - t0 > self.timeout_s:
return Result(None, "timeout", step - 1, used, trace)
resp = client.messages.create(model=self.model, max_tokens=1500, system=self.system,
tools=[t.spec for t in self.tools.values()], messages=messages)
used += resp.usage.input_tokens + resp.usage.output_tokens
trace.append({"step": step, "stop_reason": resp.stop_reason,
"content": [b.model_dump() for b in resp.content]})
if resp.stop_reason != "tool_use":
text = "".join(b.text for b in resp.content if b.type == "text")
return Result(text, "done", step, used, trace)
if used > self.max_tokens:
return Result(None, "max_tokens", step, used, trace)
messages.append({"role": "assistant", "content": resp.content})
results = []
for b in resp.content:
if b.type == "tool_use":
is_err, out = self._call(b.name, b.input)
trace.append({"step": step, "tool": b.name, "args": b.input, "error": is_err, "result": out[:500]})
results.append({"type": "tool_result", "tool_use_id": b.id, "content": out, "is_error": is_err})
messages.append({"role": "user", "content": results})
return Result(None, "max_steps", self.max_steps, used, trace)
Define tools with a decorator and run:
@tool
def calculate(expression: str) -> str:
"""Evaluate an arithmetic expression such as '(12.5 * 4) / 3'. Use for any numeric computation."""
import ast, operator as op
ops = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow, ast.USub: op.neg}
def ev(n):
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.BinOp): return ops[type(n.op)](ev(n.left), ev(n.right))
if isinstance(n, ast.UnaryOp): return ops[type(n.op)](ev(n.operand))
raise ValueError("unsupported expression")
return str(ev(ast.parse(expression, mode="eval").body))
agent = Agent([calculate], system="Use tools for arithmetic. Be concise.")
r = agent.run("What is 17% of 2,340, then multiplied by 3?")
print(r.stop, r.steps, r.tokens, r.answer)
with open("trace.jsonl", "a") as f:
f.write(json.dumps({"goal": "...", "stop": r.stop, "trace": r.trace}) + "\n")
Note that the calculator parses the expression with ast and a whitelist of operators. Never eval model output.
What around-the-loop features buy you
- Budgets (steps, tokens, wall clock) turn an infinite failure into a bounded one.
- Argument validation converts the model's mistakes into messages it can fix.
- Truncating tool output protects the context window.
- Traces let you replay and debug a failed run. You will rely on them in the observability topic.
- Explicit stop reasons let callers distinguish "finished" from "gave up".
Failure modes to test for
- Looping: the same call repeated. Detect repeated identical (tool, args) pairs and break or nudge.
- Premature stop: claims done without evidence. Add a verification step or required citations.
- Tool misuse: wrong arguments or the wrong tool. Improve descriptions; inspect traces.
- Prompt injection through tool output. Untrusted text must be treated as data.
Common mistakes
- No stop condition other than "the model says it's finished".
- Letting a tool return 50,000 characters.
- Evaluating on one run: agents are stochastic, so run each test several times.
Exercises
- Add a loop detector that stops after three identical tool calls.
- Add a web-search tool (stubbed) and write five test cases including one where the tool errors.
- Run each case five times and report the pass rate and cost distribution.
You are done when you can…
- Implement the loop with step, token and wall-clock budgets
- Generate tool schemas from Python type hints and validate arguments before running
- Produce a JSONL trace you can replay when something goes wrong