Everything a tool returns goes into messages, and the whole list is sent to the model again at every step. A long file is paid for many times, and a model that goes round in circles never stops by itself. An agent needs two limits: one on the output of its tools, and one on the number of its steps.
The output limit: you already shorten one line of text. Your short function keeps the first characters and puts ... where it cut, like this:
title = "A very long product name that does not fit on the label"
if len(title) > 20:
title = title[:20] + "..."
print(title) # A very long product ...
For a tool result you do the same with lines, and you keep both ends: the start shows what the output is, and the end is where a command puts its result or its error. A marker in the middle, like ... 370 lines cut ..., tells the model that something is missing.
The step limit: the loop counts the tool calls it has run. When the count reaches the limit, the loop ends and the program says so. A run that fails in silence looks the same as a run that is still working.
In this lesson the project has a log of 400 lines. The course model reads all of it, then switches between two wrong fixes. With both limits, your program must print:
Step 2: read_file {'path': 'orders.log'}
Model: The log lists orders, and the middle of it was cut. Nothing in it is about the tests. I'll run them.
...
Step 8: run_tests {}
Tests: FAILED (failures=1)
Stopped after 8 steps, without an answer
Trace: list_files > read_file > run_tests > read_file > write_file > run_tests > write_file > run_tests
Tests pass after the run: False
orders.log has 400 lines. Lines the model got: 31
Line 16: ... 370 lines cut ...
Your task: write cut(text), which leaves a result of up to 30 lines alone and cuts a longer one to its first 15 lines, a marker and its last 15 lines. Pass every tool result through it. Then stop the loop after MAX_STEPS = 8 steps with the line Stopped after 8 steps, without an answer, and print Answer: only when the model stopped by itself.
Assignment
Follow the Coding Tutorial to give your agent an output limit and a step limit.
Hint
The cut keeps 2 * KEEP lines, so compare the number of lines with that before you cut anything. The step check is the first thing in the loop, before run_tools, so the ninth tool call never runs.
Free plan: 30 tutor messages. PRO is unlimited.
