@pentatonic-ai/ai-agent-sdk 0.7.12 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,354 @@
1
+ """Unit tests for engine/services/_shared/embed_provider.py.
2
+
3
+ Run with:
4
+ cd packages/memory-engine
5
+ python -m pytest tests/test_embed_provider.py -v
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ # Make the engine/services tree importable for tests without packaging it.
14
+ ROOT = Path(__file__).parent.parent / "engine" / "services"
15
+ sys.path.insert(0, str(ROOT))
16
+
17
+ import json # noqa: E402
18
+
19
+ import httpx # noqa: E402
20
+ import pytest # noqa: E402
21
+
22
+ from _shared.embed_provider import ( # noqa: E402
23
+ PROVIDERS,
24
+ EmbedAuthError,
25
+ EmbedClient,
26
+ EmbedHTTPError,
27
+ EmbedProvider,
28
+ resolve_provider,
29
+ )
30
+
31
+
32
+ # ----------------------------------------------------------------------
33
+ # Helpers — stub httpx so we can assert the request shape.
34
+ # ----------------------------------------------------------------------
35
+
36
+ class _FakeResponse:
37
+ def __init__(self, status_code: int, payload: dict | str = ""):
38
+ self.status_code = status_code
39
+ if isinstance(payload, dict):
40
+ self._json = payload
41
+ self.text = json.dumps(payload)
42
+ else:
43
+ self._json = None
44
+ self.text = payload
45
+
46
+ @property
47
+ def is_success(self) -> bool:
48
+ return 200 <= self.status_code < 300
49
+
50
+ def json(self) -> dict:
51
+ if self._json is None:
52
+ raise ValueError("not json")
53
+ return self._json
54
+
55
+
56
+ class _Recorder:
57
+ """Records every httpx.post call and returns canned responses keyed by URL."""
58
+
59
+ def __init__(self):
60
+ self.calls: list[dict] = []
61
+ self.responses: dict[str, _FakeResponse] = {}
62
+
63
+ def respond(self, url: str, response: _FakeResponse) -> None:
64
+ self.responses[url] = response
65
+
66
+ def __call__(self, url, *, json, headers, timeout):
67
+ self.calls.append({"url": url, "json": json, "headers": headers, "timeout": timeout})
68
+ if url in self.responses:
69
+ return self.responses[url]
70
+ # default: 401 to flush out unmatched URLs
71
+ return _FakeResponse(401, "no stub for this url")
72
+
73
+
74
+ @pytest.fixture
75
+ def recorder(monkeypatch):
76
+ rec = _Recorder()
77
+ monkeypatch.setattr(httpx, "post", rec)
78
+ return rec
79
+
80
+
81
+ # ----------------------------------------------------------------------
82
+ # Provider resolution
83
+ # ----------------------------------------------------------------------
84
+
85
+ def test_resolve_built_in_providers():
86
+ for name in ("openai", "pentatonic-gateway", "cohere"):
87
+ p = resolve_provider(name)
88
+ assert p.name == name
89
+
90
+
91
+ def test_resolve_unknown_provider_raises():
92
+ with pytest.raises(ValueError):
93
+ resolve_provider("not-a-provider")
94
+
95
+
96
+ def test_resolve_custom_provider_from_env(monkeypatch):
97
+ monkeypatch.setenv("L4_EMBED_AUTH_HEADER", "X-Custom-Auth")
98
+ monkeypatch.setenv("L4_EMBED_AUTH_FORMAT", "Token {key}")
99
+ monkeypatch.setenv("L4_EMBED_PATH_DEFAULT", "/embed")
100
+ monkeypatch.setenv("L4_EMBED_BODY_SHAPE", "cohere")
101
+ monkeypatch.setenv("L4_EMBED_RESPONSE_SHAPE", "cohere")
102
+ p = resolve_provider("custom", env_prefix="L4_")
103
+ assert p.auth_header == "X-Custom-Auth"
104
+ assert p.auth_format == "Token {key}"
105
+ assert p.path_default == "/embed"
106
+ # body shape produces Cohere-style "texts" field
107
+ body = p.body_builder(["hi"], "model-x")
108
+ assert body == {"texts": ["hi"], "model": "model-x", "input_type": "search_document"}
109
+
110
+
111
+ # ----------------------------------------------------------------------
112
+ # Request shape
113
+ # ----------------------------------------------------------------------
114
+
115
+ def test_openai_provider_request_shape(recorder):
116
+ recorder.respond(
117
+ "https://gw/v1/embeddings",
118
+ _FakeResponse(200, {"data": [{"embedding": [0.1, 0.2]}]}),
119
+ )
120
+ client = EmbedClient(
121
+ url="https://gw/v1/embeddings",
122
+ api_key="k",
123
+ model="m",
124
+ provider=PROVIDERS["openai"],
125
+ )
126
+ out = client.embed_batch(["hello"])
127
+ assert out == [[0.1, 0.2]]
128
+ call = recorder.calls[0]
129
+ assert call["url"] == "https://gw/v1/embeddings"
130
+ assert call["json"] == {"input": ["hello"], "model": "m"}
131
+ assert call["headers"] == {"Authorization": "Bearer k"}
132
+
133
+
134
+ def test_pentatonic_provider_request_shape(recorder):
135
+ recorder.respond(
136
+ "https://lambda-gateway.pentatonic.com/v1/embed",
137
+ _FakeResponse(200, {"data": [{"embedding": [1.0, 2.0]}]}),
138
+ )
139
+ client = EmbedClient(
140
+ url="https://lambda-gateway.pentatonic.com/v1/embed",
141
+ api_key="secret",
142
+ model="nv-embed-v2",
143
+ provider=PROVIDERS["pentatonic-gateway"],
144
+ )
145
+ out = client.embed_batch(["t1"])
146
+ assert out == [[1.0, 2.0]]
147
+ call = recorder.calls[0]
148
+ assert call["url"] == "https://lambda-gateway.pentatonic.com/v1/embed"
149
+ assert call["json"] == {"input": ["t1"], "model": "nv-embed-v2"}
150
+ assert call["headers"] == {"X-API-Key": "secret"}
151
+
152
+
153
+ def test_pentatonic_response_parser_handles_both_shapes(recorder):
154
+ """Pentatonic Gateway has historically returned both {"data":[...]} and
155
+ {"embeddings":[...]} on different endpoints. Parser accepts either."""
156
+ p = PROVIDERS["pentatonic-gateway"]
157
+ assert p.response_parser({"data": [{"embedding": [1.0]}]}) == [[1.0]]
158
+ assert p.response_parser({"embeddings": [[1.0]]}) == [[1.0]]
159
+
160
+
161
+ def test_cohere_provider_request_shape(recorder):
162
+ recorder.respond(
163
+ "https://api.cohere.ai/v1/embed",
164
+ _FakeResponse(200, {"embeddings": [[3.0, 4.0]]}),
165
+ )
166
+ client = EmbedClient(
167
+ url="https://api.cohere.ai/v1/embed",
168
+ api_key="cohere-key",
169
+ model="embed-english-v3.0",
170
+ provider=PROVIDERS["cohere"],
171
+ )
172
+ out = client.embed_batch(["hi"])
173
+ assert out == [[3.0, 4.0]]
174
+ call = recorder.calls[0]
175
+ assert call["json"] == {
176
+ "texts": ["hi"],
177
+ "model": "embed-english-v3.0",
178
+ "input_type": "search_document",
179
+ }
180
+ assert call["headers"] == {"Authorization": "Bearer cohere-key"}
181
+
182
+
183
+ # ----------------------------------------------------------------------
184
+ # Auto-detect
185
+ # ----------------------------------------------------------------------
186
+
187
+ def test_autodetect_on_401_falls_back_to_pentatonic(recorder):
188
+ """Operator configured openai but the URL+key actually belong to
189
+ Pentatonic Gateway. First call 401s, auto-detect probes pentatonic
190
+ and succeeds."""
191
+ recorder.respond(
192
+ "https://lambda-gateway.pentatonic.com/v1/embeddings",
193
+ _FakeResponse(401, '{"error":"Invalid or missing API key"}'),
194
+ )
195
+ recorder.respond(
196
+ "https://lambda-gateway.pentatonic.com/v1/embed",
197
+ _FakeResponse(200, {"data": [{"embedding": [9.0]}]}),
198
+ )
199
+ client = EmbedClient(
200
+ url="https://lambda-gateway.pentatonic.com/v1/embeddings",
201
+ api_key="k",
202
+ model="nv-embed-v2",
203
+ provider=PROVIDERS["openai"],
204
+ )
205
+ out = client.embed_batch(["x"])
206
+ assert out == [[9.0]]
207
+ assert client.active_provider == "pentatonic-gateway"
208
+ # First call uses configured (openai) shape, second uses pentatonic
209
+ assert recorder.calls[0]["headers"] == {"Authorization": "Bearer k"}
210
+ assert recorder.calls[1]["headers"] == {"X-API-Key": "k"}
211
+
212
+
213
+ def test_autodetect_caches_after_first_success(recorder):
214
+ """Once auto-detect picks a winner, subsequent calls go straight to it
215
+ without retrying the original 401."""
216
+ recorder.respond(
217
+ "https://gw/v1/embeddings",
218
+ _FakeResponse(401, "wrong scheme"),
219
+ )
220
+ recorder.respond(
221
+ "https://gw/v1/embed",
222
+ _FakeResponse(200, {"data": [{"embedding": [1.0]}]}),
223
+ )
224
+ client = EmbedClient(
225
+ url="https://gw/v1/embeddings",
226
+ api_key="k",
227
+ model="m",
228
+ provider=PROVIDERS["openai"],
229
+ )
230
+ client.embed_batch(["a"]) # triggers detect
231
+ n_after_first = len(recorder.calls)
232
+ client.embed_batch(["b"]) # should go straight to /v1/embed
233
+ assert len(recorder.calls) == n_after_first + 1
234
+ assert recorder.calls[-1]["url"] == "https://gw/v1/embed"
235
+
236
+
237
+ def test_autodetect_disabled_raises(recorder):
238
+ recorder.respond("https://gw/v1/embeddings", _FakeResponse(401, "no auth"))
239
+ client = EmbedClient(
240
+ url="https://gw/v1/embeddings",
241
+ api_key="k",
242
+ model="m",
243
+ provider=PROVIDERS["openai"],
244
+ autodetect=False,
245
+ )
246
+ with pytest.raises(EmbedAuthError):
247
+ client.embed_batch(["x"])
248
+ # Only one call: no probing happened.
249
+ assert len(recorder.calls) == 1
250
+
251
+
252
+ def test_autodetect_all_fail_raises(recorder):
253
+ """Every candidate also 401s — raise EmbedAuthError."""
254
+ recorder.respond("https://gw/v1/embeddings", _FakeResponse(401, "x"))
255
+ recorder.respond("https://gw/v1/embed", _FakeResponse(401, "x"))
256
+ client = EmbedClient(
257
+ url="https://gw/v1/embeddings",
258
+ api_key="k",
259
+ model="m",
260
+ provider=PROVIDERS["openai"],
261
+ )
262
+ with pytest.raises(EmbedAuthError):
263
+ client.embed_batch(["x"])
264
+
265
+
266
+ # ----------------------------------------------------------------------
267
+ # Error handling
268
+ # ----------------------------------------------------------------------
269
+
270
+ def test_non_401_http_error_does_not_trigger_autodetect(recorder):
271
+ recorder.respond(
272
+ "https://gw/v1/embeddings",
273
+ _FakeResponse(503, "upstream down"),
274
+ )
275
+ client = EmbedClient(
276
+ url="https://gw/v1/embeddings",
277
+ api_key="k",
278
+ model="m",
279
+ provider=PROVIDERS["openai"],
280
+ )
281
+ with pytest.raises(EmbedHTTPError) as exc:
282
+ client.embed_batch(["x"])
283
+ assert exc.value.status == 503
284
+ assert len(recorder.calls) == 1
285
+
286
+
287
+ def test_empty_input_returns_empty(recorder):
288
+ client = EmbedClient(
289
+ url="https://gw/v1/embeddings",
290
+ api_key="k",
291
+ model="m",
292
+ provider=PROVIDERS["openai"],
293
+ )
294
+ assert client.embed_batch([]) == []
295
+ assert recorder.calls == []
296
+
297
+
298
+ # ----------------------------------------------------------------------
299
+ # from_env construction
300
+ # ----------------------------------------------------------------------
301
+
302
+ def test_from_env_reads_layer_prefix(monkeypatch, recorder):
303
+ monkeypatch.setenv("L4_NV_EMBED_URL", "https://lambda-gateway.pentatonic.com/v1/embed")
304
+ monkeypatch.setenv("L4_EMBED_API_KEY", "real-key")
305
+ monkeypatch.setenv("L4_EMBED_MODEL", "nv-embed-v2")
306
+ monkeypatch.setenv("L4_EMBED_PROVIDER", "pentatonic-gateway")
307
+ recorder.respond(
308
+ "https://lambda-gateway.pentatonic.com/v1/embed",
309
+ _FakeResponse(200, {"data": [{"embedding": [42.0]}]}),
310
+ )
311
+ client = EmbedClient.from_env(prefix="L4_")
312
+ out = client.embed_batch(["t"])
313
+ assert out == [[42.0]]
314
+ assert client.active_provider == "pentatonic-gateway"
315
+ assert recorder.calls[0]["headers"] == {"X-API-Key": "real-key"}
316
+
317
+
318
+ def test_from_env_default_provider_is_openai(monkeypatch):
319
+ monkeypatch.setenv("L5_NV_EMBED_URL", "https://gw/v1/embeddings")
320
+ monkeypatch.setenv("L5_EMBED_API_KEY", "k")
321
+ client = EmbedClient.from_env(prefix="L5_")
322
+ assert client.active_provider == "openai"
323
+
324
+
325
+ def test_from_env_autodetect_opt_out(monkeypatch, recorder):
326
+ monkeypatch.setenv("L4_NV_EMBED_URL", "https://gw/v1/embeddings")
327
+ monkeypatch.setenv("L4_EMBED_API_KEY", "k")
328
+ monkeypatch.setenv("L4_EMBED_AUTODETECT", "false")
329
+ recorder.respond("https://gw/v1/embeddings", _FakeResponse(401, "x"))
330
+ client = EmbedClient.from_env(prefix="L4_")
331
+ with pytest.raises(EmbedAuthError):
332
+ client.embed_batch(["x"])
333
+ assert len(recorder.calls) == 1
334
+
335
+
336
+ # ----------------------------------------------------------------------
337
+ # URL handling
338
+ # ----------------------------------------------------------------------
339
+
340
+ def test_url_without_path_gets_provider_default(recorder):
341
+ """If operator provides only a base URL, the provider's path_default
342
+ is appended."""
343
+ recorder.respond(
344
+ "https://lambda-gateway.pentatonic.com/v1/embed",
345
+ _FakeResponse(200, {"data": [{"embedding": [0.0]}]}),
346
+ )
347
+ client = EmbedClient(
348
+ url="https://lambda-gateway.pentatonic.com",
349
+ api_key="k",
350
+ model="m",
351
+ provider=PROVIDERS["pentatonic-gateway"],
352
+ )
353
+ client.embed_batch(["x"])
354
+ assert recorder.calls[0]["url"] == "https://lambda-gateway.pentatonic.com/v1/embed"