Sub topic 5
Tool calling: letting the model request actions
This chapter assumes you can write Python, read JSON, and have called a chat-style LLM API before. It covers how a model asks for an action and how your code carries it out.
The core idea
A language model only produces text. It cannot read a file, query a database, or check the weather. Tool calling closes that gap. You describe a set of functions to the model. When the model decides one is needed, it replies with a structured request, such as a function name and a JSON object of arguments, instead of a normal answer.
The model never runs anything. Your program does. This split matters for safety, because your code decides whether a requested call actually happens.
What the model sees
For each tool you supply a name, a description, and an argument schema, usually JSON Schema. The model picks a tool from these descriptions alone, so they act as instructions. A later chapter covers writing them well.
Dispatching calls in Python
A registry maps tool names to functions. The dispatcher returns errors as text, so the model can read the failure and try again. A crash would end the run.
import json
def get_weather(city: str) -> str:
# Stand-in for a real API call.
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return TOOLS[name](**arguments)
except Exception as exc:
return json.dumps({"error": str(exc)})The model can request a tool that does not exist, or pass wrong arguments. Both cases land in the error branches above, and TypeError from a bad argument name is caught by the except.
Testing without a real model
A scripted model lets you test the plumbing deterministically. It asks for the tool once, then answers. The loop that drives it is the subject of the next chapters, so it appears here only so the example runs.
def run_agent(call_model, user_goal: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": user_goal}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": reply.get("tool_call")})
call = reply.get("tool_call")
if call is None:
return reply["content"]
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
return "Stopped: step limit reached."
def fake_model(messages):
# Scripted stand-in for a real model, useful for testing the loop.
if messages[-1]["role"] == "user":
return {"content": None, "tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
return {"content": "It is 18 C in Oslo.", "tool_call": None}
print(run_agent(fake_model, "What is the weather in Oslo?"))This prints It is 18 C in Oslo. The tool result is appended to the history, so the model sees it on its next turn.
Common errors
- Trusting arguments. Model output is untrusted input. Validate it before use.
- Raising instead of returning errors. An exception stops the run. A returned error message lets the model recover.
- Dropping the tool result. If you do not append the result to the history, the model repeats the same call.
- Non-string results. Return text, usually JSON, because that is what goes back into the conversation.
Exercise
Why does run_tool return a JSON error string for an unknown tool name, rather than raising an exception?
Show answer
The error text goes back into the history, so the model can read what went wrong and choose a different call or answer. An uncaught exception would end the program and the model would never see the failure.