aid-runtime-python 0.1.107__tar.gz → 0.1.109__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.107 → aid_runtime_python-0.1.109}/PKG-INFO +1 -1
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/pyproject.toml +1 -1
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/__init__.py +1 -1
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/__init__.py +8 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/guardrails.py +25 -9
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/ir.py +16 -3
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/managed.py +271 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/bedrock.py +36 -1
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/vertex.py +48 -2
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/__init__.py +10 -4
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/embedding.py +151 -6
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime_python.egg-info/SOURCES.txt +1 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_bedrock_provider.py +7 -5
- aid_runtime_python-0.1.109/tests/test_guardrails_model_armor.py +381 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_embedding.py +198 -1
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_vertex_provider.py +9 -2
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/README.md +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/setup.cfg +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/chat_model.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/deep_agents.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/engine.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/loop.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/memory.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/policy.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/state.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/cache.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/concurrency.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/control.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/cost.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/decisions.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/errors.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/evals/__init__.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/evals/dataset.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/evals/gate.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/evals/metrics.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/evals/predicate.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/evals/runner.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/gateway.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/local_trace.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/pipeline.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/prompts.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/__init__.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/anthropic.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/base.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/fake.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/gemini.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/gemini_wire.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/http.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/py.typed +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/chunking.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/citations.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/connectors.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/gate.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/hybrid.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/knowledge_base.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/metrics.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/pgvector.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/rerank.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/retriever.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/stores.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/retrieval/types.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/steps.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/structured.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/tools.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/tracing.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/types.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime_python.egg-info/requires.txt +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_agents_budget.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_agents_deep_agents.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_agents_hitl.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_agents_loop.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_agents_memory.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_anthropic_provider.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_cache.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_concurrency.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_control.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_cost.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_dataset.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_decisions.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_evals.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_evals_assert_gate.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_evals_decision.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_evals_gate.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_evals_predicate.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_gateway.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_gemini_provider.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_guardrails.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_guardrails_managed.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_http_provider.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_local_trace.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_package.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_pipeline.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_prompts.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_chunking.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_citations.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_connectors.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_gate.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_hybrid.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_knowledge_base.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_metrics.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_rerank.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_stores.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_retrieval_types.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_steps.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_streaming.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_structured.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_tool_permissions.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_tools.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/tests/test_tracing.py +0 -0
- {aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/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.
|
|
3
|
+
Version: 0.1.109
|
|
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.109"
|
|
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"
|
{aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/__init__.py
RENAMED
|
@@ -39,11 +39,15 @@ from aid_runtime.agents.ir import (
|
|
|
39
39
|
)
|
|
40
40
|
from aid_runtime.agents.loop import AgentRuntime
|
|
41
41
|
from aid_runtime.agents.managed import (
|
|
42
|
+
MODEL_ARMOR_TEMPLATE_ENV,
|
|
42
43
|
BedrockGuardrailClient,
|
|
43
44
|
GuardrailClient,
|
|
44
45
|
GuardrailOutcome,
|
|
45
46
|
ManagedGuardrailSettings,
|
|
47
|
+
ModelArmorGuardrailClient,
|
|
48
|
+
ModelArmorGuardrailSettings,
|
|
46
49
|
managed_guardrail_settings,
|
|
50
|
+
model_armor_settings,
|
|
47
51
|
)
|
|
48
52
|
from aid_runtime.agents.memory import (
|
|
49
53
|
IMPLEMENTED_MEMORY_KINDS,
|
|
@@ -72,6 +76,7 @@ __all__ = [
|
|
|
72
76
|
"GUARDRAIL_STAGES",
|
|
73
77
|
"IMPLEMENTED_MEMORY_KINDS",
|
|
74
78
|
"MEMORY_SCOPES",
|
|
79
|
+
"MODEL_ARMOR_TEMPLATE_ENV",
|
|
75
80
|
"AgentCheckpoint",
|
|
76
81
|
"AgentDefinition",
|
|
77
82
|
"AgentRuntime",
|
|
@@ -94,6 +99,8 @@ __all__ = [
|
|
|
94
99
|
"ManagedGuardrailSettings",
|
|
95
100
|
"MemoryDefinition",
|
|
96
101
|
"MemoryStore",
|
|
102
|
+
"ModelArmorGuardrailClient",
|
|
103
|
+
"ModelArmorGuardrailSettings",
|
|
97
104
|
"PendingApproval",
|
|
98
105
|
"Principal",
|
|
99
106
|
"RunResult",
|
|
@@ -107,6 +114,7 @@ __all__ = [
|
|
|
107
114
|
"detect",
|
|
108
115
|
"evaluate_policy",
|
|
109
116
|
"managed_guardrail_settings",
|
|
117
|
+
"model_armor_settings",
|
|
110
118
|
"policy_source",
|
|
111
119
|
"render_context",
|
|
112
120
|
]
|
{aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/agents/guardrails.py
RENAMED
|
@@ -50,7 +50,7 @@ from typing import Any, Literal, Protocol, cast
|
|
|
50
50
|
from pydantic import BaseModel, ConfigDict
|
|
51
51
|
|
|
52
52
|
from aid_runtime.agents.ir import DecisionDefinition, GuardrailDefinition
|
|
53
|
-
from aid_runtime.agents.managed import
|
|
53
|
+
from aid_runtime.agents.managed import GuardrailClient, managed_client_for
|
|
54
54
|
from aid_runtime.decisions import DecisionClient, DecisionQuestion, DecisionResponse
|
|
55
55
|
from aid_runtime.errors import ConfigurationError, GuardrailBlockedError
|
|
56
56
|
|
|
@@ -78,8 +78,14 @@ ACTION_REDACT: GuardrailAction = "redact"
|
|
|
78
78
|
ACTION_FLAG: GuardrailAction = "flag"
|
|
79
79
|
ACTION_ESCALATE: GuardrailAction = "escalate"
|
|
80
80
|
|
|
81
|
-
#: The
|
|
81
|
+
#: The managed engines. ``builtin`` is the default and needs no name here.
|
|
82
82
|
ENGINE_BEDROCK = "bedrock"
|
|
83
|
+
ENGINE_MODEL_ARMOR = "model-armor"
|
|
84
|
+
|
|
85
|
+
#: Engines whose policy lives in a cloud service rather than in this process. The IR
|
|
86
|
+
#: gate allows at most one of them per deployment, because the engine below builds a
|
|
87
|
+
#: single client whose destination the environment names.
|
|
88
|
+
ENGINE_MANAGED: frozenset[str] = frozenset({ENGINE_BEDROCK, ENGINE_MODEL_ARMOR})
|
|
83
89
|
|
|
84
90
|
GUARDRAIL_STAGES: tuple[GuardrailStage, ...] = ("input", "retrieval", "tool-call", "output")
|
|
85
91
|
GUARDRAIL_ACTIONS: tuple[GuardrailAction, ...] = (
|
|
@@ -335,17 +341,27 @@ class GuardrailEngine:
|
|
|
335
341
|
#: boot when no request reaches a decision-backed guardrail.
|
|
336
342
|
self._client_factory = client_factory or DecisionClient
|
|
337
343
|
self._client: DecisionAsker | None = None
|
|
338
|
-
#: Same rule for a managed engine: a document with no
|
|
339
|
-
#:
|
|
340
|
-
self._guardrail_client_factory = guardrail_client_factory
|
|
344
|
+
#: Same rule for a managed engine: a document with no managed-engine guardrail
|
|
345
|
+
#: must never require cloud credentials to start.
|
|
346
|
+
self._guardrail_client_factory = guardrail_client_factory
|
|
341
347
|
self._guardrail_client: GuardrailClient | None = None
|
|
342
348
|
|
|
343
349
|
def declared(self, guardrail_id: str) -> GuardrailDefinition | None:
|
|
344
350
|
return self._declared.get(guardrail_id)
|
|
345
351
|
|
|
346
|
-
def _managed(self) -> GuardrailClient:
|
|
352
|
+
def _managed(self, engine: str) -> GuardrailClient:
|
|
353
|
+
"""The client for ``engine``, built on first use.
|
|
354
|
+
|
|
355
|
+
An injected factory wins, because a test or an embedding app does not need
|
|
356
|
+
the engine it named -- it needs the outcome it expects. Otherwise the engine
|
|
357
|
+
picks its own client, so ``engine: model-armor`` never constructs a Bedrock
|
|
358
|
+
client that would then read the wrong environment names.
|
|
359
|
+
"""
|
|
347
360
|
if self._guardrail_client is None:
|
|
348
|
-
|
|
361
|
+
factory = self._guardrail_client_factory
|
|
362
|
+
self._guardrail_client = (
|
|
363
|
+
factory() if factory is not None else managed_client_for(engine)
|
|
364
|
+
)
|
|
349
365
|
return self._guardrail_client
|
|
350
366
|
|
|
351
367
|
def check_input(
|
|
@@ -413,8 +429,8 @@ class GuardrailEngine:
|
|
|
413
429
|
policies=policies,
|
|
414
430
|
message=guardrail.message,
|
|
415
431
|
)
|
|
416
|
-
elif guardrail.engine
|
|
417
|
-
outcome = await self._managed().apply(
|
|
432
|
+
elif guardrail.engine in ENGINE_MANAGED:
|
|
433
|
+
outcome = await self._managed(guardrail.engine).apply(
|
|
418
434
|
source="INPUT" if stage == "input" else "OUTPUT",
|
|
419
435
|
text=text,
|
|
420
436
|
)
|
|
@@ -58,7 +58,7 @@ _ON_BUDGET_EXHAUSTED = frozenset({"fail", "degrade"})
|
|
|
58
58
|
#: rejects it again rather than trusting that every document came through a gate.
|
|
59
59
|
_GUARDRAIL_STAGES = frozenset({"input", "output", "retrieval", "tool-call"})
|
|
60
60
|
_GUARDRAIL_ACTIONS = frozenset({"block", "redact", "flag", "escalate"})
|
|
61
|
-
_GUARDRAIL_ENGINES = frozenset({"builtin", "bedrock"})
|
|
61
|
+
_GUARDRAIL_ENGINES = frozenset({"builtin", "bedrock", "model-armor"})
|
|
62
62
|
_BEDROCK_CONTENT_FILTERS = frozenset(
|
|
63
63
|
{"sexual", "violence", "hate", "insults", "misconduct", "prompt-attack"}
|
|
64
64
|
)
|
|
@@ -152,8 +152,11 @@ class GuardrailDefinition:
|
|
|
152
152
|
outcome that produces no record; the rest are guardrail actions. The trailing
|
|
153
153
|
defaults keep every keyword call site written before decisions existed valid.
|
|
154
154
|
|
|
155
|
-
``engine`` is ``builtin`` (this process runs the detectors) or
|
|
156
|
-
|
|
155
|
+
``engine`` is ``builtin`` (this process runs the detectors) or a managed engine:
|
|
156
|
+
``bedrock`` (the deployment's guardrail evaluates ``bedrock``) or ``model-armor``
|
|
157
|
+
(a Vertex AI Model Armor template named by ``MODEL_ARMOR_TEMPLATE`` holds the
|
|
158
|
+
policy). A managed engine leaves ``policies`` empty and refuses ``redact`` where
|
|
159
|
+
the service cannot rewrite text.
|
|
157
160
|
"""
|
|
158
161
|
|
|
159
162
|
id: str
|
|
@@ -457,6 +460,16 @@ def _guardrail(
|
|
|
457
460
|
# The managed service rewrites the one field it is given, so a managed
|
|
458
461
|
# redaction is always over the prompt text.
|
|
459
462
|
redact = ("text",)
|
|
463
|
+
if action == "redact" and engine == "model-armor":
|
|
464
|
+
# Refused for the same reason the gate refuses it: the template's filters
|
|
465
|
+
# inspect and report unless it names an advanced DLP de-identify template,
|
|
466
|
+
# which this process cannot see. A redaction that may not happen is worse
|
|
467
|
+
# than a refused build.
|
|
468
|
+
raise ConfigurationError(
|
|
469
|
+
f"{where} uses action 'redact' with engine 'model-armor'; Model Armor "
|
|
470
|
+
"reports what it matched, and only an advanced DLP de-identify template "
|
|
471
|
+
"rewrites text"
|
|
472
|
+
)
|
|
460
473
|
tool_ids = tuple(_str_list(entry.get("tools"), f"{where} tools"))
|
|
461
474
|
missing = sorted(set(tool_ids) - set(tools))
|
|
462
475
|
if missing:
|
|
@@ -27,6 +27,7 @@ from __future__ import annotations
|
|
|
27
27
|
import asyncio
|
|
28
28
|
import json
|
|
29
29
|
import os
|
|
30
|
+
import re
|
|
30
31
|
from collections.abc import Callable, Mapping, Sequence
|
|
31
32
|
from dataclasses import dataclass
|
|
32
33
|
from datetime import UTC, datetime
|
|
@@ -36,23 +37,43 @@ import httpx
|
|
|
36
37
|
|
|
37
38
|
from aid_runtime.errors import ConfigurationError, ProviderError, ProviderResponseError
|
|
38
39
|
from aid_runtime.providers.bedrock import BedrockProvider, rfc3986, sigv4_headers
|
|
40
|
+
from aid_runtime.providers.vertex import VertexProvider
|
|
39
41
|
|
|
40
42
|
__all__ = [
|
|
41
43
|
"CONTENT_STRENGTHS",
|
|
42
44
|
"CONTENT_TYPES",
|
|
43
45
|
"GUARDRAIL_ID_ENV",
|
|
44
46
|
"GUARDRAIL_VERSION_ENV",
|
|
47
|
+
"MODEL_ARMOR_TEMPLATE_ENV",
|
|
45
48
|
"PII_TYPES",
|
|
46
49
|
"BedrockGuardrailClient",
|
|
47
50
|
"GuardrailClient",
|
|
48
51
|
"GuardrailOutcome",
|
|
49
52
|
"ManagedGuardrailSettings",
|
|
53
|
+
"ModelArmorGuardrailClient",
|
|
54
|
+
"ModelArmorGuardrailSettings",
|
|
55
|
+
"managed_client_for",
|
|
50
56
|
"managed_guardrail_settings",
|
|
57
|
+
"model_armor_settings",
|
|
51
58
|
]
|
|
52
59
|
|
|
53
60
|
GUARDRAIL_ID_ENV = "BEDROCK_GUARDRAIL_ID"
|
|
54
61
|
GUARDRAIL_VERSION_ENV = "BEDROCK_GUARDRAIL_VERSION"
|
|
55
62
|
|
|
63
|
+
#: The full resource name of the Model Armor template the deployment owns.
|
|
64
|
+
MODEL_ARMOR_TEMPLATE_ENV = "MODEL_ARMOR_TEMPLATE"
|
|
65
|
+
|
|
66
|
+
#: ``projects/{project}/locations/{location}/templates/{id}``, the only address the
|
|
67
|
+
#: sanitize methods take. The location embedded in it selects the regional endpoint.
|
|
68
|
+
_MODEL_ARMOR_TEMPLATE = re.compile(
|
|
69
|
+
r"^projects/[^/]+/locations/(?P<location>[^/]+)/templates/[^/]+$"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
_MODEL_ARMOR_METHODS: Mapping[str, str] = {
|
|
73
|
+
"INPUT": "sanitizeUserPrompt",
|
|
74
|
+
"OUTPUT": "sanitizeModelResponse",
|
|
75
|
+
}
|
|
76
|
+
|
|
56
77
|
#: One entry per ``BedrockContentFilter`` in ``packages/ir/src/shapes.ts``.
|
|
57
78
|
CONTENT_TYPES: Mapping[str, str] = {
|
|
58
79
|
"sexual": "SEXUAL",
|
|
@@ -127,6 +148,44 @@ def managed_guardrail_settings() -> ManagedGuardrailSettings:
|
|
|
127
148
|
return ManagedGuardrailSettings(id=guardrail_id or "", version=version or "")
|
|
128
149
|
|
|
129
150
|
|
|
151
|
+
@dataclass(frozen=True, slots=True)
|
|
152
|
+
class ModelArmorGuardrailSettings:
|
|
153
|
+
"""Where the deployment put the Model Armor template.
|
|
154
|
+
|
|
155
|
+
``template`` is the full resource name, because that is the only address the
|
|
156
|
+
sanitize methods take. ``location`` is derived from it rather than read from a
|
|
157
|
+
second environment name: the two cannot disagree, and a deployment that moved
|
|
158
|
+
the template across regions cannot leave the app calling the old endpoint.
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
template: str
|
|
162
|
+
location: str
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def model_armor_settings() -> ModelArmorGuardrailSettings:
|
|
166
|
+
"""Read the template name, or explain what is missing or malformed.
|
|
167
|
+
|
|
168
|
+
A Model Armor template has no version in its name. Pinning is the template's own
|
|
169
|
+
``filter_version_selector``, which the operator sets on the resource -- so unlike
|
|
170
|
+
``BEDROCK_GUARDRAIL_VERSION`` there is nothing here for the app to refuse.
|
|
171
|
+
"""
|
|
172
|
+
template = os.environ.get(MODEL_ARMOR_TEMPLATE_ENV)
|
|
173
|
+
if not template:
|
|
174
|
+
raise ConfigurationError(
|
|
175
|
+
"the spec declares a model-armor guardrail, so "
|
|
176
|
+
f"{MODEL_ARMOR_TEMPLATE_ENV} must be set: the deployment creates the template, "
|
|
177
|
+
"the app only names it"
|
|
178
|
+
)
|
|
179
|
+
match = _MODEL_ARMOR_TEMPLATE.match(template)
|
|
180
|
+
if match is None:
|
|
181
|
+
raise ConfigurationError(
|
|
182
|
+
f"{MODEL_ARMOR_TEMPLATE_ENV} must be a template resource name "
|
|
183
|
+
"projects/{project}/locations/{location}/templates/{id}, not "
|
|
184
|
+
f"{template!r}"
|
|
185
|
+
)
|
|
186
|
+
return ModelArmorGuardrailSettings(template=template, location=match.group("location"))
|
|
187
|
+
|
|
188
|
+
|
|
130
189
|
@dataclass(frozen=True, slots=True)
|
|
131
190
|
class GuardrailOutcome:
|
|
132
191
|
"""One ``ApplyGuardrail`` answer, in terms the engine can act on.
|
|
@@ -322,3 +381,215 @@ def _entries(value: Any) -> tuple[Mapping[str, Any], ...]:
|
|
|
322
381
|
|
|
323
382
|
def _prefixed(family: str, value: Any) -> str | None:
|
|
324
383
|
return f"{family}:{value}" if isinstance(value, str) and value else None
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class ModelArmorGuardrailClient:
|
|
387
|
+
"""``sanitizeUserPrompt`` / ``sanitizeModelResponse`` with a bearer token.
|
|
388
|
+
|
|
389
|
+
Model Armor is Google Cloud's counterpart to ``ApplyGuardrail``: the template
|
|
390
|
+
holds the policy, and the call takes text and answers with a verdict. The wire
|
|
391
|
+
shape differs in one way the engine must not paper over -- there is a single
|
|
392
|
+
overall ``filterMatchState`` plus a per-filter ``matchState``, not a per-assessment
|
|
393
|
+
action -- so the labels below name the filter that matched rather than an AWS
|
|
394
|
+
policy family.
|
|
395
|
+
|
|
396
|
+
Two rules keep the fail-closed promise:
|
|
397
|
+
|
|
398
|
+
* ``invocationResult`` must be ``SUCCESS``. ``PARTIAL`` means a filter was
|
|
399
|
+
skipped, so "no match" would be a verdict about filters that never ran.
|
|
400
|
+
* Only DLP's ``deidentifyResult`` rewrites text. A template without an advanced
|
|
401
|
+
de-identify configuration inspects and reports; the spec layer refuses
|
|
402
|
+
``action: redact`` for this engine rather than promising a rewrite the service
|
|
403
|
+
may not perform.
|
|
404
|
+
"""
|
|
405
|
+
|
|
406
|
+
def __init__(
|
|
407
|
+
self,
|
|
408
|
+
*,
|
|
409
|
+
settings: ModelArmorGuardrailSettings | None = None,
|
|
410
|
+
provider: VertexProvider | None = None,
|
|
411
|
+
base_url: str | None = None,
|
|
412
|
+
client: httpx.AsyncClient | None = None,
|
|
413
|
+
timeout_seconds: float = 15.0,
|
|
414
|
+
max_attempts: int = 2,
|
|
415
|
+
backoff_seconds: float = 0.25,
|
|
416
|
+
) -> None:
|
|
417
|
+
if max_attempts < 1:
|
|
418
|
+
raise ValueError("max_attempts must be at least 1")
|
|
419
|
+
self._settings = settings
|
|
420
|
+
self._base_url = base_url.rstrip("/") if base_url is not None else None
|
|
421
|
+
self._max_attempts = max_attempts
|
|
422
|
+
self._backoff = backoff_seconds
|
|
423
|
+
self._client = client or httpx.AsyncClient(timeout=timeout_seconds)
|
|
424
|
+
self._owns_client = client is None
|
|
425
|
+
self._provider = provider or VertexProvider(
|
|
426
|
+
name="model-armor", timeout_seconds=timeout_seconds, client=self._client
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
@property
|
|
430
|
+
def settings(self) -> ModelArmorGuardrailSettings:
|
|
431
|
+
if self._settings is None:
|
|
432
|
+
self._settings = model_armor_settings()
|
|
433
|
+
return self._settings
|
|
434
|
+
|
|
435
|
+
async def aclose(self) -> None:
|
|
436
|
+
if self._owns_client:
|
|
437
|
+
await self._client.aclose()
|
|
438
|
+
|
|
439
|
+
async def apply(self, *, source: str, text: str) -> GuardrailOutcome:
|
|
440
|
+
if source not in _SOURCES:
|
|
441
|
+
raise ValueError(f"source must be INPUT or OUTPUT, not {source!r}")
|
|
442
|
+
settings = self.settings
|
|
443
|
+
token = await self._provider.access_token()
|
|
444
|
+
method = _MODEL_ARMOR_METHODS[source]
|
|
445
|
+
field = "userPromptData" if source == "INPUT" else "modelResponseData"
|
|
446
|
+
payload = json.dumps({field: {"text": text}}, separators=(",", ":"))
|
|
447
|
+
url = self._url(settings, method)
|
|
448
|
+
answer = await self._post(
|
|
449
|
+
url,
|
|
450
|
+
{"authorization": f"Bearer {token}", "content-type": "application/json"},
|
|
451
|
+
payload,
|
|
452
|
+
)
|
|
453
|
+
return _parse_model_armor(answer)
|
|
454
|
+
|
|
455
|
+
def _url(self, settings: ModelArmorGuardrailSettings, method: str) -> str:
|
|
456
|
+
base = self._base_url or f"https://modelarmor.{settings.location}.rep.googleapis.com"
|
|
457
|
+
return f"{base}/v1/{settings.template}:{method}"
|
|
458
|
+
|
|
459
|
+
async def _post(self, url: str, headers: dict[str, str], body: str) -> str:
|
|
460
|
+
last_error: Exception | None = None
|
|
461
|
+
for attempt in range(1, self._max_attempts + 1):
|
|
462
|
+
try:
|
|
463
|
+
response = await self._client.post(url, content=body, headers=headers)
|
|
464
|
+
except httpx.TransportError as exc:
|
|
465
|
+
last_error = exc
|
|
466
|
+
if attempt == self._max_attempts:
|
|
467
|
+
break
|
|
468
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
469
|
+
continue
|
|
470
|
+
if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
|
|
471
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
472
|
+
continue
|
|
473
|
+
if response.status_code >= 400:
|
|
474
|
+
raise ProviderError(
|
|
475
|
+
"the Model Armor template returned "
|
|
476
|
+
f"{response.status_code}: {response.text[:500]}"
|
|
477
|
+
)
|
|
478
|
+
return response.text
|
|
479
|
+
raise ProviderError(f"the Model Armor template could not be reached: {last_error}")
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def managed_client_for(engine: str) -> GuardrailClient:
|
|
483
|
+
"""The client an engine needs, chosen from the engine alone.
|
|
484
|
+
|
|
485
|
+
Model Armor is not Bedrock with different names: the two read different
|
|
486
|
+
environment variables and call different APIs. Selecting here keeps the engine
|
|
487
|
+
from constructing a Bedrock client for a deployment that named a template.
|
|
488
|
+
"""
|
|
489
|
+
return ModelArmorGuardrailClient() if engine == "model-armor" else BedrockGuardrailClient()
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _parse_model_armor(body: str) -> GuardrailOutcome:
|
|
493
|
+
try:
|
|
494
|
+
answer = json.loads(body)
|
|
495
|
+
except json.JSONDecodeError as exc:
|
|
496
|
+
raise ProviderResponseError(
|
|
497
|
+
"the Model Armor template returned a non-JSON body", body
|
|
498
|
+
) from exc
|
|
499
|
+
if not isinstance(answer, dict):
|
|
500
|
+
raise ProviderResponseError("the Model Armor template returned no object", body)
|
|
501
|
+
result = answer.get("sanitizationResult")
|
|
502
|
+
if not isinstance(result, Mapping):
|
|
503
|
+
raise ProviderResponseError("the Model Armor response has no sanitizationResult", body)
|
|
504
|
+
invocation = result.get("invocationResult")
|
|
505
|
+
if invocation != "SUCCESS":
|
|
506
|
+
raise ProviderResponseError(
|
|
507
|
+
"the Model Armor template could not evaluate every filter "
|
|
508
|
+
f"(invocationResult {invocation!r})",
|
|
509
|
+
body,
|
|
510
|
+
)
|
|
511
|
+
state = result.get("filterMatchState")
|
|
512
|
+
if state == "NO_MATCH_FOUND":
|
|
513
|
+
return GuardrailOutcome(intervened=False)
|
|
514
|
+
if state != "MATCH_FOUND":
|
|
515
|
+
raise ProviderResponseError(
|
|
516
|
+
f"the Model Armor template returned unknown filterMatchState {state!r}", body
|
|
517
|
+
)
|
|
518
|
+
filters = result.get("filterResults")
|
|
519
|
+
return GuardrailOutcome(
|
|
520
|
+
intervened=True,
|
|
521
|
+
policies=_model_armor_labels(filters),
|
|
522
|
+
text=_model_armor_text(filters),
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _model_armor_labels(filters: Any) -> tuple[str, ...]:
|
|
527
|
+
"""What matched, named the way the spec would name it.
|
|
528
|
+
|
|
529
|
+
``rai:hate_speech``, ``pi-and-jailbreak``, ``sdp:EMAIL_ADDRESS``,
|
|
530
|
+
``malicious-uri``: one label per filter that matched, so a trace line says which
|
|
531
|
+
check refused the text without carrying the provider's nested response.
|
|
532
|
+
"""
|
|
533
|
+
if not isinstance(filters, Mapping):
|
|
534
|
+
return ()
|
|
535
|
+
labels: list[str] = []
|
|
536
|
+
|
|
537
|
+
def add(label: str | None) -> None:
|
|
538
|
+
if label is not None and label not in labels:
|
|
539
|
+
labels.append(label)
|
|
540
|
+
|
|
541
|
+
rai = _inner(filters, "rai", "raiFilterResult")
|
|
542
|
+
if isinstance(rai, Mapping):
|
|
543
|
+
types = rai.get("raiFilterTypeResults")
|
|
544
|
+
if isinstance(types, Mapping):
|
|
545
|
+
for name, entry in types.items():
|
|
546
|
+
if isinstance(entry, Mapping) and entry.get("matchState") == "MATCH_FOUND":
|
|
547
|
+
add(_prefixed("rai", name))
|
|
548
|
+
|
|
549
|
+
if _matched(_inner(filters, "pi_and_jailbreak", "piAndJailbreakFilterResult")):
|
|
550
|
+
add("pi-and-jailbreak")
|
|
551
|
+
|
|
552
|
+
sdp = _inner(filters, "sdp", "sdpFilterResult")
|
|
553
|
+
if isinstance(sdp, Mapping):
|
|
554
|
+
inspect = sdp.get("inspectResult")
|
|
555
|
+
if isinstance(inspect, Mapping) and inspect.get("matchState") == "MATCH_FOUND":
|
|
556
|
+
for finding in _entries(inspect.get("findings")):
|
|
557
|
+
add(_prefixed("sdp", finding.get("infoType")))
|
|
558
|
+
if _matched(sdp.get("deidentifyResult")):
|
|
559
|
+
add("sdp")
|
|
560
|
+
|
|
561
|
+
if _matched(_inner(filters, "malicious_uris", "maliciousUriFilterResult")):
|
|
562
|
+
add("malicious-uri")
|
|
563
|
+
if _matched(_inner(filters, "csam", "csamFilterFilterResult")):
|
|
564
|
+
add("csam")
|
|
565
|
+
return tuple(labels)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _model_armor_text(filters: Any) -> str | None:
|
|
569
|
+
"""The de-identified text, when the template was configured to produce one."""
|
|
570
|
+
if not isinstance(filters, Mapping):
|
|
571
|
+
return None
|
|
572
|
+
sdp = _inner(filters, "sdp", "sdpFilterResult")
|
|
573
|
+
if sdp is None:
|
|
574
|
+
return None
|
|
575
|
+
deidentify = sdp.get("deidentifyResult")
|
|
576
|
+
if not isinstance(deidentify, Mapping) or deidentify.get("matchState") != "MATCH_FOUND":
|
|
577
|
+
return None
|
|
578
|
+
data = deidentify.get("data")
|
|
579
|
+
if isinstance(data, Mapping):
|
|
580
|
+
text = data.get("text")
|
|
581
|
+
if isinstance(text, str):
|
|
582
|
+
return text
|
|
583
|
+
return None
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _inner(filters: Mapping[str, Any], key: str, inner: str) -> Mapping[str, Any] | None:
|
|
587
|
+
entry = filters.get(key)
|
|
588
|
+
if not isinstance(entry, Mapping):
|
|
589
|
+
return None
|
|
590
|
+
value = entry.get(inner)
|
|
591
|
+
return value if isinstance(value, Mapping) else None
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _matched(entry: Any) -> bool:
|
|
595
|
+
return isinstance(entry, Mapping) and entry.get("matchState") == "MATCH_FOUND"
|
{aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/bedrock.py
RENAMED
|
@@ -19,6 +19,10 @@ There is no ``stream``: ``/converse-stream`` frames events in AWS's binary
|
|
|
19
19
|
event-stream format (length-prefixed records with CRC32) rather than SSE, which
|
|
20
20
|
is out of scope for this adapter. ``STREAMING`` is therefore not advertised, and
|
|
21
21
|
the capability gate refuses a spec that asks for it instead of failing mid-run.
|
|
22
|
+
|
|
23
|
+
``EMBEDDINGS`` *is* advertised: Titan models answer on ``InvokeModel``, which is
|
|
24
|
+
the uninterpreted sibling of ``complete`` sharing this adapter's region,
|
|
25
|
+
credential chain, signature and retry.
|
|
22
26
|
"""
|
|
23
27
|
|
|
24
28
|
from __future__ import annotations
|
|
@@ -229,7 +233,11 @@ class BedrockProvider:
|
|
|
229
233
|
|
|
230
234
|
@property
|
|
231
235
|
def capabilities(self) -> frozenset[Capability]:
|
|
232
|
-
|
|
236
|
+
# Embeddings are served by InvokeModel on this same host and identity, so the
|
|
237
|
+
# method that backs them is on this adapter rather than a separate client.
|
|
238
|
+
return frozenset(
|
|
239
|
+
{Capability.TOOL_CALLING, Capability.STRUCTURED_OUTPUT, Capability.EMBEDDINGS}
|
|
240
|
+
)
|
|
233
241
|
|
|
234
242
|
async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
|
|
235
243
|
body = json.dumps(self._build_payload(request, model), separators=(",", ":"))
|
|
@@ -389,6 +397,33 @@ class BedrockProvider:
|
|
|
389
397
|
"""One signed POST, uninterpreted: shared with the managed-guardrail adapter."""
|
|
390
398
|
return await self._client.post(url, content=body, headers=headers)
|
|
391
399
|
|
|
400
|
+
async def invoke_model(self, model_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
401
|
+
"""One signed ``InvokeModel`` call, uninterpreted.
|
|
402
|
+
|
|
403
|
+
Converse is the portable *chat* surface; embeddings are not on it. Titan
|
|
404
|
+
embeddings answer on ``/model/{id}/invoke`` from the same host and under the
|
|
405
|
+
same identity, so this adapter owns the path rather than a second client
|
|
406
|
+
re-deriving the region, the credential chain and the signature.
|
|
407
|
+
"""
|
|
408
|
+
body = json.dumps(payload, separators=(",", ":"))
|
|
409
|
+
region = self._resolve_region()
|
|
410
|
+
credentials = await self._credentials()
|
|
411
|
+
base = self._base_url or default_bedrock_base_url(region)
|
|
412
|
+
url = f"{base}/model/{rfc3986(model_id)}/invoke"
|
|
413
|
+
headers = self._headers(url, body, region, credentials, self._now())
|
|
414
|
+
text = await self._post(url, headers, body)
|
|
415
|
+
try:
|
|
416
|
+
answer = json.loads(text)
|
|
417
|
+
except json.JSONDecodeError as exc:
|
|
418
|
+
raise ProviderResponseError(
|
|
419
|
+
f"{self._name} returned a body that is not JSON", text
|
|
420
|
+
) from exc
|
|
421
|
+
if not isinstance(answer, dict):
|
|
422
|
+
raise ProviderResponseError(
|
|
423
|
+
f"{self._name} returned a JSON body that is not an object", text
|
|
424
|
+
)
|
|
425
|
+
return answer
|
|
426
|
+
|
|
392
427
|
async def credentials(self) -> dict[str, Any]:
|
|
393
428
|
"""The SigV4 credentials, resolved lazily.
|
|
394
429
|
|
{aid_runtime_python-0.1.107 → aid_runtime_python-0.1.109}/src/aid_runtime/providers/vertex.py
RENAMED
|
@@ -21,6 +21,7 @@ import asyncio
|
|
|
21
21
|
import json
|
|
22
22
|
import os
|
|
23
23
|
from collections.abc import Awaitable, Callable
|
|
24
|
+
from typing import Any
|
|
24
25
|
|
|
25
26
|
import httpx
|
|
26
27
|
|
|
@@ -59,7 +60,12 @@ def default_vertex_base_url(location: str) -> str:
|
|
|
59
60
|
|
|
60
61
|
|
|
61
62
|
class VertexProvider(GeminiWireClient):
|
|
62
|
-
"""Gemini on Vertex AI over ``generateContent`` / ``streamGenerateContent``.
|
|
63
|
+
"""Gemini on Vertex AI over ``generateContent`` / ``streamGenerateContent``.
|
|
64
|
+
|
|
65
|
+
Embeddings ride the same adapter: ``:predict`` shares the regional host, the
|
|
66
|
+
project/location path and the bearer token, and only the request and response
|
|
67
|
+
envelopes differ.
|
|
68
|
+
"""
|
|
63
69
|
|
|
64
70
|
def __init__(
|
|
65
71
|
self,
|
|
@@ -91,8 +97,15 @@ class VertexProvider(GeminiWireClient):
|
|
|
91
97
|
|
|
92
98
|
@property
|
|
93
99
|
def capabilities(self) -> frozenset[Capability]:
|
|
100
|
+
# Embeddings are served by `:predict` under the same project, location and
|
|
101
|
+
# bearer token, so this adapter carries the method instead of a second client.
|
|
94
102
|
return frozenset(
|
|
95
|
-
{
|
|
103
|
+
{
|
|
104
|
+
Capability.STREAMING,
|
|
105
|
+
Capability.STRUCTURED_OUTPUT,
|
|
106
|
+
Capability.TOOL_CALLING,
|
|
107
|
+
Capability.EMBEDDINGS,
|
|
108
|
+
}
|
|
96
109
|
)
|
|
97
110
|
|
|
98
111
|
async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
|
|
@@ -129,6 +142,30 @@ class VertexProvider(GeminiWireClient):
|
|
|
129
142
|
f"/publishers/google/models/{model.name}:{method}"
|
|
130
143
|
)
|
|
131
144
|
|
|
145
|
+
def project(self) -> str:
|
|
146
|
+
"""The project this adapter bills and addresses, resolved lazily."""
|
|
147
|
+
return self._resolve_project()
|
|
148
|
+
|
|
149
|
+
def location(self) -> str:
|
|
150
|
+
"""The region this adapter addresses, resolved lazily."""
|
|
151
|
+
return self._resolve_location()
|
|
152
|
+
|
|
153
|
+
async def predict(self, model_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
154
|
+
"""One ``:predict`` call, uninterpreted.
|
|
155
|
+
|
|
156
|
+
Public because embedding is the same operation against the same identity:
|
|
157
|
+
re-resolving the project, the location and the token elsewhere is three
|
|
158
|
+
chances for the embedder to address a different deployment than the chat
|
|
159
|
+
model.
|
|
160
|
+
"""
|
|
161
|
+
location = self._resolve_location()
|
|
162
|
+
base = (self._base_url or default_vertex_base_url(location)).rstrip("/")
|
|
163
|
+
url = (
|
|
164
|
+
f"{base}/v1/projects/{self._resolve_project()}/locations/{location}"
|
|
165
|
+
f"/publishers/google/models/{model_id}:predict"
|
|
166
|
+
)
|
|
167
|
+
return decode_body(await self._post(url, payload), self._name)
|
|
168
|
+
|
|
132
169
|
async def _token(self) -> str:
|
|
133
170
|
if self._access_token:
|
|
134
171
|
return self._access_token
|
|
@@ -143,6 +180,15 @@ class VertexProvider(GeminiWireClient):
|
|
|
143
180
|
self._cached_token = (token, asyncio.get_running_loop().time() + expires_in)
|
|
144
181
|
return token
|
|
145
182
|
|
|
183
|
+
async def access_token(self) -> str:
|
|
184
|
+
"""The bearer token this provider would send.
|
|
185
|
+
|
|
186
|
+
Public so a second Google API a deployment calls -- Model Armor is one --
|
|
187
|
+
reuses the same environment override, metadata mint and refresh window
|
|
188
|
+
instead of growing a second token cache with its own expiry bug.
|
|
189
|
+
"""
|
|
190
|
+
return await self._token()
|
|
191
|
+
|
|
146
192
|
async def _mint_token(self) -> tuple[str, float]:
|
|
147
193
|
if self._token_provider is not None:
|
|
148
194
|
return await self._token_provider(), 300.0
|