maigp-langgraph 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_langgraph-1.0.0/.gitignore +56 -0
- maigp_langgraph-1.0.0/PKG-INFO +165 -0
- maigp_langgraph-1.0.0/README.md +141 -0
- maigp_langgraph-1.0.0/maigp_langgraph/__init__.py +16 -0
- maigp_langgraph-1.0.0/maigp_langgraph/adapter.py +376 -0
- maigp_langgraph-1.0.0/maigp_langgraph/middleware.py +64 -0
- maigp_langgraph-1.0.0/maigp_langgraph/model.py +101 -0
- maigp_langgraph-1.0.0/pyproject.toml +31 -0
- maigp_langgraph-1.0.0/tests/__init__.py +0 -0
- maigp_langgraph-1.0.0/tests/conftest.py +140 -0
- maigp_langgraph-1.0.0/tests/test_langgraph_real.py +611 -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,165 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: maigp-langgraph
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: MAIGP governance adapter for LangGraph: blocks model calls and tool calls the governance authority does not allow (fail closed)
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Requires-Dist: langchain-core<2,>=1.0
|
|
7
|
+
Requires-Dist: langgraph-prebuilt<2,>=1.0.2
|
|
8
|
+
Requires-Dist: langgraph<2,>=1.0
|
|
9
|
+
Requires-Dist: maigp-agent-core>=1.4.0
|
|
10
|
+
Requires-Dist: maigp-client>=5.10.0
|
|
11
|
+
Provides-Extra: agency
|
|
12
|
+
Requires-Dist: maigp-agent-core[agency]>=1.3.0; extra == 'agency'
|
|
13
|
+
Provides-Extra: agency-aws
|
|
14
|
+
Requires-Dist: maigp-agent-core[agency-aws]>=1.3.0; extra == 'agency-aws'
|
|
15
|
+
Provides-Extra: agents
|
|
16
|
+
Requires-Dist: langchain<2,>=1.0; extra == 'agents'
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: httpx>=0.25.0; extra == 'dev'
|
|
19
|
+
Requires-Dist: langchain<2,>=1.0; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
22
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# maigp-langgraph
|
|
26
|
+
|
|
27
|
+
MAIGP governance for [LangGraph](https://pypi.org/project/langgraph/). It blocks model calls and tool calls that the governance authority does not allow, and fails closed when it cannot get an answer.
|
|
28
|
+
|
|
29
|
+
Part of **MAIGP**, the Mediated AI Governance Protocol: a runtime consent, scope and evidence layer for AI systems. Before a governed call runs it is **CHECK**ed (policy, scope, jurisdiction, circuit breaker). After it ran it is **RECORD**ed as tamper-evident evidence.
|
|
30
|
+
|
|
31
|
+
## What it governs
|
|
32
|
+
|
|
33
|
+
| LangGraph call | MAIGP message before | Not allowed means | After a call that ran |
|
|
34
|
+
|---|---|---|---|
|
|
35
|
+
| Model call (any entry point: `invoke`, `ainvoke`, `stream`, `astream`, `batch`) | **CHECK** | the model is never called; `MaigpGovernanceBlocked` is raised (default) or a blocked `AIMessage` is returned | **RECORD** (model id, token usage, latency, status) |
|
|
36
|
+
| Tool call | **TOOL_REQUEST** with the SHA-256 of the input and the tool definition hash (name, description, input schema) | the tool function is never called; the graph gets a `ToolMessage` with `status="error"` and the reason | **RECORD** (`use_case="tool:<name>"`, `output_ref` = SHA-256 of the result, `tool_manifest_hash`) |
|
|
37
|
+
|
|
38
|
+
Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` let a call run. Everything else does not, in ENFORCE and in REPORT mode alike: `DENY`, `RATE_LIMITED`, `UNCHECKED`, a response without a decision, an unreachable authority, an HTTP error, an exception anywhere in the CHECK path, or a CHECK slower than `check_timeout` (10 s by default).
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install maigp-langgraph
|
|
44
|
+
pip install 'maigp-langgraph[agents]' # adds langchain, for langchain.agents.create_agent middleware
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
It uses [`maigp-client`](https://pypi.org/project/maigp-client/) (the protocol client), [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/) (shared lifecycle) and `langgraph>=1.0,<2`. Tested on langgraph 1.0.0 (langgraph-prebuilt 1.0.2, langchain-core 1.0.0, langchain 1.0.0) and on langgraph 1.2.24 (langgraph-prebuilt 1.1.3, langchain-core 1.8.5, langchain 1.5.2).
|
|
48
|
+
|
|
49
|
+
## Quick start
|
|
50
|
+
|
|
51
|
+
A graph with one governed model and one governed tool. The model here is scripted so the example needs no API key; replace it with your chat model (`ChatAnthropic(...)`, `ChatOpenAI(...)`, ...). It needs a MAIGP governance authority at `gov_url`.
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
|
|
55
|
+
from langchain_core.messages import AIMessage, HumanMessage
|
|
56
|
+
from langchain_core.tools import tool
|
|
57
|
+
from langgraph.prebuilt import create_react_agent
|
|
58
|
+
|
|
59
|
+
from maigp_agent_core import AgentGovernance
|
|
60
|
+
from maigp_langgraph import MaigpLangGraph
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@tool
|
|
64
|
+
def transfer_funds(account: str, amount: int) -> str:
|
|
65
|
+
"""Move money between accounts."""
|
|
66
|
+
return f"moved {amount} to {account}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ScriptedModel(FakeMessagesListChatModel):
|
|
70
|
+
def bind_tools(self, tools, **kwargs): # a real chat model already has bind_tools
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
model = ScriptedModel(responses=[
|
|
75
|
+
AIMessage(content="", tool_calls=[{"name": "transfer_funds",
|
|
76
|
+
"args": {"account": "acct-9", "amount": 5}, "id": "call-1"}]),
|
|
77
|
+
AIMessage(content="done"),
|
|
78
|
+
])
|
|
79
|
+
|
|
80
|
+
gov = AgentGovernance(gov_url="https://gov.example.com", app_id="my-langgraph-agent",
|
|
81
|
+
hmac_secret="secret")
|
|
82
|
+
maigp = MaigpLangGraph(gov, use_case="payments-bot")
|
|
83
|
+
|
|
84
|
+
agent = create_react_agent(
|
|
85
|
+
maigp.governed_model(model), # CHECK before every model call
|
|
86
|
+
maigp.tool_node([transfer_funds]), # TOOL_REQUEST before every tool call
|
|
87
|
+
)
|
|
88
|
+
result = agent.invoke({"messages": [HumanMessage("pay acct-9 five")]})
|
|
89
|
+
print(result["messages"][-1].content)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
With the `[agents]` extra, the same governance applies to `langchain.agents.create_agent` through middleware:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from langchain.agents import create_agent
|
|
96
|
+
|
|
97
|
+
agent = create_agent(model=model, tools=[transfer_funds], middleware=[maigp.middleware()])
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
For a hand-built `StateGraph`, use the governed model inside your model node and `maigp.tool_node(tools)` as the tools node:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
gm = maigp.governed_model(model).bind_tools([transfer_funds])
|
|
104
|
+
graph.add_node("model", lambda state: {"messages": [gm.invoke(state["messages"])]})
|
|
105
|
+
graph.add_node("tools", maigp.tool_node([transfer_funds]))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## How blocking works
|
|
109
|
+
|
|
110
|
+
LangGraph has no global "before call" switch, so MAIGP uses the extension points the installed version offers. Nothing in LangGraph is patched.
|
|
111
|
+
|
|
112
|
+
- **Tools: `langgraph.prebuilt.ToolNode(..., wrap_tool_call=..., awrap_tool_call=...)`** (class `ToolNode` in `langgraph.prebuilt.tool_node`, first released in `langgraph-prebuilt` 1.0.2). `ToolNode` hands the wrapper a `ToolCallRequest` and an `execute` callable. The wrapper sends TOOL_REQUEST and calls `execute` only when the decision allows it; otherwise it returns an error `ToolMessage` and the tool function is never called. `maigp.tool_node(tools)` builds that `ToolNode`; `maigp.wrap_tool_call` and `maigp.awrap_tool_call` are public if you construct the `ToolNode` yourself.
|
|
113
|
+
- **Models: a `langchain_core.language_models.BaseChatModel` wrapper** (`GovernedChatModel`). Every entry point of a chat model (`invoke`, `ainvoke`, `stream`, `astream`, `batch`, `generate`) reaches `_generate` / `_agenerate`. The CHECK is there, before the wrapped model is called. `bind_tools` and `with_structured_output` return a model that is still governed. Pass the unbound model to `governed_model`, then bind tools on the result (`create_react_agent` does this for you).
|
|
114
|
+
- **LangChain agents: `AgentMiddleware.wrap_model_call` / `wrap_tool_call`** (and the async twins) in `langchain.agents.middleware`, through `maigp.middleware()` (extra `agents`, `langchain>=1.0`).
|
|
115
|
+
- **Interrupts and `Command`:** a `GraphInterrupt` raised inside a tool propagates unchanged and is not recorded as a failure. A tool that returns a `Command` is recorded with the SHA-256 of its `update`.
|
|
116
|
+
|
|
117
|
+
Why not LangChain callbacks: a callback handler (see [`maigp-langchain`](https://pypi.org/project/maigp-langchain/)) observes a call. It cannot stop one, so it is not an enforcement point. LangGraph does not need it.
|
|
118
|
+
|
|
119
|
+
## Refusals in the graph
|
|
120
|
+
|
|
121
|
+
- **Tool call refused:** the graph receives `ToolMessage(content="Blocked by MAIGP governance: tool 'transfer_funds' DENY: <reason>", status="error", tool_call_id=..., name=...)`. The model sees it as the tool result and the run continues. Other tool calls of the same model turn are decided on their own.
|
|
122
|
+
- **Model call refused:** by default `MaigpGovernanceBlocked` (a subclass of `maigp_agent_core.errors.GovernanceBlockedError`, with `.decision`, `.reason`, `.what`) is raised out of the model call and the graph run stops with it. With `on_model_block="message"` the model call returns an `AIMessage` (no tool calls, `response_metadata={"maigp_blocked": True, ...}`) and an agent loop ends with that reply.
|
|
123
|
+
- **AIAP agency** (opt-in): pass `AgencyGate` to `AgentGovernance(agency=...)`. After an allowing CHECK / TOOL_REQUEST and before the call, an agency grant is required. A refusal, an unreachable broker or a slow gate blocks the call the same way (`Blocked by AIAP agency: ...`). No gate means nothing changes. Install `maigp-agent-core[agency]` for the gate.
|
|
124
|
+
|
|
125
|
+
## Configuration
|
|
126
|
+
|
|
127
|
+
`MaigpLangGraph(gov, *, use_case="langgraph-agent", check_timeout=10.0, tool_version="1.0.0", on_model_block="raise")`
|
|
128
|
+
|
|
129
|
+
| Option | Meaning |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `gov` | An `AgentGovernance` from `maigp-agent-core`. `gov_url`, `app_id`, `hmac_secret` and `mode` (`ENFORCE` / `REPORT`) are set there. |
|
|
132
|
+
| `use_case` | Use case sent with model CHECK / RECORD. Override per model with `governed_model(model, use_case=...)`. |
|
|
133
|
+
| `check_timeout` | Seconds a CHECK, TOOL_REQUEST or agency request may take before the call is refused. Must be above 0. |
|
|
134
|
+
| `tool_version` | `tool_version` sent in TOOL_REQUEST. |
|
|
135
|
+
| `on_model_block` | `"raise"` (default) or `"message"`, see above. |
|
|
136
|
+
|
|
137
|
+
`governed_model(model, use_case=None, model_id=None)`: `model_id` defaults to the model's `model_name` / `model_id` / `model` attribute, else its class name.
|
|
138
|
+
|
|
139
|
+
`tool_node(tools, **kwargs)` passes `kwargs` to `ToolNode` (`name`, `handle_tool_errors`, ...) and refuses `wrap_tool_call` / `awrap_tool_call`, which would replace governance.
|
|
140
|
+
|
|
141
|
+
## Fail-closed semantics
|
|
142
|
+
|
|
143
|
+
- A refused call never reaches the model or the tool. The check is made on the request that is actually executed.
|
|
144
|
+
- `MaigpLangGraph(...)` raises `RuntimeError` when the client is disabled (an empty `gov_url` makes `maigp-client` answer ALLOW to everything), and when the installed LangGraph's `ToolNode` has no `wrap_tool_call`. It raises `TypeError` for a `gov` without a client.
|
|
145
|
+
- RECORD runs after the call and never raises into the graph: a failed RECORD is logged. A call that was blocked is never recorded as run.
|
|
146
|
+
- A tool that raised is recorded with status `ERROR` and no `output_ref`; an exception inside a model call is recorded as `ERROR` and re-raised.
|
|
147
|
+
- `maigp-client` caches a CHECK decision for the `ttl_seconds` the authority returns (default 300 s), per `use_case` and model id. Within that time the same CHECK is answered from the cache. Set a short `ttl_seconds` on the authority if you need a decision per call.
|
|
148
|
+
- Sync graphs (`invoke`, `stream`) call the async client on one background event-loop thread owned by the adapter, so they work inside and outside a running event loop. Use one style (sync or async) per `MaigpLangGraph` instance: the client's HTTP connection pool belongs to one event loop.
|
|
149
|
+
|
|
150
|
+
## Limitations
|
|
151
|
+
|
|
152
|
+
- Governance covers only the models and `ToolNode`s you build through the adapter. A tool run by an ungoverned `ToolNode`, or a model you did not wrap, is not governed. `create_react_agent(model, [tool_a])` builds its own `ToolNode`: pass `maigp.tool_node([tool_a])` instead.
|
|
153
|
+
- A tool you call directly in your own code (`tool.invoke(...)`) does not pass through a `ToolNode` and is not governed.
|
|
154
|
+
- `create_react_agent` is deprecated in LangGraph 1.x in favour of `langchain.agents.create_agent`. Both work with this adapter.
|
|
155
|
+
- Streaming model output is checked once before the stream starts and is delivered as one chunk (the wrapper does not stream token by token).
|
|
156
|
+
- Model-level RECORD reports the token usage the model returns in `usage_metadata`; a model that returns none records 0.
|
|
157
|
+
|
|
158
|
+
## Links
|
|
159
|
+
|
|
160
|
+
- Protocol, specs and full adapter catalog: https://github.com/owner-spec/aigp-protocol
|
|
161
|
+
- Issues: https://github.com/owner-spec/aigp-protocol/issues
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
License: Proprietary. © Kanjani AI Research & Causum.
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# maigp-langgraph
|
|
2
|
+
|
|
3
|
+
MAIGP governance for [LangGraph](https://pypi.org/project/langgraph/). It blocks model calls and tool calls that the governance authority does not allow, and fails closed when it cannot get an answer.
|
|
4
|
+
|
|
5
|
+
Part of **MAIGP**, the Mediated AI Governance Protocol: a runtime consent, scope and evidence layer for AI systems. Before a governed call runs it is **CHECK**ed (policy, scope, jurisdiction, circuit breaker). After it ran it is **RECORD**ed as tamper-evident evidence.
|
|
6
|
+
|
|
7
|
+
## What it governs
|
|
8
|
+
|
|
9
|
+
| LangGraph call | MAIGP message before | Not allowed means | After a call that ran |
|
|
10
|
+
|---|---|---|---|
|
|
11
|
+
| Model call (any entry point: `invoke`, `ainvoke`, `stream`, `astream`, `batch`) | **CHECK** | the model is never called; `MaigpGovernanceBlocked` is raised (default) or a blocked `AIMessage` is returned | **RECORD** (model id, token usage, latency, status) |
|
|
12
|
+
| Tool call | **TOOL_REQUEST** with the SHA-256 of the input and the tool definition hash (name, description, input schema) | the tool function is never called; the graph gets a `ToolMessage` with `status="error"` and the reason | **RECORD** (`use_case="tool:<name>"`, `output_ref` = SHA-256 of the result, `tool_manifest_hash`) |
|
|
13
|
+
|
|
14
|
+
Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` let a call run. Everything else does not, in ENFORCE and in REPORT mode alike: `DENY`, `RATE_LIMITED`, `UNCHECKED`, a response without a decision, an unreachable authority, an HTTP error, an exception anywhere in the CHECK path, or a CHECK slower than `check_timeout` (10 s by default).
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install maigp-langgraph
|
|
20
|
+
pip install 'maigp-langgraph[agents]' # adds langchain, for langchain.agents.create_agent middleware
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
It uses [`maigp-client`](https://pypi.org/project/maigp-client/) (the protocol client), [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/) (shared lifecycle) and `langgraph>=1.0,<2`. Tested on langgraph 1.0.0 (langgraph-prebuilt 1.0.2, langchain-core 1.0.0, langchain 1.0.0) and on langgraph 1.2.24 (langgraph-prebuilt 1.1.3, langchain-core 1.8.5, langchain 1.5.2).
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
A graph with one governed model and one governed tool. The model here is scripted so the example needs no API key; replace it with your chat model (`ChatAnthropic(...)`, `ChatOpenAI(...)`, ...). It needs a MAIGP governance authority at `gov_url`.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
|
|
31
|
+
from langchain_core.messages import AIMessage, HumanMessage
|
|
32
|
+
from langchain_core.tools import tool
|
|
33
|
+
from langgraph.prebuilt import create_react_agent
|
|
34
|
+
|
|
35
|
+
from maigp_agent_core import AgentGovernance
|
|
36
|
+
from maigp_langgraph import MaigpLangGraph
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@tool
|
|
40
|
+
def transfer_funds(account: str, amount: int) -> str:
|
|
41
|
+
"""Move money between accounts."""
|
|
42
|
+
return f"moved {amount} to {account}"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ScriptedModel(FakeMessagesListChatModel):
|
|
46
|
+
def bind_tools(self, tools, **kwargs): # a real chat model already has bind_tools
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
model = ScriptedModel(responses=[
|
|
51
|
+
AIMessage(content="", tool_calls=[{"name": "transfer_funds",
|
|
52
|
+
"args": {"account": "acct-9", "amount": 5}, "id": "call-1"}]),
|
|
53
|
+
AIMessage(content="done"),
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
gov = AgentGovernance(gov_url="https://gov.example.com", app_id="my-langgraph-agent",
|
|
57
|
+
hmac_secret="secret")
|
|
58
|
+
maigp = MaigpLangGraph(gov, use_case="payments-bot")
|
|
59
|
+
|
|
60
|
+
agent = create_react_agent(
|
|
61
|
+
maigp.governed_model(model), # CHECK before every model call
|
|
62
|
+
maigp.tool_node([transfer_funds]), # TOOL_REQUEST before every tool call
|
|
63
|
+
)
|
|
64
|
+
result = agent.invoke({"messages": [HumanMessage("pay acct-9 five")]})
|
|
65
|
+
print(result["messages"][-1].content)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
With the `[agents]` extra, the same governance applies to `langchain.agents.create_agent` through middleware:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from langchain.agents import create_agent
|
|
72
|
+
|
|
73
|
+
agent = create_agent(model=model, tools=[transfer_funds], middleware=[maigp.middleware()])
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
For a hand-built `StateGraph`, use the governed model inside your model node and `maigp.tool_node(tools)` as the tools node:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
gm = maigp.governed_model(model).bind_tools([transfer_funds])
|
|
80
|
+
graph.add_node("model", lambda state: {"messages": [gm.invoke(state["messages"])]})
|
|
81
|
+
graph.add_node("tools", maigp.tool_node([transfer_funds]))
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## How blocking works
|
|
85
|
+
|
|
86
|
+
LangGraph has no global "before call" switch, so MAIGP uses the extension points the installed version offers. Nothing in LangGraph is patched.
|
|
87
|
+
|
|
88
|
+
- **Tools: `langgraph.prebuilt.ToolNode(..., wrap_tool_call=..., awrap_tool_call=...)`** (class `ToolNode` in `langgraph.prebuilt.tool_node`, first released in `langgraph-prebuilt` 1.0.2). `ToolNode` hands the wrapper a `ToolCallRequest` and an `execute` callable. The wrapper sends TOOL_REQUEST and calls `execute` only when the decision allows it; otherwise it returns an error `ToolMessage` and the tool function is never called. `maigp.tool_node(tools)` builds that `ToolNode`; `maigp.wrap_tool_call` and `maigp.awrap_tool_call` are public if you construct the `ToolNode` yourself.
|
|
89
|
+
- **Models: a `langchain_core.language_models.BaseChatModel` wrapper** (`GovernedChatModel`). Every entry point of a chat model (`invoke`, `ainvoke`, `stream`, `astream`, `batch`, `generate`) reaches `_generate` / `_agenerate`. The CHECK is there, before the wrapped model is called. `bind_tools` and `with_structured_output` return a model that is still governed. Pass the unbound model to `governed_model`, then bind tools on the result (`create_react_agent` does this for you).
|
|
90
|
+
- **LangChain agents: `AgentMiddleware.wrap_model_call` / `wrap_tool_call`** (and the async twins) in `langchain.agents.middleware`, through `maigp.middleware()` (extra `agents`, `langchain>=1.0`).
|
|
91
|
+
- **Interrupts and `Command`:** a `GraphInterrupt` raised inside a tool propagates unchanged and is not recorded as a failure. A tool that returns a `Command` is recorded with the SHA-256 of its `update`.
|
|
92
|
+
|
|
93
|
+
Why not LangChain callbacks: a callback handler (see [`maigp-langchain`](https://pypi.org/project/maigp-langchain/)) observes a call. It cannot stop one, so it is not an enforcement point. LangGraph does not need it.
|
|
94
|
+
|
|
95
|
+
## Refusals in the graph
|
|
96
|
+
|
|
97
|
+
- **Tool call refused:** the graph receives `ToolMessage(content="Blocked by MAIGP governance: tool 'transfer_funds' DENY: <reason>", status="error", tool_call_id=..., name=...)`. The model sees it as the tool result and the run continues. Other tool calls of the same model turn are decided on their own.
|
|
98
|
+
- **Model call refused:** by default `MaigpGovernanceBlocked` (a subclass of `maigp_agent_core.errors.GovernanceBlockedError`, with `.decision`, `.reason`, `.what`) is raised out of the model call and the graph run stops with it. With `on_model_block="message"` the model call returns an `AIMessage` (no tool calls, `response_metadata={"maigp_blocked": True, ...}`) and an agent loop ends with that reply.
|
|
99
|
+
- **AIAP agency** (opt-in): pass `AgencyGate` to `AgentGovernance(agency=...)`. After an allowing CHECK / TOOL_REQUEST and before the call, an agency grant is required. A refusal, an unreachable broker or a slow gate blocks the call the same way (`Blocked by AIAP agency: ...`). No gate means nothing changes. Install `maigp-agent-core[agency]` for the gate.
|
|
100
|
+
|
|
101
|
+
## Configuration
|
|
102
|
+
|
|
103
|
+
`MaigpLangGraph(gov, *, use_case="langgraph-agent", check_timeout=10.0, tool_version="1.0.0", on_model_block="raise")`
|
|
104
|
+
|
|
105
|
+
| Option | Meaning |
|
|
106
|
+
|---|---|
|
|
107
|
+
| `gov` | An `AgentGovernance` from `maigp-agent-core`. `gov_url`, `app_id`, `hmac_secret` and `mode` (`ENFORCE` / `REPORT`) are set there. |
|
|
108
|
+
| `use_case` | Use case sent with model CHECK / RECORD. Override per model with `governed_model(model, use_case=...)`. |
|
|
109
|
+
| `check_timeout` | Seconds a CHECK, TOOL_REQUEST or agency request may take before the call is refused. Must be above 0. |
|
|
110
|
+
| `tool_version` | `tool_version` sent in TOOL_REQUEST. |
|
|
111
|
+
| `on_model_block` | `"raise"` (default) or `"message"`, see above. |
|
|
112
|
+
|
|
113
|
+
`governed_model(model, use_case=None, model_id=None)`: `model_id` defaults to the model's `model_name` / `model_id` / `model` attribute, else its class name.
|
|
114
|
+
|
|
115
|
+
`tool_node(tools, **kwargs)` passes `kwargs` to `ToolNode` (`name`, `handle_tool_errors`, ...) and refuses `wrap_tool_call` / `awrap_tool_call`, which would replace governance.
|
|
116
|
+
|
|
117
|
+
## Fail-closed semantics
|
|
118
|
+
|
|
119
|
+
- A refused call never reaches the model or the tool. The check is made on the request that is actually executed.
|
|
120
|
+
- `MaigpLangGraph(...)` raises `RuntimeError` when the client is disabled (an empty `gov_url` makes `maigp-client` answer ALLOW to everything), and when the installed LangGraph's `ToolNode` has no `wrap_tool_call`. It raises `TypeError` for a `gov` without a client.
|
|
121
|
+
- RECORD runs after the call and never raises into the graph: a failed RECORD is logged. A call that was blocked is never recorded as run.
|
|
122
|
+
- A tool that raised is recorded with status `ERROR` and no `output_ref`; an exception inside a model call is recorded as `ERROR` and re-raised.
|
|
123
|
+
- `maigp-client` caches a CHECK decision for the `ttl_seconds` the authority returns (default 300 s), per `use_case` and model id. Within that time the same CHECK is answered from the cache. Set a short `ttl_seconds` on the authority if you need a decision per call.
|
|
124
|
+
- Sync graphs (`invoke`, `stream`) call the async client on one background event-loop thread owned by the adapter, so they work inside and outside a running event loop. Use one style (sync or async) per `MaigpLangGraph` instance: the client's HTTP connection pool belongs to one event loop.
|
|
125
|
+
|
|
126
|
+
## Limitations
|
|
127
|
+
|
|
128
|
+
- Governance covers only the models and `ToolNode`s you build through the adapter. A tool run by an ungoverned `ToolNode`, or a model you did not wrap, is not governed. `create_react_agent(model, [tool_a])` builds its own `ToolNode`: pass `maigp.tool_node([tool_a])` instead.
|
|
129
|
+
- A tool you call directly in your own code (`tool.invoke(...)`) does not pass through a `ToolNode` and is not governed.
|
|
130
|
+
- `create_react_agent` is deprecated in LangGraph 1.x in favour of `langchain.agents.create_agent`. Both work with this adapter.
|
|
131
|
+
- Streaming model output is checked once before the stream starts and is delivered as one chunk (the wrapper does not stream token by token).
|
|
132
|
+
- Model-level RECORD reports the token usage the model returns in `usage_metadata`; a model that returns none records 0.
|
|
133
|
+
|
|
134
|
+
## Links
|
|
135
|
+
|
|
136
|
+
- Protocol, specs and full adapter catalog: https://github.com/owner-spec/aigp-protocol
|
|
137
|
+
- Issues: https://github.com/owner-spec/aigp-protocol/issues
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
License: Proprietary. © Kanjani AI Research & Causum.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""maigp-langgraph: MAIGP governance for LangGraph. Blocks, fail closed.
|
|
2
|
+
|
|
3
|
+
``MaigpLangGraph(gov).governed_model(model)`` and ``.tool_node(tools)`` put an AIGP CHECK / TOOL_REQUEST
|
|
4
|
+
in front of every model call and tool call of a LangGraph graph, and a RECORD after each call that ran.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "1.0.0"
|
|
8
|
+
|
|
9
|
+
from maigp_agent_core import AgentGovernance
|
|
10
|
+
from maigp_agent_core.errors import GovernanceBlockedError
|
|
11
|
+
|
|
12
|
+
from .adapter import MaigpGovernanceBlocked, MaigpLangGraph, sha256_ref
|
|
13
|
+
from .model import GovernedChatModel
|
|
14
|
+
|
|
15
|
+
__all__ = ["MaigpLangGraph", "GovernedChatModel", "MaigpGovernanceBlocked",
|
|
16
|
+
"GovernanceBlockedError", "AgentGovernance", "sha256_ref"]
|