Start learning free

LESSON 47 OF 129 · AI ENGINEERING: TOOL USE

Only Allowed Actions

Practice

A model writes the name of the tool it wants as plain text. It usually picks a name from your tools list, but nothing forces it to. In this lesson a customer wants money back, and the model asks for a tool named issue_refund. You never offered that tool: the model made the name up.

Your functions dictionary is the allow-list: the only actions the model can set off are the ones in it. Before you use a name that came from outside, check it with not in. Inside a loop, continue then skips the rest of the body for that one item:

prices = {"tea": 2, "coffee": 3}
for drink in ["tea", "wine", "coffee"]:
    if drink not in prices:
        print("Not on the menu:", drink)
        continue
    print(drink, "costs", prices[drink])

Without the check, prices["wine"] stops the program with a KeyError. With it, the loop prints a message for wine and goes on to coffee.

A refused request still needs an answer: every tool_use block needs a tool_result, also the ones you refuse. No function runs, so the answer is a fixed text from your own code, with is_error set to True so the model knows its request failed. Your program must print:

Model: I'm sorry about that. I'll refund order 7 and check its status.
Not allowed: issue_refund {'amount': 62, 'order_id': 7}
Tool: lookup_order {'order_id': 7} -> {'id': 7, 'ordered': '2026-05-30', 'status': 'shipped'}
Tool results sent in one message: 2
Answer: I can't send refunds myself. Order 7 has shipped, so you can still return it, and the shop's team refunds you when it arrives. Do you want me to start the return?

The lesson's check then prints that the model was called 2 times, that 0 refunds were sent, and what the model got back for issue_refund.

Your task: in run_tools, refuse every tool whose name is not in functions: print "Not allowed:" with the name and the input, append a tool_result with the text "This tool is not allowed." and is_error True, and go on to the next block with continue.


Assignment
Follow the Coding Tutorial to turn the functions dictionary into an allow-list, so a tool name the model made up is answered with an error and never crashes the program.


Hint
All three steps go above the function = functions[block.name] line. The refused result has the same four keys as the one at the end of the loop, but its content is a plain string and is_error is always True. Without continue the code still reaches the lookup and crashes.


STEP 1 OF 4
    Ctrl + Enter to check