From 001c8d61f599343760e6f05298392d6737a051a0 Mon Sep 17 00:00:00 2001 From: John Rogers Date: Wed, 2 Dec 2026 14:28:37 +0000 Subject: [PATCH] Embed MiniLM through the Delosis embedding service, beside E5 The Delosis embedding service (delosis-embedding-api 1.2.0) now serves several models from one container, Harmony's default MiniLM among them. A deployment can have it embed MiniLM as well as E5, so the API process no longer loads its own copy at start-up. - delosis_e5_embeddings.py becomes delosis_embeddings.py, a client for any model the service serves for Harmony (REMOTE_MODELS: e5, minilm). HARMONY_EMBEDDER_URL / _TOKEN / _MODELS configure it. The old HARMONY_E5_EMBEDDER_URL / _TOKEN still work and mean E5 only, asked for without a model name, as before. - Requests name the model, and a reply must name the same model and have its dimension: a service that predates model names answers with E5, which must never be taken for MiniLM. - hugging_face_embeddings.py loads at start-up only the models the service does not serve. If the service fails, MiniLM is loaded in-process on first use and used for 60 s before the service is tried again. That fallback normalises, so every MiniLM vector in a process has the service's unit scale (k-means and HDBSCAN use raw vectors; everything else is cosine). E5 has no in-process fallback. - With none of the settings, nothing changes. The service's MiniLM vectors match the in-process ones to cosine 0.9999999 on 498 MHC catalogue items (2 Dec 2026). Unit tests with a fake service and stand-in models: tests/unit_tests. Co-Authored-By: Claude Opus 5.5 --- harmony_api/constants.py | 6 +- harmony_api/core/settings.py | 20 +- harmony_api/helpers.py | 8 +- harmony_api/services/delosis_e5_embeddings.py | 100 -------- harmony_api/services/delosis_embeddings.py | 189 ++++++++++++++ .../services/hugging_face_embeddings.py | 89 +++++-- tests/unit_tests/test_delosis_embeddings.py | 231 ++++++++++++++++++ 7 files changed, 507 insertions(+), 136 deletions(-) delete mode 100644 harmony_api/services/delosis_e5_embeddings.py create mode 100644 harmony_api/services/delosis_embeddings.py create mode 100644 tests/unit_tests/test_delosis_embeddings.py diff --git a/harmony_api/constants.py b/harmony_api/constants.py index e3b3127..e1388ff 100644 --- a/harmony_api/constants.py +++ b/harmony_api/constants.py @@ -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", diff --git a/harmony_api/core/settings.py b/harmony_api/core/settings.py index 4b95b6e..ef5a6d7 100644 --- a/harmony_api/core/settings.py +++ b/harmony_api/core/settings.py @@ -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, diff --git a/harmony_api/helpers.py b/harmony_api/helpers.py index 82ee765..6752454 100644 --- a/harmony_api/helpers.py +++ b/harmony_api/helpers.py @@ -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 @@ -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": @@ -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"] diff --git a/harmony_api/services/delosis_e5_embeddings.py b/harmony_api/services/delosis_e5_embeddings.py deleted file mode 100644 index c6f5e92..0000000 --- a/harmony_api/services/delosis_e5_embeddings.py +++ /dev/null @@ -1,100 +0,0 @@ -""" -Multilingual E5 embeddings via the delosis-embedding-api service. - -The stock Harmony API loads its Hugging Face models in-process with -sentence-transformers. E5 is instead served by the delosis-embedding-api -container (intfloat/multilingual-e5-base, 768-d) that already backs Harmony -Discovery, so the API container gains a model without another ~1 GB of -weights or RAM. Same host, dedicated docker network (embedder-harmony). - -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. -""" - -import time - -import numpy as np -import requests - -from harmony_api.core.settings import get_settings - -settings = get_settings() - -QUERY_PREFIX = "query: " -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 get_embed_url() -> str | None: - """Accept either a base URL or a full endpoint URL (mirrors Discovery's client).""" - url = (settings.HARMONY_E5_EMBEDDER_URL or "").strip().rstrip("/") - if not url: - return None - if "/text/" not in url: - url = f"{url}/text/embed" - return url - - -def is_configured() -> bool: - return get_embed_url() is not None - - -def get_delosis_e5_embeddings(texts: list[str]) -> np.ndarray: - """ - :param texts: List of texts. - - Get E5 embeddings from the Delosis embedding service. Vectors come back - L2-normalised by the service, matching what sentence-transformers returns - for the in-process models, so the library's cosine maths is unchanged. - """ - - if not texts: - return np.array([]) - - url = get_embed_url() - if url is None: - raise RuntimeError("HARMONY_E5_EMBEDDER_URL is not configured") - - headers = {} - token = (settings.HARMONY_E5_EMBEDDER_TOKEN or "").strip() - if token: - headers["Authorization"] = f"Bearer {token}" - - vectors: list[list[float]] = [] - for start in range(0, len(texts), BATCH_SIZE): - chunk = [QUERY_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": ""} - 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() - 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" - ) - 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) diff --git a/harmony_api/services/delosis_embeddings.py b/harmony_api/services/delosis_embeddings.py new file mode 100644 index 0000000..9da9259 --- /dev/null +++ b/harmony_api/services/delosis_embeddings.py @@ -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"]) diff --git a/harmony_api/services/hugging_face_embeddings.py b/harmony_api/services/hugging_face_embeddings.py index 6e4f202..797a5a2 100644 --- a/harmony_api/services/hugging_face_embeddings.py +++ b/harmony_api/services/hugging_face_embeddings.py @@ -1,20 +1,51 @@ +import threading +import time + import numpy as np from sentence_transformers import SentenceTransformer from harmony_api.constants import HUGGINGFACE_MINILM_L12_V2, HUGGINGFACE_MPNET_BASE_V2, \ HUGGINGFACE_MENTAL_HEALTH_HARMONISATION_1 - -# Load Hugging Face sentence transformers +from harmony_api.services import delosis_embeddings + +HUGGING_FACE_MODEL_NAMES = [ + HUGGINGFACE_MINILM_L12_V2["model"], + HUGGINGFACE_MPNET_BASE_V2["model"], + HUGGINGFACE_MENTAL_HEALTH_HARMONISATION_1["model"], +] + +# After the Delosis embedding service fails, embed in-process for this long +# before trying it again, so requests don't each wait for its retries. +REMOTE_RETRY_AFTER_SECONDS = 60 + +_models: dict[str, SentenceTransformer] = {} +_load_lock = threading.Lock() +_remote_down_until: dict[str, float] = {} + + +def _get_model(model_name: str) -> SentenceTransformer: + """The in-process model, loaded on first use.""" + model = _models.get(model_name) + if model is None: + with _load_lock: + model = _models.get(model_name) + if model is None: + print(f"INFO:\t Loading Hugging Face model {model_name}...") + model = SentenceTransformer(model_name) + _models[model_name] = model + return model + + +# Load Hugging Face sentence transformers at start-up, except the ones the +# Delosis embedding service serves (see delosis_embeddings.py): those are only +# loaded here if the service fails. print("INFO:\t Checking Hugging Face models...") -model_huggingface_minilm_l12_v2 = SentenceTransformer( - HUGGINGFACE_MINILM_L12_V2["model"] -) -model_huggingface_mpnet_base_v2 = SentenceTransformer( - HUGGINGFACE_MPNET_BASE_V2["model"] -) -model_huggingface_mental_health_harmonisation = SentenceTransformer( - HUGGINGFACE_MENTAL_HEALTH_HARMONISATION_1["model"] -) +for _model_name in HUGGING_FACE_MODEL_NAMES: + if delosis_embeddings.is_served(_model_name): + print(f"INFO:\t {_model_name} is served by the Delosis embedding service") + else: + _get_model(_model_name) + def __get_hugging_face_embeddings(texts: list[str], model_name: str) -> np.ndarray: """ @@ -27,22 +58,26 @@ def __get_hugging_face_embeddings(texts: list[str], model_name: str) -> np.ndarr if not texts: return np.array([]) - embeddings = [] - - if model_name == HUGGINGFACE_MINILM_L12_V2["model"]: - embeddings = model_huggingface_minilm_l12_v2.encode( - sentences=texts, convert_to_numpy=True - ) - elif model_name == HUGGINGFACE_MPNET_BASE_V2["model"]: - embeddings = model_huggingface_mpnet_base_v2.encode( - sentences=texts, convert_to_numpy=True - ) - elif model_name == HUGGINGFACE_MENTAL_HEALTH_HARMONISATION_1["model"]: - embeddings = model_huggingface_mental_health_harmonisation.encode( - sentences=texts, convert_to_numpy=True - ) - - return embeddings + if model_name not in HUGGING_FACE_MODEL_NAMES: + return [] + + served = delosis_embeddings.is_served(model_name) + if served and time.monotonic() >= _remote_down_until.get(model_name, 0.0): + try: + return delosis_embeddings.get_embeddings(texts, model_name) + except Exception as e: + _remote_down_until[model_name] = time.monotonic() + REMOTE_RETRY_AFTER_SECONDS + print( + f"WARNING:\t Delosis embedding service failed for {model_name} ({e}); " + f"embedding in-process for {REMOTE_RETRY_AFTER_SECONDS} s" + ) + + # The service's vectors are unit length. When it serves this model, the + # in-process fallback normalises too, so every vector for it in this process + # has the same scale (k-means and HDBSCAN clustering use raw vectors). + return _get_model(model_name).encode( + sentences=texts, convert_to_numpy=True, normalize_embeddings=served + ) def get_hugging_face_embeddings_mpnet_base_v2(texts: list[str]) -> np.ndarray: diff --git a/tests/unit_tests/test_delosis_embeddings.py b/tests/unit_tests/test_delosis_embeddings.py new file mode 100644 index 0000000..d4296f9 --- /dev/null +++ b/tests/unit_tests/test_delosis_embeddings.py @@ -0,0 +1,231 @@ +""" +Unit tests for the Delosis embedding service client +(harmony_api/services/delosis_embeddings.py) and the in-process fallback in +hugging_face_embeddings.py, with a fake service and stand-in models, so no +weights are loaded and nothing is sent anywhere. + +Needs numpy, requests, pydantic-settings and pytest only: + + python -m pytest tests/unit_tests +""" + +import importlib +import sys +import types + +import numpy as np +import pytest +import requests + +MINILM = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" +MPNET = "sentence-transformers/paraphrase-multilingual-mpnet-base-v2" +MENTAL_HEALTH = "harmonydata/mental_health_harmonisation_1" +E5 = "intfloat/multilingual-e5-base" +DIMS = {"e5": 768, "minilm": 384} + +SETTINGS = ("HARMONY_EMBEDDER_URL", "HARMONY_EMBEDDER_TOKEN", "HARMONY_EMBEDDER_MODELS", + "HARMONY_E5_EMBEDDER_URL", "HARMONY_E5_EMBEDDER_TOKEN") + + +class FakeResponse: + def __init__(self, body, status=200): + self.body, self.status_code = body, status + + def json(self): + return self.body + + def raise_for_status(self): + if self.status_code >= 400: + raise requests.HTTPError(f"HTTP {self.status_code}") + + +class FakeService: + """The embedding service: answers a call without a model name with E5, + as delosis-embedding-api does. `answer_as` makes it answer with another + model whatever it was asked for (a service that predates model names); + `down` refuses connections.""" + + def __init__(self, answer_as=None, down=False): + self.answer_as, self.down = answer_as, down + self.posts = [] + + def post(self, url, json, headers, timeout): + self.posts.append({"url": url, "json": json, "headers": headers}) + if self.down: + raise requests.ConnectionError("connection refused") + name = self.answer_as or json.get("model") or "e5" + dim = DIMS[name] + vectors = [[dim ** -0.5] * dim for _ in json["texts"]] + body = {"vectors": vectors, "embeddings": vectors} + if json.get("model") or self.answer_as: + body["model"] = name + return FakeResponse(body) + + +class FakeST: + """Stands in for SentenceTransformer.""" + + loaded = [] + + def __init__(self, name): + self.name = name + self.dim = 384 if "MiniLM" in name else 768 + self.calls = [] + FakeST.loaded.append(name) + + def encode(self, sentences, convert_to_numpy=True, normalize_embeddings=False, **_): + self.calls.append((list(sentences), normalize_embeddings)) + scale = 1.0 if normalize_embeddings else 5.0 + return np.full((len(sentences), self.dim), scale * self.dim ** -0.5, dtype=np.float32) + + +@pytest.fixture +def load(monkeypatch): + """The two modules reloaded with the given settings, a fake service and + stand-in models.""" + + def make(service=None, **env): + for k in SETTINGS: + monkeypatch.delenv(k, raising=False) + for k, v in env.items(): + monkeypatch.setenv(k, v) + FakeST.loaded = [] + fake_st_module = types.ModuleType("sentence_transformers") + fake_st_module.SentenceTransformer = FakeST + monkeypatch.setitem(sys.modules, "sentence_transformers", fake_st_module) + from harmony_api.services import delosis_embeddings + delosis_embeddings = importlib.reload(delosis_embeddings) + monkeypatch.setattr(delosis_embeddings.time, "sleep", lambda s: None) + if service is not None: + monkeypatch.setattr(delosis_embeddings, "_session", service) + sys.modules.pop("harmony_api.services.hugging_face_embeddings", None) + hf = importlib.import_module("harmony_api.services.hugging_face_embeddings") + return delosis_embeddings, hf + + yield make + sys.modules.pop("harmony_api.services.hugging_face_embeddings", None) + + +BOTH = {"HARMONY_EMBEDDER_URL": "http://embedder.test:8000", "HARMONY_EMBEDDER_MODELS": "e5,minilm"} + + +def test_nothing_configured_is_stock_harmony(load): + d, hf = load() + assert not d.is_configured() and not d.is_served(MINILM) + assert FakeST.loaded == [MINILM, MPNET, MENTAL_HEALTH] + out = hf.get_hugging_face_embeddings_minilm_l12_v2(["I feel sad"]) + assert out.shape == (1, 384) + assert hf._models[MINILM].calls == [(["I feel sad"], False)] # unnormalised, as before + + +def test_the_e5_only_settings_still_mean_e5_without_a_model_name(load): + service = FakeService() + d, hf = load(service, HARMONY_E5_EMBEDDER_URL="http://embedder.test:8000") + assert d.is_configured() and not d.is_served(MINILM) + assert MINILM in FakeST.loaded + out = d.get_delosis_e5_embeddings(["I feel sad"]) + assert out.shape == (1, 768) + sent = service.posts[0] + assert sent["url"] == "http://embedder.test:8000/text/embed" + assert sent["json"] == {"texts": ["query: I feel sad"], "prefix": ""} + + +def test_minilm_is_not_loaded_in_process_when_the_service_serves_it(load): + d, hf = load(FakeService(), **BOTH) + assert d.is_served(MINILM) and d.is_configured() + assert FakeST.loaded == [MPNET, MENTAL_HEALTH] + + +def test_minilm_goes_to_the_service_by_name_without_a_prefix(load): + service = FakeService() + d, hf = load(service, **BOTH) + out = hf.get_hugging_face_embeddings_minilm_l12_v2(["I feel sad", "I worry"]) + assert out.shape == (2, 384) + assert service.posts[0]["json"] == {"texts": ["I feel sad", "I worry"], "prefix": "", "model": "minilm"} + assert MINILM not in FakeST.loaded + + +def test_e5_is_asked_for_by_name_with_its_prefix(load): + service = FakeService() + d, hf = load(service, **BOTH) + d.get_delosis_e5_embeddings(["x"]) + assert service.posts[0]["json"] == {"texts": ["query: x"], "prefix": "", "model": "e5"} + + +def test_a_token_is_sent_as_a_bearer(load): + service = FakeService() + d, hf = load(service, HARMONY_EMBEDDER_TOKEN="secret", **BOTH) + d.get_delosis_e5_embeddings(["x"]) + assert service.posts[0]["headers"] == {"Authorization": "Bearer secret"} + + +def test_big_batches_are_split(load): + service = FakeService() + d, hf = load(service, **BOTH) + out = hf.get_hugging_face_embeddings_minilm_l12_v2([f"item {i}" for i in range(600)]) + assert out.shape == (600, 384) + assert [len(p["json"]["texts"]) for p in service.posts] == [256, 256, 88] + + +def test_a_reply_from_another_model_is_never_taken_for_minilm(load): + # A service that predates model names answers with E5 whatever it is asked. + service = FakeService(answer_as="e5") + d, hf = load(service, **BOTH) + with pytest.raises(RuntimeError, match="answered with e5"): + d.get_embeddings(["x"], MINILM) + + +def test_minilm_falls_back_in_process_normalised_when_the_service_is_down(load): + service = FakeService(down=True) + d, hf = load(service, **BOTH) + out = hf.get_hugging_face_embeddings_minilm_l12_v2(["x", "y"]) + assert out.shape == (2, 384) + assert np.allclose(np.linalg.norm(out, axis=1), 1.0) # same scale as the service's + assert len(service.posts) == d.RETRIES + # For the next minute requests stay in-process without trying the service. + hf.get_hugging_face_embeddings_minilm_l12_v2(["z"]) + assert len(service.posts) == d.RETRIES + assert FakeST.loaded.count(MINILM) == 1 + + +def test_the_service_is_tried_again_after_the_pause(load, monkeypatch): + service = FakeService(down=True) + d, hf = load(service, **BOTH) + hf.get_hugging_face_embeddings_minilm_l12_v2(["x"]) + service.down = False + monkeypatch.setitem(hf._remote_down_until, MINILM, 0.0) + hf.get_hugging_face_embeddings_minilm_l12_v2(["y"]) + assert service.posts[-1]["json"]["model"] == "minilm" + + +def test_e5_has_no_in_process_fallback(load): + d, hf = load(FakeService(down=True), **BOTH) + with pytest.raises(requests.ConnectionError): + d.get_delosis_e5_embeddings(["x"]) + + +def test_wrong_dimensions_are_refused(load, monkeypatch): + service = FakeService() + d, hf = load(service, **BOTH) + monkeypatch.setitem(DIMS, "minilm", 768) + with pytest.raises(RuntimeError, match="not 384-d"): + d.get_embeddings(["x"], MINILM) + + +def test_an_unknown_model_name_in_the_settings_is_an_error(load): + with pytest.raises(ValueError, match="gemma"): + load(FakeService(), HARMONY_EMBEDDER_URL="http://embedder.test:8000", + HARMONY_EMBEDDER_MODELS="e5,gemma") + + +def test_minilm_only(load): + d, hf = load(FakeService(), HARMONY_EMBEDDER_URL="http://embedder.test:8000", + HARMONY_EMBEDDER_MODELS="minilm") + assert d.is_served(MINILM) and not d.is_configured() + + +def test_no_texts(load): + service = FakeService() + d, hf = load(service, **BOTH) + assert len(hf.get_hugging_face_embeddings_minilm_l12_v2([])) == 0 + assert service.posts == []