AI Model for Choosing Which Knowledge Base to Search: Start With an LLM Selector, Then Test Source Recall
A query router over multiple knowledge bases should return one, several or no source IDs. A small structured-output LLM is the sensible first choice, and a held-out test of source recall decides whether anything else is worth the work.
The best first model for choosing which knowledge base to search is a small LLM with structured output. Give it a short description of each permitted knowledge base, and let it return one, several or no source IDs. LlamaIndex's RouterRetriever with a multi selector implements this query-routing pattern, and the LLM makes the selection. Move to a shortlist search, a trained classifier or an option scorer such as Parsec's TOD only when a held-out test shows that the LLM misses required sources or costs too much. No published study has compared these approaches on enterprise knowledge bases, so your own test has to settle it.
A knowledge-base router returns a set of source IDs, and the set can be empty
The router has a narrow job. It takes the question, any state from the conversation so far and a description of each knowledge base that the user may search. It returns the IDs of the knowledge bases to search. It does not retrieve documents, write the answer or take any action.
Take a company with three knowledge bases. HR covers benefits, leave and workplace policy. Finance covers expenses, reimbursements and purchasing approvals. IT covers hardware standards, device provisioning and troubleshooting. A question such as "Can I expense a replacement laptop?" needs two of them. Finance holds the expense rule, and IT holds the hardware standard that sets which laptop qualifies. The correct output is ["finance", "it"].
A question such as "What is the Wi-Fi password at the Lisbon client's office?" needs none of them. The correct output is an empty set, so that the application can say that it has no source rather than search HR and produce an answer from the closest policy.
Keeping four stages apart makes each one testable on its own:
- Source selection returns the set of knowledge-base IDs.
- Document retrieval searches only those knowledge bases and returns passages.
- Answer generation writes a reply from the passages.
- Execution carries out any action that the reply calls for, such as filing a ticket.
Access permissions belong in application code before the first stage. If a user cannot read the Finance knowledge base, its description should be removed from the list before any model scores it. A router that can see a forbidden source can select it, and a prompt instruction is not an access control.
LlamaIndex's RouterRetriever supplies the plumbing, and the selector makes the choice
LlamaIndex is the framework, not the model. Its RouterRetriever, in the source code of the v0.14.26 release from November 13, 2026, "Selects one (or multiple) out of several candidate retrievers to execute a query." Each knowledge base is wrapped as a RetrieverTool with a name and a description. When the selector returns several indexes, the router searches each chosen retriever and merges the results by node ID.
The selector does the routing. LlamaIndex ships several selectors, including these five:
LLMSingleSelectorasks an LLM for the one most relevant choice and parses a JSON answer.LLMMultiSelectorasks for several choices, up tomax_outputs, with the same JSON parsing.PydanticSingleSelectorandPydanticMultiSelectoruse the LLM's function-calling interface and return typed selection objects.EmbeddingSingleSelectorcompares the question's embedding with each description's embedding and returns the single closest match.
A single selector cannot produce the laptop answer, because it returns exactly one knowledge base. For a catalog in which questions can cross departments, the multi selector is the starting point.
Three details in the source code matter for production use. The max_outputs value is written into the prompt, but the code does not cut the parsed list down to that number. The default prompts offer no "none of these" answer. And a selector that returns zero selections makes RouterRetriever raise "Failed to select retriever", because the single-selection branch reads an index that does not exist.
The fix for the last two is an explicit no-source option backed by a retriever that returns nothing. The application then treats an empty result as "no source" rather than as an error. This minimal router pins the versions in the v0.14.26 tree and applies permissions before the selector sees the catalog:
# pip install llama-index-core==0.14.26 llama-index-llms-anthropic==0.12.3
from llama_index.core.base.base_retriever import BaseRetriever
from llama_index.core.retrievers import RouterRetriever
from llama_index.core.selectors import PydanticMultiSelector
from llama_index.core.tools import RetrieverTool
from llama_index.llms.anthropic import Anthropic
NO_SOURCE = "no_source"
class EmptyRetriever(BaseRetriever):
def _retrieve(self, query_bundle):
return []
def permitted_tools(catalog, user):
allowed = [kb for kb in catalog if user.can_read(kb.id)] # access check first
tools = [
RetrieverTool.from_defaults(retriever=kb.retriever, name=kb.id,
description=kb.description)
for kb in allowed
]
tools.append(RetrieverTool.from_defaults(
retriever=EmptyRetriever(), name=NO_SOURCE,
description="Choose only if no other knowledge base covers the question."))
return tools
llm = Anthropic(model="claude-haiku-5-5", temperature=0)
def llm_router(tools):
selector = PydanticMultiSelector.from_defaults(llm=llm, max_outputs=3)
return RouterRetriever(selector=selector, retriever_tools=tools)
The application still has to check the selector's output. It should drop no_source when other IDs come back with it, cap the list at three, and log every selection with its reason. LlamaIndex's get_selector_from_llm helper prefers the Pydantic selectors and falls back to the JSON-parsing selectors when the model does not support function calling. The Anthropic integration marks claude-haiku-5-5 as a function-calling model.
Four kinds of selector are worth comparing, and the simplest one that passes should win
The options differ mainly in what they need before they work and in how their output maps to a set of sources.
- Rules or description embeddings need no model call per question. Keyword rules suit a catalog in which each source has its own vocabulary.
EmbeddingSingleSelectorreturns only one match, so multi-source questions need a similarity threshold that you write and tune yourself. - A structured-output LLM selector needs only descriptions. It can return several IDs or the no-source option, and its reasons can be logged. Its cost and latency grow with the length of the catalog in the prompt.
- An untuned option scorer returns a probability for each supplied option and generates no text. Parsec's TOD is a named example.
- A trained classifier needs labelled questions. A multi-label classifier, with one yes-or-no output per knowledge base, matches the router's contract directly. SetFit, whose v1.2.0 release came out on September 4, 2026, fine-tunes Sentence Transformers for few-shot classification. Its README claims that 8 labelled examples per class can compete with full fine-tuning on one review dataset, which is not a routing task.
The decision table matches each situation to a starting approach.
| Situation | Start with | Add when the test demands it |
|---|---|---|
| Up to a few dozen sources, no labelled questions | LLM multi selector with a no-source option | Better descriptions before a bigger model |
| Stable domains, high volume, labelled questions | Multi-label classifier, compared with the LLM | LLM fallback for low-confidence cases |
| Hundreds or thousands of sources that change | Description search for a shortlist, then an LLM selector | Separate test of shortlist recall |
| Answers that need a second search based on the first | Agent loop with each knowledge base as a tool | Limit on the number of searches |
| Need for a fixed price per decision without labels | Option scorer such as TOD, compared with the LLM | Confidence gate to an LLM |
Parsec describes TOD as a "universal decision model" that ranks the next action from a list of allowed actions. It generates no free text and cannot invent an option. The public release is a set of LoRA adapters on google/gemma-4-12B-it plus a ModernBERT-base retriever. The adapters are listed as Apache-2.0, but the base weights are not included, and users must accept the Gemma 4 licence. Parsec's TOD page prices hosted use at $0.30 per 1,000 decisions, flat regardless of context length, and says that a confidence gate passes uncertain turns to a parent LLM. Parsec's open-jev repository is a separate route, built on a local Gemma 3 4B with an SDK for fine-tuning small decision models. Tuning either one is optional. TOD's own repository says that it is not state of the art on the JevBench decision benchmark, and nobody has published a test of it on knowledge-base routing.
A probability that sums to one needs an explicit policy before it can choose two sources
TOD's predict(state, options, question, images) returns one probability per supplied option, and the probabilities sum to 1. That output describes a choice among mutually exclusive options. It is not a calibrated yes-or-no score for each knowledge base. For the laptop question, the mass may split between Finance and IT, so a rule such as "select anything above 0.5" could select neither.
The selector therefore needs a documented multi-source policy. One workable policy adds options in order of probability until their total passes a threshold, stops at a fixed maximum, and defers to a fallback when the maximum is reached first. The following selector implements that policy in LlamaIndex. It maps each score back to a source ID by position, because TOD returns its scores in the order of the supplied options.
from llama_index.core.base.base_selector import BaseSelector, SelectorResult, SingleSelection
class Defer(Exception):
"""Raised when the top scores stay below the threshold; the caller widens the search."""
class ScoreSelector(BaseSelector):
def __init__(self, score_fn, mass=0.8, max_sources=3):
self._score = score_fn # (question, descriptions) -> one probability per option
self._mass, self._max = mass, max_sources
def _get_prompts(self):
return {}
def _update_prompts(self, prompts):
pass
def _select(self, choices, query):
probs = self._score(query.query_str, [c.description for c in choices])
if len(probs) != len(choices):
raise ValueError("scorer must return one score per option")
order = sorted(range(len(choices)), key=lambda i: probs[i], reverse=True)
picked, total = [], 0.0
for i in order[: self._max]:
picked.append(SingleSelection(index=i, reason=f"{choices[i].name} p={probs[i]:.2f}"))
total += probs[i]
if total >= self._mass:
return SelectorResult(selections=picked)
raise Defer(f"top {self._max} options cover only {total:.2f}")
async def _aselect(self, choices, query):
return self._select(choices, query)
# TOD-backed scorer: load the model as its repository describes, then
# score_fn = lambda q, opts: tod.predict(state="", options=opts, question=q, images=None)
The same class accepts any scorer that returns one probability per option, including a classifier. The threshold of 0.8 and the cap of three are placeholders. Both should be set on a development split and then checked on held-out multi-source questions. TOD's repository also gives serving caveats: use chunked_eager or eager attention rather than sdpa, and do not quantise it with bitsandbytes int8.
Catalogs with hundreds of sources need a shortlist step, and the shortlist needs its own recall test
Putting every description in the prompt stops working as the catalog grows. Anthropic's documentation for its tool search tool says that Claude's ability to pick the right tool "degrades once you exceed 30-50 available tools." Its answer is a two-step design. A search over tool names and descriptions loads a few candidates, five by default, and the model chooses among them. Anthropic's November 24, 2025 announcement describes a 58-tool setup that used about 55,000 tokens of definitions before any work began. The documentation says that tool search typically cuts that load by over 85 percent. On Anthropic's internal tests, selection accuracy for Opus 4.5 rose from 79.5% to 88.1% with tool search.
The same pattern works for knowledge bases. Each knowledge base becomes a tool or a description document. An embedding or BM25 search returns a shortlist of perhaps 20, and the LLM selector chooses from the shortlist. Anthropic's docs also support a custom search that returns tool_reference blocks, so the shortlist step can use your own embedding index.
The two steps fail in different ways, so they need separate measurements. Shortlist recall is the share of required sources that appear in the shortlist. Selection recall is the share that the selector then picks. A source that the shortlist drops cannot be recovered by any selector. Three cases need their own test questions:
- Descriptions that overlap heavily, such as two regional HR policies, push one of them out of a short list.
- A newly added knowledge base has no history of questions and may have a thin description.
- A question that needs a source outside the top 20 shows whether the shortlist size is too small.
Questions that need successive searches call for iterative routing, which is where MoRE fits
Some questions reveal the next source only after the first search. A question about whether a contractor's laptop purchase was approved may need the Finance record before it is clear which IT asset policy applies. A one-shot router cannot handle this. An agent loop that exposes each knowledge base as a tool, and allows a second search based on retrieved evidence, can handle it.
Mixture-of-Retrieval Experts, or MoRE, is the research version of this idea. The paper, revised on April 6, 2026, trains a multimodal LLM to choose which retrieval expert to engage "conditioned on the evolving reasoning state." Its retrieval experts search a Wikipedia text corpus, an image corpus and a table corpus, and its training method is called Step-GRPO. The authors report average gains of over 7% against baselines on open-domain question-answering benchmarks, and the repository says that SIGIR 2026 accepted the work. That result concerns public multimodal corpora. It does not show that a learned router beats an LLM selector on company HR, Finance and IT documents.
Over-routing costs more than the router itself in a worked example
The router's own cost is small, and the searches that it triggers are not. The example below assumes 1 million questions a month, a catalog of 12 knowledge bases and Anthropic's list prices.
The LLM selector runs on Claude Haiku 5.5 at $0.10 per million input tokens and $0.50 per million output tokens. Each call is assumed to use 1,500 input tokens. That figure includes 406 tokens of tool-use system prompt, which Anthropic lists for forced tool choice on Haiku 5.5, plus about 720 tokens of descriptions. Each call is also assumed to return 80 output tokens. That is $0.00019 per question, or about $190 a month. Suppose instead that the 1,420 tokens that stay the same on every call are served from Anthropic's prompt cache at $0.01 per million. The cost then falls to about $62 a month, ignoring cache writes. TOD at $0.30 per 1,000 decisions is $300 a month, before any turns that it passes to an LLM.
Over-routing changes the picture. Suppose that each extra knowledge base adds five passages of 400 tokens to the answer model, Claude Sonnet 5.5, at $2 per million input tokens. One unnecessary source then costs $0.004 per question. If 20% of questions route to one extra source, that adds $800 a month, more than any of the routers. A fallback that searches all 12 sources on 10% of questions adds 11 sources each time. That costs $0.044 per fallback question, or $4,400 a month.
The opposite error, a missed required source, has no list price. It produces a wrong or incomplete answer. That is why a router should be judged on recall first and on cost second.
A held-out test set with human-checked source sets should decide the comparison
No published evaluation compares rules, an LLM selector, an untuned option scorer and a trained classifier on enterprise knowledge-base routing with source recall and answer quality measured separately. The test that would settle it is modest in size. It needs a few hundred real questions, each with a human-checked set of required sources. The set should include:
- single-source questions from every knowledge base;
- multi-source questions such as the laptop example;
- no-source questions that the catalog cannot answer;
- questions that need a second search after the first; and
- questions about recently added sources.
Each candidate router should then be scored on the same held-out split, with these measures reported:
- Source recall and precision are measured across all questions that have at least one required source.
- The missed-required-source rate is the share of questions in which any required source was not selected.
- No-source accuracy is the share of unanswerable questions that returned an empty set.
- Deferral coverage is the share of questions handled without fallback at the precision target that you set on the development split.
- Final answer correctness is graded by a person against the same questions, so that routing errors can be separated from generation errors.
- Latency is reported at the median and 95th percentile, with the hardware named for any self-hosted model.
- Total cost includes the router, the downstream searches, the extra passages sent to the answer model and the fallback.
The scoring itself fits in a few lines.
def routing_metrics(cases, route):
# cases: [{"q": str, "required": set_of_ids}]; route(q) -> set_of_ids or raises Defer
hit = need = picked = missed = empty_ok = empty_n = deferred = 0
for c in cases:
try:
got = route(c["q"])
except Defer:
deferred += 1
continue
req = c["required"]
if not req:
empty_n += 1
empty_ok += not got
continue
hit += len(got & req)
need += len(req)
picked += len(got)
missed += not req <= got
return {"recall": hit / max(need, 1), "precision": hit / max(picked, 1),
"missed_rate": missed / max(len(cases) - empty_n - deferred, 1),
"no_source_acc": empty_ok / max(empty_n, 1),
"coverage": 1 - deferred / len(cases)}
A published result should include the prompts, the source descriptions, the data provenance, the package and model versions, the hardware and confidence intervals from a bootstrap over questions. The smallest router that meets the recall target on that test is the right model for that catalog.
Sources
- LlamaIndex v0.14.26 release: https://github.com/run-llama/llama_index/releases/tag/v0.14.26
- LlamaIndex RouterRetriever source (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-core/llama_index/core/retrievers/router_retriever.py
- LlamaIndex base selector source (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-core/llama_index/core/base/base_selector.py
- LlamaIndex LLM selectors source (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-core/llama_index/core/selectors/llm_selectors.py
- LlamaIndex selector prompts (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-core/llama_index/core/selectors/prompts.py
- LlamaIndex Pydantic selectors source (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-core/llama_index/core/selectors/pydantic_selectors.py
- LlamaIndex embedding selector source (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-core/llama_index/core/selectors/embedding_selectors.py
- LlamaIndex selector utilities (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-core/llama_index/core/selectors/utils.py
- LlamaIndex Anthropic integration, pyproject (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-integrations/llms/llama-index-llms-anthropic/pyproject.toml
- LlamaIndex Anthropic integration, model utilities (v0.14.26): https://github.com/run-llama/llama_index/blob/v0.14.26/llama-index-integrations/llms/llama-index-llms-anthropic/llama_index/llms/anthropic/utils.py
- Anthropic, Introducing advanced tool use: https://www.anthropic.com/research/advanced-tool-use
- Anthropic, Tool search tool documentation: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool
- Anthropic, Pricing: https://platform.claude.com/docs/en/about-claude/pricing
- Peng et al., Mixture-of-Retrieval Experts (arXiv 2505.22095): https://arxiv.org/abs/2505.22095
- OpenBMB, MoRE repository: https://github.com/OpenBMB/MoRE
- Hugging Face, SetFit repository: https://github.com/huggingface/setfit
- Hugging Face, SetFit v1.2.0 release: https://github.com/huggingface/setfit/releases/tag/v1.2.0
- Parsec, TOD: https://parseclab.ai/tod/
- Parsec, TOD model card: https://huggingface.co/parsecai/tod
- Parsec, TOD repository: https://github.com/daseinlabs/tod
- Parsec, open-jev repository: https://github.com/daseinlabs/open-jev