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

# Contextual video match

> An article goes in, a ranked playlist of video comes out, and every match carries the entities, keywords and categories that produced it.

![Contextual video match](https://mixpeek.com/templates/contextual-video-match/scenes.webp)

An article goes in, a ranked playlist of video comes out, and every match carries the entities, keywords and categories that produced it. Both sides are embedded twice, once by a text model and once by a multimodal one, so nothing is embedded at query time and a clip in another language still matches.

> [card] [Deploy in Studio](https://studio.mixpeek.com/manifests/apply?url=https%3A%2F%2Fmixpeek.com%2Ftemplates%2Fcontextual-video-match.namespace.yaml\&manifest_url=https%3A%2F%2Fmixpeek.com%2Ftemplates%2Fcontextual-video-match.namespace.yaml\&src=template-contextual-video-match\&template=contextual-video-match\&template_name=Contextual+video+match\&sync=1\&utm_source=docs\&utm_medium=template_deploy\&utm_campaign=mvs_onramp)
>
> Creates every resource below in your organization, with sample data.

> [card] [Download the manifest](https://mixpeek.com/templates/contextual-video-match.namespace.yaml)
>
> `contextual-video-match.namespace.yaml`, the file Studio and the API apply.

> [card] [Template page](https://mixpeek.com/templates/contextual-video-match)
>
> The demo and the use case on mixpeek.com.

## At a glance

| | |
| - | - |
| **Creates** | 1 namespace, 2 buckets, 4 collections, 2 retrievers, 1 alert |
| **Extractors** | [`multimodal_extractor`](https://docs.mixpeek.com/docs/extract/extractors#multimodal) v1, [`text_extractor`](https://docs.mixpeek.com/docs/extract/extractors#text) v1 |
| **Models** | [Multilingual E5 Large Instruct](https://mixpeek.com/models/multilingual-e5-large-instruct), [Vertex AI multimodalembedding@001](https://mixpeek.com/models/multimodalembedding) |
| **Daily spend budget** | 1 USD, set on the namespace. Queries are not capped. |
| **Sample data** | 4 objects, uploaded to `videos`, `articles` when you apply |
| **Version** | 1.0, updated 2026-09-14 |

## 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[("videos")]
  b1[("articles")]
  c2["video-scenes<br/>multimodal_extractor v1"]
  c3["article-multimodal<br/>multimodal_extractor v1"]
  c4["scene-transcripts<br/>text_extractor v1"]
  c5["article-text<br/>text_extractor v1"]
  r6{{"contextual-match"}}
  r7{{"scene-search"}}
  b0 --> c2
  b1 --> c3
  c2 --> c4
  b1 --> c5
  c4 --> r6
  c2 --> r6
  c5 --> r6
  c3 --> r6
  c2 --> r7
  c4 --> r7
```

## Deploy it

> [tab] API
>
> **1. Get the manifest**
>
> ```bash theme={null}
> curl -sO https://mixpeek.com/templates/contextual-video-match.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=@contextual-video-match.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=@contextual-video-match.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.

> [tab] Studio
>
> Open [Deploy in Studio](https://studio.mixpeek.com/manifests/apply?url=https%3A%2F%2Fmixpeek.com%2Ftemplates%2Fcontextual-video-match.namespace.yaml\&manifest_url=https%3A%2F%2Fmixpeek.com%2Ftemplates%2Fcontextual-video-match.namespace.yaml\&src=template-contextual-video-match\&template=contextual-video-match\&template_name=Contextual+video+match\&sync=1\&utm_source=docs\&utm_medium=template_deploy\&utm_campaign=mvs_onramp), sign in, choose where to deploy, and select **Apply to my workspace**. Studio shows each resource as it is created.

## Run the first query

Look up the namespace id by name, then run `scene-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/contextual-video-match \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" | jq -r .namespace_id)

curl -X POST https://api.mixpeek.com/v1/retrievers/scene-search/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"query": "a kitchen scene with someone cooking at a hob"}}' \
  | 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/contextual-video-match", headers=AUTH).json()

run = requests.post(
    "https://api.mixpeek.com/v1/retrievers/scene-search/execute",
    headers={**AUTH, "X-Namespace": ns["namespace_id"]},
    json={"inputs": {"query": "a kitchen scene with someone cooking at a hob"}},
).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/contextual-video-match", { headers: auth }).then((r) => r.json());

const run = await fetch("https://api.mixpeek.com/v1/retrievers/scene-search/execute", {
  method: "POST",
  headers: { ...auth, "X-Namespace": ns.namespace_id, "Content-Type": "application/json" },
  body: JSON.stringify({"inputs": {"query": "a kitchen scene with someone cooking at a hob"}}),
}).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 `videos`. `NAMESPACE_ID` is the id from the namespace lookup above.

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

```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/videos/objects",
    params={"auto_process": "true"},
    headers=HEADERS,
    json={
        "blobs": [
            {
                "property": "content",
                "type": "video",
                "data": "https://example.com/clip.mp4"
            }
        ]
    },
).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/videos/objects?auto_process=true", {
  method: "POST",
  headers,
  body: JSON.stringify({
    "blobs": [
      {
        "property": "content",
        "type": "video",
        "data": "https://example.com/clip.mp4"
      }
    ]
  }),
}).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

### `contextual-match`

Matches scene-transcripts and video-scenes against a document from article-text and article-multimodal, with no query-time embedding.

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

**Searches:** `scene-transcripts`, `video-scenes`, `article-text`, `article-multimodal`

| Input | Type | Required | Description |
| - | - | - | - |
| `article_text_doc_id` | string | yes | Document id of the article in article-text, whose stored text vector the scene transcripts are matched against |
| `article_multimodal_doc_id` | string | yes | Document id of the same article in article-multimodal, whose stored multimodal vector the video scenes are matched against |
| `article_entities` | array | no | Entities already extracted from the article; drives the 0.25 overlap term |
| `article_keywords` | array | no | Keywords already extracted from the article; drives the 0.15 overlap term |
| `article_iab_categories` | array | no | IAB categories for the article; drives the 0.10 taxonomy term and the Entertainment-against-News penalty |

### `scene-search`

Type what a scene should show or say and get the matching seconds of video, ranked over the frames and the transcript together.

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

**Searches:** `video-scenes`, `scene-transcripts`

| Input | Type | Required | Description |
| - | - | - | - |
| `query` | text | yes | What to look for; searched across every index below |

## Collections

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

> [accordion] video-scenes
>
> multimodal\_extractor\@v1 over bucket videos. Feeds scene-transcripts, contextual-match, scene-search.
>
> **Reads** bucket `videos` with [`multimodal_extractor`](https://docs.mixpeek.com/docs/extract/extractors#multimodal) v1.
>
> **Inputs:** `video` ← `content`
>
> **Copied onto each document:** `file_location`, `segment_id`, `start_time`, `end_time`, `tenant_id`
>
> | Document field | Type |
> | - | - |
> | `file_location` | any |
> | `segment_id` | any |
> | `start_time` | number |
> | `end_time` | number |
> | `tenant_id` | any |
> | `start_frame` | integer |
> | `end_frame` | integer |
> | `fps` | number |
> | `source_fps` | number |
> | `analysis_fps` | number |
> | `width` | integer |
> | `height` | integer |
> | `aspect_ratio` | number |
> | `duration` | number |
> | `transcription` | string |
> | `description` | string |
> | `ocr_text` | string |
> | `json_output` | object |
> | `thumbnail_url` | string |
> | `source_video_url` | string |
> | `video_segment_url` | string |
> | `multimodal_extractor_v1_multimodal_embedding` | array\<number> |
> | `multimodal_extractor_v1_transcription_embedding` | array\<number> |
> | `internal_metadata` | object |

> [accordion] article-multimodal
>
> multimodal\_extractor\@v1 over bucket articles. Feeds contextual-match.
>
> **Reads** bucket `articles` with [`multimodal_extractor`](https://docs.mixpeek.com/docs/extract/extractors#multimodal) v1.
>
> **Inputs:** `text` ← `content`
>
> **Copied onto each document:** `article_url`, `published_at`, `tenant_id`
>
> | Document field | Type |
> | - | - |
> | `article_url` | any |
> | `published_at` | any |
> | `tenant_id` | any |
> | `start_time` | number |
> | `end_time` | number |
> | `start_frame` | integer |
> | `end_frame` | integer |
> | `fps` | number |
> | `source_fps` | number |
> | `analysis_fps` | number |
> | `width` | integer |
> | `height` | integer |
> | `aspect_ratio` | number |
> | `duration` | number |
> | `transcription` | string |
> | `description` | string |
> | `ocr_text` | string |
> | `json_output` | object |
> | `thumbnail_url` | string |
> | `source_video_url` | string |
> | `video_segment_url` | string |
> | `multimodal_extractor_v1_multimodal_embedding` | array\<number> |
> | `multimodal_extractor_v1_transcription_embedding` | array\<number> |
> | `internal_metadata` | object |

> [accordion] scene-transcripts
>
> text\_extractor\@v1 over collection video-scenes. Feeds contextual-match, scene-search.
>
> **Reads** collection `video-scenes` with [`text_extractor`](https://docs.mixpeek.com/docs/extract/extractors#text) v1.
>
> **Inputs:** `text` ← `transcription`
>
> **Copied onto each document:** `segment_id`, `video_segment_url`, `start_time`, `end_time`
>
> | Document field | Type |
> | - | - |
> | `segment_id` | any |
> | `video_segment_url` | string |
> | `start_time` | number |
> | `end_time` | number |
> | `text` | string |
> | `text_extractor_v1_embedding` | array\<number> |
> | `video_id` | string |
> | `title` | string |
> | `channel` | string |
> | `video_url` | string |
> | `duration_seconds` | integer |
> | `publish_date` | string |
> | `start_ms` | integer |
> | `end_ms` | integer |
> | `segment_index` | integer |
> | `heading_path` | string |
> | `chunk_kind` | string |
> | `code_language` | string |
> | `total_segments` | integer |

> [accordion] article-text
>
> text\_extractor\@v1 over bucket articles. Feeds contextual-match.
>
> **Reads** bucket `articles` with [`text_extractor`](https://docs.mixpeek.com/docs/extract/extractors#text) v1.
>
> **Inputs:** `text` ← `content`
>
> **Copied onto each document:** `article_url`, `published_at`, `tenant_id`
>
> | Document field | Type |
> | - | - |
> | `article_url` | any |
> | `published_at` | any |
> | `tenant_id` | any |
> | `text` | string |
> | `text_extractor_v1_embedding` | array\<number> |
> | `video_id` | string |
> | `title` | string |
> | `channel` | string |
> | `video_url` | string |
> | `duration_seconds` | integer |
> | `publish_date` | string |
> | `start_ms` | integer |
> | `end_ms` | integer |
> | `segment_index` | integer |
> | `heading_path` | string |
> | `chunk_kind` | string |
> | `code_language` | string |
> | `total_segments` | integer |

## Also created

**[Alerts](https://docs.mixpeek.com/docs/enrich/alerts-and-triggers.md)**

* `contextual-match-returning-nothing`: Emails the org notifications address (Settings -> Notifications; unset means opted out) when contextual-match has come back empty on its last five runs: the articles are matching no scene, so the video index or the article documents need a look.

> [accordion] Cost estimate at list price
>
> At 10,000 items a month (2 minutes or 10 pages each) and 100,000 queries, this template costs about **7,301.11 USD a month** (730.09 USD per 1,000 items). The namespace's daily spend budget pauses new batches before you pass it.
>
> | Part | USD a month |
> | - | - |
> | Processing | 7,300.50 |
> | Storage | 0.41 |
> | Queries | 0.20 |
> | Processing in `video-scenes` | 7,272.00 |
> | Processing in `article-multimodal` | 28.50 |

## 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 contextual-video-match.namespace.yaml expandable theme={null}
# contextual-video-match: one manifest spins up the namespace.
# Platform manifest schema (GET /v1/discovery/schema). Validate with POST /v1/manifest/validate,
# apply with POST /v1/manifest/apply or the Deploy button. Wiring comes from the flow diagram:
# edges are bucket -> collection sources, collection -> retriever scope, retriever -> view.
# 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, so an upgrade looks like a dead end without this. Use
# mode=upsert to also patch resources that exist but have drifted from this file.
version: '1.0'
metadata:
  name: contextual-video-match
  description: "Namespace template contextual-video-match. Generated from the flow diagram on mixpeek.com/templates/contextual-video-match."
namespaces:
  - name: contextual-video-match
    description: "Everything below lives in this namespace."
    feature_extractors:
      - name: multimodal_extractor
        version: v1
      - name: text_extractor
        version: v1
    # 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

# Data sources. A storage connection carries credentials, so it is created in Studio
# (or POST /v1/organizations/connections) and synced into the bucket named here.
#   video-corpus: s3, continuous, the video library you want matched against, in your account -> bucket videos
#   article-feed: manual, continuous, one object per page: the article text, its URL, its publish time and the tenant it belongs to -> bucket articles
buckets:
  - name: videos
    namespace: contextual-video-match
    description: "Meant to be fed by video-corpus (s3, continuous). No source is connected yet: applying this manifest creates the bucket only. Connect the source to this bucket in Studio (Syncs) to start the feed."
    schema:
      properties:
        content:
          type: video
  - name: articles
    namespace: contextual-video-match
    description: "Meant to be fed by article-feed (manual, continuous): upload files here or write them through the API. Nothing arrives until you do."
    schema:
      properties:
        content:
          type: text

# Connect your own storage. Create the secrets named below, uncomment, and apply again;
# apply live-tests the connection, so it must have real credentials to succeed.
# Until then the buckets above accept direct uploads.
# storage_connections:
#   - name: video-corpus-connection
#     provider: s3
#     description: "Read-only access to the s3 location holding the video library you want matched against, in your account."
#     config:
#       region: us-east-1
#       credentials:
#         type: access_key
#         access_key_id: ${{ secrets.AWS_ACCESS_KEY_ID }}
#         secret_access_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

# bucket_syncs:
#   - name: video-corpus-sync
#     bucket: videos
#     connection: video-corpus-connection
#     source_path: "videos/"
#     sync_mode: continuous
#     polling_interval_seconds: 300
#     skip_duplicates: true
#     file_filters:
#       include_patterns: ["*.mp4", "*.mov", "*.webm"]
#     schema_mapping:
#       mappings:
#         content:
#           target_type: blob
#           source: {type: file}
#           blob_type: video

collections:
  - name: video-scenes
    namespace: contextual-video-match
    description: "multimodal_extractor@v1 over bucket videos. Feeds scene-transcripts, contextual-match, scene-search."
    source:
      type: bucket
      bucket: videos
    feature_extractor:
      name: multimodal_extractor
      version: v1
      parameters:
        run_transcription: true
        run_video_description: true
        run_ocr: true
        description_prompt: "Identify the named entities and topical keywords present in this video segment, from what is spoken, shown on screen, and visible in the frame. Transcribe any text burned into the frame, such as captions, lower thirds, tickers and signage, verbatim."
        response_shape:
          type: "object"
          properties:
            entities:
              type: "array"
              items:
                type: "string"
              description: "Named entities (people, organizations, places) in canonical English form, deduplicated. 3-10 items."
            keywords:
              type: "array"
              items:
                type: "string"
              description: "Topical keywords or short phrases describing what the segment is about. 3-8 items."
            iab_categories:
              type: "array"
              items:
                type: "string"
              description: "IAB Content Taxonomy tier-1 category names that describe this segment, written exactly as IAB names them, for example \"News & Politics\", \"Arts & Entertainment\", \"Sports\", \"Automotive\". 1-3 items."
            ocr_text:
              type: "string"
              description: "Text burned into the frame, transcribed verbatim: captions, lower thirds, tickers, signage. Empty string when the segment shows no text."
      input_mappings:
        video: content
      field_passthrough:
        - source_path: file_location
        - source_path: segment_id
        - source_path: start_time
        - source_path: end_time
        - source_path: tenant_id
    enabled: true
  - name: article-multimodal
    namespace: contextual-video-match
    description: "multimodal_extractor@v1 over bucket articles. Feeds contextual-match."
    source:
      type: bucket
      bucket: articles
    feature_extractor:
      name: multimodal_extractor
      version: v1
      input_mappings:
        text: content
      field_passthrough:
        - source_path: article_url
        - source_path: published_at
        - source_path: tenant_id
    enabled: true
  - name: scene-transcripts
    namespace: contextual-video-match
    description: "text_extractor@v1 over collection video-scenes. Feeds contextual-match, scene-search."
    source:
      type: collection
      collection: video-scenes
    feature_extractor:
      name: text_extractor
      version: v1
      input_mappings:
        text: transcription
      field_passthrough:
        - source_path: segment_id
        - source_path: video_segment_url
        - source_path: start_time
        - source_path: end_time
    enabled: true
  - name: article-text
    namespace: contextual-video-match
    description: "text_extractor@v1 over bucket articles. Feeds contextual-match."
    source:
      type: bucket
      bucket: articles
    feature_extractor:
      name: text_extractor
      version: v1
      input_mappings:
        text: content
      field_passthrough:
        - source_path: article_url
        - source_path: published_at
        - source_path: tenant_id
    enabled: true
retrievers:
  - name: contextual-match
    namespace: contextual-video-match
    description: "Matches scene-transcripts and video-scenes against a document from article-text and article-multimodal, with no query-time embedding."
    collections:
      - scene-transcripts
      - video-scenes
      - article-text
      - article-multimodal
    input_schema:
      article_text_doc_id:
        type: string
        required: true
        description: "Document id of the article in article-text, whose stored text vector the scene transcripts are matched against"
      article_multimodal_doc_id:
        type: string
        required: true
        description: "Document id of the same article in article-multimodal, whose stored multimodal vector the video scenes are matched against"
      article_entities:
        type: array
        required: false
        description: "Entities already extracted from the article; drives the 0.25 overlap term"
      article_keywords:
        type: array
        required: false
        description: "Keywords already extracted from the article; drives the 0.15 overlap term"
      article_iab_categories:
        type: array
        required: false
        description: "IAB categories for the article; drives the 0.10 taxonomy term and the Entertainment-against-News penalty"
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://text_extractor@v1"
              collection_identifiers:
                - scene-transcripts
              query:
                input_mode: document
                document_ref:
                  collection_id: article-text
                  document_id: "{{INPUT.article_text_doc_id}}"
              top_k: 30
              min_score: 0.15
            - feature_uri: "mixpeek://multimodal_extractor@v1/vertex_multimodal_embedding"
              collection_identifiers:
                - video-scenes
              query:
                input_mode: document
                document_ref:
                  collection_id: article-multimodal
                  document_id: "{{INPUT.article_multimodal_doc_id}}"
              top_k: 30
          fusion: rrf
          final_top_k: 30
      - stage_name: deduplicate
        stage_id: deduplicate
        parameters:
          strategy: field
          fields:
            - source_video_url
            - start_time
          keep: first
      - stage_name: score
        stage_id: code_execution
        parameters:
          language: python
          output_field: scoring
          timeout_ms: 5000
          code: |
            _ae = {{ INPUT.article_entities }}
            _ak = {{ INPUT.article_keywords }}
            _ac = {{ INPUT.article_iab_categories }}
            art_ents = set(str(e).lower() for e in (_ae or []))
            art_kws = set(str(k).lower() for k in (_ak or []))
            art_cats = set(str(c).lower() for c in (_ac or []))
            result = []
            for doc in docs:
                ve = set(str(e).lower() for e in doc.get('entities', []))
                vk = set(str(k).lower() for k in doc.get('keywords', []))
                vc = set(str(c).lower() for c in doc.get('iab_categories', []))
                vt = ((doc.get('transcription') or '') + ' ' + (doc.get('ocr_text') or '')).lower()
                te = set(e for e in art_ents if e in vt)
                all_ents = (art_ents & ve) | te
                eo = len(all_ents) / max(len(art_ents), 1) if art_ents else 0
                ko = len(art_kws & vk) / max(len(art_kws), 1) if art_kws else 0
                to = len(art_cats & vc) / max(len(art_cats), 1) if art_cats else 0
                s = doc.get('scores', {}).get('search', doc.get('score', 0))
                cs = 0.50 * s + 0.25 * min(eo * 1.5, 1.0) + 0.15 * min(ko * 1.5, 1.0) + 0.10 * to
                tp = 0.7 if vc and vc & {'entertainment', 'arts & entertainment'} and art_cats & {'news & politics', 'law government & politics'} else 1.0
                cs *= tp
                result.append({'contextual_score': round(cs, 4), 'entity_overlap': round(eo, 4), 'keyword_overlap': round(ko, 4), 'taxonomy_overlap': round(to, 4), 'entities_matched': list(all_ents)[:5], 'keywords_matched': list(art_kws & vk)[:5], 'iab_matched': list(art_cats & vc)[:3], 'taxonomy_penalty': tp})
    tags:
      - template:contextual-video-match
  - name: scene-search
    namespace: contextual-video-match
    description: "Type what a scene should show or say and get the matching seconds of video, ranked over the frames and the transcript together."
    collections:
      - video-scenes
      - scene-transcripts
    input_schema:
      query:
        type: text
        required: true
        description: "What to look for; searched across every index below"
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://multimodal_extractor@v1/vertex_multimodal_embedding"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 30
            - feature_uri: "mixpeek://text_extractor@v1"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 30
          fusion: rrf
          final_top_k: 30
    tags:
      - template:contextual-video-match
alerts:
  - name: contextual-match-returning-nothing
    namespace: contextual-video-match
    description: "Emails the org notifications address (Settings -> Notifications; unset means opted out) when contextual-match has come back empty on its last five runs: the articles are matching no scene, so the video index or the article documents need a look."
    source: system
    system_condition:
      type: retriever_no_results
      params:
        min_samples: 5
    notification_config:
      channels:
        - channel_type: email
      include_matches: true
      include_scores: true
    enabled: true

# Plan 11.14: two public-domain films and two public-domain texts from the
# starter sample set, ingested after apply, and the use case they must satisfy.
seed:
  - bucket: videos
    max_objects: 2
    objects:
      - blobs: {content: samples/starter/videos/norelco-speed.mp4}
      - blobs: {content: samples/starter/videos/mexican-hat-dance.mp4}
  - bucket: articles
    max_objects: 2
    objects:
      - blobs: {content: samples/starter/texts/frankenstein.txt}
      - blobs: {content: samples/starter/texts/a-christmas-carol.txt}
acceptance:
  max_cost_usd: 0.5
  steps:
    - name: video-scenes-indexed
      kind: documents
      collection: video-scenes
      expect: {min_documents: 2}
    - name: articles-indexed
      kind: documents
      collection: article-text
      expect: {min_documents: 2}
    - name: scenes-answer-a-typed-search
      kind: query
      retriever: scene-search
      inputs: {query: a man shaving with an electric razor}
      expect: {min_results: 1}
```

## 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/contextual-video-match.md`.

```text Prompt theme={null}
Set up the Mixpeek "Contextual video match" template in my organization. My API key is in MIXPEEK_API_KEY.
1. Download https://mixpeek.com/templates/contextual-video-match.namespace.yaml to contextual-video-match.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/contextual-video-match and keep namespace_id. Send it as the X-Namespace header on every call below.
5. POST {"inputs": {"query": "a kitchen scene with someone cooking at a hob"}} to https://api.mixpeek.com/v1/retrievers/scene-search/execute. Read documents, check that status is completed, and print warnings.
Reference for this template: https://mixpeek.com/docs/templates/contextual-video-match.md
```

## How it works

Each video becomes a set of segment documents and each article one document, embedded by the same two models. `contextual-match` compares an article's stored vectors with the segments', so no embedding runs at query time.

### The video side

`video-scenes` runs `multimodal_extractor@v1`, which cuts each video into 10-second segments. Each segment gets a 1408-dimension Vertex AI frame vector, its speech in `transcription`, on-screen text in `ocr_text`, and one Gemini call whose `response_shape` writes `entities`, `keywords` and `iab_categories`.

`scene-transcripts` reads `video-scenes` as its source and embeds each transcript with `text_extractor` (1024 dimensions), so speech and frame matches come from two separate indexes.

### The article side

`article-text` embeds each whole article with `text_extractor`. `article-multimodal` embeds the same text with the Vertex AI multimodal model, in the same space as the frame vectors, so an article's text can find a segment by what it shows.

### How `contextual-match` ranks

You call `contextual-match` with the two document ids of one article:

1. **`search`** runs the `article-text` vector against `scene-transcripts` and the `article-multimodal` vector against `video-scenes`, and merges the lists with `rrf` into 30 documents.
2. **`deduplicate`** keeps the first document for each pair of `source_video_url` and `start_time`.
3. **`score`** runs Python that writes a `scoring` object onto each document, adding four terms:

| Term | Weight | Measures |
| - | - | - |
| Search score | 0.50 | The document's score from the `search` stage |
| Entity overlap | 0.25 | Share of `article_entities` found in the segment's `entities`, transcript or on-screen text, times 1.5, capped at 1 |
| Keyword overlap | 0.15 | Share of `article_keywords` in the segment's `keywords`, times 1.5, capped at 1 |
| IAB overlap | 0.10 | Share of `article_iab_categories` in the segment's `iab_categories` |

The total is multiplied by 0.7 when the segment is entertainment and the article is news or politics. `scoring` also lists what matched, so you can show why a video was picked.

> [!WARNING]
>
> `score` leaves `documents` in fusion order. Sort on `scoring.contextual_score` yourself, or add a `sort_attribute` stage as `playlist` does below. The article's entities, keywords and categories are inputs you send; without them the three overlap terms are 0.

The alert `contextual-match-returning-nothing` emails your organization when `contextual-match` returns nothing 5 runs in a row.

## Call `contextual-match`

The retriever needs the article's `document_id` in `article-text` and in `article-multimodal`. Both come from one bucket object, so list each collection by `source_object_id`, with `OBJECT_ID` set to one article's `object_id`:

```bash cURL theme={null}
FILTER='{"filters": {"AND": [{"field": "source_object_id", "operator": "eq", "value": "'"$OBJECT_ID"'"}]}}'
TEXT_DOC=$(curl -s -X POST https://api.mixpeek.com/v1/collections/article-text/documents/list \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" -d "$FILTER" | jq -r '.results[0].document_id')
MM_DOC=$(curl -s -X POST https://api.mixpeek.com/v1/collections/article-multimodal/documents/list \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" -d "$FILTER" | jq -r '.results[0].document_id')

curl -s -X POST https://api.mixpeek.com/v1/retrievers/contextual-match/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"article_text_doc_id": "'"$TEXT_DOC"'", "article_multimodal_doc_id": "'"$MM_DOC"'",
       "article_entities": ["Victor Frankenstein", "Geneva"], "article_keywords": ["science", "monster"],
       "article_iab_categories": ["Books & Literature"]}}' \
  | jq '{status, warnings, documents: (.documents | sort_by(-.scoring.contextual_score) | map({document_id, start_time, contextual_score: .scoring.contextual_score}))}'
```

## From the template to a production player

The rest of this page builds what a publisher runs behind a video player. Steps 1 to 4 edit `contextual-video-match.namespace.yaml`; apply once at the end. Steps 5 to 7 are calls from your own code.

### 1. Sync the video library from S3

Set up the IAM role as [Object storage](https://docs.mixpeek.com/docs/ingest/object-storage.md) describes, and store its ARN and external id as organization secrets, which apply reads as `${{ secrets.NAME }}`.

```bash cURL theme={null}
for PAIR in "VIDEO_LIBRARY_ROLE_ARN=arn:aws:iam::123456789012:role/mixpeek-storage-sync-role" \
            "VIDEO_LIBRARY_EXTERNAL_ID=mixpeek-acme-news-7f3a"; do
  curl -X POST https://api.mixpeek.com/v1/organizations/secrets \
    -H "Authorization: Bearer $MIXPEEK_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"secret_name": "'"${PAIR%%=*}"'", "secret_value": "'"${PAIR#*=}"'"}'
done
```

Upload each video with the player's filter fields as S3 user metadata:

```bash Upload a video with its metadata theme={null}
aws s3 cp clip_1234.mp4 s3://your-video-bucket/videos/clip_1234.mp4 \
  --metadata video_id=1234,title="Council approves stadium",publisher_id=pub_123,channel_id=ch_city,is_shared=true,published_at=2026-12-01T09:30:00Z
```

Add those fields to the `videos` bucket schema, and replace the commented `storage_connections` and `bucket_syncs` blocks with these. `source_path` starts with the S3 bucket name.

```yaml contextual-video-match.namespace.yaml: the videos bucket theme={null}
  - name: videos
    namespace: contextual-video-match
    description: "Meant to be fed by video-corpus (s3, continuous). No source is connected yet: applying this manifest creates the bucket only. Connect the source to this bucket in Studio (Syncs) to start the feed."
    schema:
      properties:
        content:
          type: video
        video_id:
          type: string
        title:
          type: string
        publisher_id:
          type: string
        channel_id:
          type: string
        is_shared:
          type: string
        published_at:
          type: string
```

```yaml contextual-video-match.namespace.yaml: connection and sync theme={null}
storage_connections:
  - name: video-corpus-connection
    provider: s3
    description: "Read-only access to the S3 prefix that holds the video library."
    config:
      region: us-east-1
      credentials:
        type: iam_role
        role_arn: ${{ secrets.VIDEO_LIBRARY_ROLE_ARN }}
        external_id: ${{ secrets.VIDEO_LIBRARY_EXTERNAL_ID }}

bucket_syncs:
  - name: video-corpus-sync
    bucket: videos
    connection: video-corpus-connection
    source_path: "your-video-bucket/videos/"
    sync_mode: continuous
    polling_interval_seconds: 60
    skip_duplicates: true
    file_filters:
      include_patterns: ["*.mp4", "*.mov", "*.webm"]
    schema_mapping:
      mappings:
        content:
          target_type: blob
          source: {type: file}
          blob_type: video
        video_id:
          target_type: field
          source: {type: metadata, key: video_id}
        title:
          target_type: field
          source: {type: metadata, key: title}
        publisher_id:
          target_type: field
          source: {type: metadata, key: publisher_id}
        channel_id:
          target_type: field
          source: {type: metadata, key: channel_id}
        is_shared:
          target_type: field
          source: {type: metadata, key: is_shared}
          transform: lowercase
        published_at:
          target_type: field
          source: {type: metadata, key: published_at}
```

`is_shared` arrives as a string, and `transform: lowercase` makes `True` and `true` the same value, so step 4 compares against `"true"`. Each sync run submits a batch that runs every collection on `videos`; for a library of thousands of videos, read [Buckets](https://docs.mixpeek.com/docs/ingest/buckets.md) on batch ingestion first.

### 2. Copy the player's fields onto every document

`playlist` filters segments on `publisher_id`, `is_shared` and `channel_id`. Append them to `video-scenes`' `field_passthrough`, and declare a `keyword` payload index for each, which a filter inside a vector search needs.

```yaml contextual-video-match.namespace.yaml: video-scenes field_passthrough theme={null}
      field_passthrough:
        - source_path: file_location
        - source_path: segment_id
        - source_path: start_time
        - source_path: end_time
        - source_path: tenant_id
        - source_path: video_id
        - source_path: title
        - source_path: publisher_id
        - source_path: channel_id
        - source_path: is_shared
        - source_path: published_at
```

```yaml contextual-video-match.namespace.yaml: the namespace theme={null}
namespaces:
  - name: contextual-video-match
    description: "Everything below lives in this namespace."
    feature_extractors:
      - name: multimodal_extractor
        version: v1
      - name: text_extractor
        version: v1
    payload_indexes:
      - field_name: brand_safety
        type: keyword
      - field_name: publisher_id
        type: keyword
      - field_name: channel_id
        type: keyword
      - field_name: is_shared
        type: keyword
    budget:
      daily_usd: 1
```

For articles, add `article_id`, `title`, `publisher_id`, `article_url` and `published_at` as `string` properties to the `articles` schema. Append `article_id`, `title` and `publisher_id` to `article-text`'s `field_passthrough`, and `article_id` to `article-multimodal`'s.

### 3. Label articles and videos at ingest

Each collection runs a labeling retriever on every new document as a [retriever enrichment](https://docs.mixpeek.com/docs/enrich/taxonomies.md). The retriever selects that document with [`attribute_filter`](https://docs.mixpeek.com/docs/retrieve/stages#attribute-filter) and asks Gemini for structured output with [`llm_enrich`](https://docs.mixpeek.com/docs/retrieve/stages#llm-enrich).

`label-articles` returns `iab_categories`, `entities` and `keywords` with the same instructions as `video-scenes`' `response_shape`, plus `sentiment` and `brand_safety`. `label-scenes` returns only `sentiment` and `brand_safety`, and `include_media: true` sends the segment's clip with the prompt. Add both to `retrievers`:

```yaml contextual-video-match.namespace.yaml: label retrievers theme={null}
  - name: label-articles
    namespace: contextual-video-match
    description: "Labels one article document with IAB categories, entities, keywords, sentiment and a brand-safety rating. Run by article-text's retriever enrichment on every new document."
    collections:
      - article-text
    input_schema:
      document_id:
        type: string
        required: true
        description: "The article-text document to label"
    stages:
      - stage_name: this_document
        stage_id: attribute_filter
        parameters:
          field: document_id
          operator: eq
          value: "{{INPUT.document_id}}"
      - stage_name: label
        stage_id: llm_enrich
        parameters:
          provider: google
          prompt: "Label this news article for contextual video advertising. Article text: {{DOC.text}}"
          output_field: labels
          output_schema:
            type: object
            properties:
              iab_categories:
                type: array
                items: {type: string}
                description: "IAB Content Taxonomy tier-1 category names that describe the article, written exactly as IAB names them, for example \"News & Politics\", \"Sports\". 1-3 items."
              entities:
                type: array
                items: {type: string}
                description: "Named people, organizations and places in canonical English form, deduplicated. 3-10 items."
              keywords:
                type: array
                items: {type: string}
                description: "Topical keywords or short phrases describing what the article is about. 3-8 items."
              sentiment:
                type: string
                enum: [positive, neutral, negative]
              brand_safety:
                type: string
                enum: [safe, sensitive, unsafe]
                description: "safe: suits any advertiser. sensitive: news of conflict, crime, disaster or death, reported without graphic detail. unsafe: graphic violence, adult content, hate speech or other material no advertiser should appear beside."
    tags:
      - template:contextual-video-match
  - name: label-scenes
    namespace: contextual-video-match
    description: "Rates one video segment's sentiment and brand safety from its frames, speech and on-screen text. Run by video-scenes' retriever enrichment on every new document."
    collections:
      - video-scenes
    input_schema:
      document_id:
        type: string
        required: true
        description: "The video-scenes document to label"
    stages:
      - stage_name: this_document
        stage_id: attribute_filter
        parameters:
          field: document_id
          operator: eq
          value: "{{INPUT.document_id}}"
      - stage_name: label
        stage_id: llm_enrich
        parameters:
          provider: google
          include_media: true
          prompt: "Rate this video segment for contextual video advertising, from what it shows and says. Transcript: {{DOC.transcription}} On-screen text: {{DOC.ocr_text}}"
          output_field: labels
          output_schema:
            type: object
            properties:
              sentiment:
                type: string
                enum: [positive, neutral, negative]
              brand_safety:
                type: string
                enum: [safe, sensitive, unsafe]
                description: "safe: suits any advertiser. sensitive: news of conflict, crime, disaster or death, shown without graphic detail. unsafe: graphic violence, adult content, hate speech or other material no advertiser should appear beside."
    tags:
      - template:contextual-video-match
```

Then attach each to its collection. `retriever_enrichments` sits beside `source` and `feature_extractor`. Add this to `video-scenes`:

```yaml contextual-video-match.namespace.yaml: video-scenes enrichment theme={null}
    retriever_enrichments:
      - retriever_id: label-scenes
        input_mappings:
          - input_key: document_id
            source: {source_type: document_field, path: document_id}
        write_back_fields:
          - {source_field: labels.sentiment, target_field: sentiment, mode: first}
          - {source_field: labels.brand_safety, target_field: brand_safety, mode: first}
```

And this one to `article-text`:

```yaml contextual-video-match.namespace.yaml: article-text enrichment theme={null}
    retriever_enrichments:
      - retriever_id: label-articles
        input_mappings:
          - input_key: document_id
            source: {source_type: document_field, path: document_id}
        write_back_fields:
          - {source_field: labels.iab_categories, target_field: iab_categories, mode: first}
          - {source_field: labels.entities, target_field: entities, mode: first}
          - {source_field: labels.keywords, target_field: keywords, mode: first}
          - {source_field: labels.sentiment, target_field: sentiment, mode: first}
          - {source_field: labels.brand_safety, target_field: brand_safety, mode: first}
```

`retriever_id` takes the retriever's name, and apply resolves it to the id.

> [!NOTE]
>
> An enrichment runs only on documents written after it is attached, so the sample documents carry no `brand_safety` and `playlist` leaves them out. To label existing documents, run their objects again in a batch with `dedup_strategy: replace`, which charges the extraction again; see [Reprocess existing content](https://docs.mixpeek.com/docs/templates/reprocess-existing-content.md).

### 4. Add the playlist retriever

`playlist` takes an article and returns up to 5 segments the publisher may show, best first. It searches only `video-scenes`, which carries the brand-safety and rights fields:

```yaml contextual-video-match.namespace.yaml: the playlist retriever theme={null}
  - name: playlist
    namespace: contextual-video-match
    description: "Takes an article and returns up to 5 brand-safe video segments the publisher may show, ranked by contextual score."
    collections:
      - video-scenes
      - article-multimodal
    input_schema:
      article_multimodal_doc_id:
        type: string
        required: true
        description: "Document id of the article in article-multimodal, whose stored vector the video segments are matched against"
      publisher_id:
        type: string
        required: true
        description: "The publisher whose page the player is on; its own videos and the shared library are eligible"
      article_entities:
        type: array
        required: false
        description: "The article's entities, read from its article-text document"
      article_keywords:
        type: array
        required: false
        description: "The article's keywords, read from its article-text document"
      article_iab_categories:
        type: array
        required: false
        description: "The article's IAB categories, read from its article-text document"
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://multimodal_extractor@v1/vertex_multimodal_embedding"
              collection_identifiers:
                - video-scenes
              query:
                input_mode: document
                document_ref:
                  collection_id: article-multimodal
                  document_id: "{{INPUT.article_multimodal_doc_id}}"
              top_k: 100
              filters:
                AND:
                  - field: brand_safety
                    operator: in
                    value: [safe, sensitive]
                  - OR:
                      - field: publisher_id
                        operator: eq
                        value: "{{INPUT.publisher_id}}"
                      - field: is_shared
                        operator: eq
                        value: "true"
          final_top_k: 100
      - stage_name: one_per_video
        stage_id: deduplicate
        parameters:
          strategy: field
          fields:
            - source_video_url
          keep: first
      - stage_name: score
        stage_id: code_execution
        parameters:
          language: python
          output_field: scoring
          timeout_ms: 5000
          code: |
            _ae = {{ INPUT.article_entities }}
            _ak = {{ INPUT.article_keywords }}
            _ac = {{ INPUT.article_iab_categories }}
            art_ents = set(str(e).lower() for e in (_ae or []))
            art_kws = set(str(k).lower() for k in (_ak or []))
            art_cats = set(str(c).lower() for c in (_ac or []))
            result = []
            for doc in docs:
                ve = set(str(e).lower() for e in doc.get('entities', []))
                vk = set(str(k).lower() for k in doc.get('keywords', []))
                vc = set(str(c).lower() for c in doc.get('iab_categories', []))
                vt = ((doc.get('transcription') or '') + ' ' + (doc.get('ocr_text') or '')).lower()
                te = set(e for e in art_ents if e in vt)
                all_ents = (art_ents & ve) | te
                eo = len(all_ents) / max(len(art_ents), 1) if art_ents else 0
                ko = len(art_kws & vk) / max(len(art_kws), 1) if art_kws else 0
                to = len(art_cats & vc) / max(len(art_cats), 1) if art_cats else 0
                s = doc.get('scores', {}).get('search', doc.get('score', 0))
                cs = 0.50 * s + 0.25 * min(eo * 1.5, 1.0) + 0.15 * min(ko * 1.5, 1.0) + 0.10 * to
                tp = 0.7 if vc and vc & {'entertainment', 'arts & entertainment'} and art_cats & {'news & politics', 'law government & politics'} else 1.0
                cs *= tp
                result.append({'contextual_score': round(cs, 4), 'entity_overlap': round(eo, 4), 'keyword_overlap': round(ko, 4), 'taxonomy_overlap': round(to, 4), 'entities_matched': list(all_ents)[:5], 'keywords_matched': list(art_kws & vk)[:5], 'iab_matched': list(art_cats & vc)[:3], 'taxonomy_penalty': tp})
      - stage_name: rank
        stage_id: sort_attribute
        parameters:
          field: scoring.contextual_score
          direction: desc
      - stage_name: top5
        stage_id: limit
        parameters:
          limit: 5
    tags:
      - template:contextual-video-match
```

The search filter runs inside the vector search, so `top_k: 100` counts only segments that pass it; `brand_safety` `in [safe, sensitive]` also drops unlabeled segments. A segment qualifies when it belongs to the publisher or `is_shared` is `"true"`. `one_per_video` keeps the best segment of each video, and `rank` sorts on the `score` stage's result.

Now apply the file with `?mode=upsert`. It creates the new resources and adds bucket properties, appended `field_passthrough` entries and payload indexes; `create_missing` would skip those. A changed `parameters` block on a collection that holds documents is refused and named in `refused`.

### 5. Send articles and look them up

Write each article to `articles` when it is published, with plain text (no page markup) in `content`:

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/buckets/articles/objects?auto_process=true" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "blobs": [{"property": "content", "type": "text", "data": "The council voted 7 to 2 on Tuesday to approve the new stadium on the east waterfront. Construction starts in March."}],
    "article_id": "a_5521",
    "title": "City council approves new stadium",
    "publisher_id": "pub_123",
    "article_url": "https://news.example.com/2026/12/stadium-approved",
    "published_at": "2026-12-01T09:30:00Z",
    "idempotency_key": "article-a_5521"
  }'
```

When the batch has finished, read the article's two documents by `article_id` and store what the player needs in your CMS. One lookup per article is enough:

```bash cURL theme={null}
FILTER='{"filters": {"AND": [{"field": "article_id", "operator": "eq", "value": "a_5521"}]}}'
curl -s -X POST https://api.mixpeek.com/v1/collections/article-text/documents/list \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" -d "$FILTER" \
  | jq '.results[0] | {entities, keywords, iab_categories, sentiment, brand_safety}'
curl -s -X POST https://api.mixpeek.com/v1/collections/article-multimodal/documents/list \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" -d "$FILTER" \
  | jq -r '.results[0].document_id'
```

A player can skip video on an `unsafe` article altogether.

### 6. Call the playlist from the player, behind a flag

The player runs `playlist` with the stored article fields and the publisher's id; excluded channels go in `filters`. Fall back to your current playlist when the flag is off, the call fails, the run is `degraded`, or too few videos come back.

```javascript player.js theme={null}
async function playlistFor(article, publisher, fallback) {
  if (!flags.mixpeekPlaylist) return fallback;
  const body = {
    inputs: {
      article_multimodal_doc_id: article.mixpeekMultimodalDocId,
      publisher_id: publisher.id,
      article_entities: article.entities,
      article_keywords: article.keywords,
      article_iab_categories: article.iabCategories,
    },
  };
  if (publisher.excludedChannels.length > 0) {
    body.filters = { AND: [{ field: "channel_id", operator: "nin", value: publisher.excludedChannels }] };
  }
  try {
    const res = await fetch("https://api.mixpeek.com/v1/retrievers/playlist/execute", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${MIXPEEK_API_KEY}`,
        "X-Namespace": MIXPEEK_NAMESPACE_ID,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(800),
    });
    if (!res.ok) return fallback;
    const run = await res.json();
    if (run.status !== "completed" || run.documents.length < 3) return fallback;
    return { videos: run.documents, executionId: run.execution_id, retrieverId: run.retriever_id };
  } catch {
    return fallback;
  }
}
```

Keep the API key on your server by running `playlistFor` in your own endpoint. To test the call by hand:

```bash cURL theme={null}
curl -s -X POST https://api.mixpeek.com/v1/retrievers/playlist/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {"article_multimodal_doc_id": "'"$MM_DOC"'", "publisher_id": "pub_123",
               "article_entities": ["City Council"], "article_keywords": ["stadium"],
               "article_iab_categories": ["News & Politics"]},
    "filters": {"AND": [{"field": "channel_id", "operator": "nin", "value": ["ch_gossip"]}]}
  }' \
  | jq '{status, warnings, execution_id, documents: [.documents[] | {document_id, title, start_time, contextual_score: .scoring.contextual_score}]}'
```

### 7. Send viewer events back

Record each video's outcome as an [interaction](https://docs.mixpeek.com/docs/retrieve/relevance.md) with the run's `execution_id` and `retriever_id`: `impression`, `play`, `long_view` or `skip`, and editors' verdicts as `positive_feedback` or `negative_feedback`. `feature_id` is the segment's `document_id`, and `position` its place in the playlist, from 0.

```bash cURL theme={null}
curl -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 '{"feature_id": "'"$DOCUMENT_ID"'", "interaction_type": ["impression"], "position": 0,
       "execution_id": "'"$EXECUTION_ID"'", "retriever_id": "'"$RETRIEVER_ID"'", "session_id": "view_77"}'
```

Buffered events go up to 1,000 per call to `POST /v1/retrievers/interactions/batch`. They land in your namespace's [system collections](https://docs.mixpeek.com/docs/manage/vector-store.md), where you can build an evaluation set and test ranking changes against real viewing.

## Next steps

> [card] [Retriever enrichments](https://docs.mixpeek.com/docs/enrich/taxonomies.md)
>
> How a retriever labels each new document and writes fields back.

> [card] [Filters](https://docs.mixpeek.com/docs/retrieve/retrievers.md)
>
> Every operator for rights, recency and brand-safety rules.


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