aid-runtime-python 0.1.96__tar.gz → 0.1.97__tar.gz
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_python-0.1.96 → aid_runtime_python-0.1.97}/PKG-INFO +1 -1
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/pyproject.toml +1 -1
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/__init__.py +9 -1
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/providers/__init__.py +14 -4
- aid_runtime_python-0.1.97/src/aid_runtime/providers/gemini.py +113 -0
- aid_runtime_python-0.1.97/src/aid_runtime/providers/gemini_wire.py +345 -0
- aid_runtime_python-0.1.97/src/aid_runtime/providers/vertex.py +200 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/__init__.py +2 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/embedding.py +182 -29
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime_python.egg-info/SOURCES.txt +3 -0
- aid_runtime_python-0.1.97/tests/test_gemini_provider.py +246 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_embedding.py +123 -0
- aid_runtime_python-0.1.96/src/aid_runtime/providers/vertex.py +0 -448
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/README.md +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/setup.cfg +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/__init__.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/chat_model.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/deep_agents.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/engine.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/guardrails.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/ir.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/loop.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/memory.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/policy.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/agents/state.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/cache.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/concurrency.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/control.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/cost.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/decisions.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/errors.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/evals/__init__.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/evals/dataset.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/evals/gate.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/evals/metrics.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/evals/predicate.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/evals/runner.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/gateway.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/local_trace.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/pipeline.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/prompts.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/providers/anthropic.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/providers/base.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/providers/bedrock.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/providers/fake.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/providers/http.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/py.typed +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/chunking.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/citations.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/connectors.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/gate.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/hybrid.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/metrics.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/pgvector.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/rerank.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/retriever.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/stores.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/retrieval/types.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/steps.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/structured.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/tools.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/tracing.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/types.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime_python.egg-info/requires.txt +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_agents_budget.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_agents_deep_agents.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_agents_hitl.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_agents_loop.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_agents_memory.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_anthropic_provider.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_bedrock_provider.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_cache.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_concurrency.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_control.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_cost.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_dataset.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_decisions.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_evals.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_evals_assert_gate.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_evals_decision.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_evals_gate.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_evals_predicate.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_gateway.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_guardrails.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_http_provider.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_local_trace.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_package.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_pipeline.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_prompts.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_chunking.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_citations.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_connectors.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_gate.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_hybrid.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_metrics.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_rerank.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_stores.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_retrieval_types.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_steps.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_streaming.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_structured.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_tool_permissions.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_tools.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_tracing.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_types.py +0 -0
- {aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/tests/test_vertex_provider.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: aid-runtime-python
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.97
|
|
4
4
|
Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
|
|
5
5
|
Author: The AID Framework authors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "aid-runtime-python"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.97"
|
|
8
8
|
description = "The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -160,12 +160,15 @@ from aid_runtime.providers import (
|
|
|
160
160
|
BEDROCK_SERVICE,
|
|
161
161
|
DEFAULT_ANTHROPIC_BASE_URL,
|
|
162
162
|
DEFAULT_BASE_URL,
|
|
163
|
+
DEFAULT_GEMINI_BASE_URL,
|
|
163
164
|
DEFAULT_VERTEX_LOCATION,
|
|
165
|
+
GEMINI_API_KEY_ENV,
|
|
164
166
|
METADATA_TOKEN_URL,
|
|
165
167
|
VERTEX_TOKEN_ENV,
|
|
166
168
|
AnthropicProvider,
|
|
167
169
|
BedrockProvider,
|
|
168
170
|
FakeProvider,
|
|
171
|
+
GeminiProvider,
|
|
169
172
|
OpenAICompatibleProvider,
|
|
170
173
|
Provider,
|
|
171
174
|
ScriptedTurn,
|
|
@@ -191,6 +194,7 @@ from aid_runtime.retrieval import (
|
|
|
191
194
|
FakeDeterministicEmbedder,
|
|
192
195
|
FileConnector,
|
|
193
196
|
FixedChunker,
|
|
197
|
+
GeminiEmbedder,
|
|
194
198
|
IndexSpec,
|
|
195
199
|
IngestReport,
|
|
196
200
|
InMemoryVectorStore,
|
|
@@ -297,7 +301,7 @@ from aid_runtime.types import (
|
|
|
297
301
|
)
|
|
298
302
|
|
|
299
303
|
#: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
|
|
300
|
-
__version__ = "0.1.
|
|
304
|
+
__version__ = "0.1.97"
|
|
301
305
|
|
|
302
306
|
__all__ = [
|
|
303
307
|
"ANTHROPIC_VERSION",
|
|
@@ -306,10 +310,12 @@ __all__ = [
|
|
|
306
310
|
"DEFAULT_ANTHROPIC_BASE_URL",
|
|
307
311
|
"DEFAULT_BASE_URL",
|
|
308
312
|
"DEFAULT_CANDIDATE_FACTOR",
|
|
313
|
+
"DEFAULT_GEMINI_BASE_URL",
|
|
309
314
|
"DEFAULT_TYPESAFE_BASE_URL",
|
|
310
315
|
"DEFAULT_VERTEX_LOCATION",
|
|
311
316
|
"DEPTH_KEY",
|
|
312
317
|
"EMITTED_KEY",
|
|
318
|
+
"GEMINI_API_KEY_ENV",
|
|
313
319
|
"GEN_AI_OPERATION_CHAT",
|
|
314
320
|
"INDEX_KEY",
|
|
315
321
|
"ITEM_KEY",
|
|
@@ -387,6 +393,8 @@ __all__ = [
|
|
|
387
393
|
"GateConfigurationError",
|
|
388
394
|
"GateResult",
|
|
389
395
|
"GatewayRunner",
|
|
396
|
+
"GeminiEmbedder",
|
|
397
|
+
"GeminiProvider",
|
|
390
398
|
"GenerationResult",
|
|
391
399
|
"GuardrailBlockedError",
|
|
392
400
|
"HumanApproval",
|
{aid_runtime_python-0.1.96 → aid_runtime_python-0.1.97}/src/aid_runtime/providers/__init__.py
RENAMED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"""Provider adapters.
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Five wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM
|
|
4
4
|
and Azure's compatible endpoint), Anthropic's Messages API, Amazon Bedrock's
|
|
5
|
-
Converse API, and
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
Converse API, and Gemini's ``generateContent`` -- which the Vertex AI adapter
|
|
6
|
+
serves over an OAuth2 bearer token and the Gemini API adapter serves with one API
|
|
7
|
+
key. Bedrock is signed with SigV4 and Vertex is OAuth2-bearer, which is why
|
|
8
|
+
neither can be an OpenAI-compatible base URL. A sixth, deterministic fake serves
|
|
9
|
+
tests and the eval-gate fixture.
|
|
8
10
|
"""
|
|
9
11
|
|
|
10
12
|
from __future__ import annotations
|
|
@@ -22,6 +24,11 @@ from aid_runtime.providers.bedrock import (
|
|
|
22
24
|
rfc3986,
|
|
23
25
|
)
|
|
24
26
|
from aid_runtime.providers.fake import FakeProvider, ScriptedTurn
|
|
27
|
+
from aid_runtime.providers.gemini import (
|
|
28
|
+
DEFAULT_GEMINI_BASE_URL,
|
|
29
|
+
GEMINI_API_KEY_ENV,
|
|
30
|
+
GeminiProvider,
|
|
31
|
+
)
|
|
25
32
|
from aid_runtime.providers.http import DEFAULT_BASE_URL, OpenAICompatibleProvider
|
|
26
33
|
from aid_runtime.providers.vertex import (
|
|
27
34
|
DEFAULT_VERTEX_LOCATION,
|
|
@@ -36,12 +43,15 @@ __all__ = [
|
|
|
36
43
|
"BEDROCK_SERVICE",
|
|
37
44
|
"DEFAULT_ANTHROPIC_BASE_URL",
|
|
38
45
|
"DEFAULT_BASE_URL",
|
|
46
|
+
"DEFAULT_GEMINI_BASE_URL",
|
|
39
47
|
"DEFAULT_VERTEX_LOCATION",
|
|
48
|
+
"GEMINI_API_KEY_ENV",
|
|
40
49
|
"METADATA_TOKEN_URL",
|
|
41
50
|
"VERTEX_TOKEN_ENV",
|
|
42
51
|
"AnthropicProvider",
|
|
43
52
|
"BedrockProvider",
|
|
44
53
|
"FakeProvider",
|
|
54
|
+
"GeminiProvider",
|
|
45
55
|
"OpenAICompatibleProvider",
|
|
46
56
|
"Provider",
|
|
47
57
|
"ScriptedTurn",
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Gemini API adapter -- the public Gemini service, not Vertex AI.
|
|
2
|
+
|
|
3
|
+
Same wire as Vertex (``contents`` of ``parts``, ``functionDeclarations``,
|
|
4
|
+
``systemInstruction``), so the translation lives in ``gemini_wire``. What differs is
|
|
5
|
+
everything around it: one API key instead of an OAuth2 token, a fixed host with no
|
|
6
|
+
project or location, and the ``v1beta`` endpoint.
|
|
7
|
+
|
|
8
|
+
The API key travels in ``x-goog-api-key`` rather than a query string. Google's own
|
|
9
|
+
docs offer ``?key=`` as well, but a query string ends up in access logs, proxy
|
|
10
|
+
history and error reports far more readily than a header does.
|
|
11
|
+
|
|
12
|
+
A wrong key comes back as ``400 FAILED_PRECONDITION``, so 400 is never retried.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
from aid_runtime.errors import ProviderError, ProviderResponseError
|
|
22
|
+
from aid_runtime.providers.gemini_wire import (
|
|
23
|
+
GeminiWireClient,
|
|
24
|
+
build_payload,
|
|
25
|
+
decode_body,
|
|
26
|
+
read_candidate,
|
|
27
|
+
)
|
|
28
|
+
from aid_runtime.types import (
|
|
29
|
+
Capability,
|
|
30
|
+
CompletionRequest,
|
|
31
|
+
CompletionResponse,
|
|
32
|
+
ModelSpec,
|
|
33
|
+
TokenUsage,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
__all__ = ["DEFAULT_GEMINI_BASE_URL", "GEMINI_API_KEY_ENV", "GeminiProvider"]
|
|
37
|
+
|
|
38
|
+
DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com"
|
|
39
|
+
GEMINI_API_KEY_ENV = "GEMINI_API_KEY"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class GeminiProvider(GeminiWireClient):
|
|
43
|
+
"""Gemini over ``generateContent`` / ``streamGenerateContent``.
|
|
44
|
+
|
|
45
|
+
``DEFAULT_RETRYABLE_STATUS`` deliberately omits 400: this service answers
|
|
46
|
+
``400 FAILED_PRECONDITION`` for a bad API key, and retrying that only spends money.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
*,
|
|
52
|
+
api_key: str | None = None,
|
|
53
|
+
base_url: str | None = None,
|
|
54
|
+
name: str = "gemini",
|
|
55
|
+
timeout_seconds: float = 60.0,
|
|
56
|
+
max_attempts: int = 3,
|
|
57
|
+
backoff_seconds: float = 0.5,
|
|
58
|
+
client: httpx.AsyncClient | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__(
|
|
61
|
+
name=name,
|
|
62
|
+
timeout_seconds=timeout_seconds,
|
|
63
|
+
max_attempts=max_attempts,
|
|
64
|
+
backoff_seconds=backoff_seconds,
|
|
65
|
+
client=client,
|
|
66
|
+
)
|
|
67
|
+
self._api_key = api_key
|
|
68
|
+
self._base_url = base_url
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def capabilities(self) -> frozenset[Capability]:
|
|
72
|
+
return frozenset(
|
|
73
|
+
{Capability.STREAMING, Capability.STRUCTURED_OUTPUT, Capability.TOOL_CALLING}
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
|
|
77
|
+
body = await self._post(self._url(model, stream=False), build_payload(request, model))
|
|
78
|
+
return self._parse(body, model)
|
|
79
|
+
|
|
80
|
+
def _url(self, model: ModelSpec, *, stream: bool) -> str:
|
|
81
|
+
base = (self._base_url or DEFAULT_GEMINI_BASE_URL).rstrip("/")
|
|
82
|
+
method = "streamGenerateContent?alt=sse" if stream else "generateContent"
|
|
83
|
+
return f"{base}/v1beta/models/{model.name}:{method}"
|
|
84
|
+
|
|
85
|
+
async def _headers(self) -> dict[str, str]:
|
|
86
|
+
return {
|
|
87
|
+
"x-goog-api-key": self._key(),
|
|
88
|
+
"content-type": "application/json",
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
def _key(self) -> str:
|
|
92
|
+
if self._api_key:
|
|
93
|
+
return self._api_key
|
|
94
|
+
env_key = os.environ.get(GEMINI_API_KEY_ENV)
|
|
95
|
+
if env_key:
|
|
96
|
+
return env_key
|
|
97
|
+
raise ProviderError(
|
|
98
|
+
f"{self._name} has no API key: set model provider 'apiKeyEnv' or {GEMINI_API_KEY_ENV}"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def _parse(self, text: str, model: ModelSpec) -> CompletionResponse:
|
|
102
|
+
body = decode_body(text, self._name)
|
|
103
|
+
result, calls, reason, usage = read_candidate(body, model)
|
|
104
|
+
if result == "" and not calls and reason is None:
|
|
105
|
+
raise ProviderResponseError(f"{self._name} returned no candidates", text)
|
|
106
|
+
return CompletionResponse(
|
|
107
|
+
text=result,
|
|
108
|
+
model=model.name,
|
|
109
|
+
provider=self._name,
|
|
110
|
+
usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
|
|
111
|
+
tool_calls=tuple(calls),
|
|
112
|
+
finish_reason=reason or ("tool-calls" if calls else "stop"),
|
|
113
|
+
)
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
"""The Gemini wire dialect shared by the Vertex and Gemini API adapters.
|
|
2
|
+
|
|
3
|
+
Both services take the same request body -- ``contents`` of ``parts``, Google-shaped
|
|
4
|
+
tool declarations, ``systemInstruction``, ``generationConfig`` -- and answer with the
|
|
5
|
+
same ``candidates`` and ``usageMetadata``. They differ only in the endpoint, the
|
|
6
|
+
credentials and the embedding method, so the translation and the retry loop live here
|
|
7
|
+
once and each adapter supplies its URL and auth headers. A test builds one request
|
|
8
|
+
through both adapters and asserts the bodies are byte-identical, which is what keeps
|
|
9
|
+
these functions honest.
|
|
10
|
+
|
|
11
|
+
This module is internal: it is not re-exported from ``aid_runtime``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import AsyncIterator
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from aid_runtime.errors import ProviderError, ProviderResponseError
|
|
24
|
+
from aid_runtime.types import (
|
|
25
|
+
CompletionRequest,
|
|
26
|
+
FinishReason,
|
|
27
|
+
Message,
|
|
28
|
+
ModelSpec,
|
|
29
|
+
StreamChunk,
|
|
30
|
+
TokenUsage,
|
|
31
|
+
ToolCall,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"DEFAULT_RETRYABLE_STATUS",
|
|
36
|
+
"GeminiWireClient",
|
|
37
|
+
"build_payload",
|
|
38
|
+
"decode_body",
|
|
39
|
+
"finish_reason",
|
|
40
|
+
"read_candidate",
|
|
41
|
+
"system_prompt",
|
|
42
|
+
"usage",
|
|
43
|
+
"wire_contents",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
DEFAULT_RETRYABLE_STATUS = frozenset({408, 409, 424, 425, 429, 500, 502, 503, 504})
|
|
47
|
+
|
|
48
|
+
FINISH_REASONS: dict[str, FinishReason] = {
|
|
49
|
+
"STOP": "stop",
|
|
50
|
+
"MAX_TOKENS": "length",
|
|
51
|
+
"SAFETY": "content-filter",
|
|
52
|
+
"RECITATION": "content-filter",
|
|
53
|
+
"BLOCKLIST": "content-filter",
|
|
54
|
+
"PROHIBITED_CONTENT": "content-filter",
|
|
55
|
+
"SPII": "content-filter",
|
|
56
|
+
"MALFORMED_FUNCTION_CALL": "error",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def build_payload(request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
|
|
61
|
+
"""Translate a completion request into the body both Gemini endpoints accept."""
|
|
62
|
+
generation_config: dict[str, Any] = {"maxOutputTokens": _max_tokens(request, model)}
|
|
63
|
+
if request.temperature is not None:
|
|
64
|
+
generation_config["temperature"] = request.temperature
|
|
65
|
+
if request.stop:
|
|
66
|
+
generation_config["stopSequences"] = list(request.stop)
|
|
67
|
+
payload: dict[str, Any] = {
|
|
68
|
+
"contents": wire_contents(request.messages),
|
|
69
|
+
"generationConfig": generation_config,
|
|
70
|
+
}
|
|
71
|
+
system = system_prompt(request.messages)
|
|
72
|
+
if system:
|
|
73
|
+
payload["systemInstruction"] = {"parts": [{"text": system}]}
|
|
74
|
+
if request.tools:
|
|
75
|
+
payload["tools"] = [
|
|
76
|
+
{
|
|
77
|
+
"functionDeclarations": [
|
|
78
|
+
{
|
|
79
|
+
"name": tool.name,
|
|
80
|
+
"description": tool.description,
|
|
81
|
+
"parameters": tool.parameters or {"type": "object", "properties": {}},
|
|
82
|
+
}
|
|
83
|
+
for tool in request.tools
|
|
84
|
+
]
|
|
85
|
+
}
|
|
86
|
+
]
|
|
87
|
+
return payload
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def wire_contents(messages: tuple[Message, ...]) -> list[dict[str, Any]]:
|
|
91
|
+
"""Render the message list as ``contents``; system turns move to ``systemInstruction``."""
|
|
92
|
+
contents: list[dict[str, Any]] = []
|
|
93
|
+
for message in messages:
|
|
94
|
+
if message.role == "system":
|
|
95
|
+
continue
|
|
96
|
+
if message.role == "tool":
|
|
97
|
+
contents.append(
|
|
98
|
+
{
|
|
99
|
+
"role": "user",
|
|
100
|
+
"parts": [
|
|
101
|
+
{
|
|
102
|
+
"functionResponse": {
|
|
103
|
+
"name": message.name or "tool",
|
|
104
|
+
"response": {"content": message.content},
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
],
|
|
108
|
+
}
|
|
109
|
+
)
|
|
110
|
+
continue
|
|
111
|
+
parts: list[dict[str, Any]] = []
|
|
112
|
+
if message.content:
|
|
113
|
+
parts.append({"text": message.content})
|
|
114
|
+
for call in message.tool_calls:
|
|
115
|
+
parts.append({"functionCall": {"name": call.name, "args": call.arguments}})
|
|
116
|
+
if not parts:
|
|
117
|
+
parts.append({"text": ""})
|
|
118
|
+
contents.append(
|
|
119
|
+
{"role": "model" if message.role == "assistant" else "user", "parts": parts}
|
|
120
|
+
)
|
|
121
|
+
return contents
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def system_prompt(messages: tuple[Message, ...]) -> str:
|
|
125
|
+
return "\n".join(message.content for message in messages if message.role == "system")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def finish_reason(raw: str) -> FinishReason:
|
|
129
|
+
return FINISH_REASONS.get(raw, "stop")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def usage(body: dict[str, Any]) -> TokenUsage | None:
|
|
133
|
+
raw = body.get("usageMetadata")
|
|
134
|
+
if not isinstance(raw, dict):
|
|
135
|
+
return None
|
|
136
|
+
return TokenUsage(
|
|
137
|
+
input_tokens=int(raw.get("promptTokenCount") or 0),
|
|
138
|
+
output_tokens=int(raw.get("candidatesTokenCount") or 0),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def read_candidate(
|
|
143
|
+
body: dict[str, Any], model: ModelSpec
|
|
144
|
+
) -> tuple[str, list[ToolCall], FinishReason | None, TokenUsage | None]:
|
|
145
|
+
"""Read the first candidate into text, calls, finish reason and usage."""
|
|
146
|
+
candidates = body.get("candidates")
|
|
147
|
+
candidate = candidates[0] if isinstance(candidates, list) and candidates else None
|
|
148
|
+
content = candidate.get("content") if isinstance(candidate, dict) else None
|
|
149
|
+
parts = content.get("parts") if isinstance(content, dict) else None
|
|
150
|
+
|
|
151
|
+
text_parts: list[str] = []
|
|
152
|
+
calls: list[ToolCall] = []
|
|
153
|
+
if isinstance(parts, list):
|
|
154
|
+
for index, part in enumerate(parts):
|
|
155
|
+
if not isinstance(part, dict):
|
|
156
|
+
continue
|
|
157
|
+
value = part.get("text")
|
|
158
|
+
if isinstance(value, str):
|
|
159
|
+
text_parts.append(value)
|
|
160
|
+
continue
|
|
161
|
+
call = part.get("functionCall")
|
|
162
|
+
if not isinstance(call, dict):
|
|
163
|
+
continue
|
|
164
|
+
name = call.get("name")
|
|
165
|
+
if not isinstance(name, str) or not name:
|
|
166
|
+
continue
|
|
167
|
+
arguments = call.get("args")
|
|
168
|
+
calls.append(
|
|
169
|
+
ToolCall(
|
|
170
|
+
id=f"{model.name}-call-{index}",
|
|
171
|
+
name=name,
|
|
172
|
+
arguments=arguments if isinstance(arguments, dict) else {},
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
reason: FinishReason | None = None
|
|
177
|
+
raw_reason = candidate.get("finishReason") if isinstance(candidate, dict) else None
|
|
178
|
+
if isinstance(raw_reason, str):
|
|
179
|
+
reason = finish_reason(raw_reason)
|
|
180
|
+
|
|
181
|
+
# Gemini reports the reason alongside the call; the call is the better signal.
|
|
182
|
+
if calls and reason in (None, "stop"):
|
|
183
|
+
reason = "tool-calls"
|
|
184
|
+
return "".join(text_parts), calls, reason, usage(body)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def decode_body(text: str, provider: str) -> dict[str, Any]:
|
|
188
|
+
"""Parse a non-streamed body, refusing anything that is not a JSON object."""
|
|
189
|
+
try:
|
|
190
|
+
body = json.loads(text)
|
|
191
|
+
except json.JSONDecodeError as exc:
|
|
192
|
+
raise ProviderResponseError(f"{provider} returned a body that is not JSON", text) from exc
|
|
193
|
+
if not isinstance(body, dict):
|
|
194
|
+
raise ProviderResponseError(f"{provider} returned a JSON body that is not an object", text)
|
|
195
|
+
return body
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _max_tokens(request: CompletionRequest, model: ModelSpec) -> int:
|
|
199
|
+
if request.max_output_tokens is not None:
|
|
200
|
+
return min(request.max_output_tokens, model.max_output_tokens)
|
|
201
|
+
return model.max_output_tokens
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class GeminiWireClient:
|
|
205
|
+
"""The HTTP half of the Gemini dialect; adapters supply ``_url`` and ``_headers``.
|
|
206
|
+
|
|
207
|
+
The retry policy is per adapter because a status means different things to each
|
|
208
|
+
service: a transport failure or a 429 is worth another attempt on both, but the
|
|
209
|
+
Gemini API also answers ``400 FAILED_PRECONDITION`` for a bad key, so callers must
|
|
210
|
+
be able to narrow ``_retryable_status`` without touching this loop.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
def __init__(
|
|
214
|
+
self,
|
|
215
|
+
*,
|
|
216
|
+
name: str,
|
|
217
|
+
timeout_seconds: float = 60.0,
|
|
218
|
+
max_attempts: int = 3,
|
|
219
|
+
backoff_seconds: float = 0.5,
|
|
220
|
+
client: httpx.AsyncClient | None = None,
|
|
221
|
+
) -> None:
|
|
222
|
+
self._name = name
|
|
223
|
+
self._timeout = timeout_seconds
|
|
224
|
+
self._max_attempts = max_attempts
|
|
225
|
+
self._backoff = backoff_seconds
|
|
226
|
+
self._client = client
|
|
227
|
+
self._owns_client = client is None
|
|
228
|
+
self._retryable_status = DEFAULT_RETRYABLE_STATUS
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def name(self) -> str:
|
|
232
|
+
return self._name
|
|
233
|
+
|
|
234
|
+
async def aclose(self) -> None:
|
|
235
|
+
if self._client is not None and self._owns_client:
|
|
236
|
+
await self._client.aclose()
|
|
237
|
+
self._client = None
|
|
238
|
+
|
|
239
|
+
def _ensure_client(self) -> httpx.AsyncClient:
|
|
240
|
+
if self._client is None:
|
|
241
|
+
self._client = httpx.AsyncClient(timeout=self._timeout)
|
|
242
|
+
self._owns_client = True
|
|
243
|
+
return self._client
|
|
244
|
+
|
|
245
|
+
def _url(self, model: ModelSpec, *, stream: bool) -> str:
|
|
246
|
+
raise NotImplementedError
|
|
247
|
+
|
|
248
|
+
async def _headers(self) -> dict[str, str]:
|
|
249
|
+
raise NotImplementedError
|
|
250
|
+
|
|
251
|
+
async def stream(
|
|
252
|
+
self, request: CompletionRequest, *, model: ModelSpec
|
|
253
|
+
) -> AsyncIterator[StreamChunk]:
|
|
254
|
+
client = self._ensure_client()
|
|
255
|
+
headers = await self._headers()
|
|
256
|
+
payload = build_payload(request, model)
|
|
257
|
+
url = self._url(model, stream=True)
|
|
258
|
+
|
|
259
|
+
usage: TokenUsage | None = None
|
|
260
|
+
finish: FinishReason | None = None
|
|
261
|
+
last_error: Exception | None = None
|
|
262
|
+
for attempt in range(1, self._max_attempts + 1):
|
|
263
|
+
try:
|
|
264
|
+
async with client.stream("POST", url, json=payload, headers=headers) as response:
|
|
265
|
+
if (
|
|
266
|
+
response.status_code in self._retryable_status
|
|
267
|
+
and attempt < self._max_attempts
|
|
268
|
+
):
|
|
269
|
+
last_error = ProviderError(f"{self._name} returned {response.status_code}")
|
|
270
|
+
await response.aread()
|
|
271
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
272
|
+
continue
|
|
273
|
+
if response.status_code >= 400:
|
|
274
|
+
detail = (await response.aread()).decode("utf-8", "replace")
|
|
275
|
+
raise ProviderError(
|
|
276
|
+
f"{self._name} returned {response.status_code}: {detail[:500]}"
|
|
277
|
+
)
|
|
278
|
+
async for line in response.aiter_lines():
|
|
279
|
+
if not line.startswith("data:"):
|
|
280
|
+
continue
|
|
281
|
+
data = line[len("data:") :].strip()
|
|
282
|
+
if not data or data == "[DONE]":
|
|
283
|
+
continue
|
|
284
|
+
try:
|
|
285
|
+
chunk = json.loads(data)
|
|
286
|
+
except json.JSONDecodeError as exc:
|
|
287
|
+
raise ProviderResponseError(
|
|
288
|
+
f"{self._name} streamed non-JSON", data
|
|
289
|
+
) from exc
|
|
290
|
+
if not isinstance(chunk, dict):
|
|
291
|
+
continue
|
|
292
|
+
text, _calls, reason, chunk_usage = read_candidate(chunk, model)
|
|
293
|
+
if chunk_usage is not None:
|
|
294
|
+
usage = chunk_usage
|
|
295
|
+
if reason is not None:
|
|
296
|
+
finish = reason
|
|
297
|
+
if text:
|
|
298
|
+
yield StreamChunk(delta=text)
|
|
299
|
+
except httpx.TransportError as exc:
|
|
300
|
+
last_error = exc
|
|
301
|
+
if attempt == self._max_attempts:
|
|
302
|
+
break
|
|
303
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
304
|
+
continue
|
|
305
|
+
else:
|
|
306
|
+
yield StreamChunk(
|
|
307
|
+
finish_reason=finish or "stop",
|
|
308
|
+
usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
|
|
309
|
+
)
|
|
310
|
+
return
|
|
311
|
+
|
|
312
|
+
raise ProviderError(
|
|
313
|
+
f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
|
|
314
|
+
) from last_error
|
|
315
|
+
|
|
316
|
+
async def _post(self, url: str, payload: dict[str, Any]) -> str:
|
|
317
|
+
client = self._ensure_client()
|
|
318
|
+
headers = await self._headers()
|
|
319
|
+
last_error: Exception | None = None
|
|
320
|
+
for attempt in range(1, self._max_attempts + 1):
|
|
321
|
+
try:
|
|
322
|
+
response = await client.post(url, json=payload, headers=headers)
|
|
323
|
+
except httpx.TransportError as exc:
|
|
324
|
+
last_error = exc
|
|
325
|
+
if attempt == self._max_attempts:
|
|
326
|
+
break
|
|
327
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
328
|
+
continue
|
|
329
|
+
|
|
330
|
+
if response.status_code in self._retryable_status and attempt < self._max_attempts:
|
|
331
|
+
last_error = ProviderError(
|
|
332
|
+
f"{self._name} returned {response.status_code}: {response.text[:500]}"
|
|
333
|
+
)
|
|
334
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
335
|
+
continue
|
|
336
|
+
|
|
337
|
+
if response.status_code >= 400:
|
|
338
|
+
raise ProviderError(
|
|
339
|
+
f"{self._name} returned {response.status_code}: {response.text[:500]}"
|
|
340
|
+
)
|
|
341
|
+
return response.text
|
|
342
|
+
|
|
343
|
+
raise ProviderError(
|
|
344
|
+
f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
|
|
345
|
+
) from last_error
|