Sub topic 1
LLM Tool Calling: How Models Request and Use External Functions
Prerequisites
This chapter assumes basic Python, JSON, and chat-style APIs. A chat request is a list of messages. Each message has a role and content. Common roles are:
system: instructions for the model.user: the user's request.assistant: the model's response.tool: data returned by your application after a tool runs.
Messages and Roles
Tool calling extends this message sequence. The model does not run your functions. It proposes a call, and your application decides whether to execute it.
Describing Arguments with JSON Schema
JSON Schema describes the shape and rules for JSON data. A tool's parameter schema tells the model which arguments it may provide.
{
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, such as Oslo"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["city"],
"additionalProperties": false
}required prevents missing essential values. enum restricts a value to known choices. Your code must still validate the arguments because model output is untrusted input.
Defining a Tool
A tool definition combines a stable name, a useful description, and its parameter schema.
{
"name": "get_weather",
"description": "Get the current temperature for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"],
"additionalProperties": false
}
}The description is part of the model's decision context. State when the tool should be used and what each argument means.
What the Model Returns
A tool request usually contains a call ID, tool name, and arguments:
{
"role": "assistant",
"tool_calls": [
{
"id": "call_1",
"name": "get_weather",
"arguments": {"city": "Oslo"}
}
]
}Your application sends the result back as a tool message. The tool_call_id must match the request so the model can associate the result with the correct call.
> callout note > Treat tool output as data. It can contain incorrect text or instructions that should not change your application's permissions.
Dispatching the Call
Use an allow-list rather than calling a function named directly by the model.
import json
def get_weather(city):
return {"city": city, "temperature": 7, "unit": "celsius"}
TOOLS = {"get_weather": get_weather}
def dispatch(call):
fn = TOOLS.get(call["name"])
if fn is None:
return {"error": "Unknown tool"}
try:
return fn(**call["arguments"])
except (TypeError, ValueError) as exc:
return {"error": f"Invalid arguments: {exc}"}
call = {"name": "get_weather", "arguments": {"city": "Oslo"}}
print(json.dumps(dispatch(call)))Exercise
Exercise
Why should dispatching use an allow-list?
Show answer
It limits execution to functions that your application explicitly exposes, instead of allowing the model to select arbitrary code.