> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mixpeek.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Document intelligence for PDFs and scans

> Search PDFs page by page, native or scanned, by what each page says.

Search PDFs page by page, native or scanned, by what each page says. Every page becomes a document with its extracted text, a description and an embedding, and results can be gathered back under the file they came from.

> [card] [Jump to the manifest](#the-manifest)
>
> `document-intelligence.namespace.yaml`: apply it with one API call, then read the walkthrough below to change it.

## At a glance

| | |
| - | - |
| **Creates** | 1 namespace, 1 bucket, 1 collection, 2 retrievers |
| **Extractors** | [`universal_extractor`](https://docs.mixpeek.com/docs/extract/extractors#universal) v1 |
| **Daily spend budget** | 1 USD, set on the namespace. Queries are not capped. |
| **Sample data** | 6 objects, uploaded to `documents` when you apply |

## How the pieces connect

Buckets hold what you upload, collections turn it into searchable documents, and retrievers answer queries over the collections.

```mermaid theme={null}
flowchart LR
  b0[("documents")]
  c1["document-pages<br/>universal_extractor v1"]
  r2{{"document-search"}}
  r3{{"document-search-by-file"}}
  b0 --> c1
  c1 --> r2
  c1 --> r3
```

## Deploy it

**1. Get the manifest**

```bash theme={null}
# Copy the manifest from the bottom of this page into document-intelligence.namespace.yaml
```

**2. Validate it**

Validate runs every check apply runs and creates nothing. Fix each entry in `errors`, then run it again.

```bash theme={null}
curl -X POST https://api.mixpeek.com/v1/manifest/validate \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -F "manifest_file=@document-intelligence.namespace.yaml"
```

**3. Apply it**

Apply creates every resource in one call. `wait_for_seed=true` also waits until the sample objects are processed, so the first query below has documents to return.

```bash theme={null}
curl -X POST "https://api.mixpeek.com/v1/manifest/apply?wait_for_seed=true" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -F "manifest_file=@document-intelligence.namespace.yaml"
```

The response lists each resource with its outcome in `resources`. Apply refuses a resource that already exists and rolls the whole apply back, so to apply the file again over this namespace add `?mode=create_missing`, which creates only what is missing.

## Run the first query

Look up the namespace id by name, then run `document-search`. Check `status` and `warnings` along with `documents`: a run that times out still answers 200, with `status` `degraded`.

```bash cURL theme={null}
NAMESPACE_ID=$(curl -s https://api.mixpeek.com/v1/namespaces/document-intelligence \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" | jq -r .namespace_id)

curl -X POST https://api.mixpeek.com/v1/retrievers/document-search/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"query": "farmers allowed to hay and graze conservation reserve acres after bad weather"}}' \
  | jq '{status, warnings, documents: [.documents[] | {document_id, score}]}'
```

```python Python theme={null}
import os, requests

AUTH = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}"}
ns = requests.get("https://api.mixpeek.com/v1/namespaces/document-intelligence", headers=AUTH).json()

run = requests.post(
    "https://api.mixpeek.com/v1/retrievers/document-search/execute",
    headers={**AUTH, "X-Namespace": ns["namespace_id"]},
    json={"inputs": {"query": "farmers allowed to hay and graze conservation reserve acres after bad weather"}},
).json()

print(run["status"], run["warnings"])  # "completed" on a clean run
for doc in run["documents"]:
    print(doc["document_id"], doc["score"])
```

```javascript JavaScript theme={null}
const auth = { Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}` };
const ns = await fetch("https://api.mixpeek.com/v1/namespaces/document-intelligence", { headers: auth }).then((r) => r.json());

const run = await fetch("https://api.mixpeek.com/v1/retrievers/document-search/execute", {
  method: "POST",
  headers: { ...auth, "X-Namespace": ns.namespace_id, "Content-Type": "application/json" },
  body: JSON.stringify({"inputs": {"query": "farmers allowed to hay and graze conservation reserve acres after bad weather"}}),
}).then((r) => r.json());

console.log(run.status, run.warnings); // "completed" on a clean run
for (const doc of run.documents) console.log(doc.document_id, doc.score);
```

## Add your own data

Each object you add to a bucket is processed by every collection that reads it. This adds one object to `documents`. `NAMESPACE_ID` is the id from the namespace lookup above.

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/buckets/documents/objects?auto_process=true" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"title": "example", "document_type": "example", "issuer": "example", "blobs": [{"property": "document", "type": "pdf", "data": "https://example.com/report.pdf"}]}'
```

```python Python theme={null}
import os, requests

HEADERS = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}", "X-Namespace": os.environ["NAMESPACE_ID"]}

obj = requests.post(
    "https://api.mixpeek.com/v1/buckets/documents/objects",
    params={"auto_process": "true"},
    headers=HEADERS,
    json={
        "title": "example",
        "document_type": "example",
        "issuer": "example",
        "blobs": [
            {
                "property": "document",
                "type": "pdf",
                "data": "https://example.com/report.pdf"
            }
        ]
    },
).json()
print(obj["object_id"], obj["status"])  # PENDING until processing finishes
```

```javascript JavaScript theme={null}
const headers = {
  Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}`,
  "X-Namespace": process.env.NAMESPACE_ID,
  "Content-Type": "application/json",
};

const obj = await fetch("https://api.mixpeek.com/v1/buckets/documents/objects?auto_process=true", {
  method: "POST",
  headers,
  body: JSON.stringify({
    "title": "example",
    "document_type": "example",
    "issuer": "example",
    "blobs": [
      {
        "property": "document",
        "type": "pdf",
        "data": "https://example.com/report.pdf"
      }
    ]
  }),
}).then((r) => r.json());
console.log(obj.object_id, obj.status); // PENDING until processing finishes
```

The object is `PENDING` until processing finishes, then `COMPLETED` or `FAILED`. [Buckets and objects](https://docs.mixpeek.com/docs/ingest/buckets.md) covers object states, retries and duplicates.

## Retrievers

### `document-search`

Describe what you are looking for and get back the pages closest in meaning, from any file, best first.

**Stages:** [`feature_search`](https://docs.mixpeek.com/docs/retrieve/stages#feature-search)

**Searches:** `document-pages`

| Input | Type | Required | Description |
| - | - | - | - |
| `query` | text | yes | What to look for; embedded and compared against every page |

### `document-search-by-file`

The same search, with matching pages gathered under the file they came from: at most 3 pages per file, files ordered by their best page.

**Stages:** [`feature_search`](https://docs.mixpeek.com/docs/retrieve/stages#feature-search) → [`group_by`](https://docs.mixpeek.com/docs/retrieve/stages#group-by)

**Searches:** `document-pages`

| Input | Type | Required | Description |
| - | - | - | - |
| `query` | text | yes | What to look for; embedded and compared against every page |

## Collections

Each collection runs one extractor over a bucket, or over another collection's documents.

> [accordion] document-pages
>
> universal\_extractor\@v1 over bucket documents: one document per page, carrying the page's text (its text layer, or OCR for a scan), a generated description and a Gemini Embedding 2 vector. Feeds document-search and document-search-by-file.
>
> **Reads** bucket `documents` with [`universal_extractor`](https://docs.mixpeek.com/docs/extract/extractors#universal) v1.
>
> **Inputs:** `content` ← `document`
>
> **Copied onto each document:** `title`, `document_type`, `issuer`

## The manifest

Every resource above comes from this file. Change it and apply it again with `?mode=upsert` to update what exists. [Manifests](https://docs.mixpeek.com/docs/manage/manifests.md) documents each field.

```yaml document-intelligence.namespace.yaml expandable theme={null}
# document-intelligence: one manifest spins up a namespace that reads PDFs, native and scanned,
# and makes every page searchable.
# Platform manifest schema (GET /v1/discovery/schema). Validate with POST /v1/manifest/validate,
# apply with POST /v1/manifest/apply. Wiring: the documents bucket feeds the document-pages
# collection, which both retrievers search.
# Applying a SECOND time, over a namespace this template already created: use
# POST /v1/manifest/apply?mode=create_missing, which creates what is missing and leaves
# what exists alone. The default, create_only, fails the WHOLE apply and rolls it back if
# any resource already exists. Use mode=upsert to also patch resources that exist but have
# drifted from this file, which is how you apply an edit to a retriever or collection.
version: '1.0'
metadata:
  name: document-intelligence
  description: "Guide template document-intelligence: PDFs parsed page by page by universal_extractor (text layer or OCR), embedded with Gemini Embedding 2, and searched by meaning."
namespaces:
  - name: document-intelligence
    description: "Everything below lives in this namespace."
    feature_extractors:
      - name: universal_extractor
        version: v1
    # Payload indexes. A `text` index on the extracted page text lets a retriever add a BM25
    # keyword search; `keyword` indexes make exact-match filters on document_type and issuer
    # fast and are required to filter or group on them inside a vector search.
    payload_indexes:
      - field_name: text
        type: text
      - field_name: document_type
        type: keyword
      - field_name: issuer
        type: keyword
    # Daily spend budget, in dollars of what you are charged (1,000 credits a dollar).
    # New batches pause once the namespace has spent this much today; queries are not capped.
    # Raise it later on the namespace: PATCH /v1/namespaces/<id> {"spend_budget": {"daily_usd": N}}.
    budget:
      daily_usd: 1

buckets:
  - name: documents
    namespace: document-intelligence
    description: "One object per file: the PDF in document, plus a title, a document_type and the issuer. Upload files here or write objects through the API."
    schema:
      properties:
        document:
          type: pdf
          required: true
        title:
          type: string
        document_type:
          type: string
        issuer:
          type: string

collections:
  - name: document-pages
    namespace: document-intelligence
    description: "universal_extractor@v1 over bucket documents: one document per page, carrying the page's text (its text layer, or OCR for a scan), a generated description and a Gemini Embedding 2 vector. Feeds document-search and document-search-by-file."
    source:
      type: bucket
      bucket: documents
    feature_extractor:
      name: universal_extractor
      version: v1
      input_mappings:
        content: document
      parameters:
        extract_text: true
        generate_description: true
        max_document_pages: 10
      field_passthrough:
        - source_path: title
        - source_path: document_type
        - source_path: issuer
    enabled: true

retrievers:
  - name: document-search
    namespace: document-intelligence
    description: "Describe what you are looking for and get back the pages closest in meaning, from any file, best first."
    collections:
      - document-pages
    input_schema:
      query:
        type: text
        required: true
        description: "What to look for; embedded and compared against every page"
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://universal_extractor@v1/gemini-embedding-2"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 50
          final_top_k: 10
    tags:
      - template:document-intelligence
  - name: document-search-by-file
    namespace: document-intelligence
    description: "The same search, with matching pages gathered under the file they came from: at most 3 pages per file, files ordered by their best page."
    collections:
      - document-pages
    input_schema:
      query:
        type: text
        required: true
        description: "What to look for; embedded and compared against every page"
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://universal_extractor@v1/gemini-embedding-2"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 50
          final_top_k: 50
      - stage_name: by_file
        stage_id: group_by
        parameters:
          group_by_field: source_object_id
          max_per_group: 3
          output_mode: all
    tags:
      - template:document-intelligence

# Six public-domain PDFs. Three are current IRS forms with a native text layer, served by
# irs.gov. Three are 1984 to 1986 issues of the USDA Farm Broadcasters Letter, scanned by the
# Internet Archive and hosted on Wikimedia Commons (licence: public domain). The two kinds
# share no vocabulary, so a query about grain exports lands on the letters and a query about
# withholding lands on the forms.
seed:
  - bucket: documents
    max_objects: 6
    objects:
      - blobs: {document: "https://www.irs.gov/pub/irs-pdf/fw9.pdf"}
        title: "Form W-9, Request for Taxpayer Identification Number and Certification"
        document_type: tax_form
        issuer: IRS
      - blobs: {document: "https://www.irs.gov/pub/irs-pdf/fw4.pdf"}
        title: "Form W-4, Employee's Withholding Certificate"
        document_type: tax_form
        issuer: IRS
      - blobs: {document: "https://www.irs.gov/pub/irs-pdf/f1040.pdf"}
        title: "Form 1040, U.S. Individual Income Tax Return"
        document_type: tax_form
        issuer: IRS
      - blobs: {document: "https://upload.wikimedia.org/wikipedia/commons/1/1e/Farm_broadcasters_letter_%28IA_CAT82764458008%29.pdf"}
        title: "Farm Broadcasters Letter No. 2180, September 13, 1984"
        document_type: newsletter
        issuer: USDA
      - blobs: {document: "https://upload.wikimedia.org/wikipedia/commons/9/93/Farm_broadcasters_letter_%28IA_CAT82764458031%29.pdf"}
        title: "Farm Broadcasters Letter No. 2203, March 7, 1985"
        document_type: newsletter
        issuer: USDA
      - blobs: {document: "https://upload.wikimedia.org/wikipedia/commons/a/a5/Farm_broadcasters_letter_%28IA_CAT82764458088%29.pdf"}
        title: "Farm Broadcasters Letter No. 2261, May 8, 1986"
        document_type: newsletter
        issuer: USDA
```

## Hand it to an agent

Paste this prompt into Claude Code, Cursor or another coding agent. To give the agent this whole page instead, use **Copy page** in the menu at the top of the page, or point it at the page's Markdown at `https://mixpeek.com/docs/templates/document-intelligence.md`.

```text Prompt theme={null}
Set up the Mixpeek "Document intelligence for PDFs and scans" template in my organization. My API key is in MIXPEEK_API_KEY.
1. Save the manifest at the bottom of https://mixpeek.com/docs/templates/document-intelligence as document-intelligence.namespace.yaml.
2. POST it to https://api.mixpeek.com/v1/manifest/validate as the multipart field manifest_file, with the header Authorization: Bearer $MIXPEEK_API_KEY. Fix every entry in errors and validate again.
3. POST the same file to https://api.mixpeek.com/v1/manifest/apply?wait_for_seed=true. Every entry in resources should be created.
4. GET https://api.mixpeek.com/v1/namespaces/document-intelligence and keep namespace_id. Send it as the X-Namespace header on every call below.
5. POST {"inputs": {"query": "farmers allowed to hay and graze conservation reserve acres after bad weather"}} to https://api.mixpeek.com/v1/retrievers/document-search/execute. Read documents, check that status is completed, and print warnings.
Reference for this template: https://mixpeek.com/docs/templates/document-intelligence.md
```

## How it works

`universal_extractor` reads the bucket's `document` property, detects that the file is a document, and works page by page. Each page becomes one document in `document-pages` with these fields:

| Field | What it holds |
| - | - |
| `text` | The page's text. A native PDF gives its text layer; a scanned page is read with OCR. |
| `description` | A short description of the page, written by Gemini. |
| `page_number` | The page's number in the file. |
| `segment_index`, `segment_total` | The page's position and the file's page count, as the extractor counted them. |
| `modality` | `document` for a PDF. |

Each page also gets a 3072-dimension vector from Gemini Embedding 2, which both retrievers search as `mixpeek://universal_extractor@v1/gemini-embedding-2`. Gemini Embedding 2 puts text, images, audio, video and PDFs in one vector space, so a text query compares directly with a page.

The parameters in the manifest:

* `extract_text: true` writes `text`. Turn it off and pages are still searchable by their vector, but there is no text to read, filter on, rerank or match with BM25.
* `generate_description: true` writes `description`.
* `max_document_pages: 10` caps the pages processed per file (default 50, ceiling 200). Raise it before you upload longer files.

The seed mixes native PDFs (IRS forms W-9, W-4 and 1040) with scans (three USDA Farm Broadcasters Letters from 1984 to 1986), so you see both text paths.

Each change below is an edit to the manifest. Apply it again with `?mode=upsert`.

## Find pages, then files

`document-search` returns pages. Two pages from the same file come back as two documents, each with its own score.

`document-search-by-file` adds a `group_by` stage on `source_object_id`, the bucket object each page came from:

* `max_per_group: 3` keeps the 3 best pages of each file.
* `output_mode: all` returns each group with its pages. Use `first` for one page per file, the best match, or `flatten` for a plain list with at most 3 pages per file.

Files come back in the order of their best page. `final_top_k: 50` on the search gives the grouping enough pages to fill several files.

To trace any page back to its file and the collections that processed it, read its lineage. Each document carries `collection_id` and `document_id`:

```bash cURL theme={null}
read COLLECTION_ID DOCUMENT_ID < <(curl -s -X POST https://api.mixpeek.com/v1/retrievers/document-search/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"query": "who must provide a taxpayer identification number"}}' \
  | jq -r '.documents[0] | "\(.collection_id) \(.document_id)"')

curl -s "https://api.mixpeek.com/v1/collections/$COLLECTION_ID/documents/$DOCUMENT_ID/lineage" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  | jq '.lineage | {root_object_id, root_bucket_id, source_type}'
```

## Filter by document type

Every page carries its file's `document_type` and `issuer`, both indexed as `keyword`. Send `filters` in the execute body to search one kind of file:

```bash cURL theme={null}
curl -X POST https://api.mixpeek.com/v1/retrievers/document-search/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {"query": "sales of corn and wheat to the Soviet Union"},
    "filters": {"AND": [{"field": "document_type", "operator": "eq", "value": "newsletter"}]}
  }' \
  | jq '{status, warnings, documents: [.documents[] | {title, page_number, score}]}'
```

To fix the filter into a retriever instead, put `pre_filters` on the search stage, beside `parameters`:

```yaml document-search stages, IRS forms only theme={null}
    stages:
      - stage_name: search
        stage_id: feature_search
        pre_filters:
          AND:
            - field: issuer
              operator: eq
              value: IRS
        parameters:
          searches:
            - feature_uri: "mixpeek://universal_extractor@v1/gemini-embedding-2"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 50
          final_top_k: 10
```

## Match form numbers and exact terms

An embedding treats a form number like "1040" as a loose number. Add a BM25 search over the extracted page text, which the namespace already indexes as `text`, and fuse it with the dense search:

```yaml document-search stages, dense plus BM25 theme={null}
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://universal_extractor@v1/gemini-embedding-2"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 50
            - feature_uri: "mixpeek://universal_extractor@v1/gemini-embedding-2"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              lexical: true
              top_k: 50
          fusion: rrf
          final_top_k: 10
```

The entry with `lexical: true` searches no vector: it matches the query's words against the `text` index, and its `feature_uri` only scopes it to this collection. `rrf` merges the two lists by rank.

## Rerank pages

A cross-encoder orders pages more precisely than vector distance. Add a `rerank` stage after the search and point it at `text`:

```yaml document-search stages, with a rerank stage theme={null}
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://universal_extractor@v1/gemini-embedding-2"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 50
          final_top_k: 20
      - stage_name: rerank
        stage_id: rerank
        parameters:
          inference_name: BAAI__bge_reranker_v2_m3
          query: "{{INPUT.query}}"
          document_field: text
          max_candidates: 20
          top_k: 5
```

The stage's default `document_field` is `content`, which these pages do not have, and a document without the field is left out. `max_candidates` caps how many pages are scored; at 4 CPU, 10 documents take about 8 seconds with `BAAI__bge_reranker_v2_m3`.

## Change what is extracted

Edit `feature_extractor.parameters` on `document-pages`:

```yaml document-pages feature_extractor.parameters theme={null}
      parameters:
        extract_text: true
        generate_description: false
        max_document_pages: 50
```

* `generate_description: false` skips the Gemini call that writes `description`.
* `output_dimensionality` (256 to 3072) shrinks the vectors. It resizes the vector index, so set it before the first upload: a collection that already holds documents refuses a change to it.

New settings apply to objects processed after the change. Pages already written keep what they were extracted with.

> [!NOTE]
>
> The collection reads one property per object. To also index phone photos of documents, add a bucket with an `image` property and a second collection with `universal_extractor` over it. Both collections share the Gemini Embedding 2 space, so list both in the retriever's `collections` and one query searches PDFs and photos together.

## Next steps

> [card] [Universal extractor](https://docs.mixpeek.com/docs/extract/extractors.md#universal)
>
> Every parameter and output field, for documents, images, audio and video.

> [card] [Group By](https://docs.mixpeek.com/docs/retrieve/stages.md#group-by)
>
> Grouping modes, ordering within a group and caps on group position.

> [card] [Classify documents](https://docs.mixpeek.com/docs/enrich/taxonomies.md)
>
> Label each file by type (contract, invoice, form) with a taxonomy.

> [card] [Text extractor](https://docs.mixpeek.com/docs/extract/extractors.md#text)
>
> Run a second collection over the page text for chunking and structured extraction.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.