maigp-google-adk 1.0.0__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.
- maigp_google_adk-1.0.0/.gitignore +56 -0
- maigp_google_adk-1.0.0/PKG-INFO +62 -0
- maigp_google_adk-1.0.0/README.md +51 -0
- maigp_google_adk-1.0.0/aigp_google_adk/__init__.py +8 -0
- maigp_google_adk-1.0.0/aigp_google_adk/governance.py +32 -0
- maigp_google_adk-1.0.0/aigp_google_adk/handler.py +226 -0
- maigp_google_adk-1.0.0/pyproject.toml +17 -0
- maigp_google_adk-1.0.0/tests/__init__.py +0 -0
- maigp_google_adk-1.0.0/tests/test_handler.py +333 -0
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
dist/
|
|
6
|
+
build/
|
|
7
|
+
.venv/
|
|
8
|
+
.eggs/
|
|
9
|
+
|
|
10
|
+
# Node
|
|
11
|
+
node_modules/
|
|
12
|
+
dist/
|
|
13
|
+
|
|
14
|
+
# Go
|
|
15
|
+
bin/
|
|
16
|
+
|
|
17
|
+
# Rust
|
|
18
|
+
target/
|
|
19
|
+
|
|
20
|
+
# .NET
|
|
21
|
+
bin/
|
|
22
|
+
obj/
|
|
23
|
+
|
|
24
|
+
# Java
|
|
25
|
+
*.class
|
|
26
|
+
out/
|
|
27
|
+
|
|
28
|
+
# IDE
|
|
29
|
+
.idea/
|
|
30
|
+
.vscode/
|
|
31
|
+
.kiro/
|
|
32
|
+
*.swp
|
|
33
|
+
|
|
34
|
+
# OS
|
|
35
|
+
.DS_Store
|
|
36
|
+
Thumbs.db
|
|
37
|
+
|
|
38
|
+
# Secrets (never commit)
|
|
39
|
+
.env
|
|
40
|
+
*.pem
|
|
41
|
+
*.key
|
|
42
|
+
*.pdf
|
|
43
|
+
BACKLOG/
|
|
44
|
+
patent/
|
|
45
|
+
docs/.archive/
|
|
46
|
+
review/
|
|
47
|
+
|
|
48
|
+
# Generated navigable spec split — derived from the monoliths by
|
|
49
|
+
# specification/tools/spec_split.py; the manifest + monoliths are the
|
|
50
|
+
# source of truth, not this output. Same convention as Mars (spec/*/*/).
|
|
51
|
+
specification/*/*/
|
|
52
|
+
specification/split-index.md
|
|
53
|
+
|
|
54
|
+
# Local rendering/preview site — self-contained, not part of the
|
|
55
|
+
# published specification, never pushed.
|
|
56
|
+
site/
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: maigp-google-adk
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: AIGP governance adapter for Google ADK (Agent Development Kit)
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Requires-Dist: google-adk>=0.1.0
|
|
7
|
+
Requires-Dist: maigp-agent-core>=1.0.0
|
|
8
|
+
Provides-Extra: otel
|
|
9
|
+
Requires-Dist: opentelemetry-api>=1.20; extra == 'otel'
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# maigp-google-adk
|
|
13
|
+
|
|
14
|
+
AIGP governance for the Google Agent Development Kit (ADK).
|
|
15
|
+
|
|
16
|
+
Part of **MAIGP** — the Mediated AI Governance Protocol: a runtime consent / scope / evidence layer for AI systems. Every governed call is **CHECK**ed before it runs (policy, scope, jurisdiction, circuit-breaker) and **RECORD**ed + **TRACE**d as tamper-evident evidence after.
|
|
17
|
+
|
|
18
|
+
## What it governs
|
|
19
|
+
|
|
20
|
+
Governs Google ADK agents via a governed callback.
|
|
21
|
+
|
|
22
|
+
## Governance model
|
|
23
|
+
|
|
24
|
+
This adapter maps the framework's lifecycle onto the AIGP agent-governance loop provided by [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/):
|
|
25
|
+
|
|
26
|
+
| Framework event | AIGP action |
|
|
27
|
+
|---|---|
|
|
28
|
+
| run / invocation start | **CHECK** (`pre_invoke`) — allowed? under what authority? |
|
|
29
|
+
| each model reply | token accounting (`on_model_call`) |
|
|
30
|
+
| each tool / function call | tool governance (`on_tool_call`) |
|
|
31
|
+
| run complete | **RECORD** + **TRACE** (`post_invoke`) |
|
|
32
|
+
| failure | `on_error` (recorded, then re-raised) |
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install maigp-google-adk
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Pulls in [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/) (shared lifecycle) and, transitively, [`maigp-client`](https://pypi.org/project/maigp-client/).
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from aigp_google_adk import AigpAdkGovernance, AigpAdkCallback
|
|
47
|
+
|
|
48
|
+
gov = AigpAdkGovernance(gov_url="https://gov.example.com",
|
|
49
|
+
app_id="my-adk-agent", hmac_secret="secret")
|
|
50
|
+
|
|
51
|
+
# Attach AigpAdkCallback to your ADK agent for CHECK/RECORD coverage
|
|
52
|
+
callback = AigpAdkCallback(gov)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Links
|
|
56
|
+
|
|
57
|
+
- Protocol, specs & full adapter catalog: https://github.com/owner-spec/aigp-protocol
|
|
58
|
+
- Issues: https://github.com/owner-spec/aigp-protocol/issues
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
License: Proprietary. © Kanjani AI Research & Causum.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# maigp-google-adk
|
|
2
|
+
|
|
3
|
+
AIGP governance for the Google Agent Development Kit (ADK).
|
|
4
|
+
|
|
5
|
+
Part of **MAIGP** — the Mediated AI Governance Protocol: a runtime consent / scope / evidence layer for AI systems. Every governed call is **CHECK**ed before it runs (policy, scope, jurisdiction, circuit-breaker) and **RECORD**ed + **TRACE**d as tamper-evident evidence after.
|
|
6
|
+
|
|
7
|
+
## What it governs
|
|
8
|
+
|
|
9
|
+
Governs Google ADK agents via a governed callback.
|
|
10
|
+
|
|
11
|
+
## Governance model
|
|
12
|
+
|
|
13
|
+
This adapter maps the framework's lifecycle onto the AIGP agent-governance loop provided by [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/):
|
|
14
|
+
|
|
15
|
+
| Framework event | AIGP action |
|
|
16
|
+
|---|---|
|
|
17
|
+
| run / invocation start | **CHECK** (`pre_invoke`) — allowed? under what authority? |
|
|
18
|
+
| each model reply | token accounting (`on_model_call`) |
|
|
19
|
+
| each tool / function call | tool governance (`on_tool_call`) |
|
|
20
|
+
| run complete | **RECORD** + **TRACE** (`post_invoke`) |
|
|
21
|
+
| failure | `on_error` (recorded, then re-raised) |
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install maigp-google-adk
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Pulls in [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/) (shared lifecycle) and, transitively, [`maigp-client`](https://pypi.org/project/maigp-client/).
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from aigp_google_adk import AigpAdkGovernance, AigpAdkCallback
|
|
36
|
+
|
|
37
|
+
gov = AigpAdkGovernance(gov_url="https://gov.example.com",
|
|
38
|
+
app_id="my-adk-agent", hmac_secret="secret")
|
|
39
|
+
|
|
40
|
+
# Attach AigpAdkCallback to your ADK agent for CHECK/RECORD coverage
|
|
41
|
+
callback = AigpAdkCallback(gov)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Links
|
|
45
|
+
|
|
46
|
+
- Protocol, specs & full adapter catalog: https://github.com/owner-spec/aigp-protocol
|
|
47
|
+
- Issues: https://github.com/owner-spec/aigp-protocol/issues
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
License: Proprietary. © Kanjani AI Research & Causum.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""AigpAdkGovernance — entry point for Google ADK agent governance."""
|
|
2
|
+
|
|
3
|
+
from aigp_agent_core import AgentGovernance
|
|
4
|
+
from .handler import AigpAdkCallback
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AigpAdkGovernance(AgentGovernance):
|
|
8
|
+
"""Google ADK governance wrapper.
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
governance = AigpAdkGovernance(gov_url=..., app_id=..., hmac_secret=...)
|
|
12
|
+
callback = governance.callback(agent_name="my-agent", user_id="user-1")
|
|
13
|
+
|
|
14
|
+
agent = Agent(
|
|
15
|
+
model="gemini-2.0-flash",
|
|
16
|
+
name="my-agent",
|
|
17
|
+
before_model_callback=callback.before_model_callback,
|
|
18
|
+
after_model_callback=callback.after_model_callback,
|
|
19
|
+
before_tool_callback=callback.before_tool_callback,
|
|
20
|
+
after_tool_callback=callback.after_tool_callback,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
result = agent.run("Analyze this security finding")
|
|
24
|
+
callback.on_agent_end(result)
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def callback(self, *, agent_name: str = "", model_id: str = "",
|
|
28
|
+
user_id: str = "") -> AigpAdkCallback:
|
|
29
|
+
"""Create an ADK callback wired to this governance instance."""
|
|
30
|
+
return AigpAdkCallback(
|
|
31
|
+
self, agent_name=agent_name, model_id=model_id, user_id=user_id
|
|
32
|
+
)
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Google ADK Callback — maps Google ADK lifecycle to AIGP governance.
|
|
2
|
+
|
|
3
|
+
Google ADK agents use callback hooks:
|
|
4
|
+
- before_model_callback(callback_context, llm_request)
|
|
5
|
+
- after_model_callback(callback_context, llm_response)
|
|
6
|
+
- before_tool_callback(callback_context, tool_name, tool_input)
|
|
7
|
+
- after_tool_callback(callback_context, tool_name, tool_output)
|
|
8
|
+
|
|
9
|
+
This adapter maps those to AIGP governance methods:
|
|
10
|
+
- before_model_callback → pre_invoke (first call), track model start
|
|
11
|
+
- after_model_callback → on_model_call (token accumulation)
|
|
12
|
+
- before_tool_callback → record tool start time
|
|
13
|
+
- after_tool_callback → on_tool_call (tool governance)
|
|
14
|
+
- Agent completion → post_invoke + set_output_metadata
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import logging
|
|
19
|
+
import time
|
|
20
|
+
from typing import Any, Optional
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _run_async(coro):
|
|
26
|
+
"""Run an async coroutine from sync context."""
|
|
27
|
+
try:
|
|
28
|
+
loop = asyncio.get_running_loop()
|
|
29
|
+
import concurrent.futures
|
|
30
|
+
with concurrent.futures.ThreadPoolExecutor() as pool:
|
|
31
|
+
future = pool.submit(asyncio.run, coro)
|
|
32
|
+
return future.result()
|
|
33
|
+
except RuntimeError:
|
|
34
|
+
return asyncio.run(coro)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _detect_content_type(result) -> str:
|
|
38
|
+
"""Detect output content type from agent result.
|
|
39
|
+
|
|
40
|
+
Inspects the result for content type hints:
|
|
41
|
+
- dict with 'content_type' key
|
|
42
|
+
- dict with 'images' or 'image' key → 'image'
|
|
43
|
+
- dict with 'audio' key → 'audio'
|
|
44
|
+
- dict with 'video' key → 'video'
|
|
45
|
+
- Otherwise defaults to 'text'
|
|
46
|
+
"""
|
|
47
|
+
if isinstance(result, dict):
|
|
48
|
+
if "content_type" in result:
|
|
49
|
+
return result["content_type"]
|
|
50
|
+
if "images" in result or "image" in result:
|
|
51
|
+
return "image"
|
|
52
|
+
if "audio" in result:
|
|
53
|
+
return "audio"
|
|
54
|
+
if "video" in result:
|
|
55
|
+
return "video"
|
|
56
|
+
return "text"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _extract_metadata(result) -> dict:
|
|
60
|
+
"""Extract D-SIG metadata from agent result if available."""
|
|
61
|
+
if isinstance(result, dict):
|
|
62
|
+
return result.get("metadata", {})
|
|
63
|
+
return {}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _extract_usage_from_response(llm_response) -> dict:
|
|
67
|
+
"""Extract token usage from a Google ADK LLM response.
|
|
68
|
+
|
|
69
|
+
Google ADK responses typically have usage_metadata with:
|
|
70
|
+
- prompt_token_count (input tokens)
|
|
71
|
+
- candidates_token_count (output tokens)
|
|
72
|
+
- total_token_count
|
|
73
|
+
"""
|
|
74
|
+
usage = {}
|
|
75
|
+
if llm_response is None:
|
|
76
|
+
return usage
|
|
77
|
+
|
|
78
|
+
# Try to get usage_metadata from the response object
|
|
79
|
+
usage_metadata = getattr(llm_response, "usage_metadata", None)
|
|
80
|
+
if usage_metadata:
|
|
81
|
+
input_tokens = getattr(usage_metadata, "prompt_token_count", 0)
|
|
82
|
+
output_tokens = getattr(usage_metadata, "candidates_token_count", 0)
|
|
83
|
+
usage = {
|
|
84
|
+
"input_tokens": input_tokens or 0,
|
|
85
|
+
"output_tokens": output_tokens or 0,
|
|
86
|
+
}
|
|
87
|
+
elif isinstance(llm_response, dict):
|
|
88
|
+
um = llm_response.get("usage_metadata", {})
|
|
89
|
+
usage = {
|
|
90
|
+
"input_tokens": um.get("prompt_token_count", 0),
|
|
91
|
+
"output_tokens": um.get("candidates_token_count", 0),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return usage
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _extract_model_id(callback_context) -> str:
|
|
98
|
+
"""Extract model ID from ADK callback context."""
|
|
99
|
+
if callback_context is None:
|
|
100
|
+
return ""
|
|
101
|
+
# Prefer model info from the agent object
|
|
102
|
+
agent = getattr(callback_context, "agent", None)
|
|
103
|
+
if agent:
|
|
104
|
+
model = getattr(agent, "model", None)
|
|
105
|
+
if isinstance(model, str) and model:
|
|
106
|
+
return model
|
|
107
|
+
model_id = getattr(agent, "model_id", None)
|
|
108
|
+
if isinstance(model_id, str) and model_id:
|
|
109
|
+
return model_id
|
|
110
|
+
# Fall back to context-level model_id
|
|
111
|
+
model_id = getattr(callback_context, "model_id", None)
|
|
112
|
+
if isinstance(model_id, str) and model_id:
|
|
113
|
+
return model_id
|
|
114
|
+
return ""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _extract_agent_name(callback_context) -> str:
|
|
118
|
+
"""Extract agent name from ADK callback context."""
|
|
119
|
+
if callback_context is None:
|
|
120
|
+
return ""
|
|
121
|
+
agent = getattr(callback_context, "agent", None)
|
|
122
|
+
if agent:
|
|
123
|
+
return getattr(agent, "name", "") or ""
|
|
124
|
+
return getattr(callback_context, "agent_name", "") or ""
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class AigpAdkCallback:
|
|
128
|
+
"""Google ADK callback implementing AIGP governance.
|
|
129
|
+
|
|
130
|
+
Usage with Google ADK:
|
|
131
|
+
from google.adk import Agent
|
|
132
|
+
from aigp_google_adk import AigpAdkGovernance
|
|
133
|
+
|
|
134
|
+
governance = AigpAdkGovernance(gov_url=..., app_id=..., hmac_secret=...)
|
|
135
|
+
callback = governance.callback()
|
|
136
|
+
|
|
137
|
+
agent = Agent(
|
|
138
|
+
model="gemini-2.0-flash",
|
|
139
|
+
name="my-agent",
|
|
140
|
+
before_model_callback=callback.before_model_callback,
|
|
141
|
+
after_model_callback=callback.after_model_callback,
|
|
142
|
+
before_tool_callback=callback.before_tool_callback,
|
|
143
|
+
after_tool_callback=callback.after_tool_callback,
|
|
144
|
+
)
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
def __init__(self, governance, *, agent_name: str = "", model_id: str = "",
|
|
148
|
+
user_id: str = ""):
|
|
149
|
+
self._gov = governance
|
|
150
|
+
self._agent_name = agent_name
|
|
151
|
+
self._model_id = model_id
|
|
152
|
+
self._user_id = user_id
|
|
153
|
+
self._tool_start_times: dict[str, float] = {}
|
|
154
|
+
self._invoked = False
|
|
155
|
+
self._last_response: Any = None
|
|
156
|
+
|
|
157
|
+
def before_model_callback(self, callback_context=None, llm_request=None, **kwargs):
|
|
158
|
+
"""Called before each model invocation in Google ADK.
|
|
159
|
+
|
|
160
|
+
On first call, triggers pre_invoke to send AIGP CHECK.
|
|
161
|
+
Returns None to allow the request to proceed (returning a response
|
|
162
|
+
would skip the model call in ADK).
|
|
163
|
+
"""
|
|
164
|
+
if not self._invoked:
|
|
165
|
+
agent_name = self._agent_name or _extract_agent_name(callback_context)
|
|
166
|
+
model_id = self._model_id or _extract_model_id(callback_context)
|
|
167
|
+
self._gov.pre_invoke(agent_name, model_id, self._user_id)
|
|
168
|
+
self._invoked = True
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
def after_model_callback(self, callback_context=None, llm_response=None, **kwargs):
|
|
172
|
+
"""Called after each model response in Google ADK.
|
|
173
|
+
|
|
174
|
+
Extracts token usage from the response and accumulates via on_model_call.
|
|
175
|
+
Returns None to pass the response through unchanged.
|
|
176
|
+
"""
|
|
177
|
+
usage = _extract_usage_from_response(llm_response)
|
|
178
|
+
self._gov.on_model_call(usage=usage)
|
|
179
|
+
self._last_response = llm_response
|
|
180
|
+
return None
|
|
181
|
+
|
|
182
|
+
def before_tool_callback(self, callback_context=None, tool_name: str = "",
|
|
183
|
+
tool_input: Any = None, **kwargs):
|
|
184
|
+
"""Called before a tool execution in Google ADK.
|
|
185
|
+
|
|
186
|
+
Records the start time for duration tracking.
|
|
187
|
+
Returns None to allow the tool call to proceed.
|
|
188
|
+
"""
|
|
189
|
+
self._tool_start_times[tool_name] = time.time()
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
def after_tool_callback(self, callback_context=None, tool_name: str = "",
|
|
193
|
+
tool_output: Any = None, **kwargs):
|
|
194
|
+
"""Called after a tool execution in Google ADK.
|
|
195
|
+
|
|
196
|
+
Computes duration and sends tool governance via on_tool_call.
|
|
197
|
+
Returns None to pass the output through unchanged.
|
|
198
|
+
"""
|
|
199
|
+
start = self._tool_start_times.pop(tool_name, time.time())
|
|
200
|
+
duration_ms = int((time.time() - start) * 1000)
|
|
201
|
+
result_str = str(tool_output) if tool_output is not None else ""
|
|
202
|
+
|
|
203
|
+
_run_async(self._gov.on_tool_call(tool_name, duration_ms=duration_ms, result=result_str))
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
def on_agent_end(self, result: Any = None, **kwargs):
|
|
207
|
+
"""Call when the ADK agent completes its execution.
|
|
208
|
+
|
|
209
|
+
Sets D-SIG output metadata and calls post_invoke.
|
|
210
|
+
This should be called manually after agent.run() completes,
|
|
211
|
+
or via the governed_run() wrapper.
|
|
212
|
+
"""
|
|
213
|
+
content_type = _detect_content_type(result)
|
|
214
|
+
metadata = _extract_metadata(result)
|
|
215
|
+
self._gov.set_output_metadata(content_type, metadata)
|
|
216
|
+
_run_async(self._gov.post_invoke())
|
|
217
|
+
|
|
218
|
+
def on_agent_error(self, error: Exception, **kwargs):
|
|
219
|
+
"""Call on agent error."""
|
|
220
|
+
_run_async(self._gov.on_error(error))
|
|
221
|
+
|
|
222
|
+
def reset(self):
|
|
223
|
+
"""Reset the callback state for reuse across multiple invocations."""
|
|
224
|
+
self._invoked = False
|
|
225
|
+
self._tool_start_times.clear()
|
|
226
|
+
self._last_response = None
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "maigp-google-adk"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "AIGP governance adapter for Google ADK (Agent Development Kit)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = ["maigp-agent-core>=1.0.0", "google-adk>=0.1.0"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
otel = ["opentelemetry-api>=1.20"]
|
|
15
|
+
|
|
16
|
+
[tool.hatch.build.targets.wheel]
|
|
17
|
+
packages = ["aigp_google_adk"]
|
|
File without changes
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""Tests for AIGP Google ADK adapter."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from unittest.mock import AsyncMock, MagicMock, patch
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# ── Mock out aigp_agent_core to avoid dependency on aigp_client ──
|
|
10
|
+
@pytest.fixture(autouse=True)
|
|
11
|
+
def mock_aigp_core(monkeypatch):
|
|
12
|
+
"""Provide mock aigp_agent_core so handler.py can be imported."""
|
|
13
|
+
mock_core = MagicMock()
|
|
14
|
+
|
|
15
|
+
class _MockGovernanceBlockedError(Exception):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
mock_core.AgentGovernance = MagicMock
|
|
19
|
+
mock_core.governance = MagicMock()
|
|
20
|
+
mock_core.governance.GovernanceBlockedError = _MockGovernanceBlockedError
|
|
21
|
+
|
|
22
|
+
monkeypatch.setitem(sys.modules, "aigp_agent_core", mock_core)
|
|
23
|
+
monkeypatch.setitem(sys.modules, "aigp_agent_core.governance", mock_core.governance)
|
|
24
|
+
|
|
25
|
+
# Also mock the governance module to avoid transitive import
|
|
26
|
+
mock_gov_module = MagicMock()
|
|
27
|
+
monkeypatch.setitem(sys.modules, "aigp_google_adk.governance", mock_gov_module)
|
|
28
|
+
|
|
29
|
+
return mock_core
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture
|
|
33
|
+
def handler_module(mock_aigp_core):
|
|
34
|
+
"""Import handler module after mocking dependencies."""
|
|
35
|
+
if "aigp_google_adk.handler" in sys.modules:
|
|
36
|
+
del sys.modules["aigp_google_adk.handler"]
|
|
37
|
+
if "aigp_google_adk" in sys.modules:
|
|
38
|
+
del sys.modules["aigp_google_adk"]
|
|
39
|
+
from aigp_google_adk.handler import (
|
|
40
|
+
AigpAdkCallback,
|
|
41
|
+
_detect_content_type,
|
|
42
|
+
_extract_metadata,
|
|
43
|
+
_extract_usage_from_response,
|
|
44
|
+
)
|
|
45
|
+
return AigpAdkCallback, _detect_content_type, _extract_metadata, _extract_usage_from_response
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@pytest.fixture
|
|
49
|
+
def mock_governance():
|
|
50
|
+
"""Create a mock governance instance with all required methods."""
|
|
51
|
+
gov = MagicMock()
|
|
52
|
+
gov.pre_invoke = MagicMock()
|
|
53
|
+
gov.on_model_call = MagicMock()
|
|
54
|
+
gov.set_output_metadata = MagicMock()
|
|
55
|
+
gov.post_invoke = AsyncMock()
|
|
56
|
+
gov.on_error = AsyncMock()
|
|
57
|
+
gov.on_tool_call = AsyncMock()
|
|
58
|
+
return gov
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@pytest.fixture
|
|
62
|
+
def callback(handler_module, mock_governance):
|
|
63
|
+
"""Create an AigpAdkCallback with mock governance."""
|
|
64
|
+
AigpAdkCallback, _, _, _ = handler_module
|
|
65
|
+
return AigpAdkCallback(mock_governance, agent_name="test-agent", model_id="gemini-2.0-flash", user_id="user-1")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
69
|
+
# Test 1: before_model_callback triggers pre_invoke
|
|
70
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
71
|
+
|
|
72
|
+
class TestBeforeModelCallback:
|
|
73
|
+
"""Test that before_model_callback triggers AIGP CHECK via pre_invoke."""
|
|
74
|
+
|
|
75
|
+
def test_first_call_triggers_pre_invoke(self, callback, mock_governance):
|
|
76
|
+
"""First before_model_callback should call pre_invoke."""
|
|
77
|
+
result = callback.before_model_callback(callback_context=None, llm_request=None)
|
|
78
|
+
|
|
79
|
+
mock_governance.pre_invoke.assert_called_once_with("test-agent", "gemini-2.0-flash", "user-1")
|
|
80
|
+
assert result is None # None means allow request to proceed
|
|
81
|
+
|
|
82
|
+
def test_subsequent_calls_do_not_re_invoke(self, callback, mock_governance):
|
|
83
|
+
"""Second before_model_callback should not call pre_invoke again."""
|
|
84
|
+
callback.before_model_callback()
|
|
85
|
+
callback.before_model_callback()
|
|
86
|
+
|
|
87
|
+
mock_governance.pre_invoke.assert_called_once()
|
|
88
|
+
|
|
89
|
+
def test_extracts_agent_name_from_context(self, handler_module, mock_governance):
|
|
90
|
+
"""Should extract agent name from callback_context if not set."""
|
|
91
|
+
AigpAdkCallback, _, _, _ = handler_module
|
|
92
|
+
cb = AigpAdkCallback(mock_governance)
|
|
93
|
+
|
|
94
|
+
# Create mock callback context with agent
|
|
95
|
+
ctx = MagicMock()
|
|
96
|
+
ctx.agent = MagicMock()
|
|
97
|
+
ctx.agent.name = "context-agent"
|
|
98
|
+
ctx.agent.model = "gemini-pro"
|
|
99
|
+
|
|
100
|
+
cb.before_model_callback(callback_context=ctx)
|
|
101
|
+
|
|
102
|
+
mock_governance.pre_invoke.assert_called_once_with("context-agent", "gemini-pro", "")
|
|
103
|
+
|
|
104
|
+
def test_returns_none_to_allow_request(self, callback, mock_governance):
|
|
105
|
+
"""before_model_callback must return None to not skip the model call."""
|
|
106
|
+
result = callback.before_model_callback()
|
|
107
|
+
assert result is None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
111
|
+
# Test 2: after_model_callback accumulates tokens
|
|
112
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
113
|
+
|
|
114
|
+
class TestAfterModelCallback:
|
|
115
|
+
"""Test that after_model_callback records token usage."""
|
|
116
|
+
|
|
117
|
+
def test_extracts_usage_from_response_object(self, callback, mock_governance):
|
|
118
|
+
"""Should extract token usage from response with usage_metadata attr."""
|
|
119
|
+
response = MagicMock()
|
|
120
|
+
response.usage_metadata = MagicMock()
|
|
121
|
+
response.usage_metadata.prompt_token_count = 150
|
|
122
|
+
response.usage_metadata.candidates_token_count = 75
|
|
123
|
+
|
|
124
|
+
result = callback.after_model_callback(llm_response=response)
|
|
125
|
+
|
|
126
|
+
mock_governance.on_model_call.assert_called_once_with(
|
|
127
|
+
usage={"input_tokens": 150, "output_tokens": 75}
|
|
128
|
+
)
|
|
129
|
+
assert result is None
|
|
130
|
+
|
|
131
|
+
def test_extracts_usage_from_dict_response(self, callback, mock_governance):
|
|
132
|
+
"""Should extract token usage from dict-format response."""
|
|
133
|
+
response = {
|
|
134
|
+
"usage_metadata": {
|
|
135
|
+
"prompt_token_count": 200,
|
|
136
|
+
"candidates_token_count": 100,
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
callback.after_model_callback(llm_response=response)
|
|
141
|
+
|
|
142
|
+
mock_governance.on_model_call.assert_called_once_with(
|
|
143
|
+
usage={"input_tokens": 200, "output_tokens": 100}
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
def test_handles_none_response(self, callback, mock_governance):
|
|
147
|
+
"""Should handle None response gracefully."""
|
|
148
|
+
callback.after_model_callback(llm_response=None)
|
|
149
|
+
|
|
150
|
+
mock_governance.on_model_call.assert_called_once_with(usage={})
|
|
151
|
+
|
|
152
|
+
def test_handles_response_without_usage(self, callback, mock_governance):
|
|
153
|
+
"""Should handle response without usage_metadata."""
|
|
154
|
+
response = MagicMock(spec=[]) # No attributes
|
|
155
|
+
|
|
156
|
+
callback.after_model_callback(llm_response=response)
|
|
157
|
+
|
|
158
|
+
mock_governance.on_model_call.assert_called_once_with(usage={})
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
162
|
+
# Test 3: Tool callbacks
|
|
163
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
164
|
+
|
|
165
|
+
class TestToolCallbacks:
|
|
166
|
+
"""Test before_tool_callback and after_tool_callback governance."""
|
|
167
|
+
|
|
168
|
+
def test_before_tool_records_start_time(self, callback):
|
|
169
|
+
"""before_tool_callback should record start time."""
|
|
170
|
+
result = callback.before_tool_callback(tool_name="search_web", tool_input={"q": "test"})
|
|
171
|
+
|
|
172
|
+
assert "search_web" in callback._tool_start_times
|
|
173
|
+
assert result is None
|
|
174
|
+
|
|
175
|
+
def test_after_tool_calls_governance(self, callback, mock_governance):
|
|
176
|
+
"""after_tool_callback should call on_tool_call with name and duration."""
|
|
177
|
+
callback.before_tool_callback(tool_name="calculator", tool_input={})
|
|
178
|
+
callback.after_tool_callback(tool_name="calculator", tool_output="42")
|
|
179
|
+
|
|
180
|
+
mock_governance.on_tool_call.assert_called_once()
|
|
181
|
+
call_kwargs = mock_governance.on_tool_call.call_args[1]
|
|
182
|
+
assert call_kwargs["result"] == "42"
|
|
183
|
+
assert "duration_ms" in call_kwargs
|
|
184
|
+
|
|
185
|
+
def test_after_tool_cleans_up_start_time(self, callback, mock_governance):
|
|
186
|
+
"""after_tool_callback should remove tool from tracking."""
|
|
187
|
+
callback.before_tool_callback(tool_name="my_tool")
|
|
188
|
+
callback.after_tool_callback(tool_name="my_tool", tool_output="ok")
|
|
189
|
+
|
|
190
|
+
assert "my_tool" not in callback._tool_start_times
|
|
191
|
+
|
|
192
|
+
def test_multiple_tools_tracked_independently(self, callback, mock_governance):
|
|
193
|
+
"""Multiple concurrent tools should be tracked independently."""
|
|
194
|
+
callback.before_tool_callback(tool_name="tool_a")
|
|
195
|
+
callback.before_tool_callback(tool_name="tool_b")
|
|
196
|
+
|
|
197
|
+
assert "tool_a" in callback._tool_start_times
|
|
198
|
+
assert "tool_b" in callback._tool_start_times
|
|
199
|
+
|
|
200
|
+
callback.after_tool_callback(tool_name="tool_a", tool_output="a")
|
|
201
|
+
assert "tool_a" not in callback._tool_start_times
|
|
202
|
+
assert "tool_b" in callback._tool_start_times
|
|
203
|
+
|
|
204
|
+
def test_after_tool_handles_missing_start(self, callback, mock_governance):
|
|
205
|
+
"""after_tool_callback should handle missing start gracefully."""
|
|
206
|
+
callback.after_tool_callback(tool_name="unknown", tool_output="result")
|
|
207
|
+
mock_governance.on_tool_call.assert_called_once()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
211
|
+
# Test 4: Agent end / D-SIG metadata
|
|
212
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
213
|
+
|
|
214
|
+
class TestAgentEnd:
|
|
215
|
+
"""Test on_agent_end sets D-SIG metadata and calls post_invoke."""
|
|
216
|
+
|
|
217
|
+
def test_on_agent_end_calls_post_invoke(self, callback, mock_governance):
|
|
218
|
+
"""on_agent_end should trigger post_invoke."""
|
|
219
|
+
callback.on_agent_end(result="done")
|
|
220
|
+
|
|
221
|
+
mock_governance.post_invoke.assert_called_once()
|
|
222
|
+
|
|
223
|
+
def test_sets_text_content_type_for_string(self, callback, mock_governance):
|
|
224
|
+
"""String result should set content_type='text'."""
|
|
225
|
+
callback.on_agent_end(result="Hello, world!")
|
|
226
|
+
|
|
227
|
+
mock_governance.set_output_metadata.assert_called_once_with("text", {})
|
|
228
|
+
|
|
229
|
+
def test_sets_content_type_from_dict(self, callback, mock_governance):
|
|
230
|
+
"""Dict with content_type key should use it."""
|
|
231
|
+
result = {"content_type": "image", "data": "base64..."}
|
|
232
|
+
callback.on_agent_end(result=result)
|
|
233
|
+
|
|
234
|
+
mock_governance.set_output_metadata.assert_called_once_with("image", {})
|
|
235
|
+
|
|
236
|
+
def test_extracts_metadata_from_result(self, callback, mock_governance):
|
|
237
|
+
"""Dict with metadata key should extract it."""
|
|
238
|
+
result = {"images": ["img.png"], "metadata": {"resolution": "1024x1024"}}
|
|
239
|
+
callback.on_agent_end(result=result)
|
|
240
|
+
|
|
241
|
+
mock_governance.set_output_metadata.assert_called_once_with(
|
|
242
|
+
"image", {"resolution": "1024x1024"}
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
def test_on_agent_error_calls_on_error(self, callback, mock_governance):
|
|
246
|
+
"""on_agent_error should forward to governance on_error."""
|
|
247
|
+
error = RuntimeError("Something failed")
|
|
248
|
+
callback.on_agent_error(error)
|
|
249
|
+
|
|
250
|
+
mock_governance.on_error.assert_called_once_with(error)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
254
|
+
# Test 5: Full lifecycle
|
|
255
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
256
|
+
|
|
257
|
+
class TestFullLifecycle:
|
|
258
|
+
"""Test complete agent lifecycle through ADK callbacks."""
|
|
259
|
+
|
|
260
|
+
def test_full_lifecycle(self, callback, mock_governance):
|
|
261
|
+
"""Full lifecycle: before_model → after_model → tool → end."""
|
|
262
|
+
# Model call
|
|
263
|
+
callback.before_model_callback()
|
|
264
|
+
response = MagicMock()
|
|
265
|
+
response.usage_metadata = MagicMock()
|
|
266
|
+
response.usage_metadata.prompt_token_count = 50
|
|
267
|
+
response.usage_metadata.candidates_token_count = 25
|
|
268
|
+
callback.after_model_callback(llm_response=response)
|
|
269
|
+
|
|
270
|
+
# Tool call
|
|
271
|
+
callback.before_tool_callback(tool_name="search")
|
|
272
|
+
callback.after_tool_callback(tool_name="search", tool_output="results")
|
|
273
|
+
|
|
274
|
+
# Agent end
|
|
275
|
+
callback.on_agent_end(result="Final answer")
|
|
276
|
+
|
|
277
|
+
mock_governance.pre_invoke.assert_called_once()
|
|
278
|
+
mock_governance.on_model_call.assert_called_once()
|
|
279
|
+
mock_governance.on_tool_call.assert_called_once()
|
|
280
|
+
mock_governance.set_output_metadata.assert_called_once_with("text", {})
|
|
281
|
+
mock_governance.post_invoke.assert_called_once()
|
|
282
|
+
|
|
283
|
+
def test_reset_allows_reuse(self, callback, mock_governance):
|
|
284
|
+
"""reset() should allow the callback to be reused."""
|
|
285
|
+
callback.before_model_callback()
|
|
286
|
+
callback.reset()
|
|
287
|
+
callback.before_model_callback()
|
|
288
|
+
|
|
289
|
+
# pre_invoke called twice (once per lifecycle)
|
|
290
|
+
assert mock_governance.pre_invoke.call_count == 2
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
294
|
+
# Test 6: Helper functions
|
|
295
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
296
|
+
|
|
297
|
+
class TestHelpers:
|
|
298
|
+
"""Test utility/helper functions."""
|
|
299
|
+
|
|
300
|
+
def test_detect_content_type_text(self, handler_module):
|
|
301
|
+
"""_detect_content_type should default to 'text'."""
|
|
302
|
+
_, _detect_content_type, _, _ = handler_module
|
|
303
|
+
assert _detect_content_type("hello") == "text"
|
|
304
|
+
assert _detect_content_type(42) == "text"
|
|
305
|
+
assert _detect_content_type(None) == "text"
|
|
306
|
+
|
|
307
|
+
def test_detect_content_type_from_dict(self, handler_module):
|
|
308
|
+
"""_detect_content_type should detect from dict keys."""
|
|
309
|
+
_, _detect_content_type, _, _ = handler_module
|
|
310
|
+
assert _detect_content_type({"content_type": "audio"}) == "audio"
|
|
311
|
+
assert _detect_content_type({"image": "data"}) == "image"
|
|
312
|
+
assert _detect_content_type({"images": []}) == "image"
|
|
313
|
+
assert _detect_content_type({"video": "data"}) == "video"
|
|
314
|
+
|
|
315
|
+
def test_extract_usage_from_response_object(self, handler_module):
|
|
316
|
+
"""_extract_usage_from_response with attrs."""
|
|
317
|
+
_, _, _, _extract_usage = handler_module
|
|
318
|
+
response = MagicMock()
|
|
319
|
+
response.usage_metadata = MagicMock()
|
|
320
|
+
response.usage_metadata.prompt_token_count = 100
|
|
321
|
+
response.usage_metadata.candidates_token_count = 50
|
|
322
|
+
assert _extract_usage(response) == {"input_tokens": 100, "output_tokens": 50}
|
|
323
|
+
|
|
324
|
+
def test_extract_usage_from_dict(self, handler_module):
|
|
325
|
+
"""_extract_usage_from_response with dict."""
|
|
326
|
+
_, _, _, _extract_usage = handler_module
|
|
327
|
+
response = {"usage_metadata": {"prompt_token_count": 80, "candidates_token_count": 40}}
|
|
328
|
+
assert _extract_usage(response) == {"input_tokens": 80, "output_tokens": 40}
|
|
329
|
+
|
|
330
|
+
def test_extract_usage_from_none(self, handler_module):
|
|
331
|
+
"""_extract_usage_from_response with None."""
|
|
332
|
+
_, _, _, _extract_usage = handler_module
|
|
333
|
+
assert _extract_usage(None) == {}
|