chore(embeddings): update the embeddings server and release it as 1.1.0 (#6300)

* chore(embeddings): replace transformers with tokenizers and drop pip from the image

* chore(embeddings): fix the dev health check and docs, add a changelog entry

* chore(embeddings): port the dependency and threading updates from #6379

Brings over the changes from #6379 that this branch didn't have yet:

- onnxruntime 1.26.0, tokenizers 0.23.3, starlette 1.8.0 and uvicorn 0.54.0,
  plus huggingface_hub 2.2.0 and transformers 5.19.0 in the build stage.
- The model download is pinned to its current revision.
- Inference uses as many threads as the container's CPU limit, which
  EMBEDDINGS_NUM_THREADS overrides.
- Inference runs in a worker thread behind a lock, so /health answers during
  long batches.
- An empty texts list returns 400 instead of 500.
- Helm, its README, Cloudron and the README point to baserow/embeddings:1.1.0.

Co-authored-by: Bram Wiepjes <bramw@protonmail.com>

* chore(embeddings): address review feedback

- The build stage writes tokenizer.json with the 512-token truncation and
  per-batch padding, so app.py only loads it. The build stage uses the
  tokenizers library for this and no longer installs transformers.
- tokenizers is installed with --no-deps. Its only dependency,
  huggingface-hub, is used by from_pretrained, which the app never calls.
- The README's local run installs the image's packages, downloads the model
  with _download_model.py into EMBEDDINGS_MODEL_DIR (default /model), and
  its snippet posts texts instead of text.

* chore(embeddings): fix the issues found while verifying the image

- requirements.txt pins all 13 runtime packages and is installed with
  --no-deps, so rebuilds are reproducible. The builder no longer installs
  git, and the build fails if the app can't be imported.
- Requests are processed 8 texts at a time and limited to 256 texts and a
  1 MiB body, so a single request can't OOM-kill the container anymore.
- Inference holds a lock in its worker thread, and a queued request whose
  client has gone is skipped.
- Malformed input, including lone surrogates, returns 400 instead of 500.
- The app refuses to start with a tokenizer.json that doesn't truncate at
  512 tokens, or with EMBEDDINGS_NUM_THREADS below 1.
- _download_model.py can be re-run.
- The README, docs, Cloudron manifest and changelog match the code, and the
  Cloudron manifest gets a 1.5 GiB memory limit and the /health check.

* chore(embeddings): correct the response size per text in a comment

---------

Co-authored-by: Bram Wiepjes <bramw@protonmail.com>
This commit is contained in:
Davide SilvestriandBram Wiepjes authored and GitHub committed 2026-10-15 14:18:02 +02:00
1 parent 4ff953ed43
commit 7c3525dc1a
15 files changed
+313 -112

No files matched your search

+3
View File
@@ -99,6 +99,9 @@ venv/
.venv/
.profiles/
# Model downloaded by a local run of the embeddings server
embeddings/model/
# Media files
backend/media/
@@ -0,0 +1,14 @@
{
"type": "breaking_change",
"message": "Remove pip and requests from the embeddings image",
"issue_origin": "github",
"issue_number": null,
"domain": "core",
"bullet_points": [
"transformers is replaced by tokenizers",
"Health checks can't import requests anymore",
"Use python -m ensurepip --default-pip for pip",
"The image moves to Python 3.14 and Debian 13"
],
"created_at": "2026-10-14"
}
@@ -0,0 +1,14 @@
{
"type": "refactor",
"message": "Update and speed up the embeddings server",
"issue_origin": "github",
"issue_number": null,
"domain": "core",
"bullet_points": [
"Helm and Cloudron now use embeddings 1.1.0",
"Inference threads follow the CPU limit",
"Health checks answer during long requests",
"Large requests no longer run out of memory"
],
"created_at": "2026-10-14"
}
@@ -8,8 +8,8 @@
"contactEmail": "bram@baserow.io",
"tags": ["no-code", "nocode", "database", "data", "collaborate", "airtable"],
"version": "2.1.4",
"healthCheckPath": "/api/_health/",
"healthCheckPath": "/health",
"httpPort": 80,
"memoryLimit": 1000000,
"memoryLimit": 1610612736,
"manifestVersion": 2
}
+1 -1
View File
@@ -1,5 +1,5 @@
```
cloudron install -l embeddings.{YOUR_DOMAIN} --image baserow/embeddings:1.0.0
cloudron install -l embeddings.{YOUR_DOMAIN} --image baserow/embeddings:1.1.0
```
In the Baserow app in Cloudron do:
+1 -1
View File
@@ -519,7 +519,7 @@ caddy:
| --------------------------------------------------------------- | --------------------------------------------------------------- | -------------------------- |
| `baserow-embeddings.enabled` | Set to true to enable the Baserow Embeddings service. | `false` |
| `baserow-embeddings.image.repository` | Docker image repository for the Embeddings service. | `embeddings` |
| `baserow-embeddings.image.tag` | Docker image tag for the Embeddings service, which is versioned separately from Baserow. | `1.0.0` |
| `baserow-embeddings.image.tag` | Docker image tag for the Embeddings service, which is versioned separately from Baserow. | `1.1.0` |
| `baserow-embeddings.workingDir` | Working directory for the container, empty to use the image's own. | `""` |
| `baserow-embeddings.resources` | Resource requests and limits for the Embeddings service. | |
| `baserow-embeddings.autoscaling.enabled` | Enable autoscaling for the Embeddings service. | `false` |
+1 -1
View File
@@ -686,7 +686,7 @@ baserow-embeddings:
enabled: false
image:
repository: embeddings
tag: "1.0.0"
tag: "1.1.0"
workingDir: ""
resources:
requests:
+1 -1
View File
@@ -348,7 +348,7 @@ services:
"CMD",
"python",
"-c",
"import requests; requests.get('http://localhost/health').raise_for_status()",
"import urllib.request; urllib.request.urlopen('http://localhost/health', timeout=5)",
]
interval: 1m30s
timeout: 10s
+2 -2
View File
@@ -32,7 +32,7 @@ From inside the container:
./baserow sync_knowledge_base
```
This will schedule a task to import `website_export.csv` containing all the docs and generate the embeddings using the local service. Once completed, asking the assistant to search for docs should show "Exploring the knowledge base..." in the UI when the assistant uses the `search_docs` tool, and the answers should show sources from the docs.
This will schedule a task to import `website_export.csv` containing all the docs and generate the embeddings using the local service. Once completed, asking the assistant to search for docs should show "Exploring the knowledge base..." in the UI when the assistant uses the `search_user_docs` tool, and the answers should show sources from the docs.
## Troubleshooting
@@ -80,4 +80,4 @@ curl -X POST "$BASEROW_EMBEDDINGS_API_URL/embed" \
-d '{"texts": "test"}'
```
This command should return a vector of more than 500 numbers. If it doesn't, check that the embeddings container is running and healthy.
This command should return a vector of 384 numbers. If it doesn't, check that the embeddings container is running and healthy.
+1 -1
View File
@@ -182,7 +182,7 @@ service and point Baserow at it.
### Run the embeddings container
```bash
docker run -d --name baserow-embeddings -p 80:80 baserow/embeddings:latest
docker run -d --name baserow-embeddings -p 80:80 baserow/embeddings:1.1.0
```
### Point Baserow to it
+14 -13
View File
@@ -1,14 +1,10 @@
FROM python:3.14.8-slim-trixie AS builder
RUN apt-get update && apt-get install -y --no-install-recommends \
git && rm -rf /var/lib/apt/lists/*
WORKDIR /build
COPY _download_model.py .
COPY requirements.txt _download_model.py ./
RUN pip install --no-cache-dir \
huggingface_hub==0.31.0 \
transformers==4.53.0 && \
RUN pip install --no-cache-dir --root-user-action=ignore \
-c requirements.txt huggingface_hub==2.2.0 tokenizers && \
python _download_model.py && \
rm _download_model.py
@@ -16,15 +12,20 @@ FROM python:3.14.8-slim-trixie
COPY --from=builder /model /model
RUN pip install --no-cache-dir \
onnxruntime==1.24.1 \
transformers==4.53.0 \
starlette==0.48.0 \
uvicorn==0.37.0 && \
rm -rf /root/.cache
RUN apt-get update && apt-get upgrade -y && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
# Nothing installs packages at runtime, so pip only adds CVEs.
RUN pip install --no-cache-dir --root-user-action=ignore --no-deps \
-r requirements.txt && \
pip uninstall -y --root-user-action=ignore pip && \
rm -rf /root/.cache
COPY app.py .
# --no-deps can't catch a missing dependency, so fail the build instead of startup.
RUN python -B -c "import app"
EXPOSE 80
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "80"]
+62 -56
View File
@@ -1,6 +1,6 @@
# Baserow Embeddings Service
A lightweight, self-contained text embedding microservice for Baserow's AI Assistant features. This service provides fast sentence embeddings using an ONNX-optimized model.
A lightweight, self-contained text embedding microservice for Baserow's AI Assistant features. This service provides fast sentence embeddings using an ONNX export of the model.
## Overview
@@ -8,29 +8,28 @@ This service converts text into dense vector representations (embeddings) that c
- Semantic search and similarity matching
- Document retrieval for RAG (Retrieval-Augmented Generation)
- Finding relevant database rows based on natural language queries
- Clustering and classification tasks
## Model
**Model**: `sentence-transformers/all-MiniLM-L6-v2`
**Model**: `sentence-transformers/all-MiniLM-L6-v2`, from its ONNX export `optimum/all-MiniLM-L6-v2` at a pinned revision
- Embedding dimension: 384
- Texts are truncated at 512 tokens. Baserow's stored vectors were made this way, so changing the truncation or the model means re-embedding them.
- Optimized for semantic similarity tasks
- Converted to ONNX format for faster inference
- Compact size with good performance trade-off
## Architecture
The service uses a multi-stage Docker build:
1. **Builder stage**: Downloads the model and converts it to ONNX format
1. **Builder stage**: Downloads the ONNX model and configures its tokenizer
2. **Runtime stage**: Minimal Python image with only runtime dependencies
3. **Result**: Small, production-ready container (~500MB)
3. **Result**: Small, production-ready container (~380MB)
### Key Features
- **ONNX Runtime**: 2-3x faster inference compared to PyTorch
- **ONNX Runtime**: CPU inference without PyTorch
- **Mean pooling**: Converts token embeddings to sentence embeddings
- **L2 normalization**: Enables cosine similarity via dot product
- **Batch support**: Process multiple texts in a single request
@@ -41,7 +40,7 @@ The service uses a multi-stage Docker build:
### Run locally
```
docker run -p 8080:80 baserow/embeddings:1.0.0
docker run -p 127.0.0.1:8080:80 baserow/embeddings:1.1.0
```
### Build for publish
@@ -49,16 +48,32 @@ docker run -p 8080:80 baserow/embeddings:1.0.0
```
docker buildx build \
--platform linux/amd64,linux/arm64 \
-t baserow/embeddings:1.0.0 \
-t baserow/embeddings:1.1.0 \
-t baserow/embeddings:latest \
--push .
```
### Build and run from source
```bash
docker build -t baserow-embeddings .
docker run -p 127.0.0.1:8080:80 baserow-embeddings
```
The service will be available at `http://localhost:8080`.
### Configuration
| Environment variable | Description | Default |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `EMBEDDINGS_NUM_THREADS` | Number of CPU threads used for inference, as a positive integer. Requests are processed one at a time, using all threads. | The container's CPU limit rounded up, or all CPUs without a limit. |
| `EMBEDDINGS_MODEL_DIR` | Directory with the model files. Change it only to run the service outside Docker. | `/model` |
## API
### Endpoints
#### `POST http://localhost:8080/embed`
#### `POST /embed`
Generate embeddings for one or more texts.
@@ -86,6 +101,10 @@ or for batching:
}
```
Texts longer than 512 tokens are truncated.
**Errors:** `400` with an `error` message for invalid JSON, a missing `texts` field, a `texts` that isn't a string or a list of strings, an empty list or more than 256 texts, and `413` for a body over 1 MiB.
**Example:**
```bash
@@ -106,79 +125,66 @@ Health check endpoint.
}
```
## Building
```bash
docker build -t baserow-embeddings .
```
## Running
```bash
docker run -p 8080:80 baserow-embeddings
```
The service will be available at `http://localhost:8080`.
## Development
### Local Testing
```bash
# Install dependencies
pip install optimum[onnxruntime]==1.27.0 transformers==4.53.0 starlette==0.48.0 uvicorn==0.37.0
# From this directory, with Python 3.13 or newer (the image uses 3.14)
python3 -m venv .venv
source .venv/bin/activate
# Install the image's packages, plus huggingface_hub to download the model
pip install --no-deps -r requirements.txt
pip install -c requirements.txt huggingface_hub==2.2.0
# Download model
python -c "
from optimum.onnxruntime import ORTModelForFeatureExtraction
from transformers import AutoTokenizer
model = ORTModelForFeatureExtraction.from_pretrained('sentence-transformers/all-MiniLM-L6-v2', export=True)
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
model.save_pretrained('./model')
tokenizer.save_pretrained('./model')
"
export EMBEDDINGS_MODEL_DIR="$PWD/model"
python _download_model.py
# Run locally
uvicorn app:app --host 0.0.0.0 --port 8080
# Run locally, in a shell where EMBEDDINGS_MODEL_DIR is set
uvicorn app:app --host 127.0.0.1 --port 8080
```
### Testing the API
```python
import requests
import json
import urllib.request
response = requests.post('http://localhost:8080/embed', json={
'text': ['Hello world', 'How are you?']
})
request = urllib.request.Request(
"http://localhost:8080/embed",
data=json.dumps({"texts": ["Hello world", "How are you?"]}).encode(),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request) as response:
embeddings = json.load(response)["embeddings"]
embeddings = response.json()['embeddings']
print(f"Generated {len(embeddings)} embeddings of dimension {len(embeddings[0])}")
```
## Integration with Baserow
This service is used by Baserow's AI Assistant to:
Baserow's AI Assistant uses this service to search the Baserow documentation:
1. **Index database content**: Convert rows into searchable embeddings
2. **Semantic search**: Find relevant rows based on user questions
3. **Context retrieval**: Provide relevant data to the LLM for answering questions
The embeddings enable the assistant to understand the semantic meaning of user queries and match them with the most relevant database records, even when there's no exact keyword match.
1. **Indexing**: after migrations, or on demand with the `sync_knowledge_base` management command, Baserow splits the docs into chunks and stores their embeddings
2. **Search**: the assistant's `search_user_docs` tool embeds the user's question and finds the closest chunks, even without a keyword match
3. **Context**: the matching chunks are passed to the LLM to answer the question
## Performance
- **Inference time**: ~10-30ms per text on CPU
- **Batch processing**: More efficient for multiple texts
- **Memory usage**: ~200MB RAM
- **Throughput**: ~100-300 requests/second (CPU-dependent)
Measured on an Apple M2 Max with the Helm chart's limits of 1 CPU and 1.5 GiB:
- **Inference time**: about 6 ms for a short query and 75 ms for a 1,000-character text
- **Batch processing**: saves HTTP round trips, not CPU time. Each group of 8 texts is padded to its longest text, so mixing short and long texts costs extra CPU, about 50% more for 1,000-character docs chunks.
- **Memory usage**: about 150 MB idle, about 450 MB with 1,000-character texts and up to about 700 MB with texts at the 512-token limit, because requests are processed 8 texts at a time
- **Throughput**: about 150 short queries or 12 texts of 1,000 characters per second. Long texts scale with more CPUs, short queries much less.
## Dependencies
- Python 3.14
- optimum[onnxruntime] 1.27.0
- transformers 4.53.0
- starlette 0.48.0
- uvicorn 0.37.0
Python 3.14, with every runtime package pinned in [requirements.txt](requirements.txt), so rebuilds install exactly the same versions. `huggingface_hub` is only used in the build stage, to download the model.
To update a package, install the new versions of `numpy`, `onnxruntime`, `starlette` and `uvicorn` into a clean Python 3.14 environment, add `tokenizers` with `--no-deps`, and write the output of `pip freeze` below the comment at the top of `requirements.txt`. The build stage installs `huggingface_hub`, pinned in the Dockerfile and above, with `-c requirements.txt`, so check that it still installs. After a bump, compare a few vectors with the previous image.
## License
+28 -11
View File
@@ -1,27 +1,44 @@
#!/usr/bin/env python3
"""Download and convert the embedding model to ONNX format."""
"""Download the ONNX embedding model and configure its tokenizer."""
from huggingface_hub import snapshot_download
from transformers import AutoTokenizer
import json
import os
import shutil
from huggingface_hub import snapshot_download
from tokenizers import Tokenizer
MODEL_ID = "optimum/all-MiniLM-L6-v2"
OUTPUT_DIR = "/model"
# Pinned so rebuilding the image can never change the stored vectors.
MODEL_REVISION = "10244843eba3d9e479b27a4b81c94b56d8e9f4f2"
OUTPUT_DIR = os.environ.get("EMBEDDINGS_MODEL_DIR", "/model")
print(f"Downloading {MODEL_ID} from Hugging Face...")
local_dir = snapshot_download(repo_id=MODEL_ID, allow_patterns=["*.onnx", "*.json", "*.txt"])
print(f"Saving tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
os.makedirs(OUTPUT_DIR, exist_ok=True)
tokenizer.save_pretrained(OUTPUT_DIR)
local_dir = snapshot_download(
repo_id=MODEL_ID,
revision=MODEL_REVISION,
allow_patterns=["*.onnx", "*.json", "*.txt"],
)
print("Copying ONNX model files...")
os.makedirs(OUTPUT_DIR, exist_ok=True)
for item in os.listdir(local_dir):
src = os.path.join(local_dir, item)
dst = os.path.join(OUTPUT_DIR, item)
if os.path.isfile(src):
shutil.copy(src, dst)
# The cache's files are read-only, and copying that mode breaks re-runs.
shutil.copyfile(src, dst)
print("Configuring the tokenizer...")
with open(os.path.join(local_dir, "tokenizer_config.json")) as f:
tokenizer_config = json.load(f)
tokenizer = Tokenizer.from_file(os.path.join(local_dir, "tokenizer.json"))
# Override the file's 128-token settings to match how stored vectors were made.
tokenizer.enable_truncation(max_length=tokenizer_config["model_max_length"])
tokenizer.enable_padding(
pad_id=tokenizer.token_to_id(tokenizer_config["pad_token"]),
pad_token=tokenizer_config["pad_token"],
)
tokenizer.save(os.path.join(OUTPUT_DIR, "tokenizer.json"))
print("Done! ONNX model is ready at", OUTPUT_DIR)
+155 -23
View File
@@ -1,54 +1,186 @@
import asyncio
import json
import math
import os
import threading
import numpy as np
import onnxruntime as ort
from starlette.applications import Starlette
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
import onnxruntime as ort
from transformers import AutoTokenizer
import numpy as np
import os
from tokenizers import Tokenizer
# Load ONNX model directly
MODEL_DIR = "/model"
tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
MODEL_DIR = os.environ.get("EMBEDDINGS_MODEL_DIR", "/model")
# onnxruntime keeps the memory of its largest batch, so cap the batch size.
INFERENCE_BATCH_SIZE = 8
# The tokenizer reads whole texts before truncating them, so bound the input.
MAX_BODY_BYTES = 2**20
# Each text adds about 8 KB of JSON to the response.
MAX_TEXTS = 256
# Create inference session
tokenizer = Tokenizer.from_file(os.path.join(MODEL_DIR, "tokenizer.json"))
# A raw download truncates at 128 tokens, while the stored vectors used 512.
if not tokenizer.truncation or tokenizer.truncation["max_length"] != 512:
raise RuntimeError(f"Run _download_model.py to configure {MODEL_DIR}")
def read_cgroup_cpu_quota() -> tuple[int, int] | None:
try:
with open("/sys/fs/cgroup/cpu.max") as f:
quota, period = f.read().split()
return None if quota == "max" else (int(quota), int(period))
except (OSError, ValueError):
pass
# Older hosts still run cgroup v1, where -1 means unlimited.
try:
with open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us") as f:
quota = int(f.read())
with open("/sys/fs/cgroup/cpu/cpu.cfs_period_us") as f:
period = int(f.read())
return None if quota <= 0 else (quota, period)
except (OSError, ValueError):
return None
def default_num_threads() -> int:
# onnxruntime ignores the container CPU limit and would get throttled.
count = os.process_cpu_count() or 1
cpu_quota = read_cgroup_cpu_quota()
if cpu_quota:
quota, period = cpu_quota
count = min(count, max(1, math.ceil(quota / period)))
return count
def inference_threads() -> int:
value = os.environ.get("EMBEDDINGS_NUM_THREADS", "").strip()
if not value:
return default_num_threads()
if not value.isdecimal() or int(value) < 1:
raise ValueError("EMBEDDINGS_NUM_THREADS must be a positive integer")
return int(value)
session_options = ort.SessionOptions()
session_options.intra_op_num_threads = inference_threads()
model_path = os.path.join(MODEL_DIR, "model.onnx")
session = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
session = ort.InferenceSession(
model_path, session_options, providers=["CPUExecutionProvider"]
)
def mean_pooling(token_embeddings, attention_mask):
# Inference already uses every thread, so parallel requests would oversubscribe.
inference_lock = threading.Lock()
# Requests wait here, not in a thread, so ones whose client left can be skipped.
request_lock = asyncio.Lock()
def mean_pooling(
token_embeddings: np.ndarray, attention_mask: np.ndarray
) -> np.ndarray:
input_mask_expanded = np.expand_dims(attention_mask, -1)
input_mask_expanded = np.broadcast_to(input_mask_expanded, token_embeddings.shape).astype(float)
input_mask_expanded = np.broadcast_to(
input_mask_expanded, token_embeddings.shape
).astype(float)
sum_embeddings = np.sum(token_embeddings * input_mask_expanded, axis=1)
sum_mask = np.clip(np.sum(input_mask_expanded, axis=1), a_min=1e-9, a_max=None)
return sum_embeddings / sum_mask
async def embed(request):
def embed_batch(texts: list[str]) -> list[list[float]]:
encodings = tokenizer.encode_batch(texts)
ort_inputs = {
"input_ids": np.array([e.ids for e in encodings], dtype=np.int64),
"attention_mask": np.array(
[e.attention_mask for e in encodings], dtype=np.int64
),
"token_type_ids": np.array([e.type_ids for e in encodings], dtype=np.int64),
}
ort_outputs = session.run(None, ort_inputs)
token_embeddings = ort_outputs[0]
embeddings = mean_pooling(token_embeddings, ort_inputs["attention_mask"])
embeddings = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
return embeddings.tolist()
def compute_embeddings(texts: list[str]) -> list[list[float]]:
embeddings = []
with inference_lock:
for start in range(0, len(texts), INFERENCE_BATCH_SIZE):
embeddings.extend(embed_batch(texts[start : start + INFERENCE_BATCH_SIZE]))
return embeddings
def is_text(value: object) -> bool:
if not isinstance(value, str):
return False
try:
data = await request.json()
value.encode()
except UnicodeEncodeError:
# JSON allows lone surrogates, which the tokenizer can't encode.
return False
return True
async def read_body(request: Request) -> bytes | None:
"""Return the request body, or None when it's larger than MAX_BODY_BYTES."""
body = bytearray()
async for chunk in request.stream():
body += chunk
if len(body) > MAX_BODY_BYTES:
return None
return bytes(body)
async def embed(request: Request) -> JSONResponse:
try:
body = await read_body(request)
data = None if body is None else json.loads(body)
except Exception:
return JSONResponse({"error": "Invalid JSON"}, status_code=400)
if not data or "texts" not in data:
if body is None:
return JSONResponse({"error": "Request body over 1 MiB"}, status_code=413)
if not isinstance(data, dict) or "texts" not in data:
return JSONResponse({"error": "Missing texts field"}, status_code=400)
texts = data["texts"]
if isinstance(texts, str):
texts = [texts]
encoded = tokenizer(texts, padding=True, truncation=True, return_tensors="np")
ort_inputs = {k: v for k, v in encoded.items()}
if not isinstance(texts, list) or not all(is_text(text) for text in texts):
return JSONResponse(
{"error": "texts must be a string or a list of strings"}, status_code=400
)
# Run model
ort_outputs = session.run(None, ort_inputs)
token_embeddings = ort_outputs[0]
if not texts:
return JSONResponse({"error": "Empty texts field"}, status_code=400)
embeddings = mean_pooling(token_embeddings, encoded["attention_mask"])
embeddings = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
if len(texts) > MAX_TEXTS:
return JSONResponse(
{"error": f"At most {MAX_TEXTS} texts per request"}, status_code=400
)
return JSONResponse({"embeddings": embeddings.tolist()})
async with request_lock:
if await request.is_disconnected():
return JSONResponse({"error": "Client disconnected"}, status_code=499)
# Off the event loop, so health checks still answer during long requests.
embeddings = await run_in_threadpool(compute_embeddings, texts)
async def health(request):
return JSONResponse({"embeddings": embeddings})
async def health(request: Request) -> JSONResponse:
return JSONResponse({"status": "healthy"})
app = Starlette(
routes=[
Route("/embed", embed, methods=["POST"]),
+14
View File
@@ -0,0 +1,14 @@
# Installed with --no-deps: tokenizers' huggingface-hub is unused.
anyio==4.15.1
click==8.5.0
flatbuffers==25.12.19
h11==0.16.0
idna==3.20
numpy==2.5.4
onnxruntime==1.26.0
packaging==26.3
protobuf==7.36.2
starlette==1.8.0
tokenizers==0.23.3
typing_extensions==4.16.0
uvicorn==0.54.0