Sub topic 5
Turning retrieval into a tool
This chapter assumes you know basic Python, what a prompt and a completion are, and how embeddings and vector search find similar text. It also assumes you have seen the classic retrieve-then-generate pipeline. Here you will wrap a retriever so a model can call it. The loop that runs those calls comes in the next chapter.
From a fixed step to a choice
In classic RAG, your code decides everything about retrieval. It embeds the user's words, fetches the top results, and pastes them into the prompt. The model never sees the search step.
def answer_with_rag(question, embed, search, generate, k=4):
# Classic RAG: retrieval always runs once, with the user's words as the query.
query_vector = embed(question)
chunks = search(query_vector, k) # each chunk: {"id": str, "text": str}
context = "\n\n".join(f"[{c['id']}] {c['text']}" for c in chunks)
prompt = (
"Answer using only the context below. "
"If the context does not contain the answer, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
return generate(prompt)Three decisions are hard-coded here. Retrieval always runs, even for "hello". The query is always the raw user message. The number of results is always k. Turning retrieval into a tool hands these three decisions to the model: whether to search, what to search for, and how much to fetch.
Tool calling is the mechanism for this. You describe a function to the model. The model replies with a structured request to call it, naming the function and giving arguments. Your code runs the function and returns the result. The model never runs anything itself.
Three parts of a retrieval tool
A retrieval tool has three parts, and the model sees only the first two.
- A specification: the name, a description, and a schema for the parameters.
- An implementation: the Python function your code runs.
- A result format: what the function returns, which becomes text in the conversation.
The diagram shows how they connect.
Writing the specification
The specification is the only documentation the model has for your tool. Treat the description as a prompt.
{
"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"]
}
}Exact field names for tool definitions differ between model providers. Some use parameters, others use input_schema. The content is the same: a name, a description, and a JSON Schema.
Each part of this specification does a job.
- The name should say what the tool does.
search_docsis better thantool1, and better thansearchwhen you later add a second source. - The description says when to call the tool and when not to. "Do not use it for greetings" is what lets the model skip retrieval. The last sentence invites a second attempt.
- The
querydescription asks for a self-contained query. The model writes this string, and your retriever sees only the string. A query like "what about the limit?" fails because the retriever has no earlier messages. requiredlists onlyquery. Makingtop_koptional gives the model fewer ways to fail.- The
top_kdescription states the range. A schema can enforce a range too, but you should not rely on that alone, as the next section shows.
Writing the implementation
The function behind the schema receives whatever the model produced. Models sometimes send out-of-range numbers, numbers as strings, or extra fields. Validate at this boundary.
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]Here my_retriever stands for whatever search backend you already have. Four choices in this short function matter.
- Clamping
top_kkeeps one bad argument from flooding the context window or returning nothing. - Truncating text to 1,200 characters caps the cost of each result. Every character you return is paid for again on each later model call in the same conversation.
- Returning
idandtextonly hides embedding vectors, scores you do not need, and internal metadata. Vectors are noise to the model and use many tokens. - Keeping the
idgives the model something to cite. The classic pipeline already labeled chunks as[id], and the tool result keeps that habit.
Notice what is missing: the embedding step. The model sends text, and your function embeds it inside the retriever. The model never handles vectors.
Result format
Tool results become text in the conversation, so the format affects how well the model uses them. The list of {id, text} objects above is a good default. A few rules help.
- Return a stable shape every time. A model copes better when each result looks alike.
- Include a source label or title if you have one. It helps the model judge relevance and write citations.
- Return an empty list when nothing matches. Do not return an error for "no results", because that is a normal outcome.
- Return a clear error object for real failures, for example
{"error": "search backend timed out"}. The model can then retry or tell the user.
Edge cases and common errors
| Problem | Symptom | Fix |
|---|---|---|
| Vague description | The model searches for greetings or never searches at all | State when to use the tool and when not to |
| Query depends on chat history | The retriever returns unrelated passages | Ask for self-contained queries in the parameter description |
| Unvalidated `top_k` | Huge results or exceptions | Clamp and convert arguments in code |
| Whole documents returned | Cost and latency grow with every step | Return short passages and truncate |
| Raw vectors or metadata returned | Wasted tokens, confused answers | Return only ids and text |
| Tool errors raised as exceptions | The whole run crashes | Catch them and return an error object |
Two further points are worth knowing.
First, the model may call the tool with arguments that do not match your schema at all, such as a missing query. Wrap the call in error handling so the model gets a readable message back instead of a crash.
Second, a tool result is untrusted input. Retrieved text can contain instructions written by someone else. Returning the text as data is fine, but a later chapter covers how to defend against instructions hidden inside it.
Comparing with the classic pipeline
The same retriever now serves a different design.
| Aspect | Classic RAG | Retrieval as a tool |
|---|---|---|
| Whether to search | Always | Model decides |
| Query text | The user's raw message | Written by the model |
| Number of passages | Fixed `k` | Model may choose within limits |
| Number of searches | One | Zero or more |
| Where code controls behavior | Pipeline order | Tool description and validation |
Control has moved. In the classic pipeline you control behavior through code order. With a tool, you control it through the description, the schema, and the checks inside the function. The model gains freedom, and you must bound that freedom in the places it touches your system.
Exercise
A user asks "and what is the maximum for that?" right after a message about upload sizes. The model calls search_docs with the query "maximum for that" and gets irrelevant passages. Name two changes to the tool that reduce this failure, and say where each change goes.
Show answer
First, change the query parameter description to demand a short, self-contained query that does not rely on earlier messages, so the model writes something like "maximum upload file size". This goes in the specification. Second, add a check in the implementation that handles poor results, for example returning an empty list when nothing matches well, so the model can see the search failed and retry with a better query. Adding the instruction to the tool description to "call it again with a different query" also helps.
Exercise
Why does searchdocs clamp topk and truncate passage text inside the function instead of trusting the schema description "from 1 to 8"?
Show answer
The description is guidance to the model, not a guarantee. The model can send a value outside the range, or a string. Code inside the function is the only place that always runs, so it must enforce limits. Truncation also caps how many tokens each result adds, and those tokens are paid for again on every later model call.