Trace every step an agent takes
In this task you'll record every model call and tool call so you can see what an agent did and why.
An agent's answer hides most of the story. A trace records each step: the model call (time taken, tokens, cost so far), each tool call (name, arguments, outcome) and how the run ended. Give each run a trace id so all its lines can be found together, and write one JSON object per line so any tool can read it.
Flag anything worth a look: refused or invalid calls, injection-like text in tool output, runs stopped by the step limit or budget. In production, send traces to your monitoring (OpenTelemetry has conventions for AI calls, and Azure Monitor and Application Insights can store them) and alert on unusual patterns, such as a sudden rise in refused calls.
Example. Harbourline Design's agent bill doubled one week. The traces showed one request pattern hitting the step limit every time: the model kept calling the same search tool with the same query. A fix to the tool description cut the steps from eight to three.
Before you start
You need: Python 3.10 or newer (on Windows, use py where the steps say python). No AI account: the practice model runs on your computer. oncall.py from the final project. Time: 20 minutes.
Where to look
- oncall.py
- Trace
- trace.jsonl
- trace_summary.py
Steps
- In oncall.py, read the
Traceclass and thetrace.log(...)calls inrun()(excerpt in Commands). - Run
python oncall.pyandAGENT_APPROVE=no python oncall.py "Check the stock-worker logs"(PowerShell: set$env:AGENT_APPROVE="no"first). - Open trace.jsonl: one line per event, all sharing the run's trace id.
- Save
trace_summary.pyand runpython trace_summary.py. The stock-worker run shows restart_service(refused) and 'injection text'.One line per run is enough to spot the run that needs a person.
Commands
class Trace:
def __init__(self, path="trace.jsonl"):
self.id, self.path, self.cost = uuid.uuid4().hex[:12], path, 0.0
def log(self, **event):
event = {"trace": self.id, "at": round(time.time(), 3), **event}
with open(self.path, "a", encoding="utf-8") as f: f.write(json.dumps(event) + "\n")
# trace_summary.py
# trace_summary.py: one line per agent run from trace.jsonl, newest last.
import json, sys
runs = {}
for line in open(sys.argv[1] if len(sys.argv) > 1 else "trace.jsonl", encoding="utf-8"):
e = json.loads(line); r = runs.setdefault(e["trace"], {"task": "", "steps": 0, "tools": [], "tokens": 0, "cost": 0.0, "end": "?", "flags": []})
if e["type"] == "start": r["task"] = e["task"][:40]
if e["type"] == "model": r["steps"] = e["step"]; r["tokens"] += e["input_tokens"] + e["output_tokens"]; r["cost"] = e["cost_gbp"]
if e["type"] == "tool":
r["tools"].append(e["tool"] + ("" if e["outcome"] == "ok" else f"({e['outcome']})"))
if e["injection"]: r["flags"].append("injection text")
if e["type"] in ("answer", "stop"): r["end"] = e.get("reason", "answer")
for tid, r in runs.items():
print(f"{tid} {r['task']:<40} steps {r['steps']} tokens {r['tokens']:>5} GBP {r['cost']:.6f} {r['end']:<9} {', '.join(r['tools'])} {' '.join(sorted(set(r['flags'])))}")
python oncall.py
python trace_summary.py
Watch out for
- Cost
- Free. In production, traces can be large; keep full text for a short time and summaries for longer.
- Security
- Traces hold everything the agent saw, which may include personal data or secrets from logs. Restrict who can read them and mask secrets before writing.
- Common mistakes
- Logging only the final answer, and no trace id, so you can't put a run back together.
Clean up
Delete trace.jsonl and eval-trace.jsonl when you no longer need them.
Words to know
- Trace
- A record of every step one agent run took.
- Trace id
- An id shared by every line of one run.
- JSON Lines
- A file with one JSON object per line.
- OpenTelemetry
- An open standard for traces, metrics and logs.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On