maigp-langgraph 1.0.0__py3-none-any.whl

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.
@@ -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"]
@@ -0,0 +1,376 @@
1
+ """MaigpLangGraph: governs every model call and tool call of a LangGraph graph, fail closed.
2
+
3
+ Enforcement points used (langgraph 1.2.x / langgraph-prebuilt 1.1.x / langchain-core 1.8.x, all official):
4
+
5
+ - Tools: ``langgraph.prebuilt.ToolNode(tools, wrap_tool_call=..., awrap_tool_call=...)``. ToolNode calls the
6
+ wrapper with a ``ToolCallRequest`` and an ``execute`` callable. The wrapper asks the authority first and
7
+ only calls ``execute`` when the call is allowed; otherwise it returns an error ``ToolMessage`` and the
8
+ tool function is never called. ``MaigpLangGraph.tool_node(tools)`` builds that ToolNode.
9
+ - Models: a ``langchain_core`` ``BaseChatModel`` subclass (``GovernedChatModel``, see model.py) that wraps
10
+ the real chat model. Every entry point (invoke, ainvoke, stream, astream, batch) goes through its
11
+ ``_generate`` / ``_agenerate``, where the CHECK happens before the inner model is called.
12
+ - LangChain agents (``langchain.agents.create_agent``): ``AgentMiddleware.wrap_model_call`` /
13
+ ``wrap_tool_call`` (and the async twins), via ``MaigpLangGraph.middleware()`` (extra ``agents``).
14
+
15
+ Nothing in LangGraph is patched. A call is cancelled by not calling the inner model / ``execute``.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import hashlib
22
+ import json
23
+ import logging
24
+ import threading
25
+ import time
26
+ from dataclasses import dataclass
27
+ from typing import Any, Awaitable, Callable
28
+
29
+ from maigp_agent_core import AgencyRequiredError
30
+ from maigp_agent_core.errors import GovernanceBlockedError
31
+ from langgraph.errors import GraphBubbleUp
32
+ from maigp_client import tool_definition_hash
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ #: The only decisions that let a governed call run (same set as maigp-client / maigp-agent-core).
37
+ ALLOWING_DECISIONS = ("ALLOW", "ALLOW_WITH_CONSTRAINTS")
38
+
39
+ DEFAULT_CHECK_TIMEOUT_SECONDS = 10.0
40
+ DEFAULT_USE_CASE = "langgraph-agent"
41
+
42
+
43
+ class MaigpGovernanceBlocked(GovernanceBlockedError):
44
+ """A model call was refused by governance (raised from the model; tool refusals are ToolMessages)."""
45
+
46
+ def __init__(self, message: str, *, what: str = "", decision: str = "", reason: str = ""):
47
+ super().__init__(message)
48
+ self.what, self.decision, self.reason = what, decision, reason
49
+
50
+
51
+ def sha256_ref(value: Any) -> str:
52
+ """``sha256:<hex>`` of the canonical JSON of ``value`` (non-JSON values via ``str``)."""
53
+ try:
54
+ data = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
55
+ except (TypeError, ValueError):
56
+ data = str(value)
57
+ return "sha256:" + hashlib.sha256(data.encode()).hexdigest()
58
+
59
+
60
+ def _decision(result: Any) -> tuple[str, str, str]:
61
+ """(decision, reason, request_id) from a GovernanceDecision object or a dict.
62
+
63
+ Anything that is not a string decision is returned as ``""`` (never read as ALLOW).
64
+ """
65
+ if result is None:
66
+ return "", "no decision returned", ""
67
+ if isinstance(result, dict):
68
+ get = result.get
69
+ else:
70
+ def get(key, default=""):
71
+ return getattr(result, key, default)
72
+ d = get("decision", "")
73
+ return (d if isinstance(d, str) else ""), str(get("reason", "") or ""), str(get("request_id", "") or "")
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Refusal:
78
+ """Why a call was not allowed to run."""
79
+ what: str
80
+ decision: str
81
+ reason: str
82
+ text: str
83
+
84
+
85
+ def blocked_text(what: str, decision: str, reason: str) -> Refusal:
86
+ return Refusal(what, decision, reason,
87
+ f"Blocked by MAIGP governance: {what} {decision}: {reason or 'no reason given'}")
88
+
89
+
90
+ class _SyncBridge:
91
+ """Runs the (async) maigp-client from LangGraph's sync paths on ONE background event loop.
92
+
93
+ A sync graph (``graph.invoke``) runs nodes in worker threads, possibly under a caller that already
94
+ has a running loop, so ``asyncio.run`` per call is unsafe and would also hand the client's pooled
95
+ HTTP connections to a loop that is then closed. One long-lived loop thread avoids both.
96
+ """
97
+
98
+ def __init__(self) -> None:
99
+ self._loop: asyncio.AbstractEventLoop | None = None
100
+ self._lock = threading.Lock()
101
+
102
+ def _ensure(self) -> asyncio.AbstractEventLoop:
103
+ with self._lock:
104
+ if self._loop is None or self._loop.is_closed():
105
+ loop = asyncio.new_event_loop()
106
+ threading.Thread(target=loop.run_forever, name="maigp-langgraph-sync", daemon=True).start()
107
+ self._loop = loop
108
+ return self._loop
109
+
110
+ def run(self, coro: Awaitable[Any]) -> Any:
111
+ return asyncio.run_coroutine_threadsafe(coro, self._ensure()).result() # type: ignore[arg-type]
112
+
113
+
114
+ def tool_definition_of(tool: Any) -> dict | None:
115
+ """``{name, description, input_schema}`` of a LangChain tool as the model is shown it, or None.
116
+
117
+ The schema is the OpenAI-function ``parameters`` of ``convert_to_openai_tool`` (injected arguments such as
118
+ state / runtime are not part of it). Never a placeholder: if it cannot be built there is no hash.
119
+ """
120
+ if tool is None:
121
+ return None
122
+ try:
123
+ from langchain_core.utils.function_calling import convert_to_openai_tool
124
+ fn = convert_to_openai_tool(tool)["function"]
125
+ return {"name": str(fn["name"]), "description": str(fn.get("description", "")),
126
+ "input_schema": fn.get("parameters", {})}
127
+ except Exception:
128
+ return None
129
+
130
+
131
+ class MaigpLangGraph:
132
+ """Governance for LangGraph graphs.
133
+
134
+ Args:
135
+ gov: an ``AgentGovernance`` (maigp-agent-core); its ``client`` sends CHECK / TOOL_REQUEST / RECORD.
136
+ use_case: use case for model-call CHECK and RECORD (default ``"langgraph-agent"``).
137
+ check_timeout: seconds a CHECK / TOOL_REQUEST (and an agency request) may take before the call is
138
+ refused. Must be > 0. Default 10.
139
+ tool_version: ``tool_version`` sent in TOOL_REQUEST.
140
+ on_model_block: what a refused model call does. ``"raise"`` (default) raises
141
+ :class:`MaigpGovernanceBlocked` out of the model call, so the graph run stops with that error.
142
+ ``"message"`` returns an ``AIMessage`` (no tool calls) saying it was blocked, so a normal agent
143
+ loop ends with that reply. Tool refusals are always an error ``ToolMessage``.
144
+
145
+ Raises:
146
+ RuntimeError: ``gov`` has a disabled client (empty ``gov_url``: it would answer ALLOW to everything),
147
+ or the installed LangGraph's ``ToolNode`` has no ``wrap_tool_call`` hook (cannot enforce).
148
+ """
149
+
150
+ def __init__(self, gov: Any, *, use_case: str = DEFAULT_USE_CASE,
151
+ check_timeout: float = DEFAULT_CHECK_TIMEOUT_SECONDS,
152
+ tool_version: str = "1.0.0", on_model_block: str = "raise"):
153
+ if check_timeout <= 0:
154
+ raise ValueError("check_timeout must be > 0")
155
+ if on_model_block not in ("raise", "message"):
156
+ raise ValueError("on_model_block must be 'raise' or 'message'")
157
+ client = getattr(gov, "client", None)
158
+ if client is None:
159
+ raise TypeError("gov must be an AgentGovernance (maigp-agent-core) with a .client")
160
+ if getattr(client, "_enabled", True) is False:
161
+ # MaigpClient(enabled=False) (AgentGovernance with an empty gov_url) answers ALLOW to everything
162
+ # without asking anyone: refusing here keeps "governed" from meaning "open".
163
+ raise RuntimeError("maigp-langgraph: governance client is disabled (no gov_url); "
164
+ "refusing to build an adapter that cannot govern")
165
+ _require_wrap_tool_call()
166
+ self._gov = gov
167
+ self._client = client
168
+ self._use_case = use_case
169
+ self._check_timeout = check_timeout
170
+ self._tool_version = tool_version
171
+ self._on_model_block = on_model_block
172
+ self._bridge = _SyncBridge()
173
+
174
+ # ── public API ──
175
+ @property
176
+ def governance(self) -> Any:
177
+ return self._gov
178
+
179
+ def governed_model(self, model: Any, *, use_case: str | None = None, model_id: str | None = None):
180
+ """Wrap a LangChain chat model so every call is CHECKed first (see GovernedChatModel).
181
+
182
+ Pass the UNBOUND model, then bind tools on the result (``create_react_agent`` and
183
+ ``bind_tools`` on the wrapper keep governance)."""
184
+ from .model import GovernedChatModel
185
+ return GovernedChatModel(inner=model, maigp=self, use_case=use_case or "", gov_model_id=model_id or "")
186
+
187
+ def tool_node(self, tools: Any, **kwargs: Any):
188
+ """A ``langgraph.prebuilt.ToolNode`` whose every tool call is TOOL_REQUESTed first.
189
+
190
+ ``kwargs`` go to ``ToolNode`` (``name``, ``handle_tool_errors``, ...). ``wrap_tool_call`` /
191
+ ``awrap_tool_call`` are refused: they would replace governance.
192
+ """
193
+ from langgraph.prebuilt import ToolNode
194
+ if "wrap_tool_call" in kwargs or "awrap_tool_call" in kwargs:
195
+ raise TypeError("maigp-langgraph: tool_node() owns wrap_tool_call / awrap_tool_call; "
196
+ "pass other options only")
197
+ return ToolNode(tools, wrap_tool_call=self.wrap_tool_call,
198
+ awrap_tool_call=self.awrap_tool_call, **kwargs)
199
+
200
+ def middleware(self):
201
+ """An ``AgentMiddleware`` for ``langchain.agents.create_agent(..., middleware=[...])``.
202
+
203
+ Needs ``langchain>=1.0`` (``pip install 'maigp-langgraph[agents]'``)."""
204
+ from .middleware import build_middleware
205
+ return build_middleware(self)
206
+
207
+ # ── CHECK path ──
208
+ async def _ask(self, what: str, factory: Callable[[], Awaitable[Any]]) -> tuple[bool, str, str, str]:
209
+ """One CHECK / TOOL_REQUEST. Returns (allowed, decision, reason, request_id); never raises."""
210
+ try:
211
+ result = await asyncio.wait_for(factory(), timeout=self._check_timeout)
212
+ d, reason, request_id = _decision(result)
213
+ except asyncio.TimeoutError:
214
+ d, reason, request_id = "UNCHECKED", f"CHECK timed out after {self._check_timeout:g}s", ""
215
+ except Exception as e: # fail closed: a broken CHECK path never lets the call through
216
+ d, reason, request_id = "UNCHECKED", f"CHECK failed: {type(e).__name__}: {e}", ""
217
+ allowed = d in ALLOWING_DECISIONS
218
+ if not allowed:
219
+ logger.warning("AIGP: %s BLOCKED (%s): %s", what, d or "no decision", reason)
220
+ return allowed, d or "UNCHECKED", reason, request_id
221
+
222
+ async def _agency(self, what: str, use_case: str, trace_id: str) -> Refusal | None:
223
+ """AIAP agency after an allowing CHECK. None = may run (no gate, or a usable grant), else the
224
+ refusal. Never raises."""
225
+ if getattr(self._gov, "agency", None) is None:
226
+ return None
227
+ try:
228
+ await asyncio.wait_for(self._gov.arequire_agency(use_case, trace_id=trace_id),
229
+ timeout=self._check_timeout)
230
+ return None
231
+ except asyncio.TimeoutError:
232
+ code, reason = "TIMEOUT", f"agency request timed out after {self._check_timeout:g}s"
233
+ except AgencyRequiredError as e:
234
+ code, reason = (e.code or "REFUSED"), str(e)
235
+ except Exception as e:
236
+ code, reason = "BROKER_ERROR", f"agency gate failed: {type(e).__name__}: {e}"
237
+ logger.warning("AIAP: %s BLOCKED (agency %s): %s", what, code, reason)
238
+ return Refusal(what, f"AGENCY_{code}", reason,
239
+ f"Blocked by AIAP agency: {what} {code}: {reason or 'no reason given'}")
240
+
241
+ async def _record(self, **kw: Any) -> None:
242
+ try:
243
+ await asyncio.wait_for(
244
+ self._client.record(session_id=getattr(self._gov, "session_id", "") or "", **kw),
245
+ timeout=self._check_timeout)
246
+ except Exception as e: # RECORD is after the fact: a failure is logged, never raised
247
+ logger.error("AIGP RECORD failed (%s): %s", kw.get("use_case"), e)
248
+
249
+ # ── model calls (used by GovernedChatModel and the middleware) ──
250
+ def _resolve_use_case(self, use_case: str = "") -> str:
251
+ return use_case or self._use_case
252
+
253
+ async def agate_model(self, use_case: str, model_id: str) -> tuple[Refusal | None, tuple | None]:
254
+ """CHECK before a model call. Returns (refusal, ticket): ``refusal`` None = run the call."""
255
+ use_case = self._resolve_use_case(use_case)
256
+ allowed, d, reason, request_id = await self._ask(
257
+ "model call", lambda: self._client.check(use_case=use_case, model_id=model_id))
258
+ if not allowed:
259
+ return blocked_text("model call", d, reason), None
260
+ refused = await self._agency("model call", use_case, request_id)
261
+ if refused:
262
+ return refused, None
263
+ return None, (request_id, use_case, model_id, time.monotonic())
264
+
265
+ async def arecord_model(self, ticket: tuple, *, input_tokens: int = 0, output_tokens: int = 0,
266
+ failed: bool = False) -> None:
267
+ request_id, use_case, model_id, started = ticket
268
+ await self._record(use_case=use_case, model_id=model_id, request_id=request_id,
269
+ input_tokens=int(input_tokens or 0), output_tokens=int(output_tokens or 0),
270
+ duration_ms=(time.monotonic() - started) * 1000,
271
+ status="ERROR" if failed else "SUCCESS")
272
+
273
+ def gate_model(self, use_case: str, model_id: str) -> tuple[Refusal | None, tuple | None]:
274
+ return self._bridge.run(self.agate_model(use_case, model_id))
275
+
276
+ def record_model(self, ticket: tuple, **kw: Any) -> None:
277
+ self._bridge.run(self.arecord_model(ticket, **kw))
278
+
279
+ def model_refused(self, refusal: Refusal):
280
+ """The model-call refusal in the configured idiom: raises, or returns a blocked AIMessage."""
281
+ if self._on_model_block == "message":
282
+ from langchain_core.messages import AIMessage
283
+ return AIMessage(content=refusal.text, response_metadata={
284
+ "maigp_blocked": True, "maigp_decision": refusal.decision})
285
+ raise MaigpGovernanceBlocked(refusal.text, what=refusal.what,
286
+ decision=refusal.decision, reason=refusal.reason)
287
+
288
+ # ── tool calls ──
289
+ async def _agate_tool(self, request: Any) -> tuple[Refusal | None, tuple | None]:
290
+ call = request.tool_call
291
+ name = str(call.get("name", ""))
292
+ definition = tool_definition_of(getattr(request, "tool", None))
293
+ manifest_hash = ""
294
+ extra: dict = {}
295
+ if definition is not None:
296
+ extra["tool_definition"] = definition
297
+ manifest_hash = tool_definition_hash(definition["name"], definition["description"],
298
+ definition["input_schema"])
299
+ params_hash = sha256_ref(call.get("args"))
300
+ allowed, d, reason, request_id = await self._ask(
301
+ f"tool '{name}'", lambda: self._client.tool_request(
302
+ tool_id=name, tool_version=self._tool_version, input_params_hash=params_hash, **extra))
303
+ if not allowed:
304
+ return blocked_text(f"tool '{name}'", d, reason), None
305
+ refused = await self._agency(f"tool '{name}'", self._use_case, request_id)
306
+ if refused:
307
+ return refused, None
308
+ return None, (request_id, name, manifest_hash, time.monotonic())
309
+
310
+ async def _arecord_tool(self, ticket: tuple, result: Any, failed: bool) -> None:
311
+ """RECORD a tool call that ran. ``result`` None (the tool raised): no output_ref."""
312
+ request_id, name, manifest_hash, started = ticket
313
+ extra = {"tool_manifest_hash": manifest_hash} if manifest_hash else {}
314
+ await self._record(use_case=f"tool:{name}", model_id="", request_id=request_id, **extra,
315
+ input_tokens=0, output_tokens=0,
316
+ duration_ms=(time.monotonic() - started) * 1000,
317
+ status="ERROR" if failed else "SUCCESS",
318
+ output_ref="" if result is None else _result_ref(result))
319
+
320
+ @staticmethod
321
+ def _blocked_message(request: Any, refusal: Refusal):
322
+ from langchain_core.messages import ToolMessage
323
+ call = request.tool_call
324
+ return ToolMessage(content=refusal.text, name=call.get("name"), tool_call_id=call.get("id"), status="error")
325
+
326
+ def wrap_tool_call(self, request: Any, execute: Callable[[Any], Any]) -> Any:
327
+ """``ToolNode(wrap_tool_call=...)``: TOOL_REQUEST, run only if allowed, RECORD."""
328
+ refusal, ticket = self._bridge.run(self._agate_tool(request))
329
+ if ticket is None:
330
+ return self._blocked_message(request, refusal)
331
+ try:
332
+ result = execute(request)
333
+ except GraphBubbleUp: # an interrupt inside the tool is a pause, not a failure
334
+ raise
335
+ except Exception:
336
+ self._bridge.run(self._arecord_tool(ticket, None, True))
337
+ raise
338
+ self._bridge.run(self._arecord_tool(ticket, result, _is_error(result)))
339
+ return result
340
+
341
+ async def awrap_tool_call(self, request: Any, execute: Callable[[Any], Awaitable[Any]]) -> Any:
342
+ """``ToolNode(awrap_tool_call=...)``: async twin of :meth:`wrap_tool_call`."""
343
+ refusal, ticket = await self._agate_tool(request)
344
+ if ticket is None:
345
+ return self._blocked_message(request, refusal)
346
+ try:
347
+ result = await execute(request)
348
+ except GraphBubbleUp:
349
+ raise
350
+ except Exception:
351
+ await self._arecord_tool(ticket, None, True)
352
+ raise
353
+ await self._arecord_tool(ticket, result, _is_error(result))
354
+ return result
355
+
356
+
357
+ def _is_error(result: Any) -> bool:
358
+ return getattr(result, "status", None) == "error"
359
+
360
+
361
+ def _result_ref(result: Any) -> str:
362
+ """sha256 of a tool result: a ToolMessage's content, or a Command's update."""
363
+ content = getattr(result, "content", None)
364
+ if content is None:
365
+ content = getattr(result, "update", result)
366
+ return sha256_ref(content)
367
+
368
+
369
+ def _require_wrap_tool_call() -> None:
370
+ """Refuse a LangGraph whose ToolNode cannot intercept a tool call: governance that cannot block is none."""
371
+ import inspect
372
+ from langgraph.prebuilt import ToolNode
373
+ params = inspect.signature(ToolNode.__init__).parameters
374
+ if "wrap_tool_call" not in params or "awrap_tool_call" not in params:
375
+ raise RuntimeError("maigp-langgraph: installed langgraph ToolNode has no wrap_tool_call / "
376
+ "awrap_tool_call; cannot enforce governance (requires langgraph>=1.0,<2)")
@@ -0,0 +1,64 @@
1
+ """``langchain.agents.create_agent`` middleware: MAIGP in ``wrap_model_call`` / ``wrap_tool_call``.
2
+
3
+ Imported only by ``MaigpLangGraph.middleware()`` (needs ``langchain>=1.0``).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ from langchain.agents.middleware import AgentMiddleware
11
+
12
+
13
+ def build_middleware(maigp: Any) -> AgentMiddleware:
14
+ from .model import _model_id
15
+
16
+ class MaigpMiddleware(AgentMiddleware):
17
+ """Governs every model call and tool call of a ``create_agent`` agent (fail closed)."""
18
+
19
+ name = "MaigpMiddleware"
20
+
21
+ def _usage(self, response: Any) -> dict:
22
+ for m in getattr(response, "result", None) or []:
23
+ u = getattr(m, "usage_metadata", None)
24
+ if u:
25
+ return {"input_tokens": int(u.get("input_tokens", 0) or 0),
26
+ "output_tokens": int(u.get("output_tokens", 0) or 0)}
27
+ if hasattr(response, "usage_metadata"):
28
+ u = response.usage_metadata or {}
29
+ return {"input_tokens": int(u.get("input_tokens", 0) or 0),
30
+ "output_tokens": int(u.get("output_tokens", 0) or 0)}
31
+ return {}
32
+
33
+ def wrap_model_call(self, request, handler):
34
+ refusal, ticket = maigp.gate_model("", _model_id(request.model) or type(request.model).__name__)
35
+ if refusal is not None:
36
+ return maigp.model_refused(refusal)
37
+ try:
38
+ response = handler(request)
39
+ except Exception:
40
+ maigp.record_model(ticket, failed=True)
41
+ raise
42
+ maigp.record_model(ticket, **self._usage(response))
43
+ return response
44
+
45
+ async def awrap_model_call(self, request, handler):
46
+ refusal, ticket = await maigp.agate_model(
47
+ "", _model_id(request.model) or type(request.model).__name__)
48
+ if refusal is not None:
49
+ return maigp.model_refused(refusal)
50
+ try:
51
+ response = await handler(request)
52
+ except Exception:
53
+ await maigp.arecord_model(ticket, failed=True)
54
+ raise
55
+ await maigp.arecord_model(ticket, **self._usage(response))
56
+ return response
57
+
58
+ def wrap_tool_call(self, request, handler):
59
+ return maigp.wrap_tool_call(request, handler)
60
+
61
+ async def awrap_tool_call(self, request, handler):
62
+ return await maigp.awrap_tool_call(request, handler)
63
+
64
+ return MaigpMiddleware()
@@ -0,0 +1,101 @@
1
+ """GovernedChatModel: a ``BaseChatModel`` that CHECKs with MAIGP before it calls the real model.
2
+
3
+ LangGraph graphs call chat models through ``invoke`` / ``ainvoke`` / ``stream`` / ``astream`` / ``batch``.
4
+ All of them reach ``BaseChatModel._generate`` / ``_agenerate`` (this class does not implement ``_stream``,
5
+ so streaming falls back to the same path). That is where the CHECK sits, so there is no entry point around it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from langchain_core.language_models.chat_models import BaseChatModel
13
+ from langchain_core.messages import AIMessage, BaseMessage
14
+ from langchain_core.outputs import ChatGeneration, ChatResult
15
+ from pydantic import ConfigDict
16
+
17
+
18
+ def _model_id(model: Any) -> str:
19
+ """Best-effort model identifier of a chat model (or a binding around one)."""
20
+ seen = 0
21
+ while model is not None and seen < 8:
22
+ for attr in ("model_name", "model_id", "model"):
23
+ v = getattr(model, attr, None)
24
+ if isinstance(v, str) and v:
25
+ return v
26
+ model = getattr(model, "bound", None)
27
+ seen += 1
28
+ return ""
29
+
30
+
31
+ def _as_message(out: Any) -> BaseMessage:
32
+ return out if isinstance(out, BaseMessage) else AIMessage(content=str(out))
33
+
34
+
35
+ class GovernedChatModel(BaseChatModel):
36
+ """Wraps ``inner`` (a chat model or a bound model). Build with ``MaigpLangGraph.governed_model``."""
37
+
38
+ model_config = ConfigDict(arbitrary_types_allowed=True)
39
+
40
+ inner: Any
41
+ maigp: Any
42
+ use_case: str = ""
43
+ gov_model_id: str = ""
44
+
45
+ @property
46
+ def _llm_type(self) -> str:
47
+ return "maigp-governed"
48
+
49
+ @property
50
+ def _identifying_params(self) -> dict:
51
+ return {"inner": getattr(self.inner, "_llm_type", type(self.inner).__name__)}
52
+
53
+ def _mid(self) -> str:
54
+ return self.gov_model_id or _model_id(self.inner) or type(self.inner).__name__
55
+
56
+ def bind_tools(self, tools: Any, **kwargs: Any) -> "GovernedChatModel":
57
+ """Bind tools on the inner model; the result is still governed."""
58
+ return self.model_copy(update={"inner": self.inner.bind_tools(tools, **kwargs)})
59
+
60
+ @staticmethod
61
+ def _call_kwargs(stop: Any, kwargs: dict) -> dict:
62
+ kw = dict(kwargs)
63
+ if stop is not None:
64
+ kw["stop"] = stop
65
+ return kw
66
+
67
+ @staticmethod
68
+ def _result(msg: BaseMessage) -> ChatResult:
69
+ return ChatResult(generations=[ChatGeneration(message=msg)])
70
+
71
+ @staticmethod
72
+ def _tokens(msg: BaseMessage) -> dict:
73
+ u = getattr(msg, "usage_metadata", None) or {}
74
+ return {"input_tokens": int(u.get("input_tokens", 0) or 0),
75
+ "output_tokens": int(u.get("output_tokens", 0) or 0)}
76
+
77
+ def _generate(self, messages: list[BaseMessage], stop: list[str] | None = None,
78
+ run_manager: Any = None, **kwargs: Any) -> ChatResult:
79
+ refusal, ticket = self.maigp.gate_model(self.use_case, self._mid())
80
+ if refusal is not None:
81
+ return self._result(self.maigp.model_refused(refusal)) # raises unless on_model_block="message"
82
+ try:
83
+ out = _as_message(self.inner.invoke(messages, **self._call_kwargs(stop, kwargs)))
84
+ except Exception:
85
+ self.maigp.record_model(ticket, failed=True)
86
+ raise
87
+ self.maigp.record_model(ticket, **self._tokens(out))
88
+ return self._result(out)
89
+
90
+ async def _agenerate(self, messages: list[BaseMessage], stop: list[str] | None = None,
91
+ run_manager: Any = None, **kwargs: Any) -> ChatResult:
92
+ refusal, ticket = await self.maigp.agate_model(self.use_case, self._mid())
93
+ if refusal is not None:
94
+ return self._result(self.maigp.model_refused(refusal))
95
+ try:
96
+ out = _as_message(await self.inner.ainvoke(messages, **self._call_kwargs(stop, kwargs)))
97
+ except Exception:
98
+ await self.maigp.arecord_model(ticket, failed=True)
99
+ raise
100
+ await self.maigp.arecord_model(ticket, **self._tokens(out))
101
+ return self._result(out)
@@ -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,7 @@
1
+ maigp_langgraph/__init__.py,sha256=Uof4hwmOuWh4TdtojWxSrGP2xT6hhPuA4oiTDPQmYXA,672
2
+ maigp_langgraph/adapter.py,sha256=2BSWh9xtTzFeNK8Iw2UpxNhQ7vU3s9YwSQMQfKzM4lg,18532
3
+ maigp_langgraph/middleware.py,sha256=VNDB53rak6macTPNEtMW4mC6bm3XskSDtnUOVbgV0AU,2532
4
+ maigp_langgraph/model.py,sha256=rP_0Bt8zMGj-C9fUQ4w3yFatxgvDWGiSUgQUyJemhNc,4042
5
+ maigp_langgraph-1.0.0.dist-info/METADATA,sha256=hu-bsDz4OrpXrCD9myxtQ_rjXbhZjMmYXhbAVtaC6NM,11536
6
+ maigp_langgraph-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ maigp_langgraph-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any