ARCHITECTURE · RETRIEVAL · 5 MIN READ

Retrieval that can ask a better question

Give the agent a bounded search-and-check loop over your own knowledge.

Download example files Code + setup + checks in a ZIP
Jump to a section 11 sections

EXAMPLE USE CASE

Find the returns policy when the first query misses

A user says “refund” while the authorized document uses “returns”. A single literal search misses the evidence.

Input
Question refund, tenant a, and a small corpus containing returns, shipping and another tenant’s private policy.
Expected output
The returns-v2 source ID and its 30-day policy after one bounded rewrite.
  • Success check: The first query misses; the rewrite finds the correct source; an unrelated warranty question returns insufficient evidence.
  • Try a failure: A near match from tenant b must never be used to answer tenant a.

Example scope: A runnable lexical retrieval-control lab. Production embeddings, an LLM query rewriter and answer generation are identified as replaceable components, not simulated as complete integrations.

Qdrant examplepgvector exampleRagas exampleCohere Rerank example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
questionquerycandidatesevidencegrounded resultbounded retryQuestion + scopeTask and access boundaryRetrieval plannerBounded query choicesScoped retrieverVector, lexical or hybridRanked evidenceRerank and fit contextAnswer gateSupport or abstainCitations + evalInspect sources and quality
  1. Resolve the user’s actual question and the corpus they are allowed to search.

  2. Choose an initial query and a limited rewrite/fallback policy rather than searching until any answer looks plausible.

  3. Apply access and metadata constraints while retrieving candidates; retain source IDs and versions.

  4. Select relevant passages, remove duplicates and keep their citation mapping within the context budget.

  5. Answer only supported claims. Insufficient evidence should trigger a bounded retry or an explicit abstention.

  6. Return source references and measure retrieval recall, answer support, source freshness and latency separately.

    Result or stopping point
Retrieval planner

Choose an initial query and a limited rewrite/fallback policy rather than searching until any answer looks plausible.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Components for this use case

  • Docling or Unstructured extracts versioned source text; Qdrant or pgvector retrieves tenant-scoped candidates; a reranker can improve relevance after retrieval.
  • An SDK agent can choose retrieval/rewrite actions, but the application enforces a maximum search count and preserves source IDs for the final answer and evaluation.

Build the corpus first

  • Parse documents, preserve provenance, chunk deliberately, and attach access-control metadata.
  • Create embeddings and a keyword index as needed.
  • Establish a reproducible ingestion path so updates and deletions reach the retrieval layer.

Bound the retrieval loop

  • The planner selects a query and source.
  • Search returns candidates, a reranker prioritizes passages, and a sufficiency check decides whether to answer or refine.
  • Cap the number of search rounds and return uncertainty when evidence remains incomplete.

Evaluate retrieval and generation separately

  • Measure whether the right passage was retrieved before evaluating the answer.
  • Include access-filtered searches, exact identifiers, stale documents, and contradictory records.
  • Preserve the selected evidence with the run for inspection.

Set up the lab

  • Python 3.11 or newer. This local lab exposes the control flow without a model call.
  • Use an empty directory; the example may create a local SQLite file.
Shell
python3 -m venv .venv
source .venv/bin/activate

Implement the example

Save as retrieve.py

Python · retrieve.py
documents = [
    {"id": "returns-v2", "tenant": "a", "text": "Returns accepted within 30 days."},
    {"id": "shipping-v1", "tenant": "a", "text": "Shipping normally takes 5 days."},
    {"id": "private", "tenant": "b", "text": "Returns accepted within 90 days."},
]
def retrieve(query, tenant):
    terms = set(query.lower().split())
    candidates = [d for d in documents if d["tenant"] == tenant]
    scored = [(len(terms & set(d["text"].lower().split())), d) for d in candidates]
    return [d for score,d in sorted(scored, key=lambda x:x[0], reverse=True) if score > 0][:2]

def answer(query, tenant):
    for rewrite in (query, query.replace("refund", "returns")):
        hits = retrieve(rewrite, tenant)
        if hits:
            return {"evidence": [h["id"] for h in hits], "answer": hits[0]["text"]}
    return {"evidence": [], "answer": "Insufficient evidence"}

result = answer("refund", "a")
assert result["evidence"] == ["returns-v2"]
assert answer("warranty", "a")["evidence"] == []
print(result)

Run and verify

Shell
python retrieve.py
  • The first search misses; a bounded query rewrite finds the return policy and preserves its source ID.
  • This is a lexical control-flow lab. Replace the retriever with a vector or hybrid index while preserving the tenant filter and citations.

Troubleshooting and failure tests

  • Do not endlessly rewrite a question until some unrelated document matches.
  • Evaluate retrieved evidence separately from the final answer; a plausible answer can hide failed retrieval.

Before production

  • Version chunks, embeddings, access rules and source documents together.
  • Measure recall at k, source freshness, unsupported claims, latency, and cost against a fixed test set.

Keep exploring

AI agent evaluation: frameworks, tools and an exampleUse PostgreSQL and pgvector for agent memoryA context pipeline for a long-running agent