Start learning free

LESSON 39 OF 129 · AI ENGINEERING: TOOL USE

Run It and Send the Result

Practice

The model asked for lookup_order and stopped. It can't run the function: your program does. Then the model has to see the result, and it remembers nothing between calls. So the next call must carry the whole story: the question, the model's request, and the result.

The model's request goes back as an assistant message whose content is the reply's whole list of blocks. The result goes in a user message, inside a tool result block with three keys: "type" (always "tool_result"), "tool_use_id" (the id of the request it answers) and "content" (the result as text).

The model reads text, so a dictionary is turned into a JSON string first:

weather = {"temp": 21}
text = json.dumps(weather)
print(text)    # {"temp": 21}

With the story complete, the model stops with "end_turn" and answers with the order's real status and date. 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
Result: {'id': 4, 'ordered': '2026-04-18', 'status': 'shipped'}
Stop reason: end_turn
Answer: Good news: order 4 has shipped. You placed it on 2026-04-18.

Your task: run lookup_order with the request's input and print the result. Append the model's turn to messages. Build a tool_result block with the same id and the result as JSON text, and append it in a user message. Call the model again and print the new stop reason and the answer.


Assignment
Follow the Coding Tutorial to run the tool, send its result to the model and print the model's answer.


Hint
The id in the tool result must be the one the model sent: tool_use.id. The content of the last user message is a list that holds the block, not a string.


STEP 1 OF 11
    Ctrl + Enter to check