Skip to content
Index Ai Academy
Phase 10 · Scaling & shipping

Tracing, budgets and guardrails

See what an agent did, cap what it spends, and stop it when it loops.

About 40 minutes · Model names and prices checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers9

First principles

What goes wrong if the harness checks its budget only after a paid tool finishes?

A useful budget is an execution rule at the boundary, supported by per-call traces and cumulative usage. Check allowance before starting work and reconcile the actual use after it completes.

  1. Starting point

    Harness estimates the next call's cost

  2. What changes

    Budget gate compares it with the remaining allowance

  3. Result

    Trace records the admitted call or the reason for stopping

Compare all three steps
  1. Starting point

    Harness estimates the next call's cost

  2. What changes

    Budget gate compares it with the remaining allowance

  3. Result

    Trace records the admitted call or the reason for stopping

Complete and reverse the trace

Given Harness estimates the next call's cost and Trace records the admitted call or the reason for stopping, write down the missing step that connects them.

Compare with the worked step

Budget gate compares it with the remaining allowance

Now take Budget gate compares it with the remaining allowance and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Harness estimates the next call's cost. Check that your implementation produces the result shown above.

Try it on a new case

A run has one unit left and the next call requires two. What should an operator see?

Show worked reasoning

The harness should stop before the call and record a budget event with the needed and remaining amounts. That makes the missing result explainable without overspending.

Run, change, and build

Check this when debugging. Relying on the turn budget alone to stop loops.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. A run has one unit left and the next call requires two. What should an operator see?

Why it matters

In production an agent runs thousands of times a day with no one watching. When a user reports "it did something weird", you need to see exactly what happened. When a bug makes it loop, you need it to stop before it spends a fortune. Tracing, budgets and guardrails turn a clever demo into a service a team can run and trust.

What you'll be able to do

  • Trace an agent run as nested spans: the run, each model call and each tool call
  • Track tokens and cost per run, and stop at a budget
  • Detect an agent stuck repeating the same call
  • Plan the operational side of shipping a harness: logging, privacy, rollout and monitoring
Quick check
A user reports that the agent "did something weird" yesterday. What do you need to find out what happened?
  1. The agent's system prompt as it was last month
  2. The total number of runs across all users that day
  3. A screenshot of the problem, taken by the user today
  4. A trace of that run: each model call, tool call and result
Show the answer

A trace of that run: each model call, tool call and result

A trace records every step of a run, like a flight recorder, so you can replay what the agent saw and did. Budgets and guardrails stop runs before they go too far; traces explain them afterward.

The idea: record the run, cap it, notice repeats

Recall: Logging and monitoring logged each call, and The core loop, built properly counted turns. In production you also need the tree of what happened, a spending limit and a guard against loops.

Traces and spans

After a plane has trouble, investigators read the flight recorder to see exactly what happened and when. A trace is that record for one agent run. It's made of spans: timed steps, each with a parent.

run "fix failing test"                 41.2 s   $0.183
├── model call 1                        3.1 s   in 4,210  out 312
├── tool read_file src/cart.py          0.01 s
├── model call 2                        2.8 s   in 5,060  out 158
├── tool bash "pytest -x"               6.4 s   exit 1
└── ...

Each span records its name, start and end time, its parent, and attributes: tokens, stop reason, tool name, exit code, error. Standards such as OpenTelemetry, with its conventions for generative AI, let you send these to common observability tools. Many LLM tracing products accept the same data. Tracing a run end to end follows one trace across several programs.

What to record, and what not to:

  • Do: IDs, timings, token counts, costs, tool names, stop reasons, errors, the harness and model versions.
  • Careful: full prompts and tool outputs. They help debugging most, but may hold personal data, secrets or customer code. Redact, sample, restrict access, and set a retention period.
Quick check
From the lesson on logging and monitoring: p95 latency is the time that 95% of requests beat, and it shows the slow tail that an average hides. What does this print for ten runs, in seconds: the mean, and a simple p95?
latencies = sorted([1.2, 0.9, 1.1, 1.0, 8.5, 1.3, 0.8, 1.0, 1.1, 0.9])
mean = sum(latencies) / len(latencies)
p95 = latencies[int(0.95 * len(latencies))]
print(round(mean, 2), p95)
  1. 1.78 1.3
  2. 1.0 8.5
  3. 8.5 1.78
  4. 1.78 8.5
Show the answer

1.78 8.5

Nine runs took about a second, and one took 8.5. The mean of 1.78 describes none of them. The p95 points straight at the slow one. A trace, in this lesson, is how you find out where that run spent its time: which model call, which tool, which retry.

Try it now

Step through the spans. The tool call holds most of the time, and an install holds most of the tool call.

Budgets

A prepaid phone card can't run up a surprise bill. Every run needs limits that stop it cleanly in the same way:

budgetstops
turnsloops that never converge
tokens or dollarsexpensive runs, such as huge files read again and again
wall-clock timeruns stuck waiting on slow tools
tool calls of one kindfor example, at most 3 deploys

Work out cost from usage on each response. Cache reads cost much less than normal input, and cache writes a little more, so count them separately. Prices change; keep them in config, not code.

In your own words
What is a trace, and what makes a good span?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: tracer, budget and loop guard

Worked example

Reading a trace

A trace is a tree of timed steps. Draw one as a waterfall and the slow part stands out at once.

import matplotlib.pyplot as plt
from agentlab import spans_plot

PRICE_IN, PRICE_OUT = 4, 20   # dollars per million tokens, Opus 5.5
SPANS = [
    {"id": 1, "name": "agent turn", "start_ms": 0, "end_ms": 8200},
    {"id": 2, "parent": 1, "name": "model call", "service": "model",
     "start_ms": 0, "end_ms": 1100, "tokens_in": 4210, "tokens_out": 312},
    {"id": 3, "parent": 1, "name": "tool: run_tests", "service": "tools",
     "start_ms": 1100, "end_ms": 7800},
    {"id": 4, "parent": 3, "name": "install packages", "service": "tools",
     "start_ms": 1100, "end_ms": 7000},
    {"id": 5, "parent": 3, "name": "pytest", "service": "tools",
     "start_ms": 7000, "end_ms": 7780},
    {"id": 6, "parent": 1, "name": "model call", "service": "model",
     "start_ms": 7800, "end_ms": 8200, "tokens_in": 5060, "tokens_out": 158},
]
spans_plot(SPANS, unit="ms", highlight=[3, 4])
cost = sum(s.get("tokens_in", 0) * PRICE_IN + s.get("tokens_out", 0) * PRICE_OUT
           for s in SPANS) / 1_000_000
print(f"model cost of the turn: ${cost:.4f}")
plt.show()
It runs right here in your browser, with nothing to install.

Without a trace you might blame the model. Here most of the turn goes to installing packages, inside one tool, and that's what you'd cache. Two model calls cost $0.0465 together: 4,210 + 5,060 input tokens and 312 + 158 output tokens at $4 and $20 per million.

Drill

Where did the time go?

Write time_by_name(spans): each span has name, start_ms and end_ms. Return a list of (name, total_ms) tuples, adding up spans with the same name, longest total first.

SPANS = [
    {"name": "model_call", "start_ms": 0, "end_ms": 2400},
    {"name": "tool:read_file", "start_ms": 2400, "end_ms": 2450},
    {"name": "model_call", "start_ms": 2450, "end_ms": 5100},
    {"name": "tool:run_tests", "start_ms": 5100, "end_ms": 9300},
]


def time_by_name(spans):
    return []


print(time_by_name(SPANS))
In the lesson, your code is checked as you write it.
Worked example

Cost from usage

Count each kind of input token at its own rate. These prices are made up for the example.

# dollars per million tokens
PRICES = {"input": 5.00, "output": 25.00, "cache_read": 0.50, "cache_write": 6.25}

def cost(usage):
    return (usage["input_tokens"] * PRICES["input"]
            + usage["output_tokens"] * PRICES["output"]
            + usage.get("cache_read_input_tokens", 0) * PRICES["cache_read"]
            + usage.get("cache_creation_input_tokens", 0) * PRICES["cache_write"]
            ) / 1_000_000

first = {"input_tokens": 300, "output_tokens": 400,
         "cache_creation_input_tokens": 20_000}
later = {"input_tokens": 300, "output_tokens": 400,
         "cache_read_input_tokens": 20_000}
print(f"first call  ${cost(first):.4f}")
print(f"later calls ${cost(later):.4f}")
In the lesson you can change this and run it.

Once the prefix is cached, later calls cost far less. That's why a stable prefix matters so much for agents.

Quick check
Prices are dollars per million tokens. What does this print?
prices = {"input": 3.0, "output": 15.0}
usage = {"input_tokens": 2000, "output_tokens": 1000}
cost = (usage["input_tokens"] * prices["input"]
        + usage["output_tokens"] * prices["output"]) / 1_000_000
print(round(cost, 3))
  1. 21.0
  2. 0.021
  3. 0.018
  4. 0.0021
Show the answer

0.021

2,000 × $3 plus 1,000 × $15 is $21 per million tokens of each, so $0.021 for this call.

Drill

Flag runs that cost far more than usual

Write outliers(costs, multiple=5): return the positions of runs whose cost is more than multiple times the median of all the costs (use statistics.median).

import statistics


def outliers(costs, multiple=5):
    return []


print(outliers([0.12, 0.09, 0.15, 4.80, 0.11, 0.10]))
In the lesson, your code is checked as you write it.

Counting repeats

A budget stops a stuck agent eventually. A guard notices after a few calls. It fingerprints each call as the tool name plus its input as sorted JSON, and counts the last ten.

Quick check
A loop detector looks for the same tool called with the same input several times in a row. What does this print as four calls arrive, one by one?
calls = [("read", "app.py"), ("run", "pytest"), ("run", "pytest"), ("run", "pytest")]

def stuck(history, repeats=3):
    return len(history) >= repeats and len(set(history[-repeats:])) == 1

print([stuck(calls[:n]) for n in range(1, 5)])
  1. [False, True, True, True]
  2. [False, False, True, True]
  3. [False, False, False, True]
  4. [False, False, False, False]
Show the answer

[False, False, False, True]

After the fourth call, the last three are identical, and the detector fires. It took 4 calls. A turn budget of 50 would have let the agent hit the same window 46 more times first. When it fires, a good harness tells the model what it noticed, so the next step can be something different.

Worked example

The same call, three times

Here's the fingerprint idea from this section. The call is the same if the tool and its input match, whatever order the input's keys came in.

import json
from collections import Counter

def fingerprint(tool, args):
    return tool + ":" + json.dumps(args, sort_keys=True)

def watch(calls, window=10, limit=3):
    recent = []
    for n, (tool, args) in enumerate(calls, 1):
        recent = (recent + [fingerprint(tool, args)])[-window:]
        if Counter(recent)[recent[-1]] >= limit:
            return f"step in at call {n}: {tool} repeated {limit} times"
    return "no loop"

calls = [("read", {"path": "a.py", "limit": 10}), ("edit", {"path": "a.py"}),
         ("read", {"limit": 10, "path": "a.py"}), ("run", {"cmd": "test"}),
         ("read", {"path": "a.py", "limit": 10})]
print(watch(calls))
print(watch(calls[:4]))
In the lesson you can change this and run it.

The third read has its keys in a different order and still counts, because the JSON is sorted first. This catches a stuck agent after a few calls, not after your turn budget and a large bill.

Quick check
The loop guard sees read_file with the same input three times in its window. What should the harness do first?
  1. Raise the turn budget, so the model has enough turns to get past the loop
  2. Ignore it: reading the same file three times is normal and costs very little
  3. Stop the run at once, without a word to the model, and return what it has so far
  4. Tell the model in the tool result that it's repeating itself; stop the run if it carries on
Show the answer

Tell the model in the tool result that it's repeating itself; stop the run if it carries on

A nudge often breaks the loop cheaply. A firm stop comes next if it doesn't.

In your own words
How do you find out why a run cost 40 times more than usual?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: layers, rollout and what to log

Shipping a harness

A restaurant tries a new dish on a few tables before it goes on the menu. Ship agents with the same care:

  • Version everything: system prompt, tool definitions, model and harness code. Record versions on every trace, so you can tell which change caused what.
  • Run the eval suite before each release (evaluation harnesses).
  • Roll out gradually: a small share of traffic first, and compare success, cost and complaints.
  • Monitor: success rate, cost per task, turns per task, error and refusal rates, and loop stops. Alert on sudden changes.
  • Plan for failure: what does the user see when the API is down, a budget is hit, or a run is stopped? Clear statuses beat silent failures.

A turn budget is the last resort

A building has smoke alarms and sprinklers as well as fire doors. A budget will stop a stuck agent eventually, but "eventually" might be $20 and 100 turns later. Loop detection catches it after three identical calls, and a cost limit stops expensive runs whatever they're doing. Use all of them, in layers.

Logs are full of secrets

Agent logs are unusually sensitive. Full prompts contain whatever the agent read: customer records, private code, or keys it found in a config file. So decide on redaction and a retention limit before you start logging, not after. Store the sensitive parts separately, with stricter access, and delete them on a schedule. Metadata such as token counts, tool names and timings can usually be kept for longer.

Quick check
Which part of an agent's logs can usually be kept longest?
  1. Keys the agent found in config files
  2. Full prompts, with all the agent read
  3. Metadata: token counts, tool names and timings
  4. Customer records from tool results
Show the answer

Metadata: token counts, tool names and timings

Metadata says how the agent behaved without holding what it read. The sensitive parts are stored apart and deleted on a schedule.

Prices belong in config

Prices change, and new models arrive. If they're hard-coded across your harness, your cost reports silently drift from reality. Keep one table in config, and record the model id on each span, so that you can recalculate old runs if you need to.

Treat prompts as code

A one-line change to a system prompt can change an agent's behavior more than a thousand lines of code. Yet people often edit prompts directly in production, with no review and no test. So keep prompts in version control. Run your eval suite on every change, and roll out in stages, just as you would with code. Include the prompt version on every trace, so that when behavior shifts, you can tell which change caused it.

When a shipped agent starts misbehaving, ask first what changed: the prompt, the tools, the model, or the data it reads. Those four cover almost every regression you'll see, and your traces should be able to answer it.

In your own words
What is the first response to an agent calling read_file three times with the same input?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What is a span in a trace?

  1. One timed step, such as a model call or a tool call, with a parent and attributes
  2. The whole agent run's final answer, saved along with how long it took
  3. A type of token, billed at its own rate and counted apart from the others
  4. A log line with no timing, recording that a step happened and nothing else

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write