Start learning free

LESSON 38 OF 129 · AI ENGINEERING: TOOL USE

The Model Asks for a Tool in Python

Practice

When the model wants a tool, its reply is more than one text. reply.content is a list of blocks, and each block says what it is in its type: "text" for words, "tool_use" for a request to use a tool.

Don't count on positions. The model may skip the text, or ask for two tools at once, so the request is not always block 1. Go through the list and check what each item is. The same idea on a basket:

for item in basket:
    if item["kind"] == "gift":
        gift = item

A tool request has three parts. name is the tool the model picked. input is a Python dictionary, shaped the way your input_schema says. id names this one request: you will send it back with the tool's result.

The reply also says why the model stopped, in reply.stop_reason. Here it is "tool_use": the model isn't done, it stopped to wait for the tool. Your program must print:

Stop reason: tool_use
Text: I'll look up order 4 for you.
Tool: lookup_order
Input: {'order_id': 4}
Id: toolu_011

Your task: print the stop reason. Then loop over reply.content: print the text of a text block, and keep the tool_use block in a variable named tool_use. After the loop, print the request's name, input and id.


Assignment
Follow the Coding Tutorial to find the tool request in the model's reply and print its parts.


Hint
Compare block.type with "text" and with "tool_use". The three prints of the request go after the loop, at the left edge, each with its label.


STEP 1 OF 9
    Ctrl + Enter to check

    Ai Tool Request in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free