Trace every step an agent takes

DevOps, Hands On20 minutesFreeSteps checked 23 November 2026By Cloud Hands On

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

  1. oncall.py
  2. Trace
  3. trace.jsonl
  4. trace_summary.py

Steps

  1. In oncall.py, read the Trace class and the trace.log(...) calls in run() (excerpt in Commands).
  2. Run python oncall.py and AGENT_APPROVE=no python oncall.py "Check the stock-worker logs" (PowerShell: set $env:AGENT_APPROVE="no" first).
  3. Open trace.jsonl: one line per event, all sharing the run's trace id.
  4. Save trace_summary.py and run python 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

Keep going