aid-runtime-python 0.1.80__tar.gz → 0.1.82__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.
Files changed (102) hide show
  1. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/PKG-INFO +1 -1
  2. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/pyproject.toml +1 -1
  3. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/__init__.py +14 -4
  4. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/providers/__init__.py +17 -6
  5. aid_runtime_python-0.1.82/src/aid_runtime/providers/vertex.py +448 -0
  6. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
  7. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime_python.egg-info/SOURCES.txt +3 -1
  8. aid_runtime_python-0.1.82/tests/test_vertex_provider.py +447 -0
  9. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/README.md +0 -0
  10. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/setup.cfg +0 -0
  11. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/__init__.py +0 -0
  12. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/chat_model.py +0 -0
  13. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/deep_agents.py +0 -0
  14. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/engine.py +0 -0
  15. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/guardrails.py +0 -0
  16. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/ir.py +0 -0
  17. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/loop.py +0 -0
  18. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/memory.py +0 -0
  19. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/policy.py +0 -0
  20. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/agents/state.py +0 -0
  21. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/cache.py +0 -0
  22. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/concurrency.py +0 -0
  23. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/control.py +0 -0
  24. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/cost.py +0 -0
  25. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/errors.py +0 -0
  26. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/evals/__init__.py +0 -0
  27. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/evals/dataset.py +0 -0
  28. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/evals/gate.py +0 -0
  29. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/evals/metrics.py +0 -0
  30. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/evals/predicate.py +0 -0
  31. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/evals/runner.py +0 -0
  32. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/gateway.py +0 -0
  33. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/local_trace.py +0 -0
  34. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/pipeline.py +0 -0
  35. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/prompts.py +0 -0
  36. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/providers/anthropic.py +0 -0
  37. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/providers/base.py +0 -0
  38. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/providers/bedrock.py +0 -0
  39. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/providers/fake.py +0 -0
  40. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/providers/http.py +0 -0
  41. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/py.typed +0 -0
  42. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/__init__.py +0 -0
  43. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/chunking.py +0 -0
  44. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/citations.py +0 -0
  45. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/connectors.py +0 -0
  46. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/embedding.py +0 -0
  47. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/gate.py +0 -0
  48. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/hybrid.py +0 -0
  49. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/metrics.py +0 -0
  50. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/pgvector.py +0 -0
  51. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/rerank.py +0 -0
  52. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/retriever.py +0 -0
  53. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/stores.py +0 -0
  54. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/retrieval/types.py +0 -0
  55. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/steps.py +0 -0
  56. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/structured.py +0 -0
  57. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/tools.py +0 -0
  58. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/tracing.py +0 -0
  59. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime/types.py +0 -0
  60. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
  61. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime_python.egg-info/requires.txt +0 -0
  62. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
  63. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_agents_budget.py +0 -0
  64. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_agents_deep_agents.py +0 -0
  65. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_agents_hitl.py +0 -0
  66. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_agents_loop.py +0 -0
  67. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_agents_memory.py +0 -0
  68. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_anthropic_provider.py +0 -0
  69. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_bedrock_provider.py +0 -0
  70. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_cache.py +0 -0
  71. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_concurrency.py +0 -0
  72. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_control.py +0 -0
  73. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_cost.py +0 -0
  74. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_dataset.py +0 -0
  75. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_evals.py +0 -0
  76. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_evals_assert_gate.py +0 -0
  77. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_evals_gate.py +0 -0
  78. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_evals_predicate.py +0 -0
  79. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_gateway.py +0 -0
  80. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_guardrails.py +0 -0
  81. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_http_provider.py +0 -0
  82. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_local_trace.py +0 -0
  83. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_package.py +0 -0
  84. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_pipeline.py +0 -0
  85. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_prompts.py +0 -0
  86. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_chunking.py +0 -0
  87. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_citations.py +0 -0
  88. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_connectors.py +0 -0
  89. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_embedding.py +0 -0
  90. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_gate.py +0 -0
  91. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_hybrid.py +0 -0
  92. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_metrics.py +0 -0
  93. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_rerank.py +0 -0
  94. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_stores.py +0 -0
  95. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_retrieval_types.py +0 -0
  96. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_steps.py +0 -0
  97. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_streaming.py +0 -0
  98. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_structured.py +0 -0
  99. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_tool_permissions.py +0 -0
  100. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_tools.py +0 -0
  101. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_tracing.py +0 -0
  102. {aid_runtime_python-0.1.80 → aid_runtime_python-0.1.82}/tests/test_types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.80
3
+ Version: 0.1.82
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.80"
7
+ version = "0.1.82"
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"
@@ -17,10 +17,10 @@ Design boundaries worth stating up front, because they are deliberate:
17
17
  ``data`` frames with the first delta before completion. Anything not advertising
18
18
  the capability raises :class:`~aid_runtime.errors.CapabilityMismatchError`
19
19
  instead of pretending to stream.
20
- * **One narrow adapter seam, three dialects, and a fake.** Breadth of vendor
20
+ * **One narrow adapter seam, four dialects, and a fake.** Breadth of vendor
21
21
  coverage stays a later concern; a correct seam is worth more than a wide shallow
22
- one. Three dialects ship: OpenAI-compatible, Anthropic Messages, and Bedrock
23
- Converse, alongside a deterministic fake that lets the eval gate run offline.
22
+ one. Four dialects ship: OpenAI-compatible, Anthropic Messages, Bedrock Converse,
23
+ and Vertex AI, alongside a deterministic fake that lets the eval gate run offline.
24
24
  """
25
25
 
26
26
  from __future__ import annotations
@@ -145,13 +145,18 @@ from aid_runtime.providers import (
145
145
  BEDROCK_SERVICE,
146
146
  DEFAULT_ANTHROPIC_BASE_URL,
147
147
  DEFAULT_BASE_URL,
148
+ DEFAULT_VERTEX_LOCATION,
149
+ METADATA_TOKEN_URL,
150
+ VERTEX_TOKEN_ENV,
148
151
  AnthropicProvider,
149
152
  BedrockProvider,
150
153
  FakeProvider,
151
154
  OpenAICompatibleProvider,
152
155
  Provider,
153
156
  ScriptedTurn,
157
+ VertexProvider,
154
158
  default_bedrock_base_url,
159
+ default_vertex_base_url,
155
160
  )
156
161
  from aid_runtime.retrieval import (
157
162
  DEFAULT_CANDIDATE_FACTOR,
@@ -277,7 +282,7 @@ from aid_runtime.types import (
277
282
  )
278
283
 
279
284
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
280
- __version__ = "0.1.80"
285
+ __version__ = "0.1.82"
281
286
 
282
287
  __all__ = [
283
288
  "ANTHROPIC_VERSION",
@@ -286,6 +291,7 @@ __all__ = [
286
291
  "DEFAULT_ANTHROPIC_BASE_URL",
287
292
  "DEFAULT_BASE_URL",
288
293
  "DEFAULT_CANDIDATE_FACTOR",
294
+ "DEFAULT_VERTEX_LOCATION",
289
295
  "DEPTH_KEY",
290
296
  "EMITTED_KEY",
291
297
  "GEN_AI_OPERATION_CHAT",
@@ -293,11 +299,13 @@ __all__ = [
293
299
  "ITEM_KEY",
294
300
  "LIMITER_KEY",
295
301
  "MAX_STEP_DEPTH",
302
+ "METADATA_TOKEN_URL",
296
303
  "PRINCIPAL_KEY",
297
304
  "REDUCED_KEY",
298
305
  "RESERVED_KEYS",
299
306
  "STEPS_KEY",
300
307
  "TRACE_DIR_ENV",
308
+ "VERTEX_TOKEN_ENV",
301
309
  "AgentBudgetDegradedError",
302
310
  "AgentCheckpoint",
303
311
  "AgentDefinition",
@@ -455,6 +463,7 @@ __all__ = [
455
463
  "UnknownModelAliasError",
456
464
  "VectorStore",
457
465
  "VectorStoreSpec",
466
+ "VertexProvider",
458
467
  "__version__",
459
468
  "agent_span",
460
469
  "aid_attributes",
@@ -471,6 +480,7 @@ __all__ = [
471
480
  "create_store",
472
481
  "default_bedrock_base_url",
473
482
  "default_metrics",
483
+ "default_vertex_base_url",
474
484
  "embedder_for",
475
485
  "emit_step",
476
486
  "estimate_cost_usd",
@@ -1,11 +1,10 @@
1
1
  """Provider adapters.
2
2
 
3
- Three wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM and
4
- Azure's compatible endpoint), Anthropic's Messages API, and Amazon Bedrock's
5
- Converse API, plus one deterministic fake for tests and the eval-gate fixture.
6
- Bedrock is signed with SigV4 rather than keyed, which is why it cannot be an
7
- OpenAI-compatible base URL. Vertex is a transport adapter over the same seam and
8
- is still out of scope.
3
+ Four wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM
4
+ and Azure's compatible endpoint), Anthropic's Messages API, Amazon Bedrock's
5
+ Converse API, and Vertex AI's ``generateContent``. Bedrock is signed with SigV4
6
+ and Vertex is OAuth2-bearer, which is why neither can be an OpenAI-compatible
7
+ base URL. A fifth, deterministic fake serves tests and the eval-gate fixture.
9
8
  """
10
9
 
11
10
  from __future__ import annotations
@@ -24,18 +23,30 @@ from aid_runtime.providers.bedrock import (
24
23
  )
25
24
  from aid_runtime.providers.fake import FakeProvider, ScriptedTurn
26
25
  from aid_runtime.providers.http import DEFAULT_BASE_URL, OpenAICompatibleProvider
26
+ from aid_runtime.providers.vertex import (
27
+ DEFAULT_VERTEX_LOCATION,
28
+ METADATA_TOKEN_URL,
29
+ VERTEX_TOKEN_ENV,
30
+ VertexProvider,
31
+ default_vertex_base_url,
32
+ )
27
33
 
28
34
  __all__ = [
29
35
  "ANTHROPIC_VERSION",
30
36
  "BEDROCK_SERVICE",
31
37
  "DEFAULT_ANTHROPIC_BASE_URL",
32
38
  "DEFAULT_BASE_URL",
39
+ "DEFAULT_VERTEX_LOCATION",
40
+ "METADATA_TOKEN_URL",
41
+ "VERTEX_TOKEN_ENV",
33
42
  "AnthropicProvider",
34
43
  "BedrockProvider",
35
44
  "FakeProvider",
36
45
  "OpenAICompatibleProvider",
37
46
  "Provider",
38
47
  "ScriptedTurn",
48
+ "VertexProvider",
39
49
  "default_bedrock_base_url",
50
+ "default_vertex_base_url",
40
51
  "rfc3986",
41
52
  ]
@@ -0,0 +1,448 @@
1
+ """Vertex AI adapter for Gemini models.
2
+
3
+ Vertex speaks its own dialect: ``contents`` of ``parts`` rather than messages,
4
+ Google-shaped tool declarations, and a dedicated streaming endpoint. It is
5
+ authenticated with an OAuth2 bearer token, not an API key -- the token is
6
+ resolved once per call from an explicit value, an environment variable, or the
7
+ GCE metadata server that Cloud Run and Cloud Functions provide.
8
+
9
+ Deliberately no cryptography dependency: on GCP the metadata server mints the
10
+ token, and off GCP a developer supplies one (``gcloud auth print-access-token``).
11
+ A service-account JSON file would need RS256 signing, which is a dependency the
12
+ runtime does not otherwise carry.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import json
19
+ import os
20
+ from collections.abc import AsyncIterator, Awaitable, Callable
21
+ from typing import Any
22
+
23
+ import httpx
24
+
25
+ from aid_runtime.errors import ProviderError, ProviderResponseError
26
+ from aid_runtime.types import (
27
+ Capability,
28
+ CompletionRequest,
29
+ CompletionResponse,
30
+ FinishReason,
31
+ Message,
32
+ ModelSpec,
33
+ StreamChunk,
34
+ TokenUsage,
35
+ ToolCall,
36
+ )
37
+
38
+ __all__ = [
39
+ "DEFAULT_VERTEX_LOCATION",
40
+ "METADATA_TOKEN_URL",
41
+ "VERTEX_TOKEN_ENV",
42
+ "VertexProvider",
43
+ "default_vertex_base_url",
44
+ ]
45
+
46
+ DEFAULT_VERTEX_LOCATION = "us-central1"
47
+ METADATA_TOKEN_URL = (
48
+ "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" # noqa: S105
49
+ )
50
+ VERTEX_TOKEN_ENV = "GOOGLE_ACCESS_TOKEN" # noqa: S105
51
+
52
+ _RETRYABLE_STATUS = frozenset({408, 409, 424, 425, 429, 500, 502, 503, 504})
53
+ _FINISH_REASONS: dict[str, FinishReason] = {
54
+ "STOP": "stop",
55
+ "MAX_TOKENS": "length",
56
+ "SAFETY": "content-filter",
57
+ "RECITATION": "content-filter",
58
+ "BLOCKLIST": "content-filter",
59
+ "PROHIBITED_CONTENT": "content-filter",
60
+ "SPII": "content-filter",
61
+ "MALFORMED_FUNCTION_CALL": "error",
62
+ }
63
+
64
+
65
+ def default_vertex_base_url(location: str) -> str:
66
+ return f"https://{location}-aiplatform.googleapis.com"
67
+
68
+
69
+ class VertexProvider:
70
+ """Gemini on Vertex AI over ``generateContent`` / ``streamGenerateContent``."""
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ project: str | None = None,
76
+ location: str | None = None,
77
+ access_token: str | None = None,
78
+ base_url: str | None = None,
79
+ name: str = "google",
80
+ timeout_seconds: float = 60.0,
81
+ max_attempts: int = 3,
82
+ backoff_seconds: float = 0.5,
83
+ client: httpx.AsyncClient | None = None,
84
+ token_provider: Callable[[], Awaitable[str]] | None = None,
85
+ ) -> None:
86
+ self._name = name
87
+ self._project = project
88
+ self._location = location
89
+ self._access_token = access_token
90
+ self._base_url = base_url
91
+ self._timeout = timeout_seconds
92
+ self._max_attempts = max_attempts
93
+ self._backoff = backoff_seconds
94
+ self._client = client
95
+ self._owns_client = client is None
96
+ self._token_provider = token_provider
97
+ self._cached_token: tuple[str, float] | None = None
98
+
99
+ @property
100
+ def name(self) -> str:
101
+ return self._name
102
+
103
+ @property
104
+ def capabilities(self) -> frozenset[Capability]:
105
+ return frozenset(
106
+ {Capability.STREAMING, Capability.STRUCTURED_OUTPUT, Capability.TOOL_CALLING}
107
+ )
108
+
109
+ async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
110
+ body = await self._post(self._url(model, stream=False), self._build_payload(request, model))
111
+ return self._parse(body, model)
112
+
113
+ async def stream(
114
+ self, request: CompletionRequest, *, model: ModelSpec
115
+ ) -> AsyncIterator[StreamChunk]:
116
+ client = self._ensure_client()
117
+ headers = await self._headers()
118
+ payload = self._build_payload(request, model)
119
+ url = self._url(model, stream=True)
120
+
121
+ usage: TokenUsage | None = None
122
+ finish: FinishReason | None = None
123
+ last_error: Exception | None = None
124
+ for attempt in range(1, self._max_attempts + 1):
125
+ try:
126
+ async with client.stream("POST", url, json=payload, headers=headers) as response:
127
+ if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
128
+ last_error = ProviderError(f"{self._name} returned {response.status_code}")
129
+ await response.aread()
130
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
131
+ continue
132
+ if response.status_code >= 400:
133
+ detail = (await response.aread()).decode("utf-8", "replace")
134
+ raise ProviderError(
135
+ f"{self._name} returned {response.status_code}: {detail[:500]}"
136
+ )
137
+ async for line in response.aiter_lines():
138
+ if not line.startswith("data:"):
139
+ continue
140
+ data = line[len("data:") :].strip()
141
+ if not data or data == "[DONE]":
142
+ continue
143
+ try:
144
+ chunk = json.loads(data)
145
+ except json.JSONDecodeError as exc:
146
+ raise ProviderResponseError(
147
+ f"{self._name} streamed non-JSON", data
148
+ ) from exc
149
+ if not isinstance(chunk, dict):
150
+ continue
151
+ text, _calls, reason, chunk_usage = _read_candidate(chunk, model)
152
+ if chunk_usage is not None:
153
+ usage = chunk_usage
154
+ if reason is not None:
155
+ finish = reason
156
+ if text:
157
+ yield StreamChunk(delta=text)
158
+ except httpx.TransportError as exc:
159
+ last_error = exc
160
+ if attempt == self._max_attempts:
161
+ break
162
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
163
+ continue
164
+ else:
165
+ yield StreamChunk(
166
+ finish_reason=finish or "stop",
167
+ usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
168
+ )
169
+ return
170
+
171
+ raise ProviderError(
172
+ f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
173
+ ) from last_error
174
+
175
+ async def aclose(self) -> None:
176
+ if self._client is not None and self._owns_client:
177
+ await self._client.aclose()
178
+ self._client = None
179
+
180
+ def _ensure_client(self) -> httpx.AsyncClient:
181
+ if self._client is None:
182
+ self._client = httpx.AsyncClient(timeout=self._timeout)
183
+ self._owns_client = True
184
+ return self._client
185
+
186
+ def _resolve_project(self) -> str:
187
+ if self._project:
188
+ return self._project
189
+ for key in ("GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "GOOGLE_PROJECT_ID"):
190
+ value = _env(key)
191
+ if value:
192
+ return value
193
+ raise ProviderError(
194
+ f"{self._name} needs a project: set model provider 'project' or GOOGLE_CLOUD_PROJECT"
195
+ )
196
+
197
+ def _resolve_location(self) -> str:
198
+ if self._location:
199
+ return self._location
200
+ for key in ("GOOGLE_CLOUD_REGION", "VERTEX_LOCATION", "GOOGLE_CLOUD_LOCATION"):
201
+ value = _env(key)
202
+ if value:
203
+ return value
204
+ return DEFAULT_VERTEX_LOCATION
205
+
206
+ def _url(self, model: ModelSpec, *, stream: bool) -> str:
207
+ location = self._resolve_location()
208
+ base = (self._base_url or default_vertex_base_url(location)).rstrip("/")
209
+ project = self._resolve_project()
210
+ method = "streamGenerateContent?alt=sse" if stream else "generateContent"
211
+ return (
212
+ f"{base}/v1/projects/{project}/locations/{location}"
213
+ f"/publishers/google/models/{model.name}:{method}"
214
+ )
215
+
216
+ async def _token(self) -> str:
217
+ if self._access_token:
218
+ return self._access_token
219
+ env_token = _env(VERTEX_TOKEN_ENV) or _env("VERTEX_ACCESS_TOKEN")
220
+ if env_token:
221
+ return env_token
222
+ if self._cached_token is not None:
223
+ token, expires_at = self._cached_token
224
+ if expires_at - asyncio.get_running_loop().time() > 60:
225
+ return token
226
+ token, expires_in = await self._mint_token()
227
+ self._cached_token = (token, asyncio.get_running_loop().time() + expires_in)
228
+ return token
229
+
230
+ async def _mint_token(self) -> tuple[str, float]:
231
+ if self._token_provider is not None:
232
+ return await self._token_provider(), 300.0
233
+
234
+ client = self._ensure_client()
235
+ try:
236
+ response = await client.get(METADATA_TOKEN_URL, headers={"Metadata-Flavor": "Google"})
237
+ except httpx.TransportError as exc:
238
+ raise ProviderError(
239
+ f"{self._name} has no credentials: set {VERTEX_TOKEN_ENV} or run on GCP "
240
+ f"where the metadata server mints a token ({exc})"
241
+ ) from exc
242
+ if response.status_code >= 400:
243
+ raise ProviderError(
244
+ f"{self._name} metadata token request returned {response.status_code}: "
245
+ f"{response.text[:200]}"
246
+ )
247
+ try:
248
+ body = response.json()
249
+ except json.JSONDecodeError as exc:
250
+ raise ProviderResponseError(
251
+ f"{self._name} metadata token is not JSON", response.text
252
+ ) from exc
253
+ token = body.get("access_token") if isinstance(body, dict) else None
254
+ if not isinstance(token, str) or not token:
255
+ raise ProviderResponseError(
256
+ f"{self._name} metadata response had no access_token", response.text
257
+ )
258
+ expires_in = body.get("expires_in", 300)
259
+ return token, float(expires_in) if isinstance(expires_in, (int, float)) else 300.0
260
+
261
+ async def _headers(self) -> dict[str, str]:
262
+ return {
263
+ "authorization": f"Bearer {await self._token()}",
264
+ "content-type": "application/json",
265
+ }
266
+
267
+ def _build_payload(self, request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
268
+ generation_config: dict[str, Any] = {"maxOutputTokens": _max_tokens(request, model)}
269
+ if request.temperature is not None:
270
+ generation_config["temperature"] = request.temperature
271
+ if request.stop:
272
+ generation_config["stopSequences"] = list(request.stop)
273
+ payload: dict[str, Any] = {
274
+ "contents": _wire_contents(request.messages),
275
+ "generationConfig": generation_config,
276
+ }
277
+ system = _system_prompt(request.messages)
278
+ if system:
279
+ payload["systemInstruction"] = {"parts": [{"text": system}]}
280
+ if request.tools:
281
+ payload["tools"] = [
282
+ {
283
+ "functionDeclarations": [
284
+ {
285
+ "name": tool.name,
286
+ "description": tool.description,
287
+ "parameters": tool.parameters or {"type": "object", "properties": {}},
288
+ }
289
+ for tool in request.tools
290
+ ]
291
+ }
292
+ ]
293
+ return payload
294
+
295
+ async def _post(self, url: str, payload: dict[str, Any]) -> str:
296
+ client = self._ensure_client()
297
+ headers = await self._headers()
298
+ last_error: Exception | None = None
299
+ for attempt in range(1, self._max_attempts + 1):
300
+ try:
301
+ response = await client.post(url, json=payload, headers=headers)
302
+ except httpx.TransportError as exc:
303
+ last_error = exc
304
+ if attempt == self._max_attempts:
305
+ break
306
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
307
+ continue
308
+
309
+ if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
310
+ last_error = ProviderError(
311
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
312
+ )
313
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
314
+ continue
315
+
316
+ if response.status_code >= 400:
317
+ raise ProviderError(
318
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
319
+ )
320
+ return response.text
321
+
322
+ raise ProviderError(
323
+ f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
324
+ ) from last_error
325
+
326
+ def _parse(self, text: str, model: ModelSpec) -> CompletionResponse:
327
+ try:
328
+ body = json.loads(text)
329
+ except json.JSONDecodeError as exc:
330
+ raise ProviderResponseError(
331
+ f"{self._name} returned a body that is not JSON", text
332
+ ) from exc
333
+ if not isinstance(body, dict):
334
+ raise ProviderResponseError(
335
+ f"{self._name} returned a JSON body that is not an object", text
336
+ )
337
+ result, calls, reason, usage = _read_candidate(body, model)
338
+ if result == "" and not calls and reason is None:
339
+ raise ProviderResponseError(f"{self._name} returned no candidates", text)
340
+ return CompletionResponse(
341
+ text=result,
342
+ model=model.name,
343
+ provider=self._name,
344
+ usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
345
+ tool_calls=tuple(calls),
346
+ finish_reason=reason or ("tool-calls" if calls else "stop"),
347
+ )
348
+
349
+
350
+ def _read_candidate(
351
+ body: dict[str, Any], model: ModelSpec
352
+ ) -> tuple[str, list[ToolCall], FinishReason | None, TokenUsage | None]:
353
+ """Read the first candidate into text, calls, finish reason and usage."""
354
+ candidates = body.get("candidates")
355
+ candidate = candidates[0] if isinstance(candidates, list) and candidates else None
356
+ content = candidate.get("content") if isinstance(candidate, dict) else None
357
+ parts = content.get("parts") if isinstance(content, dict) else None
358
+
359
+ text_parts: list[str] = []
360
+ calls: list[ToolCall] = []
361
+ if isinstance(parts, list):
362
+ for index, part in enumerate(parts):
363
+ if not isinstance(part, dict):
364
+ continue
365
+ value = part.get("text")
366
+ if isinstance(value, str):
367
+ text_parts.append(value)
368
+ continue
369
+ call = part.get("functionCall")
370
+ if not isinstance(call, dict):
371
+ continue
372
+ name = call.get("name")
373
+ if not isinstance(name, str) or not name:
374
+ continue
375
+ arguments = call.get("args")
376
+ calls.append(
377
+ ToolCall(
378
+ id=f"{model.name}-call-{index}",
379
+ name=name,
380
+ arguments=arguments if isinstance(arguments, dict) else {},
381
+ )
382
+ )
383
+
384
+ reason: FinishReason | None = None
385
+ raw_reason = candidate.get("finishReason") if isinstance(candidate, dict) else None
386
+ if isinstance(raw_reason, str):
387
+ reason = _FINISH_REASONS.get(raw_reason, "stop")
388
+
389
+ usage: TokenUsage | None = None
390
+ raw_usage = body.get("usageMetadata")
391
+ if isinstance(raw_usage, dict):
392
+ usage = TokenUsage(
393
+ input_tokens=int(raw_usage.get("promptTokenCount") or 0),
394
+ output_tokens=int(raw_usage.get("candidatesTokenCount") or 0),
395
+ )
396
+
397
+ # Gemini reports the reason alongside the call; the call is the better signal.
398
+ if calls and reason in (None, "stop"):
399
+ reason = "tool-calls"
400
+ return "".join(text_parts), calls, reason, usage
401
+
402
+
403
+ def _wire_contents(messages: tuple[Message, ...]) -> list[dict[str, Any]]:
404
+ contents: list[dict[str, Any]] = []
405
+ for message in messages:
406
+ if message.role == "system":
407
+ continue
408
+ if message.role == "tool":
409
+ contents.append(
410
+ {
411
+ "role": "user",
412
+ "parts": [
413
+ {
414
+ "functionResponse": {
415
+ "name": message.name or "tool",
416
+ "response": {"content": message.content},
417
+ }
418
+ }
419
+ ],
420
+ }
421
+ )
422
+ continue
423
+ parts: list[dict[str, Any]] = []
424
+ if message.content:
425
+ parts.append({"text": message.content})
426
+ for call in message.tool_calls:
427
+ parts.append({"functionCall": {"name": call.name, "args": call.arguments}})
428
+ if not parts:
429
+ parts.append({"text": ""})
430
+ contents.append(
431
+ {"role": "model" if message.role == "assistant" else "user", "parts": parts}
432
+ )
433
+ return contents
434
+
435
+
436
+ def _system_prompt(messages: tuple[Message, ...]) -> str:
437
+ return "\n".join(message.content for message in messages if message.role == "system")
438
+
439
+
440
+ def _max_tokens(request: CompletionRequest, model: ModelSpec) -> int:
441
+ if request.max_output_tokens is not None:
442
+ return min(request.max_output_tokens, model.max_output_tokens)
443
+ return model.max_output_tokens
444
+
445
+
446
+ def _env(key: str) -> str | None:
447
+ value = os.environ.get(key)
448
+ return value if value else None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.80
3
+ Version: 0.1.82
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
@@ -38,6 +38,7 @@ src/aid_runtime/providers/base.py
38
38
  src/aid_runtime/providers/bedrock.py
39
39
  src/aid_runtime/providers/fake.py
40
40
  src/aid_runtime/providers/http.py
41
+ src/aid_runtime/providers/vertex.py
41
42
  src/aid_runtime/retrieval/__init__.py
42
43
  src/aid_runtime/retrieval/chunking.py
43
44
  src/aid_runtime/retrieval/citations.py
@@ -95,4 +96,5 @@ tests/test_structured.py
95
96
  tests/test_tool_permissions.py
96
97
  tests/test_tools.py
97
98
  tests/test_tracing.py
98
- tests/test_types.py
99
+ tests/test_types.py
100
+ tests/test_vertex_provider.py