Sub topic 4
Tool calling in one page
This chapter assumes you know basic Python, what a prompt and a completion are, and how a classic retrieve-then-generate pipeline works. It covers the one mechanism the rest of the tutorial relies on: letting a model request that your code run a function.
What tool calling is
A language model only produces text. It cannot open a file, query a database, or search your documents. Tool calling (also called function calling) is a protocol that works around this limit.
- You describe a set of functions to the model: a name, a plain-language description, and a schema for the arguments.
- The model replies either with a normal answer or with a structured request, such as "call
search_docswithquery = 'rate limits'". - Your code runs the function. The model never executes anything itself.
- You send the function's result back to the model as a new message.
- The model reads the result and either answers or requests another call.
The model decides. Your code executes. This split is the whole idea, and it is why retrieval can become something the model chooses to do instead of a step that always runs.
The three parts of a tool definition
A tool definition has three parts, and the model reads all of them as text.
- Name. A short identifier such as
search_docs. Use a verb and a noun. - Description. Tells the model when to use the tool and when not to. This is the most important part for retrieval.
- Parameter schema. A JSON Schema object that lists each argument, its type, and which ones are required.
Here is a retrieval tool defined this way. Exact field names differ between model providers. Some call the schema parameters, others input_schema. The content is the same.
{
"name": "search_docs",
"description": "Search the product documentation. Use it for questions about product behavior, configuration or limits. Do not use it for greetings or general knowledge. Call it again with a different query if the first results do not answer the question.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "A short, self-contained search query. Do not rely on earlier messages for meaning."
},
"top_k": {
"type": "integer",
"description": "Number of passages to return, from 1 to 8."
}
},
"required": ["query"]
}
}Look at what the description does. It names the subject area, so the model knows the tool fits product questions. It says what to skip, so the model does not search for "hello". It allows a retry, so the model knows a weak result is not the end. The query description tells the model to write a standalone query, because the search engine cannot see the conversation.
What the model sends back
When the model wants a tool, its reply contains one or more tool calls. Each call has an id, a tool name, and arguments. Providers differ on whether the arguments arrive as a parsed object or a JSON string, so check yours. In this chapter we use a provider-neutral shape:
{
"content": "",
"tool_calls": [
{"id": "call_1", "name": "search_docs", "arguments": {"query": "API rate limit per minute", "top_k": 4}}
]
}Three points matter here.
- The
idlinks the call to its result. When you send the result back, you include the same id so the model knows which request it answers. - A reply can hold several calls at once. Your code must run all of them and return a result for each.
- A reply with no tool calls is the final answer. This is how a loop knows when to stop.
Running the call
The model only names a tool and supplies arguments. Your code looks the tool up, runs it, and packages the result. This is the function behind the schema above.
def search_docs(query, top_k=4):
# Wrap your own retriever so the model sees ids and text, never raw vectors.
top_k = max(1, min(int(top_k), 8))
chunks = my_retriever.search(query, top_k) # your retriever, returns [{"id": str, "text": str}]
return [{"id": c["id"], "text": c["text"][:1200]} for c in chunks]my_retriever stands for whatever search backend you already have. The wrapper does three jobs.
- It clamps
top_kto the range the schema promised. The schema describes the range, but nothing forces the model to obey it. - It truncates each passage, so one long chunk cannot fill the context.
- It returns ids with the text, so the model can cite its sources later.
Then your code appends the result as a message with the tool role and the matching call id. Serialize it to a string, usually with json.dumps.
import json
def tool_message(call, result):
return {
"role": "tool",
"tool_call_id": call["id"],
"content": json.dumps(result),
}Treat arguments as untrusted input
The arguments come from model output, so they can be wrong. A model may invent a parameter, send a string where an integer belongs, omit a required field, or call a tool that does not exist. Handle each case and report the problem back to the model as a result. A model can often fix its own mistake when it sees the error.
def safe_run(call, tools_by_name):
tool = tools_by_name.get(call["name"])
if tool is None:
return {"error": f"unknown tool: {call['name']}"}
try:
return tool(**call["arguments"])
except (TypeError, ValueError) as exc:
return {"error": f"bad arguments: {exc}"}TypeError covers missing or unexpected argument names. ValueError covers values such as int("many"). Errors from your own retriever, such as a network failure, deserve separate handling, because retrying the same call may help there.
Why this matters for RAG
Compare this with the classic pipeline, where embed, search and generate always run once, in that order, with the user's words as the query. With tool calling, search becomes one option among others. The model can:
- skip retrieval for a greeting,
- write a better query than the user's raw question,
- search twice with different wording,
- pick between several tools, one per source.
None of this needs new retrieval technology. It needs the same retriever, wrapped as a tool, plus a loop that keeps calling the model until it stops asking for tools. The next chapters build exactly that.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The model never calls the tool | Description is vague or the tool is not in the request | Say which questions need it and check that the definitions are sent |
| The model always calls the tool, even for "hi" | Description has no "do not use" clause | Add when not to use it |
| Queries like "what about that one?" | The model relied on earlier messages | Require self-contained queries in the parameter description |
| Provider error about a missing tool result | A call id received no tool message | Return one result for every call, including failed ones |
| The context fills up quickly | Tool results are large | Truncate passages and cap `top_k` |
| Arguments arrive as a string | The provider sends JSON text | Parse with `json.loads` before running the tool |
Exercise
A model returns two tool calls in one reply, with ids "a1" and "a2". Your code runs only the first and sends back one tool message with id "a1", then calls the model again. What is likely to happen, and what should the code do instead?
Show answer
Most providers reject the request or the model gets confused, because call "a2" has no matching result. The code should run every call in the reply and append one tool message per call, each with its own id (including an error result if a call fails), before calling the model again.
Exercise
Your search tool's description says only "Searches documents." Users report that the model searches for every message, including "thanks!", and that follow-up questions produce poor queries. Name two edits that fix this.
Show answer
First, add a "do not use" clause to the tool description, for example "Do not use it for greetings or general knowledge". Second, change the query parameter description to require a short, self-contained query that does not rely on earlier messages. The model then writes standalone queries such as "reset password for API key" instead of "what about that one?".