LLM Tool Calling Explained with a Working Example
Ask the chat from lesson 3 "Do I need an umbrella in Pune today?" and it can only guess: a model knows its training text and your messages, not today's weather. Your program can look the weather up. LLM tool calling connects the two: the model asks your code to run a function, then answers from what it returns. You will build it around a fake get_weather(city).
The model asks, your code runs
A model only produces text; it cannot open a website or run Python. A tool is a function in your program that you describe to the model, so it knows it may ask for it. In tool calling, the model replies with a request instead of an answer: the function's name and its arguments, the input values to pass. Your program decides whether to run it.
Under the hood it is still text: models such as llama3.2:3b were trained to write calls in a fixed format, which Ollama turns into structured data. For a model without that training, Ollama answers HTTP 400 with an error ending in does not support tools.
In the sequence diagram, notice where step 4 happens: on your app's line, not the model's.
Describe a tool: name, description and parameters
The model knows your tool only from its description. Each item in the tools list of /api/chat has "type": "function" and three fields: a name, a plain-language description, and parameters, a JSON schema of the arguments like those in lesson 4. This is the lab's definition in weather_tool.py:
WEATHER_TOOL = {
"type": "function",
"function": {
"name": "get_weather",
"description": "Get today's weather and chance of rain for one city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "A city name, for example Pune"},
},
"required": ["city"],
},
},
}
The script sends "tools": [WEATHER_TOOL] with the request from lesson 2, at temperature 0 for repeatable choices. Ollama writes the tools into the prompt, so descriptions cost tokens, and the model picks a tool by reading them: say what it returns and when it helps.
To keep the tool deterministic, giving the same output on every run, get_weather makes no network call: it reads FAKE_WEATHER, fixed data for five cities, where Pune has rain showers and an 80% chance of rain. An unknown city returns an error key rather than raising an exception, so the model has something to read.
Read the reply: tool_calls instead of text
When the model wants a tool, the reply's message has an empty content and a tool_calls list. The aha of the annotated JSON: the reply is a request built from your description, and nothing has run yet.
In Ollama's API, arguments is a JSON object, so response.json() already gives you a Python dictionary. The id is random: call_ plus eight characters. One reply can hold several calls, each with its own index (asking about Pune and Mumbai may bring two), so always loop over the list. The test is message.get("tool_calls") or []: an empty list means content is the final answer.
Run the function and send the result back
Lesson 3 promised a fourth role, tool; this is it. First append the model's reply, with its tool_calls, to messages, so the history shows what was asked. Then add one tool message per call: content holds the result as a string, tool_name names the function, and tool_call_id repeats the call's id. The core of the script, simplified:
messages.append(message) # the request, with its tool_calls
for call in tool_calls:
result = run_tool_call(call) # check, then run the function
messages.append({"role": "tool", "tool_name": call["function"]["name"],
"tool_call_id": call["id"], "content": json.dumps(result)})
message = ask(args.model, messages, tools, args.timeout) # call the model again
On the next call the model has not been waiting like the receptionist: each call stands alone, so it sees the result only because the history now holds it. It writes the final text, or asks for another tool. The flowchart's arrow back to the top is that loop: it ends only when a reply has no tool_calls, so the lab caps it at 3 model calls. The agent in lesson 6 is this loop with more tools and safety rails.
Run the lab
With Ollama from lesson 1 running and the labs cloned, these commands make a virtual environment, install requests and pydantic, and ask the question:
cd course-labs/building-llm-apps/05-tool-calling
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python3 weather_tool.py 'Do I need an umbrella in Pune today?'
pip should end with Successfully installed (or "already satisfied"). Then the script logs each step; the last line is the model's wording and varies:
Question: Do I need an umbrella in Pune today?
[call 1] sending 2 messages to llama3.2:3b with 1 tool: get_weather
[call 1] model requested get_weather with {"city": "Pune"}
[call 1] get_weather returned {"city": "Pune", "condition": "rain showers", "temperature_c": 24, "chance_of_rain_percent": 80}
[call 2] sending 4 messages to llama3.2:3b with 1 tool: get_weather
[call 2] model answered with text
Answer: Yes, take an umbrella: Pune has rain showers today and an 80% chance of rain.
It worked if call 1 ends with a tool request, the returned line shows the fixed Pune data, and the answer uses it. Call 2 sends 4 messages: the lab's short system prompt, your question, the request and the result. cannot connect to Ollama means the container is stopped; No module named 'pydantic' means the environment is not active.
Pitfalls: wrong tools, invented arguments, the shell
Small models call a tool when none is needed, pick the wrong one, invent a tool name, or invent arguments, such as an extra "date": "today" or a city you never mentioned. Treat every call as untrusted input, data you check before acting on it, because a model wrote it after reading text you do not control.
The lab checks twice. TOOLS is an allow-list, a dictionary of the only names the script will run. Then a pydantic class, as in lesson 4, checks the arguments, and extra="forbid" rejects any the tool does not have:
class WeatherArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
city: str = Field(min_length=1, max_length=40)
TOOLS = {"get_weather": (get_weather, WeatherArgs)}
When a check fails, the function does not run. The error goes back as the tool result, for example invalid arguments for get_weather: date: Extra inputs are not permitted, so the model can fix its call or tell the user. That is why the cap leaves room for a third call.
Never run model-supplied text as a shell command. subprocess.run(f"grep {city} cities.txt", shell=True) looks harmless until the city is Pune; rm -rf ~: the shell, the program that runs command lines, reads ; as the end of one command and runs the next. Look values up in a dictionary, or pass a list of arguments without shell=True. Text that hijacks a model on purpose, prompt injection, comes in lesson 13.
Check yourself
A teammate says "the model looked up the weather". What actually happened, and which program read the weather data?
The model only wrote a request in tool_calls. Your app checked it and ran get_weather, and the model read the result on the next call. A model produces text; it cannot run anything.
The model calls get_weather with a city and an extra "date": "tomorrow". Why send an error back instead of dropping the date or raising an exception?
Dropping it answers a different question, and an exception ends the chat with nothing. Sent as the tool result, the error lets the model fix the call or explain that it only has today's weather.
Why is a run_command(cmd) tool that hands the model's text to a shell unsafe, even if the system prompt says "only run safe commands"?
The arguments are untrusted: a confused model, or injected text, can produce any command, and a system prompt is a request, not a rule. Narrow tools with checked arguments limit the worst call to what the tool allows.