Start learning free

LESSON 87 OF 129 · AI ENGINEERING: AGENTS

Knowing When to Stop

Practice

Budgets stop a run that goes wrong. A run that goes right should stop on purpose. Until now the agent stopped when the model wrote plain text, but plain text can be the answer, a question, or just "I'll check that next". In this lesson the agent gets one clear way to say I'm done: a tool named finish. No function stands behind it. It is a signal: your loop sees the call, prints its summary and ends the run.

Going in circles: an agent can also get stuck. A tool fails, the model tries the very same call again, it fails again, and so on until a budget runs out. You catch that early if you remember the last thing you saw. Here is the idea on a list of words:

last = ""
for word in ["red", "blue", "blue", "green"]:
    if word == last:
        print("twice in a row:", word)
        break
    last = word

This prints twice in a row: blue. A tool call is a name and an input, not a word, so you first write it as one piece of text. json.dumps({"product_id": 7}) gives the text {"product_id": 7}, and two equal inputs always give the same text.

When your code is done, the run on order 6 ends because the agent called finish. Then the check sends the agent after order 60, which doesn't exist, and your loop stops it at step 2 instead of step 6:

Step 4
  Summary: Order 6 isn't late: it was cancelled, so nothing was sent. …
Stopped: the agent called finish
Steps: 4 Cost: 0.0062
…
Step 1
  Thought: Plan step 1: I look up order 60.
  Tool: lookup_order {'order_id': 60} -> {'error': 'Order not found'}
Step 2
Stopped: the same call twice in a row: lookup_order {"order_id": 60}
Steps: 2 Cost: 0.0034

Your task: the agent with its plan and its budgets is already in the editor. Add the finish tool and tell the agent to use it. Catch the call in the loop, print its summary and stop with the reason the agent called finish. Then stop a run that makes the same call twice in a row, and print that reason too.


Assignment
Follow the Coding Tutorial to give the agent a finish tool and to stop it when it repeats a call.


Hint
Both checks stand above the run_tools line, so finish and a repeated call are never run as tools. Store this call in last_call only after the comparison.


STEP 1 OF 11
    Ctrl + Enter to check