Lesson 34.6 · 6 of 6 · 6 min read · Reviewed 24 Nov 2026
Feeding errors and stack traces back to the model
By the end, you can
- Turn a raw exception or stack trace into a tool result the model can act on.
- Decide what to keep, cut and hide before an error reaches the model.
Lesson 34.3 covered the shape of a structured errorStructured error: An error returned to the model with a type, a message and whether retrying might help.: a flag, a category and whether a retry could help. This lesson is about the content. When a tool throws, you have a raw exception, often with a long stack traceTrace: A record of everything that happened during one request or agent run, as a tree of timed steps.. What you pass back decides whether the model fixes the problem or flails.
A raw trace is the wrong default
A full trace is written for a developer with the source code open. The model has neither. It costs hundreds of tokens, most lines are framework internals, and it can leak paths, hostnames or credentials. Worse, it rarely says what to do next, so agentsAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. often just retry the same call.
What to send instead
| Keep | Cut | Hide |
|---|---|---|
| Error type and a one-line message | Framework and library frames | API keys, tokens, passwords |
| The input value that caused it | Repeated lines in loops | Internal hostnames and IP addresses |
| One or two frames from your own code | Memory addresses, thread ids | Full file paths on your servers |
| A suggested next step | Timestamps and log prefixes | Other customers’ data |
A worked example
The get_invoice tool fails. The raw trace ends with:
File "/srv/app/vendor/db/pool.py", line 411, in execute
File "/srv/app/vendor/db/cursor.py", line 88, in _run
File "/srv/app/tools/invoices.py", line 42, in get_invoice
row = db.one("SELECT * FROM invoices WHERE id = %s", int(invoice_id))
ValueError: invalid literal for int() with base 10: 'INV-2291'
The useful facts are on the last two lines: the tool expected a number, and the model sent a string with a prefix. The tool result becomes:
{
"is_error": true,
"content": "{\"errorCategory\": \"validation\", \"isRetryable\": true, \"error\": \"ValueError\", \"message\": \"invoice_id must be digits only\", \"got\": \"INV-2291\", \"next\": \"Retry with the number part only, for example 2291.\"}"
}
That is about 60 tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. instead of 600, and the model can fix its input on the next call. Log the full trace on your side, with a request id, so engineers can still debug.
Coding agents are different
When an agent’s job is to fix code, the error is the task. Still trim it:
- Keep the failing test name, the assertion and the expected and actual values.
- Keep frames in the project’s own files, with line numbers; drop frames inside installed packages.
- If 40 tests fail with the same error, send the first one in full and a count of the rest.
- Cap the size, and say what you cut: “38 similar failures omitted”.
Common mistakes
- Passing secrets through. Database errors often echo connection strings. Scrub before returning.
- Rewording errors into vagueness. “Something went wrong” is as unhelpful as 300 lines.
- Hiding the input. Without the bad value, the model cannot see what to change.
- No loop guard. If the same error comes back twice, return a non-retryable error and suggest escalating, so the loop ends.
Key points
- Send the model the error type, a short message, the input that caused it and a suggested next step, not the whole trace.
- Keep the few frames from your own code that point at the cause; drop framework noise and repeated lines.
- Strip secrets, tokens, internal hostnames and personal data before any error text leaves the tool.
- For coding agents, the failing test name, assertion and the line in the user's code are the useful part.
Trim a stack trace for the model
Turn a raw exception into a short, safe tool result with a clear next step.
You will have: A to_tool_result() function and a structured error about half the size of the raw trace, with no secrets.
Steps
- Run the starter: the whole trace, secret included, goes to the model.
- Build a JSON body with the category, error type, a short message, the bad input and a next step.
- Keep only your own frames and scrub the connection string and server paths.
- Run it and compare the sizes.
Done when
- The result names ValueError and the input INV-2291.
- Only the tools/invoices.py frame is kept.
- The script prints secret in result: False.
Open in the Playground No API key needed.
Starter code (Python)
# Turn a raw exception and a long trace into a short, safe tool result for the model.
import json
import re
RAW_TRACE = """Traceback (most recent call last):
File "/srv/app/vendor/web/handler.py", line 233, in dispatch
File "/srv/app/vendor/db/pool.py", line 411, in execute
File "/srv/app/vendor/db/cursor.py", line 88, in _run
File "/srv/app/tools/invoices.py", line 42, in get_invoice
row = db.one(SQL, int(invoice_id))
ValueError: invalid literal for int() with base 10: 'INV-2291'
DB_URL=postgres://app:demo-pass@db-internal-7:5432/billing"""
def get_invoice(invoice_id):
return {"id": int(invoice_id)} # fails for "INV-2291"
def to_tool_result(exc, bad_input, trace):
# TODO: instead of the whole trace, return a JSON body with errorCategory, isRetryable, the error type,
# TODO: a short message, the bad input, only your own frames (not /vendor/) and a suggested next step.
# TODO: scrub the connection string and the /srv/app/ prefix before anything is returned.
return {"is_error": True, "content": trace}
try:
get_invoice("INV-2291")
except ValueError as e:
result = to_tool_result(e, "INV-2291", RAW_TRACE)
print(result["content"])
print(f"size: about {len(RAW_TRACE) // 4} tokens raw, {len(result['content']) // 4} tokens trimmed")
print("secret in result:", "demo-pass" in result["content"])
Show a solution
# Turn a raw exception and a long trace into a short, safe tool result for the model.
import json
import re
RAW_TRACE = """Traceback (most recent call last):
File "/srv/app/vendor/web/handler.py", line 233, in dispatch
File "/srv/app/vendor/db/pool.py", line 411, in execute
File "/srv/app/vendor/db/cursor.py", line 88, in _run
File "/srv/app/tools/invoices.py", line 42, in get_invoice
row = db.one(SQL, int(invoice_id))
ValueError: invalid literal for int() with base 10: 'INV-2291'
DB_URL=postgres://app:demo-pass@db-internal-7:5432/billing"""
def get_invoice(invoice_id):
return {"id": int(invoice_id)} # fails for "INV-2291"
def scrub(text):
text = re.sub(r"://[^\s:@]+:[^\s@]+@[^\s/]+", "://[hidden]", text)
return re.sub(r"/srv/app/", "", text)
def own_frames(trace):
frames = re.findall(r'File "([^"]+)", line (\d+), in (\w+)', trace)
return [f"{scrub(f)}:{n} in {fn}" for f, n, fn in frames if "/vendor/" not in f]
def to_tool_result(exc, bad_input, trace):
body = {
"errorCategory": "validation",
"isRetryable": True,
"error": type(exc).__name__,
"message": "invoice_id must be digits only",
"got": bad_input,
"where": own_frames(trace),
"next": "Retry with the number part only, for example 2291.",
}
return {"is_error": True, "content": json.dumps(body)}
try:
get_invoice("INV-2291")
except ValueError as e:
result = to_tool_result(e, "INV-2291", RAW_TRACE)
print(result["content"])
print(f"size: about {len(RAW_TRACE) // 4} tokens raw, {len(result['content']) // 4} tokens trimmed")
print("secret in result:", "demo-pass" in result["content"])
Finished the chapter? Take the chapter check.