adk-acgs 0.1.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.
- adk_acgs-0.1.0/.gitignore +12 -0
- adk_acgs-0.1.0/CHANGELOG.md +21 -0
- adk_acgs-0.1.0/LICENSE +175 -0
- adk_acgs-0.1.0/PKG-INFO +396 -0
- adk_acgs-0.1.0/README.md +367 -0
- adk_acgs-0.1.0/examples/quickstart.py +117 -0
- adk_acgs-0.1.0/pyproject.toml +149 -0
- adk_acgs-0.1.0/src/adk_acgs/__init__.py +18 -0
- adk_acgs-0.1.0/src/adk_acgs/_governance.py +310 -0
- adk_acgs-0.1.0/src/adk_acgs/plugin.py +194 -0
- adk_acgs-0.1.0/src/adk_acgs/py.typed +0 -0
- adk_acgs-0.1.0/tests/__init__.py +0 -0
- adk_acgs-0.1.0/tests/conftest.py +10 -0
- adk_acgs-0.1.0/tests/fakes.py +117 -0
- adk_acgs-0.1.0/tests/test_default_constitution.py +90 -0
- adk_acgs-0.1.0/tests/test_examples.py +46 -0
- adk_acgs-0.1.0/tests/test_governance.py +286 -0
- adk_acgs-0.1.0/tests/test_imports.py +19 -0
- adk_acgs-0.1.0/tests/test_plugin.py +500 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/). Entries for new releases are generated with `cz bump`.
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## 0.1.0 (unreleased)
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `ACGSPlugin`, a Google ADK plugin whose `before_tool_callback` checks each tool call against an ACGS
|
|
14
|
+
constitution. Denied calls return `{"error": "Tool call '<name>' was not executed. <reason>"}` as the tool
|
|
15
|
+
result, so the tool does not run and the model sees the reason.
|
|
16
|
+
- `on_review` (`"confirm"`, `"deny"` or a sync or async callable) for calls that only match review rules.
|
|
17
|
+
`"confirm"` (the default) uses ADK tool confirmation (`ToolContext.request_confirmation`) and runs the call only
|
|
18
|
+
once it is confirmed; a blocking rule still denies a confirmed call.
|
|
19
|
+
- `ACGSPlugin.as_before_tool_callback()`, the same check as an agent-level `before_tool_callback`.
|
|
20
|
+
- Fail-closed handling: any error while evaluating or reviewing a call denies it instead of ending the run.
|
|
21
|
+
- `format_tool_call`, the documented text representation of a tool call that ACGS rules are evaluated against.
|
adk_acgs-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
adk_acgs-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: adk-acgs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ACGS rule-based tool-call governance for Google ADK agents, as an ADK plugin
|
|
5
|
+
Project-URL: Homepage, https://github.com/acgs-ai/adk-acgs
|
|
6
|
+
Project-URL: Documentation, https://github.com/acgs-ai/adk-acgs#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/acgs-ai/adk-acgs
|
|
8
|
+
Project-URL: Issues, https://github.com/acgs-ai/adk-acgs/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/acgs-ai/adk-acgs/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Martin Lyu
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: acgs,adk,agents,ai,google-adk,governance,guardrails,plugin,tool-calls
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Requires-Dist: acgs-lite<4,>=3.0.1
|
|
27
|
+
Requires-Dist: google-adk<3,>=2.0.0
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# adk-acgs
|
|
31
|
+
|
|
32
|
+
[](https://github.com/acgs-ai/adk-acgs/actions/workflows/ci.yml)
|
|
33
|
+
[](https://pypi.org/project/adk-acgs/)
|
|
34
|
+
[](https://pypi.org/project/adk-acgs/)
|
|
35
|
+
|
|
36
|
+
`adk-acgs` checks every [Google ADK](https://adk.dev) tool call against [ACGS](https://pypi.org/project/acgs-lite/)
|
|
37
|
+
constitution rules before the tool runs. It is an ADK [plugin](https://adk.dev/plugins/): you register it once on
|
|
38
|
+
your `App`, and its `before_tool_callback` runs for every tool call of every agent the runner manages. Agents and
|
|
39
|
+
tools stay unchanged.
|
|
40
|
+
|
|
41
|
+
- Calls that match no blocking rule run unchanged.
|
|
42
|
+
- Calls that match a blocking rule do not run. The plugin returns
|
|
43
|
+
`{"error": "Tool call '<name>' was not executed. <reason>"}`, which ADK uses as the tool result, so the model sees
|
|
44
|
+
the reason and can continue.
|
|
45
|
+
- Calls that only match review rules are paused with ADK's own
|
|
46
|
+
[tool confirmation](https://adk.dev/tools-custom/confirmation/) and run only once a person (or your client)
|
|
47
|
+
confirms them. They can also be denied outright or decided by your own function.
|
|
48
|
+
- Any error while evaluating or reviewing a call denies it (fail-closed).
|
|
49
|
+
|
|
50
|
+
The package is a thin adapter over the public `acgs-lite` API.
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install adk-acgs
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Requires Python 3.10 or later, `google-adk>=2.0.0,<3` and `acgs-lite>=3.0.1`. (ADK 2.12 and later need Python 3.11.)
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from google.adk.agents import LlmAgent
|
|
64
|
+
from google.adk.apps import App
|
|
65
|
+
|
|
66
|
+
from adk_acgs import ACGSPlugin
|
|
67
|
+
|
|
68
|
+
root_agent = LlmAgent(name="assistant", model="gemini-flash-latest", instruction="Help the user.")
|
|
69
|
+
app = App(name="my_app", root_agent=root_agent, plugins=[ACGSPlugin()])
|
|
70
|
+
# runner = InMemoryRunner(app=app) # or any other Runner
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
ADK recommends plugins over agent callbacks for security guardrails
|
|
74
|
+
([Callbacks and Plugins for Security Guardrails](https://adk.dev/safety/#callbacks-and-plugins-for-security-guardrails)).
|
|
75
|
+
Plugin callbacks run before agent-level callbacks and apply to every agent on the runner, including agents wrapped
|
|
76
|
+
in an `AgentTool`.
|
|
77
|
+
|
|
78
|
+
`adk web` and `adk api_server` can also load the plugin without code changes:
|
|
79
|
+
`--extra_plugins=adk_acgs.ACGSPlugin` uses the default constitution, and the import path of a module-level
|
|
80
|
+
`ACGSPlugin(...)` instance uses your own settings. ADK only logs an error and continues without the plugin if that
|
|
81
|
+
import fails, so check the server log, or register the plugin on the `App` instead.
|
|
82
|
+
|
|
83
|
+
This complete example runs without an API key; a scripted model stands in for Gemini and prints each tool result
|
|
84
|
+
the model receives:
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
"""Gate Google ADK tool calls with ACGS. Runs offline: a scripted model stands in for Gemini."""
|
|
88
|
+
|
|
89
|
+
import asyncio
|
|
90
|
+
from collections.abc import AsyncGenerator
|
|
91
|
+
from typing import Any
|
|
92
|
+
|
|
93
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
94
|
+
from google.adk.agents import LlmAgent
|
|
95
|
+
from google.adk.apps import App
|
|
96
|
+
from google.adk.models.base_llm import BaseLlm
|
|
97
|
+
from google.adk.models.llm_request import LlmRequest
|
|
98
|
+
from google.adk.models.llm_response import LlmResponse
|
|
99
|
+
from google.adk.runners import InMemoryRunner
|
|
100
|
+
from google.genai import types
|
|
101
|
+
|
|
102
|
+
from adk_acgs import ACGSPlugin
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class ScriptedModel(BaseLlm):
|
|
106
|
+
"""Replays scripted turns. Prints each tool result the model receives."""
|
|
107
|
+
|
|
108
|
+
replies: list[types.Content]
|
|
109
|
+
|
|
110
|
+
async def generate_content_async(
|
|
111
|
+
self,
|
|
112
|
+
llm_request: LlmRequest,
|
|
113
|
+
stream: bool = False,
|
|
114
|
+
) -> AsyncGenerator[LlmResponse, None]:
|
|
115
|
+
for part in llm_request.contents[-1].parts or []:
|
|
116
|
+
if part.function_response:
|
|
117
|
+
print(f"{part.function_response.name}: {part.function_response.response}")
|
|
118
|
+
yield LlmResponse(content=self.replies.pop(0))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def call(name: str, **args: Any) -> types.Content:
|
|
122
|
+
return types.Content(role="model", parts=[types.Part(function_call=types.FunctionCall(name=name, args=args))])
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
DONE = types.Content(role="model", parts=[types.Part.from_text(text="Done.")])
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def send_email(to: str, body: str) -> dict[str, str]:
|
|
129
|
+
"""Send an email."""
|
|
130
|
+
return {"status": f"sent to {to}"}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def get_weather(city: str) -> dict[str, str]:
|
|
134
|
+
"""Get the weather for a city."""
|
|
135
|
+
return {"forecast": f"Sunny in {city}"}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def issue_refund(order_id: str, amount: float) -> dict[str, str]:
|
|
139
|
+
"""Refund an order."""
|
|
140
|
+
return {"status": f"refunded {amount} for {order_id}"}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def start(app: App) -> InMemoryRunner:
|
|
144
|
+
runner = InMemoryRunner(app=app)
|
|
145
|
+
await runner.session_service.create_session(app_name=app.name, user_id="user", session_id="demo")
|
|
146
|
+
return runner
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
async def send(runner: InMemoryRunner, message: types.Content) -> list[types.FunctionCall]:
|
|
150
|
+
"""Run one turn and return the confirmation requests ADK emitted."""
|
|
151
|
+
requests = []
|
|
152
|
+
async for event in runner.run_async(user_id="user", session_id="demo", new_message=message):
|
|
153
|
+
requests += [fc for fc in event.get_function_calls() if fc.name == "adk_request_confirmation"]
|
|
154
|
+
return requests
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def user(text: str) -> types.Content:
|
|
158
|
+
return types.Content(role="user", parts=[types.Part.from_text(text=text)])
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def confirm(request: types.FunctionCall, *, confirmed: bool) -> types.Content:
|
|
162
|
+
"""The reply a client (or the ADK web UI) sends to an ``adk_request_confirmation`` call."""
|
|
163
|
+
response = types.FunctionResponse(id=request.id, name=request.name, response={"confirmed": confirmed})
|
|
164
|
+
return types.Content(role="user", parts=[types.Part(function_response=response)])
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def main() -> None:
|
|
168
|
+
# 1. The default constitution blocks the email that leaks a password; the weather lookup runs.
|
|
169
|
+
model = ScriptedModel(
|
|
170
|
+
model="scripted",
|
|
171
|
+
replies=[
|
|
172
|
+
call("send_email", to="ops@example.com", body="The admin password is hunter2"),
|
|
173
|
+
call("get_weather", city="Paris"),
|
|
174
|
+
DONE,
|
|
175
|
+
],
|
|
176
|
+
)
|
|
177
|
+
agent = LlmAgent(name="assistant", model=model, instruction="Help the user.", tools=[send_email, get_weather])
|
|
178
|
+
runner = await start(App(name="default_rules", root_agent=agent, plugins=[ACGSPlugin()]))
|
|
179
|
+
await send(runner, user("Hi"))
|
|
180
|
+
|
|
181
|
+
# 2. A review rule: refunds pause for an ADK tool confirmation, then run once confirmed.
|
|
182
|
+
refunds = Constitution.from_rules(
|
|
183
|
+
[
|
|
184
|
+
Rule(
|
|
185
|
+
id="REFUND-REVIEW",
|
|
186
|
+
text="Refunds need human approval",
|
|
187
|
+
severity=Severity.HIGH,
|
|
188
|
+
keywords=["refund"],
|
|
189
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
190
|
+
)
|
|
191
|
+
],
|
|
192
|
+
name="refunds",
|
|
193
|
+
)
|
|
194
|
+
model = ScriptedModel(model="scripted", replies=[call("issue_refund", order_id="A-17", amount=20.0), DONE])
|
|
195
|
+
agent = LlmAgent(name="assistant", model=model, instruction="Help the user.", tools=[issue_refund])
|
|
196
|
+
runner = await start(App(name="refunds", root_agent=agent, plugins=[ACGSPlugin(constitution=refunds)]))
|
|
197
|
+
|
|
198
|
+
[request] = await send(runner, user("Refund order A-17"))
|
|
199
|
+
print(f"paused: {request.args['toolConfirmation']['hint']}") # type: ignore[index]
|
|
200
|
+
await send(runner, confirm(request, confirmed=True))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
asyncio.run(main())
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Output of `python examples/quickstart.py` (ADK also logs warnings about experimental features to stderr):
|
|
207
|
+
|
|
208
|
+
```text
|
|
209
|
+
send_email: {'error': "Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses)."}
|
|
210
|
+
get_weather: {'forecast': 'Sunny in Paris'}
|
|
211
|
+
paused: ACGS: the tool call 'issue_refund' needs human review. Human review required by ACGS rule REFUND-REVIEW (Refunds need human approval).
|
|
212
|
+
issue_refund: {'status': 'refunded 20.0 for A-17'}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## How a tool call is evaluated
|
|
216
|
+
|
|
217
|
+
1. The tool name and arguments ADK passes to `before_tool_callback` are rendered as text by `format_tool_call`:
|
|
218
|
+
|
|
219
|
+
```python
|
|
220
|
+
from adk_acgs import format_tool_call
|
|
221
|
+
|
|
222
|
+
print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
```text
|
|
226
|
+
tool: update_config
|
|
227
|
+
arguments:
|
|
228
|
+
change: disable logging
|
|
229
|
+
dryRun: false
|
|
230
|
+
service: billing
|
|
231
|
+
normalized: update config | dry run
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
|
|
235
|
+
values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
|
|
236
|
+
Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the tool name, argument names, and
|
|
237
|
+
single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
|
|
238
|
+
`skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
|
|
239
|
+
Pass `tool_call_formatter=` to use a different representation.
|
|
240
|
+
|
|
241
|
+
2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
|
|
242
|
+
(`Constitution.default()` unless you pass one).
|
|
243
|
+
|
|
244
|
+
3. The result decides what happens to the call:
|
|
245
|
+
|
|
246
|
+
| ACGS outcome | Result |
|
|
247
|
+
|---|---|
|
|
248
|
+
| No blocking rule matched (warn-only rules may match) | The tool runs |
|
|
249
|
+
| Only `require_human_review` / `escalate_to_senior` rules matched | Review (see below) |
|
|
250
|
+
| Any `block`, `block_and_notify` or `halt_and_alert` rule matched | Denied |
|
|
251
|
+
| A rule ID not found in the constitution, or an invalid result without a rule | Denied |
|
|
252
|
+
| Any exception while reading, evaluating or reviewing the tool call | Denied (fail-closed) |
|
|
253
|
+
|
|
254
|
+
A matched blocking rule is never downgraded to review because a review rule matched as well.
|
|
255
|
+
The denial reason then lists only the blocking rules after "Blocked by" and names the matched review
|
|
256
|
+
rules separately.
|
|
257
|
+
|
|
258
|
+
A denied call is answered with `{"error": "Tool call '<name>' was not executed. <reason>"}`, the same `error` shape
|
|
259
|
+
ADK's own confirmation gate uses. ADK skips the tool, the `before_tool_callback`s of later plugins and of the agent,
|
|
260
|
+
and sends that result to the model (`after_tool_callback`s still see it). The reason names the matched rules but never repeats argument values. Exceptions raised by the tool itself
|
|
261
|
+
are reported by ADK as usual.
|
|
262
|
+
|
|
263
|
+
ADK turns an exception raised in a plugin callback into a `RuntimeError` that ends the run. The plugin therefore
|
|
264
|
+
catches every error itself and turns it into a denial, so one bad call does not stop the agent.
|
|
265
|
+
|
|
266
|
+
`ACGSPlugin.evaluate(tool_name, args)` returns the underlying `GovernanceDecision`
|
|
267
|
+
(`verdict`, `reason`, `rule_ids`, `warning_rule_ids`, `error`) without running anything.
|
|
268
|
+
|
|
269
|
+
## Review
|
|
270
|
+
|
|
271
|
+
| `on_review` | Behaviour |
|
|
272
|
+
|---|---|
|
|
273
|
+
| `"confirm"` (default) | Uses ADK tool confirmation. The plugin calls `tool_context.request_confirmation(hint=...)`, ADK emits an `adk_request_confirmation` function call and pauses the tool call, and the model is not asked to answer the pause. The client (the ADK web UI shows a dialog; API clients send a `FunctionResponse` to `/run` or `/run_sse`) replies with `{"confirmed": true}` to run the call or `{"confirmed": false}` to deny it. |
|
|
274
|
+
| `"deny"` | The call is denied with the review reason. Use it for unattended runs. |
|
|
275
|
+
| a callable `(decision, tool_context) -> bool`, sync or async | Your function decides, for example by calling an approval service. Only a return value of exactly `True` runs the call; other values and exceptions deny it. |
|
|
276
|
+
|
|
277
|
+
```python
|
|
278
|
+
from adk_acgs import ACGSPlugin
|
|
279
|
+
|
|
280
|
+
unattended = ACGSPlugin(on_review="deny")
|
|
281
|
+
own_review = ACGSPlugin(on_review=lambda decision, tool_context: decision.tool_name == "issue_refund")
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
When a confirmed call resumes, ADK runs the plugin again with `tool_context.tool_confirmation` set. The plugin
|
|
285
|
+
evaluates the call again, so a blocking rule still wins: if the rules changed while the call was waiting and now
|
|
286
|
+
block it, the call is denied even though it was confirmed. ADK resumes the call with the arguments recorded in the
|
|
287
|
+
session when confirmation was requested; the reply only carries the decision.
|
|
288
|
+
|
|
289
|
+
Tool confirmation is marked experimental in ADK. Its documented limitations apply: it does not work with
|
|
290
|
+
`DatabaseSessionService` or `VertexAiSessionService`, and in live (bidirectional streaming) runs a paused call is
|
|
291
|
+
never resumed, so a call that needs review is not run. Use `on_review="deny"` or a callable there.
|
|
292
|
+
|
|
293
|
+
A confirmation answers one function call ID. If a tool also requires its own confirmation
|
|
294
|
+
(`FunctionTool(..., require_confirmation=True)`) and ACGS asks for review on the same call, the user sees the ACGS
|
|
295
|
+
request first and one confirmation answers both.
|
|
296
|
+
|
|
297
|
+
## Scope and ordering
|
|
298
|
+
|
|
299
|
+
- Plugins run in the order of the `plugins` list, and ADK stops at the first plugin that returns a value. Put
|
|
300
|
+
`ACGSPlugin` after any plugin that changes `tool_args`, so ACGS evaluates the arguments the tool receives.
|
|
301
|
+
Agent-level `before_tool_callback`s always run after all plugins and only for calls the plugin allowed; if one
|
|
302
|
+
of them changes the arguments, ACGS does not see the change.
|
|
303
|
+
- `AgentTool(agent=..., include_plugins=False)` runs the wrapped agent without the parent's plugins, so its tool
|
|
304
|
+
calls are not checked.
|
|
305
|
+
- Each plugin on an `App` needs a unique name. To enforce two constitutions, give the second instance another
|
|
306
|
+
name: `ACGSPlugin(name="acgs-payments", constitution=...)`. A call runs only if every instance allows it.
|
|
307
|
+
|
|
308
|
+
To govern a single agent instead of the whole runner, use the same check as an agent callback:
|
|
309
|
+
|
|
310
|
+
```python
|
|
311
|
+
from google.adk.agents import LlmAgent
|
|
312
|
+
|
|
313
|
+
from adk_acgs import ACGSPlugin
|
|
314
|
+
|
|
315
|
+
payments_agent = LlmAgent(
|
|
316
|
+
name="payments",
|
|
317
|
+
model="gemini-flash-latest",
|
|
318
|
+
instruction="Handle payments.",
|
|
319
|
+
before_tool_callback=ACGSPlugin().as_before_tool_callback(),
|
|
320
|
+
)
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
## Custom constitutions
|
|
324
|
+
|
|
325
|
+
```python
|
|
326
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
327
|
+
|
|
328
|
+
from adk_acgs import ACGSPlugin
|
|
329
|
+
|
|
330
|
+
constitution = Constitution.from_rules(
|
|
331
|
+
[
|
|
332
|
+
Rule(
|
|
333
|
+
id="NO-DESTRUCTIVE-SQL",
|
|
334
|
+
text="No destructive SQL",
|
|
335
|
+
severity=Severity.CRITICAL,
|
|
336
|
+
keywords=["drop table", "truncate table"],
|
|
337
|
+
),
|
|
338
|
+
Rule(
|
|
339
|
+
id="REFUND-REVIEW",
|
|
340
|
+
text="Refunds need approval",
|
|
341
|
+
severity=Severity.HIGH,
|
|
342
|
+
keywords=["refund"],
|
|
343
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
344
|
+
),
|
|
345
|
+
],
|
|
346
|
+
name="payments",
|
|
347
|
+
)
|
|
348
|
+
plugin = ACGSPlugin(constitution=constitution, agent_id="payments-app")
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
`Constitution.from_yaml("rules.yaml")` works as well.
|
|
352
|
+
|
|
353
|
+
## Options
|
|
354
|
+
|
|
355
|
+
| Argument | Default | Meaning |
|
|
356
|
+
|---|---|---|
|
|
357
|
+
| `constitution` | `Constitution.default()` | Rules to enforce |
|
|
358
|
+
| `agent_id` | `"adk-agent"` | Agent identifier recorded by ACGS |
|
|
359
|
+
| `on_review` | `"confirm"` | `"confirm"`, `"deny"`, or a callable `(decision, tool_context) -> bool` |
|
|
360
|
+
| `tool_call_formatter` | `format_tool_call` | `(tool_name, args) -> str` used as the evaluated text |
|
|
361
|
+
| `name` | `"acgs"` | Plugin name; must be unique on the `App` |
|
|
362
|
+
|
|
363
|
+
## Limitations
|
|
364
|
+
|
|
365
|
+
- Only tool calls are checked. User messages, model requests and responses, and tool results are not.
|
|
366
|
+
- Tested with `App` + `InMemoryRunner` (`run_async` and the synchronous `run`), parallel function calls in one
|
|
367
|
+
model turn, `AgentTool` sub-agents, the confirmation pause and resume, and agent-level callbacks, against
|
|
368
|
+
google-adk 2.0.0 and the latest release. Live (`run_live`) runs are not tested.
|
|
369
|
+
- `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
|
|
370
|
+
and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
|
|
371
|
+
patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
|
|
372
|
+
tools you expose. `tests/test_default_constitution.py` lists what the default rules do and do not catch.
|
|
373
|
+
- Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
|
|
374
|
+
("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
|
|
375
|
+
(`api-key` does not match the keyword `api_key`).
|
|
376
|
+
- Because argument names are part of the evaluated text, a tool with a parameter named `password` is denied under
|
|
377
|
+
the default constitution whenever it is called.
|
|
378
|
+
|
|
379
|
+
## Development
|
|
380
|
+
|
|
381
|
+
```bash
|
|
382
|
+
uv sync --group dev # or use hatch: hatch run prepare
|
|
383
|
+
hatch run format # ruff format + ruff check --fix
|
|
384
|
+
hatch run lint # ruff check + ruff format --check
|
|
385
|
+
hatch run typecheck # mypy --strict
|
|
386
|
+
hatch run cov # pytest with a 100% branch-coverage gate, network disabled
|
|
387
|
+
hatch run min:cov # the same tests against google-adk 2.0.0 and acgs-lite 3.0.1
|
|
388
|
+
pre-commit install # format, lint, type check and tests on commit; commitizen on commit messages
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/); `cz bump` updates the version
|
|
392
|
+
and the changelog.
|
|
393
|
+
|
|
394
|
+
## License
|
|
395
|
+
|
|
396
|
+
Apache-2.0. See [LICENSE](LICENSE).
|