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

# Tune relevance

> Measure retriever quality with evaluations (NDCG, recall), pick a fusion strategy, record interactions and turn on learned fusion.

Measure how good a retriever's results are, change the pipeline, and measure again, until the numbers and your users agree.

**Prerequisites:** a [retriever](https://docs.mixpeek.com/docs/retrieve/retrievers.md) with a `feature_search` stage, saved in `RETRIEVER_ID`, and `MIXPEEK_API_KEY` and `NAMESPACE_ID` set. Learned fusion also needs two or more entries in `searches` and a `user_id` input.

**1. Measure a baseline**

Create a ground-truth dataset and run an evaluation. Keep the `evaluation_id`. See [Measure quality with an evaluation](#measure-quality-with-an-evaluation).

**2. Change the pipeline**

Try a different [fusion strategy](#hybrid-search-fusion-strategies), add a [`rerank`](https://docs.mixpeek.com/docs/retrieve/stages#rerank) stage, or filter earlier.

**3. Measure again**

Run the same dataset with `baseline_evaluation_id` set, and keep the change only if the metrics rise.

**4. Learn from users**

[Record interactions](#record-interactions) from your UI, then [turn on learned fusion](#learned-fusion-auto-tune) in shadow mode and ramp it up.

## Measure quality with an evaluation

An evaluation runs every query in a ground-truth dataset through a retriever and scores the results. Each query has a `query_id`, a `query_input` keyed by the retriever's `input_schema`, the `relevant_documents`, and optional `relevance_scores` from 0 to 5 for NDCG.

```bash cURL theme={null}
curl -sS -X POST "https://api.mixpeek.com/v1/retrievers/evaluations/datasets" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "dataset_name": "product-search-golden",
    "queries": [
      {
        "query_id": "q1",
        "query_input": {"query": "wireless earbuds"},
        "relevant_documents": ["doc_a1", "doc_a2", "doc_a3"],
        "relevance_scores": {"doc_a1": 5, "doc_a2": 3, "doc_a3": 2}
      },
      {
        "query_id": "q2",
        "query_input": {"query": "noise canceling headphones"},
        "relevant_documents": ["doc_b1", "doc_b4"]
      }
    ]
  }'
```

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

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

dataset = {
    "dataset_name": "product-search-golden",
    "queries": [
        {
            "query_id": "q1",
            "query_input": {"query": "wireless earbuds"},
            "relevant_documents": ["doc_a1", "doc_a2", "doc_a3"],
            "relevance_scores": {"doc_a1": 5, "doc_a2": 3, "doc_a3": 2},
        },
        {
            "query_id": "q2",
            "query_input": {"query": "noise canceling headphones"},
            "relevant_documents": ["doc_b1", "doc_b4"],
        },
    ],
}
requests.post(
    "https://api.mixpeek.com/v1/retrievers/evaluations/datasets",
    headers=HEADERS,
    json=dataset,
).raise_for_status()

run = requests.post(
    f"https://api.mixpeek.com/v1/retrievers/{os.environ['RETRIEVER_ID']}/evaluations",
    headers=HEADERS,
    json={
        "dataset_name": "product-search-golden",
        "evaluation_config": {"k_values": [1, 5, 10], "metrics": ["precision", "recall", "ndcg", "mrr"]},
    },
).json()
print(run["evaluation_id"])
```

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

await fetch("https://api.mixpeek.com/v1/retrievers/evaluations/datasets", {
  method: "POST",
  headers,
  body: JSON.stringify({
    dataset_name: "product-search-golden",
    queries: [
      {
        query_id: "q1",
        query_input: { query: "wireless earbuds" },
        relevant_documents: ["doc_a1", "doc_a2", "doc_a3"],
        relevance_scores: { doc_a1: 5, doc_a2: 3, doc_a3: 2 },
      },
      {
        query_id: "q2",
        query_input: { query: "noise canceling headphones" },
        relevant_documents: ["doc_b1", "doc_b4"],
      },
    ],
  }),
});

const res = await fetch(
  `https://api.mixpeek.com/v1/retrievers/${process.env.RETRIEVER_ID}/evaluations`,
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      dataset_name: "product-search-golden",
      evaluation_config: { k_values: [1, 5, 10], metrics: ["precision", "recall", "ndcg", "mrr"] },
    }),
  },
);
const run = await res.json();
console.log(run.evaluation_id);
```

The run is asynchronous and keys on the dataset name. Poll `GET /v1/retrievers/{retriever_id}/evaluations/{evaluation_id}` until `status` is `completed`, then read `overall_metrics` and `metrics_by_k`.

| `evaluation_config` key | Default | Description |
| - | - | - |
| `metrics` | `precision`, `recall`, `f1`, `map`, `ndcg`, `mrr` | `f2` is also available and weights recall over precision. |
| `k_values` | `[1, 5, 10, 20]` | Cutoffs for the `@k` metrics. |
| `k_multiples_of_relevant` | none | Per-query cutoffs as multiples of R, the number of relevant items listed for that query: `[1, 2]` adds `f1_at_1r` and `f2_at_2r`. |
| `baseline_evaluation_id` | none | A completed run on the same dataset to compare against. |
| `stages` | the saved stages | Score an inline pipeline on the retriever's collections without saving it. |
| `repeats` | `1` | Run each query several times to see run-to-run spread. |

Aim for 50 queries or more. `POST /v1/retrievers/{retriever_id}/evaluations/generate-from-interactions` builds a dataset from recorded interactions. A retriever that returns one document per group needs `relevance_field` on the dataset, so `relevant_documents` lists that field's values instead of document ids. See [Run evaluation](https://docs.mixpeek.com/docs/api-reference/retriever-evaluations/run-evaluation.md).

To grade by source file, set `relevance_field: "root_object_id"`. Every result carries `root_object_id`, the id of the bucket object it was extracted from, so the scenes of one video or the chunks of one PDF share it. List object ids in `relevant_documents`; results from one file count once, at the rank of the first, so the scores read per file. A customer field stored as `root_object_id` takes the place of the source object id.

```json Dataset graded by source file theme={null}
{
  "dataset_name": "videos-by-source",
  "relevance_field": "root_object_id",
  "queries": [
    {"query_id": "q1", "query_input": {"query": "how to apply primer"}, "relevant_documents": ["obj_8f2c1a", "obj_19be07"]}
  ]
}
```

## Hybrid search fusion strategies

When `feature_search` runs two or more searches, `fusion` decides how their ranked lists merge into one. Set it in the stage's `parameters` beside `searches`.

| `fusion` | Score | Use it when |
| - | - | - |
| `rrf` (default) | `weight / (60 + rank)`, summed over searches | You have no reason to pick another. Ignores raw scores, so dense plus BM25 works. |
| `dbsf` | Each search min-max normalized to 0 to 1, times `weight`, summed | Searches score on different scales and you want one to lead, for example transcript `1.0`, frames `0.2`. |
| `weighted` | `weight × score`, summed | Searches score on the same scale and you know their importance. |
| `max` | The highest score across searches | One strong match on any search is enough. |
| `learned` | Weights sampled per user from interactions | Users differ and you record interactions. |

```json feature_search with two searches under dbsf theme={null}
{
  "stage_name": "search",
  "stage_type": "filter",
  "config": {
    "stage_id": "feature_search",
    "parameters": {
      "fusion": "dbsf",
      "searches": [
        {
          "feature_uri": "mixpeek://multimodal_extractor@v1/multilingual_e5_large_instruct_v1",
          "query": {"input_mode": "text", "value": "{{INPUT.query}}"},
          "weight": 1.0
        },
        {
          "feature_uri": "mixpeek://multimodal_extractor@v1/vertex_multimodal_embedding",
          "query": {"input_mode": "text", "value": "{{INPUT.query}}"},
          "weight": 0.2
        }
      ],
      "final_top_k": 25
    }
  }
}
```

RRF scores are small by design. The best possible score is about `1 / 61 ≈ 0.0164` per search, so a top score near `0.017` is healthy. Compare documents by their order; the size of an RRF score carries no meaning on its own. For an absolute 0 to 1 score, run one search without fusion, or gate on a rerank score with [`score_threshold`](https://docs.mixpeek.com/docs/retrieve/stages#score-threshold). Every strategy adds under 10 ms.

## Record interactions

An interaction records what a user did with one result. Send `feature_id` (the result's `document_id`), `interaction_type` (always an array), and `position` (0-based rank). Add `retriever_id`, `execution_id`, `user_id`, `session_id`, and the result's `feature_uri`, which learned fusion needs to credit the right search.

```bash cURL theme={null}
curl -sS -X POST "https://api.mixpeek.com/v1/retrievers/interactions" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d @- <<JSON
{
  "feature_id": "doc_a1",
  "interaction_type": ["click", "long_view"],
  "position": 2,
  "retriever_id": "$RETRIEVER_ID",
  "user_id": "user_123",
  "session_id": "sess_456",
  "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
  "metadata": {"duration_ms": 45000}
}
JSON
```

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

requests.post(
    "https://api.mixpeek.com/v1/retrievers/interactions",
    headers={
        "Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}",
        "X-Namespace": os.environ["NAMESPACE_ID"],
    },
    json={
        "feature_id": "doc_a1",
        "interaction_type": ["click", "long_view"],
        "position": 2,
        "retriever_id": os.environ["RETRIEVER_ID"],
        "user_id": "user_123",
        "session_id": "sess_456",
        "feature_uri": "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
        "metadata": {"duration_ms": 45000},
    },
).raise_for_status()
```

```javascript JavaScript theme={null}
await fetch("https://api.mixpeek.com/v1/retrievers/interactions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}`,
    "X-Namespace": process.env.NAMESPACE_ID,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    feature_id: "doc_a1",
    interaction_type: ["click", "long_view"],
    position: 2,
    retriever_id: process.env.RETRIEVER_ID,
    user_id: "user_123",
    session_id: "sess_456",
    feature_uri: "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1",
    metadata: { duration_ms: 45000 },
  }),
});
```

The array holds the signals of one user action, so a click followed by a long read is `["click", "long_view"]`. Send separate actions as separate interactions. For buffered events, `POST /v1/retrievers/interactions/batch` takes up to 1,000 per call; batched events skip the real-time session cache.

| `interaction_type` | Default reward | Record it when |
| - | - | - |
| `impression` | 0 | A result is shown |
| `click` | 1.0 | The user opens a result |
| `dwell` | 0.5 | The user lingers |
| `long_view` | 1.0 | Sustained engagement; put `duration_ms` in `metadata` |
| `add_to_cart` | 2.0 | Purchase intent |
| `purchase` | 3.0 | Conversion |
| `bookmark`, `share` | 1.5 | Saved or shared |
| `positive_feedback` | 2.0 | Thumbs up, or an editor approves |
| `negative_feedback` | -2.0 | Thumbs down, or an editor rejects |
| `skip`, `return_to_results` | -0.5 | Shown and ignored, or a quick bounce |

`view`, `wishlist`, `query_refinement`, `zero_results`, `filter_toggle`, `play`, `download`, `save`, `add_to_project` and `rating` are also valid and score 0 unless your `reward_map` names them. Interactions are stored in the namespace's `mxp_retriever_interactions` system collection, which you can list and filter like any collection. See [Create interaction](https://docs.mixpeek.com/docs/api-reference/retriever-interactions/create-interaction.md).

## Learned fusion (Auto-Tune)

Learned fusion sets the weights between a stage's searches per user, from that user's interactions. Each search's `feature_uri` is one arm of a Thompson Sampling bandit with a Beta(alpha, beta) distribution. A positive reward adds to alpha, a negative reward adds its absolute value to beta, and each query samples weights from the distributions. With no interactions, every search gets an equal weight.

Set `"fusion": "learned"` and a `learning_config` in the `feature_search` parameters, and declare `user_id` in the retriever's `input_schema`:

```json learning_config for a shadow-mode rollout theme={null}
{
  "fusion": "learned",
  "learning_config": {
    "context_features": ["INPUT.user_id"],
    "reward_map": {"click": 1.0, "add_to_cart": 2.0, "purchase": 3.0, "negative_feedback": -2.0},
    "min_interactions": 5,
    "shadow_mode": true,
    "rollout_pct": 100.0
  }
}
```

| `learning_config` field | Default | Description |
| - | - | - |
| `context_features` | `["INPUT.user_id"]` | Inputs that identify the user. An empty list turns off per-user learning. |
| `demographic_features` | `[]` | Inputs for a segment fallback, for example `["INPUT.user_segment"]`. |
| `min_interactions` | `5` | Interactions a user needs before their own weights are used, 1 to 100. |
| `reward_map` | the table above | Replaces the defaults entirely. Include every type you want counted. |
| `shadow_mode` | `false` | Compute and report learned weights, serve RRF results. |
| `rollout_pct` | `100.0` | Share of requests that get learned weights, bucketed by a hash of `user_id`. |
| `decay_factor` | `0.995` | Per-day weight on older interactions. `1.0` turns decay off. |
| `min_weight`, `max_weight` | `0.05`, `0.95` | Bounds on each sampled weight. |

Weights come from the first level with data: the user (after `min_interactions`), the user's segment, all users of the retriever, then equal weights. Learned fusion changes how searches are weighted; it keeps no per-document state, so a document that ranks low in every search stays low. To move single documents, add a [`rerank`](https://docs.mixpeek.com/docs/retrieve/stages#rerank) stage.

Roll out in three steps: run with `shadow_mode: true` and compare the reported weights with your evaluation; set `shadow_mode: false` with `rollout_pct` at 10, then raise it; set `fusion` back to `rrf` to turn it off. Each change is a `PATCH` of the retriever's stages and applies on the next request. A published retriever's stages are fixed, so clone it first.

## Check that it worked

* **Evaluation:** the new run's `metrics_by_k` beats the baseline at the `k` your UI shows.
* **Learned fusion:** an execute response from a learned-fusion stage carries `learned_fusion_context`. `gate` is `serve`, `shadow` or `skip`. `context_level` is `personal`, `demographic`, `global`, `session` or `none`. `sampled_weights` gives the weight per feature URI.
* **Production:** the retriever analytics endpoints show the effect on real traffic.

| Endpoint | Returns |
| - | - |
| [`GET /v1/analytics/retrievers/{retriever_id}/performance`](https://docs.mixpeek.com/docs/api-reference/analytics/get-retriever-performance) | Latency percentiles and query counts |
| [`GET /v1/analytics/retrievers/{retriever_id}/stages`](https://docs.mixpeek.com/docs/api-reference/analytics/get-stage-breakdown) | Time and document counts per stage |
| [`GET /v1/analytics/retrievers/{retriever_id}/signals`](https://docs.mixpeek.com/docs/api-reference/analytics/get-retriever-signals) | Cache hits, rerank scores, filter reduction |
| [`POST /v1/analytics/retrievers/{retriever_id}/analyze-tuning`](https://docs.mixpeek.com/docs/api-reference/analytics/analyze-for-tuning) | Parameter suggestions from the last `days` (default 7) |

## What goes wrong

| Symptom | Cause and fix |
| - | - |
| `context_level` reads `global` or `none` for a known user | The user's interactions lack `retriever_id`, `feature_uri` or `user_id`, or number fewer than `min_interactions`. |
| A reward type has no effect | A custom `reward_map` replaces the defaults; add the type. |
| The retriever is rejected on create | `learned` needs 2 or more searches; `min_weight` must be under `max_weight`; every `reward_map` key must be a valid interaction type. |
| An evaluation finishes as `failed` | Every query skipped, usually because `query_input` keys do not match the retriever's `input_schema`. Each query's `error` names the key. |
| Weights swing after a few thumbs-down | A large negative reward outweighs many clicks. Keep negative values smaller than positive ones. |
| Top RRF scores look low | Expected. See [fusion strategies](#hybrid-search-fusion-strategies). |

A click at position 8 earns the same reward as a click at position 0. Mixpeek stores `position` for your own analysis.

## Related

* [Stages](https://docs.mixpeek.com/docs/retrieve/stages.md): `rerank`, `mmr`, `score_threshold` and the other sort stages
* [Annotations](https://docs.mixpeek.com/docs/enrich/annotations.md): explicit labels that can seed a dataset with `from_annotations`
* [Monitoring and troubleshooting](https://docs.mixpeek.com/docs/production/monitoring.md): latency, slow queries and alerts


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