---
agent:
  instructions: "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://mixpeek.com/.well-known/search?q={query}"
  method: GET
  documentation: "https://mixpeek.com/llms.txt"
---

1.  [](/)
2.  [Code examples](/recipes)
3.  Document RAG Pipeline

Back to code examples

# Document RAG Pipeline

Retrieval-augmented generation for document collections. Extracts text, tables, and figures from PDFs using OCR and layout analysis, then retrieves relevant page sections to answer natural language questions with precise page and section citations.

text

image

Multi-Stage

[Run in Builder](/build?recipe=document-rag-pipeline)

Python

cURL

from mixpeek import Mixpeek

client \= Mixpeek(api\_key\="YOUR\_API\_KEY", namespace\="policy-docs")

\# 1. A bucket for the PDFs, and a collection that splits every page into layout blocks

bucket \= client.buckets.create(

    bucket\_name\="policies",

    bucket\_schema\={"properties": {"policy": {"type": "pdf"}}},

)

collection \= client.collections.create(

    collection\_name\="policies",

    source\={"type": "bucket", "bucket\_ids": \[bucket\["bucket\_id"\]\]},

    feature\_extractor\={

        "feature\_extractor\_name": "document\_graph\_extractor",

        "version": "v1",

    },

)

client.buckets.upload(

    bucket\["bucket\_id"\],

    blobs\=\[{"property": "policy", "type": "pdf", "data": "s3://your-bucket/policies/enterprise-terms.pdf"}\],

)

client.collections.trigger(collection\["collection\_id"\])

\# 2. The retriever finds blocks, reranks them and writes the answer. BM25 reads the

\#    namespace's text payload indexes, so declare one on text\_raw before relying on it.

retriever \= client.retrievers.create(

    retriever\_name\="policy-rag",

    collection\_identifiers\=\["policies"\],

    input\_schema\={"query": {"type": "text", "required": True}},

    stages\=\[

        {

            "stage\_name": "search",

            "stage\_id": "feature\_search",

            "parameters": {

                "searches": \[

                    {

                        "feature\_uri": "mixpeek://document\_graph\_extractor@v1/intfloat\_\_multilingual\_e5\_large\_instruct",

                        "query": {"input\_mode": "text", "value": "{{INPUT.query}}"},

                        "top\_k": 50,

                    },

                    {

                        "feature\_uri": "mixpeek://document\_graph\_extractor@v1/intfloat\_\_multilingual\_e5\_large\_instruct",

                        "query": {"input\_mode": "text", "value": "{{INPUT.query}}"},

                        "top\_k": 50,

                        "lexical": True,

                    },

                \],

                "fusion": "rrf",

                "final\_top\_k": 50,

            },

        },

        {

            "stage\_name": "rerank",

            "stage\_id": "rerank",

            "parameters": {

                "inference\_name": "BAAI\_\_bge\_reranker\_v2\_m3",

                "query": "{{INPUT.query}}",

                "document\_field": "text\_raw",

                "top\_k": 8,

            },

        },

        {

            "stage\_name": "answer",

            "stage\_id": "summarize",

            "parameters": {

                "prompt": "Answer the question {{INPUT.query}} using only these numbered passages, and cite the passage numbers. {{DOCUMENTS}}",

                "provider": "google",

                "model\_name": "gemini-2.5-flash-lite",

                "content\_field": "text\_raw",

                "output\_field": "answer",

                "include\_sources": True,

            },

        },

    \],

)

results \= client.retrievers.execute(retriever\["retriever\_id"\], inputs\={"query": "What is the refund policy for enterprise customers?"})

answer \= results\["documents"\]\[0\]

print(answer\["answer"\])

\# The summary document lists the documents it read; fetch them for citations

for i, document\_id in enumerate(answer.get("source\_document\_ids") or \[\], 1):

    source \= client.documents.get(collection\["collection\_id"\], document\_id)

    print(f"\[{i}\]", source.get("root\_object\_id"), source.get("page\_number"))

### Feature Extractors

Document Graph Extractor

Decompose PDFs into spatial blocks (paragraphs, tables, forms, headers) with layout classification and E5 text embeddings.

### Retriever Stages

feature search

Search and filter documents by vector similarity using feature embeddings

filter

rerank

Rerank documents using cross-encoder models for accurate relevance

sort

summarize

Condense multiple documents into a summary using an LLM

reduce

## Frequently asked questions

### Does this handle scanned PDFs and handwritten documents?

Yes. The document-graph-extractor uses OCR and layout analysis to process scanned pages, typed text, handwritten notes, tables, and embedded figures.

### How are documents chunked for retrieval?

Documents are chunked by logical sections using layout analysis. Headers, paragraphs, tables, and figures are preserved as coherent units rather than split at arbitrary character limits.

### Can I restrict answers to specific documents?

Yes. Use attribute filters to limit retrieval to specific document IDs, categories, or date ranges before the RAG context is assembled.

## Related code examples and resources

Pages on the same stages, extractors and patterns.

[

Extractor

### Document Graph Extractor

Decompose PDFs into spatial blocks (paragraphs, tables, forms, headers) with layout classification and E5 text embeddings.

Learn more





](/extractors/document-graph)[

Recipe

### Multimodal Knowledge Base

Consolidate documents, videos, images, and audio into a single searchable knowledge base with RAG capabilities. Supports natural language Q&A across all content types, with citations linking back to the exact source document, video timestamp, or image.

Learn more





](/recipes/multimodal-knowledge-base)[

Recipe

### Document Intelligence Search

Extract and search through PDFs, presentations, and documents. Combines OCR, layout analysis, and semantic search for comprehensive document retrieval.

Learn more





](/recipes/document-search-pipeline)[

Recipe

### PDF Data Extraction Pipeline

Extract structured data from PDFs including tables, forms, and text. Convert unstructured documents into structured, queryable data.

Learn more





](/recipes/pdf-extraction-pipeline)[

Recipe

### Document Classification Pipeline

Classify documents into custom business categories using layout-aware extraction and taxonomy enrichment. Handles invoices, contracts, reports, forms, and correspondence by analyzing both textual content and visual document structure.

Learn more





](/recipes/document-classification)[

Recipe

### BYO Embeddings Vector Search

Bring pre-computed embeddings from any provider (OpenAI, Cohere, Together, etc.) and upsert them directly into MVS for instant vector search. No feature extractors, no pipelines -- just embeddings in, results out.

Learn more





](/recipes/mvs-byo-embeddings-search)