Tutorials · Chapter D (4/4) · ~11 min
Tools in code
Play → read → next
Wire a tool call in Python — model chooses, your code runs, result returns.
Code Lab
Tools in code
Wire function calling: tool name → function → result → reply.
Recap
What you just did
You implemented the tool loop builders ship: schemas the model can choose, a dispatcher in your code, and a second model turn with the tool result. That’s how agents stop hallucinating the weather and start reading an API.
Teach
How it works
def get_weather(city: str) -> str:
return f"72F and clear in {city}" # stand-in for an API
tools = {"get_weather": get_weather}
# model might return: name="get_weather", args={"city": "Lisbon"}
name, args = "get_weather", {"city": "Lisbon"}
result = tools[name](**args)
# send result back in the next messages turn
print(result)
- Declare tools (name, args, description)
- Model selects one (or none)
- Your code runs it — never trust invented results
- Model answers using the real output
Mental model: LLM proposes; Python disposes.
Use it
When you'd use this
- Checking calendars, tickets, or inventory mid-chat
- Safe math via a calculator tool
- “Book / fetch / search” actions behind your auth
Watch out
Watch out
Validate arguments. Don’t let freeform strings delete files or spend money without guards. If the tool fails, say it failed — don’t let the model invent a success.
Try next
Try this next
Send a user message that should not call a tool. Confirm your dispatcher stays quiet.