Coverage for app / services / embeddings.py: 99%
180 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2The platform's embedding model: one class per inference backend.
4Knowledge is indexed and searched with one embedding model, and the vectors
5are only comparable with each other: a collection built with one model cannot
6be searched with another (Titan's vectors have 1024 dimensions, OpenAI's
71536). So the model is the deployment's, chosen by ``INFERENCE_BACKEND`` like
8everything else that reaches a model, and never a separate setting that could
9drift from it:
11* ``direct`` — OpenAI ``text-embedding-3-small``, with the vendor's key.
12 Local development without AWS.
13* ``bedrock`` — Amazon Titan Text Embeddings V2, in ``BEDROCK_REGION``
14 (in-region only: Titan has no EU or Global profile), so knowledge text goes
15 nowhere chat prompts do not already go.
17Each is a catalogue model (``providers/registry.py``), so its calls are
18priced on the catalogue's card and, on Bedrock, allowed by the invoke role's
19model list. svc-core asks ``GET /knowledge/embedding`` which one is active
20and builds its Qdrant collections at that size, stamped with the
21embedder's ``key``; a collection stamped with another key is rebuilt
22(svc-core ``services/knowledge/reindex.py``), and until then
23``rag.dense_search`` skips it rather than query it with the wrong vectors.
25Every call goes through ``Embedder.embed_many``: the spending ceiling is
26checked before each chunk of texts, and each chunk is one metered call with
27the tokens the provider reported, so a document of 400 chunks is a handful
28of trace rows rather than 400.
29"""
31from __future__ import annotations
33import asyncio
34import json
35import threading
36import time
37from abc import ABC, abstractmethod
38from collections.abc import Callable
39from concurrent.futures import ThreadPoolExecutor
40from dataclasses import dataclass
41from typing import Any, ClassVar
43from app.common.settings import get_settings
44from app.services import inference_routes, metering, model_errors
45from app.services.provider_usage import UNREPORTED, TokenUsage
48class EmbeddingError(RuntimeError):
49 """The embedding model answered with something that is not one vector of
50 the expected size per text."""
53class ChunkFailed(Exception):
54 """A chunk failed part-way through: ``cause`` is the first failure, and
55 ``usage`` what the texts embedded before it spent — billed all the same."""
57 def __init__(self, cause: BaseException, usage: TokenUsage | None) -> None:
58 super().__init__(str(cause))
59 self.cause = cause
60 self.usage = usage
63@dataclass(frozen=True)
64class SimilarityFloors:
65 """The cosine-similarity floors searches apply with this embedder.
67 Each model's scores sit in their own range, so a floor tuned for one
68 drops everything, or nothing, on another. Named by how strict the search
69 is: the retrieval pipeline's ``standard``; a per-knowledge-base tool's
70 ``strict``; the broad ``search_knowledge`` tool's ``loose``.
72 ``memory`` is agent memory recall's (``app.memory.recall``): a short
73 memory against a short request, with no reranker after it, so the
74 floor alone decides what reaches the model. Provisional for both
75 embedders below — set between ``standard`` and ``strict`` and to be
76 tuned with ``python -m tests.memory.report --embedder active`` once a
77 deployment's embedder is reachable (``docs/guides/memory.md``).
78 """
80 standard: float
81 strict: float
82 loose: float
83 memory: float = 0.5
86class Embedder(ABC):
87 """One embedding model, served on one inference backend."""
89 #: The ``inference_routes`` backend this embedder serves.
90 backend: ClassVar[str]
91 #: The catalogue identity — what each call is metered and priced as.
92 provider: ClassVar[str]
93 model: ClassVar[str]
94 dimensions: ClassVar[int]
95 #: Texts per metered call.
96 max_batch: ClassVar[int]
97 #: Longest text the model accepts; longer ones are cut, not refused.
98 max_input_chars: ClassVar[int]
99 floors: ClassVar[SimilarityFloors]
101 @classmethod
102 def key(cls) -> str:
103 """Which vectors this embedder makes: a collection stamped with
104 another key holds vectors from another space."""
105 return f"{cls.provider}/{cls.model}/{cls.dimensions}"
107 @classmethod
108 def identity(cls) -> dict[str, Any]:
109 """What ``GET /knowledge/embedding`` serves."""
110 return {
111 "provider": cls.provider,
112 "model": cls.model,
113 "dimensions": cls.dimensions,
114 "key": cls.key(),
115 "backend": cls.backend,
116 "available": cls.available(),
117 }
119 @classmethod
120 def available(cls) -> bool:
121 """Whether this deployment can call the model at all."""
122 return True
124 async def embed_many(self, texts: list[str]) -> list[list[float]]:
125 """One vector per text, in order. Within a run, a text the run has
126 embedded already is not embedded again (``embedding_cache``)."""
127 from app.services import embedding_cache
129 cache = embedding_cache.current()
130 if cache is None:
131 return await self._embed_all(texts)
132 return await cache.vectors(
133 self.key(), [t[: self.max_input_chars] for t in texts], self._embed_all
134 )
136 async def _embed_all(self, texts: list[str]) -> list[list[float]]:
137 """One vector per text, in order: every one embedded, in metered
138 chunks of ``max_batch``."""
139 out: list[list[float]] = []
140 for i in range(0, len(texts), self.max_batch):
141 chunk = [t[: self.max_input_chars] for t in texts[i : i + self.max_batch]]
142 metering.check_limits()
143 started = time.monotonic()
144 try:
145 vectors, usage = await self._embed_chunk(chunk)
146 except Exception as exc:
147 cause, spent = (
148 (exc.cause, exc.usage)
149 if isinstance(exc, ChunkFailed)
150 else (exc, None)
151 )
152 if spent is not None and spent.input_tokens:
153 # Texts embedded before the failure were billed.
154 metering.record(
155 self.provider,
156 self.model,
157 kind="embedding",
158 latency_ms=metering.elapsed_ms(started),
159 usage=spent,
160 )
161 metering.record(
162 self.provider,
163 self.model,
164 kind="embedding",
165 latency_ms=metering.elapsed_ms(started),
166 status=metering.CALL_ERROR,
167 error=model_errors.describe(cause),
168 )
169 model_errors.raise_if_fatal(cause)
170 raise cause from None
171 metering.record(
172 self.provider,
173 self.model,
174 kind="embedding",
175 latency_ms=metering.elapsed_ms(started),
176 usage=usage,
177 )
178 if len(vectors) != len(chunk) or any(
179 len(v) != self.dimensions for v in vectors
180 ):
181 raise EmbeddingError(
182 f"{self.model} returned {len(vectors)} vectors for "
183 f"{len(chunk)} texts, expected {self.dimensions} dimensions"
184 )
185 out.extend(vectors)
186 return out
188 async def embed_one(self, text: str) -> list[float]:
189 return (await self.embed_many([text]))[0]
191 @abstractmethod
192 async def _embed_chunk(
193 self, texts: list[str]
194 ) -> tuple[list[list[float]], TokenUsage]:
195 """Embed one chunk; return its vectors in order and its usage."""
198_REGISTRY: dict[str, type[Embedder]] = {}
201def register(cls: type[Embedder]) -> type[Embedder]:
202 _REGISTRY[cls.backend] = cls
203 return cls
206def all_embedders() -> list[type[Embedder]]:
207 return list(_REGISTRY.values())
210_INSTANCES: dict[str, Embedder] = {}
213def active() -> Embedder:
214 """The embedder this deployment indexes and searches with."""
215 backend = inference_routes.backend()
216 instance = _INSTANCES.get(backend)
217 if instance is None:
218 instance = _INSTANCES[backend] = _REGISTRY[backend]()
219 return instance
222# ── OpenAI (direct) ──────────────────────────────────────────────────────────
225@register
226class OpenAIEmbedder(Embedder):
227 backend = inference_routes.DIRECT
228 provider = "openai"
229 model = "text-embedding-3-small"
230 dimensions = 1536
231 max_batch = 256
232 # 8,191 tokens; the chunker keeps texts far below that.
233 max_input_chars = 30_000
234 # The floors every search used before embeddings were per backend.
235 floors = SimilarityFloors(standard=0.35, strict=0.7, loose=0.2, memory=0.45)
237 def __init__(self) -> None:
238 self._client: Any = None
240 def _openai(self) -> Any:
241 if self._client is None:
242 from openai import AsyncOpenAI
244 self._client = AsyncOpenAI(api_key=get_settings().openai_api_key)
245 return self._client
247 async def _embed_chunk(
248 self, texts: list[str]
249 ) -> tuple[list[list[float]], TokenUsage]:
250 response = await self._openai().embeddings.create(input=texts, model=self.model)
251 # The API returns items with an ``index``; keep input order explicitly.
252 ordered = sorted(response.data, key=lambda d: getattr(d, "index", 0))
253 usage = getattr(response, "usage", None)
254 return [item.embedding for item in ordered], (
255 TokenUsage(input_tokens=int(getattr(usage, "prompt_tokens", 0) or 0))
256 if usage is not None
257 else UNREPORTED
258 )
261# ── Amazon Titan on Bedrock ──────────────────────────────────────────────────
264#: The share of the account's Titan quota svc-ai sends. The quota is per
265#: account and region, so anything else calling Titan there (an operator's
266#: smoke test, a second environment) draws on the same 6,000 a minute.
267QUOTA_SHARE = 0.8
270class Pacer:
271 """Spaces requests evenly, so the process never sends more than
272 ``per_minute``: each request takes the next free slot and waits for it.
273 Even spacing, not a per-minute count, because Bedrock throttles bursts
274 inside a minute too."""
276 def __init__(
277 self,
278 per_minute: float,
279 *,
280 clock: Callable[[], float] = time.monotonic,
281 sleep: Callable[[float], None] = time.sleep,
282 ) -> None:
283 self.interval = 60.0 / per_minute if per_minute > 0 else 0.0
284 self._next = 0.0
285 self._lock = threading.Lock()
286 self._clock = clock
287 self._sleep = sleep
289 def wait(self) -> None:
290 if not self.interval:
291 return
292 with self._lock:
293 now = self._clock()
294 slot = max(now, self._next)
295 self._next = slot + self.interval
296 if slot > now:
297 self._sleep(slot - now)
300_POOL: ThreadPoolExecutor | None = None
301_PACER: Pacer | None = None
302_POOL_LOCK = threading.Lock()
305def _pacer() -> Pacer:
306 """The process-wide pace of Titan requests: ``QUOTA_SHARE`` of the
307 account's quota (``EMBEDDING_RPM_QUOTA``)."""
308 global _PACER
309 with _POOL_LOCK:
310 if _PACER is None:
311 quota = int(get_settings().EMBEDDING_RPM_QUOTA or 0)
312 _PACER = Pacer(quota * QUOTA_SHARE)
313 return _PACER
316def _pool() -> ThreadPoolExecutor:
317 """The process-wide cap on Titan requests in flight: enough threads to
318 reach the pacer's rate, and no more. Titan takes one text per request,
319 so this and the pacer — not a batch size — set indexing's speed."""
320 global _POOL
321 with _POOL_LOCK:
322 if _POOL is None:
323 workers = max(1, int(get_settings().EMBEDDING_CONCURRENCY or 1))
324 _POOL = ThreadPoolExecutor(
325 max_workers=workers, thread_name_prefix="titan-embed"
326 )
327 return _POOL
330@register
331class TitanEmbedder(Embedder):
332 backend = inference_routes.BEDROCK
333 #: Registered under Bedrock itself, like the open-weight models: no
334 #: vendor API serves it, and its maker (``amazon``) is read off the id.
335 provider = inference_routes.BEDROCK
336 model = "amazon.titan-embed-text-v2:0"
337 dimensions = 1024
338 max_batch = 64
339 #: Titan refuses more than 8,192 tokens (or 50,000 characters, whichever
340 #: comes first). Chunks are 512 tokens; this caps a long query below the
341 #: token limit for any script, and its first 8,000 characters carry its
342 #: meaning.
343 max_input_chars = 8_000
344 #: Provisional: Titan's cosine scores run lower than OpenAI's. Tune them
345 #: against the guide once it is rebuilt
346 #: (``docs/system/deployment/bedrock-migration.md`` section 4).
347 floors = SimilarityFloors(standard=0.25, strict=0.5, loose=0.15, memory=0.4)
349 def __init__(self) -> None:
350 self._client: Any = None
351 self._lock = threading.Lock()
353 @classmethod
354 def available(cls) -> bool:
355 return inference_routes.has_access(inference_routes.bedrock_vendor(cls.model))
357 def _bedrock(self) -> Any:
358 with self._lock:
359 if self._client is None:
360 import boto3
362 self._client = boto3.client(
363 "bedrock-runtime",
364 config=inference_routes.bedrock_client_config(
365 30.0, retry_mode="adaptive", max_attempts=5
366 ),
367 )
368 return self._client
370 def _invoke_one(self, text: str) -> tuple[list[float], int | None]:
371 _pacer().wait()
372 response = self._bedrock().invoke_model(
373 modelId=self.model,
374 contentType="application/json",
375 accept="application/json",
376 body=json.dumps(
377 {"inputText": text, "dimensions": self.dimensions, "normalize": True}
378 ),
379 )
380 payload = json.loads(response["body"].read())
381 count = payload.get("inputTextTokenCount")
382 return list(payload["embedding"]), (int(count) if count is not None else None)
384 async def _embed_chunk(
385 self, texts: list[str]
386 ) -> tuple[list[list[float]], TokenUsage]:
387 try:
388 inference_routes.resolve(self.provider, self.model)
389 except inference_routes.RouteUnavailable as exc:
390 # The account may not use Amazon's models (BEDROCK_MODEL_ACCESS).
391 raise model_errors.ModelUnavailableError(
392 model_errors.FatalKind.PERMISSION, None, self.provider
393 ) from exc
394 loop = asyncio.get_running_loop()
395 results = await asyncio.gather(
396 *(loop.run_in_executor(_pool(), self._invoke_one, t) for t in texts),
397 return_exceptions=True,
398 )
399 counts = [r[1] for r in results if not isinstance(r, BaseException)]
400 reported = all(c is not None for c in counts)
401 usage = TokenUsage(input_tokens=sum(c or 0 for c in counts))
402 failures = [r for r in results if isinstance(r, BaseException)]
403 if failures:
404 raise ChunkFailed(failures[0], usage if reported else None)
405 vectors = [r[0] for r in results] # type: ignore[index]
406 return vectors, usage if reported else UNREPORTED