Coverage for app / util / embedding.py: 100%

63 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Embedding utility for knowledge document indexing. 

3 

4svc-core has no LLM egress (it lives on internal Docker networks), so vectors 

5are produced by svc-ai's ``POST /knowledge/embed``. Delegating also pins 

6ingestion and retrieval to one embedding model by construction: svc-ai's 

7active embedder (``app/services/embeddings.py``, chosen by its 

8``INFERENCE_BACKEND``) serves both. 

9 

10Which model that is — and so the size of its vectors — is svc-ai's to say: 

11``active()`` asks ``GET /knowledge/embedding`` and caches the answer briefly. 

12Collections are built at that size and stamped with its ``key`` 

13(``qdrant_client.ensure_collection``); a collection stamped with another key 

14holds vectors from another model and is rebuilt by 

15``services/knowledge/reindex.py``. A vector of the wrong size is reported as 

16an ``EmbeddingError`` so the document is marked *failed* instead of silently 

17indexing garbage. 

18""" 

19 

20import logging 

21import threading 

22import time 

23from dataclasses import asdict, dataclass 

24 

25from app.services import ai_client 

26 

27logger = logging.getLogger(__name__) 

28 

29_BATCH_SIZE = 256 # texts per svc-ai request (svc-ai batches to the provider) 

30 

31#: How long svc-ai's answer is trusted. The model changes only when svc-ai 

32#: is redeployed with another backend, so a few minutes is plenty. 

33_IDENTITY_TTL_S = 300.0 

34 

35 

36@dataclass(frozen=True) 

37class EmbeddingIdentity: 

38 """An embedding model, as collections are built for it.""" 

39 

40 provider: str 

41 model: str 

42 dimensions: int 

43 #: Names the vector space: ``provider/model/dimensions``. 

44 key: str 

45 backend: str = "" 

46 #: Whether the deployment may call it (Bedrock model access). 

47 available: bool = True 

48 

49 def as_metadata(self) -> dict: 

50 """What a collection records about the vectors it holds.""" 

51 return { 

52 "provider": self.provider, 

53 "model": self.model, 

54 "dimensions": self.dimensions, 

55 "key": self.key, 

56 } 

57 

58 def as_dict(self) -> dict: 

59 return asdict(self) 

60 

61 

62#: Every collection built before collections recorded their model: OpenAI's 

63#: 1536-dimension vectors, the only ones the platform made then. 

64LEGACY = EmbeddingIdentity( 

65 provider="openai", 

66 model="text-embedding-3-small", 

67 dimensions=1536, 

68 key="openai/text-embedding-3-small/1536", 

69 backend="direct", 

70) 

71 

72_lock = threading.Lock() 

73_cached: tuple[float, EmbeddingIdentity] | None = None 

74 

75 

76class EmbeddingError(RuntimeError): 

77 """Raised when svc-ai cannot embed the texts or returns the wrong shape.""" 

78 

79 

80def active(*, refresh: bool = False) -> EmbeddingIdentity: 

81 """The embedding model svc-ai indexes and searches with. 

82 

83 Raises ``EmbeddingError`` when svc-ai cannot be asked: nothing may be 

84 built at a guessed size. 

85 """ 

86 global _cached 

87 with _lock: 

88 if ( 

89 not refresh 

90 and _cached is not None 

91 and time.monotonic() - _cached[0] < _IDENTITY_TTL_S 

92 ): 

93 return _cached[1] 

94 try: 

95 body = ai_client.embedding_identity() 

96 except ai_client.AIServiceError as exc: 

97 raise EmbeddingError( 

98 f"could not ask svc-ai for its embedding model: {exc}" 

99 ) from exc 

100 identity = EmbeddingIdentity( 

101 provider=str(body["provider"]), 

102 model=str(body["model"]), 

103 dimensions=int(body["dimensions"]), 

104 key=str(body["key"]), 

105 backend=str(body.get("backend") or ""), 

106 available=bool(body.get("available", True)), 

107 ) 

108 with _lock: 

109 _cached = (time.monotonic(), identity) 

110 return identity 

111 

112 

113def forget() -> None: 

114 """Drop the cached model, so the next ``active()`` asks svc-ai.""" 

115 global _cached 

116 with _lock: 

117 _cached = None 

118 

119 

120def embed_texts(texts: list[str]) -> list[list[float]]: 

121 """ 

122 Return a list of embedding vectors, one per input text, via svc-ai. 

123 

124 Raises ``EmbeddingError`` when svc-ai is unreachable, rejects the 

125 request, or returns vectors of a size other than the active model's. 

126 ``ai_client.ModelRefusedError`` (the spending ceiling, model access, 

127 credentials) passes through unchanged: a person has to act on it, and a 

128 caller leaves the document waiting rather than failed. 

129 """ 

130 if not texts: 

131 return [] 

132 expected = active().dimensions 

133 all_embeddings: list[list[float]] = [] 

134 for i in range(0, len(texts), _BATCH_SIZE): 

135 batch = texts[i : i + _BATCH_SIZE] 

136 try: 

137 result = ai_client.embed_texts(batch) 

138 except ai_client.ModelRefusedError: 

139 raise 

140 except ai_client.AIServiceError as exc: 

141 raise EmbeddingError(f"embedding via svc-ai failed: {exc}") from exc 

142 vectors = result.get("embeddings") or [] 

143 if len(vectors) != len(batch): 

144 raise EmbeddingError( 

145 f"svc-ai returned {len(vectors)} vectors for {len(batch)} texts" 

146 ) 

147 dims = result.get("dimensions") or (len(vectors[0]) if vectors else 0) 

148 if dims != expected: 

149 # svc-ai may have been redeployed with another model since the 

150 # cached answer: ask again once before calling it a mismatch. 

151 forget() 

152 expected = active().dimensions 

153 if dims != expected: 

154 raise EmbeddingError( 

155 f"embedding model {result.get('model', '?')} returns {dims} " 

156 f"dimensions but the vector index expects {expected}" 

157 ) 

158 all_embeddings.extend(vectors) 

159 return all_embeddings