07.7 Managed RAG: Provider Tools, Platforms and Frameworks

RetrievalLesson 7 of 1114,653 words6 parts
Module 07 · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

Everything in 07.1 through 07.6 assumed you build the retrieval stack yourself: you parse files (Module 05), embed and index them (Module 06), and wire retrieval into generation. That stack is the right default — but it is not the only option, and for many teams it is not the right one. Every major provider now sells a managed retrieval layer: upload files, get citations back, pay per call. Cloud platforms sell the same capability as a service on top of your existing cloud. And a dozen open-source frameworks promise to assemble the whole pipeline for you. This lesson maps the whole landscape — provider tools, cloud platforms and frameworks — teaches you how to decide between building and buying, and shows how to keep the Retriever contract (06.10) so a black-box service can sit inside the same pipeline, be evaluated with the same harness, and be swapped out when it stops earning its keep.

What you'll learn

  • The build-vs-buy decision framework: control, quality ceiling, data residency, cost model, lock-in, observability and team skills — and a worked cost model you can reuse
  • Every provider-managed retrieval tool as of November 2026, end to end: OpenAI File Search and vector stores, Anthropic's citation- and search-result-block approach (it has no vector store), and, as optional extras, Google Gemini File Search with its grounding tools and OpenRouter's plugins (it has no RAG store either), with the limits, pricing shapes and citation formats of each
  • The cloud platforms: Vertex AI RAG Engine, Amazon Bedrock Knowledge Bases (including the managed KB generally available since June 2026), Snowflake Cortex Search and Databricks AI Search — what each is and where each fits — plus two off-cloud managed options, Cloudflare AI Search and Pinecone Assistant
  • The frameworks: LlamaIndex, LangChain/LangGraph, Haystack, DSPy, txtai, RAG-in-a-box apps and the Vercel AI SDK — what they actually provide, the abstraction cost, and when they help or hurt
  • The hybrid approach: own your ingestion and store, use framework glue sparingly, keep the Retriever boundary
  • How to evaluate a black-box retriever with the 06.10 harness, and a bake-off procedure for comparing managed and custom options on quality, latency and cost

What you don't need

  • API keys. Every provider sample is labelled illustrative; the parts you can run for free are pure Python (the cost model, the filter translation, the bake-off runner) or run against fakes and the local stand-in from 03.1, Part 12.
  • A cloud account. The platform sections teach you what exists, how each piece fits together and how to compare them — not how to click through consoles.
  • The retrieval pipeline itself. Chunking, embedding, indexes, hybrid search and reranking are Modules 05 and 06; this lesson treats them as finished machinery.

Setup

This lesson's code needs Python 3.11+ and the provider SDKs. If you have been working through Module 07, your docs_qa package and the retrievers.py/harness.py files from 06.10 already exist. If not, the samples that need them say so; everything else stands alone.

bash
uv add openai anthropic google-genai pydantic python-dotenv
# or: pip install openai anthropic google-genai pydantic python-dotenv

These commands install the newest release of each package. The hosted samples were checked against openai 3.x, anthropic 2.x, google-genai 2.x and pydantic 2.x (versions in 07.1's Setup) as of November 2026; managed-service SDKs change quickly, so check the library's changelog if a call does not match.

Part 4's framework snippets are illustrative only — they name packages you would install in a separate experiment (llama-index, langchain, haystack-ai, dspy, txtai), and installing and testing them is its own exercise. The .env file holds the keys, exactly as in 03.1:

bash
# .env  (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...

What you must be able to do after this lesson#

  • Decide between building and buying RAG
  • Compare provider managed retrieval tools
  • Compare cloud platforms and frameworks for RAG
  • Combine managed and custom parts
  • Run a bake-off between options

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Should we just use the provider's file search instead of building retrieval?" Part 1: The build-vs-buy decision framework
"Our corpus is 40 GB of PDFs — can file search even hold it?" 2.6 Provider comparison
"The vendor says their retriever is better. How do we check?" 2.8 Evaluating a black-box retriever
"We need our documents to stay in our AWS account." Part 3: Cloud platforms
"Should we adopt LlamaIndex or LangChain for RAG?" Part 4: Frameworks
"The framework upgrade broke retrieval silently." 4.9 Dependency hygiene
"We want the framework's loaders but our own retriever." Part 5: The hybrid approach
"Managed tool vs our own pipeline — how do we pick on evidence?" Part 6: The bake-off

Part 1: The build-vs-buy decision framework#

1.1 The spectrum, not a switch#

"Build vs buy" sounds binary, but managed RAG is a spectrum. At one end you own every stage; at the other you own almost nothing. Every option in this lesson sits somewhere on it, and the useful question is never "managed or custom?" but "which stages do I want to own, and which am I willing to delegate?"

flowchart LR
    subgraph custom ["You own everything (Modules 05-06)"]
        C1[Parse & clean] --> C2[Chunk & enrich] --> C3[Embed & index] --> C4[Retrieve & rerank] --> C5[Generate & cite]
    end
    subgraph hybrid ["Hybrid: own the store, delegate glue or search"]
        H1[Your ingestion] --> H2[Your vector DB] --> H3["Framework or<br/>provider search API"] --> H4[Your generation]
    end
    subgraph managed ["Managed tool (Part 2)"]
        M1["Upload files"] --> M2["Provider parses,<br/>chunks, embeds,<br/>indexes, retrieves"] --> M3["Provider model<br/>generates + cites"]
    end
    subgraph platform ["Cloud platform (Part 3)"]
        P1["Your data lake /<br/>blob storage"] --> P2["Managed index +<br/>retrieval service"] --> P3["Your app calls<br/>retrieve + generate"]
    end

The stages you can delegate independently:

Stage Who can own it
Parsing, OCR, cleaning, chunking, metadata You (Module 05), a framework, or the managed tool's ingestion
Embedding model choice You pick it explicitly (custom, frameworks, most cloud platforms) or the vendor picks it for you (OpenAI file search does not document its choice; Gemini lets you pick between two)
Vector index / store Your database, a vector DB vendor, or the provider's managed index
Retrieval algorithm (dense, hybrid, filters, rerank) Your code, a framework, or hidden inside the managed tool
Query understanding / rewriting Your code (07.3) or the model inside the managed tool
Generation and citations Your prompts and pipeline, or the provider's tool-call loop

Notice the last row: with a provider file-search tool, even generation happens inside the provider's tool loop. The model decides when to search, what query to issue, how many results to pull, and how to cite them. That is the deepest form of delegation, and it is the source of most of the trade-offs below.

1.2 The seven dimensions#

Score every option on these. None is decisive alone; the weighting is yours.

Dimension What to ask Custom pipeline Provider tool Cloud platform Framework
Control Can you change chunking, ranking, filters, prompts per stage? Total Little — chunking/ranking mostly fixed Medium — you control index config and query params, less the internals Medium-high — it's your code, but inside their abstractions
Quality ceiling Can it beat a tuned custom pipeline on your data? Highest in principle — every knob is yours Unknown until measured; often good enough High — you own retrieval params and can add your own reranker Same as custom, minus whatever the abstraction blocks
Data residency & privacy Where do the documents and embeddings live? Who can see them? Wherever you put them Provider's cloud (check ZDR/residency: 2.2) Your cloud account/region — strongest story Your infrastructure entirely
Cost model Per-token, per-GB, per-call, or per-node-hour? Embedding + storage + LLM tokens Storage $/GB-day + per-call fee + LLM tokens Index storage + compute + LLM tokens Same as custom + your ops time
Lock-in What happens if you leave? None — it's your code and data High — re-ingest into your own store to leave Medium — data usually exportable, APIs proprietary Medium — abstractions leak provider specifics anyway
Observability Can you see the query, the hits, the scores, the prompt? Total — your traces Partial — annotations/citations yes, raw ranking no (until you use the search API) Good — you own the retrieve call Depends on their hooks
Team skills What must the team learn? Embeddings, vector DBs, evals One API; the hard parts are hidden — and so are the debugging tools Cloud platform + retrieval concepts Framework APIs + their upgrade churn

1.3 A worked cost model#

Costs have three shapes, and they don't compare directly:

  • Usage-shaped (custom): pay for embedding tokens at index time, vector storage (usually cheap or free tier), and LLM tokens at query time. Cost scales with corpus size × query volume.
  • Subscription + usage (provider tools): a storage fee per GB per day plus a per-tool-call fee plus the same LLM tokens. The per-call fee is small but non-zero; the storage fee can dominate for large corpora.
  • Infrastructure-shaped (cloud platforms): index storage, index compute (node-hours or capacity units), plus whatever LLM you call separately. Often cheapest at very large scale, most expensive to start.

A back-of-envelope calculator makes this concrete. Pure Python, no dependencies — run it:

python
# cost_model.py — compare three RAG cost shapes for one workload.
# All numbers are PARAMETERS you fill in from each vendor's pricing page.
# Nothing here is a real price; the structure is what you reuse.

def monthly_costs(
    corpus_mb: float,
    queries_per_month: int,
    retrieved_tokens_per_query: int,   # context the answer is grounded on
    llm_input_usd_per_mtok: float,
    llm_output_usd_per_mtok: float,
    output_tokens_per_answer: int,
    # custom pipeline
    embed_usd_per_mtok: float = 0.02,
    corpus_tokens: int = 0,             # pass corpus_tokens=corpus_mb*250_000 for English prose
    vector_db_usd_per_month: float = 0.0,
    # provider tool (OpenAI file-search shape)
    storage_usd_per_gb_day: float = 0.10,
    free_storage_gb: float = 1.0,
    tool_call_usd_per_1k: float = 2.50,
    # cloud platform
    platform_index_usd_per_month: float = 0.0,
) -> dict:
    corpus_gb = corpus_mb / 1024
    corpus_tok = corpus_tokens or int(corpus_mb * 250_000)  # ~250k tokens per MB of prose

    embed_cost = corpus_tok / 1e6 * embed_usd_per_mtok      # one-off-ish; amortise however you like
    llm_cost = queries_per_month * (
        retrieved_tokens_per_query / 1e6 * llm_input_usd_per_mtok
        + output_tokens_per_answer / 1e6 * llm_output_usd_per_mtok
    )

    custom = embed_cost / 12 + vector_db_usd_per_month + llm_cost
    provider = (max(0.0, corpus_gb - free_storage_gb) * 30 * storage_usd_per_gb_day
                + queries_per_month / 1000 * tool_call_usd_per_1k + llm_cost)
    platform = platform_index_usd_per_month + llm_cost

    return {"custom": custom, "provider_tool": provider,
            "cloud_platform": platform, "llm_tokens": llm_cost}


if __name__ == "__main__":
    # A mid-size help centre: ~200 MB of docs, 100k questions/month.
    # Retrieved context ~2,000 tokens; answers ~400 tokens; a mid-tier chat model.
    r = monthly_costs(
        corpus_mb=200, queries_per_month=100_000,
        retrieved_tokens_per_query=2_000, output_tokens_per_answer=400,
        llm_input_usd_per_mtok=1.0, llm_output_usd_per_mtok=5.0,
        vector_db_usd_per_month=50,          # e.g. a small managed pgvector/Pinecone tier
        platform_index_usd_per_month=300,    # e.g. a small search-service tier
    )
    for k, v in r.items():
        print(f"{k:>15}: ${v:>10,.2f}/month")
Output4 lines
         custom: $    450.08/month
  provider_tool: $    650.00/month
 cloud_platform: $    700.00/month
     llm_tokens: $    400.00/month

Read that carefully, because the lesson it teaches is the point:

  • The LLM tokens are identical in all three — $400 of every total is generation, which no retrieval choice changes. Retrieval decisions move only the other line items, and at this scale those are tens to hundreds of dollars, not thousands.
  • The provider tool's storage fee scales with corpus size, not usage. At 200 MB it is under the 1 GB free allowance — effectively $0 — and its $650 is almost all the $250 of per-call fees plus the shared $400 of tokens. At 2 TB the same fee would be ~$6,100/month before a single query — at which point "cheap per call" becomes "expensive to keep warm".
  • The embedding cost is amortised. A one-off embedding bill spread over a year is noise; what matters is re-embedding on every chunking change, which a managed tool does for you (and bills you for in storage terms, not tokens).
  • Platform index cost is a step function, not a curve: a small search tier costs the same whether you query it 10 times or 10 million times. Below a few thousand queries a month, the platform's fixed cost loses to usage-priced options; above it, they converge.

1.4 The decision table#

Situation Lean toward Because
Prototype / internal tool / < ~1M tokens of docs Provider file-search tool Hours to ship; per-call pricing is trivial at this scale
Docs must never leave your cloud account or region Cloud platform in your account, or custom Data residency is a hard constraint, not a preference
Strict per-document access control (each user sees a subset) Custom or platform with native ACLs Check whether the managed tool's filters can express your ACLs before you commit — and test for leaks (07.11)
Need to tune chunking, hybrid weights, reranker, query rewriting Custom or framework-over-your-store Managed tools hide exactly the knobs you'd tune
Corpus changes constantly (news, tickets, prices) Custom pipeline with incremental indexing, or a platform with sync Managed tools re-index on upload; check their update semantics and lag
No ML/vector-search experience on the team Provider tool first, platform second The skill cliff is real; buy time to learn on a low-stakes tool
Compliance requires audit of what was retrieved Custom or platform Black-box rankings can't be audited the same way
Multi-provider strategy (don't couple retrieval to one model vendor) Custom store + any search API, or a platform Provider tools only work with that provider's models
Very large corpus (> ~100 GB) with modest query volume Custom or platform Per-GB-day storage fees compound; index storage is usually cheaper
Need citations users can verify Any — but verify the citation granularity each gives Page-level (Gemini PDFs), sentence- or block-level spans (Anthropic), chunk-level (OpenAI) differ

Part 2: Provider-managed retrieval tools (as of November 2026)#

This part covers what OpenAI and Anthropic (the two primary providers), then Gemini and OpenRouter (optional), actually offer for managed retrieval, verified against official documentation in November 2026. Volatile details — limits, prices, supported models — are dated and linked; re-check them before you build on them.

2.1 What "managed" means end to end#

Every provider tool follows the same shape, and it is worth naming the stages once so you can compare what each hides:

flowchart LR
    subgraph ingest ["Index time (you trigger, they run)"]
        A["Upload / import<br/>files"] --> B["Parse +<br/>chunk"] --> C["Embed"] --> D["Index<br/>(vector + keyword)"]
    end
    subgraph query ["Query time (per request)"]
        E["Your prompt +<br/>tool config"] --> F["Retrieve top-k<br/>chunks"] --> G["Model generates<br/>+ cites"]
    end
    ingest --> query

What varies between providers: which file types are accepted, whether you control chunking, whether you can filter by metadata, what the citation looks like, what the index costs to keep, and — critically — whether you can call retrieval without generation. That last point decides whether a managed tool can sit behind your own Retriever interface (Part 2.8) or only inside the provider's generation loop.

2.2 OpenAI: File Search and vector stores#

OpenAI's managed RAG is the file_search tool in the Responses API (it also works in Chat Completions), backed by vector stores you create and fill yourself. Source: File search guide and Retrieval guide, as of November 2026.

Index time. You upload files to the Files API, attach them to a vector store, and OpenAI parses, chunks, embeds and indexes them:

python
# openai_file_search.py — the index-time flow, per the official guide.
# Illustrative: needs OPENAI_API_KEY; output shapes follow the documented API.
import time
from openai import OpenAI

client = OpenAI()

# 1. Upload the file (Files API)
with open("handbook.pdf", "rb") as f:
    file = client.files.create(file=f, purpose="assistants")

# 2. Create a vector store and attach the file
store = client.vector_stores.create(
    name="handbook-kb",
    # expires_after={"anchor": "last_active_at", "days": 30},  # optional TTL, 1-365 days
)
vs_file = client.vector_stores.files.create_and_poll(
    vector_store_id=store.id,
    file_id=file.id,
    # Optional: metadata filters and chunking strategy
    attributes={"department": "people", "year": "2026"},
    chunking_strategy={
        "type": "static",
        "static": {"max_chunk_size_tokens": 800, "chunk_overlap_tokens": 200},
    },
)
print("file status:", vs_file.status)   # "completed" when indexed

Documented details that matter:

  • Chunking: chunking_strategy static accepts max_chunk_size_tokens between 100 and 4096 (default 800) and chunk_overlap_tokens (default 400, must not exceed half the chunk size). An auto strategy also exists. You can set chunking per file or per batch.
  • Attributes: each vector-store file takes an attributes map — at most 16 keys, keys up to 64 characters, string values up to 512 characters (values may also be booleans or numbers) — used for filtering. There is no nested schema, no full-text metadata index beyond these keys.
  • Batch ingestion: vector_stores.file_batches ingests up to 500 files per request; file and batch creation share a limit of 300 requests/minute per store.
  • File limits: max 512 MB and 5,000,000 tokens per file (tokens computed automatically). Supported types are a fixed list — PDF, DOCX, PPTX, HTML, Markdown, JSON, code files, TXT and similar; notably no CSV, XLSX or image files as of November 2026. Check the supported-files table before you plan an upload.
  • Supported file types caveat: text MIME types must be UTF-8, UTF-16 or ASCII encoded.

Query time — inside the model. The file_search tool is one entry in the tools array; the model decides when and how to search:

python
# openai_file_search_query.py — the query-time flow.
# Needs `store` from openai_file_search.py (the vector store you created there),
# or fetch it again: store = client.vector_stores.retrieve("<vs_id>")
# Illustrative output.
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-luna",
    input="How many vacation days do contractors get?",
    tools=[{
        "type": "file_search",
        "vector_store_ids": [store.id],          # one or more stores
        "max_num_results": 5,                     # 1-50; default ~10
        "filters": {                              # attribute filter, applied before ranking
            "type": "in", "key": "department", "value": ["people", "contracts"],
        },
        "ranking_options": {
            "ranker": "auto",                      # or "default-2024-11-15"
            "score_threshold": 0.0,                # 0-1; higher = fewer, more relevant chunks
            # Optional RRF weights (API reference + SDK type; not in the guide page):
            # "hybrid_search": {"embedding_weight": 0.5, "text_weight": 0.5},
        },
    }],
    include=["file_search_call.results"],          # return raw chunks, not just citations
)
print(response.output_text)

# The tool call itself is inspectable: which queries the model issued,
# and (with include=["file_search_call.results"]) the raw chunks + scores.
for item in response.output:
    if item.type == "file_search_call":
        print("queries:", item.queries)
Example output · illustrative4 lines
Contractors do not accrue paid vacation under the Contractor Agreement;
unpaid leave can be requested through the standard leave process.

queries: ["contractor vacation days entitlement", "vacation policy for contractors"]

Documented details that matter:

  • max_num_results: 1–50; the underlying search returns 10 by default. Fewer results = fewer retrieved tokens = cheaper and faster, at some quality cost.
  • filters: comparison filters (eq, ne, gt, gte, lt, lte, in, nin) on file attributes, combined with and/or compound filters. Filters apply to files, not individual chunks — every chunk of a matching file is eligible.
  • ranking_options: three fields on the file_search tool, per the API reference and the openai SDK type definitions (the reference and the SDK's FileSearchTool type agree, checked 11 November 2026): ranker (auto or the dated default-2024-11-15; the retrieval guide's prose example names default-2024-08-21, which neither the reference nor the SDK types list, so treat the typed values as the current ones), score_threshold (0–1) and hybrid_search — an embedding_weight and a text_weight that balance semantic against keyword matches in reciprocal-rank fusion. Where each is documented matters: the file-search guide page itself mentions only max_num_results, filters and the include option, so treat the ranking options as API-reference-level knobs; the retrieval-only vector_stores.search endpoint's SDK type lists ranker (which also accepts none to skip reranking and save latency) and score_threshold but not hybrid_search, although the retrieval guide's prose does describe tuning hybrid_search weights there, so test whether your SDK version and endpoint accept it. Either way you can weight the fusion; you cannot see it (no per-result semantic-vs-keyword breakdown), and OpenAI documents no default weights, so only change them against your eval set.
  • Results: by default you get the answer text with file citations as annotations, not the retrieved chunks. include=["file_search_call.results"] returns the raw chunks (text, filename, score) — this is what makes the retriever evaluable (2.8). The call object also exposes queries — the exact search strings the model issued — which is the closest thing to visibility into the model's query formulation.
  • vector_stores.search extras: the retrieval-only endpoint (2.8) accepts rewrite_query=true, which has OpenAI rewrite your natural-language query for better retrieval — the rewritten query comes back in the response's search_query field. This is the one query-understanding knob a managed retriever exposes, and it matters because inside the file_search tool loop the model writes the retrieval query itself, bypassing your 07.3 rewriting pipeline (2.7).
  • Pricing (pricing page, as of November 2026): $0.10 per GB per day of vector-store storage (first 1 GB free) plus $2.50 per 1,000 tool calls (the pricing page lists the per-call fee for the Responses API), plus the model's normal token costs — retrieved chunks are billed as input tokens. Calls to the retrieval-only vector_stores.search endpoint are not listed as tool calls, but check the page for your tier before assuming they are free.
  • Rate limits: file-search tool calls share the model's normal rate limits; the docs list 500 RPM on the Build tier and 1,000 RPM on Launch/Grow for file search.
  • Retention & residency: /v1/vector_stores is not Zero-Data-Retention eligible — with no expiry policy the index is application state kept until you delete it (abuse-monitoring logs are still 30 days). You can set an expires_after policy (anchor: "last_active_at", days 1–365) on create or update: once expired the store's status flips to expired, its files are deleted and storage billing stops — useful for ephemeral corpora like a quarterly report or a temporary eval set. On the data-controls page (checked 11 November 2026) /v1/vector_stores and file search are listed for regional storage on all ten regional endpoints (us., eu., au., ca., jp., in., sg., kr., gb. and ae. api.openai.com), but for regional processing the page lists file search only for the United States and Europe endpoints, and several regions carry extra requirements (for example an active ZDR agreement), so "data stays in region" depends on which of the two you need and which endpoint you use. Re-read that page for your account before you promise residency.
  • The embedding model is not documented. OpenAI does not publish which embedding model vector stores use as of November 2026; community sources report text-embedding-3-large at reduced dimensions, but treat that as unverified. You cannot choose or swap it.

2.4 Anthropic: no vector store — citations, search-result blocks and tools#

Anthropic has no managed vector store and no file-search tool as of 1 December 2026 (re-checked against the Claude Platform docs for search results and the Files API on 2026-12-02; the Files API stores files you reference by file_id in Messages requests, and it does not chunk, embed or search them for you). Its answer to RAG is deliberately different: you retrieve yourself (or via a tool), then hand Claude the results as search_result content blocks, and its citations feature ties claims to sources. Sources: Search results, Citations, Files API, as of November 2026.

Two ways search_result blocks reach the model:

  1. In a tool result — your custom search tool returns them inside a tool_result block, which is the dynamic-RAG path (closest to what file_search does, but you own retrieval). A complete round trip is route C of 07.5 §3.2.
  2. Directly in a user message — for pre-fetched or cached content.
python
# anthropic_search_results.py — a search_result block inside a user message.
# Illustrative: needs ANTHROPIC_API_KEY.
import anthropic

client = anthropic.Anthropic()

msg = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "How many vacation days do contractors get?"},
            {"type": "search_result",
             "source": "kb://handbook/contractor-agreement",   # any stable identifier works
             "title": "Contractor agreement",
             "content": [{"type": "text",
                          "text": "Contractor agreement: no paid vacation entitlement for contractors."}],
             "citations": {"enabled": True}},
        ],
    }],
)
for block in msg.content:
    if block.type == "text":
        print(block.text)
        for cit in getattr(block, "citations", []) or []:
            print("  cited:", cit)
Example output · illustrative9 lines
Contractors receive no paid vacation entitlement under the Contractor
Agreement; they may request unpaid leave.

  cited: {'type': 'search_result_location',
          'cited_text': 'Contractor agreement: no paid vacation entitlement for contractors.',
          'source': 'kb://handbook/contractor-agreement',
          'title': 'Contractor agreement',
          'search_result_index': 0,
          'start_block_index': 0, 'end_block_index': 1}

Notice the citation type: a search_result block yields a search_result_location citation (source, title, search_result_index, and the span of your own content blocks, start_block_index to end_block_index), not the char_location you get for a plain-text document. Because you wrote the source and title, the citation carries your identifiers straight back, and it maps onto a chunk ID with no lookup table.

The citations feature also works on document content blocks — PDF, plain text, or custom content you supply — with citations: {"enabled": True} set on all or none of the documents (or search results) in a request; mixing the two settings is an error. For documents, Claude chunks the text into sentences and returns citation objects with locations: page ranges for PDFs (page_location), character offsets for text (char_location), content-block indices for custom content (content_block_location). That is passage-level attribution decided by Anthropic's chunker, not yours. Two more constraints from the docs (as of November 2026): cited_text does not count toward your output tokens, and enabling citations together with output_config.format structured output returns a 400 error — see 07.5 §3.2 for what to do instead.

What Anthropic does offer on the managed side:

  • Files API — upload documents once, reference them by file_id in document blocks across requests (with context and title fields, and citations enabled per document); unlike citations, the Files API is not ZDR-eligible (files are retained until you delete them or they expire).
  • Web search server tool — web_search_20250305 (basic), web_search_20260209 (adds dynamic filtering: Claude writes code that filters results before they hit the context window), web_search_20260318 (response-inclusion control for agentic flows). These run on Anthropic's infrastructure (server_tool_use blocks), cite sources, and web search is ZDR-eligible except for dynamic filtering, which Anthropic lists as not eligible for ZDR or HIPAA; the _20260209 and later versions use dynamic filtering by default (allowed_callers defaults to code execution), so set allowed_callers: ["direct"] if you need the ZDR-eligible direct path (web search is billed at $10 per 1,000 searches plus tokens). Citations and search_result blocks are ZDR-eligible too, with one caveat from Anthropic's data-retention page (checked 11 November 2026): the Covered Models (Claude Fable 5.2, 5.1 and 5, Mythos 5.2, 5.1 and 5) require 30-day retention, so "eligible" does not apply to them unless Anthropic authorises it. Check the model you intend to use before promising a customer zero retention.
  • MCP connector and client tools — the intended RAG path is your retriever exposed as a tool (or an MCP server), with search_result blocks carrying the evidence back. Retrieval quality is entirely yours to measure — which is the point of 06.10's harness.

2.3 Google: Gemini File Search and grounding tools#

Gemini's managed RAG is the File Search tool, exposed through file_search_stores in the google-genai SDK and usable from both generate_content and the Interactions API. Source: File search guide, as of November 2026.

Index time. You create a store — and unlike OpenAI, you choose the embedding model:

python
# gemini_file_search.py — index time, per the official guide.
# Illustrative: needs GEMINI_API_KEY.
import time
from google import genai
from google.genai import types

client = genai.Client()

store = client.file_search_stores.create(config={
    "display_name": "handbook-kb",
    "embedding_model": "models/gemini-embedding-2",   # multimodal; omit for text-only default (gemini-embedding-001)
})

op = client.file_search_stores.upload_to_file_search_store(
    file="handbook.pdf",
    file_search_store_name=store.name,
    config={
        "display_name": "handbook.pdf",
        "chunking_config": {"white_space_config": {
            "max_tokens_per_chunk": 512,
            "max_overlap_tokens": 64,
        }},
        "custom_metadata": [
            {"key": "department", "string_value": "people"},
            {"key": "year", "numeric_value": 2026},
        ],
    },
)
while not op.done:
    time.sleep(5)
    op = client.operations.get(op)
print("indexed:", store.name)

Documented details that matter:

  • Embedding model choice: embedding_model accepts models/gemini-embedding-2 (multimodal — text and images, PNG/JPEG up to 4K) or defaults to models/gemini-embedding-001 (text-optimised). This is a real knob OpenAI doesn't give you.
  • Two upload paths: upload_to_file_search_store takes a local file or path directly; import_file pulls in a file you already uploaded via the Files API. Both return a long-running operation you poll.
  • Chunking: chunking_config.white_space_config exposes max_tokens_per_chunk and max_overlap_tokens — coarser control than OpenAI's (no min/max bounds documented; the strategy is whitespace-based).
  • Metadata: custom_metadata is a list of key/value pairs (string_value or numeric_value). At query time a metadata_filter string follows Google's list-filter syntax, AIP-160 — the guide's own example is author="Robert Graves", and AIP-160 also defines AND/OR combinations such as category="footwear" AND season="spring-2026". The guide page defers to AIP-160 for the full grammar rather than restating it.
  • Retention: raw uploaded File objects are deleted after 48 hours, but the imported data in the store persists indefinitely until you delete the store or document (no TTL; embeddings die only if the model is deprecated).

Query time. The file_search tool goes in tools, with store names and an optional metadata filter:

python
# gemini_file_search_query.py — query time via generate_content.
# Illustrative output.
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="How many vacation days do contractors get?",
    config=types.GenerateContentConfig(
        tools=[types.Tool(file_search=types.FileSearch(
            file_search_store_names=[store.name],
            metadata_filter='department="people"',
            top_k=8,                     # chunks retrieved per query — the one ranking-adjacent knob
        ))],
    ),
)
print(response.text)

# Citations ride on the response: grounding_metadata -> grounding_chunks
# -> retrieved_context (title, page_number, media_id for images).
gm = response.candidates[0].grounding_metadata
for chunk in gm.grounding_chunks or []:
    rc = chunk.retrieved_context
    print(rc.title, rc.page_number)
Example output · illustrative5 lines
Contractors do not accrue paid vacation; unpaid leave may be requested
through the standard leave process.

Contractor agreement  4
Leave policy — overview  12

The Interactions API spells the same thing as a plain dict ({"type": "file_search", "file_search_store_names": [...], "metadata_filter": "..."}) and returns file_citation annotations on text blocks — with file_name, source, page_number, custom_metadata and a media_id you can use to download a cited image via file_search_stores.download_media.

Documented details that matter:

  • top_k: types.FileSearch also accepts top_k — the number of semantic retrieval chunks fetched per query (the google-genai type documents it; the File Search guide page does not mention it, so test its effect on your store). It is the one ranking-adjacent knob Gemini exposes; there is still no score threshold, ranker choice or hybrid-weight control. It matters doubly when adapting the tool to a k-bounded Retriever contract (2.8).
  • Supported models (as of November 2026, from the File Search guide): Gemini 4 Carbon (gemini-4-carbon, generally available since 10 November 2026 per the Gemini changelog; see 02.9, 2.3); Gemini 4 Argon; 3.8 Flash; 3.6 Flash; 3.5 Flash-Lite; 3.1 Pro Preview; 3.1 Flash-Lite; 3 Flash Preview; 2.5 Pro; and 2.5 Flash-Lite. File Search is not available in the Live API.
  • No tool mixing: File Search cannot be combined with google_search grounding or url_context in the same call as of November 2026 — pick one built-in grounding source per request. (Gemini 3 and 4 models can combine File Search with custom function-calling tools.)
  • Limits: max 100 MB per file; total store size depends on tier — Free 1 GB, Tier 1 10 GB, Tier 2 100 GB, Tier 3 1 TB — and Google recommends keeping each store under ~20 GB for latency. Store size counts roughly 3× your input size (documents + embeddings).
  • Pricing (as of November 2026): you pay embedding-generation cost at index time (per the gemini-embedding pricing), storage is free, query-time embeddings are free, and retrieved document tokens are billed as ordinary context tokens. There is no per-call tool fee — a structurally different (and often cheaper) model than OpenAI's.
  • Multimodal: with gemini-embedding-2, images (PNG/JPEG ≤ 4K) are indexed alongside text and citations can point at them. Audio and video are not supported.
  • Grounding siblings: google_search (types.Tool(google_search=types.GoogleSearch(), exclude_domains=[...])) grounds on live web results with groundingMetadata (queries run, sources, citation spans); url_context ({"url_context": {}}) lets the model read specific URLs. Both are separate tools — the natural partner for File Search in a hybrid "private docs + public web" product, used in separate calls or alternating turns.

2.5 OpenRouter: no RAG store — plugins and server tools#

OpenRouter is a router, not a platform: it has no vector store, no file-search index, no managed retrieval. What it has are plugins (request/response mutations that run once per call) and server tools (model-invoked tools that run 0–N times). Sources: Plugins, Web search server tool, PDF inputs, as of November 2026.

  • File parsing (file-parser plugin): {"id": "file-parser", "pdf": {"engine": ...}} parses PDFs you attach to the request into text the model can read. Engines: cloudflare-ai (PDF→markdown, free), mistral-ocr (~$2 per 1,000 pages; $2.20 in the US region), native (for models that accept files natively — billed as input tokens). With no engine set, OpenRouter prefers the model's native file handling and falls back to mistral-ocr; mistral-ocr forwards at most 8 extracted images per PDF to the model. The older pdf-text engine is deprecated and redirects to cloudflare-ai. On Chat Completions the response carries file annotations you can echo back on later requests to skip re-parsing costs. This parses per request — there is no persistent index, so it's "RAG" only in the sense that the whole document rides in the prompt (see 07.1's long-context discussion).
  • Web search: the web plugin and the :online model-slug suffix are both deprecated in favour of the openrouter:web_search server tool — use the explicit tools entry. Engines: auto (the default: native search when the model's provider has it, otherwise Exa), native (the provider's own search, for example Anthropic, Google, OpenAI and SpaceXAI models), exa, firecrawl, parallel, perplexity. max_results 1–25 (default 5; 1–20 for Perplexity, and ignored under native provider search), allowed_domains/excluded_domains filters (honoured by Exa/Firecrawl/Parallel/Perplexity and some native providers — Google's native search supports neither, and OpenAI's honours only allowed_domains; Exa accepts both lists together, the others make them mutually exclusive), plus budget knobs max_uses (searches per request) and max_total_results. Firecrawl is rejected when Zero Data Retention is enforced.
  • The pattern for private docs: upload nothing persistent — chunk and embed yourself (Modules 05–06), retrieve with your own retriever, and pass chunks as message content; or expose your retriever as an MCP server that OpenRouter-routed models can call. OpenRouter's role is model access and routing, not retrieval.
python
# openrouter_plugins.py — the two request shapes, per the docs.
# Illustrative: needs OPENROUTER_API_KEY; OpenRouter speaks Chat Completions
# through the openai SDK (lesson 03.5).
from openai import OpenAI

client = OpenAI(base_url="https://openrouter.ai/api/v1")

# 1. Server tool: model decides when to search the web (0-N calls per request)
resp = client.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[{"role": "user", "content": "What changed in the latest privacy policy?"}],
    tools=[{"type": "openrouter:web_search",
            "parameters": {"engine": "native", "max_results": 5}}],
)

# 2. Plugin: PDF parsing, runs once per request (mutates the request).
# `plugins` is not a Chat Completions parameter — it travels in the body,
# so with the openai SDK it goes through extra_body (one spelling only).
resp2 = client.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[{"role": "user", "content": [
        {"type": "text", "text": "Summarise the refund policy in this PDF."},
        {"type": "file", "file": {"filename": "policy.pdf", "file_data": "data:application/pdf;base64,..."}},
    ]}],
    extra_body={"plugins": [{"id": "file-parser",
                             "pdf": {"engine": "cloudflare-ai"}}]},
)

# Web-search answers carry url_citation annotations on the message. The openai
# SDK parses them into objects, so use attribute access (not ann["..."]).
print(resp.choices[0].message.content)
for ann in getattr(resp.choices[0].message, "annotations", None) or []:
    if ann.type == "url_citation":
        print("  cited:", ann.url_citation.url)
Example output · illustrative4 lines
The privacy policy was updated on 2026-10-01: data retention for
account records is now 24 months.

  cited: https://example.com/privacy

2.6 Provider comparison table#

OpenAI File Search Anthropic Gemini File Search (optional) OpenRouter (optional)
Managed index ✅ vector stores ❌ none ✅ file search stores ❌ none
You choose embedding model ❌ (undocumented) n/a ✅ gemini-embedding-001/2 n/a
Chunking control size + overlap (100–4096) n/a (sentence chunking for citations) max tokens + overlap n/a
Metadata filters attributes (≤16 keys) + eq/ne/gt/gte/lt/lte/in/nin, and/or n/a custom_metadata + AIP-160 metadata_filter string n/a
Retrieval without generation ✅ vector_stores.search ✅ your tool, your retriever ⚠️ store APIs manage files; query path is the model tool ✅ your retriever
Citation granularity file-level annotations (+ raw chunks via include) sentence/page/char/block via citations API page-level for PDFs, image media_id provider-dependent (web search citations)
Multimodal index ❌ text files only documents incl. PDF/images via Files API ✅ images w/ embedding-2 per-request PDF parsing only
Pricing shape $/GB-day storage + $/1k calls + tokens tokens only (+ web search per-call) index-time embeddings + tokens (storage & query embeddings free) tokens + plugin/search fees
Retention index until deleted (or expires_after TTL); not ZDR-eligible your data stays yours; web search ZDR for basic version store until deleted; raw files 48h depends on routed provider
Regions regional endpoints incl. file search Anthropic regions Gemini API regions routed provider's regions

2.7 What managed tools hide — and why it matters#

Every row of "❌" and "⚠️" above is a knob you give up. Concretely, a managed tool decides for you:

  • How documents are parsed — a scanned PDF's OCR quality, a table's structure, a footer's noise. Module 05 spent eleven lessons on this; the managed tool gives you one parser.
  • How chunks are cut — you get at most size/overlap. No semantic chunking, no parent-child, no per-doc-type strategies (Module 05 owns all of these).
  • Which embedding model runs — OpenAI doesn't even document theirs; Gemini gives you two choices.
  • How results are ranked and fused — dense vs keyword vs hybrid weights are mostly fixed or coarse (score_threshold, ranker and RRF hybrid_search weights on OpenAI, set but not observable; only top_k on Gemini).
  • What query the retriever sees — inside the tool loop, the model writes the retrieval query. Your 07.3 rewriting pipeline is bypassed entirely unless you go around the tool. The one exception is OpenAI's vector_stores.search, which accepts rewrite_query=true — a managed-side query rewrite you can switch on, or bypass with your own 07.3 pipeline.
  • Update semantics — delete-and-reindex vs incremental; how long a change takes to appear; whether deletes propagate.

None of this is a reason not to use them — for a prototype or a small corpus, "good enough retrieval in an afternoon" beats "perfect retrieval in a month". It is a reason to measure before you trust, which is the next section.

2.8 Evaluating a black-box retriever#

The 06.10 harness evaluates any Retriever — it only sees search(query, k, filters) -> list[Hit]. A managed tool fits the contract in two ways, and the difference matters:

Path What you see What you lose
Search API (OpenAI vector_stores.search; a platform's query API) ranked chunks + scores + file metadata nothing — full Hit mapping
Tool-call loop (OpenAI file_search in Responses; Gemini file_search in generate_content) citations/annotations only, unless you also pass include=["file_search_call.results"] the query the model issued, intermediate ranking, per-stage scores

Prefer the search-API path for evaluation: it isolates retrieval from generation, exactly like your custom retriever. The tool-loop path measures the whole system — retrieval plus the model's query formulation — which is also valuable but answers a different question.

Adapter code. The bridge is small because the contract is small. This maps OpenAI's vector_stores.search response onto Hit:

python
# docs_qa/managed.py — adapt a managed search API to the Retriever protocol
# (06.10: search(query, k, filters) -> list[Hit]).
# `Hit` and `Retriever` are imported from the 06.10 retrievers module.
from __future__ import annotations

from retrievers import Hit  # id, score, text, metadata, source — the 06.10 contract


class OpenAIStoreRetriever:
    """Retrieve from an OpenAI vector store via vector_stores.search —
    retrieval WITHOUT generation, so the 06.10 harness can score it."""

    name = "openai-file-search"

    def __init__(self, client, vector_store_id: str, rewrite_query: bool = False):
        self.client = client
        self.vector_store_id = vector_store_id
        self.rewrite_query = rewrite_query   # let OpenAI rewrite the query for retrieval

    def search(self, query: str, k: int = 10,
               filters: dict | None = None) -> list[Hit]:
        # Translate the harness's flat filters dict into OpenAI's
        # ComparisonFilter/CompoundFilter DSL (see filter translation below).
        api_filters = _to_openai_filters(filters) if filters else None
        page = self.client.vector_stores.search(
            vector_store_id=self.vector_store_id,
            query=query,
            max_num_results=max(1, min(k, 50)),     # API caps at 50
            filters=api_filters,
            rewrite_query=self.rewrite_query,        # response carries search_query either way
        )
        hits = []
        for r in page.data:
            # Each result carries file_id/filename/score/attributes/content[].text
            text = "\n".join(c.text for c in r.content if getattr(c, "text", None))
            hits.append(Hit(
                id=f"{r.file_id}:{r.filename}",
                score=r.score,
                text=text,
                metadata=dict(r.attributes or {}),
                source="openai-file-search",  # black box: backend name, not a pipeline stage
            ))
        return hits


def _to_openai_filters(filters: dict) -> dict:
    """Flat {key: value} harness filters -> OpenAI compound 'and' of 'eq' filters.
    Extend for in/not-in when the eval set needs set membership."""
    clauses = [{"type": "eq", "key": k, "value": v} for k, v in filters.items()]
    return clauses[0] if len(clauses) == 1 else {"type": "and", "filters": clauses}

The same pattern works for any platform with a query API: Bedrock KB's Retrieve/RetrieveAndGenerate, Snowflake SEARCH_PREVIEW, Databricks ai_search() — each becomes a Retriever adapter of 30–60 lines. This is the single most important habit in this lesson: never let a managed retriever exist outside the contract. If it can't produce Hits, you can't evaluate it, can't A/B it, and can't swap it.

One nuance on Hit.source: the 06.10 convention puts the pipeline stage there ("dense", "bm25", "rrf", "reranker:..."). A managed retriever hides its internal stages, so the adapter above carries the backend name instead — the only honest provenance label available. Keep that distinction in mind when you compare source values across retrievers: a custom hybrid retriever and a vendor adapter will report on different axes.

For the tool-loop path (no search API), you can still evaluate end-to-end — run the labelled question set through the full Responses call and score the answer with the 07.9 generation metrics. That measures the system, not the retriever; say so in your report.


Part 3: Cloud platforms#

Deep-dive

Provider tools (Part 2) are the shallow end of "buy": one API, one corpus shape, one model family. Cloud platforms are the deep end: a managed retrieval service inside your cloud account, which your application (and any model) can call. They sit between "provider tool" and "build it yourself" — you still write ingestion triggers and the generation call, but the index, ranking and scaling are theirs.

The four that matter as of November 2026, neutrally:

3.1 Google Cloud: Vertex AI RAG Engine (now part of Gemini Enterprise Agent Platform)#

Google's managed RAG is the RAG Engine — RagCorpus objects you create, import files into, and query — now surfaced under the Gemini Enterprise Agent Platform branding in the docs. Sources: RAG Engine docs, RAG quickstart, as of November 2026.

  • Corpus: a RagCorpus holds RagFiles. You pick the embedding model and the vector DB backend in the corpus config. Note the API moved: the top-level rag_embedding_model_config/rag_vector_db_config fields are deprecated in the current v1beta1 reference in favour of backend_config (vectorDbConfig or the newer vertexAiSearchConfig for Agent Platform Search) plus corpusTypeConfig (document vs memory corpus) — older docs and SDK versions still show the old field names, so check which your installed client emits.
  • Ingestion: import_files pulls from Cloud Storage, Google Drive, Slack, Jira or SharePoint, or a ≤25 MB direct upload. RagFileChunkingConfig exposes chunk_size/chunk_overlap. Unchanged files are deduplicated on re-import (skipped_rag_files_count).
  • Backends: default is ragManagedDb (Google-managed; choose KNN or ANN retrieval — ANN for corpora over ~10K files). The vector_db union also offers Google's own vector search service on the Gemini Enterprise Agent Platform, Feature Store (formerly Vertex AI Feature Store), and Pinecone — Pinecone being the only non-Google managed vector DB we cover on the list, which matters when weighing lock-in and exit cost. The embedding config can specify a hybridSearchConfig (dense endpoint plus BM25 sparse search with tunable k1/b parameters) — more ranking control than most managed tools expose.
  • Query: retrieval returns ranked contexts you pass to any Gemini (or supported) model; the platform also integrates with Agent Engine/ADK for agentic retrieval.
  • Fit: strongest if you're already on GCP and want managed ingestion from Google-native sources (Drive, Slack, Jira) without running a vector DB. Data stays in your GCP project; VPC-SC and CMEK are supported (data residency and AXT controls are not, per the docs).

3.2 AWS: Amazon Bedrock Knowledge Bases#

Bedrock's managed RAG is Knowledge Bases: you point it at a data source, it parses/chunks/embeds/indexes into a vector store you choose, and you query via Retrieve or RetrieveAndGenerate. Source: KB docs, managed KB, as of November 2026.

  • Two KB types, two connector sets. The newer managed KB (generally available since 17 June 2026) — where Bedrock hosts the vector store, embedding model, reranker and retrieval — carries the broad connector list, which has grown every month since launch: S3, Box, Confluence Cloud and Data Center, SharePoint Online, Google Drive, OneDrive, Salesforce, ServiceNow, Zendesk, Web Crawler and Custom (API-pushed). Customer-managed KBs (you choose and run the vector store; the docs also call them custom knowledge bases) are being steered to S3 and the custom API-push source: since 30 September 2026 AWS no longer allows new Confluence, SharePoint, Salesforce or Web Crawler connectors on them (existing connectors keep working). Check which connectors your KB type supports before designing ingestion — in GovCloud, managed KBs offer S3 + Custom only. Sources: the managed KB connector list and the GA announcement, checked 8 November 2026.
  • Managed KB extras: a managed parser, selectable chunking (default / fixed-size / none), multimodal indexing for images, audio and video (optionally via the TwelveLabs Marengo Embed 3.0 embedding model), an agentic retriever (query planning, interim-result evaluation and re-ranking for multi-hop questions) alongside plain hybrid retrieval, a deletion-protection threshold on syncs (a sync that would delete more than N% of indexed documents, default 15, skips its delete phase — a cheap guard against an empty source bucket wiping your index), optional sync schedules (daily/weekly/monthly), and a managedSearchConfiguration block in the Retrieve call (the vectorSearchConfiguration field applies only to customer-managed KBs).
  • Managed KB embedding trade-off. The default is a service-managed embedding model (no model choice, no dimension tuning). You can instead pick a Bedrock embedder (Titan Text Embeddings V2, Cohere Embed v3/v4, Nova Multimodal Embeddings, or TwelveLabs Marengo 3.0 for image/audio/video) — but the embedding type cannot be changed after creation, and a KB with a custom embedding model cannot use the managed reranker. That is a real "own the knob, lose the feature" decision to make before the first sync, not after.
  • Pricing shape (managed KB, as of November 2026, Bedrock pricing page): index storage $5.00 per GB of raw data per month; managed parsing, managed embeddings and the managed reranker are $0; $1.00 per 1,000 Retrieve calls; agentic retrieval adds $4.00 per 1,000 agentic calls on top of the underlying retrieve calls. Compare that shape with OpenAI's ($/GB-day plus $/1k calls) in the cost model of 1.3: AWS has a higher storage rate but bundles the embedding and rerank work.
  • Ingestion is a sync job (StartIngestionJob) that crawls changes since last sync — plus direct KnowledgeBaseDocuments ingestion on supported data sources.
  • Vector stores — your choice (customer-managed KBs): OpenSearch Serverless or Service, Aurora (RDS), Neptune, Pinecone, Redis Enterprise Cloud, S3 Vectors — or the managed KB default where Bedrock hosts the vector store for you.
  • Embedding models (customer-managed KBs): Bedrock-hosted (Amazon Titan, Cohere Embed) or your own; multimodal options exist (Titan Multimodal, TwelveLabs Marengo for image/audio/video).
  • Chunking & metadata: configurable per data source; sidecar .metadata.json files control per-file attributes, including an includeForEmbedding flag that decides whether a metadata key/value is concatenated into the chunk before embedding (boosting metadata-aware retrieval) — a genuinely useful knob.
  • Fit: strongest if you're on AWS and want the broadest choice of vector store and embedding model, with data sources that already live in AWS. More moving parts than a provider tool; the Retrieve API is clean for your Retriever adapter.

Snowflake's answer is Cortex Search — a fully managed hybrid search service defined in SQL over a Snowflake table, aimed squarely at RAG inside the Snowflake ecosystem. Source: Cortex Search overview, CREATE CORTEX SEARCH SERVICE, as of November 2026.

sql
CREATE OR REPLACE CORTEX SEARCH SERVICE handbook_svc
  ON chunk_text
  ATTRIBUTES department, doc_type
  WAREHOUSE = search_wh
  TARGET_LAG = '1 hour'
  EMBEDDING_MODEL = 'snowflake-arctic-embed-l-v2.0'
  AS (SELECT chunk_text, department, doc_type FROM rag_chunks);
  • What it is: hybrid vector + keyword retrieval with semantic reranking built in — no embedding model to run, no vector DB to manage. ATTRIBUTES columns are your filterable metadata; TARGET_LAG sets freshness (how far behind the source table the index may lag); EMBEDDING_MODEL picks a Snowflake-managed embedder (or you supply your own vectors).
  • Query: Python API, REST API, or the SEARCH_PREVIEW SQL function; results feed Cortex Agents (Snowflake's agent framework) or your own app. Dynamic filters, per-call column selection, limit up to 1,000 results (default 10), and tunable ranking via scoring_config/named scoring_profile are supported; the SQL and Python APIs also offer multi_index_query for column-targeted search.
  • Fit: strongest if your corpus already lives in Snowflake tables — the index is defined on your data, not uploaded to a foreign store, which is the cleanest data-residency story of the four for Snowflake shops.

Databricks' answer is AI Search (renamed from Vector Search in 2026) plus Lakebase Search for operational Postgres workloads. Sources: AI Search, Lakebase Search, ai_search(), as of November 2026.

  • AI Search: an index built on a Delta Lake table (or streaming table/materialized view) with HNSW ANN search, hybrid keyword+vector, reranking, metadata filtering, ACLs on endpoints, and automatic sync when the source table changes. Query via REST API, the vector_search() SQL function, or — in Beta — ai_search(), which takes knowledge sources (AI Search indexes or Lakebase tables), plans queries across them, dedupes, reranks, and can synthesize a grounded answer in one SQL call.
  • Lakebase Search: Postgres extensions inside Lakebase projects — lakebase_vector for ANN search (a pgvector-compatible lakebase_ann index using IVF partitioning + RaBitQ quantization, claimed to build 50–100× faster than HNSW and to scale past 1B vectors per index), lakebase_text for BM25 (lakebase_bm25 index), and optional lakebase_tokenizer for configurable/CJK tokenization. Enabling it on a project is irreversible (it cannot be turned off), restarts all computes in the project, and, per the ai_search page, needs beta access (checked 12 November 2026). Synced tables can mirror Unity Catalog data into search-ready Postgres types — for teams that want search co-located with their transactional data.
  • Fit: strongest if you're a Databricks shop with data in Delta tables — the "index follows your table" model removes a whole ingestion pipeline. ai_search() is the closest thing here to a managed end-to-end RAG call, and it's Beta.

3.4.1 Also worth knowing: edge and vector-vendor managed RAG#

Not every team lives in one of the clouds above. Two more managed options come up constantly in real projects, and both follow the same "retrieve without generating" rule that keeps them inside your Retriever contract. Sources: Cloudflare AI Search limits and pricing, AI Search overview, Pinecone Assistant docs, checked 8 November 2026.

  • Cloudflare AI Search — a managed search service: you create an instance, upload files or connect a source, and it indexes continuously with hybrid (semantic + keyword) search on by default, metadata filtering, OCR for scanned PDFs and images, and multimodal image search. You reach it through a Workers binding, a REST API or a built-in MCP endpoint. Billing begins 1 December 2026: a monthly allowance (5 million ingestion tokens, 10 GB-month of storage, 1,000 semantic and 1,000 full-text queries), then $0.75 per million ingestion tokens, $2.00 per GB-month of storage and $0.75 per 1,000 semantic/vector/hybrid queries (full-text queries $0.10 per 1,000). Limits: up to 10 MiB for PDFs with OCR and plain-text or code files, and 4 MiB for other formats. Fit: documentation and knowledge-base search for sites and agents already running on Cloudflare Workers; a per-tenant instance is the natural way to isolate customers. (The product was launched as AutoRAG and renamed AI Search in September 2025 per Cloudflare's changelog; older posts and the legacy /autorag/ API paths use the old name. The dates and rates above are from Cloudflare's pricing page as of November 2026; re-check before quoting any number.)
  • Pinecone Assistant — a managed layer on top of the Pinecone vector database: upload files, then call either the Chat API (retrieval plus a generated, cited answer, also available in an OpenAI Chat Completions-compatible shape) or the Context API (the same retrieval, without generation, returning structured snippets you pass to your own model). Chat is metered in assistant input and output tokens; the Context API is metered in separate context-processed tokens (per Pinecone's pricing and limits page, as of November 2026; the OpenAI-compatible chat interface is described in Pinecone's chat guide). The Context API is the one that fits Retriever, so treat the Chat API as a demo path and the Context API as the production path if you adopt it.

Both illustrate the lesson's recurring decision: take the vendor's index, but insist on a retrieval-only endpoint so you can score it with the same harness as everything else (2.8).

3.5 Neutral comparison#

Vertex AI RAG Engine Bedrock KB Snowflake Cortex Search Databricks AI Search
Core primitive RagCorpus of files Knowledge base over data source Search service over a table Index over a Delta table
You pick embedder ✅ (config) ✅ (Bedrock or own) ✅ (Snowflake-managed or own vectors) ✅ (index config)
Chunking control size + overlap per data source via source query via source table
Ranking you control medium medium low (managed ensemble) medium (rerank config)
ACL / security IAM + VPC-SC/CMEK IAM, resource policies Snowflake RBAC endpoint ACLs
Freshness re-import (dedup) sync jobs TARGET_LAG auto-sync on table change
Query without generation ✅ retrieve API ✅ Retrieve API ✅ query APIs ✅ ai_search/vector_search
Lock-in GCP APIs AWS APIs Snowflake SQL Databricks SQL/API
Best fit GCP-native docs (Drive/Slack/Jira) AWS data sources Snowflake-resident data Delta-resident data

Part 4: Frameworks and libraries#

Reference

Frameworks are the third option: their code assembles the pipeline on your infrastructure. Unlike managed tools, you still own the vector store, the embedding calls and the model calls — but their abstractions decide how documents become retrievable chunks and how queries become answers.

4.1 What frameworks actually provide#

Strip away the marketing and a RAG framework is a bundle of five things, all of which Modules 05–06 already taught you to build:

Framework piece What it is You could build it with
Loaders/readers File → parsed documents (PDF, HTML, Office, DBs, APIs) Module 05 parsers
Splitters/node parsers Documents → chunks (size, overlap, semantic, sentence-window) Module 05 chunking
Vector stores/integrations Wrappers for Pinecone, pgvector, Qdrant, Chroma, OpenSearch, ... Module 06 stores
Retrievers + query engines retrieve() → ranked nodes; query() → answer with synthesis Module 06 retrievers + Module 04 prompts
Evaluators/observability RAG metrics, tracing hooks 06.10 harness + 07.9 evals

The honest summary: a framework is a large, maintained collection of the glue between stages you already understand. Its value is breadth (200 file loaders, 50 vector stores, provider quirks handled) and velocity (a working pipeline in an afternoon). Its cost is that the glue is the product — you inherit their abstractions, their defaults, their upgrade cadence, and their blind spots.

4.2 LlamaIndex#

What it is: the most RAG-focused framework — "the data framework for LLM applications". Current release line is llama-index/llama-index-core 0.14.x (0.14.25 as of November 2026; Python ≥3.10). Sources: PyPI, docs, as of November 2026.

python
# llamaindex_minimal.py — the canonical LlamaIndex RAG in ~10 lines.
# Illustrative: needs llama-index + an OPENAI_API_KEY.
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader("data/handbook").load_data()   # loaders
index = VectorStoreIndex.from_documents(documents)              # embed + store + index
retriever = index.as_retriever(similarity_top_k=5)              # your Retriever seam
query_engine = index.as_query_engine(similarity_top_k=5)        # retrieve + synthesize

nodes = retriever.retrieve("How many vacation days do contractors get?")
for n in nodes:
    print(n.score, n.metadata, n.get_content()[:80])
print(query_engine.query("How many vacation days do contractors get?"))

What it gives you beyond that: IngestionPipeline (parse→chunk→embed→upsert as a DAG), MetadataFilters/ExactMatchFilter for pre-retrieval filtering, QueryEngine variants (RetrieverQueryEngine, CitationQueryEngine, SubQuestionQueryEngine for decomposition, RouterQueryEngine for multi-index), rerankers, chat stores, and agent workflows. The architecture mirrors the module: index-time pipeline and query-time engine are separate objects — the same offline/online split as 07.1.

Watch: the package is really a family — llama-index-core plus dozens of llama-index-llms-*, -embeddings-*, -vector-stores-*, -readers-* integrations with independent version numbers. Pinning llama-index doesn't pin your integrations; an upgrade can change retrieval behaviour silently. See 4.9.

4.3 LangChain / LangGraph#

What it is: the broadest LLM framework — chains, retrievers, agents, and the LangGraph runtime for stateful graphs. Current: langchain 1.5.x, langchain-core 1.8.x, langgraph 1.2.x (as of 12 November 2026; the samples in 08F.1 use langchain 1.5.0 and langgraph 1.2.22, the versions whose docs were read). Sources: PyPI, changelog, as of November 2026.

python
# langchain_minimal.py — retrieval chain, LangChain v1 style.
# Illustrative: needs langchain + langchain-openai + langchain-classic + langchain-text-splitters.
# The loader is a few lines of your own code: langchain-community is sunset (see the warning below).
from pathlib import Path

from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_core.prompts import ChatPromptTemplate
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chain

docs = [Document(page_content=p.read_text(), metadata={"source": str(p)})
        for p in sorted(Path("data/handbook").glob("*.md"))]
chunks = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100).split_documents(docs)
store = InMemoryVectorStore.from_documents(chunks, OpenAIEmbeddings())

retriever = store.as_retriever(search_kwargs={"k": 5})
prompt = ChatPromptTemplate.from_template(
    "Answer only from the context.\n\nContext:\n{context}\n\nQuestion: {input}"
)
qa = create_retrieval_chain(retriever, create_stuff_documents_chain(ChatOpenAI(), prompt))
print(qa.invoke({"input": "How many vacation days do contractors get?"})["answer"])

LangGraph is the stateful sibling: retrieval becomes a node in a graph (retrieve → grade → maybe re-retrieve → generate), which is the seed of the agentic patterns in 07.8. For pure RAG you don't need it; for loops and human-in-the-loop you do.

4.4 Haystack#

What it is: deepset's pipeline framework — explicitly "components connected into pipelines or agents", strong on document stores, evals and production deployments. Current stable: haystack-ai 3.5.x (3.5.0, released 10 November 2026; Python ≥3.11); the 2.x line is the previous stable. Source: PyPI, docs, as of November 2026.

python
# haystack_minimal.py — a two-node pipeline: retrieve then prompt+generate.
# Haystack 3.x style, per the official quickstart.
# Illustrative: needs haystack-ai + an OPENAI_API_KEY.
from haystack import Pipeline, Document
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.retrievers import InMemoryBM25Retriever
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.utils import Secret

# Index time: chunks go into the document store. A real pipeline uses a
# DocumentWriter component; write_documents() is the same call underneath.
store = InMemoryDocumentStore()
store.write_documents([
    Document(content="Contractors receive no paid vacation entitlement."),
    Document(content="Full-time employees accrue 25 days of paid leave per year."),
])

retriever = InMemoryBM25Retriever(document_store=store)   # the retriever reads from the store written above
prompt_builder = ChatPromptBuilder(template=[
    ChatMessage.from_system(
        "Answer using only the documents.\nDocuments:\n"
        "{% for doc in documents %}{{ doc.content }}\n{% endfor %}"
    ),
    ChatMessage.from_user("{{question}}"),
], required_variables="*")
llm = OpenAIChatGenerator(api_key=Secret.from_env_var("OPENAI_API_KEY"))

pipe = Pipeline()
pipe.add_component("retriever", retriever)
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("llm", llm)
pipe.connect("retriever", "prompt_builder.documents")
pipe.connect("prompt_builder", "llm")

result = pipe.run({
    "retriever": {"query": "contractor vacation days"},
    "prompt_builder": {"question": "contractor vacation days"},
})
print(result["llm"]["replies"])

Haystack's distinguishing feature is that pipelines are typed, inspectable objects — you can draw them, test components in isolation, and swap the document store without touching the pipeline. It also has first-class eval components (DocumentRecallEvaluator, DocumentMRREvaluator, ContextRelevanceEvaluator, FaithfulnessEvaluator) that anticipate 07.9. Watch: 3.x changed the component surface — chat generators take ChatPromptBuilder/ChatMessage templates and non-OpenAI providers live in separate haystack_integrations packages (anthropic-haystack, google-genai-haystack, …) — so check which major your installed version and docs target before copying snippets.

4.5 DSPy#

What it is: not a RAG framework but a programming model for LM pipelines — you declare signatures (input→output types) and modules, then optimise them against metrics with teleprompters (optimizers like BootstrapFewShot, MIPROv2). Current: dspy 3.5.x (3.5.0, released 10 November 2026). Source: PyPI, as of November 2026.

python
# dspy_minimal.py — RAG as a DSPy module with a retriever tool.
# Illustrative: needs dspy + provider config.
import dspy

class RAGAnswer(dspy.Signature):
    """Answer the question using only the retrieved context."""
    context: str = dspy.InputField()
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

class RAG(dspy.Module):
    def __init__(self, retriever):
        super().__init__()
        self.retriever = retriever          # your Retriever protocol fits here
        self.generate = dspy.Predict(RAGAnswer)
    def forward(self, question: str):
        hits = self.retriever.search(question, k=5)
        context = "\n\n".join(h.text for h in hits)
        return self.generate(context=context, question=question)

DSPy's value isn't retrieval — it's that prompts, few-shot examples and pipeline structure become optimisable objects you improve against your eval set automatically. It pairs naturally with the 06.10/07.9 harness: your retriever stays a plain function, DSPy tunes the generation side. Watch: it's a different paradigm — steeper learning curve, most payoff when you have an eval set and iteration budget.

4.6 txtai and RAG-in-a-box#

  • txtai (txtai 9.14.x, October 2026): an all-in-one embeddings database + API + agent tooling — txtai gives you an embedded vector store, REST API, and RAG pipelines with minimal code. Great for a self-contained service or edge deployments; less suited when you already have a vector DB and want the framework to stay out of the way.
  • RAG-in-a-box apps (Dify, Flowise, Langflow, Open WebUI, Khoj, etc.): full applications with ingestion UI, chat UI and pipelines pre-wired. They are products, not libraries — evaluate them as products (export your data, check their chunking defaults, read their eval story) rather than as dependencies. Several are open source if you need to own the deployment.
  • The pattern to notice: every one of these is "Modules 05–06 as a product". If you adopt one, you're adopting their chunking, their embedding defaults and their retrieval — the same black-box trade-off as Part 2, with more control knobs exposed.

4.7 Vercel AI SDK (TypeScript — mention only)#

The path is Python-only, but you'll meet this in TypeScript shops: the Vercel AI SDK (ai v7.x, @ai-sdk/langchain adapter) has first-class RAG primitives — embedding providers, vector stores, embedMany, retrieval helpers and streaming UI hooks — and LangChain graphs can be adapted into its stream protocol. If your team ships Next.js, it's the idiomatic choice; the concepts map 1:1 onto what you've built here (embed → store → retrieve → generate → stream). Nothing in this lesson depends on it.

4.8 A minimal framework version of docs_qa#

Here's the same pipeline you've built across 07.1–07.6, expressed in LlamaIndex terms — the point is to see the mapping, not to adopt it:

docs_qa piece (this module) LlamaIndex equivalent
Module 05 ParsedDocument/Chunk + enrichment Document + IngestionPipeline + node parsers
Embedder protocol (06.1) Settings.embed_model / integration embedder
VectorStore + Retriever (06.x) VectorStoreIndex + as_retriever()
QueryPlan (07.3) QueryTransform / query-rewrite components
ContextBuilder + grounding PromptSpec (07.4) PromptTemplate / PromptHelper + response synthesizers
Citation/cite.py (07.5) CitationQueryEngine
ConversationManager (07.6) ChatMemoryBuffer / chat stores
06.10 harness.py RetrieverEvaluator / custom eval over retrieve()

The mapping is nearly isomorphic — which is exactly why the Retriever protocol boundary matters (Part 5): whatever sits behind search() — your pgvector store, a LlamaIndex index, an OpenAI vector store, a Bedrock KB — is swappable because the contract doesn't change.

4.9 The abstraction cost and dependency hygiene#

Frameworks abstract the mechanics well and the decisions badly. The mechanics — parsing 200 file types, talking to 50 vector stores, retrying provider quirks — are genuinely hard and genuinely not your core competency. The decisions — chunk size, overlap, embedding model, top-k, prompt template, reranker — are exactly where your eval set earns its keep, and a framework's defaults are tuned for everyone's data, not yours.

Three concrete costs:

  1. Hidden defaults. VectorStoreIndex.from_documents picks an embedding model, a chunk size and a similarity threshold you didn't choose. On your eval set those defaults are a hypothesis, not an answer — measure them like any other config.
  2. Version churn. LlamaIndex's dozens of independently-versioned integration packages, LangChain's package reorganisation (langchain-community sunset on 22 May 2026 and archived 19 June 2026, langchain-classic), Haystack's 2.x→3.x transition — an "minor" upgrade can change retrieval behaviour with no code change on your side. Pin everything, read changelogs, re-run your eval set on upgrade.
  3. Escape hatches get expensive. The day you need a chunking strategy the framework doesn't expose, or a filter it can't express, you're either fighting the abstraction or bypassing it — at which point you're maintaining both their pipeline and your escape hatch.

Dependency hygiene (03.11, 13.2 covers this for provider wrappers; it applies doubly to frameworks): treat a framework like any other dependency — lock the resolved versions in your lockfile for production (the lessons' install commands name packages only, so the lockfile is where a version gets fixed), check its dependency tree doesn't fight your installed SDKs (checked against openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0, pydantic 2.14), isolate it behind your Retriever/Embedder protocols so swapping it out is a config change, and re-run your retrieval eval on every upgrade. A framework you can't remove in an afternoon is a framework that owns your pipeline.


Part 5: The hybrid approach#

Deep-dive

The best production answer is usually not a corner of the spectrum — it's a deliberate mix: own the stages where your differentiation lives, delegate the stages that are commodity.

5.1 Own the store, delegate the glue#

A common winning shape:

flowchart LR
    subgraph yours ["You own (differentiation)"]
        A["Module 05 ingestion<br/>(your parsers, chunking,<br/>metadata, ACLs)"] --> B["Module 06 store<br/>(your vector DB,<br/>hybrid, reranker)"]
        G["Your generation<br/>(07.4 prompts,<br/>07.5 citations)"]
    end
    subgraph glue ["Framework glue (commodity)"]
        F["LlamaIndex/Haystack<br/>for loaders, evals,<br/>observability only"]
    end
    B -->|Retriever protocol| G
    F -.->|optional helpers| A
    F -.->|optional eval| B
  • Own ingestion when parsing quality, chunking strategy or metadata is your edge (it almost always is for domain corpora).
  • Own the store when you need ACLs, hybrid tuning, freshness control or data residency the managed tools can't give you.
  • Delegate loaders/evals to a framework when its breadth saves real time — a SimpleDirectoryReader for 30 file types beats maintaining 30 parsers, as long as its output feeds your Chunk pipeline, not its own index.
  • Delegate nothing you can't measure. Whatever you delegate, wrap it in a Retriever/Embedder and score it on the 06.10 harness before and after.

5.2 Keep the Retriever protocol boundary#

This is the architectural rule that makes everything in this lesson reversible:

python
# docs_qa/retriever_boundary.py — every retrieval backend behind one seam.
# `Hit` comes from 06.10's retrievers.py; `Retriever` is re-declared here as
# a structural protocol — any object with search() satisfies it.
# `search()` is the ONLY method the rest of docs_qa ever calls.
from typing import Protocol
from retrievers import Hit

class Retriever(Protocol):
    name: str
    def search(self, query: str, k: int = 10,
               filters: dict | None = None) -> list[Hit]: ...

# Backends you might plug in — all satisfy the same protocol:
#   CustomRetriever      — your Module 06 pipeline (dense+BM25+rerank)
#   OpenAIStoreRetriever — Part 2.8's managed adapter
#   BedrockKBRetriever   — Retrieve API adapter
#   LlamaIndexRetriever  — wraps index.as_retriever(), maps nodes -> Hit
#   LangChainRetriever   — wraps store.as_retriever(), maps docs -> Hit

The discipline: nothing above the seam knows which backend is live. Config selects it (RETRIEVER=openai-file-search vs custom); the eval harness, the generation pipeline and the conversation manager don't change. This is what turns "should we switch to managed?" from a migration project into a config flag plus an eval run.

5.3 Migration strategies and avoiding lock-in#

  • Ingest once, index twice. Keep your parsed Chunks (Module 05 output) as the source of truth. Any managed store is a projection of that corpus — you can rebuild any of them. Never let a managed tool be the only place your cleaned data exists.
  • Dual-run during migration. Run custom and managed retrievers side by side on the same question set (the bake-off in Part 6). Shadow-compare for a sprint before cutting over; the harness gives you the diff.
  • Export before you need it. Vector stores are mostly exportable as documents, not as vectors — plan on re-embedding on the way out (embedding cost is cheap; index rebuild is a pipeline run, not a project).
  • Isolate provider specifics in the adapter. Filter DSLs, attribute schemas, score semantics, citation shapes — all live in the 30–60-line adapter, never in docs_qa core. When the vendor changes an API, you rewrite one file.
  • Date your dependencies. Every managed feature in this lesson is volatile — pin the API version/date you coded against, re-verify on upgrade, and keep the "as of November 2026" notes visible in your runbook.

Part 6: Evaluation and the bake-off#

You cannot choose between managed and custom on vibes. The method is the same one 06.10 built for retrievers, extended one level up to the whole answer.

6.1 Managed vs custom evaluation#

What you evaluate Custom pipeline Managed tool Platform
Retrieval (hit rate, recall@k, MRR) 06.10 harness directly search-API adapter → same harness query API adapter → same harness
Generation (faithfulness, relevance, citation precision) 07.9 evals on your pipeline same evals on the tool-loop output same evals on retrieve+generate
Latency your traces per-stage timing hidden; measure end-to-end + search API per-stage visible (you own retrieve call)
Cost token accounting (03.7) tokens + storage $/GB-day + $/1k calls index cost + tokens
Debuggability full trace partial (include results / citations) good (you own the retrieve call)

The rule: evaluate at the highest level you can introspect. A managed tool you can only see through citations gets end-to-end eval; one with a search API gets retrieval eval and end-to-end eval. Both numbers go in the report — a tool can retrieve well and generate poorly (bad prompting inside their loop), or retrieve poorly and generate well (lucky answers).

6.2 The bake-off procedure#

  1. Fix the question set. Use the labelled eval set from 06.10 (eval_queries.jsonl) — same queries, same qrels, same splits. Add unanswerable and freshness cases per 07.9.
  2. Fix the judge. Same generation model, same judge model, same prompts for every candidate — otherwise you're measuring the judge, not the retriever.
  3. Candidate adapters. Wrap each option as a Retriever (custom, OpenAI store, Bedrock KB, LlamaIndex-over-your-store, ...). Config-driven, one file each.
  4. Run retrieval eval. 06.10 harness per candidate → recall@k, MRR, nDCG, latency percentiles, cost/query.
  5. Run end-to-end eval. Same questions through each candidate's full answer path → faithfulness, answer relevance, citation precision, abstention accuracy (07.9 metrics).
  6. Paired comparison. Bootstrap CIs on the differences (06.10 Part 4.5) — "managed is better" needs the interval to exclude zero, not just a higher mean.
  7. Cost & ops tally. Add storage fees, per-call fees, index build time, update lag, and the engineer-hours to maintain each. The cheapest-per-query option isn't always cheapest-per-answer.
  8. Decide with a date. Record the winner and the runner-up, the eval set version, and a re-check date — managed features change monthly.

6.3 Script skeleton#

Pure Python, no dependencies — run it against fakes to see the shape. In production each Retriever is a real adapter; the comparison machinery doesn't change:

python
# bakeoff.py — compare retriever candidates on one labelled set.
# Pure local: fake retrievers below; swap in real adapters per candidate.
import json, math, random, re, time, zlib
from dataclasses import dataclass, field

@dataclass(frozen=True)
class Hit:
    id: str; score: float; text: str = ""; metadata: dict = field(default_factory=dict)

# A tiny corpus so the fake retrievers have something real to rank.
CORPUS = {
    "contract-9":   "Contractors work under the master service agreement; vacation and paid leave are not provided to contractors.",
    "contract-10":  "Invoice payment terms are net-30 from the invoice date; late payments accrue interest.",
    "contract-11":  "Liability under the master service agreement is capped at 12 months of fees.",
    "handbook-001": "Full-time employees accrue 1.5 vacation days per month; contractors do not accrue vacation.",
    "handbook-002": "Unused sick leave rolls over up to 10 days into the next year.",
    "handbook-003": "Expense reports are reviewed by your manager within 5 business days.",
    "handbook-005": "Parental leave: 16 weeks for the primary caregiver and 6 weeks for the secondary caregiver.",
    "help-101":     "Install the VPN client from the IT portal and sign in with single sign-on.",
    "help-102":     "VPN error 2041 means the client certificate expired; reinstall the VPN client.",
    "help-103":     "Reset your password from the account settings page.",
    "ticket-77":    "Billing ticket: customer disputes the March invoice and asks for a payment extension.",
}

def tokens(text):
    return re.findall(r"[a-z0-9]+", text.lower())

class FakeRetriever:
    """Deterministic stand-in whose ranking depends on the query: word overlap between the
    query and each document, plus a fixed pseudo-random 'noise' per (retriever, query, doc).
    `aliases` models query expansion (a stronger retriever knows 'rollover' ~ 'rolls over');
    `noise` models ranking wobble. The same inputs always give the same ranking."""
    def __init__(self, name, aliases=None, noise=0.0, latency_ms=0.0, cost_per_query=0.0):
        self.name, self.aliases, self.noise = name, aliases or {}, noise
        self.latency_ms, self.cost_per_query = latency_ms, cost_per_query
    def search(self, query, k=10, filters=None):
        time.sleep(self.latency_ms / 1000)
        q = set(tokens(query))
        for word in list(q):
            q.update(self.aliases.get(word, []))
        scored = []
        for doc_id, text in CORPUS.items():
            overlap = len(q & set(tokens(text)))
            jitter = (zlib.crc32(f"{self.name}|{query}|{doc_id}".encode()) % 1000) / 1000
            scored.append((overlap + self.noise * jitter, doc_id))
        scored.sort(key=lambda t: (-t[0], t[1]))
        return [Hit(id=i, score=s, text=CORPUS[i]) for s, i in scored[:k]]

@dataclass
class Query:
    qid: str; query: str; relevant: list[str]   # gold chunk ids (06.10 qrels)

def recall_at_k(hits, relevant, k):
    got = {h.id for h in hits[:k]}
    return len(got & set(relevant)) / len(relevant) if relevant else 0.0

def mrr(hits, relevant):
    for rank, h in enumerate(hits, 1):
        if h.id in relevant:
            return 1.0 / rank
    return 0.0

def run_candidate(retriever, queries, k=3):
    rows = []
    for q in queries:
        t0 = time.perf_counter()
        hits = retriever.search(q.query, k=k)
        ms = (time.perf_counter() - t0) * 1000
        rows.append({"qid": q.qid, "recall": recall_at_k(hits, q.relevant, k),
                     "mrr": mrr(hits, q.relevant), "latency_ms": ms,
                     "cost": retriever.cost_per_query})
    n = len(rows)
    return {"name": retriever.name, "rows": rows,
            "recall": sum(r["recall"] for r in rows) / n,
            "mrr": sum(r["mrr"] for r in rows) / n,
            "latency_p50": sorted(r["latency_ms"] for r in rows)[n // 2],
            "cost_per_query": retriever.cost_per_query}

def bootstrap_ci(diffs, iters=2000, seed=7):
    """95% CI for the mean paired difference (06.10's method, simplified)."""
    rng, n = random.Random(seed), len(diffs)
    means = sorted(sum(rng.choice(diffs) for _ in range(n)) / n for _ in range(iters))
    return means[int(0.025 * iters)], means[int(0.975 * iters)]

if __name__ == "__main__":
    queries = [
        Query("q1", "contractor vacation", ["contract-9", "handbook-001"]),
        Query("q2", "vpn error 2041", ["help-102"]),
        Query("q3", "payment due date for invoices", ["contract-10"]),
        Query("q4", "sick leave rollover", ["handbook-002"]),
        Query("q5", "unanswerable: CEO salary", []),   # abstention case
    ]
    aliases = {"rollover": ["rolls", "over"], "contractor": ["contractors"],
               "invoices": ["invoice"], "due": ["terms"]}
    candidates = [
        FakeRetriever("custom-hybrid", aliases, noise=0.5, latency_ms=180, cost_per_query=0.002),
        FakeRetriever("openai-file-search", {"rollover": ["rolls", "over"]}, noise=1.5, latency_ms=320, cost_per_query=0.004),
        FakeRetriever("bedrock-kb", {}, noise=2.0, latency_ms=240, cost_per_query=0.003),
    ]
    results = [run_candidate(c, queries) for c in candidates]
    for r in results:
        print(f"{r['name']:>20}  recall@3={r['recall']:.2f}  mrr={r['mrr']:.2f}  "
              f"p50={r['latency_p50']:.0f}ms  ${r['cost_per_query']:.4f}/q")

    # paired diff: managed vs custom on recall@3, query by query
    diffs = [m["recall"] - c["recall"] for m, c in zip(results[1]["rows"], results[0]["rows"])]
    lo, hi = bootstrap_ci(diffs)
    print(f"\nmanaged - custom recall@3 diff: mean={sum(diffs)/len(diffs):+.2f}, "
          f"95% CI [{lo:+.2f}, {hi:+.2f}]")
    print("per-query recall@3 (custom / managed):",
          ", ".join(f"{c['qid']}={c['recall']:.1f}/{m['recall']:.1f}"
                    for c, m in zip(results[0]["rows"], results[1]["rows"])))
Output6 lines
       custom-hybrid  recall@3=0.80  mrr=0.80  p50=185ms  $0.0020/q
  openai-file-search  recall@3=0.70  mrr=0.67  p50=323ms  $0.0040/q
          bedrock-kb  recall@3=0.70  mrr=0.80  p50=245ms  $0.0030/q

managed - custom recall@3 diff: mean=-0.10, 95% CI [-0.30, +0.00]
per-query recall@3 (custom / managed): q1=1.0/0.5, q2=1.0/1.0, q3=1.0/1.0, q4=1.0/1.0, q5=0.0/0.0

(The recall, MRR and cost columns are deterministic; the p50 latencies are measured sleeps, so yours will land within a few milliseconds of 185, 323 and 245 rather than match exactly.)

Why these numbers mean something. Each FakeRetriever ranks the toy CORPUS by word overlap with the query, so different queries get different rankings and the metrics can differ per query. The per-query line shows where the gap comes from: on q1 ("contractor vacation") custom-hybrid finds both gold chunks, while openai-file-search finds only one of them in its top 3, because it has no alias linking the query word "contractor" to the "contractors" in handbook-001, so that passage matches on a single word and its larger ranking noise is enough to push it out of the top 3. The differences are built into the fakes' aliases and noise settings, so they demonstrate the machinery (per-query scoring, paired differences, a confidence interval), not the quality of any real product. Change an alias or the noise level and the table moves; that is the point of an evaluation that depends on the query.

One simplification to fix before you reuse this code: q5 has no relevant chunks, so recall_at_k returns 0.0 for every candidate and quietly drags all three recall means down. custom-hybrid's 0.80 is really 1.00 over the four answerable queries, and the other two candidates' 0.70 is 0.875. Recall is undefined when there is nothing to find. A real harness drops such rows from retrieval metrics and scores them separately as abstention cases (what the model does when retrieval returns nothing useful; 07.9 §2.6). Note also that the fakes, like real vector search, return their top 3 for q5 anyway: nearest neighbours are never empty, which is why abstention needs its own check. Exercise 5 asks you to do exactly that.

Read it the way a senior engineer would: the managed option is slower and costlier per query in this toy, and its recall CI touches zero — not a decisive loss on five queries, not a win either. That's the honest answer a bake-off gives you: "on this set, custom is at least as good and cheaper; managed buys speed-to-ship, not quality." Five queries is a demo, not a decision — the real set is 50–200 labelled questions, and the CI is what makes the difference trustworthy.


Managed and framework RAG fails in characteristic ways — mostly silent ones, because the internals are hidden. Each row is a symptom you can actually observe, its likely root cause, and the check that catches it.

Symptom Likely cause How to catch it Fix
Answers cite the wrong document version (superseded policy still wins) Managed tool re-indexed but old file not deleted; platform sync lag Ask a question whose answer changed recently; check the cited file's date Delete/re-import the old file; check sync TARGET_LAG/job status; filter on a version/effective_date attribute
Retrieval quality dropped after a "minor" framework upgrade Hidden default changed (chunk size, top-k, score threshold, embedding model) Diff the framework changelog; re-run the 06.10 harness before/after Pin the previous version; make every default an explicit config value; gate upgrades on the eval set
Intermittently empty answers on valid questions Managed tool's score_threshold/max_num_results too strict; or metadata filter too narrow Log the tool-call params; replay the failing query with filters removed Lower score_threshold, raise max_num_results, widen the attribute filter; check for zero-result behaviour in traces
Cost per answer 3× what the pricing page implied Retrieved chunks billed as input tokens; storage $/GB-day compounding; per-call tool fees on every turn of a conversation Reconcile one week's invoice against usage tokens + call counts Cap max_num_results, cache repeated queries, prune the corpus, re-run the Part 1 cost model with real numbers
A document's ACL leaked to the wrong tenant File-level attributes can't express per-chunk or per-user ACLs; filter applied post-retrieval or forgotten Tenant-isolation test set (06.6); ask a question only one tenant's doc answers, as another tenant Move to a store/platform with native ACLs; scope the vector store or attribute per tenant; never rely on prompt instructions for access control
Citations point at the right file but wrong passage File-level (OpenAI) or page-level (Gemini) granularity too coarse for the claim Spot-check 20 citations against source text Use passage-level citations (Anthropic-style) or your own cite.py verification (07.5); retrieve-then-cite yourself for the claims that matter
The model "searched" but ignored your metadata filter Filter set on the wrong store, wrong key, or the model rephrased the query away from filtered docs Inspect the file_search_call params in the response (include=["file_search_call.results"]) Validate filter keys against the attribute schema at upload; assert filter presence in tests; prefer explicit filter construction over model-chosen
Bake-off said managed wins; production says custom wins Eval set too small or unrepresentative; judge drift; corpus changed after the bake-off Compare the eval-set distribution to production query logs Version the eval set; stratify by real query mix; re-run bake-off quarterly and on corpus changes
Ingestion "succeeds" but half the files never got indexed Per-file token/size limit silently skipped; unsupported MIME type; batch partial failure Check per-file status (vs_file.status, file_counts.failed on batches) — don't trust the batch's overall status Split oversized files upstream (Module 05 chunking); verify supported types before upload; alert on failed file counts
Answer contradicts a newer document because the old one still ranks higher No freshness signal in ranking; both versions present Ask about a recently-changed policy; check which file the citation points to Add effective_date/version attributes and filter on latest; delete superseded files; prefer platforms with sync-aware deletes

The meta-lesson: every managed failure is an observability failure first. You can't debug what you can't see, so the mitigation for almost every row is the same — get retrieval-only visibility (search API or include results) and a labelled eval set before the failure happens in production.


Common misconceptions#

Misconception Reality
"Managed RAG is always worse than building it yourself." For small corpora and standard questions, provider tools are often good enough and ship in hours. The quality ceiling is lower, but the floor is high and the cost of reaching it is near zero. Measure on your data, not in the abstract.
"If the provider offers file search, we don't need a vector database." You need a retrievable index — theirs counts. But the moment you need per-document ACLs beyond file-level filters, hybrid tuning, or data residency, their index stops being sufficient. The Retriever boundary keeps the exit open.
"File search returns the chunks, so it's just a vector DB with extra steps." It returns at most 50 chunks with coarse scores — no access to the index internals, the embedding model, or the ranking pipeline. It's a retrieval service, not an inspectable store.
"Gemini File Search and OpenAI file search are interchangeable." Different embedding models (Gemini lets you choose; OpenAI's is undocumented), different filter languages, different citation granularities (page-level vs file-level), different pricing shapes (per-GB-day + per-call vs free storage + token-billed retrieval).
"Anthropic has no RAG story." It has no vector store, but search_result blocks + citations + the Files API + web search is a complete, arguably cleaner, attribution-first RAG story — you just own retrieval.
"Frameworks are just wrappers around the same APIs." The wrapper is the value and the cost: 200 loaders, 50 stores, opinionated defaults. The pipeline you build with raw SDKs is more code but fully yours; the framework is less code but partially theirs.
"A framework's built-in evaluator means we don't need our own eval set." Their evaluators measure their metrics on their assumptions. Your labelled question set and qrels are the only ground truth that transfers across tools — keep it framework-agnostic.
"Managed tools can't be evaluated." They can — through the search API where one exists (OpenAI vector_stores.search, platform query APIs), or end-to-end through the generation call. What you can't do is introspect why a result ranked where it did.
"Vector-store storage is free because it's 'just vectors'." OpenAI charges $0.10/GB-day after the first GB (or set expires_after for ephemeral corpora); at corpus scale that's real money. Gemini charges for index-time embeddings but storage/query embeddings are free. Pricing shapes differ enough to change the build-vs-buy answer.
"Once we pick managed, we're locked in." Only if you let the managed store become the only copy of your cleaned data and put vendor APIs throughout docs_qa. Keep chunks as source of truth, adapters thin, and migration is a config change.

Key takeaways#

  • Build vs buy is a spectrum, not a switch. The useful question is which stages you own: parsing/chunking, embedding, indexing, retrieval, generation. Provider tools delegate nearly all of them; cloud platforms delegate the index; frameworks delegate the glue.
  • Score options on seven dimensions: control, quality ceiling, data residency, cost model, lock-in, observability, team skills. Cost has three shapes — usage (custom), subscription+usage (provider tools), infrastructure (platforms) — and the LLM tokens are identical across all of them.
  • OpenAI File Search (file_search + vector stores) is the most turnkey: upload → citations, with vector_stores.search giving you a retrieval-only path for eval (plus rewrite_query and expires_after TTLs). You don't pick the embedding model; storage is $0.10/GB-day + $2.50/1k calls; the index is not ZDR-eligible.
  • Gemini File Search is the most configurable managed tool: you choose the embedding model (text or multimodal), get page-level citations and image references, pay only for index-time embeddings + tokens — but stores are tier-capped and can't mix with google_search/url_context in one call.
  • Anthropic has no vector store — its RAG is search_result blocks + citations + Files API + web search server tools, with retrieval left to you. OpenRouter has no RAG store — plugins parse PDFs per-request and openrouter:web_search grounds on the web; private docs mean your own retriever.
  • Cloud platforms (Vertex AI RAG Engine, Bedrock KB, Snowflake Cortex Search, Databricks AI Search) put the index next to your data — strongest residency and governance, most platform lock-in. Platform features can be retired on a vendor's schedule, so keep the Retriever boundary. Pricing shapes differ sharply: per-GB-day plus per-call (OpenAI), per-GB-month plus per-1,000 retrievals with free managed embeddings (Bedrock managed KB), per-1,000 agentic calls on top of retrievals (Bedrock agentic retrieval), per-million-ingestion-tokens plus per-query (Cloudflare AI Search).
  • Frameworks (LlamaIndex, LangChain/LangGraph, Haystack, DSPy, txtai) sell the glue: loaders, splitters, stores, retrievers, evaluators. Their value is breadth and velocity; their cost is hidden defaults, version churn and escape-hatch friction. langchain-community was sunset on 22 May 2026 (repository archived 19 June 2026, 0.4.2 last release): check which package owns what before you write code.
  • The Retriever protocol is the great equaliser. Every option — custom, provider search API, platform query API, framework retriever — adapts to search(query, k, filters) -> list[Hit]. Keep the boundary thin and every backend becomes a config flag.
  • Evaluate black boxes from the outside. Search-API adapters feed the 06.10 harness directly; tool-loop paths get end-to-end eval. Same question set, same judge, paired bootstrap CIs — that's the bake-off.
  • Hybrid wins: own ingestion and store where your edge is, delegate commodity glue, keep chunks as source of truth, and never let a managed store be the only copy of your data.

Terms introduced in this lesson#

Term One-line definition
Managed RAG Retrieval pipeline (parse→chunk→embed→index→search) run by a provider or platform instead of your code
Vector store The indexed container a managed tool or platform builds from your files
File Search (OpenAI) OpenAI's file_search Responses tool + vector stores: upload files, model retrieves and cites
File Search store (Gemini) Google's file_search_stores container with a selectable embedding model
search_result block Anthropic content block carrying retrieved text + provenance for citation
Citation / grounding metadata Provider-returned pointers tying answer text to source locations (page, chunk, char range)
Plugin (OpenRouter) A once-per-request request/response mutation (file-parser, deprecated web)
Server tool A model-invoked tool that runs 0–N times on the provider's infrastructure (web_search, file_search)
RAG Engine / RagCorpus Vertex AI's managed RAG index object and its file container
Knowledge base (Bedrock) A managed retrieval layer binding data sources to an index and query API
Cortex Search service Snowflake's SQL-defined hybrid (vector+keyword) search service with semantic reranking
AI Search index (Databricks) Databricks' index over Delta tables with HNSW ANN, hybrid search and reranking
Framework / loader / splitter RAG libraries supplying file parsers, chunkers, store wrappers and retrievers
Query engine A framework object combining retriever + prompt + generator into query()
Build vs buy spectrum The range from owning every pipeline stage to delegating nearly all of them
Black-box retriever A managed retriever whose internals (chunking, ranking, embedding) you can't inspect
Retriever adapter A thin class mapping a managed/platform/framework search API onto the Retriever protocol
Agentic retrieval (managed) A platform feature where an LLM plans sub-queries, runs them in parallel and merges the reranked results (Bedrock managed KB, Databricks ai_search()); billed per token or per agentic call, not per plain query
search_result_location The citation type Claude returns for a search_result block: your source and title, search_result_index and the cited span of your content blocks
Retrieval-only endpoint A managed API that returns ranked chunks without generating an answer (OpenAI vector_stores.search, Bedrock Retrieve, Pinecone Context API) — the one you can wrap in a Retriever
Bake-off A controlled comparison of retrieval candidates on one labelled set, one judge, paired statistics

All terms are also collected in the glossary.


Exercises#

  1. Cost model (cost_model.py): re-run the calculator with your own numbers — a 2 GB corpus, 10k queries/month, and each provider's real pricing from Part 2/3. At what corpus size does the provider tool's storage fee overtake the platform's fixed index cost? At what query volume does the custom pipeline's per-query cost lose?

  2. Retriever adapter: implement a BedrockKBRetriever as a Retriever protocol adapter (30–60 lines), mapping the platform's query response to Hit. Run it through the 06.10 harness.py on eval_queries.jsonl with a fake client returning canned results — verify the metrics populate.

  3. Filter translation: extend _to_openai_filters to handle in/nin set membership and nested and/or, then write the inverse translator (OpenAI DSL → flat dict) for round-tripping eval filters. Test both directions on a small fixture.

  4. Framework mapping: pick one framework from Part 4 and write the equivalent of the docs_qa retrieve step using its retriever, wrapped back into your Hit shape. Note every place its defaults differ from your Module 06 config (chunk size, top-k, score threshold).

  5. Bake-off: extend bakeoff.py with a fourth candidate and a second metric (nDCG or MAP from 06.10's metrics.py). Add an unanswerable query and verify the abstention case is scored, not silently passed.

  6. Decision memo: for the Module 07 running corpus (handbook/help-centre/tickets/contracts), write a one-page build-vs-buy recommendation covering: which option you'd prototype with, which you'd run in production, and the three facts you'd re-verify in six months. Cite the sections that informed each choice.


Check yourself#

  1. What's the difference between a provider-managed tool (file_search) and a cloud platform (RAG Engine, Bedrock KB) in terms of what you own?
  2. Name the seven dimensions of the build-vs-buy framework and give one situation where each tips the decision.
  3. OpenAI file search: what are the defaults and limits for max_num_results, max_chunk_size_tokens, chunk_overlap_tokens, file size, and per-store file/batch rate limit?
  4. Why can't you pick OpenAI's embedding model for vector stores, and why does that matter for evaluation?
  5. Gemini File Search: which two embedding models can you choose, and what's the practical difference?
  6. Why can't Gemini File Search be combined with google_search or url_context in one call, and what's the workaround?
  7. Anthropic has no vector store — so how does Claude do RAG, and what does search_result give you that file citations don't? Which citation type does it return?
  8. OpenRouter has no RAG store — what do its file-parser plugin and openrouter:web_search server tool actually do, and what's the gap for private documents?
  9. Why can't you change a Bedrock managed KB's embedding type after creation, and what do you lose by picking a custom embedding model?
  10. What does the Retriever protocol boundary buy you when evaluating a black-box managed retriever?
  11. Why is vector_stores.search (OpenAI) better for retrieval eval than the file_search tool loop?
  12. In the bake-off, why do you compare candidates with paired differences and confidence intervals rather than just comparing means?
  13. A managed tool hides your chunking and ranking. Give two concrete situations where that's a real problem, and the mitigation for each.
  14. langchain-community was sunset on 22 May 2026 (repository archived 19 June 2026, 0.4.2 last release): what does that mean for a team whose loaders live there, and what's the dependency-hygiene rule?
  15. You are creating an Amazon Bedrock managed knowledge base and are tempted to pick a custom embedding model. What do you give up, and when can you change your mind?

Further resources#


← 07.6 — Conversational RAG | Module 07 overview | 07.8 — Advanced RAG: Agentic RAG, GraphRAG and Beyond →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close