> ## 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.

# Stages

> Every retriever stage: what it does, when to use it, the parameters you set, a JSON example, and its latency or cost.

A [retriever](https://docs.mixpeek.com/docs/retrieve/retrievers.md) runs a list of stages in order. Each stage takes the documents from the stage before it and passes on a new list. This page lists every stage by category, then gives each one a section with its parameters and an example. `GET /v1/retrievers/stages` returns every stage's full parameter schema ([List available retriever stages](https://docs.mixpeek.com/docs/api-reference/retriever-stages/list-available-retriever-stages.md)).

| Stage | `stage_type` | What it does | Typical latency |
| - | - | - | - |
| **Filter** | | | |
| [`feature_search`](#feature-search) | `filter` | Vector, keyword (BM25) or hybrid search with fusion | 10 to 80 ms |
| [`attribute_filter`](#attribute-filter) | `filter` | Keep documents whose fields match conditions | 5 to 20 ms |
| [`llm_filter`](#llm-filter) | `filter` | Keep documents an LLM approves against your criteria | 200 to 500 ms |
| [`agent_search`](#agent-search) | `filter` | LLM loop that calls other stages as tools | 2 to 30 s |
| [`query_expand`](#query-expand) | `filter` | Search LLM-written query variations and fuse | 300 to 800 ms |
| **Sort** | | | |
| [`sort_relevance`](#sort-relevance) | `sort` | Order by a score field | under 5 ms |
| [`sort_attribute`](#sort-attribute) | `sort` | Order by a field, with optional score boosts | under 5 ms |
| [`mmr`](#mmr) | `sort` | Diversify results | 10 to 50 ms |
| [`rerank`](#rerank) | `sort` | Rescore with a cross-encoder or decision model | about 3 s per document on CPU |
| [`maxsim_rerank`](#maxsim-rerank) | `sort` | Rescore with ColBERT late interaction | |
| [`score_normalize`](#score-normalize) | `sort` | Rescale scores | under 1 ms |
| **Reduce** | | | |
| [`limit`](#limit) | `reduce` | Keep the first N | under 1 ms |
| [`score_threshold`](#score-threshold) | `reduce` | Drop documents under an absolute score | under 1 ms |
| [`deduplicate`](#deduplicate) | `reduce` | Remove duplicates by field or text | 5 to 100 ms |
| [`sample`](#sample) | `reduce` | Random or stratified sample | under 5 ms |
| [`aggregate`](#aggregate) | `reduce` | Counts, sums, averages and more, per group | 5 to 50 ms |
| [`temporal`](#temporal) | `reduce` | Metrics per time window, with drift | 5 to 50 ms |
| [`summarize`](#summarize) | `reduce` | LLM summary of the documents | 500 to 2,000 ms |
| [`moment_group`](#moment-group) | `reduce` | Merge video segments into moments | 5 to 50 ms |
| **Group** | | | |
| [`group_by`](#group-by) | `reduce` | Group by a field value | 5 to 20 ms |
| [`cluster`](#cluster) | `reduce` | Cluster by embedding at query time | 50 to 200 ms |
| **Apply** | | | |
| [`json_transform`](#json-transform) | `apply` | Reshape each document with a template | under 1 ms per document |
| [`rag_prepare`](#rag-prepare) | `apply` | Pack documents into an LLM context with citations | under 10 ms |
| [`unwind`](#unwind) | `apply` | One document per array element | under 5 ms |
| [`api_call`](#api-call) | `apply` | Call an HTTP API per document | 100 to 500 ms |
| [`sql_lookup`](#sql-lookup) | `apply` | Query PostgreSQL per document | 10 to 100 ms |
| [`external_web_search`](#external-web-search) | `apply` | Add web results from Exa | 200 to 500 ms |
| [`external_reverse_image`](#external-reverse-image) | `apply` | Add web matches for an image | |
| [`web_scrape`](#web-scrape) | `apply` | Fetch page content from URLs | 500 to 5,000 ms |
| [`cross_compare`](#cross-compare) | `apply` | Match elements against a reference collection | 50 to 1,500 ms |
| [`traverse_edge`](#traverse-edge) | `apply` | Follow edges, lineage or time overlap to related documents | |
| **Enrich** | | | |
| [`llm_enrich`](#llm-enrich) | `apply` | Write LLM output to a field | 300 to 800 ms per batch |
| [`classify`](#classify) | `apply` | Label documents with a classifier | depends on the model |
| [`taxonomy_enrich`](#taxonomy-enrich) | `apply` | Attach taxonomy nodes | 20 to 100 ms |
| [`document_enrich`](#document-enrich) | `apply` | Join a document from another collection | 5 to 20 ms per document |
| [`agentic_enrich`](#agentic-enrich) | `enrich` | Multi-turn agent writes a structured label | 2 to 30 s per document |
| [`code_execution`](#code-execution) | `enrich` | Run your Python or JavaScript in a sandbox | 5 to 50 ms per document |

Put cheap stages first. A filter or `limit` before `rerank` or an LLM stage cuts the documents those slow stages process.

## Stage object

Every stage in a retriever's `stages` array has the same shape:

```json Stage object with every optional key theme={null}
{
  "stage_name": "search",
  "stage_type": "filter",
  "config": {
    "stage_id": "feature_search",
    "parameters": {
      "searches": [
        {
          "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
          "query": {"input_mode": "text", "value": "{{INPUT.query}}"}
        }
      ]
    },
    "pre_filters": {
      "AND": [{"field": "metadata.language", "operator": "eq", "value": "en"}]
    }
  },
  "on_error": "skip",
  "output_alias": "text_hits"
}
```

| Key | Description |
| - | - |
| `stage_name` | Your label. Response metadata is keyed by it, under `stage_statistics.stages.<stage_name>`. |
| `stage_type` | Optional. The API infers it from `stage_id`. Execute-time `filters` merge only into `filter` stages. |
| `config.stage_id` | The stage to run, from the table above. |
| `config.parameters` | The stage's parameters, as listed in its section. |
| `config.pre_filters` | A [filter](https://docs.mixpeek.com/docs/retrieve/retrievers.md#filters) applied before the stage. `post_filters` is accepted and never applied. |
| `on_error` | `skip` continues with the previous stage's documents. Default `error` fails the run. |
| `output_alias` | Also store this stage's output at `CONTEXT.<alias>` for later stages. |

Parameters accept `{{INPUT.*}}`, `{{DOC.*}}`, `{{CONTEXT.*}}` and `{{STAGE.*}}` templates (see [Stages and templates](https://docs.mixpeek.com/docs/retrieve/retrievers.md#stages-and-templates)).

**LLM stages.** `llm_filter`, `llm_enrich`, `summarize`, `agent_search` and `agentic_enrich` take `provider` (`openai`, `google`, `anthropic`, `typesafe`) and `model_name`. To use your own provider key, store it with `POST /v1/organizations/secrets` and set `api_key` to `{{secrets.your_secret_name}}`. `llm_filter` and `llm_enrich` refuse a run that sends them more than `max_candidates` documents (default 10, at most 50), before any model call.

## Filter stages

A filter stage keeps a subset of documents with the same schema. `feature_search` and `attribute_filter` can also run first and read documents from the collections.

### Feature search

Finds documents by vector similarity, keyword (BM25) match, or both. Each entry in `searches` queries one feature index, and the stage fuses the hits into one ranked list. Use it as the first stage of almost every retriever.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `searches` | array | `[]` | One entry per index to query, up to 10. Each entry takes `feature_uri`, `query` and optional `top_k` (default `100`, max `5000`). |
| `searches[].query.input_mode` | string | `text` | `text`, `content` (URL or base64), `document` (reuse a stored document's vector), `vector` or `multi_content`. |
| `final_top_k` | integer | `25` | Documents returned after fusion, 1 to 5,000. |
| `fusion` | string | `rrf` | How several searches combine: `rrf`, `dbsf`, `weighted`, `max` or `learned`. See [Tune relevance](https://docs.mixpeek.com/docs/retrieve/relevance.md#hybrid-search-fusion-strategies). |
| `collection_identifiers` | array | retriever's collections | Collection ids or names this stage searches. A list only; a template is refused. |
| `select_fields` | array | every field | Fields to read for each result. A field a later stage needs must be in the list. |

```json feature_search stage theme={null}
{
  "stage_name": "search",
  "stage_type": "filter",
  "config": {
    "stage_id": "feature_search",
    "parameters": {
      "searches": [
        {
          "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
          "query": {"input_mode": "text", "value": "{{INPUT.query}}"},
          "top_k": 100
        }
      ],
      "final_top_k": 25
    },
    "pre_filters": {
      "AND": [
        {"field": "metadata.status", "operator": "eq", "value": "published"}
      ]
    }
  }
}
```

`pre_filters` sits beside `parameters` inside `config`, and the vector store applies it during the search, so `top_k` counts matching documents. Filtered fields need payload indexes. A wrong `feature_uri` returns an error listing the `available_feature_uris` for your collections.

**Latency:** 10 to 50 ms for one search, 20 to 80 ms with fusion.

> [accordion] Per-search options
>
> | Parameter | Type | Default | Description |
> | - | - | - | - |
> | `lexical` | boolean | `false` | Run this entry as BM25 only. Needs a `text` payload index. Fuse it with a dense entry under `rrf` for hybrid search. |
> | `lexical_field` | string | none | With `lexical: true`, the one text field to match, for example `transcript`. |
> | `filters` | object | none | Conditions for this entry only, in the `pre_filters` shape. A document must match both. |
> | `weight` | number | `1.0` | This entry's weight under `weighted`, `rrf` and `dbsf`. |
> | `min_score` | number | none | Drop this entry's hits below the score, 0 to 1. |
> | `optional` | boolean | `false` | Skip this entry when its index is empty instead of failing. |
> | `on_empty` | string | `error` | What happens when the query input resolves to empty: `error`, `skip` or `random`. |
> | `query_preprocessing` | object | none | Split a large query file (video, PDF) into chunks with its extractor, search each, and fuse. Takes `max_chunks` (default `20`) and `aggregation` (`rrf`, `max`, `avg`). |

> [accordion] Query by image, by a stored document, or with both
>
> Each entry's `query` picks its own `input_mode`, so one stage can fuse a text search with an image search. `content` embeds a URL or base64 file with the index's extractor; `document` reuses the vectors a stored document already has, with no inference.
>
> ```json feature_search with text, image and document queries theme={null}
> {
>   "stage_id": "feature_search",
>   "parameters": {
>     "searches": [
>       {
>         "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
>         "query": {"input_mode": "text", "value": "{{INPUT.query}}"}
>       },
>       {
>         "feature_uri": "mixpeek://image_extractor@v1/google_siglip_base_v1",
>         "query": {"input_mode": "content", "value": "{{INPUT.image_url}}"}
>       },
>       {
>         "feature_uri": "mixpeek://image_extractor@v1/google_siglip_base_v1",
>         "query": {"input_mode": "document", "document_ref": {"collection_id": "col_products", "document_id": "doc_product_123"}}
>       }
>     ],
>     "fusion": "rrf",
>     "final_top_k": 25
>   }
> }
> ```

> [accordion] Group and facet inside the search
>
> `group_by` groups hits in the vector store by a field such as `source_object_id`. It takes `field`, `max_per_group` (default `1`), `limit` (default `25` groups, overrides `final_top_k`) and `output_mode` (`first`, `all`, `flatten`).
>
> `facets` returns value counts per field alongside the hits. Each entry is `{"key": "metadata.category", "limit": 10, "exact": false}`, and the field needs a keyword index. Facets count under `pre_filters` only.

### Attribute filter

Keeps documents whose fields match conditions. After a search it filters the documents in memory. As the first stage it reads matching documents straight from the collections, with no embeddings needed.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `field` | string | none | Field path for a single condition, for example `metadata.status`. |
| `operator` | string | `eq` | One of the 20 operators in [Filters](https://docs.mixpeek.com/docs/retrieve/retrievers.md#filters). |
| `value` | any | none | Literal or template. A list for `in` and `nin`, a boolean for `exists` and `is_null`. |
| `conditions` | object | none | `AND`, `OR` and `NOT` lists of `field`/`operator`/`value` conditions. Use instead of `field`. |
| `natural_language` | string | none | A plain-English filter that an LLM turns into `conditions` at run time. Adds one LLM call, about 200 to 500 ms. |
| `case_insensitive` | boolean | `false` | Compare strings without case. |
| `max_scan_documents` | integer | `10000` | First stage only: the most documents scanned per collection, up to `100000`. |

```json attribute_filter stage theme={null}
{
  "stage_name": "in_stock_under_price",
  "stage_type": "filter",
  "config": {
    "stage_id": "attribute_filter",
    "parameters": {
      "conditions": {
        "AND": [
          {"field": "metadata.in_stock", "operator": "eq", "value": true},
          {"field": "metadata.price", "operator": "lte", "value": "{{INPUT.max_price}}"}
        ]
      }
    }
  }
}
```

When a first-stage scan stops with matches left, the response carries a warning and a `first_stage_scan_documents` entry in `limits`. Raise `max_scan_documents` when a later group or aggregate needs every match.

**Latency:** 5 to 20 ms.

### LLM filter

Sends each document to an LLM with your criteria and keeps the ones it approves. Use it for judgments a field cannot express, such as tone or topic, after a search has narrowed the set.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `criteria` | string | `Keep only documents relevant to {{INPUT.query}}` | What to keep and what to drop. An empty value skips the stage. |
| `provider` | string | `google` | `openai`, `google`, `anthropic` or `typesafe`. Inferred from `model_name` when omitted. |
| `model_name` | string | provider default | For example `gpt-4o-mini`, or `jev-latest` for calibrated keep/discard probabilities. |
| `max_candidates` | integer | `10` | The most documents the stage accepts, up to `50`. A run that sends more is refused before any model call. |
| `include_media` | boolean | `false` | Send each document's image or video to the model with its fields. |
| `include_reasoning` | boolean | `false` | Record each decision's reason in the stage metadata. |

```json llm_filter stage theme={null}
{
  "stage_name": "technical_only",
  "stage_type": "filter",
  "config": {
    "stage_id": "llm_filter",
    "parameters": {
      "criteria": "Keep only technical documentation about {{INPUT.query}}. Drop marketing pages.",
      "provider": "openai",
      "model_name": "gpt-4o-mini",
      "max_candidates": 20
    }
  }
}
```

Kept documents come back unchanged. **Latency:** 200 to 500 ms per batch, about 100 tokens per document.

### Agent search

Runs an LLM reasoning loop that calls other stages as tools, deciding at each turn what to search or filter next. Use it for multi-hop questions where you cannot fix the pipeline in advance.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `strategy` | string | `iterative_refinement` | `iterative_refinement`, `multi_hop`, `tree_navigation`, `cluster_navigation`, `full_catalog` or `custom`. |
| `stages` | array | from strategy | Stage ids the agent may call, for example `["feature_search", "attribute_filter"]`. |
| `max_iterations` | integer | `5` | Reasoning turns, 1 to 20. |
| `timeout_seconds` | number | `60.0` | Wall-clock limit for the loop, 5 to 300. The agent returns partial results on timeout. |
| `min_confidence` | number | `0.0` | The loop keeps going while the agent's confidence is below this. |
| `context_source` | object | none | `{"type": "manifest"}` gives the agent a map of the retriever's collections, fields and clusters. |
| `provider`, `model_name` | string | provider default | The model needs tool calling. |

```json agent_search stage theme={null}
{
  "stage_name": "agent",
  "stage_type": "filter",
  "config": {
    "stage_id": "agent_search",
    "parameters": {
      "strategy": "multi_hop",
      "max_iterations": 5,
      "timeout_seconds": 60,
      "context_source": {"type": "manifest"}
    }
  }
}
```

`cluster_navigation` walks a cluster hierarchy top-down with a beam search over the centroid documents a [cluster](https://docs.mixpeek.com/docs/enrich/clusters.md) run writes. Set `cluster_navigation.centroid_collection_ids` to that run's output collection.

**Latency:** 2 to 30 s, depending on iterations and the stages called. Cost is the LLM calls plus each called stage.

### Query expand

Asks an LLM for variations of the query, runs a feature search for each, and fuses the results. Use it to raise recall on short or ambiguous queries.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `feature_search_config` | object | required | The full `feature_search` parameters. Each variation replaces the query text. |
| `num_expansions` | integer | `3` | Variations to generate, 1 to 10. |
| `expansion_model` | string | `gpt-4o-mini` | Model that writes the variations. |
| `include_original` | boolean | `true` | Also search the original query. |
| `fusion_strategy` | string | `rrf` | `rrf` or `linear`. |
| `rrf_k` | integer | `60` | RRF constant. 20 to 40 favors precision, 80 to 100 favors recall. |
| `expansion_timeout_ms` | integer | server default | Budget for the LLM call. On timeout the stage searches the original query alone and adds a warning. |

```json query_expand stage theme={null}
{
  "stage_name": "expand",
  "stage_type": "filter",
  "config": {
    "stage_id": "query_expand",
    "parameters": {
      "num_expansions": 3,
      "feature_search_config": {
        "searches": [
          {
            "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
            "query": {"input_mode": "text", "value": "{{INPUT.query}}"},
            "top_k": 50
          }
        ],
        "final_top_k": 25
      }
    }
  }
}
```

**Latency:** 300 to 800 ms: one LLM call plus `num_expansions + 1` searches run concurrently.

## Sort stages

A sort stage returns the same documents in a new order. `mmr` and `rerank` can also trim the list with `top_k`.

### Sort relevance

Reorders documents by a score field, highest first by default. Use it to restore relevance order after a stage that changed the order, or to order by a score another stage wrote.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `score_field` | string | `score` | Field to sort on, for example `scores.rerank`. |
| `direction` | string | `desc` | `desc` or `asc`. |
| `missing_score` | string | `bottom` | Where a document without the field goes: `bottom`, `top` or `preserve`. |

```json sort_relevance stage theme={null}
{
  "stage_name": "by_score",
  "stage_type": "sort",
  "config": {
    "stage_id": "sort_relevance",
    "parameters": {
      "score_field": "score",
      "direction": "desc"
    }
  }
}
```

The stage never computes similarity. `feature_address` and `use_query_embedding` have no effect, and a retriever that sets `use_query_embedding` is refused with 422 from 2026-11-02. **Latency:** under 5 ms.

### Sort attribute

Orders documents by a field value such as price, date or rating. `score_boosts` adds weighted terms to the score first, so you can blend relevance with popularity or recency.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `field` | string | `metadata.created_at` | Field to sort on. Accepts templates such as `metadata.{{INPUT.sort_by}}`. |
| `direction` | string | `desc` | `desc` or `asc`. |
| `nulls_last` | boolean | `true` | Put missing values last in either direction. |
| `score_boosts` | array | none | Terms added to `score`: each has `weight`, `function` (`linear`, `log1p`, `recency`, `match`) and `field`. |
| `case_insensitive` | boolean | `false` | Compare strings without case. |

```json sort_attribute stage theme={null}
{
  "stage_name": "newest_first",
  "stage_type": "sort",
  "config": {
    "stage_id": "sort_attribute",
    "parameters": {
      "field": "metadata.published_at",
      "direction": "desc",
      "nulls_last": true
    }
  }
}
```

A `recency` boost needs `half_life_days` (or `half_life_field`). A `match` boost needs a `condition` in the `attribute_filter` `conditions` form. **Latency:** under 5 ms.

### MMR

Maximal Marginal Relevance picks documents that are relevant and unlike the ones already picked. Use it to stop near-duplicates from filling the top of the list.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `lambda` | number | `0.7` | 1.0 is pure relevance, 0.0 is maximum diversity. |
| `top_k` | integer | `25` | Documents returned, 1 to 500. |
| `diversity_feature_uri` | string | none | Embedding that measures how alike two documents are. |
| `diversity_fields` | array | none | Field names to diversify on instead of embeddings, for example `["metadata.brand"]`. |
| `similarity_metric` | string | `cosine` | `cosine`, `dot` or `euclidean`. |

```json mmr stage theme={null}
{
  "stage_name": "diversify",
  "stage_type": "sort",
  "config": {
    "stage_id": "mmr",
    "parameters": {
      "lambda": 0.7,
      "top_k": 20,
      "diversity_feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1"
    }
  }
}
```

The stage writes each document's MMR score to `scores.mmr`. `diversity_features` weights several embeddings together. **Latency:** 10 to 50 ms, no model calls.

### Rerank

Scores each candidate against the query with a cross-encoder or a decision model, then reorders. Use it when the top few results must be right and you can afford seconds.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `inference_name` | string | `BAAI__bge_reranker_v2_m3` | Reranker: `BAAI__bge_reranker_v2_m3`, `typesafe__jev` or `mixpeek__decision`. |
| `query` | string | `{{INPUT.query}}` | Text compared with each document. |
| `document_field` | string | `content` | Text field to score. Rerank reads text only. |
| `max_candidates` | integer | `10` | Incoming documents scored, up to 1,000. The rest follow unscored in their order. `null` scores all. |
| `top_k` | integer | all | Documents kept after reranking. |
| `relevance_criteria` | string | none | The condition `typesafe__jev` and `mixpeek__decision` judge against. |
| `learning_config` | object | none | `evaluation_dataset_id` names the evaluation a trained reranker is scored on; a trained set ships only when it beats the live configuration there. `shipped_weight_set` is read-only, written by that gate. |

```json rerank stage theme={null}
{
  "stage_name": "rerank",
  "stage_type": "sort",
  "config": {
    "stage_id": "rerank",
    "parameters": {
      "inference_name": "BAAI__bge_reranker_v2_m3",
      "query": "{{INPUT.query}}",
      "document_field": "content",
      "max_candidates": 20,
      "top_k": 10
    }
  }
}
```

The score goes to `scores.rerank`; `score` keeps the retrieval value. If the deployment does not serve the model, saving the retriever returns 422 with `details.served_alternatives`.

**Latency:** measured p50 3.26 s for `BAAI__bge_reranker_v2_m3` on a production pipeline, about 3 s per document at 0.5 CPU. Cost grows with `max_candidates`, so keep it small. On 100 SciFact claims, Jev over the top 30 raised nDCG\@10 from 0.817 to 0.880 at 669 ms per query.

### Maxsim rerank

Rescores candidates with late interaction (ColBERT MaxSim): each query token matches its closest document token, and the matches are summed. Use it after a fast dense search to sharpen the order.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `feature_uri` | string | required | The multi-vector feature, for example `mixpeek://colbert_extractor@v1/colbertv2_v1`. |
| `query` | string | `{{INPUT.query}}` | Query text, encoded by the feature's model. |
| `top_n` | integer | all, up to 1,000 | Rescore only the first `top_n`; the rest follow in order. |
| `match_on` | string | `document_id` | `root_object_id` reads token vectors from another collection over the same bucket objects. |
| `missing` | string | `bottom` | A candidate with no token vectors: `bottom` or `drop`. |

```json maxsim_rerank stage theme={null}
{
  "stage_name": "colbert_rerank",
  "stage_type": "sort",
  "config": {
    "stage_id": "maxsim_rerank",
    "parameters": {
      "feature_uri": "mixpeek://colbert_extractor@v1/colbertv2_v1",
      "query": "{{INPUT.query}}",
      "top_n": 100,
      "match_on": "root_object_id"
    }
  }
}
```

A collection runs one extractor, so dense search plus ColBERT needs two collections over one bucket: search the text one, rerank with `match_on: root_object_id`. Stage metadata reports `candidates`, `scored` and `missing_tokens`.

### Score normalize

Rescales scores to a common range so you can compare or threshold them. Use it before `score_threshold` or before mixing scores from different stages.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `method` | string | `min_max` | `min_max`, `z_score`, `softmax` or `l2`. |
| `score_field` | string | `score` | Field to normalize. Use `scores.rerank` after a rerank. |
| `output_field` | string | none | Write here and keep the original. Unset overwrites `score_field`. |
| `min_value`, `max_value` | number | observed | Fixed bounds for `min_max`, for scaling that is stable across queries. |

```json score_normalize stage theme={null}
{
  "stage_name": "normalize",
  "stage_type": "sort",
  "config": {
    "stage_id": "score_normalize",
    "parameters": {
      "method": "min_max",
      "score_field": "scores.rerank",
      "output_field": "scores.normalized"
    }
  }
}
```

**Latency:** under 1 ms.

## Reduce stages

A reduce stage shrinks the list or collapses it into fewer, new documents. Several of them change what `documents` holds, and each section says what you get back.

### Limit

Keeps the first `limit` documents after skipping `offset`. It is the pipeline's `LIMIT ... OFFSET`.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `limit` | integer | `10` | Documents kept, 1 to 10,000. |
| `offset` | integer | `0` | Documents skipped first, up to 10,000. |

```json limit stage theme={null}
{
  "stage_name": "top_ten",
  "stage_type": "reduce",
  "config": {
    "stage_id": "limit",
    "parameters": {
      "limit": 10,
      "offset": 0
    }
  }
}
```

For pages a user clicks through, use the execute request's `pagination` instead (see [Retrievers](https://docs.mixpeek.com/docs/retrieve/retrievers.md#pagination)). **Latency:** under 1 ms.

### Score threshold

Drops every document whose score fails an absolute bar. When nothing clears it, `documents` is empty and the stage sets `all_below_threshold`, so your UI can show "no good results".

| Parameter | Type | Default | Description |
| - | - | - | - |
| `min_score` | number | required | The bar a document must meet. |
| `score_field` | string | `score` | Field to test, for example `scores.rerank`. |
| `comparison` | string | `gte` | `gte` or `gt`. |
| `missing_score` | string | `drop` | A document without the field: `drop` or `keep`. |

```json score_threshold stage theme={null}
{
  "stage_name": "quality_gate",
  "stage_type": "reduce",
  "config": {
    "stage_id": "score_threshold",
    "parameters": {
      "min_score": 0.5,
      "score_field": "scores.rerank"
    }
  }
}
```

Threshold a calibrated score such as a rerank probability. Raw vector scores shift between queries; run [`score_normalize`](https://docs.mixpeek.com/docs/retrieve/stages#score-normalize) first if you must gate on them. **Latency:** under 1 ms.

### Deduplicate

Removes duplicates by exact field values or by text similarity. Use `field` for ids and URLs, `content` for near-identical text.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `strategy` | string | `field` | `field` or `content`. |
| `fields` | array | none | Required for `field`: documents equal on all listed fields are duplicates. |
| `content_field` | string | `content` | Text compared under `content`. |
| `similarity_threshold` | number | `0.95` | Under `content`, similarity above this is a duplicate. |
| `keep` | string | `first` | Keep the `first` (highest ranked) or `last` copy. |

```json deduplicate stage theme={null}
{
  "stage_name": "one_per_url",
  "stage_type": "reduce",
  "config": {
    "stage_id": "deduplicate",
    "parameters": {
      "strategy": "field",
      "fields": ["metadata.url"]
    }
  }
}
```

**Latency:** under 5 ms by field, 10 to 100 ms by content.

### Sample

Picks a random, stratified or reservoir sample. Use it for review queues, evaluation sets, or a spread across categories.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `count` | integer | `10` | Documents to return, 1 to 1,000. |
| `strategy` | string | `random` | `random`, `stratified` or `reservoir`. |
| `stratify_by` | string | none | Required for `stratified`: the field to sample across in proportion. |
| `seed` | integer | none | Fix it for the same output on the same input. |
| `preserve_top_k` | integer | `0` | Always keep this many top-scored documents, then sample the rest. |

```json sample stage theme={null}
{
  "stage_name": "per_category_sample",
  "stage_type": "reduce",
  "config": {
    "stage_id": "sample",
    "parameters": {
      "count": 50,
      "strategy": "stratified",
      "stratify_by": "metadata.category",
      "seed": 42
    }
  }
}
```

**Latency:** under 5 ms.

### Aggregate

Computes metrics over the documents, overall or per group. By default it returns no documents, and the rows are at `stage_statistics.stages.<stage_name>.metadata.aggregations` in the execute response.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `aggregations` | array | one `count` | Each has `function`, `alias`, and `field` where the function reads one. |
| `group_by` | array | none | Fields to group by, each `{"field": "metadata.category"}`. |
| `sort_by`, `sort_order` | string | none, `desc` | Order groups by a metric alias. |
| `limit` | integer | none | Groups returned, up to 1,000. |
| `emit_groups` | boolean | `false` | Return each row as a document in `documents`, so later stages can use them. |
| `include_documents` | boolean | `false` | Pass the input documents through and add the rows to metadata. |

> [accordion] Aggregation functions
>
> Every function except `count` reads `field`. `co_occurrence` and `correlation` also read `field_b`; `percentile` takes `percentile_value` (0 to 100, default 50); `frequency` and `co_occurrence` take `top_k` (1 to 100, default 10).
>
> | Function | Returns | Example use |
> | - | - | - |
> | `count` | Number of documents in the group | Total results |
> | `count_distinct` | Number of unique values of `field` | Unique authors |
> | `sum` | Sum of a numeric field | Total revenue |
> | `avg` | Average of a numeric field | Average price |
> | `min` | Smallest value of a numeric field | Lowest price |
> | `max` | Largest value of a numeric field | Highest price |
> | `first` | Value from the first document in the group | Top-ranked title |
> | `last` | Value from the last document in the group | Lowest-ranked title |
> | `collect` | List of all values, duplicates kept | All tags |
> | `collect_distinct` | List of unique values | Distinct tags |
> | `percentile` | One percentile of a numeric field | P50, P95 |
> | `stddev` | Standard deviation (sample) | Score spread |
> | `variance` | Variance (sample) | Price volatility |
> | `frequency` | Top-K values with counts and percent | Top categories |
> | `co_occurrence` | Top-K pairs of two fields with counts | Brand and category pairs |
> | `correlation` | Pearson correlation of two numeric fields | Price vs. rating |

> [accordion] More aggregate examples
>
> Each item is the `config` of an aggregate stage.
>
> ```json aggregate config values theme={null}
> [
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "count", "alias": "total"}, {"function": "avg", "field": "metadata.price", "alias": "avg_price"}, {"function": "min", "field": "metadata.price", "alias": "min_price"}, {"function": "max", "field": "metadata.price", "alias": "max_price"}]}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "count", "alias": "total"}, {"function": "count_distinct", "field": "metadata.brand", "alias": "brand_count"}, {"function": "frequency", "field": "metadata.brand", "alias": "top_brands", "top_k": 5}], "include_documents": true}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "percentile", "field": "score", "percentile_value": 95, "alias": "p95_score"}, {"function": "avg", "field": "score", "alias": "avg_score"}]}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "count", "alias": "total_docs"}, {"function": "sum", "field": "metadata.views", "alias": "total_views"}, {"function": "avg", "field": "metadata.engagement_rate", "alias": "avg_engagement"}, {"function": "count_distinct", "field": "metadata.author_id", "alias": "unique_authors"}]}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "count", "alias": "total_published"}, {"function": "sum", "field": "metadata.views", "alias": "total_views"}, {"function": "avg", "field": "metadata.engagement", "alias": "avg_engagement"}, {"function": "percentile", "field": "metadata.views", "percentile_value": 90, "alias": "p90_views"}], "group_by": [{"field": "metadata.author", "alias": "author"}]}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "count", "alias": "available_products"}, {"function": "min", "field": "metadata.price", "alias": "lowest_price"}, {"function": "max", "field": "metadata.price", "alias": "highest_price"}, {"function": "avg", "field": "metadata.rating", "alias": "avg_rating"}, {"function": "count_distinct", "field": "metadata.brand", "alias": "brand_count"}], "group_by": [{"field": "metadata.category", "alias": "category"}], "include_documents": true}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "percentile", "field": "score", "alias": "median_score", "percentile_value": 50}, {"function": "percentile", "field": "score", "alias": "p90_score", "percentile_value": 90}, {"function": "stddev", "field": "score", "alias": "score_spread"}, {"function": "variance", "field": "score", "alias": "score_variance"}]}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "frequency", "field": "category", "alias": "top_categories", "top_k": 10}, {"function": "frequency", "field": "brand", "alias": "top_brands", "top_k": 5}]}},
>   {"stage_id": "aggregate", "parameters": {"aggregations": [{"function": "co_occurrence", "field": "brand", "field_b": "category", "alias": "brand_category_pairs"}, {"function": "correlation", "field": "price", "field_b": "rating", "alias": "price_rating_corr"}]}}
> ]
> ```

```json aggregate stage theme={null}
{
  "stage_name": "by_category",
  "stage_type": "reduce",
  "config": {
    "stage_id": "aggregate",
    "parameters": {
      "group_by": [{"field": "metadata.category"}],
      "aggregations": [
        {"function": "count", "alias": "total"},
        {"function": "avg", "field": "metadata.price", "alias": "avg_price"}
      ],
      "sort_by": "total",
      "limit": 10,
      "emit_groups": true
    }
  }
}
```

`emit_groups` and `include_documents` cannot be combined. **Latency:** 5 to 50 ms.

### Temporal

Buckets documents into time windows and computes metrics per window, with optional drift detection between windows. Use it for trend lines and spike alerts over search results.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `time_field` | string | required | ISO 8601 or epoch timestamp field. |
| `window` | string | `day` | `hour`, `day`, `week`, `month`, `quarter` or `year`. |
| `aggregations` | array | one `count` | Each has `function`, `alias` and, except for `count`, `field`. |
| `drift` | object | none | `{"metric": "count", "threshold": 50.0}` flags windows that change more than 50% from the previous one. |
| `include_documents` | boolean | `false` | Pass documents through. Unset returns window results in metadata only. |

```json temporal stage theme={null}
{
  "stage_name": "daily_trend",
  "stage_type": "reduce",
  "config": {
    "stage_id": "temporal",
    "parameters": {
      "time_field": "metadata.published_at",
      "window": "day",
      "aggregations": [{"function": "count", "alias": "count"}],
      "drift": {"metric": "count", "threshold": 50.0}
    }
  }
}
```

**Latency:** 5 to 50 ms.

### Summarize

Sends the documents to an LLM and returns a summary document, or one per group. Use it to answer a question from the retrieved content.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `prompt` | string | a summarize prompt | Must contain `{{DOCUMENTS}}`. Also takes `{{DOC_COUNT}}`, `{{GROUP_VALUE}}` and `{{INPUT.*}}`. |
| `provider`, `model_name` | string | `google`, provider default | The LLM. |
| `content_field` | string | `content` | Field read from each document. |
| `group_by` | string | none | One summary per value of this field. |
| `output_field` | string | `summary` | Field holding the summary. |
| `max_input_tokens` | integer | none | Input budget. Over it, documents are cut by `truncation_strategy`. |
| `output_schema` | object | none | JSON schema for structured output. |

```json summarize stage theme={null}
{
  "stage_name": "answer",
  "stage_type": "reduce",
  "config": {
    "stage_id": "summarize",
    "parameters": {
      "provider": "google",
      "prompt": "Answer {{INPUT.query}} using only these sources:\n\n{{DOCUMENTS}}",
      "output_field": "summary"
    }
  }
}
```

`documents` holds the summary documents, with `source_document_ids` for citations. **Latency:** 500 to 2,000 ms.

### Moment group

Merges matching video segments that sit close in time into moments with a start and end, per video. Use it to return "minute 3:10 to 3:42" instead of a list of frames.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `parent_field` | string | `source_object_id` | Field that names the video. |
| `time_field` | string | `query_chunks` | Interval source. For a text query use the segment's `start_time`. |
| `merge_tolerance_ms` | integer | `2000` | Largest gap merged into one moment, up to 60,000. |
| `max_moments_per_parent` | integer | `10` | Moments kept per video. |
| `score_strategy` | string | `max` | How merged scores combine: `max`, `avg` or `sum`. |
| `output_mode` | string | `annotated` | `annotated` keeps the best document per video with a `moments` array. `moments_only` returns moment documents. |

```json moment_group stage theme={null}
{
  "stage_name": "moments",
  "stage_type": "reduce",
  "config": {
    "stage_id": "moment_group",
    "parameters": {
      "time_field": "start_time",
      "merge_tolerance_ms": 2000,
      "max_moments_per_parent": 5
    }
  }
}
```

`query_chunks` exists only for file-input queries with preprocessing. Fields ending `_time`, `_s`, `_sec` or `_seconds` are read as seconds; moments are always in milliseconds. **Latency:** 5 to 50 ms.

## Group stages

Group stages bucket documents. They are reduce stages in the API, so their `stage_type` is `reduce`.

### Group by

Groups documents that share a field value, for example every chunk of one video or every product of one brand.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `group_by_field` | string | `source_object_id` | Field to group on. |
| `max_per_group` | integer | `10` | Documents kept per group, highest score first. `1` deduplicates. |
| `output_mode` | string | `all` | `first` returns the top document per group, `all` returns groups, `flatten` returns a flat list. |
| `group_order` | array | by score | Order documents inside a group by fields, each `{"field": "start_time", "direction": "asc"}`. |
| `ungrouped_values` | array | `[]` | Values that mean "no group", such as `""`. Those documents pass through on their own. |

```json group_by stage theme={null}
{
  "stage_name": "one_per_video",
  "stage_type": "reduce",
  "config": {
    "stage_id": "group_by",
    "parameters": {
      "group_by_field": "source_object_id",
      "max_per_group": 3,
      "output_mode": "all"
    }
  }
}
```

To group inside the vector store before results leave it, use `group_by` on [`feature_search`](https://docs.mixpeek.com/docs/retrieve/stages#feature-search). `position_caps` limits how many groups of one kind lead a page. **Latency:** 5 to 20 ms.

### Cluster

Clusters the documents by embedding similarity at query time, to show themes in a result set. For clusters over a whole collection, use [Clusters](https://docs.mixpeek.com/docs/enrich/clusters.md).

| Parameter | Type | Default | Description |
| - | - | - | - |
| `algorithm` | string | `hdbscan` | `hdbscan`, `kmeans`, `dbscan`, `agglomerative`, `spectral` or `gaussian_mixture`. |
| `n_clusters` | integer | none | Required for `kmeans`, `spectral`, `agglomerative` and `gaussian_mixture`, 2 to 100. |
| `min_cluster_size` | integer | `5` | For `hdbscan` and `dbscan`. |
| `feature_uri` | string | from the upstream search | Embedding to cluster on. |
| `output_mode` | string | `clusters` | `clusters` returns one document per cluster with `members`. `labeled` returns every document with `cluster_id`. `representatives` returns the document nearest each centroid. |
| `max_members_per_cluster` | integer | `50` | Members listed per cluster. |

```json cluster stage theme={null}
{
  "stage_name": "themes",
  "stage_type": "reduce",
  "config": {
    "stage_id": "cluster",
    "parameters": {
      "algorithm": "kmeans",
      "n_clusters": 5,
      "output_mode": "labeled"
    }
  }
}
```

**Latency:** 50 to 200 ms.

## Apply stages

An apply stage reshapes documents, expands them, or adds data from outside the collection. The [enrich stages](#enrich-stages) below are apply stages in the API too, apart from `agentic_enrich` and `code_execution`.

### JSON transform

Renders a Jinja2 template per document and replaces the document with the resulting JSON. Use it to shape output for a frontend or an external API.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `template` | string | an id and content template | Jinja2 that renders valid JSON. Reads `DOC`, `INPUT` and `CONTEXT`. |
| `fail_on_error` | boolean | `false` | `false` drops a document that fails to render and adds a warning. `true` fails the run. |

```json json_transform stage theme={null}
{
  "stage_name": "card_shape",
  "stage_type": "apply",
  "config": {
    "stage_id": "json_transform",
    "parameters": {
      "template": "{\"id\": \"{{ DOC.document_id }}\", \"title\": {{ DOC.metadata.title | tojson }}, \"score\": {{ DOC.score }}}"
    }
  }
}
```

**Latency:** under 1 ms per document.

### RAG prepare

Packs documents into an LLM context within a token budget and builds citations. It calls no LLM; feed its output to `summarize`, `llm_enrich` or your own model call.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `max_tokens` | integer | `8000` | Token budget for the context, 100 to 128,000. |
| `output_mode` | string | `single_context` | `single_context` returns one document with `rag_context` and `citations`. `formatted_list` returns N formatted documents. |
| `truncation_strategy` | string | `priority_truncate` | `priority_truncate`, `proportional` or `drop_last`. |
| `document_template` | string | `[{{CONTEXT.INDEX}}] {{DOC.content}}` | How each document is written into the context. |
| `citation.style` | string | `numbered` | `numbered`, `bracketed`, `footnote` or `none`. |

```json rag_prepare stage theme={null}
{
  "stage_name": "context",
  "stage_type": "apply",
  "config": {
    "stage_id": "rag_prepare",
    "parameters": {
      "max_tokens": 8000,
      "output_mode": "single_context",
      "citation": {"style": "numbered", "include_url": true}
    }
  }
}
```

Token counts use the `cl100k_base` tokenizer by default. **Latency:** under 10 ms.

### Unwind

Turns each element of an array field into its own document, like MongoDB's `$unwind`. Use it to rank tags, line items or detected objects one by one.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `field` | string | required | The array field, for example `metadata.tags`. |
| `output_field` | string | none | Put the element here and keep the original array. Unset replaces the array. |
| `include_array_index` | string | none | Name of a field that receives the element's 0-based index. |
| `preserve_null_and_empty` | boolean | `false` | Keep documents whose array is missing or empty. |

```json unwind stage theme={null}
{
  "stage_name": "one_per_tag",
  "stage_type": "apply",
  "config": {
    "stage_id": "unwind",
    "parameters": {
      "field": "metadata.tags",
      "output_field": "tag",
      "include_array_index": "tag_index"
    }
  }
}
```

**Latency:** under 5 ms.

### API call

Calls an HTTP API per document and stores the response on it. Use it to join live data such as stock, pricing or CRM fields.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `url` | string | required in practice | Endpoint, with `{{DOC.field}}` and `{{INPUT.field}}` templates. Single braces are sent literally. |
| `allowed_domains` | array | `["httpbin.org"]` | Domains the stage may call. Wildcards such as `*.example.com` work. |
| `method` | string | `GET` | `GET`, `POST`, `PUT`, `PATCH` or `DELETE`. |
| `auth` | object | none | `type` (`api_key`, `bearer`, `basic`, `custom_header`) and `secret_ref`, the name of an organization secret. |
| `output_field` | string | `api_response` | Where the response goes. `response_path` (JSONPath) keeps part of it. |
| `timeout` | integer | `10` | Seconds, 1 to 60. |
| `on_error` | string | `skip` | `skip`, `remove` or `raise`. |

```json api_call stage theme={null}
{
  "stage_name": "stripe_customer",
  "stage_type": "apply",
  "config": {
    "stage_id": "api_call",
    "parameters": {
      "url": "https://api.stripe.com/v1/customers/{{DOC.metadata.stripe_id}}",
      "allowed_domains": ["api.stripe.com"],
      "auth": {"type": "bearer", "secret_ref": "stripe_api_key"},
      "output_field": "metadata.stripe_customer"
    }
  }
}
```

Create the secret first with `POST /v1/organizations/secrets`. `when` takes a filter tree so only matching documents make the call. **Latency:** 100 to 500 ms per request.

### SQL lookup

Runs a parameterized `SELECT` against a PostgreSQL connection per document and stores the rows on it.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `connection_id` | string | required | Organization connection id (`conn_...`) or name. |
| `query` | string | required | A `SELECT` with `$1`, `$2` placeholders. Writes are blocked. |
| `parameters` | object | `{}` | Values for the placeholders, with templates such as `{{DOC.metadata.sku}}`. Keys bind in alphabetical order: `$1` takes the first key alphabetically. |
| `output_field` | string | `sql_result` | Where the result goes. |
| `result_handling` | string | `first` | `first` row, `all` rows, or `error_if_empty`. |
| `timeout` | integer | `30` | Seconds, 1 to 300. |

```json sql_lookup stage theme={null}
{
  "stage_name": "inventory",
  "stage_type": "apply",
  "config": {
    "stage_id": "sql_lookup",
    "parameters": {
      "connection_id": "inventory_db",
      "query": "SELECT stock_level, warehouse_location FROM inventory WHERE sku = $1",
      "parameters": {"sku": "{{DOC.metadata.sku}}"},
      "output_field": "metadata.inventory"
    }
  }
}
```

| Database | Connection type |
| - | - |
| PostgreSQL | `postgresql` |

A connection to a provider other than PostgreSQL fails with `Connection does not support SQL queries`; reach a warehouse through [`api_call`](https://docs.mixpeek.com/docs/retrieve/stages#api-call). **Latency:** 10 to 100 ms.

> [accordion] Join warehouse metrics onto results
>
> A creative library often keys a metrics table (spend, ROAS, thumb-stop rate) by `creative_id`. Use `sql_lookup` when the table is in PostgreSQL, and `api_call` against an HTTP endpoint that runs the query when it is in Snowflake or another warehouse. Both run after the search and add a `warehouse_metrics` field to each document. A joined value cannot rank results; to rank by ROAS, ingest it as document data.
>
> ```json sql_lookup from PostgreSQL theme={null}
> {
>   "stage_name": "warehouse_metrics",
>   "stage_type": "apply",
>   "config": {
>     "stage_id": "sql_lookup",
>     "parameters": {
>       "connection_id": "ad_metrics_postgres",
>       "query": "SELECT spend, roas, thumbstop_rate FROM creative_performance WHERE creative_id = $1",
>       "parameters": {"creative_id": "{{DOC.metadata.creative_id}}"},
>       "output_field": "warehouse_metrics"
>     }
>   }
> }
> ```
>
> ```json api_call to another warehouse theme={null}
> {
>   "stage_name": "warehouse_metrics",
>   "stage_type": "apply",
>   "config": {
>     "stage_id": "api_call",
>     "parameters": {
>       "url": "https://metrics.example.com/v1/creatives/{{DOC.metadata.creative_id}}/performance",
>       "allowed_domains": ["metrics.example.com"],
>       "auth": {"type": "bearer", "secret_ref": "metrics_api_token"},
>       "output_field": "warehouse_metrics",
>       "on_error": "skip"
>     }
>   }
> }
> ```
>
> A creative with no row gets `null`. `api_call` sends one request per document, one after another.

### External web search

Adds web results from Exa to the documents you already have. Use it when your collections may lack fresh or outside content.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `query` | string | `{{INPUT.query}}` | The web query. |
| `num_results` | integer | `10` | Web results added, 1 to 100. |
| `category` | string | none | For example `research paper`, `news`, `github`. |
| `start_published_date` | string | none | `YYYY-MM-DD`; only content published after it. |
| `include_text` | boolean | `true` | Include a text snippet with each result. |

```json external_web_search stage theme={null}
{
  "stage_name": "web",
  "stage_type": "apply",
  "config": {
    "stage_id": "external_web_search",
    "parameters": {
      "query": "{{INPUT.query}}",
      "num_results": 5,
      "category": "news"
    }
  }
}
```

**Latency:** 200 to 500 ms.

### External reverse image

Appends open-web matches for a query image from Google Lens through SerpAPI, after your own image matches. Your earlier results always stay in `documents`.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `image_url` | string | `{{INPUT.image_url}}` | The image to search for. |
| `top_k` | integer | `20` | Web matches appended, 1 to 100. |
| `provider`, `engine` | string | `serpapi`, `google_lens` | The only values today. |

```json external_reverse_image stage theme={null}
{
  "stage_name": "web_image_matches",
  "stage_type": "apply",
  "config": {
    "stage_id": "external_reverse_image",
    "parameters": {
      "image_url": "{{INPUT.image_url}}",
      "top_k": 10
    }
  }
}
```

The deployment needs a SerpAPI key. Without one, or when the call fails, the stage returns your earlier results with a warning.

### Web scrape

Fetches the page at a URL, from a document field or the input, and stores its main text. It can also crawl links from a seed URL.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `url_field` | string | `metadata.url` | Document field holding the URL. |
| `url` | string | none | A URL from input, such as `{{INPUT.url}}`, with no documents needed. |
| `output_field` | string | `web_content` | Gets `text`, `title`, `url` and `final_url`. |
| `strategy` | string | `auto` | `static`, `javascript` (browser rendering) or `auto` (static first). |
| `timeout` | integer | `10` | Seconds, 1 to 60. JavaScript pages may need 20 to 30. |
| `max_depth`, `max_pages` | integer | none | Set either to crawl: depth up to 5, pages up to 100. |

```json web_scrape stage theme={null}
{
  "stage_name": "fetch_pages",
  "stage_type": "apply",
  "config": {
    "stage_id": "web_scrape",
    "parameters": {
      "url_field": "metadata.url",
      "strategy": "auto",
      "timeout": 20
    }
  }
}
```

**Latency:** 500 to 5,000 ms per page.

### Cross compare

Compares each source document's elements with a reference collection through a cascade of match tiers (exact, fuzzy, vector) and labels each match. Use it for drift, duplicate and compliance checks, for example a product video against its documentation.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `reference_collection_id` | string | required | Collection to compare against. |
| `source_field`, `reference_field` | string | `content` | Fields holding the elements on each side. |
| `extraction_mode` | string | `raw` | `raw`, `lines`, `labels` or `list`. |
| `match_tiers` | array | exact, then fuzzy | Each tier has `type` (`exact`, `fuzzy`, `vector`), `threshold` (default `0.75`) and, for `vector`, `feature_uri`. |
| `classifications` | array | 0.95 `exact_match`, 0.85 `close_match`, 0.65 `partial_match`, else `no_match` | `min_score` to `label` rules applied to the match score. |
| `output_mode` | string | `findings` | `findings` returns one document per comparison. `enrich` adds results to each source document. |

```json cross_compare stage theme={null}
{
  "stage_name": "compare_to_docs",
  "stage_type": "apply",
  "config": {
    "stage_id": "cross_compare",
    "parameters": {
      "reference_collection_id": "col_product_docs",
      "extraction_mode": "lines",
      "match_tiers": [
        {"type": "exact"},
        {"type": "fuzzy", "threshold": 0.85},
        {"type": "vector", "threshold": 0.8, "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1"}
      ],
      "output_mode": "findings"
    }
  }
}
```

Each finding carries `match_tier`, `match_score`, `classification` and `confidence`. **Latency:** 50 to 1,500 ms, depending on tiers.

### Traverse edge

Moves from the current documents to related ones. It follows typed object edges, walks lineage up to the document each hit came from, or keeps hits whose time spans overlap spans in another collection.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `follow` | string | `edges` | `edges`, `lineage` or `overlap`. |
| `edge_type` | string or array | none | Edges mode, required: the edge types to follow, for example `used_in_ad`. |
| `direction` | string | `any` | Edges mode: `out`, `in` or `any`. |
| `target_collection_id` | string | none | Lineage mode: the collection to climb to. Edges mode: only return documents from it. Overlap mode: the collection to join with. |
| `include_evidence` | boolean | `false` | Attach `_evidence` listing the input documents that reached each result. |
| `limit` | integer | `200` | Edges mode: total documents fetched. |

```json traverse_edge stage theme={null}
{
  "stage_name": "to_parent_video",
  "stage_type": "apply",
  "config": {
    "stage_id": "traverse_edge",
    "parameters": {
      "follow": "lineage",
      "target_collection_id": "col_videos",
      "include_evidence": true
    }
  }
}
```

Lineage mode reads each document's `_internal.lineage.source_document_id`, so you can search a segment collection and return whole videos. Overlap mode takes `spans`, `target_spans`, `min_overlap_seconds` and `max_targets` (default `5000`); a join over `max_targets` is refused with 400, and `on_error: "skip"` is refused at create. The stage calls no model and adds no credits.

## Enrich stages

An enrich stage adds fields to each document from a model, a taxonomy, another collection or your own code. Most of them are `apply` stages in the API; the `stage_type` in each example is the one the API infers.

### LLM enrich

Sends each document to an LLM with your prompt and writes the answer to a field. Use `output_schema` to get structured fields such as entities, sentiment or a category.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `prompt` | string | a 2 to 3 sentence summary prompt | Instruction, with `{{DOC.field}}` and `{{INPUT.field}}` templates. |
| `output_field` | string | `summary` | Where the result is written. |
| `output_schema` | object | none | JSON schema the answer must follow. |
| `provider`, `model_name` | string | `google`, provider default | For example `gpt-4o-mini` or `claude-haiku-4-5-20251001`. |
| `max_candidates` | integer | `10` | The most documents the stage accepts, up to 50. More is refused with 400 before any model call. |
| `include_media` | boolean | `false` | Send each document's video or image with its fields. |
| `temperature` | number | `0.2` | Sampling temperature. |

```json llm_enrich stage theme={null}
{
  "stage_name": "extract_entities",
  "stage_type": "apply",
  "config": {
    "stage_id": "llm_enrich",
    "parameters": {
      "provider": "openai",
      "model_name": "gpt-4o-mini",
      "prompt": "List the brands and products mentioned in: {{DOC.content}}",
      "output_field": "entities",
      "output_schema": {
        "type": "object",
        "properties": {
          "brands": {"type": "array", "items": {"type": "string"}},
          "products": {"type": "array", "items": {"type": "string"}}
        }
      }
    }
  }
}
```

**Cost:** 2 credits per document in the results. [Explain](https://docs.mixpeek.com/docs/api-reference/retrievers/explain-retriever-execution-plan.md) prices the stage before you run it. **Latency:** 300 to 800 ms per batch; at the stage's ceiling (25,000 ms by default) unanswered calls are cancelled and the answered ones kept.

### Classify

Labels each document with a classifier at query time. Set exactly one of `task` (a hosted task), `inference_name` (a hosted label model) or `feature_uri` (your own classifier plugin).

| Parameter | Type | Default | Description |
| - | - | - | - |
| `task` | string | none | `nsfw`: content safety for text, image or video with `mixpeek/content-classifier-v1`. |
| `inference_name` | string | none | `typesafe__jev` classifies into your `labels`. |
| `labels` | array or object | none | Labels to choose from, or a map of label to description. |
| `document_field` | string | `content` | Text to classify. With `nsfw`, `image_field` or `video_field` classify media instead. |
| `output_field` | string | `classification` | Where the result is written. |
| `drop_if_unsafe` | boolean | `false` | With `nsfw`, remove flagged documents instead of labeling them. |

```json classify stage theme={null}
{
  "stage_name": "safety",
  "stage_type": "apply",
  "config": {
    "stage_id": "classify",
    "parameters": {
      "task": "nsfw",
      "image_field": "thumbnail_url",
      "drop_if_unsafe": true
    }
  }
}
```

The `nsfw` task returns `nsfw_score` (0 to 1), `label` and `is_nsfw`, and flags at `nsfw_threshold` (default `0.7`). It runs on CPU.

### Taxonomy enrich

Matches each document against a [taxonomy](https://docs.mixpeek.com/docs/enrich/taxonomies.md) at query time and writes the best nodes onto it. Use it when labels must reflect the current taxonomy without reprocessing the collection.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `taxonomy_id` | string | required in practice | The taxonomy. Its `input_mappings` choose the vector to compare. |
| `top_k` | integer | `3` | Assignments kept per document, up to 50. |
| `min_score` | number | `0.0` | Similarity an assignment needs. |
| `fields` | array | `[]` | Node fields to copy, each with `field_path`, optional `target_field` and `merge_mode`. |
| `when` | object | none | Filter tree; only matching documents are enriched. |

```json taxonomy_enrich stage theme={null}
{
  "stage_name": "categorize",
  "stage_type": "apply",
  "config": {
    "stage_id": "taxonomy_enrich",
    "parameters": {
      "taxonomy_id": "tax_product_categories",
      "top_k": 1,
      "min_score": 0.6,
      "fields": [{"field_path": "label", "target_field": "category"}]
    }
  }
}
```

Assignments land as flat fields named from the taxonomy id without its `tax_` prefix, for example `_taxonomy_product_categories_label` and `_taxonomy_product_categories_score`. A document with no assignment over `min_score` passes through unchanged. **Latency:** 20 to 100 ms.

### Document enrich

Joins each document with a document from another collection, like a SQL `LEFT JOIN`. Join by a field match, or find the match with a retriever.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `target_collection_id` | string | required for a field join | Collection to read from. |
| `source_field` | string | `source_object_id` | Field on this document to match. |
| `target_field` | string | `document_id` | Field on the target to match against. |
| `fields_to_merge` | array | whole document | Target fields to copy. |
| `output_field` | string | none | Nest the result here. Unset merges into the document root. |
| `retriever_id` | string | none | Find the match with a saved retriever instead, fed by `retriever_inputs`. |
| `allow_missing` | boolean | `true` | `false` drops documents with no match. |

```json document_enrich stage theme={null}
{
  "stage_name": "join_author",
  "stage_type": "apply",
  "config": {
    "stage_id": "document_enrich",
    "parameters": {
      "target_collection_id": "col_users",
      "source_field": "metadata.author_id",
      "target_field": "metadata.user_id",
      "fields_to_merge": ["metadata.name", "metadata.team"],
      "output_field": "author"
    }
  }
}
```

**Latency:** 5 to 20 ms per document for a field join.

### Agentic enrich

Runs a multi-turn agent per document that can load taxonomy categories, look up already-labeled examples and analyze media before it writes a structured answer. Use it for labels a single prompt gets wrong, such as IAB categories for video.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `system_prompt` | string | required | The agent's instructions. Takes `{{INPUT.*}}`, `{{DOC.*}}` and `{{CONTEXT.*}}`. |
| `output_schema` | object | required | JSON schema of the answer. |
| `output_field` | string | `classification` | Where the answer is written. |
| `taxonomy_id` | string | none | Turns on the `get_taxonomy_categories` tool. |
| `example_collection_ids` | array | none | Turns on the `query_examples` tool. |
| `max_turns` | integer | `8` | Turns per document, up to 20. |
| `provider`, `model_name` | string | `anthropic`, `claude-sonnet-4-6` | The reasoning model. `analyze_content` uses Gemini by default. |

```json agentic_enrich stage theme={null}
{
  "stage_name": "iab_label",
  "stage_type": "enrich",
  "config": {
    "stage_id": "agentic_enrich",
    "parameters": {
      "system_prompt": "Classify this video into IAB categories. Load the taxonomy, analyze the content, then check labeled examples.",
      "output_schema": {
        "type": "object",
        "properties": {
          "iab_category": {"type": "string"},
          "confidence": {"type": "number"}
        }
      },
      "taxonomy_id": "tax_iab",
      "max_turns": 8
    }
  }
}
```

`self_consistency` runs up to 5 evaluations and votes; `escalation` re-runs low-agreement documents on a larger model. **Latency:** 2 to 30 s per document.

### Code execution

Runs your Python, TypeScript or JavaScript in a sandbox over the documents and merges the result into each one. Use it for logic no other stage expresses.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `code` | string | a word-count example | Reads `docs` (a list of documents) and sets `result` to a list of the same length. |
| `language` | string | `python` | `python`, `typescript` or `javascript`. |
| `output_field` | string | `computed` | Where each result item is merged. |
| `timeout_ms` | integer | `5000` | 100 to 30,000. |
| `env` | object | `{}` | Variables, with `{{INPUT.*}}` and `{{SECRET.name}}` templates. |
| `on_error` | string | `skip` | `skip` returns the input unchanged, `raise` fails the run. |

```json code_execution stage theme={null}
{
  "stage_name": "word_count",
  "stage_type": "enrich",
  "config": {
    "stage_id": "code_execution",
    "parameters": {
      "language": "python",
      "code": "result = [{'word_count': len(d.get('content', '').split())} for d in docs]",
      "output_field": "computed"
    }
  }
}
```

Output is capped at `max_output_size` (default 100 KB, up to 1 MB). **Latency:** 5 to 50 ms per document.

## Pipeline patterns

Stage categories map to SQL clauses: filter is `WHERE`, sort is `ORDER BY`, reduce is `LIMIT` and `GROUP BY`, enrich is `JOIN`, and apply is `SELECT`. Most pipelines follow one of these shapes.

| Goal | Stages |
| - | - |
| Question answering (RAG) | `feature_search`, `rerank`, `rag_prepare` or `summarize` |
| Product search | `feature_search` with `pre_filters`, `sort_attribute`, `limit` |
| Hybrid search | `feature_search` with a dense and a `lexical` entry under `rrf` |
| Find moments in video | `feature_search`, `moment_group` |
| One result per video | `feature_search` with `group_by`, or `group_by` after it |
| Search segments, return whole videos | `feature_search`, `traverse_edge` with `follow: "lineage"` |
| Research brief | `query_expand`, `external_web_search`, `taxonomy_enrich`, `summarize` |
| Content safety | `feature_search`, `classify` with `task: "nsfw"` |

There is no stage that blends several score fields with weights. Use `sort_attribute` with `score_boosts` to add weighted terms to `score`, or `score_normalize` and then sort on one field.

### Question answering pipeline

```json RAG retriever stages theme={null}
{
  "stages": [
    {
      "stage_name": "search",
      "stage_type": "filter",
      "config": {
        "stage_id": "feature_search",
        "parameters": {
          "searches": [
            {
              "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
              "query": {"input_mode": "text", "value": "{{INPUT.query}}"},
              "top_k": 50
            }
          ],
          "final_top_k": 20
        }
      }
    },
    {
      "stage_name": "rerank",
      "stage_type": "sort",
      "config": {
        "stage_id": "rerank",
        "parameters": {
          "inference_name": "BAAI__bge_reranker_v2_m3",
          "query": "{{INPUT.query}}",
          "max_candidates": 20,
          "top_k": 5
        }
      }
    },
    {
      "stage_name": "context",
      "stage_type": "apply",
      "config": {
        "stage_id": "rag_prepare",
        "parameters": {"max_tokens": 8000, "output_mode": "single_context"}
      }
    }
  ]
}
```

### Search segments, return whole videos

Split each video into layers, each its own collection: a `videos` layer with `split_method: "whole"` and a `scenes` layer with `split_method: "scene"`. Embed only the layer you search. Search `scenes`, then climb lineage to `videos`. Fifty scene hits from 12 videos return 12 documents, each scored by its best scene, with the scenes in `_evidence` (`start_time` and `end_time` give the moment).

```json Scene search that returns parent videos theme={null}
{
  "stages": [
    {
      "stage_name": "scene_search",
      "stage_type": "filter",
      "config": {
        "stage_id": "feature_search",
        "parameters": {
          "searches": [
            {
              "feature_uri": "mixpeek://multimodal_extractor@v1/vertex_multimodal_embedding",
              "query": {"input_mode": "text", "value": "{{INPUT.query}}"},
              "top_k": 50
            }
          ],
          "final_top_k": 50
        }
      }
    },
    {
      "stage_name": "whole_videos",
      "stage_type": "apply",
      "config": {
        "stage_id": "traverse_edge",
        "parameters": {
          "follow": "lineage",
          "target_collection_id": "videos",
          "include_evidence": true
        }
      }
    }
  ]
}
```

A scene that cannot reach `videos` is dropped, counted in `stage_statistics.stages.whole_videos.metadata`, and reported in `warnings`. A feature search over a layer with no vector index returns 400 naming the collection. To read a document's parent or children outside a retriever, use the documents API's `expand` (`parent`, `ancestors`, `root_object`, `children`), described in [Collections and features](https://docs.mixpeek.com/docs/extract/collections.md).

Deployable pipelines for these patterns are in [Templates](https://docs.mixpeek.com/docs/templates/overview.md).


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