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

# Custom extractors and models

> Build your own extractor or load your own model weights, test it offline, ship it, and use it as a custom feature in a collection.

Package your own processing code as an extractor, test it on your machine, and run it as a `custom:<name>` feature on a [collection](https://docs.mixpeek.com/docs/extract/collections.md), with its vectors searchable by a retriever.

## Prerequisites

Where an extractor can run decides how you ship it:

| Capability | Shared API (`api.mixpeek.com`) | Dedicated deployment |
| - | - | - |
| Write, `lint` and `test` an extractor offline | Yes, no API key | Yes |
| Submit an extractor for review into the built-in catalog | Yes | Yes |
| One-file YAML extractor that swaps the model of a built-in | Yes | Yes |
| Publish to or install from the public extractor marketplace | Enterprise tier | Enterprise tier |
| Upload model weights to the model registry | Any paid plan (Build, Scale, Enterprise) | Any paid plan |
| Upload, deploy and serve your own code (`/v1/namespaces/{namespace_id}/plugins`) | No: returns `403` with type `DedicatedInfrastructureRequired` | Yes |

[Contact your account team](https://mixpeek.com/contact) to provision a dedicated deployment. On a single-tenant deployment or the standalone container you can also ship an extractor as a container image declared in a [manifest](https://docs.mixpeek.com/docs/manage/manifests.md).

## Build and ship an extractor

**1. Lay out the extractor**

```text Layout theme={null}
my_extractor/
├── manifest.py      # input, output and parameter schemas, vector indexes
├── pipeline.py      # batch pipeline steps
├── realtime.py      # query-time endpoint (optional)
└── processors/
    └── core.py      # your model and logic
```

**2. Declare the manifest**

The manifest is the contract with the platform: what the extractor reads, what it writes and which vector indexes to create.

```python manifest.py theme={null}
from typing import List

from pydantic import BaseModel, Field


class MyInput(BaseModel):
    text: str = Field(..., description="Input text to process")


class MyOutput(BaseModel):
    my_embedding: List[float] = Field(..., description="384-dim embedding vector")


class MyParams(BaseModel):
    model_size: str = Field(default="base", description="base or large")


metadata = {
    "feature_extractor_name": "my_extractor",
    "version": "1.0.0",
    "description": "Custom text embedding extractor",
    "category": "text",
    "inference_type": "embedding",
}

input_schema = MyInput
output_schema = MyOutput
parameter_schema = MyParams
supported_input_types = ["text"]

features = [
    {
        "feature_type": "embedding",
        "feature_name": "my_embedding",
        "embedding_dim": 384,
        "distance_metric": "cosine",
    },
]
```

> [!WARNING]
>
> Each `features` entry needs exactly the keys `feature_type` (`"embedding"`), `feature_name`, `embedding_dim` and `distance_metric` (`"cosine"`, `"euclid"` or `"dot"`). With `type`, `name`, `dimensions` or `distance` instead, the collection gets no vector index and the batch reports `COMPLETED` with 0 documents.

The vectors land at the feature URI `mixpeek://my_extractor@1.0.0/my_embedding`.

**3. Write the batch processor**

Your processor receives a pandas DataFrame and returns it with new columns, one per `feature_name`. Read the content from the `data` column: raw text for text blobs, an S3 URL for images, video and audio. Make one batched model call per batch.

```python processors/core.py theme={null}
import pandas as pd


class MyProcessor:
    def __init__(self, config, **kwargs):
        self.config = config
        self._model = None

    def __call__(self, batch: pd.DataFrame) -> pd.DataFrame:
        if self._model is None:
            from sentence_transformers import SentenceTransformer

            self._model = SentenceTransformer("all-MiniLM-L6-v2")
        texts = batch["data"].fillna("").tolist()
        batch["my_embedding"] = self._model.encode(texts).tolist()
        return batch
```

`pipeline.py` wires the processor into Ray Data as one or more `StepDefinition`s, each with a `resource_type` (CPU or GPU) and an optional row condition such as `RowCondition.IS_IMAGE`. A step can reuse a served model, for example `get_batch_service("intfloat/multilingual-e5-large-instruct")`, instead of loading its own.

**4. Add a query-time endpoint (optional)**

`realtime.py` lets a `feature_search` stage embed the query with the same model you indexed with. It must return an `embedding` key. A `feature_search` stage sends the query as `{"files": ["..."]}`; `POST /v1/inference` sends your inputs as given.

```python realtime.py theme={null}
from shared.plugins import BaseInferenceService


class InferenceService(BaseInferenceService):
    def __init__(self):
        super().__init__()
        self._model = None

    async def run_inference(self, inputs: dict, parameters: dict) -> dict:
        if self._model is None:
            from sentence_transformers import SentenceTransformer

            self._model = SentenceTransformer("all-MiniLM-L6-v2")
        text = inputs.get("text") or (inputs.get("files") or [""])[0]
        return {"embedding": self._model.encode([text])[0].tolist()}
```

The real-time endpoint serves on a dedicated deployment. Leave out both `realtime.py` and any `feature_uri` in the manifest for a batch-only extractor.

**5. Lint and test offline**

```bash Shell theme={null}
python plugins.py lint my_extractor
python plugins.py test my_extractor
```

`lint` validates the manifest, catches wrong `features` keys and runs the security scanner. `test` runs your processor through Ray Data `map_batches` with Arrow, feeding sample rows in the `data` column as production does, and checks your output columns against the manifest. Neither needs an API key.

**6. Ship it**

Pick the path that fits your deployment:

* **Dedicated deployment:** `python plugins.py push` uploads a version and `deploy` serves it. The CLI reads `MIXPEEK_API_KEY`, `MIXPEEK_NAMESPACE` and `MIXPEEK_API_URL`.
* **Submit for review:** upload the zip through submissions, below. Mixpeek reviews it and, once approved, it joins the built-in catalog for every organization.
* **Marketplace (Enterprise):** publish a submission that passed its scan so other organizations can install a copy.

**7. Use it in a collection**

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/collections" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "collection_name": "filings",
    "source": { "type": "bucket", "bucket_ids": ["'"$BUCKET_ID"'"] },
    "features": ["custom:my_extractor"]
  }'
```

Use `feature_extractor` with `"feature_extractor_name": "my_extractor"` and `"version": "1.0.0"` when you need your own `input_mappings` or parameters. A custom feature is priced per unit from the compute profile it declares; quote it first with the cost estimate in [Limits and billing](https://docs.mixpeek.com/docs/production/limits-and-billing.md).

### Submit an extractor for review

```bash cURL theme={null}
zip -r my_extractor.zip my_extractor/

UPLOAD=$(curl -s -X POST "https://api.mixpeek.com/v1/extractors/submissions/uploads" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "my_extractor", "version": "1.0.0", "description": "Custom text embedding extractor", "file_name": "my_extractor.zip"}')
SUBMISSION_ID=$(echo "$UPLOAD" | jq -r '.submission_id')
PRESIGNED_URL=$(echo "$UPLOAD" | jq -r '.presigned_url')

curl -X PUT "$PRESIGNED_URL" -H "Content-Type: application/zip" --data-binary @my_extractor.zip

curl -X POST "https://api.mixpeek.com/v1/extractors/submissions/uploads/$SUBMISSION_ID/confirm" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'
```

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

API = "https://api.mixpeek.com/v1/extractors/submissions"
headers = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}"}

upload = requests.post(
    f"{API}/uploads",
    headers=headers,
    json={"name": "my_extractor", "version": "1.0.0", "file_name": "my_extractor.zip"},
).json()

with open("my_extractor.zip", "rb") as f:
    requests.put(upload["presigned_url"], data=f, headers={"Content-Type": "application/zip"})

result = requests.post(
    f"{API}/uploads/{upload['submission_id']}/confirm", headers=headers, json={}
).json()
print(result["status"], result.get("security_violations"))
```

```javascript JavaScript theme={null}
import { readFileSync } from "node:fs";

const API = "https://api.mixpeek.com/v1/extractors/submissions";
const headers = {
  Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}`,
  "Content-Type": "application/json",
};

const upload = await fetch(`${API}/uploads`, {
  method: "POST",
  headers,
  body: JSON.stringify({ name: "my_extractor", version: "1.0.0", file_name: "my_extractor.zip" }),
}).then((r) => r.json());

await fetch(upload.presigned_url, {
  method: "PUT",
  headers: { "Content-Type": "application/zip" },
  body: readFileSync("my_extractor.zip"),
});

const result = await fetch(`${API}/uploads/${upload.submission_id}/confirm`, {
  method: "POST",
  headers,
  body: "{}",
}).then((r) => r.json());
console.log(result.status, result.security_violations);
```

The presigned URL is valid for one hour. Confirm scans the code and checks the manifest, then sets `status` to `review` when the scan passes or `rejected` when it fails, with `security_violations` naming file and line.

### Swap the model of a built-in with one YAML file

A zip that holds a single YAML manifest configures a built-in extractor and ships no code. It names the base with `extends` and points the vector index at another embedding model, including one your organization uploaded (`org:<model_id>`). Submit it the same way; confirm sets it to `validating`, and a validation job runs one sample inference and deploys it. Call it with `POST /v1/inference`.

```yaml extractor.yaml theme={null}
name: brand_text
version: v1
extends: text_extractor/v1
output:
  vector_index:
    model: org:mdl_7f3a9c
    dimensions: 384
```

`dimensions` must match the length the model returns, or validation rejects the extractor with the traceback. The base must embed with a model Mixpeek serves, such as `text_extractor/v1` or `image_extractor/v1`; a base that calls an external embedding API, such as `multimodal_extractor/v1`, is refused at confirm.

### Publish to the extractor marketplace

On the Enterprise tier, `POST /v1/extractors/{extractor_id}/publish` lists a submission that passed its scan (status `review` or `approved`) under a `public_name`, up to 10 per organization. Anyone can browse listings with `GET /v1/public/extractors/` and no API key. `POST /v1/extractors/install` with a `public_name` copies a listing into your organization, scans it again, saves it as an `approved` submission and returns the `feature_uri` to use. See [Publish extractor](https://docs.mixpeek.com/docs/api-reference/extractor-publishing/publish-extractor-marketplace.md) and [Install public extractor](https://docs.mixpeek.com/docs/api-reference/extractor-publishing/install-public-extractor.md).

## Load your own model weights

An extractor can load any public HuggingFace model, or weights your organization uploads. Uploaded weights work on every paid plan (Build, Scale and Enterprise; the free tier gets a `403` naming the build tier), and running them inside your own extractor needs a dedicated deployment or the YAML path above.

**1. Upload the weights**

```bash cURL theme={null}
tar -czvf my_model.tar.gz ./model_weights/

curl -X POST "https://api.mixpeek.com/v1/namespaces/$NAMESPACE_ID/models" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -F "file=@my_model.tar.gz" \
  -F "name=my_embedding_model" \
  -F "version=1.0.0" \
  -F "model_format=safetensors" \
  -F "task_type=embedding"
```

Formats are `safetensors`, `onnx`, `pytorch` and `huggingface`. A name is 3 to 64 letters, digits or underscores and starts with a letter. The model joins your organization's registry, so it keeps one `model_id` in every namespace. For large archives, use the presigned flow at [Generate presigned URL for model upload](https://docs.mixpeek.com/docs/api-reference/models/generate-presigned-url-for-model-upload.md).

**2. Deploy it**

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/namespaces/$NAMESPACE_ID/models/$MODEL_ID/deploy" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY"
```

**3. Load it in your processor**

`LazyModelMixin` loads the model on the first batch and shares it across workers through Ray's object store. Set `model_source = "namespace"` for uploaded weights, or `"huggingface"` with a HuggingFace model id.

```python processors/core.py theme={null}
from engine.inference.services import BaseBatchInferenceService
from engine.models.lazy import LazyModelMixin


class MyCustomProcessor(LazyModelMixin, BaseBatchInferenceService):
    model_id = "my_embedding_model_1_0_0"
    model_source = "namespace"

    def _instantiate_model(self, weights):
        import torch

        model = torch.nn.Linear(768, 256)
        model.load_state_dict(weights)
        model.to(self._detect_device())
        model.eval()
        return model, None
```

Other attributes: `model_class` (default `AutoModel`), `tokenizer_class` (`AutoTokenizer`, or `None`), `torch_dtype` (`float32`, `float16` or `bfloat16`). `self.get_model()` returns `(model, tokenizer)`.

An organization holds up to 50 models, each archive up to 5 GB. Deploy a new version next to the old one; the extractor version in the feature URI changes with it, so both can run while you compare.

## Check that it worked

* `GET /v1/extractors/submissions/{submission_id}` shows `status`, `security_scan_passed`, `manifest_valid` and any `rejection_reason`.
* After a batch, `GET /v1/collections/{collection_id}` should list your index in `vector_indexes` with its `feature_uri`. An empty list means the manifest's `features` keys are wrong.
* Run a retriever with a `feature_search` stage on that feature URI and confirm documents come back. See [Retrievers](https://docs.mixpeek.com/docs/retrieve/retrievers.md).

## What goes wrong

> [accordion] Upload or deploy returns 403 DedicatedInfrastructureRequired
>
> The shared API does not serve `/v1/namespaces/{namespace_id}/plugins`. Develop and test offline, then submit for review, use the YAML path, or provision a dedicated deployment.

> [accordion] Task COMPLETED with 0 documents
>
> Wrong `features` keys in `manifest.py` leave the collection with no vector index; run `lint`. The other common cause is reading a column named after your bucket field instead of `batch["data"]`. Look for `[FailureAggregator]` lines in the Ray logs.

> [accordion] Confirm returns rejected
>
> The scanner blocks `subprocess`, `os.system`, `os.popen`, `os.exec*`, `eval`, `exec`, `ctypes`, `socket`, `multiprocessing`, `open`, `setattr` and `delattr` in your source. `import os` is allowed, and library file I/O such as `torch.load` or `pd.read_csv` is fine. Call `ffmpeg`, `ffprobe`, ImageMagick, `exiftool`, `mediainfo`, `sox`, `REDline` or `art-cmd` through `run_tool` from `shared.extractors.sdk`. Use `json.loads` in place of `eval`.

> [accordion] First run is slow, or the first search returns nothing
>
> On a cold engine the model loads on demand: the first batch can stay in `PROCESSING` for minutes, and the first retriever call can return 0 documents while the query-side model warms. Retry after a few seconds. Call `prefetch_hf_model()` in `setup()` to cut model download time.

> [accordion] feature\_search on your URI fails
>
> A manifest with a `feature_uri` needs a `realtime.py` to embed queries. Remove both for a batch-only extractor.

> [accordion] Archive and runtime limits
>
> A zip is up to 500 MB and 1,000 files; do not bundle model weights. Set `compute_profile = {"resource_type": "cpu", "batch_size": 32, "max_concurrency": 4}` for extractors that call an API or do no GPU work: skipping GPU allocation saves about 3 minutes of startup. For system packages or compiled binaries, set `container_image` in the manifest to an image built from the Mixpeek engine base image and pushed to your organization's Artifact Registry repository.

> [accordion] Serving settings for the real-time endpoint
>
> `compute_profile.serve` controls the Ray Serve app: `min_replicas` (default `0`, scales to zero), `max_replicas` (`1`), `idle_timeout_s` (`600`, 300 to 1800), `target_ongoing_requests` (`5`) and `placement` (`worker` or `head`). A floor above zero needs a `min_reason`.

> [accordion] Typed SDK
>
> `shared.extractors.sdk` offers `ExtractorManifest` and `Feature.embedding(name, dim)` for a validated manifest, `BatchProcessor` with `setup()` and `process()`, `InferenceService` with `setup()` and `infer()`, and helpers: `parallel_io`, `concurrent_api_calls`, `open_asset`, `download_asset`, `upload_asset`, `run_tool` and `prefetch_hf_model`. Inside a pipeline, `container.llm` calls platform LLMs with cost tracking and `container.secrets.get(name)` reads organization secrets.

## Related

* [Collections and features](https://docs.mixpeek.com/docs/extract/collections.md): use a custom feature and chain it with other collections
* [Extractors](https://docs.mixpeek.com/docs/extract/extractors.md): the built-in extractors and their parameters
* [Retriever stages](https://docs.mixpeek.com/docs/retrieve/stages.md): `feature_search` and the stages that call real-time endpoints
* [Manifests](https://docs.mixpeek.com/docs/manage/manifests.md): declare extractors and container images as code


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