Sub topic 10
Errors and Test Output as Feedback
This chapter assumes you have read the earlier chapters on tool calls and the agent loop. You should know that the harness runs a tool and appends the result to the messages as text. Here you will see why errors are the main signal an agent uses to correct itself, and how to build a harness that returns useful errors.
Why errors are input, not crashes
A language model call is stateless, and the model cannot observe your machine. It only sees text in the messages. When a tool fails, the model learns about it only if the harness puts the failure into a tool result message.
This makes the harness's policy for errors simple to state: catch the exception, turn it into text, and return it as the tool result. Do not let an exception from a tool end the whole run. The loop from the earlier chapter does this:
try:
result = TOOLS[call["name"]](**call["arguments"])
except Exception as e:
result = f"error: {e}"The model then reads error: ... on its next step and can retry with different arguments, pick a different tool, or explain that it is blocked. The error is feedback in the same sense as a compiler message is feedback for a human programmer.
Kinds of feedback
Not all failures look alike. The harness sees several different categories, and each one needs a slightly different treatment.
| Category | Example | Who caused it | Typical model response |
|---|---|---|---|
| Invalid call | Unknown tool name, missing required argument | The model | Fix the call and retry |
| Tool runtime error | `FileNotFoundError` for a wrong path | The model, usually | List the directory, then retry |
| Command failure | A shell command exits with a nonzero status | The code or the environment | Read the output, change the code |
| Test failure | An assertion fails in a test run | The code being edited | Locate the bug, edit, rerun |
| Timeout | A command runs past its limit | The command or the environment | Run something smaller or narrower |
| Policy denial | The user rejected an approval prompt | The user or the rules | Stop or choose another approach |
A test failure is a special and valuable case. A test run is a check that the harness can repeat as often as needed, so it gives the agent a way to tell whether its last edit worked. Many agent workflows rely on this pattern: edit, run the tests, read the failures, edit again.
Writing error messages the model can use
A model can only act on what the message says. Compare two results for the same mistake.
Vague:
error: [Errno 2]Specific:
error: file not found: src/utils/pars.py (workspace root: /work/app). Did you mean src/utils/parse.py?The second version names the path the model asked for, states what is wrong, and suggests a next step. A good error message answers three questions: what was attempted, why it failed, and what the model could try next.
Here is a version of read_file that returns messages of this kind. It builds on the registry from earlier chapters.
from pathlib import Path
WORKSPACE = Path("/work/app").resolve()
MAX_CHARS = 20000
def read_file(path):
target = (WORKSPACE / path).resolve()
if WORKSPACE not in target.parents and target != WORKSPACE:
return f"error: path {path!r} is outside the workspace"
if not target.exists():
siblings = sorted(p.name for p in target.parent.glob("*"))[:10] if target.parent.exists() else []
return (f"error: file not found: {path}. "
f"Files in that directory: {siblings}")
if target.is_dir():
return f"error: {path} is a directory, not a file. Use a listing tool."
text = target.read_text(errors="replace")
if len(text) > MAX_CHARS:
return text[:MAX_CHARS] + f"\n[truncated: file has {len(text)} characters]"
return textThree details matter here. The function returns a string for expected failures instead of raising, so the model gets a hint instead of a bare exception text. It checks that the resolved path stays inside the workspace, which is a safety control covered in a later chapter. It marks truncation explicitly, so the model knows it did not see the whole file.
Command output: exit codes, streams, and tail truncation
The run_command tool from the topic's earlier code returns (r.stdout + r.stderr)[-5000:]. It keeps the last 5000 characters. For command output this is a deliberate choice: build and test tools print the summary and the most important errors at the end, so the tail is usually more useful than the head.
That version has two gaps. It does not report the exit code, and it does not handle a timeout, which raises subprocess.TimeoutExpired. The loop would catch that exception, but the message would be unhelpful. A more informative version follows.
import subprocess
def run_command(command):
try:
r = subprocess.run(command, shell=True, capture_output=True,
text=True, timeout=30)
except subprocess.TimeoutExpired:
return "error: command timed out after 30 seconds. Try a narrower command."
output = r.stdout + r.stderr
if len(output) > 5000:
output = "[earlier output omitted]\n" + output[-5000:]
return f"exit code: {r.returncode}\n{output}"The exit code is the most compact signal of success. By convention, 0 means success and anything else means failure. Putting it on the first line means it survives even if the model skims.
A worked example: fixing a failing test
Suppose the task is "make the tests pass" in a project with one bug. The trace below shows the messages the harness sends over four steps. Tool calls are shortened.
user: Make the tests in tests/test_price.py pass.
assistant: [tool_call run_command: pytest tests/test_price.py -q]
tool: exit code: 1
FAILED tests/test_price.py::test_discount - assert 90.0 == 91.0
price.py:7: in apply_discount return total * (1 - rate)
assistant: [tool_call read_file: price.py]
tool: def apply_discount(total, rate):
return total * (1 - rate)
assistant: [tool_call edit_file: price.py, replace body to round to 2 decimals ...]
tool: error: old_text not found in price.py (whitespace differs?)
assistant: [tool_call read_file: price.py]
tool: (same content, with a tab character before return)
assistant: [tool_call edit_file: price.py, old_text uses the tab]
tool: ok: 1 replacement made
assistant: [tool_call run_command: pytest tests/test_price.py -q]
tool: exit code: 0
1 passed in 0.02s
assistant: The test now passes. I changed apply_discount in price.py.Look at what each result gave the model. The first test run gave a failing assertion and a file and line number. The failed edit gave a specific reason, and the model reacted by rereading the file instead of repeating the same call. The last test run, with exit code 0, was a reason to stop. The final reply has no tool calls, so the loop ends.
The cycle looks like this:
Failure modes in feedback loops
Feedback can go wrong in predictable ways.
- Repeating the same failing call. The model sends the same arguments again and again. A vague error message makes this more likely. A step limit prevents it from running forever, and the harness can also detect repeated identical calls and add a note to the result.
- Flooding the context. A test suite that prints thousands of lines fills the context window. Truncate, prefer the tail, and let the model run narrower commands.
- Hidden truncation. If the output is cut without saying so, the model may reason from partial data. Always mark the cut.
- Fixing the check instead of the code. An agent told to make the tests pass may edit the tests, delete an assertion, or special-case the expected value. Passing tests only show that the checks pass. Review the diff, and state in the task or project instructions that the tests must not be weakened.
- Trusting stale output. Results from an earlier test run stay in the context after later edits. The model may refer to a failure that is already fixed. Rerun the test after each edit instead of relying on old output.
- Misreading exit codes. Some tools print "error" text yet exit with 0, and some exit nonzero for warnings. Pass the exit code and the output together so the model can weigh both.
Designing feedback: a checklist
- Return errors as tool results. Reserve exceptions that stop the loop for harness bugs.
- Say what was attempted, why it failed, and one thing to try.
- Include the exit code with every command result.
- Keep the tail of long command output and mark truncation.
- Set a timeout on every command.
- Give the agent a fast, narrow way to run the relevant checks.
- Cap the number of steps, and consider flagging repeated identical failures.
Exercise
A tool result reads error: failed. The model then sends the same call with the same arguments four times. Name the likely cause in the harness, and give two changes that would reduce the problem.
Show answer
The error message carries no information about what was attempted, why it failed, or what to try next, so the model has no basis for changing its call. Two fixes: rewrite the message to state the cause and a suggestion (for example, the missing path and the files in that directory), and detect repeated identical calls in the harness so it adds a note or stops the run. The step limit also bounds the damage.
Exercise
Why does run_command keep the last 5000 characters of output instead of the first 5000, and what should it also report that the original version leaves out?
Show answer
Build and test tools usually print their summary and final errors at the end, so the tail is more informative than the head. The original version leaves out the exit code, which is the shortest reliable signal of success or failure, and it also gives no clear message on timeout or any marker that the output was cut.
Exercise
After an edit, an agent reports "all tests pass" but the last test run in the trace happened before the edit. What went wrong, and what harness or prompt change helps?
Show answer
The model relied on stale output that stayed in the context. The fix is to rerun the tests after every edit and base the final report on that fresh result. Project instructions can require a test run after each change, and the harness can make the final-answer step depend on a passing run.