The model never runs code. It writes a request in JSON: which tool, which arguments. Your program reads it, runs the function, and sends back the result.
AI · beginner · 8 min · 11 steps · free
What you'll learn
Describe a tool to a model with a schema
Parse the model's JSON request
Run the tool and return the result as a message
tool_calling.py
import json
# The program tells the model which tools exist, described like this.
schema = {"name": "get_weather", "parameters": {"city": "string"}}
def get_weather(city):
return {"Chennai": 33, "Delhi": 28}.get(city)
tools = {"get_weather": get_weather}
# The model does not run anything. It replies with a request, written as JSON.
reply = '{"tool": "get_weather", "arguments": {"city": "Chennai"}}'
call = json.loads(reply)
result = tools[call["tool"]](**call["arguments"])
message = {"role": "tool", "content": str(result)}
print(message)
Step by step
json reads and writes the JSON text that models use for tool requests.
The schema: a description of the tool, sent to the model along with the question. It says the tool is called get_weather and takes a city.
The real function, in your program.
A table from tool names to functions, so a name in the model's reply can be looked up.
The model's reply to "How hot is it in Chennai?": not an answer, but a request in JSON.
json.loads turns the text into a Python dict.
Look up the tool by name and call it with the arguments. ** passes the dict as named arguments: city="Chennai".
The tool looks up Chennai: 33.
The result is 33.
Wrap the result in a "tool" message to send back to the model.
This message goes back to the model, which can now write: "It is 33°C in Chennai." The agent lesson runs this same exchange in a loop.
Common mistakes
Trusting the model's arguments blindly: check them before running anything
Forgetting to send the result back, so the model never sees it
Best practices
Validate arguments, limit what tools can do, and ask the user before anything risky
Key takeaways
Tools are described to the model with a schema.
The model answers with a structured request (JSON): tool name and arguments.
Your program checks it, runs the function and returns the result.
The model uses the result to write its final answer.
Check yourself
The model replies {"tool": "get_weather", "arguments": {"city": "Delhi"}}. What does your program do?
Answer: Call get_weather(city="Delhi") and send back 28. The program runs the tool and returns its result to the model.
Why check the arguments before running a tool?
Answer: The model can make mistakes or be tricked. Treat the model's request like any untrusted input.