Intent-Only Retrieval
Use the model only to turn a question into filters. The answer is the rows your own data returns, so the model cannot add a result that does not exist.
cd examples && pytest retrieval_and_memory/test_intent_only_retrieval.pyWhat It Is
A search design where the language model reads the question and returns filters, and nothing else. Your code runs those filters against your own catalogue and returns the rows that match. The model never writes the answer and never names an item. The name is ours; the technique is close to "self-querying" retrieval but goes further by forbidding the model any part of the output a user sees.
The Problem It Solves
If a model writes the answer to "quiet hill station near here in May", it can mention a place that doesn't exist, or one that exists but is closed, or one that doesn't fit. Grounding checks reduce this, but only if you retrieved the right items first. Intent-only retrieval removes the failure at its source: a result can only be a row in your database.
How It Works
flowchart TD
Q["Question"] --> N["Normalise"]
N --> C{"Cached for this
prompt version?"}
C -->|"yes"| F["Filters"]
C -->|"no"| M["Model: question → filters
(closed vocabulary)"]
M --> V["Validate in code"]
V --> F
F --> E{"Any filters?"}
E -->|"no"| U["Say it was not understood"]
E -->|"yes"| D["Query own data"]
D --> R["Rows, or 'nothing matches'"]
- Offer a closed vocabulary. List the fields and values your data actually has, and ask for a JSON object using only those (Closed-Vocabulary Output).
- Validate the reply in code. Keep only known fields with known values.
- Handle "no filters" explicitly. If nothing usable came back, tell the user the question wasn't understood. Do not list everything and do not guess.
- Query your own data. The result set is the matching rows. If it is empty, say nothing matches.
- Cache the parse, not the answer. Key it on the normalised question and a prompt version, and cache only parses that produced filters. Data changes show up immediately because only the filters are cached. Bump the version when the prompt or vocabulary changes meaning.
- Explain from the data. Any "why this result" text comes from fields in the row, not from the model.
When to Use It
- You have a structured catalogue (products, places, documents with metadata) and users ask in natural language.
- A fabricated result is worse than a missing one.
- You want results to be explainable: each one matches stated filters.
When NOT to Use It
- The answer is the generated text: summaries, explanations, advice. Use retrieval plus a Grounding Verifier.
- Your data has little structure. If there are no fields to filter on, there is nothing for the model to return. Use Hybrid Search.
- Questions need reasoning across items ("the cheapest option that is also near the airport"). Filters can't express it; you need a query language the model writes, which brings back the validation problem in a larger form.
Trade-offs
- Expressiveness for safety. Anything the filters can't say, the system can't ask. Review the questions that return "not understood" to find missing fields.
- The filters are the product. Quality depends on the vocabulary and the matching code more than on the model.
- One model call per new question. Caching the parse removes the repeat cost, and a daily cap removes the worst case; see Quota-Aware Model Pool.
Failure Modes
Stale cache after a prompt change. Old parses keep being served under the new prompt for as long as they live. Store a prompt version beside each cached parse and ignore rows from older versions.
A failed parse cached for good. One timeout or broken reply produces no filters, the empty result is cached, and that question is "not understood" until the cache is cleared. Never cache a failure.
A confident wrong filter. The model picks a valid month that the user didn't mean. Show the applied filters next to the results so the user can see and change them.
Vocabulary drift. A new value is added to the data but not to the prompt, so questions that use it are never matched. Build the vocabulary from the data on load.
Silent broadening. When the filters match nothing, someone adds a fallback that drops a filter and retries. That reintroduces results the user did not ask for. If you relax filters, say which one.
Implementation Example
A catalogue search where the fake model is scripted. The tests show a model trying to name a place (discarded), no match (reported, not padded), cache hits on re-worded identical questions, a failed parse that is retried rather than cached, and a prompt-version bump forcing a re-read.
cd examples && pytest retrieval_and_memory/test_intent_only_retrieval.py"""Intent-Only Retrieval.
The model reads the question and returns filters. It never returns an answer.
The answer is whatever rows in your own catalogue match those filters, so every
result exists, and the model has no way to add one that doesn't.
Parsed intents are cached per (normalised question, prompt version). Bump the
version when the prompt changes so old parses are read again.
"""
from __future__ import annotations
import json
import re
from collections.abc import Callable
from dataclasses import dataclass, field
PROMPT_VERSION = 1
@dataclass
class Result:
rows: list[dict] = field(default_factory=list)
filters: dict = field(default_factory=dict)
note: str = "" # shown to the user when we could not understand or found nothing
def normalise(question: str) -> str:
return " ".join(re.findall(r"[a-z0-9]+", question.lower()))
def read_intent(raw: str, allowed: dict[str, set[str]]) -> dict[str, str]:
"""Keep only filters whose field and value the catalogue actually has."""
try:
data = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return {}
if not isinstance(data, dict):
return {}
return {k: v for k, v in data.items() if k in allowed and isinstance(v, str) and v in allowed[k]}
class Search:
def __init__(self, catalogue: list[dict], llm: Callable[[str], str], fields: list[str]):
self.catalogue = catalogue
self.llm = llm
self.allowed = {f: {str(r[f]) for r in catalogue if f in r} for f in fields}
self._cache: dict[tuple[str, int], dict[str, str]] = {}
def intent(self, question: str) -> dict[str, str]:
key = (normalise(question), PROMPT_VERSION)
if key not in self._cache:
prompt = (
"Turn the question into filters. Reply with JSON, using only these fields and values; "
"do not name any item and do not answer the question.\n"
+ "\n".join(f"- {f}: {sorted(v)}" for f, v in self.allowed.items())
+ f"\n\nQuestion: {question}"
)
filters = read_intent(self.llm(prompt), self.allowed)
if not filters:
# Don't cache a failed parse: one bad reply (a timeout, broken JSON)
# would otherwise make this question "not understood" for good.
return filters
self._cache[key] = filters
return self._cache[key]
def ask(self, question: str) -> Result:
filters = self.intent(question)
if not filters:
# Nothing usable was understood. Say so; do not guess and do not list everything.
return Result(note="I could not turn that into a search. Try naming a region or a month.")
rows = [r for r in self.catalogue if all(str(r.get(k)) == v for k, v in filters.items())]
if not rows:
return Result(filters=filters, note="Nothing in the catalogue matches that.")
return Result(rows=rows, filters=filters)Tool Landscape
| Tool | Notes |
|---|---|
| Provider structured-output modes | Constrain the model's reply to a schema of filters |
| Self-querying retrievers (LangChain, LlamaIndex) | Generate a metadata filter and a text query from a question |
| Search engines with filters and facets (Elasticsearch, OpenSearch, Postgres) | Where the filters are executed |
Related Patterns
- Closed-Vocabulary Output is the validation step this pattern relies on.
- Grounding Verifier is the alternative when the model writes the answer.
- Hybrid Search handles the unstructured part of a question that filters can't.
- Semantic Caching caches answers; this caches only the parse.
Further Reading
Spotted something wrong or have a production story? Edit this page on GitHub.