Sub topic 9
Choosing between several sources
This chapter assumes you have read the earlier chapters in this tutorial. You should know how a retrieval function is exposed as a tool, and how the agent loop runs tool calls until the model gives a final answer. You should also be comfortable with basic Python and JSON.
Why routing becomes a problem
A single search index is easy to use. The model calls search_docs, and the results come from the one place it can look. Real systems rarely stay that simple. A support assistant may need product documentation, a ticket history, a pricing database, and a changelog. Each source has different content, freshness, access rules, and query style.
Classic RAG usually handles this in one of two ways. It searches everything with one query, or it puts a hand-written router in front of the pipeline. Searching everything mixes unrelated passages and wastes context. A fixed router breaks when a question needs two sources. Agentic RAG lets the model decide the source on each call. Source routing is that decision.
Two ways to expose sources
You can give the model one tool per source, or one tool with a source parameter. Both work, and the choice affects how reliably the model routes.
| Design | Strengths | Weaknesses |
|---|---|---|
| One tool per source | Each description is specific. Parameters can differ by source. Permissions are enforced per tool. | The tool list grows with each source. Selection quality drops once there are many similar tools. |
| One tool with a `source` enum | A compact tool list. Adding a source adds one enum value. | Parameters must be shared. The per-source guidance has to fit inside one description. |
A practical rule: use separate tools when the sources take different parameters, such as a SQL-backed tool that takes a date range. Use one tool with an enum when the sources are all text indexes that accept a query and a count. The rest of this chapter uses the enum design.
A tool schema with a source parameter
The source field uses an enum, so the model can only pick a name that exists. Each value is explained in the description, because the model chooses from what you write there.
{
"name": "search_sources",
"description": "Search one knowledge source. Sources: 'docs' holds product documentation about behavior, configuration and limits. 'tickets' holds resolved support tickets, useful for error messages and workarounds. 'changelog' holds release notes, useful for questions about when something changed or which version added it. Pick the single best source for the question. If the results do not answer it, call again with a different source or query.",
"parameters": {
"type": "object",
"properties": {
"source": {
"type": "string",
"enum": ["docs", "tickets", "changelog"],
"description": "Which source to search."
},
"query": {
"type": "string",
"description": "A short, self-contained search query."
},
"top_k": {
"type": "integer",
"description": "Number of passages to return, from 1 to 8."
}
},
"required": ["source", "query"]
}
}Exact field names for tool definitions differ between model providers. The structure, a name, a description, and a typed parameter schema, is the same everywhere.
A dispatcher that tolerates bad routing
The model can still misroute. It may send a version question to docs, or invent a source name when the provider does not enforce the enum. The dispatcher should treat the source argument as untrusted input and fail in a way the model can recover from.
def _stub(source):
# Replace with a real retriever for each source.
def search(query, k):
return [{"id": f"{source}-{i}", "text": f"{source} passage {i} for '{query}'"}
for i in range(1, k + 1)]
return search
SOURCES = {
"docs": _stub("docs"),
"tickets": _stub("tickets"),
"changelog": _stub("changelog"),
}
def search_sources(source, query, top_k=4):
retriever = SOURCES.get(source)
if retriever is None:
# Return the valid names so the model can correct itself on the next step.
return {"error": f"unknown source: {source}", "valid_sources": sorted(SOURCES)}
top_k = max(1, min(int(top_k), 8))
chunks = retriever(query, top_k)
return [{"id": c["id"], "source": source, "text": c["text"][:1200]} for c in chunks]
print(search_sources("changelog", "when was SSO added", 2))
print(search_sources("wiki", "SSO"))Two details matter. The unknown-source branch returns an error object instead of raising an exception, so the agent loop from the previous chapter can append it as a tool result and let the model retry. Every passage also carries its source field. Later chapters rely on this for citations, and it helps when you debug a trace.
Writing descriptions that route well
The model routes on the descriptions, so most routing bugs are description bugs.
- Say what each source contains and what it does not contain. "Release notes, not behavior documentation" prevents overlap.
- Name the question types it suits, such as error messages, version history, or limits. Models match well on these cues.
- Avoid two sources whose descriptions could both fit the same question. If the overlap is real, state which one to try first.
- Keep descriptions short. A paragraph per source makes the tool definition long and slows every request, because the definition is sent each turn.
Querying more than one source
Some questions need several sources. "Does the export limit still apply in version 3, and why do users hit it?" needs changelog for the version change and tickets for user reports. A model that can issue several tool calls in one step, or one per loop iteration, can cover both. Your loop should therefore not assume one source per question.
Two designs let you control this. In the first, the model picks sources one at a time and decides after each result whether to continue. It is cheap on easy questions and slower on hard ones. In the second, you add a fan-out tool that searches all sources and merges the results. It gives a fixed, predictable cost and breaks the "one best source" benefit. Many teams offer the single-source tool and keep fan-out as a fallback for when two single-source calls return nothing useful.
Failure modes
- Always the same source. The model defaults to the first or most general source. Fix this by sharpening descriptions, and check traces for source frequency.
- Wrong source, confident answer. A weak match from the wrong source can still look plausible. Result grading, covered in the next chapter, is the defense. Do not rely on routing alone.
- Query written for the wrong index. A query that suits the docs ("configure retry limit") fits poorly in a ticket index, where users write error text. Tell the model in the description what each index's text looks like.
- Access control by prompt. Telling the model "do not search
hr" is not a control. Enforce permissions in the dispatcher, using the caller's identity, and leave restricted sources out of the enum for users who cannot see them. - Silent source drift. You add a source and forget to update the descriptions. Keep the enum, the description, and the
SOURCESregistry generated from one list.
Exercise
Your agent has the sources docs, tickets and changelog. Users ask "Which version removed the legacy export format, and are people still reporting problems with it?" The agent only ever calls docs and answers vaguely. Give two likely causes and one fix for each.
Show answer
Cause 1: the descriptions do not tell the model that changelog covers version history and tickets covers user-reported problems, so docs looks like the default. Fix: add question types and "not for" statements to each description. Cause 2: the loop or prompt treats one search as enough, so the model stops after the first result. Fix: allow several calls, and add result grading so a vague answer triggers a second search on a different source. Logging the chosen source per call confirms which cause applies.