Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions harmony_api/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@
}

# Multilingual E5 served by the delosis-embedding-api container
# over HTTP (see services/delosis_e5_embeddings.py). Kept under the
# over HTTP (see services/delosis_embeddings.py). Kept under the
# "huggingface" framework because that is what the model is; it is simply not
# loaded in-process. Only advertised as available when the embedder URL is
# configured (HARMONY_E5_EMBEDDER_URL).
# loaded in-process. Only advertised as available when the embedding service is
# configured to serve it (HARMONY_EMBEDDER_URL, or HARMONY_E5_EMBEDDER_URL).
DELOSIS_E5_BASE = {
"framework": "huggingface",
"model": "intfloat/multilingual-e5-base",
Expand Down
20 changes: 18 additions & 2 deletions harmony_api/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,24 @@ class Settings(BaseSettings):
default=None
)
# Base URL (or full /text/embed URL) of the delosis-embedding-api
# container that serves intfloat/multilingual-e5-base. When unset the E5 model
# is listed but reported as unavailable, so stock deployments are unaffected.
# container, and which models it embeds for Harmony (see
# services/delosis_embeddings.py). When unset the E5 model is listed but
# reported as unavailable, and every Hugging Face model runs in-process, so
# stock deployments are unaffected.
HARMONY_EMBEDDER_URL: str | None = Field(
description="URL of the Delosis embedding service, e.g. http://delosis-embedding-api:8000",
default=None,
)
HARMONY_EMBEDDER_TOKEN: str | None = Field(
description="Optional bearer token for the Delosis embedding service.",
default=None,
)
HARMONY_EMBEDDER_MODELS: str | None = Field(
description="Models the Delosis embedding service serves, comma separated: e5, minilm. "
"Unset means E5 only, asked for without a model name.",
default=None,
)
# The earlier E5-only settings, still read when HARMONY_EMBEDDER_URL is unset.
HARMONY_E5_EMBEDDER_URL: str | None = Field(
description="URL of the Delosis E5 embedding service, e.g. http://delosis-embedding-api:8000",
default=None,
Expand Down
8 changes: 4 additions & 4 deletions harmony_api/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
)
from harmony_api.core.settings import get_settings
from harmony_api.services import azure_openai_embeddings
from harmony_api.services import delosis_e5_embeddings
from harmony_api.services import delosis_embeddings
from harmony_api.services import google_embeddings
from harmony_api.services import hugging_face_embeddings
from harmony_api.services import openai_embeddings
Expand Down Expand Up @@ -142,10 +142,10 @@ def check_model_availability(model: dict) -> bool:
"""

# E5 is served over HTTP, so it is only available when the
# embedder URL is configured. Checked before the generic Hugging Face
# Delosis embedding service is configured to serve it. Checked before the generic Hugging Face
# branch because it shares that framework name.
if model["model"] == DELOSIS_E5_BASE["model"]:
return delosis_e5_embeddings.is_configured()
return delosis_embeddings.is_configured()

# Hugging Face
if model["framework"] == "huggingface":
Expand Down Expand Up @@ -264,7 +264,7 @@ def get_vectorisation_function_for_model(model: dict) -> Callable | None:
model["framework"] == DELOSIS_E5_BASE["framework"]
and model["model"] == DELOSIS_E5_BASE["model"]
):
vectorisation_function = delosis_e5_embeddings.get_delosis_e5_embeddings
vectorisation_function = delosis_embeddings.get_delosis_e5_embeddings

elif (
model["framework"] == OPENAI_ADA_02["framework"]
Expand Down
100 changes: 0 additions & 100 deletions harmony_api/services/delosis_e5_embeddings.py

This file was deleted.

189 changes: 189 additions & 0 deletions harmony_api/services/delosis_embeddings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""
Embeddings from the Delosis embedding service (delosis-embedding-api) over HTTP.

The stock Harmony API loads its Hugging Face models in-process with
sentence-transformers. A deployment that runs the delosis-embedding-api
container beside it can instead have some models embedded there, which can
pass big batches on to a GPU machine:

- intfloat/multilingual-e5-base (768-d), which is never loaded in-process, so
it is only available when the service is configured;
- sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 (384-d), Harmony's
default model. When the service serves it, it is not loaded in-process at
start-up. If the service fails, it is loaded in-process and used instead
(see hugging_face_embeddings.py). The service's MiniLM vectors match the
in-process ones (cosine >= 0.9999999 on 498 MHC catalogue items, 2 Dec 2026).

Settings (all optional; with none of them nothing changes):

HARMONY_EMBEDDER_URL the service, e.g. http://delosis-embedding-api:8000
HARMONY_EMBEDDER_TOKEN optional bearer token
HARMONY_EMBEDDER_MODELS which models it serves, from REMOTE_MODELS below,
e.g. "e5,minilm"

HARMONY_E5_EMBEDDER_URL / _TOKEN, the earlier E5-only settings, still work: on
their own they mean E5 only, asked for without a model name, as before.

Vectors come back L2-normalised by the service. The in-process models return
unnormalised vectors; every comparison in harmony and harmony_api is cosine
similarity, so the two can be mixed (e.g. in the vectors cache).

E5 is an asymmetric model that expects a role prefix on every text. Item to
item matching is symmetric, so both sides get "query: ", the prefix the E5
model card recommends for symmetric tasks (STS, paraphrase, clustering).
Discovery's retrieval path uses "query: " / "passage: " instead; do not mix
the two conventions, the spaces are different. MiniLM takes no prefix.
"""

import time

import numpy as np
import requests

from harmony_api.constants import DELOSIS_E5_BASE, HUGGINGFACE_MINILM_L12_V2
from harmony_api.core.settings import get_settings

settings = get_settings()

# Models the service can embed for Harmony: the name the service knows each by,
# the prefix Harmony applies for symmetric item matching, and the dimension.
REMOTE_MODELS = {
"e5": {"model": DELOSIS_E5_BASE["model"], "prefix": "query: ", "dim": 768},
"minilm": {"model": HUGGINGFACE_MINILM_L12_V2["model"], "prefix": "", "dim": 384},
}

BATCH_SIZE = 256
TIMEOUT_SECONDS = 120
RETRIES = 3

_session = requests.Session()
_session.mount("http://", requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=8))
_session.mount("https://", requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=8))


def _setting(name: str) -> str:
return (getattr(settings, name, None) or "").strip()


def get_embed_url() -> str | None:
"""Accept either a base URL or a full endpoint URL (mirrors Discovery's client)."""
url = (_setting("HARMONY_EMBEDDER_URL") or _setting("HARMONY_E5_EMBEDDER_URL")).rstrip("/")
if not url:
return None
if "/text/" not in url:
url = f"{url}/text/embed"
return url


def _served_keys() -> tuple[set[str], bool]:
"""The REMOTE_MODELS keys the service serves, and whether to name the model
in each request (not with the E5-only settings, which never did)."""
if get_embed_url() is None:
return set(), False
listed = _setting("HARMONY_EMBEDDER_MODELS")
if not listed:
return {"e5"}, False
keys = {k.strip() for k in listed.split(",") if k.strip()}
unknown = keys - REMOTE_MODELS.keys()
if unknown:
raise ValueError(
f"HARMONY_EMBEDDER_MODELS names {sorted(unknown)}; "
f"the Delosis embedding service can serve {sorted(REMOTE_MODELS)}"
)
return keys, True


def _key_for(model_name: str) -> str | None:
for key, spec in REMOTE_MODELS.items():
if spec["model"] == model_name:
return key
return None


def is_served(model_name: str) -> bool:
"""Whether the service is configured to embed this Harmony model."""
key = _key_for(model_name)
return key is not None and key in _served_keys()[0]


def is_configured() -> bool:
"""Whether E5 is available (the service is configured and serves it)."""
return is_served(DELOSIS_E5_BASE["model"])


def get_embeddings(texts: list[str], model_name: str) -> np.ndarray:
"""
:param texts: List of texts.
:param model_name: The Harmony model name, one of REMOTE_MODELS.

Get embeddings for a model from the Delosis embedding service.
"""

if not texts:
return np.array([])

key = _key_for(model_name)
keys, name_the_model = _served_keys()
url = get_embed_url()
if url is None or key not in keys:
raise RuntimeError(f"The Delosis embedding service is not configured to serve {model_name}")
spec = REMOTE_MODELS[key]

headers = {}
token = _setting("HARMONY_EMBEDDER_TOKEN") or _setting("HARMONY_E5_EMBEDDER_TOKEN")
if token:
headers["Authorization"] = f"Bearer {token}"

vectors: list[list[float]] = []
for start in range(0, len(texts), BATCH_SIZE):
chunk = [spec["prefix"] + (t or "") for t in texts[start:start + BATCH_SIZE]]
# prefix="" tells the service not to add its own prefix on top of ours.
payload = {"texts": chunk, "prefix": ""}
if name_the_model:
payload["model"] = key
last_error: Exception | None = None
for attempt in range(RETRIES):
try:
response = _session.post(
url, json=payload, headers=headers, timeout=TIMEOUT_SECONDS
)
response.raise_for_status()
data = response.json()
# A service that predates model names ignores the field and
# answers with its default model (E5): never take that for MiniLM.
if name_the_model and data.get("model") != key:
raise RuntimeError(
f"Asked the embedding service for {key}, it answered with "
f"{data.get('model') or 'an unnamed model'}"
)
chunk_vectors = data.get("vectors") or data.get("embeddings")
if chunk_vectors is None or len(chunk_vectors) != len(chunk):
raise RuntimeError(
f"Embedding service returned {0 if chunk_vectors is None else len(chunk_vectors)} "
f"vectors for {len(chunk)} texts"
)
if any(len(v) != spec["dim"] for v in chunk_vectors):
raise RuntimeError(
f"Embedding service returned vectors that are not {spec['dim']}-d for {key}"
)
vectors.extend(chunk_vectors)
last_error = None
break
except (requests.ConnectionError, requests.Timeout, RuntimeError) as e:
last_error = e
if attempt < RETRIES - 1:
time.sleep(0.5 * (2 ** attempt))
if last_error is not None:
raise last_error

return np.asarray(vectors, dtype=np.float32)


def get_delosis_e5_embeddings(texts: list[str]) -> np.ndarray:
"""
:param texts: List of texts.

Get E5 embeddings from the Delosis embedding service.
"""

return get_embeddings(texts, DELOSIS_E5_BASE["model"])
Loading
Loading