maigp-smolagents 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_smolagents-1.0.0/.gitignore +56 -0
- maigp_smolagents-1.0.0/PKG-INFO +152 -0
- maigp_smolagents-1.0.0/README.md +130 -0
- maigp_smolagents-1.0.0/maigp_smolagents/__init__.py +19 -0
- maigp_smolagents-1.0.0/maigp_smolagents/core.py +141 -0
- maigp_smolagents-1.0.0/maigp_smolagents/governance.py +34 -0
- maigp_smolagents-1.0.0/maigp_smolagents/model.py +103 -0
- maigp_smolagents-1.0.0/maigp_smolagents/tools.py +153 -0
- maigp_smolagents-1.0.0/pyproject.toml +25 -0
- maigp_smolagents-1.0.0/tests/__init__.py +0 -0
- maigp_smolagents-1.0.0/tests/test_real_smolagents.py +470 -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,152 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: maigp-smolagents
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: MAIGP governance adapter for Hugging Face smolagents (blocks model and tool calls, fails closed)
|
|
5
|
+
Project-URL: Homepage, https://causum.com/
|
|
6
|
+
Project-URL: Documentation, https://causum.com/
|
|
7
|
+
Project-URL: Repository, https://causum.com/
|
|
8
|
+
Author-email: Causum <engineering@causum.com>
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: maigp-agent-core>=1.4.0
|
|
11
|
+
Requires-Dist: maigp-client>=5.10.0
|
|
12
|
+
Requires-Dist: smolagents<2,>=1.19
|
|
13
|
+
Provides-Extra: agency
|
|
14
|
+
Requires-Dist: maigp-agent-core[agency]>=1.3.0; extra == 'agency'
|
|
15
|
+
Provides-Extra: agency-aws
|
|
16
|
+
Requires-Dist: maigp-agent-core[agency-aws]>=1.3.0; extra == 'agency-aws'
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: httpx>=0.25.0; extra == 'dev'
|
|
19
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
20
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# maigp-smolagents
|
|
24
|
+
|
|
25
|
+
MAIGP governance for Hugging Face [smolagents](https://github.com/huggingface/smolagents).
|
|
26
|
+
|
|
27
|
+
Part of **MAIGP**, the Mediated AI Governance Protocol: a runtime consent, scope and evidence layer for AI systems. Every governed call is **CHECK**ed (policy, scope, jurisdiction, circuit-breaker) before it runs and **RECORD**ed as evidence after.
|
|
28
|
+
|
|
29
|
+
`maigp-smolagents` stops a model call or a tool call that governance does not allow. It fails closed: if the authority cannot be reached, answers late or answers anything other than ALLOW, the call does not run.
|
|
30
|
+
|
|
31
|
+
## What it governs
|
|
32
|
+
|
|
33
|
+
| smolagents object | What it does here |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `smolagents.models.Model` (`generate`, `generate_stream`) | `GovernedModel` sends a **CHECK** before the inner model is invoked |
|
|
36
|
+
| `smolagents.tools.Tool` (`__call__`, `forward`) | `GovernedTool` sends a **TOOL_REQUEST** before the tool body runs |
|
|
37
|
+
|
|
38
|
+
Both are subclasses of the smolagents base classes, so an agent accepts them anywhere it accepts the originals. Nothing in smolagents is patched.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install maigp-smolagents
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
This pulls in `maigp-client`, `maigp-agent-core` and `smolagents`. Tested against smolagents 1.19, 1.20, 1.21, 1.23, 1.25 and 1.26 on Python 3.12. The dependency range is `smolagents>=1.19,<2`.
|
|
47
|
+
|
|
48
|
+
## Quick start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from smolagents import CodeAgent, InferenceClientModel, ToolCallingAgent, tool
|
|
52
|
+
from maigp_smolagents import MaigpGovernance
|
|
53
|
+
|
|
54
|
+
@tool
|
|
55
|
+
def transfer_funds(account: str, amount: int) -> str:
|
|
56
|
+
"""Move money between accounts.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
account: destination account
|
|
60
|
+
amount: amount to move
|
|
61
|
+
"""
|
|
62
|
+
return f"moved {amount} to {account}"
|
|
63
|
+
|
|
64
|
+
gov = MaigpGovernance(gov_url="https://gov.example.com", app_id="my-smolagents-app",
|
|
65
|
+
hmac_secret="secret")
|
|
66
|
+
|
|
67
|
+
model = InferenceClientModel() # any smolagents Model: OpenAIModel, LiteLLMModel, TransformersModel, ...
|
|
68
|
+
|
|
69
|
+
agent = ToolCallingAgent( # or CodeAgent(...)
|
|
70
|
+
tools=gov.tools([transfer_funds]), # every tool call is TOOL_REQUESTed first
|
|
71
|
+
model=gov.model(model), # every model call is CHECKed first
|
|
72
|
+
)
|
|
73
|
+
gov.require_governed(agent) # refuses an agent that has an ungoverned path
|
|
74
|
+
|
|
75
|
+
print(agent.run("Pay 5 to acct-9"))
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The same without the helper class: `governed_model(model, gov)` and `governed_tools(tools, gov)`, where `gov` is any `maigp_agent_core.AgentGovernance`.
|
|
79
|
+
|
|
80
|
+
## How blocking works
|
|
81
|
+
|
|
82
|
+
smolagents offers three places to hook in. Only two of them can stop a call.
|
|
83
|
+
|
|
84
|
+
- **`Model.generate` / `Model.generate_stream`.** The agent holds one model object and calls it for every step, for planning and for the final-answer step. `GovernedModel` is a `Model` subclass that holds the real model and calls it only after an allowing CHECK. This can block.
|
|
85
|
+
- **`Tool.__call__` / `Tool.forward`.** `ToolCallingAgent.execute_tool_call` calls `tool(**arguments)`. `GovernedTool` is a `Tool` subclass that holds the real tool and runs it only after an allowing TOOL_REQUEST. This can block.
|
|
86
|
+
- **Step callbacks** (`step_callbacks`, `agent.step_callbacks`) run after a step has finished. They cannot stop anything, so this package does not rely on them.
|
|
87
|
+
|
|
88
|
+
**CodeAgent.** A `CodeAgent` runs generated Python in `LocalPythonExecutor`, and the executor receives the agent's own tool objects (`agent.tools`) as the functions that code can call. Because you pass `GovernedTool` objects to the agent, a call from generated code (`transfer_funds("acct-9", 5)`) goes through the same `GovernedTool.__call__` and is governed exactly like a `ToolCallingAgent` call. A `try/except` in the generated code cannot turn a blocked call into a successful one. Positional and keyword calls hash to the same input hash.
|
|
89
|
+
|
|
90
|
+
**What the agent sees when a call is blocked**
|
|
91
|
+
|
|
92
|
+
- Tool call: `GovernedTool` raises `MaigpBlockedError`. smolagents reports it to the model as a tool error (`Error executing tool 'transfer_funds' ...: Blocked by AIGP governance: tool 'transfer_funds' DENY: <reason>`), and the run goes on. In a `CodeAgent` the error appears in the step's execution output.
|
|
93
|
+
- Model call: `GovernedModel` raises `MaigpBlockedError` before the inner model runs. smolagents wraps an exception from `generate` as `AgentGenerationError` and ends the run, so `agent.run(...)` raises `AgentGenerationError` with the `MaigpBlockedError` as `__cause__`. The one exception is smolagents' own final-answer fallback after `max_steps`, which catches a model error and returns the error text as the answer. The model still did not run.
|
|
94
|
+
|
|
95
|
+
## What is sent to the authority
|
|
96
|
+
|
|
97
|
+
- **Before every model call:** CHECK with `use_case` (default `smolagents`) and the model's `model_id`.
|
|
98
|
+
- **Before every tool call:** TOOL_REQUEST with `tool_id` (the tool name), `tool_version`, `input_parameters_hash` and the tool definition hash. The input hash is `sha256:` plus the SHA-256 of the canonical JSON (sorted keys, no spaces) of the call's arguments by parameter name. The definition hash is `maigp_client.tool_definition_hash(name, description, input_schema)`, where `input_schema` is `{"type": "object", "properties": tool.inputs, "required": [...]}`. This is what lets the authority deny a tool whose definition changed (`TOOL_DEFINITION_CHANGED`).
|
|
99
|
+
- **After every call that ran:** RECORD. For a model call it carries the token usage the model reported, the duration and the status. For a tool call it has `use_case="tool:<name>"`, `tool_manifest_hash`, the duration, the status (`ERROR` if the tool raised) and `output_ref`, which is `sha256:` plus the SHA-256 of the canonical JSON of the tool result. A call that was blocked is never recorded as run. A RECORD that fails is logged and cannot undo a call that already ran.
|
|
100
|
+
|
|
101
|
+
The client caches an allowing model CHECK for the `ttl_seconds` the authority returns (default 300 s) per use case and model id, so within that time one HTTP CHECK can cover several model calls. Have the authority return `ttl_seconds: 0` to CHECK every call. Tool requests are never cached.
|
|
102
|
+
|
|
103
|
+
## Configuration
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
gov.model(model, use_case="support-bot", check_timeout=10.0)
|
|
107
|
+
gov.tools(tools, use_case="support-bot", check_timeout=10.0, tool_version="1.0.0", model_id="my-model")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
| Option | Default | Meaning |
|
|
111
|
+
|---|---|---|
|
|
112
|
+
| `use_case` | `smolagents` | Use case sent in CHECK and RECORD (and the AIAP agency scope key) |
|
|
113
|
+
| `check_timeout` | `10.0` | Seconds a CHECK / TOOL_REQUEST (and agency request) may take. Slower means blocked |
|
|
114
|
+
| `tool_version` | `1.0.0` | `tool_version` in TOOL_REQUEST |
|
|
115
|
+
| `model_id` | empty | Recorded on tool-call RECORDs |
|
|
116
|
+
|
|
117
|
+
`MaigpGovernance(gov_url, app_id, hmac_secret, mode="ENFORCE" | "REPORT", agent_id=..., agency=AgencyGate(...))` is `maigp_agent_core.AgentGovernance`; see that package for the full constructor.
|
|
118
|
+
|
|
119
|
+
**AIAP agency (opt-in).** With `agency=AgencyGate(...)` on the governance, every allowed model and tool call also needs an agency grant for `use_case`; a refusal, an unreachable broker or a slow gate blocks the call. Install with `pip install 'maigp-smolagents[agency]'`.
|
|
120
|
+
|
|
121
|
+
## Fail-closed semantics
|
|
122
|
+
|
|
123
|
+
Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` let a call run. Each of these blocks the call, in `ENFORCE` and in `REPORT` mode:
|
|
124
|
+
|
|
125
|
+
- `DENY`, `RATE_LIMITED`, `UNCHECKED`
|
|
126
|
+
- a response with no decision, or a decision that is not a string
|
|
127
|
+
- an unreachable authority, a non-2xx answer, a non-JSON answer
|
|
128
|
+
- any exception in the CHECK path
|
|
129
|
+
- a CHECK slower than `check_timeout`
|
|
130
|
+
- a missing agency grant, when an agency gate is configured
|
|
131
|
+
|
|
132
|
+
A disabled client (`MaigpGovernance(gov_url="")`, which allows everything) is refused: `gov.model(...)` and `gov.tools(...)` raise `RuntimeError`.
|
|
133
|
+
|
|
134
|
+
`require_governed(agent)` raises `RuntimeError` when the agent has a model that is not a `GovernedModel`, a tool other than `final_answer` that is not a `GovernedTool`, or a `CodeAgent` with a non-local executor. It also checks managed agents.
|
|
135
|
+
|
|
136
|
+
## Limitations
|
|
137
|
+
|
|
138
|
+
- **Wrap what you give the agent.** The agent is only as governed as the model and tools you wrap. `add_base_tools=True` adds smolagents' own tools unwrapped, and `final_answer` is smolagents' built-in and is not governed (it has no side effect). Call `require_governed(agent)` after building the agent to catch both.
|
|
139
|
+
- **Remote executors are not supported.** `executor_type="docker" / "e2b" / "modal" / "wasm"` serialises each tool's source and runs it outside this process, where the governance wrapper does not run. `GovernedTool.to_dict()` raises so these executors fail instead of running an ungoverned copy, and `require_governed` rejects them. Use the local executor.
|
|
140
|
+
- **Managed agents** (`managed_agents=[...]`) are not tools. Governing the parent does not govern a sub-agent; build the sub-agent with `gov.model(...)` and `gov.tools(...) ` too. `require_governed` checks them.
|
|
141
|
+
- **The local executor is not a sandbox.** Governance decides whether a registered tool may be called. It does not limit what else generated code may do with the authorised imports; see the smolagents documentation on secure code execution.
|
|
142
|
+
- **Calls are synchronous.** smolagents is synchronous, so each CHECK blocks the calling thread until it is answered or `check_timeout` passes. The CHECK runs on a private event loop in a background thread, so this also works when called from inside a running event loop.
|
|
143
|
+
- Streaming (`stream_outputs=True`) is CHECKed once, before the first chunk, and RECORDed when the stream ends.
|
|
144
|
+
|
|
145
|
+
## Links
|
|
146
|
+
|
|
147
|
+
- Protocol, specs and adapter catalog: https://causum.com/
|
|
148
|
+
- Issues: https://causum.com/
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
License: Proprietary. © Causum.
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# maigp-smolagents
|
|
2
|
+
|
|
3
|
+
MAIGP governance for Hugging Face [smolagents](https://github.com/huggingface/smolagents).
|
|
4
|
+
|
|
5
|
+
Part of **MAIGP**, the Mediated AI Governance Protocol: a runtime consent, scope and evidence layer for AI systems. Every governed call is **CHECK**ed (policy, scope, jurisdiction, circuit-breaker) before it runs and **RECORD**ed as evidence after.
|
|
6
|
+
|
|
7
|
+
`maigp-smolagents` stops a model call or a tool call that governance does not allow. It fails closed: if the authority cannot be reached, answers late or answers anything other than ALLOW, the call does not run.
|
|
8
|
+
|
|
9
|
+
## What it governs
|
|
10
|
+
|
|
11
|
+
| smolagents object | What it does here |
|
|
12
|
+
|---|---|
|
|
13
|
+
| `smolagents.models.Model` (`generate`, `generate_stream`) | `GovernedModel` sends a **CHECK** before the inner model is invoked |
|
|
14
|
+
| `smolagents.tools.Tool` (`__call__`, `forward`) | `GovernedTool` sends a **TOOL_REQUEST** before the tool body runs |
|
|
15
|
+
|
|
16
|
+
Both are subclasses of the smolagents base classes, so an agent accepts them anywhere it accepts the originals. Nothing in smolagents is patched.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install maigp-smolagents
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This pulls in `maigp-client`, `maigp-agent-core` and `smolagents`. Tested against smolagents 1.19, 1.20, 1.21, 1.23, 1.25 and 1.26 on Python 3.12. The dependency range is `smolagents>=1.19,<2`.
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from smolagents import CodeAgent, InferenceClientModel, ToolCallingAgent, tool
|
|
30
|
+
from maigp_smolagents import MaigpGovernance
|
|
31
|
+
|
|
32
|
+
@tool
|
|
33
|
+
def transfer_funds(account: str, amount: int) -> str:
|
|
34
|
+
"""Move money between accounts.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
account: destination account
|
|
38
|
+
amount: amount to move
|
|
39
|
+
"""
|
|
40
|
+
return f"moved {amount} to {account}"
|
|
41
|
+
|
|
42
|
+
gov = MaigpGovernance(gov_url="https://gov.example.com", app_id="my-smolagents-app",
|
|
43
|
+
hmac_secret="secret")
|
|
44
|
+
|
|
45
|
+
model = InferenceClientModel() # any smolagents Model: OpenAIModel, LiteLLMModel, TransformersModel, ...
|
|
46
|
+
|
|
47
|
+
agent = ToolCallingAgent( # or CodeAgent(...)
|
|
48
|
+
tools=gov.tools([transfer_funds]), # every tool call is TOOL_REQUESTed first
|
|
49
|
+
model=gov.model(model), # every model call is CHECKed first
|
|
50
|
+
)
|
|
51
|
+
gov.require_governed(agent) # refuses an agent that has an ungoverned path
|
|
52
|
+
|
|
53
|
+
print(agent.run("Pay 5 to acct-9"))
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The same without the helper class: `governed_model(model, gov)` and `governed_tools(tools, gov)`, where `gov` is any `maigp_agent_core.AgentGovernance`.
|
|
57
|
+
|
|
58
|
+
## How blocking works
|
|
59
|
+
|
|
60
|
+
smolagents offers three places to hook in. Only two of them can stop a call.
|
|
61
|
+
|
|
62
|
+
- **`Model.generate` / `Model.generate_stream`.** The agent holds one model object and calls it for every step, for planning and for the final-answer step. `GovernedModel` is a `Model` subclass that holds the real model and calls it only after an allowing CHECK. This can block.
|
|
63
|
+
- **`Tool.__call__` / `Tool.forward`.** `ToolCallingAgent.execute_tool_call` calls `tool(**arguments)`. `GovernedTool` is a `Tool` subclass that holds the real tool and runs it only after an allowing TOOL_REQUEST. This can block.
|
|
64
|
+
- **Step callbacks** (`step_callbacks`, `agent.step_callbacks`) run after a step has finished. They cannot stop anything, so this package does not rely on them.
|
|
65
|
+
|
|
66
|
+
**CodeAgent.** A `CodeAgent` runs generated Python in `LocalPythonExecutor`, and the executor receives the agent's own tool objects (`agent.tools`) as the functions that code can call. Because you pass `GovernedTool` objects to the agent, a call from generated code (`transfer_funds("acct-9", 5)`) goes through the same `GovernedTool.__call__` and is governed exactly like a `ToolCallingAgent` call. A `try/except` in the generated code cannot turn a blocked call into a successful one. Positional and keyword calls hash to the same input hash.
|
|
67
|
+
|
|
68
|
+
**What the agent sees when a call is blocked**
|
|
69
|
+
|
|
70
|
+
- Tool call: `GovernedTool` raises `MaigpBlockedError`. smolagents reports it to the model as a tool error (`Error executing tool 'transfer_funds' ...: Blocked by AIGP governance: tool 'transfer_funds' DENY: <reason>`), and the run goes on. In a `CodeAgent` the error appears in the step's execution output.
|
|
71
|
+
- Model call: `GovernedModel` raises `MaigpBlockedError` before the inner model runs. smolagents wraps an exception from `generate` as `AgentGenerationError` and ends the run, so `agent.run(...)` raises `AgentGenerationError` with the `MaigpBlockedError` as `__cause__`. The one exception is smolagents' own final-answer fallback after `max_steps`, which catches a model error and returns the error text as the answer. The model still did not run.
|
|
72
|
+
|
|
73
|
+
## What is sent to the authority
|
|
74
|
+
|
|
75
|
+
- **Before every model call:** CHECK with `use_case` (default `smolagents`) and the model's `model_id`.
|
|
76
|
+
- **Before every tool call:** TOOL_REQUEST with `tool_id` (the tool name), `tool_version`, `input_parameters_hash` and the tool definition hash. The input hash is `sha256:` plus the SHA-256 of the canonical JSON (sorted keys, no spaces) of the call's arguments by parameter name. The definition hash is `maigp_client.tool_definition_hash(name, description, input_schema)`, where `input_schema` is `{"type": "object", "properties": tool.inputs, "required": [...]}`. This is what lets the authority deny a tool whose definition changed (`TOOL_DEFINITION_CHANGED`).
|
|
77
|
+
- **After every call that ran:** RECORD. For a model call it carries the token usage the model reported, the duration and the status. For a tool call it has `use_case="tool:<name>"`, `tool_manifest_hash`, the duration, the status (`ERROR` if the tool raised) and `output_ref`, which is `sha256:` plus the SHA-256 of the canonical JSON of the tool result. A call that was blocked is never recorded as run. A RECORD that fails is logged and cannot undo a call that already ran.
|
|
78
|
+
|
|
79
|
+
The client caches an allowing model CHECK for the `ttl_seconds` the authority returns (default 300 s) per use case and model id, so within that time one HTTP CHECK can cover several model calls. Have the authority return `ttl_seconds: 0` to CHECK every call. Tool requests are never cached.
|
|
80
|
+
|
|
81
|
+
## Configuration
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
gov.model(model, use_case="support-bot", check_timeout=10.0)
|
|
85
|
+
gov.tools(tools, use_case="support-bot", check_timeout=10.0, tool_version="1.0.0", model_id="my-model")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
| Option | Default | Meaning |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| `use_case` | `smolagents` | Use case sent in CHECK and RECORD (and the AIAP agency scope key) |
|
|
91
|
+
| `check_timeout` | `10.0` | Seconds a CHECK / TOOL_REQUEST (and agency request) may take. Slower means blocked |
|
|
92
|
+
| `tool_version` | `1.0.0` | `tool_version` in TOOL_REQUEST |
|
|
93
|
+
| `model_id` | empty | Recorded on tool-call RECORDs |
|
|
94
|
+
|
|
95
|
+
`MaigpGovernance(gov_url, app_id, hmac_secret, mode="ENFORCE" | "REPORT", agent_id=..., agency=AgencyGate(...))` is `maigp_agent_core.AgentGovernance`; see that package for the full constructor.
|
|
96
|
+
|
|
97
|
+
**AIAP agency (opt-in).** With `agency=AgencyGate(...)` on the governance, every allowed model and tool call also needs an agency grant for `use_case`; a refusal, an unreachable broker or a slow gate blocks the call. Install with `pip install 'maigp-smolagents[agency]'`.
|
|
98
|
+
|
|
99
|
+
## Fail-closed semantics
|
|
100
|
+
|
|
101
|
+
Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` let a call run. Each of these blocks the call, in `ENFORCE` and in `REPORT` mode:
|
|
102
|
+
|
|
103
|
+
- `DENY`, `RATE_LIMITED`, `UNCHECKED`
|
|
104
|
+
- a response with no decision, or a decision that is not a string
|
|
105
|
+
- an unreachable authority, a non-2xx answer, a non-JSON answer
|
|
106
|
+
- any exception in the CHECK path
|
|
107
|
+
- a CHECK slower than `check_timeout`
|
|
108
|
+
- a missing agency grant, when an agency gate is configured
|
|
109
|
+
|
|
110
|
+
A disabled client (`MaigpGovernance(gov_url="")`, which allows everything) is refused: `gov.model(...)` and `gov.tools(...)` raise `RuntimeError`.
|
|
111
|
+
|
|
112
|
+
`require_governed(agent)` raises `RuntimeError` when the agent has a model that is not a `GovernedModel`, a tool other than `final_answer` that is not a `GovernedTool`, or a `CodeAgent` with a non-local executor. It also checks managed agents.
|
|
113
|
+
|
|
114
|
+
## Limitations
|
|
115
|
+
|
|
116
|
+
- **Wrap what you give the agent.** The agent is only as governed as the model and tools you wrap. `add_base_tools=True` adds smolagents' own tools unwrapped, and `final_answer` is smolagents' built-in and is not governed (it has no side effect). Call `require_governed(agent)` after building the agent to catch both.
|
|
117
|
+
- **Remote executors are not supported.** `executor_type="docker" / "e2b" / "modal" / "wasm"` serialises each tool's source and runs it outside this process, where the governance wrapper does not run. `GovernedTool.to_dict()` raises so these executors fail instead of running an ungoverned copy, and `require_governed` rejects them. Use the local executor.
|
|
118
|
+
- **Managed agents** (`managed_agents=[...]`) are not tools. Governing the parent does not govern a sub-agent; build the sub-agent with `gov.model(...)` and `gov.tools(...) ` too. `require_governed` checks them.
|
|
119
|
+
- **The local executor is not a sandbox.** Governance decides whether a registered tool may be called. It does not limit what else generated code may do with the authorised imports; see the smolagents documentation on secure code execution.
|
|
120
|
+
- **Calls are synchronous.** smolagents is synchronous, so each CHECK blocks the calling thread until it is answered or `check_timeout` passes. The CHECK runs on a private event loop in a background thread, so this also works when called from inside a running event loop.
|
|
121
|
+
- Streaming (`stream_outputs=True`) is CHECKed once, before the first chunk, and RECORDed when the stream ends.
|
|
122
|
+
|
|
123
|
+
## Links
|
|
124
|
+
|
|
125
|
+
- Protocol, specs and adapter catalog: https://causum.com/
|
|
126
|
+
- Issues: https://causum.com/
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
License: Proprietary. © Causum.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""MAIGP governance for Hugging Face smolagents.
|
|
2
|
+
|
|
3
|
+
Wrap the model and the tools you give an agent; every model call is CHECKed and every tool call
|
|
4
|
+
is TOOL_REQUESTed before it runs, and anything but ALLOW / ALLOW_WITH_CONSTRAINTS does not run.
|
|
5
|
+
|
|
6
|
+
gov = MaigpGovernance(gov_url=..., app_id=..., hmac_secret=...)
|
|
7
|
+
agent = ToolCallingAgent(tools=gov.tools([...]), model=gov.model(model))
|
|
8
|
+
gov.require_governed(agent)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__version__ = "1.0.0"
|
|
12
|
+
|
|
13
|
+
from .core import MaigpBlockedError
|
|
14
|
+
from .governance import MaigpGovernance
|
|
15
|
+
from .model import GovernedModel, governed_model
|
|
16
|
+
from .tools import GovernedTool, governed_tools, require_governed
|
|
17
|
+
|
|
18
|
+
__all__ = ["MaigpGovernance", "MaigpBlockedError", "GovernedModel", "GovernedTool",
|
|
19
|
+
"governed_model", "governed_tools", "require_governed"]
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""The synchronous CHECK / RECORD bridge shared by the governed model and the governed tools.
|
|
2
|
+
|
|
3
|
+
smolagents is synchronous; the MAIGP client is async. Each ``Governor`` runs the client's
|
|
4
|
+
coroutines on one private event loop in a daemon thread, so the client's HTTP connection pool
|
|
5
|
+
stays on a single loop and the bridge works the same inside or outside a running event loop.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import threading
|
|
15
|
+
from typing import Any, Awaitable, Callable
|
|
16
|
+
|
|
17
|
+
from maigp_agent_core import AgencyRequiredError, GovernanceBlockedError
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
#: The only decisions that let a governed call run (same set as maigp-client / maigp-agent-core).
|
|
22
|
+
ALLOWING_DECISIONS = ("ALLOW", "ALLOW_WITH_CONSTRAINTS")
|
|
23
|
+
DEFAULT_CHECK_TIMEOUT_SECONDS = 10.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MaigpBlockedError(GovernanceBlockedError):
|
|
27
|
+
"""A model or tool call that governance did not allow. The call did not run."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, what: str, decision: str, reason: str, *, source: str = "AIGP"):
|
|
30
|
+
self.what, self.decision, self.reason = what, decision, reason
|
|
31
|
+
super().__init__(f"Blocked by {source} governance: {what} {decision}: {reason or 'no reason given'}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def sha256_ref(value: Any) -> str:
|
|
35
|
+
"""``sha256:<hex>`` of the canonical JSON of ``value`` (non-JSON values via ``str``)."""
|
|
36
|
+
try:
|
|
37
|
+
data = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
|
|
38
|
+
except (TypeError, ValueError):
|
|
39
|
+
data = str(value)
|
|
40
|
+
return "sha256:" + hashlib.sha256(data.encode()).hexdigest()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def decision_of(result: Any) -> tuple[str, str, str]:
|
|
44
|
+
"""(decision, reason, request_id); anything that is not a string decision is ``""`` (never ALLOW)."""
|
|
45
|
+
if result is None:
|
|
46
|
+
return "", "no decision returned", ""
|
|
47
|
+
get = result.get if isinstance(result, dict) else (lambda k, d="": getattr(result, k, d))
|
|
48
|
+
d = get("decision", "")
|
|
49
|
+
return (d if isinstance(d, str) else ""), str(get("reason", "") or ""), str(get("request_id", "") or "")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Governor:
|
|
53
|
+
"""Owns the governance, the timeout and the sync bridge for one governed model / tool set."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, governance: Any, *, use_case: str = "", check_timeout: float = DEFAULT_CHECK_TIMEOUT_SECONDS,
|
|
56
|
+
tool_version: str = "1.0.0", model_id: str = ""):
|
|
57
|
+
if check_timeout <= 0:
|
|
58
|
+
raise ValueError("check_timeout must be > 0")
|
|
59
|
+
client = getattr(governance, "client", None)
|
|
60
|
+
if client is None:
|
|
61
|
+
raise TypeError("governance must be a maigp_agent_core.AgentGovernance (it has no .client)")
|
|
62
|
+
self.refuse_if_disabled(governance)
|
|
63
|
+
self.gov, self.client = governance, client
|
|
64
|
+
self.use_case, self.check_timeout = use_case or "smolagents", check_timeout
|
|
65
|
+
self.tool_version, self.model_id = tool_version, model_id
|
|
66
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
67
|
+
self._lock = threading.Lock()
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def refuse_if_disabled(governance: Any) -> None:
|
|
71
|
+
# MaigpClient(enabled=False) (empty gov_url) answers ALLOW to everything without asking anyone:
|
|
72
|
+
# refusing keeps "governed" from meaning "open".
|
|
73
|
+
if getattr(getattr(governance, "client", None), "_enabled", True) is False:
|
|
74
|
+
raise RuntimeError("maigp-smolagents: governance client is disabled (no gov_url); "
|
|
75
|
+
"refusing to govern with a client that allows everything")
|
|
76
|
+
|
|
77
|
+
# ── sync bridge ──
|
|
78
|
+
def _get_loop(self) -> asyncio.AbstractEventLoop:
|
|
79
|
+
with self._lock:
|
|
80
|
+
if self._loop is None or self._loop.is_closed():
|
|
81
|
+
loop = asyncio.new_event_loop()
|
|
82
|
+
threading.Thread(target=loop.run_forever, name="maigp-smolagents", daemon=True).start()
|
|
83
|
+
self._loop = loop
|
|
84
|
+
return self._loop
|
|
85
|
+
|
|
86
|
+
def run(self, factory: Callable[[], Awaitable[Any]], timeout: float | None = None) -> Any:
|
|
87
|
+
async def bounded():
|
|
88
|
+
return await asyncio.wait_for(factory(), timeout=timeout)
|
|
89
|
+
fut = asyncio.run_coroutine_threadsafe(bounded(), self._get_loop())
|
|
90
|
+
try:
|
|
91
|
+
return fut.result(timeout=None if timeout is None else timeout + 5.0)
|
|
92
|
+
except BaseException:
|
|
93
|
+
fut.cancel()
|
|
94
|
+
raise
|
|
95
|
+
|
|
96
|
+
# ── CHECK path: never raises anything but MaigpBlockedError ──
|
|
97
|
+
def authorize(self, what: str, factory: Callable[[], Awaitable[Any]]) -> str:
|
|
98
|
+
"""Run one CHECK / TOOL_REQUEST. Returns the request_id when the call may run, else raises."""
|
|
99
|
+
if getattr(self.client, "_enabled", True) is False:
|
|
100
|
+
raise MaigpBlockedError(what, "UNCHECKED", "governance client is disabled")
|
|
101
|
+
try:
|
|
102
|
+
d, reason, request_id = decision_of(self.run(factory, self.check_timeout))
|
|
103
|
+
except (asyncio.TimeoutError, TimeoutError):
|
|
104
|
+
d, reason, request_id = "UNCHECKED", f"CHECK timed out after {self.check_timeout:g}s", ""
|
|
105
|
+
except BaseException as e: # fail closed: a broken CHECK path never lets the call through
|
|
106
|
+
if isinstance(e, (KeyboardInterrupt, SystemExit)):
|
|
107
|
+
raise
|
|
108
|
+
d, reason, request_id = "UNCHECKED", f"CHECK failed: {type(e).__name__}: {e}", ""
|
|
109
|
+
if d not in ALLOWING_DECISIONS:
|
|
110
|
+
logger.warning("AIGP: %s BLOCKED (%s): %s", what, d or "no decision", reason)
|
|
111
|
+
raise MaigpBlockedError(what, d or "UNCHECKED", reason)
|
|
112
|
+
self._agency(what, request_id)
|
|
113
|
+
return request_id
|
|
114
|
+
|
|
115
|
+
def _agency(self, what: str, request_id: str) -> None:
|
|
116
|
+
"""AIAP agency (opt-in): with a gate configured, an allowing CHECK also needs a grant."""
|
|
117
|
+
if getattr(self.gov, "agency", None) is None:
|
|
118
|
+
return
|
|
119
|
+
try:
|
|
120
|
+
self.run(lambda: self.gov.arequire_agency(self.use_case, trace_id=request_id), self.check_timeout)
|
|
121
|
+
return
|
|
122
|
+
except (asyncio.TimeoutError, TimeoutError):
|
|
123
|
+
code, reason = "TIMEOUT", f"agency request timed out after {self.check_timeout:g}s"
|
|
124
|
+
except AgencyRequiredError as e:
|
|
125
|
+
code, reason = (e.code or "REFUSED"), str(e)
|
|
126
|
+
except BaseException as e:
|
|
127
|
+
if isinstance(e, (KeyboardInterrupt, SystemExit)):
|
|
128
|
+
raise
|
|
129
|
+
code, reason = "BROKER_ERROR", f"agency gate failed: {type(e).__name__}: {e}"
|
|
130
|
+
logger.warning("AIAP: %s BLOCKED (agency %s): %s", what, code, reason)
|
|
131
|
+
raise MaigpBlockedError(what, code, reason, source="AIAP agency")
|
|
132
|
+
|
|
133
|
+
def record(self, **kw: Any) -> None:
|
|
134
|
+
"""RECORD a call that ran. A failing RECORD is logged; it cannot undo a call that already ran."""
|
|
135
|
+
try:
|
|
136
|
+
self.run(lambda: self.client.record(session_id=getattr(self.gov, "session_id", "") or "", **kw),
|
|
137
|
+
self.check_timeout)
|
|
138
|
+
except BaseException as e:
|
|
139
|
+
if isinstance(e, (KeyboardInterrupt, SystemExit)):
|
|
140
|
+
raise
|
|
141
|
+
logger.error("AIGP RECORD failed (%s): %s", kw.get("use_case"), e)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""MaigpGovernance: entry point for smolagents governance."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Iterable
|
|
6
|
+
|
|
7
|
+
from maigp_agent_core import AgentGovernance
|
|
8
|
+
|
|
9
|
+
from .model import GovernedModel, governed_model
|
|
10
|
+
from .tools import governed_tools, require_governed
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MaigpGovernance(AgentGovernance):
|
|
14
|
+
"""smolagents governance wrapper::
|
|
15
|
+
|
|
16
|
+
gov = MaigpGovernance(gov_url=..., app_id=..., hmac_secret=...)
|
|
17
|
+
agent = CodeAgent(tools=gov.tools([my_tool]), model=gov.model(model))
|
|
18
|
+
gov.require_governed(agent)
|
|
19
|
+
|
|
20
|
+
AIAP agency (opt-in): ``agency=AgencyGate(...)`` makes every allowed call also need a grant.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def model(self, model: Any, **kwargs: Any) -> GovernedModel:
|
|
24
|
+
"""See :func:`maigp_smolagents.governed_model` (kwargs: use_case, check_timeout)."""
|
|
25
|
+
return governed_model(model, self, **kwargs)
|
|
26
|
+
|
|
27
|
+
def tools(self, tools: Iterable[Any], **kwargs: Any) -> list:
|
|
28
|
+
"""See :func:`maigp_smolagents.governed_tools` (kwargs: use_case, check_timeout, tool_version, model_id)."""
|
|
29
|
+
return governed_tools(tools, self, **kwargs)
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def require_governed(agent: Any, **kwargs: Any) -> None:
|
|
33
|
+
"""See :func:`maigp_smolagents.require_governed`."""
|
|
34
|
+
require_governed(agent, **kwargs)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""GovernedModel: a smolagents ``Model`` that CHECKs before every ``generate`` / ``generate_stream``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from smolagents.models import Model
|
|
9
|
+
|
|
10
|
+
from .core import Governor
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _usage(message: Any) -> tuple[int, int]:
|
|
14
|
+
u = getattr(message, "token_usage", None)
|
|
15
|
+
return int(getattr(u, "input_tokens", 0) or 0), int(getattr(u, "output_tokens", 0) or 0)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GovernedModel(Model):
|
|
19
|
+
"""Wraps any smolagents ``Model``. smolagents calls ``model.generate(...)`` (or ``generate_stream``
|
|
20
|
+
when ``stream_outputs`` is on) for every agent step, the planning step and the final-answer step;
|
|
21
|
+
this class is the only thing the agent holds, so there is no path to the inner model around it.
|
|
22
|
+
|
|
23
|
+
A call that governance does not allow raises ``MaigpBlockedError`` before the inner model is
|
|
24
|
+
invoked. smolagents turns an exception from ``generate`` into ``AgentGenerationError``, which ends
|
|
25
|
+
the run (it is not retried): ``agent.run`` raises it, with the ``MaigpBlockedError`` as ``__cause__``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, inner: Model, governor: Governor):
|
|
29
|
+
# Not Model.__init__: every attribute not defined here is read from the inner model.
|
|
30
|
+
self._inner = inner
|
|
31
|
+
self._gov = governor
|
|
32
|
+
if not governor.model_id:
|
|
33
|
+
governor.model_id = str(getattr(inner, "model_id", "") or "")
|
|
34
|
+
self.model_id = governor.model_id
|
|
35
|
+
|
|
36
|
+
def __getattr__(self, name: str) -> Any: # only reached for attributes not found on GovernedModel
|
|
37
|
+
if name == "_inner":
|
|
38
|
+
raise AttributeError(name)
|
|
39
|
+
return getattr(self._inner, name)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def inner(self) -> Model:
|
|
43
|
+
return self._inner
|
|
44
|
+
|
|
45
|
+
def _check(self) -> str:
|
|
46
|
+
g = self._gov
|
|
47
|
+
return g.authorize("model call", lambda: g.client.check(use_case=g.use_case, model_id=g.model_id))
|
|
48
|
+
|
|
49
|
+
def _record(self, request_id: str, started: float, message: Any, error: bool) -> None:
|
|
50
|
+
g = self._gov
|
|
51
|
+
tin, tout = _usage(message)
|
|
52
|
+
g.record(use_case=g.use_case, model_id=g.model_id, request_id=request_id, input_tokens=tin,
|
|
53
|
+
output_tokens=tout, duration_ms=(time.monotonic() - started) * 1000,
|
|
54
|
+
status="ERROR" if error else "SUCCESS")
|
|
55
|
+
|
|
56
|
+
def generate(self, messages, stop_sequences=None, response_format=None, tools_to_call_from=None, **kwargs):
|
|
57
|
+
request_id = self._check()
|
|
58
|
+
started, message, error = time.monotonic(), None, True
|
|
59
|
+
try:
|
|
60
|
+
message = self._inner.generate(messages, stop_sequences=stop_sequences, response_format=response_format,
|
|
61
|
+
tools_to_call_from=tools_to_call_from, **kwargs)
|
|
62
|
+
error = False
|
|
63
|
+
return message
|
|
64
|
+
finally:
|
|
65
|
+
self._record(request_id, started, message, error)
|
|
66
|
+
|
|
67
|
+
def __call__(self, *args, **kwargs):
|
|
68
|
+
return self.generate(*args, **kwargs)
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def generate_stream(self):
|
|
72
|
+
# smolagents tests ``hasattr(model, "generate_stream")``: expose it only when the inner model has it.
|
|
73
|
+
inner_stream = self._inner.generate_stream # AttributeError here = not a streaming model
|
|
74
|
+
|
|
75
|
+
def generate_stream(messages, stop_sequences=None, response_format=None, tools_to_call_from=None, **kwargs):
|
|
76
|
+
request_id = self._check() # runs on the first next(), before the inner stream is started
|
|
77
|
+
started, last, error = time.monotonic(), None, True
|
|
78
|
+
try:
|
|
79
|
+
for delta in inner_stream(messages, stop_sequences=stop_sequences, response_format=response_format,
|
|
80
|
+
tools_to_call_from=tools_to_call_from, **kwargs):
|
|
81
|
+
if getattr(delta, "token_usage", None) is not None:
|
|
82
|
+
last = delta
|
|
83
|
+
yield delta
|
|
84
|
+
error = False
|
|
85
|
+
finally:
|
|
86
|
+
self._record(request_id, started, last, error)
|
|
87
|
+
return generate_stream
|
|
88
|
+
|
|
89
|
+
def parse_tool_calls(self, message):
|
|
90
|
+
return self._inner.parse_tool_calls(message)
|
|
91
|
+
|
|
92
|
+
def to_dict(self) -> dict:
|
|
93
|
+
return self._inner.to_dict()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def governed_model(model: Model, governance: Any, *, use_case: str = "", check_timeout: float = 10.0) -> GovernedModel:
|
|
97
|
+
"""Wrap ``model`` so every model call is CHECKed first (fail closed). ``use_case`` defaults to
|
|
98
|
+
``"smolagents"``; ``check_timeout`` (seconds) bounds the CHECK."""
|
|
99
|
+
if isinstance(model, GovernedModel):
|
|
100
|
+
return model
|
|
101
|
+
if not isinstance(model, Model):
|
|
102
|
+
raise TypeError(f"governed_model expects a smolagents Model, got {type(model).__name__}")
|
|
103
|
+
return GovernedModel(model, Governor(governance, use_case=use_case, check_timeout=check_timeout))
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""GovernedTool: a smolagents ``Tool`` that sends TOOL_REQUEST before its body can run."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Iterable
|
|
8
|
+
|
|
9
|
+
from smolagents.tools import Tool
|
|
10
|
+
|
|
11
|
+
from .core import Governor, MaigpBlockedError, sha256_ref
|
|
12
|
+
|
|
13
|
+
_NO_RESULT = object()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _definition(tool: Tool) -> dict:
|
|
17
|
+
"""{name, description, input_schema} as the model is shown it (JSON-schema form of ``inputs``)."""
|
|
18
|
+
props, required = {}, []
|
|
19
|
+
for key, spec in tool.inputs.items():
|
|
20
|
+
spec = dict(spec)
|
|
21
|
+
props[key] = spec
|
|
22
|
+
if not spec.get("nullable"):
|
|
23
|
+
required.append(key)
|
|
24
|
+
return {"name": tool.name, "description": tool.description,
|
|
25
|
+
"input_schema": {"type": "object", "properties": props, "required": required}}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class GovernedTool(Tool):
|
|
29
|
+
"""Wraps a smolagents ``Tool`` under the same name, description, inputs and output type.
|
|
30
|
+
|
|
31
|
+
Both entry points are governed: ``__call__`` (what ``ToolCallingAgent`` and the ``CodeAgent``
|
|
32
|
+
Python executor call) and ``forward``. Only one runs per call, so a call is CHECKed once.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
skip_forward_signature_validation = True # forward is generic; the inner tool's signature is validated
|
|
36
|
+
|
|
37
|
+
def __init__(self, inner: Tool, governor: Governor):
|
|
38
|
+
self._inner = inner
|
|
39
|
+
self._gov = governor
|
|
40
|
+
self.name = inner.name
|
|
41
|
+
self.description = inner.description
|
|
42
|
+
self.inputs = inner.inputs
|
|
43
|
+
self.output_type = inner.output_type
|
|
44
|
+
self.output_schema = getattr(inner, "output_schema", None)
|
|
45
|
+
self.definition = _definition(inner)
|
|
46
|
+
super().__init__()
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def inner(self) -> Tool:
|
|
50
|
+
return self._inner
|
|
51
|
+
|
|
52
|
+
def _named_args(self, args: tuple, kwargs: dict) -> Any:
|
|
53
|
+
"""The call's inputs by parameter name, so a positional call (CodeAgent code) hashes like the
|
|
54
|
+
keyword call a ToolCallingAgent makes."""
|
|
55
|
+
if len(args) == 1 and not kwargs and isinstance(args[0], dict) and all(k in self.inputs for k in args[0]):
|
|
56
|
+
return dict(args[0])
|
|
57
|
+
try:
|
|
58
|
+
sig = inspect.signature(self._inner.forward)
|
|
59
|
+
params = list(sig.parameters.values())
|
|
60
|
+
if params and params[0].name == "self": # @tool builds forward as a plain function holding ``self``
|
|
61
|
+
sig = sig.replace(parameters=params[1:])
|
|
62
|
+
bound = sig.bind(*args, **kwargs)
|
|
63
|
+
named: dict = {}
|
|
64
|
+
for pname, value in bound.arguments.items():
|
|
65
|
+
kind = sig.parameters[pname].kind
|
|
66
|
+
if kind is inspect.Parameter.VAR_KEYWORD:
|
|
67
|
+
named.update(value)
|
|
68
|
+
elif kind is inspect.Parameter.VAR_POSITIONAL:
|
|
69
|
+
named["args"] = list(value)
|
|
70
|
+
else:
|
|
71
|
+
named[pname] = value
|
|
72
|
+
return named
|
|
73
|
+
except (TypeError, ValueError):
|
|
74
|
+
return {"args": list(args), "kwargs": kwargs} if args else dict(kwargs)
|
|
75
|
+
|
|
76
|
+
def _governed(self, call, args: tuple, kwargs: dict, hash_kwargs: dict):
|
|
77
|
+
g, name = self._gov, self.name
|
|
78
|
+
params_hash = sha256_ref(self._named_args(args, hash_kwargs))
|
|
79
|
+
request_id = g.authorize(f"tool '{name}'", lambda: g.client.tool_request(
|
|
80
|
+
tool_id=name, tool_version=g.tool_version, input_params_hash=params_hash,
|
|
81
|
+
tool_definition=self.definition))
|
|
82
|
+
started, result, error = time.monotonic(), _NO_RESULT, True
|
|
83
|
+
try:
|
|
84
|
+
result = call()
|
|
85
|
+
error = False
|
|
86
|
+
return result
|
|
87
|
+
finally:
|
|
88
|
+
g.record(use_case=f"tool:{name}", model_id=g.model_id, request_id=request_id, input_tokens=0,
|
|
89
|
+
output_tokens=0, duration_ms=(time.monotonic() - started) * 1000,
|
|
90
|
+
status="ERROR" if error else "SUCCESS",
|
|
91
|
+
output_ref="" if result is _NO_RESULT else sha256_ref(result),
|
|
92
|
+
tool_manifest_hash=_manifest_hash(self.definition))
|
|
93
|
+
|
|
94
|
+
def __call__(self, *args, sanitize_inputs_outputs: bool = False, **kwargs):
|
|
95
|
+
return self._governed(lambda: self._inner(*args, sanitize_inputs_outputs=sanitize_inputs_outputs, **kwargs),
|
|
96
|
+
args, kwargs, kwargs)
|
|
97
|
+
|
|
98
|
+
def forward(self, *args, **kwargs):
|
|
99
|
+
return self._governed(lambda: self._inner.forward(*args, **kwargs), args, kwargs, kwargs)
|
|
100
|
+
|
|
101
|
+
def to_dict(self) -> dict:
|
|
102
|
+
# Remote executors (Docker, E2B, Modal, Wasm) serialise a tool's source and run it outside this
|
|
103
|
+
# process, where this wrapper does not run. Refuse rather than ship an ungoverned copy.
|
|
104
|
+
raise NotImplementedError("a governed tool cannot be serialised: its governance runs only in this process "
|
|
105
|
+
"(use the local Python executor)")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _manifest_hash(definition: dict) -> str:
|
|
109
|
+
from maigp_client import tool_definition_hash
|
|
110
|
+
return tool_definition_hash(definition["name"], definition["description"], definition["input_schema"])
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def governed_tools(tools: Iterable[Tool], governance: Any, *, use_case: str = "", check_timeout: float = 10.0,
|
|
114
|
+
tool_version: str = "1.0.0", model_id: str = "") -> list[Tool]:
|
|
115
|
+
"""Wrap each tool so every call is TOOL_REQUESTed first (fail closed). Pass the result as the
|
|
116
|
+
agent's ``tools=``. ``model_id`` is only recorded on the RECORD of each tool call."""
|
|
117
|
+
governor = Governor(governance, use_case=use_case, check_timeout=check_timeout,
|
|
118
|
+
tool_version=tool_version, model_id=model_id)
|
|
119
|
+
out: list[Tool] = []
|
|
120
|
+
for t in tools:
|
|
121
|
+
if isinstance(t, GovernedTool):
|
|
122
|
+
out.append(t)
|
|
123
|
+
elif isinstance(t, Tool):
|
|
124
|
+
out.append(GovernedTool(t, governor))
|
|
125
|
+
else:
|
|
126
|
+
raise TypeError(f"governed_tools expects smolagents Tool instances, got {type(t).__name__} "
|
|
127
|
+
"(a managed agent is not a tool: govern its own model and tools)")
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def require_governed(agent: Any, *, allow_ungoverned: Iterable[str] = ("final_answer",)) -> None:
|
|
132
|
+
"""Raise unless ``agent`` can only reach governed code: its model is a GovernedModel, every tool
|
|
133
|
+
except ``allow_ungoverned`` (default: the built-in ``final_answer``) is a GovernedTool, and a
|
|
134
|
+
CodeAgent runs code in the local executor. Recurses into managed agents. Call it after building
|
|
135
|
+
the agent; it catches ``add_base_tools=True`` (the base tools are not wrapped) and remote executors."""
|
|
136
|
+
from .model import GovernedModel
|
|
137
|
+
problems: list[str] = []
|
|
138
|
+
if not isinstance(agent.model, GovernedModel):
|
|
139
|
+
problems.append("model is not a GovernedModel")
|
|
140
|
+
skip = set(allow_ungoverned)
|
|
141
|
+
for name, t in agent.tools.items():
|
|
142
|
+
if name not in skip and not isinstance(t, GovernedTool):
|
|
143
|
+
problems.append(f"tool '{name}' is not governed")
|
|
144
|
+
executor = getattr(agent, "python_executor", None)
|
|
145
|
+
if executor is not None and type(executor).__name__ != "LocalPythonExecutor":
|
|
146
|
+
problems.append(f"python executor {type(executor).__name__} runs code outside this process")
|
|
147
|
+
for sub in getattr(agent, "managed_agents", {}).values():
|
|
148
|
+
try:
|
|
149
|
+
require_governed(sub, allow_ungoverned=allow_ungoverned)
|
|
150
|
+
except RuntimeError as e:
|
|
151
|
+
problems.append(f"managed agent '{getattr(sub, 'name', '?')}': {e}")
|
|
152
|
+
if problems:
|
|
153
|
+
raise RuntimeError("maigp-smolagents: agent is not fully governed: " + "; ".join(problems))
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "maigp-smolagents"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
authors = [{name = "Causum", email = "engineering@causum.com"}]
|
|
9
|
+
description = "MAIGP governance adapter for Hugging Face smolagents (blocks model and tool calls, fails closed)"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
dependencies = ["maigp-agent-core>=1.4.0", "maigp-client>=5.10.0", "smolagents>=1.19,<2"]
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
agency = ["maigp-agent-core[agency]>=1.3.0"]
|
|
16
|
+
agency-aws = ["maigp-agent-core[agency-aws]>=1.3.0"]
|
|
17
|
+
dev = ["pytest>=8", "respx>=0.21", "httpx>=0.25.0"]
|
|
18
|
+
|
|
19
|
+
[tool.hatch.build.targets.wheel]
|
|
20
|
+
packages = ["maigp_smolagents"]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://causum.com/"
|
|
24
|
+
Documentation = "https://causum.com/"
|
|
25
|
+
Repository = "https://causum.com/"
|
|
File without changes
|
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
"""maigp-smolagents against the REAL smolagents (ToolCallingAgent and CodeAgent).
|
|
2
|
+
|
|
3
|
+
The model is a scripted smolagents ``Model`` subclass; the MAIGP authority is stubbed at the HTTP
|
|
4
|
+
layer with respx under the real ``MaigpAgentClient``. No model API and no network beyond the stub.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
import pytest
|
|
15
|
+
import respx
|
|
16
|
+
|
|
17
|
+
pytest.importorskip("smolagents")
|
|
18
|
+
from smolagents import CodeAgent, Tool, ToolCallingAgent, tool # noqa: E402
|
|
19
|
+
from smolagents.agents import ChatMessage, MessageRole # noqa: E402
|
|
20
|
+
from smolagents.models import (ChatMessageStreamDelta, ChatMessageToolCall, # noqa: E402
|
|
21
|
+
ChatMessageToolCallFunction, Model)
|
|
22
|
+
from smolagents.monitoring import TokenUsage # noqa: E402
|
|
23
|
+
from smolagents.utils import AgentGenerationError # noqa: E402
|
|
24
|
+
|
|
25
|
+
from maigp_client import tool_definition_hash # noqa: E402
|
|
26
|
+
from maigp_smolagents import (GovernedModel, GovernedTool, MaigpBlockedError, # noqa: E402
|
|
27
|
+
MaigpGovernance, governed_model, governed_tools, require_governed)
|
|
28
|
+
from maigp_smolagents.core import sha256_ref # noqa: E402
|
|
29
|
+
|
|
30
|
+
BASE = "http://aigp.test"
|
|
31
|
+
CHECK, TOOL, RECORD = "/api/v1/check", "/api/v1/agent/tool-request", "/api/v1/record"
|
|
32
|
+
RAN: list[dict] = []
|
|
33
|
+
INPUT = {"account": "acct-9", "amount": 5}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@tool
|
|
37
|
+
def transfer_funds(account: str, amount: int) -> str:
|
|
38
|
+
"""Move money (the side effect a governance DENY must prevent).
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
account: destination account
|
|
42
|
+
amount: amount to move
|
|
43
|
+
"""
|
|
44
|
+
RAN.append({"account": account, "amount": amount})
|
|
45
|
+
return f"moved {amount} to {account}"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _tc(name, args, i="c1"):
|
|
49
|
+
return ChatMessageToolCall(id=i, type="function", function=ChatMessageToolCallFunction(name=name, arguments=args))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ScriptedModel(Model):
|
|
53
|
+
"""Replays ``script`` (list of ChatMessage) one per generate call; counts calls."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, script):
|
|
56
|
+
super().__init__(model_id="test.scripted")
|
|
57
|
+
self.script, self.calls = list(script), 0
|
|
58
|
+
|
|
59
|
+
def generate(self, messages, stop_sequences=None, response_format=None, tools_to_call_from=None, **kw):
|
|
60
|
+
msg = self.script[min(self.calls, len(self.script) - 1)]
|
|
61
|
+
self.calls += 1
|
|
62
|
+
return ChatMessage(role=MessageRole.ASSISTANT, content=msg.content, tool_calls=msg.tool_calls,
|
|
63
|
+
token_usage=TokenUsage(input_tokens=7, output_tokens=3))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class StreamingScriptedModel(ScriptedModel):
|
|
67
|
+
def generate_stream(self, messages, stop_sequences=None, response_format=None, tools_to_call_from=None, **kw):
|
|
68
|
+
msg = self.script[min(self.calls, len(self.script) - 1)]
|
|
69
|
+
self.calls += 1
|
|
70
|
+
yield ChatMessageStreamDelta(content=msg.content or "")
|
|
71
|
+
yield ChatMessageStreamDelta(content="", token_usage=TokenUsage(input_tokens=7, output_tokens=3))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def tool_script():
|
|
75
|
+
return [ChatMessage(role=MessageRole.ASSISTANT, content="", tool_calls=[_tc("transfer_funds", INPUT)]),
|
|
76
|
+
ChatMessage(role=MessageRole.ASSISTANT, content="",
|
|
77
|
+
tool_calls=[_tc("final_answer", {"answer": "done"}, "c2")])]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def code_script(call="transfer_funds(account='acct-9', amount=5)"):
|
|
81
|
+
code = f"Thought: pay.\n<code>\nr = {call}\nfinal_answer(r)\n</code>"
|
|
82
|
+
return [ChatMessage(role=MessageRole.ASSISTANT, content=code)]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Authority:
|
|
86
|
+
"""respx handlers. decision values: str | None (unreachable) | "MISSING" | "SLOW" (hangs) | "RAISE"."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, router, *, model="ALLOW", tool_="ALLOW"):
|
|
89
|
+
self.model, self.tool, self.ttl = model, tool_, 0 # ttl 0: every model call is CHECKed over HTTP
|
|
90
|
+
self.checks, self.tool_requests, self.records = [], [], []
|
|
91
|
+
router.post(CHECK).mock(side_effect=self._check)
|
|
92
|
+
router.post(TOOL).mock(side_effect=self._tool)
|
|
93
|
+
router.post(RECORD).mock(side_effect=self._record)
|
|
94
|
+
|
|
95
|
+
async def _answer(self, request, decision, sink):
|
|
96
|
+
body = json.loads(request.content)
|
|
97
|
+
sink.append(body)
|
|
98
|
+
if decision is None:
|
|
99
|
+
raise httpx.ConnectError("authority unreachable", request=request)
|
|
100
|
+
if decision == "SLOW":
|
|
101
|
+
await asyncio.sleep(3)
|
|
102
|
+
if decision == "MISSING":
|
|
103
|
+
return httpx.Response(200, json={"note": "no decision"})
|
|
104
|
+
return httpx.Response(200, json={"decision": decision, "request_id": body["request_id"],
|
|
105
|
+
"reason": f"policy says {decision}",
|
|
106
|
+
"ttl_seconds": self.ttl})
|
|
107
|
+
|
|
108
|
+
async def _check(self, request):
|
|
109
|
+
return await self._answer(request, self.model, self.checks)
|
|
110
|
+
|
|
111
|
+
async def _tool(self, request):
|
|
112
|
+
return await self._answer(request, self.tool, self.tool_requests)
|
|
113
|
+
|
|
114
|
+
async def _record(self, request):
|
|
115
|
+
self.records.append(json.loads(request.content))
|
|
116
|
+
return httpx.Response(200, json={})
|
|
117
|
+
|
|
118
|
+
def tool_records(self):
|
|
119
|
+
return [r for r in self.records if r["use_case"].startswith("tool:")]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@pytest.fixture(autouse=True)
|
|
123
|
+
def _clear():
|
|
124
|
+
RAN.clear()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@pytest.fixture
|
|
128
|
+
def router():
|
|
129
|
+
with respx.mock(assert_all_called=False) as r:
|
|
130
|
+
yield r
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def make(router, mode="ENFORCE", **kw):
|
|
134
|
+
auth = Authority(router, **kw)
|
|
135
|
+
gov = MaigpGovernance(gov_url=BASE, app_id="app-1", hmac_secret="test-hmac-not-a-secret", mode=mode)
|
|
136
|
+
return gov, auth
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def tc_agent(gov, script=None, timeout=10.0, **kw):
|
|
140
|
+
model = ScriptedModel(script or tool_script())
|
|
141
|
+
agent = ToolCallingAgent(tools=gov.tools([transfer_funds], check_timeout=timeout),
|
|
142
|
+
model=gov.model(model, check_timeout=timeout, **kw), max_steps=3, verbosity_level=-1)
|
|
143
|
+
return agent, model
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def code_agent(gov, script=None, timeout=10.0):
|
|
147
|
+
model = ScriptedModel(script or code_script())
|
|
148
|
+
agent = CodeAgent(tools=gov.tools([transfer_funds], check_timeout=timeout),
|
|
149
|
+
model=gov.model(model, check_timeout=timeout), max_steps=3, verbosity_level=-1)
|
|
150
|
+
return agent, model
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def observations(agent):
|
|
154
|
+
return " ".join(str(s.observations) + str(s.error or "") for s in agent.memory.steps if hasattr(s, "observations"))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ── allowed ──
|
|
158
|
+
def test_allowed_tool_calling_agent_runs_and_records(router):
|
|
159
|
+
gov, auth = make(router)
|
|
160
|
+
agent, model = tc_agent(gov)
|
|
161
|
+
assert agent.run("pay acct-9") == "done"
|
|
162
|
+
assert RAN == [INPUT] and model.calls == 2
|
|
163
|
+
treq = auth.tool_requests[0]
|
|
164
|
+
assert treq["tool_id"] == "transfer_funds" and treq["input_parameters_hash"] == sha256_ref(INPUT)
|
|
165
|
+
rec = auth.tool_records()[0]
|
|
166
|
+
assert rec["request_id"] == treq["request_id"] and rec["status"] == "SUCCESS"
|
|
167
|
+
assert rec["output_ref"] == "sha256:" + hashlib.sha256(
|
|
168
|
+
json.dumps("moved 5 to acct-9", sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_tool_definition_hash_sent_on_request_and_record(router):
|
|
172
|
+
gov, auth = make(router)
|
|
173
|
+
tc_agent(gov)[0].run("pay")
|
|
174
|
+
t = transfer_funds
|
|
175
|
+
expected = tool_definition_hash(t.name, t.description, {
|
|
176
|
+
"type": "object", "properties": t.inputs, "required": ["account", "amount"]})
|
|
177
|
+
assert auth.tool_requests[0]["tool_manifest_hash"] == expected
|
|
178
|
+
assert auth.tool_records()[0]["tool_manifest_hash"] == expected
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def test_every_model_call_is_checked_and_recorded_with_usage(router):
|
|
182
|
+
gov, auth = make(router)
|
|
183
|
+
agent, model = tc_agent(gov)
|
|
184
|
+
agent.run("pay")
|
|
185
|
+
assert model.calls == 2 and len(auth.checks) == 2
|
|
186
|
+
assert {c["model_id"] for c in auth.checks} == {"test.scripted"} and auth.checks[0]["use_case"] == "smolagents"
|
|
187
|
+
recs = [r for r in auth.records if not r["use_case"].startswith("tool:")]
|
|
188
|
+
assert len(recs) == 2 and recs[0]["tokens"] == {"input_tokens": 7, "output_tokens": 3, "total_tokens": 10}
|
|
189
|
+
assert recs[0]["request_id"] == auth.checks[0]["request_id"] and recs[0]["status"] == "SUCCESS"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def test_allow_with_constraints_runs(router):
|
|
193
|
+
gov, _ = make(router, model="ALLOW_WITH_CONSTRAINTS", tool_="ALLOW_WITH_CONSTRAINTS")
|
|
194
|
+
assert tc_agent(gov)[0].run("pay") == "done" and RAN == [INPUT]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def test_allowed_code_agent_runs_tool_from_generated_code(router):
|
|
198
|
+
gov, auth = make(router)
|
|
199
|
+
agent, _ = code_agent(gov)
|
|
200
|
+
assert agent.run("pay") == "moved 5 to acct-9"
|
|
201
|
+
assert RAN == [INPUT] and len(auth.tool_requests) == 1
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_positional_call_from_code_hashes_like_keyword_call(router):
|
|
205
|
+
gov, auth = make(router)
|
|
206
|
+
code_agent(gov, script=code_script("transfer_funds('acct-9', 5)"))[0].run("pay")
|
|
207
|
+
assert RAN == [INPUT]
|
|
208
|
+
assert auth.tool_requests[0]["input_parameters_hash"] == sha256_ref(INPUT)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def test_streaming_model_is_governed_and_recorded(router):
|
|
212
|
+
gov, auth = make(router)
|
|
213
|
+
model = StreamingScriptedModel(tool_script())
|
|
214
|
+
agent = ToolCallingAgent(tools=gov.tools([transfer_funds]), model=gov.model(model), max_steps=3,
|
|
215
|
+
verbosity_level=-1, stream_outputs=True)
|
|
216
|
+
assert hasattr(agent.model, "generate_stream")
|
|
217
|
+
list(agent.run("pay", stream=True))
|
|
218
|
+
assert len(auth.checks) >= 1 and len(auth.checks) == model.calls
|
|
219
|
+
assert all(r["tokens"]["input_tokens"] == 7 for r in auth.records if not r["use_case"].startswith("tool:"))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def test_non_streaming_model_does_not_pretend_to_stream(router):
|
|
223
|
+
gov, _ = make(router)
|
|
224
|
+
assert not hasattr(gov.model(ScriptedModel(tool_script())), "generate_stream")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# ── denied tool ──
|
|
228
|
+
@pytest.mark.parametrize("decision", ["DENY", "RATE_LIMITED", "UNCHECKED", "MISSING"])
|
|
229
|
+
def test_non_allow_tool_decision_never_runs_tool_calling_agent(router, decision):
|
|
230
|
+
gov, auth = make(router, tool_=decision)
|
|
231
|
+
agent, _ = tc_agent(gov)
|
|
232
|
+
agent.run("pay")
|
|
233
|
+
assert RAN == [] and auth.tool_records() == []
|
|
234
|
+
assert "Blocked by AIGP governance" in observations(agent)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def test_denied_tool_error_is_visible_to_agent_with_reason(router):
|
|
238
|
+
gov, _ = make(router, tool_="DENY")
|
|
239
|
+
agent, _ = tc_agent(gov)
|
|
240
|
+
agent.run("pay")
|
|
241
|
+
text = observations(agent)
|
|
242
|
+
assert "tool 'transfer_funds' DENY" in text and "policy says DENY" in text
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def test_denied_tool_never_runs_from_code_agent_code(router):
|
|
246
|
+
gov, auth = make(router, tool_="DENY")
|
|
247
|
+
agent, _ = code_agent(gov)
|
|
248
|
+
agent.run("pay")
|
|
249
|
+
assert RAN == [] and auth.tool_records() == []
|
|
250
|
+
assert "Blocked by AIGP governance" in observations(agent)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def test_denied_tool_not_bypassed_by_try_except_in_code(router):
|
|
254
|
+
gov, _ = make(router, tool_="DENY")
|
|
255
|
+
code = "Thought: x\n<code>\ntry:\n transfer_funds('acct-9', 5)\nexcept Exception as e:\n print('caught', e)\nfinal_answer('ok')\n</code>"
|
|
256
|
+
code_agent(gov, script=[ChatMessage(role=MessageRole.ASSISTANT, content=code)])[0].run("pay")
|
|
257
|
+
assert RAN == []
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def test_denied_tool_blocked_in_report_mode(router):
|
|
261
|
+
gov, _ = make(router, mode="REPORT", tool_="DENY")
|
|
262
|
+
tc_agent(gov)[0].run("pay")
|
|
263
|
+
assert RAN == []
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def test_missing_tool_decision_blocked_in_report_mode(router):
|
|
267
|
+
gov, _ = make(router, mode="REPORT", tool_="MISSING")
|
|
268
|
+
tc_agent(gov)[0].run("pay")
|
|
269
|
+
assert RAN == []
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def test_unreachable_authority_blocks_tool(router):
|
|
273
|
+
gov, _ = make(router, tool_=None)
|
|
274
|
+
tc_agent(gov)[0].run("pay")
|
|
275
|
+
assert RAN == []
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def test_check_that_raises_blocks_tool(router, monkeypatch):
|
|
279
|
+
gov, _ = make(router)
|
|
280
|
+
|
|
281
|
+
async def boom(**_):
|
|
282
|
+
raise RuntimeError("bug in the check path")
|
|
283
|
+
monkeypatch.setattr(gov.client, "tool_request", boom)
|
|
284
|
+
agent, _ = tc_agent(gov)
|
|
285
|
+
agent.run("pay")
|
|
286
|
+
assert RAN == [] and "UNCHECKED" in observations(agent)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def test_tool_check_timeout_blocks_tool(router):
|
|
290
|
+
gov, _ = make(router, tool_="SLOW")
|
|
291
|
+
agent, _ = tc_agent(gov, timeout=0.2)
|
|
292
|
+
agent.run("pay")
|
|
293
|
+
assert RAN == [] and "timed out" in observations(agent)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
# ── denied model ──
|
|
297
|
+
@pytest.mark.parametrize("decision", ["DENY", "RATE_LIMITED", "UNCHECKED", "MISSING", None])
|
|
298
|
+
def test_non_allow_model_decision_blocks_model_call(router, decision):
|
|
299
|
+
gov, auth = make(router, model=decision)
|
|
300
|
+
agent, model = tc_agent(gov)
|
|
301
|
+
with pytest.raises(AgentGenerationError) as e:
|
|
302
|
+
agent.run("pay")
|
|
303
|
+
assert model.calls == 0 and RAN == [] and auth.records == []
|
|
304
|
+
assert isinstance(e.value.__cause__, MaigpBlockedError)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def test_denied_model_blocks_code_agent(router):
|
|
308
|
+
gov, _ = make(router, model="DENY")
|
|
309
|
+
agent, model = code_agent(gov)
|
|
310
|
+
with pytest.raises(AgentGenerationError):
|
|
311
|
+
agent.run("pay")
|
|
312
|
+
assert model.calls == 0 and RAN == []
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def test_model_blocked_in_report_mode_too(router):
|
|
316
|
+
gov, _ = make(router, mode="REPORT", model="MISSING")
|
|
317
|
+
agent, model = tc_agent(gov)
|
|
318
|
+
with pytest.raises(AgentGenerationError):
|
|
319
|
+
agent.run("pay")
|
|
320
|
+
assert model.calls == 0
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def test_model_check_timeout_blocks(router):
|
|
324
|
+
gov, _ = make(router, model="SLOW")
|
|
325
|
+
agent, model = tc_agent(gov, timeout=0.2)
|
|
326
|
+
with pytest.raises(AgentGenerationError) as e:
|
|
327
|
+
agent.run("pay")
|
|
328
|
+
assert model.calls == 0 and "timed out" in str(e.value.__cause__)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def test_model_denied_on_second_call_stops_before_inner_model(router):
|
|
332
|
+
gov, auth = make(router)
|
|
333
|
+
agent, model = tc_agent(gov)
|
|
334
|
+
state = {"n": 0}
|
|
335
|
+
orig = auth._check
|
|
336
|
+
|
|
337
|
+
async def deny_second(request):
|
|
338
|
+
state["n"] += 1
|
|
339
|
+
auth.model = "ALLOW" if state["n"] == 1 else "DENY"
|
|
340
|
+
return await orig(request)
|
|
341
|
+
router.routes[0].mock(side_effect=deny_second)
|
|
342
|
+
with pytest.raises(AgentGenerationError):
|
|
343
|
+
agent.run("pay")
|
|
344
|
+
assert model.calls == 1 and RAN == [INPUT]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def test_direct_model_call_is_governed(router):
|
|
348
|
+
gov, _ = make(router, model="DENY")
|
|
349
|
+
inner = ScriptedModel(tool_script())
|
|
350
|
+
with pytest.raises(MaigpBlockedError):
|
|
351
|
+
gov.model(inner)([ChatMessage(role=MessageRole.USER, content="hi")])
|
|
352
|
+
assert inner.calls == 0
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def test_direct_tool_call_and_forward_are_governed(router):
|
|
356
|
+
gov, _ = make(router, tool_="DENY")
|
|
357
|
+
[t] = gov.tools([transfer_funds])
|
|
358
|
+
with pytest.raises(MaigpBlockedError):
|
|
359
|
+
t(account="a", amount=1)
|
|
360
|
+
with pytest.raises(MaigpBlockedError):
|
|
361
|
+
t.forward(account="a", amount=1)
|
|
362
|
+
assert RAN == []
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
# ── tool failure, record, wrapping ──
|
|
366
|
+
def test_tool_that_raises_is_recorded_as_error(router):
|
|
367
|
+
@tool
|
|
368
|
+
def boom(x: str) -> str:
|
|
369
|
+
"""Fail.
|
|
370
|
+
|
|
371
|
+
Args:
|
|
372
|
+
x: anything
|
|
373
|
+
"""
|
|
374
|
+
raise ValueError("kaput")
|
|
375
|
+
gov, auth = make(router)
|
|
376
|
+
[t] = gov.tools([boom])
|
|
377
|
+
with pytest.raises(ValueError):
|
|
378
|
+
t(x="1")
|
|
379
|
+
rec = auth.tool_records()[0]
|
|
380
|
+
assert rec["status"] == "ERROR" and rec["use_case"] == "tool:boom" and not rec.get("output_ref")
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def test_governed_tool_keeps_schema_and_class_tool(router):
|
|
384
|
+
gov, _ = make(router)
|
|
385
|
+
[t] = gov.tools([transfer_funds])
|
|
386
|
+
assert isinstance(t, Tool) and isinstance(t, GovernedTool)
|
|
387
|
+
assert (t.name, t.description, t.inputs, t.output_type) == (
|
|
388
|
+
transfer_funds.name, transfer_funds.description, transfer_funds.inputs, transfer_funds.output_type)
|
|
389
|
+
assert gov.tools([t]) == [t]
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def test_governed_model_delegates_and_is_a_model(router):
|
|
393
|
+
gov, _ = make(router)
|
|
394
|
+
inner = ScriptedModel(tool_script())
|
|
395
|
+
m = governed_model(inner, gov)
|
|
396
|
+
assert isinstance(m, Model) and isinstance(m, GovernedModel) and m.inner is inner
|
|
397
|
+
assert m.model_id == "test.scripted" and governed_model(m, gov) is m
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def test_rejects_non_tool_and_non_model(router):
|
|
401
|
+
gov, _ = make(router)
|
|
402
|
+
with pytest.raises(TypeError):
|
|
403
|
+
gov.tools([lambda: 1])
|
|
404
|
+
with pytest.raises(TypeError):
|
|
405
|
+
gov.model(object())
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def test_to_dict_refused_so_remote_executors_fail_closed(router):
|
|
409
|
+
gov, _ = make(router)
|
|
410
|
+
with pytest.raises(NotImplementedError):
|
|
411
|
+
gov.tools([transfer_funds])[0].to_dict()
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
# ── disabled client, require_governed ──
|
|
415
|
+
def test_disabled_client_refused():
|
|
416
|
+
gov = MaigpGovernance(gov_url="", app_id="app-1", hmac_secret="s")
|
|
417
|
+
with pytest.raises(RuntimeError, match="disabled"):
|
|
418
|
+
gov.model(ScriptedModel(tool_script()))
|
|
419
|
+
with pytest.raises(RuntimeError, match="disabled"):
|
|
420
|
+
gov.tools([transfer_funds])
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def test_require_governed_accepts_governed_agent(router):
|
|
424
|
+
gov, _ = make(router)
|
|
425
|
+
gov.require_governed(tc_agent(gov)[0])
|
|
426
|
+
require_governed(code_agent(gov)[0])
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def test_require_governed_rejects_ungoverned_tool_model_and_base_tools(router):
|
|
430
|
+
gov, _ = make(router)
|
|
431
|
+
with pytest.raises(RuntimeError, match="not a GovernedModel"):
|
|
432
|
+
require_governed(ToolCallingAgent(tools=gov.tools([transfer_funds]), model=ScriptedModel(tool_script())))
|
|
433
|
+
with pytest.raises(RuntimeError, match="tool 'transfer_funds' is not governed"):
|
|
434
|
+
require_governed(ToolCallingAgent(tools=[transfer_funds], model=gov.model(ScriptedModel(tool_script()))))
|
|
435
|
+
from smolagents import PythonInterpreterTool
|
|
436
|
+
ungoverned = CodeAgent(tools=gov.tools([transfer_funds]), model=gov.model(ScriptedModel(code_script())))
|
|
437
|
+
ungoverned.tools["python_interpreter"] = PythonInterpreterTool() # what add_base_tools=True adds
|
|
438
|
+
with pytest.raises(RuntimeError, match="tool 'python_interpreter' is not governed"):
|
|
439
|
+
require_governed(ungoverned)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def test_works_inside_a_running_event_loop(router):
|
|
443
|
+
gov, _ = make(router)
|
|
444
|
+
|
|
445
|
+
async def main():
|
|
446
|
+
return tc_agent(gov)[0].run("pay")
|
|
447
|
+
assert asyncio.run(main()) == "done" and RAN == [INPUT]
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def test_agency_refusal_blocks_in_every_mode(router, monkeypatch):
|
|
451
|
+
from maigp_agent_core import AgencyRequiredError
|
|
452
|
+
gov, _ = make(router, mode="REPORT")
|
|
453
|
+
monkeypatch.setattr(type(gov), "agency", property(lambda self: object()))
|
|
454
|
+
|
|
455
|
+
async def refuse(*a, **k):
|
|
456
|
+
raise AgencyRequiredError("no grant", code="NO_GRANT")
|
|
457
|
+
monkeypatch.setattr(gov, "arequire_agency", refuse)
|
|
458
|
+
agent, model = tc_agent(gov)
|
|
459
|
+
with pytest.raises(AgentGenerationError) as e: # the model call needs a grant too
|
|
460
|
+
agent.run("pay")
|
|
461
|
+
assert model.calls == 0 and RAN == [] and "NO_GRANT" in str(e.value.__cause__)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def test_authority_ttl_is_honoured_for_model_checks(router):
|
|
465
|
+
"""maigp-client caches a model CHECK for the authority's ttl_seconds; with a TTL one HTTP CHECK serves both calls."""
|
|
466
|
+
gov, auth = make(router)
|
|
467
|
+
auth.ttl = 300
|
|
468
|
+
agent, model = tc_agent(gov)
|
|
469
|
+
agent.run("pay")
|
|
470
|
+
assert model.calls == 2 and len(auth.checks) == 1
|