aid-runtime-python 0.1.98__py3-none-any.whl → 0.1.100__py3-none-any.whl
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.
- aid_runtime/__init__.py +19 -1
- aid_runtime/providers/bedrock.py +16 -9
- aid_runtime/retrieval/__init__.py +38 -0
- aid_runtime/retrieval/knowledge_base.py +728 -0
- aid_runtime/retrieval/retriever.py +171 -36
- aid_runtime/retrieval/types.py +173 -1
- {aid_runtime_python-0.1.98.dist-info → aid_runtime_python-0.1.100.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.98.dist-info → aid_runtime_python-0.1.100.dist-info}/RECORD +10 -9
- {aid_runtime_python-0.1.98.dist-info → aid_runtime_python-0.1.100.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.98.dist-info → aid_runtime_python-0.1.100.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,728 @@
|
|
|
1
|
+
"""Reading a corpus an engine indexed, rather than one this process indexed.
|
|
2
|
+
|
|
3
|
+
A managed knowledge base inverts the retrieval pipeline. Locally, this runtime reads a
|
|
4
|
+
source, chunks it, embeds it and writes vectors; the retriever owns every step after the
|
|
5
|
+
source. With a managed base the engine owns all of them, and the runtime is left with one
|
|
6
|
+
operation -- *retrieve* -- plus the obligation to say when that operation cannot be
|
|
7
|
+
trusted.
|
|
8
|
+
|
|
9
|
+
Two decisions this module owns.
|
|
10
|
+
|
|
11
|
+
**Retrieve, never retrieve-and-generate.** Bedrock's ``RetrieveAndGenerate`` and Vertex's
|
|
12
|
+
``vertexRagStore`` tool both generate an answer inside the service. Using either would
|
|
13
|
+
create a second generation path that no model gate, no guardrail stage and no cost ledger
|
|
14
|
+
covers, so the runtime would be serving tokens it never measured. ``Retrieve`` and
|
|
15
|
+
``:retrieveContexts`` return passages, which is exactly what the existing ``retrieval``
|
|
16
|
+
step already consumes.
|
|
17
|
+
|
|
18
|
+
**A completed ingestion is a precondition, not an assumption.** A fresh ``apply`` creates
|
|
19
|
+
an empty corpus; the ingestion job fills it minutes later. A retrieve in that window
|
|
20
|
+
returns *nothing*, which a caller reads as "the corpus has no answer" rather than "the
|
|
21
|
+
corpus was never indexed". :meth:`BedrockKnowledgeBaseClient.retrieve` therefore asks for
|
|
22
|
+
the newest ingestion job once per base and refuses with
|
|
23
|
+
:class:`~aid_runtime.errors.ConfigurationError` naming the base when none has completed.
|
|
24
|
+
Vertex AI's ``ragCorpora`` exposes no comparable field -- an import is a long-running
|
|
25
|
+
operation the caller holds, not a property of the corpus -- so there the guarantee comes
|
|
26
|
+
from the fixture client and from the deployment gating traffic on the import. That
|
|
27
|
+
limitation is stated rather than hidden behind a poll that could never return false.
|
|
28
|
+
|
|
29
|
+
**Filters are refused, not dropped.** The spec carries filter expressions as opaque
|
|
30
|
+
strings, and the two engines disagree about what a string means. Bedrock's ``Retrieve``
|
|
31
|
+
takes a structured filter document; Vertex's takes an expression in its own language.
|
|
32
|
+
Translating between them is a compiler the plan excludes, and a filter that cannot be
|
|
33
|
+
applied is worse than no declaration: retrieving the *unfiltered* corpus silently widens
|
|
34
|
+
a tenant-scoped query to every tenant. Both clients therefore declare
|
|
35
|
+
``supports_filter_expressions = False``, the retriever refuses such a binding at
|
|
36
|
+
construction, and the py-fastapi validator refuses it at plan time. ``filterable`` still
|
|
37
|
+
matters -- it is what the deployment copies into the metadata sidecar a Bedrock S3 source
|
|
38
|
+
needs before any filter can match -- but nothing at run time pretends to apply one.
|
|
39
|
+
|
|
40
|
+
The client is a protocol, and one implementation reads a JSON fixture. That is what lets
|
|
41
|
+
``aid dev``, ``aid guard`` and the eval gate exercise a managed retriever with no
|
|
42
|
+
credentials and no network, which is the same reason the embedding seam has a fake.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import asyncio
|
|
48
|
+
import hashlib
|
|
49
|
+
import json
|
|
50
|
+
import os
|
|
51
|
+
import re
|
|
52
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
53
|
+
from dataclasses import dataclass, field
|
|
54
|
+
from datetime import UTC, datetime
|
|
55
|
+
from pathlib import Path
|
|
56
|
+
from typing import Any, Protocol
|
|
57
|
+
|
|
58
|
+
import httpx
|
|
59
|
+
|
|
60
|
+
from aid_runtime.errors import ConfigurationError, ProviderError, ProviderResponseError
|
|
61
|
+
from aid_runtime.providers.bedrock import BedrockProvider, rfc3986, sigv4_headers
|
|
62
|
+
from aid_runtime.providers.vertex import (
|
|
63
|
+
DEFAULT_VERTEX_LOCATION,
|
|
64
|
+
METADATA_TOKEN_URL,
|
|
65
|
+
VERTEX_TOKEN_ENV,
|
|
66
|
+
default_vertex_base_url,
|
|
67
|
+
)
|
|
68
|
+
from aid_runtime.retrieval.types import KnowledgeBaseEngine, KnowledgeBaseSpec
|
|
69
|
+
|
|
70
|
+
__all__ = [
|
|
71
|
+
"FIXTURE_ENV",
|
|
72
|
+
"BedrockKnowledgeBaseClient",
|
|
73
|
+
"FixtureKnowledgeBaseClient",
|
|
74
|
+
"KnowledgeBaseClient",
|
|
75
|
+
"KnowledgeChunk",
|
|
76
|
+
"KnowledgeResult",
|
|
77
|
+
"VertexKnowledgeBaseClient",
|
|
78
|
+
"knowledge_base_client_for",
|
|
79
|
+
"knowledge_base_env_id",
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
#: Names a JSON file the fixture client serves results from. Set by ``aid dev`` and by a
|
|
83
|
+
#: gate, so a managed retriever runs with no credentials and no network.
|
|
84
|
+
FIXTURE_ENV = "AID_KNOWLEDGE_BASE_FIXTURE"
|
|
85
|
+
|
|
86
|
+
_BEDROCK_PREFIX = "BEDROCK_KNOWLEDGE_BASE"
|
|
87
|
+
_VERTEX_PREFIX = "VERTEX_RAG_CORPUS"
|
|
88
|
+
_BEDROCK_SERVICE = "bedrock-agent-runtime"
|
|
89
|
+
_RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
|
|
90
|
+
_MAX_ERROR_BODY = 500
|
|
91
|
+
|
|
92
|
+
#: ``GET .../ingestionjobs?maxResults=1&sortOrder=DESCENDING``. The canonical query string
|
|
93
|
+
#: is sorted by key, which this literal already is, so it can be signed and sent as one.
|
|
94
|
+
_LATEST_JOB_QUERY = "maxResults=1&sortOrder=DESCENDING"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True, slots=True)
|
|
98
|
+
class KnowledgeChunk:
|
|
99
|
+
"""One passage the engine returned.
|
|
100
|
+
|
|
101
|
+
``source_uri`` is the engine's own location for the document, kept separate from
|
|
102
|
+
``chunk_id`` because two passages of one document share the former and must not share
|
|
103
|
+
the latter. ``position`` is the engine's ordinal within its result list, which is what
|
|
104
|
+
keeps two byte-identical passages distinct.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
text: str
|
|
108
|
+
source_uri: str
|
|
109
|
+
title: str | None = None
|
|
110
|
+
position: int = 0
|
|
111
|
+
score: float = 0.0
|
|
112
|
+
metadata: Mapping[str, str] = field(default_factory=dict)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def chunk_id(self) -> str:
|
|
116
|
+
"""Stable identity derived from what the engine returned.
|
|
117
|
+
|
|
118
|
+
A managed engine assigns no chunk id this side can recompute, so identity is
|
|
119
|
+
hashed from the source, the position and the text. It is therefore stable across
|
|
120
|
+
a replay of the same answer and unique across the passages of one answer, which
|
|
121
|
+
is all a citation list needs.
|
|
122
|
+
"""
|
|
123
|
+
payload = f"{self.source_uri}\x00{self.position}\x00{self.text}".encode()
|
|
124
|
+
return "kb_" + hashlib.sha256(payload).hexdigest()[:24]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass(frozen=True, slots=True)
|
|
128
|
+
class KnowledgeResult:
|
|
129
|
+
"""What one retrieve call returned, and what it cost.
|
|
130
|
+
|
|
131
|
+
``cost_usd`` is ``None`` when the engine's rate is unverified. The retriever charges
|
|
132
|
+
nothing in that case: recording a zero would make ``aid cost`` report a free call
|
|
133
|
+
rather than an unpriced one, and those are different claims.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
chunks: tuple[KnowledgeChunk, ...]
|
|
137
|
+
cost_usd: float | None = None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def knowledge_base_env_id(base: KnowledgeBaseSpec) -> str:
|
|
141
|
+
"""The environment name a deployment exports the base's service id under.
|
|
142
|
+
|
|
143
|
+
Named per base, not per engine: two bases on one provider are two resources, and one
|
|
144
|
+
shared name would make the second silently read the first. The CLI emits the same
|
|
145
|
+
spelling into the generated infrastructure, and a test pins the two together.
|
|
146
|
+
"""
|
|
147
|
+
prefix = _BEDROCK_PREFIX if base.engine is KnowledgeBaseEngine.AWS_BEDROCK else _VERTEX_PREFIX
|
|
148
|
+
slug = re.sub(r"[^A-Za-z0-9]+", "_", base.id).strip("_").upper()
|
|
149
|
+
return f"{prefix}_{slug}"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class KnowledgeBaseClient(Protocol):
|
|
153
|
+
"""The one operation the retriever makes, so a test double signs nothing."""
|
|
154
|
+
|
|
155
|
+
#: Whether ``retrieve`` may be handed ``filters``. A client that cannot apply the
|
|
156
|
+
#: spec's expressions sets this false, and the retriever refuses the binding instead
|
|
157
|
+
#: of letting a filter be dropped.
|
|
158
|
+
supports_filter_expressions: bool
|
|
159
|
+
|
|
160
|
+
async def retrieve(
|
|
161
|
+
self,
|
|
162
|
+
base: KnowledgeBaseSpec,
|
|
163
|
+
query: str,
|
|
164
|
+
*,
|
|
165
|
+
top_k: int,
|
|
166
|
+
filters: Sequence[str] = (),
|
|
167
|
+
) -> KnowledgeResult:
|
|
168
|
+
"""One retrieve against the base, with the filters the caller asked for."""
|
|
169
|
+
|
|
170
|
+
async def aclose(self) -> None:
|
|
171
|
+
"""Release whatever the client holds open."""
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class _HttpKnowledgeBaseClient:
|
|
175
|
+
"""Shared retry and teardown for the two hosted clients."""
|
|
176
|
+
|
|
177
|
+
supports_filter_expressions = False
|
|
178
|
+
|
|
179
|
+
def __init__(
|
|
180
|
+
self,
|
|
181
|
+
*,
|
|
182
|
+
client: httpx.AsyncClient | None,
|
|
183
|
+
timeout_seconds: float,
|
|
184
|
+
max_attempts: int,
|
|
185
|
+
backoff_seconds: float,
|
|
186
|
+
) -> None:
|
|
187
|
+
if max_attempts < 1:
|
|
188
|
+
raise ValueError("max_attempts must be at least 1")
|
|
189
|
+
self._owns_client = client is None
|
|
190
|
+
self._client = client or httpx.AsyncClient(timeout=timeout_seconds)
|
|
191
|
+
self._max_attempts = max_attempts
|
|
192
|
+
self._backoff = backoff_seconds
|
|
193
|
+
|
|
194
|
+
async def aclose(self) -> None:
|
|
195
|
+
if self._owns_client:
|
|
196
|
+
await self._client.aclose()
|
|
197
|
+
|
|
198
|
+
async def _send(
|
|
199
|
+
self,
|
|
200
|
+
method: str,
|
|
201
|
+
url: str,
|
|
202
|
+
*,
|
|
203
|
+
body: str | None = None,
|
|
204
|
+
headers: Mapping[str, str] | None = None,
|
|
205
|
+
) -> str:
|
|
206
|
+
last_error: Exception | None = None
|
|
207
|
+
for attempt in range(1, self._max_attempts + 1):
|
|
208
|
+
try:
|
|
209
|
+
response = await self._client.request(
|
|
210
|
+
method, url, content=body, headers=dict(headers or {})
|
|
211
|
+
)
|
|
212
|
+
except httpx.TransportError as exc:
|
|
213
|
+
last_error = exc
|
|
214
|
+
if attempt == self._max_attempts:
|
|
215
|
+
break
|
|
216
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
217
|
+
continue
|
|
218
|
+
if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
|
|
219
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
220
|
+
continue
|
|
221
|
+
if response.status_code >= 400:
|
|
222
|
+
raise ProviderError(
|
|
223
|
+
f"the knowledge base returned {response.status_code}: "
|
|
224
|
+
f"{response.text[:_MAX_ERROR_BODY]}"
|
|
225
|
+
)
|
|
226
|
+
return response.text
|
|
227
|
+
raise ProviderError(f"the knowledge base could not be reached: {last_error}")
|
|
228
|
+
|
|
229
|
+
@staticmethod
|
|
230
|
+
def _json(body: str, *, what: str = "knowledge base") -> Mapping[str, Any]:
|
|
231
|
+
try:
|
|
232
|
+
answer = json.loads(body)
|
|
233
|
+
except json.JSONDecodeError as exc:
|
|
234
|
+
raise ProviderResponseError(f"the {what} returned a non-JSON body", body) from exc
|
|
235
|
+
if not isinstance(answer, Mapping):
|
|
236
|
+
raise ProviderResponseError(f"the {what} returned no object", body)
|
|
237
|
+
return answer
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class BedrockKnowledgeBaseClient(_HttpKnowledgeBaseClient):
|
|
241
|
+
"""``POST /knowledgebases/{id}/retrieve`` on ``bedrock-agent-runtime``, with SigV4.
|
|
242
|
+
|
|
243
|
+
Readiness is checked lazily and cached: the first retrieve for a base asks AWS for the
|
|
244
|
+
newest ingestion job, and only a ``COMPLETE`` job lets the call through. Caching keeps
|
|
245
|
+
the check off the hot path; a restarted process re-checks, which is the conservative
|
|
246
|
+
direction.
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
def __init__(
|
|
250
|
+
self,
|
|
251
|
+
*,
|
|
252
|
+
provider: BedrockProvider | None = None,
|
|
253
|
+
region: str | None = None,
|
|
254
|
+
base_url: str | None = None,
|
|
255
|
+
client: httpx.AsyncClient | None = None,
|
|
256
|
+
timeout_seconds: float = 15.0,
|
|
257
|
+
max_attempts: int = 2,
|
|
258
|
+
backoff_seconds: float = 0.25,
|
|
259
|
+
now: Callable[[], datetime] | None = None,
|
|
260
|
+
) -> None:
|
|
261
|
+
super().__init__(
|
|
262
|
+
client=client,
|
|
263
|
+
timeout_seconds=timeout_seconds,
|
|
264
|
+
max_attempts=max_attempts,
|
|
265
|
+
backoff_seconds=backoff_seconds,
|
|
266
|
+
)
|
|
267
|
+
self._base_url = base_url.rstrip("/") if base_url is not None else None
|
|
268
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
269
|
+
self._owns_provider = provider is None
|
|
270
|
+
self._provider = provider or BedrockProvider(
|
|
271
|
+
region=region,
|
|
272
|
+
timeout_seconds=timeout_seconds,
|
|
273
|
+
max_attempts=1,
|
|
274
|
+
client=client,
|
|
275
|
+
name="bedrock-knowledge-base",
|
|
276
|
+
)
|
|
277
|
+
self._ready: set[str] = set()
|
|
278
|
+
|
|
279
|
+
def _resolve(self, base: KnowledgeBaseSpec) -> str:
|
|
280
|
+
value = os.environ.get(knowledge_base_env_id(base))
|
|
281
|
+
if not value:
|
|
282
|
+
raise ConfigurationError(
|
|
283
|
+
f"knowledge base {base.id!r} has no service id: the deployment writes "
|
|
284
|
+
f"{knowledge_base_env_id(base)}, and the app only names the resource"
|
|
285
|
+
)
|
|
286
|
+
return value
|
|
287
|
+
|
|
288
|
+
async def aclose(self) -> None:
|
|
289
|
+
if self._owns_provider:
|
|
290
|
+
await self._provider.aclose()
|
|
291
|
+
await super().aclose()
|
|
292
|
+
|
|
293
|
+
async def retrieve(
|
|
294
|
+
self,
|
|
295
|
+
base: KnowledgeBaseSpec,
|
|
296
|
+
query: str,
|
|
297
|
+
*,
|
|
298
|
+
top_k: int,
|
|
299
|
+
filters: Sequence[str] = (),
|
|
300
|
+
) -> KnowledgeResult:
|
|
301
|
+
knowledge_base_id = self._resolve(base)
|
|
302
|
+
await self._ensure_ingested(knowledge_base_id)
|
|
303
|
+
payload = json.dumps(
|
|
304
|
+
{
|
|
305
|
+
"retrievalQuery": {"text": query},
|
|
306
|
+
"retrievalConfiguration": {"vectorSearchConfiguration": {"numberOfResults": top_k}},
|
|
307
|
+
},
|
|
308
|
+
separators=(",", ":"),
|
|
309
|
+
)
|
|
310
|
+
body = await self._post(self._url(knowledge_base_id, "retrieve"), payload)
|
|
311
|
+
return KnowledgeResult(
|
|
312
|
+
chunks=_bedrock_chunks(self._json(body)),
|
|
313
|
+
cost_usd=base.retrieve_cost_per_query_usd,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
async def _ensure_ingested(self, knowledge_base_id: str) -> None:
|
|
317
|
+
if knowledge_base_id in self._ready:
|
|
318
|
+
return
|
|
319
|
+
data_source = await self._first_data_source(knowledge_base_id)
|
|
320
|
+
body = await self._get(
|
|
321
|
+
self._url(
|
|
322
|
+
knowledge_base_id,
|
|
323
|
+
f"datasources/{rfc3986(data_source)}/ingestionjobs",
|
|
324
|
+
),
|
|
325
|
+
query=_LATEST_JOB_QUERY,
|
|
326
|
+
)
|
|
327
|
+
status = _first_status(self._json(body).get("ingestionJobSummaries"))
|
|
328
|
+
if status != "COMPLETE":
|
|
329
|
+
raise ConfigurationError(
|
|
330
|
+
f"knowledge base {knowledge_base_id!r} has no completed ingestion job "
|
|
331
|
+
f"(latest status: {status or 'none'}); the corpus is empty until one "
|
|
332
|
+
"finishes, and an empty corpus reads as 'the answer is not in the corpus'"
|
|
333
|
+
)
|
|
334
|
+
self._ready.add(knowledge_base_id)
|
|
335
|
+
|
|
336
|
+
async def _first_data_source(self, knowledge_base_id: str) -> str:
|
|
337
|
+
body = await self._get(self._url(knowledge_base_id, "datasources"))
|
|
338
|
+
answer = self._json(body)
|
|
339
|
+
summaries = answer.get("dataSourceSummaries")
|
|
340
|
+
if not isinstance(summaries, Sequence) or isinstance(summaries, (str, bytes)):
|
|
341
|
+
raise ProviderResponseError("the knowledge base returned no data sources", body)
|
|
342
|
+
first = next((entry for entry in summaries if isinstance(entry, Mapping)), None)
|
|
343
|
+
data_source_id = first.get("dataSourceId") if first is not None else None
|
|
344
|
+
if not isinstance(data_source_id, str) or not data_source_id:
|
|
345
|
+
raise ConfigurationError(
|
|
346
|
+
f"knowledge base {knowledge_base_id!r} has no data source, so nothing "
|
|
347
|
+
"was ever uploaded to it"
|
|
348
|
+
)
|
|
349
|
+
return data_source_id
|
|
350
|
+
|
|
351
|
+
def _url(self, knowledge_base_id: str, suffix: str) -> str:
|
|
352
|
+
region = self._provider.resolve_region()
|
|
353
|
+
base = self._base_url or f"https://{_BEDROCK_SERVICE}.{region}.amazonaws.com"
|
|
354
|
+
return f"{base}/knowledgebases/{rfc3986(knowledge_base_id)}/{suffix}"
|
|
355
|
+
|
|
356
|
+
async def _get(self, url: str, *, query: str = "") -> str:
|
|
357
|
+
headers = sigv4_headers(
|
|
358
|
+
url=url,
|
|
359
|
+
body="",
|
|
360
|
+
region=self._provider.resolve_region(),
|
|
361
|
+
credentials=await self._provider.credentials(),
|
|
362
|
+
moment=self._now(),
|
|
363
|
+
service=_BEDROCK_SERVICE,
|
|
364
|
+
method="GET",
|
|
365
|
+
query=query,
|
|
366
|
+
)
|
|
367
|
+
return await self._send("GET", f"{url}?{query}" if query else url, headers=headers)
|
|
368
|
+
|
|
369
|
+
async def _post(self, url: str, payload: str) -> str:
|
|
370
|
+
headers = sigv4_headers(
|
|
371
|
+
url=url,
|
|
372
|
+
body=payload,
|
|
373
|
+
region=self._provider.resolve_region(),
|
|
374
|
+
credentials=await self._provider.credentials(),
|
|
375
|
+
moment=self._now(),
|
|
376
|
+
service=_BEDROCK_SERVICE,
|
|
377
|
+
)
|
|
378
|
+
return await self._send("POST", url, body=payload, headers=headers)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _first_status(summaries: Any) -> str | None:
|
|
382
|
+
if not isinstance(summaries, Sequence) or isinstance(summaries, (str, bytes)):
|
|
383
|
+
return None
|
|
384
|
+
for entry in summaries:
|
|
385
|
+
if isinstance(entry, Mapping):
|
|
386
|
+
status = entry.get("status")
|
|
387
|
+
if isinstance(status, str):
|
|
388
|
+
return status
|
|
389
|
+
return None
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _bedrock_chunks(answer: Mapping[str, Any]) -> tuple[KnowledgeChunk, ...]:
|
|
393
|
+
results = answer.get("retrievalResults")
|
|
394
|
+
if not isinstance(results, Sequence) or isinstance(results, (str, bytes)):
|
|
395
|
+
return ()
|
|
396
|
+
chunks: list[KnowledgeChunk] = []
|
|
397
|
+
for position, entry in enumerate(results):
|
|
398
|
+
if not isinstance(entry, Mapping):
|
|
399
|
+
continue
|
|
400
|
+
content = entry.get("content")
|
|
401
|
+
text = content.get("text") if isinstance(content, Mapping) else None
|
|
402
|
+
if not isinstance(text, str):
|
|
403
|
+
continue
|
|
404
|
+
score = entry.get("score")
|
|
405
|
+
chunks.append(
|
|
406
|
+
KnowledgeChunk(
|
|
407
|
+
text=text,
|
|
408
|
+
source_uri=_bedrock_uri(entry.get("location")),
|
|
409
|
+
position=position,
|
|
410
|
+
score=float(score) if isinstance(score, (int, float)) else 0.0,
|
|
411
|
+
metadata=_string_map(entry.get("metadata")),
|
|
412
|
+
)
|
|
413
|
+
)
|
|
414
|
+
return tuple(chunks)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _bedrock_uri(location: Any) -> str:
|
|
418
|
+
if not isinstance(location, Mapping):
|
|
419
|
+
return ""
|
|
420
|
+
for value in location.values():
|
|
421
|
+
if isinstance(value, Mapping):
|
|
422
|
+
uri = value.get("uri")
|
|
423
|
+
if isinstance(uri, str):
|
|
424
|
+
return uri
|
|
425
|
+
return ""
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _string_map(value: Any) -> Mapping[str, str]:
|
|
429
|
+
if not isinstance(value, Mapping):
|
|
430
|
+
return {}
|
|
431
|
+
return {str(key): str(item) for key, item in value.items()}
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
class VertexKnowledgeBaseClient(_HttpKnowledgeBaseClient):
|
|
435
|
+
"""``:retrieveContexts`` on a Vertex AI RAG corpus, with an OAuth2 bearer token.
|
|
436
|
+
|
|
437
|
+
The token is resolved per call from an explicit value, ``GOOGLE_ACCESS_TOKEN``, or the
|
|
438
|
+
metadata server, which is the same order the Vertex model adapter uses -- a service
|
|
439
|
+
that can call a Gemini model on Vertex can therefore also read its corpus.
|
|
440
|
+
"""
|
|
441
|
+
|
|
442
|
+
def __init__(
|
|
443
|
+
self,
|
|
444
|
+
*,
|
|
445
|
+
project: str | None = None,
|
|
446
|
+
location: str | None = None,
|
|
447
|
+
access_token: str | None = None,
|
|
448
|
+
base_url: str | None = None,
|
|
449
|
+
client: httpx.AsyncClient | None = None,
|
|
450
|
+
timeout_seconds: float = 15.0,
|
|
451
|
+
max_attempts: int = 2,
|
|
452
|
+
backoff_seconds: float = 0.25,
|
|
453
|
+
) -> None:
|
|
454
|
+
super().__init__(
|
|
455
|
+
client=client,
|
|
456
|
+
timeout_seconds=timeout_seconds,
|
|
457
|
+
max_attempts=max_attempts,
|
|
458
|
+
backoff_seconds=backoff_seconds,
|
|
459
|
+
)
|
|
460
|
+
self._project = project
|
|
461
|
+
self._location = location
|
|
462
|
+
self._access_token = access_token
|
|
463
|
+
self._base_url = base_url.rstrip("/") if base_url is not None else None
|
|
464
|
+
|
|
465
|
+
async def retrieve(
|
|
466
|
+
self,
|
|
467
|
+
base: KnowledgeBaseSpec,
|
|
468
|
+
query: str,
|
|
469
|
+
*,
|
|
470
|
+
top_k: int,
|
|
471
|
+
filters: Sequence[str] = (),
|
|
472
|
+
) -> KnowledgeResult:
|
|
473
|
+
corpus = os.environ.get(knowledge_base_env_id(base))
|
|
474
|
+
if not corpus:
|
|
475
|
+
raise ConfigurationError(
|
|
476
|
+
f"knowledge base {base.id!r} has no corpus id: the deployment writes "
|
|
477
|
+
f"{knowledge_base_env_id(base)}, and the app only names the resource"
|
|
478
|
+
)
|
|
479
|
+
location = self._resolve_location()
|
|
480
|
+
project = self._resolve_project()
|
|
481
|
+
payload = json.dumps(
|
|
482
|
+
{"query": {"text": query, "ragRetrievalConfig": {"topK": top_k}}},
|
|
483
|
+
separators=(",", ":"),
|
|
484
|
+
)
|
|
485
|
+
url = (
|
|
486
|
+
f"{self._base_url or default_vertex_base_url(location)}/v1/projects/"
|
|
487
|
+
f"{rfc3986(project)}/locations/{rfc3986(location)}/ragCorpora/"
|
|
488
|
+
f"{rfc3986(corpus)}:retrieveContexts"
|
|
489
|
+
)
|
|
490
|
+
body = await self._send(
|
|
491
|
+
"POST",
|
|
492
|
+
url,
|
|
493
|
+
body=payload,
|
|
494
|
+
headers={
|
|
495
|
+
"authorization": f"Bearer {await self._resolve_token()}",
|
|
496
|
+
"content-type": "application/json",
|
|
497
|
+
},
|
|
498
|
+
)
|
|
499
|
+
return KnowledgeResult(
|
|
500
|
+
chunks=_vertex_chunks(self._json(body)),
|
|
501
|
+
cost_usd=base.retrieve_cost_per_query_usd,
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
def _resolve_project(self) -> str:
|
|
505
|
+
if self._project:
|
|
506
|
+
return self._project
|
|
507
|
+
for key in ("GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "GOOGLE_PROJECT_ID"):
|
|
508
|
+
value = os.environ.get(key)
|
|
509
|
+
if value:
|
|
510
|
+
return value
|
|
511
|
+
raise ConfigurationError(
|
|
512
|
+
"a Vertex RAG corpus needs a project: set GOOGLE_CLOUD_PROJECT, or the "
|
|
513
|
+
"deployment's own project variable"
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
def _resolve_location(self) -> str:
|
|
517
|
+
if self._location:
|
|
518
|
+
return self._location
|
|
519
|
+
for key in ("GOOGLE_CLOUD_REGION", "VERTEX_LOCATION", "GOOGLE_CLOUD_LOCATION"):
|
|
520
|
+
value = os.environ.get(key)
|
|
521
|
+
if value:
|
|
522
|
+
return value
|
|
523
|
+
return DEFAULT_VERTEX_LOCATION
|
|
524
|
+
|
|
525
|
+
async def _resolve_token(self) -> str:
|
|
526
|
+
if self._access_token:
|
|
527
|
+
return self._access_token
|
|
528
|
+
token = os.environ.get(VERTEX_TOKEN_ENV)
|
|
529
|
+
if token:
|
|
530
|
+
return token
|
|
531
|
+
try:
|
|
532
|
+
response = await self._client.get(
|
|
533
|
+
METADATA_TOKEN_URL, headers={"Metadata-Flavor": "Google"}
|
|
534
|
+
)
|
|
535
|
+
except httpx.TransportError as exc:
|
|
536
|
+
raise ConfigurationError(
|
|
537
|
+
f"no OAuth2 token: set {VERTEX_TOKEN_ENV}, or run where the metadata "
|
|
538
|
+
"server can mint one"
|
|
539
|
+
) from exc
|
|
540
|
+
answer = self._json(response.text, what="metadata server")
|
|
541
|
+
value = answer.get("access_token")
|
|
542
|
+
if not isinstance(value, str) or not value:
|
|
543
|
+
raise ProviderResponseError(
|
|
544
|
+
"the metadata server returned no access token", json.dumps(answer)
|
|
545
|
+
)
|
|
546
|
+
return value
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _vertex_chunks(answer: Mapping[str, Any]) -> tuple[KnowledgeChunk, ...]:
|
|
550
|
+
"""Vertex nests each passage under ``contexts[].chunk.text``.
|
|
551
|
+
|
|
552
|
+
``sourceUri`` sits on the context, not the chunk, so provenance is read one level up
|
|
553
|
+
from the text it describes.
|
|
554
|
+
"""
|
|
555
|
+
contexts = answer.get("contexts")
|
|
556
|
+
entries = contexts.get("contexts") if isinstance(contexts, Mapping) else None
|
|
557
|
+
if not isinstance(entries, Sequence) or isinstance(entries, (str, bytes)):
|
|
558
|
+
return ()
|
|
559
|
+
chunks: list[KnowledgeChunk] = []
|
|
560
|
+
for position, entry in enumerate(entries):
|
|
561
|
+
if not isinstance(entry, Mapping):
|
|
562
|
+
continue
|
|
563
|
+
chunk = entry.get("chunk")
|
|
564
|
+
text = chunk.get("text") if isinstance(chunk, Mapping) else None
|
|
565
|
+
if not isinstance(text, str):
|
|
566
|
+
text = entry.get("text")
|
|
567
|
+
if not isinstance(text, str):
|
|
568
|
+
continue
|
|
569
|
+
score = chunk.get("relevanceScore") if isinstance(chunk, Mapping) else None
|
|
570
|
+
uri = entry.get("sourceUri")
|
|
571
|
+
chunks.append(
|
|
572
|
+
KnowledgeChunk(
|
|
573
|
+
text=text,
|
|
574
|
+
source_uri=uri if isinstance(uri, str) else "",
|
|
575
|
+
title=entry.get("sourceDisplayName")
|
|
576
|
+
if isinstance(entry.get("sourceDisplayName"), str)
|
|
577
|
+
else None,
|
|
578
|
+
position=position,
|
|
579
|
+
score=float(score) if isinstance(score, (int, float)) else 0.0,
|
|
580
|
+
)
|
|
581
|
+
)
|
|
582
|
+
return tuple(chunks)
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
class FixtureKnowledgeBaseClient:
|
|
586
|
+
"""A ``KnowledgeBaseClient`` that reads recorded answers from one JSON file.
|
|
587
|
+
|
|
588
|
+
The file is keyed by knowledge base id:
|
|
589
|
+
|
|
590
|
+
.. code-block:: json
|
|
591
|
+
|
|
592
|
+
{"bases": {"product-docs": {"ready": true,
|
|
593
|
+
"chunks": [{"text": "...", "sourceUri": "s3://bucket/doc.md", "score": 0.9}]}}}
|
|
594
|
+
|
|
595
|
+
``ready`` is what makes the missing-ingestion failure testable offline: a fixture can
|
|
596
|
+
describe a base that was deployed but never indexed, and the retriever then fails with
|
|
597
|
+
the same message the hosted client raises.
|
|
598
|
+
"""
|
|
599
|
+
|
|
600
|
+
supports_filter_expressions = False
|
|
601
|
+
|
|
602
|
+
def __init__(
|
|
603
|
+
self,
|
|
604
|
+
payload: Mapping[str, Any] | None = None,
|
|
605
|
+
*,
|
|
606
|
+
path: str | Path | None = None,
|
|
607
|
+
) -> None:
|
|
608
|
+
if payload is None:
|
|
609
|
+
if path is None:
|
|
610
|
+
raise ConfigurationError(
|
|
611
|
+
f"a fixture knowledge base needs a payload or a path; set {FIXTURE_ENV} "
|
|
612
|
+
"to the JSON file the run should read"
|
|
613
|
+
)
|
|
614
|
+
try:
|
|
615
|
+
raw = Path(path).read_text(encoding="utf-8")
|
|
616
|
+
except OSError as exc:
|
|
617
|
+
raise ConfigurationError(
|
|
618
|
+
f"the knowledge base fixture {path!s} cannot be read: {exc}"
|
|
619
|
+
) from exc
|
|
620
|
+
try:
|
|
621
|
+
payload = json.loads(raw)
|
|
622
|
+
except json.JSONDecodeError as exc:
|
|
623
|
+
raise ConfigurationError(
|
|
624
|
+
f"the knowledge base fixture {path!s} is not valid JSON: {exc}"
|
|
625
|
+
) from exc
|
|
626
|
+
if not isinstance(payload, Mapping):
|
|
627
|
+
raise ConfigurationError("a knowledge base fixture must be a JSON object")
|
|
628
|
+
bases = payload.get("bases")
|
|
629
|
+
if not isinstance(bases, Mapping):
|
|
630
|
+
raise ConfigurationError(
|
|
631
|
+
"a knowledge base fixture must carry a 'bases' object keyed by base id"
|
|
632
|
+
)
|
|
633
|
+
self._bases: Mapping[str, Any] = bases
|
|
634
|
+
|
|
635
|
+
async def aclose(self) -> None:
|
|
636
|
+
return None
|
|
637
|
+
|
|
638
|
+
async def retrieve(
|
|
639
|
+
self,
|
|
640
|
+
base: KnowledgeBaseSpec,
|
|
641
|
+
query: str,
|
|
642
|
+
*,
|
|
643
|
+
top_k: int,
|
|
644
|
+
filters: Sequence[str] = (),
|
|
645
|
+
) -> KnowledgeResult:
|
|
646
|
+
entry = self._bases.get(base.id)
|
|
647
|
+
if not isinstance(entry, Mapping):
|
|
648
|
+
raise ConfigurationError(
|
|
649
|
+
f"knowledge base {base.id!r} has no fixture entry; add one under "
|
|
650
|
+
f"'bases.{base.id}' or run against the real engine"
|
|
651
|
+
)
|
|
652
|
+
if entry.get("ready") is not True:
|
|
653
|
+
raise ConfigurationError(
|
|
654
|
+
f"knowledge base {base.id!r} has no completed ingestion job "
|
|
655
|
+
f"(latest status: {entry.get('status') or 'none'}); the corpus is empty "
|
|
656
|
+
"until one finishes, and an empty corpus reads as 'the answer is not in "
|
|
657
|
+
"the corpus'"
|
|
658
|
+
)
|
|
659
|
+
chunks = _fixture_chunks(entry.get("chunks"))
|
|
660
|
+
return KnowledgeResult(
|
|
661
|
+
chunks=chunks[:top_k],
|
|
662
|
+
cost_usd=base.retrieve_cost_per_query_usd,
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _fixture_chunks(value: Any) -> tuple[KnowledgeChunk, ...]:
|
|
667
|
+
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
|
|
668
|
+
return ()
|
|
669
|
+
chunks: list[KnowledgeChunk] = []
|
|
670
|
+
for position, entry in enumerate(value):
|
|
671
|
+
if not isinstance(entry, Mapping):
|
|
672
|
+
continue
|
|
673
|
+
text = entry.get("text")
|
|
674
|
+
if not isinstance(text, str):
|
|
675
|
+
continue
|
|
676
|
+
score = entry.get("score")
|
|
677
|
+
source_uri = entry.get("sourceUri")
|
|
678
|
+
title = entry.get("title")
|
|
679
|
+
chunks.append(
|
|
680
|
+
KnowledgeChunk(
|
|
681
|
+
text=text,
|
|
682
|
+
source_uri=source_uri if isinstance(source_uri, str) else "",
|
|
683
|
+
title=title if isinstance(title, str) else None,
|
|
684
|
+
position=position,
|
|
685
|
+
score=float(score) if isinstance(score, (int, float)) else 0.0,
|
|
686
|
+
metadata=_string_map(entry.get("metadata")),
|
|
687
|
+
)
|
|
688
|
+
)
|
|
689
|
+
return tuple(chunks)
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def knowledge_base_client_for(
|
|
693
|
+
base: KnowledgeBaseSpec,
|
|
694
|
+
*,
|
|
695
|
+
fixture: str | Path | None = None,
|
|
696
|
+
client: httpx.AsyncClient | None = None,
|
|
697
|
+
region: str | None = None,
|
|
698
|
+
project: str | None = None,
|
|
699
|
+
location: str | None = None,
|
|
700
|
+
access_token: str | None = None,
|
|
701
|
+
base_url: str | None = None,
|
|
702
|
+
timeout_seconds: float = 15.0,
|
|
703
|
+
) -> KnowledgeBaseClient:
|
|
704
|
+
"""Pick the adapter for one base.
|
|
705
|
+
|
|
706
|
+
A fixture path -- explicit, or ``AID_KNOWLEDGE_BASE_FIXTURE`` -- wins over the engine,
|
|
707
|
+
for the same reason ``fake`` wins in :func:`~aid_runtime.retrieval.embedding.embedder_for`:
|
|
708
|
+
a gate has to run keyless and offline, and the engine's identity is not a thing the
|
|
709
|
+
spec may lie about to get there.
|
|
710
|
+
"""
|
|
711
|
+
path = fixture if fixture is not None else os.environ.get(FIXTURE_ENV)
|
|
712
|
+
if path:
|
|
713
|
+
return FixtureKnowledgeBaseClient(path=path)
|
|
714
|
+
if base.engine is KnowledgeBaseEngine.AWS_BEDROCK:
|
|
715
|
+
return BedrockKnowledgeBaseClient(
|
|
716
|
+
region=region,
|
|
717
|
+
base_url=base_url,
|
|
718
|
+
client=client,
|
|
719
|
+
timeout_seconds=timeout_seconds,
|
|
720
|
+
)
|
|
721
|
+
return VertexKnowledgeBaseClient(
|
|
722
|
+
project=project,
|
|
723
|
+
location=location,
|
|
724
|
+
access_token=access_token,
|
|
725
|
+
base_url=base_url,
|
|
726
|
+
client=client,
|
|
727
|
+
timeout_seconds=timeout_seconds,
|
|
728
|
+
)
|