langchain-acgs 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langchain_acgs-0.1.0/.gitignore +12 -0
- langchain_acgs-0.1.0/CHANGELOG.md +18 -0
- langchain_acgs-0.1.0/LICENSE +175 -0
- langchain_acgs-0.1.0/Makefile +40 -0
- langchain_acgs-0.1.0/PKG-INFO +358 -0
- langchain_acgs-0.1.0/README.md +328 -0
- langchain_acgs-0.1.0/examples/quickstart.py +103 -0
- langchain_acgs-0.1.0/langchain_acgs/__init__.py +18 -0
- langchain_acgs-0.1.0/langchain_acgs/_governance.py +302 -0
- langchain_acgs-0.1.0/langchain_acgs/_version.py +3 -0
- langchain_acgs-0.1.0/langchain_acgs/middleware.py +286 -0
- langchain_acgs-0.1.0/langchain_acgs/py.typed +0 -0
- langchain_acgs-0.1.0/pyproject.toml +113 -0
- langchain_acgs-0.1.0/scripts/check_imports.py +29 -0
- langchain_acgs-0.1.0/scripts/check_version.py +24 -0
- langchain_acgs-0.1.0/scripts/lint_imports.sh +8 -0
- langchain_acgs-0.1.0/tests/__init__.py +0 -0
- langchain_acgs-0.1.0/tests/integration_tests/__init__.py +0 -0
- langchain_acgs-0.1.0/tests/integration_tests/test_compile.py +8 -0
- langchain_acgs-0.1.0/tests/unit_tests/__init__.py +0 -0
- langchain_acgs-0.1.0/tests/unit_tests/fakes.py +57 -0
- langchain_acgs-0.1.0/tests/unit_tests/test_default_constitution.py +90 -0
- langchain_acgs-0.1.0/tests/unit_tests/test_examples.py +39 -0
- langchain_acgs-0.1.0/tests/unit_tests/test_governance.py +238 -0
- langchain_acgs-0.1.0/tests/unit_tests/test_imports.py +15 -0
- langchain_acgs-0.1.0/tests/unit_tests/test_middleware.py +439 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## 0.1.0 (unreleased)
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `ACGSMiddleware`, a LangChain `AgentMiddleware` that checks each tool call against an ACGS constitution in
|
|
14
|
+
`wrap_tool_call` and `awrap_tool_call`.
|
|
15
|
+
- Review verdicts pause the agent with a LangGraph `interrupt` (`ACGSReviewRequest`, same keys as
|
|
16
|
+
`ToolApprovalRequest`); `approve`, `reject` and `edit` answers, with edited arguments evaluated again.
|
|
17
|
+
- `format_tool_call`, the documented text representation of a tool call that ACGS rules are evaluated against.
|
|
18
|
+
- Fail-closed handling: evaluation errors and invalid review answers deny the call.
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
.PHONY: all format lint type test tests integration_tests check_imports check_version help
|
|
2
|
+
|
|
3
|
+
all: help
|
|
4
|
+
|
|
5
|
+
TEST_FILE ?= tests/unit_tests/ langchain_acgs/
|
|
6
|
+
PYTEST_EXTRA ?=
|
|
7
|
+
PYTHON_FILES = .
|
|
8
|
+
|
|
9
|
+
test tests:
|
|
10
|
+
uv run --group test pytest $(PYTEST_EXTRA) --disable-socket --allow-unix-socket --cov --cov-report=term-missing $(TEST_FILE)
|
|
11
|
+
|
|
12
|
+
integration_test integration_tests:
|
|
13
|
+
uv run --group test pytest $(PYTEST_EXTRA) tests/integration_tests/
|
|
14
|
+
|
|
15
|
+
lint:
|
|
16
|
+
./scripts/lint_imports.sh
|
|
17
|
+
uv run --all-groups ruff check $(PYTHON_FILES)
|
|
18
|
+
uv run --all-groups ruff format $(PYTHON_FILES) --diff
|
|
19
|
+
uv run --all-groups mypy
|
|
20
|
+
|
|
21
|
+
type:
|
|
22
|
+
uv run --all-groups mypy
|
|
23
|
+
|
|
24
|
+
format:
|
|
25
|
+
uv run --all-groups ruff format $(PYTHON_FILES)
|
|
26
|
+
uv run --all-groups ruff check --fix $(PYTHON_FILES)
|
|
27
|
+
|
|
28
|
+
check_imports: $(shell find langchain_acgs -name '*.py')
|
|
29
|
+
uv run --all-groups python ./scripts/check_imports.py $^
|
|
30
|
+
|
|
31
|
+
check_version:
|
|
32
|
+
uv run python ./scripts/check_version.py
|
|
33
|
+
|
|
34
|
+
help:
|
|
35
|
+
@echo 'format - run code formatters'
|
|
36
|
+
@echo 'lint - run import checks, ruff and mypy --strict'
|
|
37
|
+
@echo 'type - run mypy --strict'
|
|
38
|
+
@echo 'test - run unit tests with the coverage gate (network disabled)'
|
|
39
|
+
@echo 'check_imports - check that every module imports'
|
|
40
|
+
@echo 'check_version - check that pyproject.toml and _version.py agree'
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: langchain-acgs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ACGS tool-call governance middleware for LangChain agents
|
|
5
|
+
Project-URL: Documentation, https://github.com/acgs-ai/langchain-acgs#readme
|
|
6
|
+
Project-URL: Repository, https://github.com/acgs-ai/langchain-acgs
|
|
7
|
+
Project-URL: Issues, https://github.com/acgs-ai/langchain-acgs/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/acgs-ai/langchain-acgs/blob/main/CHANGELOG.md
|
|
9
|
+
Author: Martin Lyu
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: acgs,agents,governance,guardrails,human-in-the-loop,langchain,langgraph,middleware
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: <4.0.0,>=3.10.0
|
|
24
|
+
Requires-Dist: acgs-lite<4.0.0,>=3.0.1
|
|
25
|
+
Requires-Dist: langchain-core<2.0.0,>=1.2.10
|
|
26
|
+
Requires-Dist: langchain<2.0.0,>=1.2.15
|
|
27
|
+
Requires-Dist: langgraph<2.0.0,>=1.1.5
|
|
28
|
+
Requires-Dist: typing-extensions>=4.7.0
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# langchain-acgs
|
|
32
|
+
|
|
33
|
+
[](https://github.com/acgs-ai/langchain-acgs/actions/workflows/ci.yml)
|
|
34
|
+
[](https://pypi.org/project/langchain-acgs/)
|
|
35
|
+
[](https://pypi.org/project/langchain-acgs/)
|
|
36
|
+
|
|
37
|
+
`langchain-acgs` checks each tool call a LangChain agent is about to make against the rules of an
|
|
38
|
+
[ACGS](https://pypi.org/project/acgs-lite/) constitution (`acgs-lite`). It provides `ACGSMiddleware`, an
|
|
39
|
+
`AgentMiddleware` for `create_agent` that implements `wrap_tool_call` and `awrap_tool_call`:
|
|
40
|
+
|
|
41
|
+
- calls that match no blocking rule run unchanged;
|
|
42
|
+
- calls that match a blocking rule do not run; the model receives a `ToolMessage` with `status="error"` that names
|
|
43
|
+
the rule;
|
|
44
|
+
- calls that match only review rules pause the agent with a native LangGraph `interrupt`, and run only if a person
|
|
45
|
+
approves them;
|
|
46
|
+
- any error while evaluating a call, and any review answer that is not a valid decision, denies the call.
|
|
47
|
+
|
|
48
|
+
Rule evaluation is deterministic keyword and regex matching done locally by `acgs-lite`; no model or network call is
|
|
49
|
+
made.
|
|
50
|
+
|
|
51
|
+
## Installation
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install langchain-acgs
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Requires Python 3.10+, `langchain` 1.x and `acgs-lite` 3.x. Pausing for review in async code (`ainvoke`, `astream`)
|
|
58
|
+
needs Python 3.11+, as for any LangGraph `interrupt`.
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
The example below runs offline. `ScriptedModel` replays fixed tool calls in place of a chat model; in real use, pass
|
|
63
|
+
any LangChain chat model that supports tool calling. The same file is
|
|
64
|
+
[`examples/quickstart.py`](examples/quickstart.py) and is executed by the test suite.
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
"""Block a tool call that leaks a password, let a harmless one run, and pause a refund for review.
|
|
68
|
+
|
|
69
|
+
Runs offline: ``ScriptedModel`` stands in for a chat model and replays fixed tool calls.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
from collections.abc import Iterator
|
|
73
|
+
from typing import Any
|
|
74
|
+
|
|
75
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
76
|
+
from langchain.agents import create_agent
|
|
77
|
+
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
|
|
78
|
+
from langchain_core.messages import AIMessage
|
|
79
|
+
from langchain_core.runnables import RunnableConfig
|
|
80
|
+
from langchain_core.tools import tool
|
|
81
|
+
from langgraph.checkpoint.memory import InMemorySaver
|
|
82
|
+
from langgraph.types import Command
|
|
83
|
+
|
|
84
|
+
from langchain_acgs import ACGSMiddleware
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ScriptedModel(GenericFakeChatModel):
|
|
88
|
+
"""Replays scripted messages; ``create_agent`` binds tools, which this model ignores."""
|
|
89
|
+
|
|
90
|
+
def bind_tools(self, tools: Any, **kwargs: Any) -> "ScriptedModel":
|
|
91
|
+
return self
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def scripted(*messages: AIMessage) -> ScriptedModel:
|
|
95
|
+
replies: Iterator[AIMessage] = iter(messages)
|
|
96
|
+
return ScriptedModel(messages=replies)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@tool
|
|
100
|
+
def send_email(to: str, body: str) -> str:
|
|
101
|
+
"""Send an email."""
|
|
102
|
+
return f"Email sent to {to}"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@tool
|
|
106
|
+
def get_weather(city: str) -> str:
|
|
107
|
+
"""Get the weather for a city."""
|
|
108
|
+
return f"Sunny in {city}"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@tool
|
|
112
|
+
def issue_refund(order_id: str, amount: float) -> str:
|
|
113
|
+
"""Refund an order."""
|
|
114
|
+
return f"Refunded {amount} for {order_id}"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# 1. The default constitution blocks the leaked password and allows the weather lookup.
|
|
118
|
+
model = scripted(
|
|
119
|
+
AIMessage(
|
|
120
|
+
content="",
|
|
121
|
+
tool_calls=[
|
|
122
|
+
{
|
|
123
|
+
"name": "send_email",
|
|
124
|
+
"args": {"to": "ops@example.com", "body": "The admin password is hunter2"},
|
|
125
|
+
"id": "1",
|
|
126
|
+
},
|
|
127
|
+
{"name": "get_weather", "args": {"city": "Paris"}, "id": "2"},
|
|
128
|
+
],
|
|
129
|
+
),
|
|
130
|
+
AIMessage(content="Done."),
|
|
131
|
+
)
|
|
132
|
+
agent = create_agent(model, tools=[send_email, get_weather], middleware=[ACGSMiddleware()])
|
|
133
|
+
result = agent.invoke({"messages": [{"role": "user", "content": "Email the admin password, then check Paris."}]})
|
|
134
|
+
for message in result["messages"]:
|
|
135
|
+
if message.type == "tool":
|
|
136
|
+
print(f"{message.name}: {message.status}: {message.content}")
|
|
137
|
+
|
|
138
|
+
# 2. A custom rule that requires human review pauses the agent; a checkpointer lets it resume.
|
|
139
|
+
refunds = Constitution.from_rules(
|
|
140
|
+
[
|
|
141
|
+
Rule(
|
|
142
|
+
id="REFUND-REVIEW",
|
|
143
|
+
text="Refunds need human approval",
|
|
144
|
+
severity=Severity.HIGH,
|
|
145
|
+
keywords=["refund"],
|
|
146
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
147
|
+
)
|
|
148
|
+
],
|
|
149
|
+
name="refunds",
|
|
150
|
+
)
|
|
151
|
+
model = scripted(
|
|
152
|
+
AIMessage(
|
|
153
|
+
content="", tool_calls=[{"name": "issue_refund", "args": {"order_id": "A-17", "amount": 20.0}, "id": "3"}]
|
|
154
|
+
),
|
|
155
|
+
AIMessage(content="Refund issued."),
|
|
156
|
+
)
|
|
157
|
+
agent = create_agent(
|
|
158
|
+
model,
|
|
159
|
+
tools=[issue_refund],
|
|
160
|
+
middleware=[ACGSMiddleware(constitution=refunds)],
|
|
161
|
+
checkpointer=InMemorySaver(),
|
|
162
|
+
)
|
|
163
|
+
config: RunnableConfig = {"configurable": {"thread_id": "refund-1"}}
|
|
164
|
+
paused = agent.invoke({"messages": [{"role": "user", "content": "Refund order A-17."}]}, config)
|
|
165
|
+
request = paused["__interrupt__"][0].value
|
|
166
|
+
print(f"review requested: {request['name']} {request['args']} - {request['description']}")
|
|
167
|
+
|
|
168
|
+
resumed = agent.invoke(Command(resume={"type": "approve"}), config)
|
|
169
|
+
print(f"after approval: {resumed['messages'][-2].content}")
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Output:
|
|
173
|
+
|
|
174
|
+
```text
|
|
175
|
+
send_email: error: Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses).
|
|
176
|
+
get_weather: success: Sunny in Paris
|
|
177
|
+
review requested: issue_refund {'order_id': 'A-17', 'amount': 20.0} - ACGS: Human review required by ACGS rule REFUND-REVIEW (Refunds need human approval).
|
|
178
|
+
after approval: Refunded 20.0 for A-17
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## How a tool call is evaluated
|
|
182
|
+
|
|
183
|
+
1. `request.tool_call["name"]` and `request.tool_call["args"]` are rendered as text by `format_tool_call`:
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
from langchain_acgs import format_tool_call
|
|
187
|
+
|
|
188
|
+
print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
```text
|
|
192
|
+
tool: update_config
|
|
193
|
+
arguments:
|
|
194
|
+
change: disable logging
|
|
195
|
+
dryRun: false
|
|
196
|
+
service: billing
|
|
197
|
+
normalized: update config | dry run
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
|
|
201
|
+
values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
|
|
202
|
+
Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the tool name, argument names, and
|
|
203
|
+
single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
|
|
204
|
+
`skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
|
|
205
|
+
Pass `tool_call_formatter=` to use a different representation.
|
|
206
|
+
|
|
207
|
+
2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
|
|
208
|
+
(`Constitution.default()` unless you pass one).
|
|
209
|
+
|
|
210
|
+
3. The result decides what happens to the call:
|
|
211
|
+
|
|
212
|
+
| ACGS outcome | Result |
|
|
213
|
+
|---|---|
|
|
214
|
+
| No blocking rule matched (warn-only rules may match) | The next handler runs the tool |
|
|
215
|
+
| Only `require_human_review` / `escalate_to_senior` rules matched | `interrupt` with an `ACGSReviewRequest` (or a denial with `on_review="deny"`) |
|
|
216
|
+
| Any `block`, `block_and_notify` or `halt_and_alert` rule matched | Denied |
|
|
217
|
+
| A rule ID not found in the constitution, or an invalid result without a rule | Denied |
|
|
218
|
+
| Any exception while reading or evaluating the tool call | Denied (fail-closed) |
|
|
219
|
+
|
|
220
|
+
A matched blocking rule is never downgraded to review because a review rule matched as well.
|
|
221
|
+
|
|
222
|
+
A denial is returned in place of the tool result:
|
|
223
|
+
`ToolMessage(content="Tool call '<name>' was not executed. <reason>", status="error")`. The reason names the matched
|
|
224
|
+
rules but never repeats argument values. `message.artifact` holds `{"acgs_verdict": "deny", "rule_ids": [...]}` for
|
|
225
|
+
code that inspects results; it is not sent to the model. Exceptions raised by the tool itself are not handled by this
|
|
226
|
+
middleware.
|
|
227
|
+
|
|
228
|
+
`ACGSMiddleware.evaluate(tool_name, args)` returns the underlying `GovernanceDecision`
|
|
229
|
+
(`verdict`, `reason`, `rule_ids`, `warning_rule_ids`, `error`) without running anything.
|
|
230
|
+
|
|
231
|
+
## Human review
|
|
232
|
+
|
|
233
|
+
Rules whose workflow action is `require_human_review` or `escalate_to_senior` (in the default constitution:
|
|
234
|
+
`ACGS-002` and `ACGS-005`) pause the agent. The pause is a LangGraph `interrupt`, so the agent needs a checkpointer
|
|
235
|
+
to resume. Without one, the run ends with the interrupt in `result["__interrupt__"]` and the tool does not run.
|
|
236
|
+
|
|
237
|
+
The interrupt value is an `ACGSReviewRequest`, with the same keys as the `ToolApprovalRequest` that
|
|
238
|
+
`HumanInTheLoopMiddleware` raises in `per_call` mode:
|
|
239
|
+
|
|
240
|
+
```python
|
|
241
|
+
from langchain_acgs import ACGSReviewRequest
|
|
242
|
+
|
|
243
|
+
request: ACGSReviewRequest = {
|
|
244
|
+
"type": "tool_approval",
|
|
245
|
+
"tool_call_id": "3",
|
|
246
|
+
"name": "issue_refund",
|
|
247
|
+
"args": {"order_id": "A-17", "amount": 20.0},
|
|
248
|
+
"description": "ACGS: Human review required by ACGS rule REFUND-REVIEW (Refunds need human approval).",
|
|
249
|
+
}
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
Resume with one decision. `allowed_decisions` (default `("approve", "reject")`) limits which ones are accepted:
|
|
253
|
+
|
|
254
|
+
```python
|
|
255
|
+
from langgraph.types import Command
|
|
256
|
+
|
|
257
|
+
approve = Command(resume={"type": "approve"})
|
|
258
|
+
reject = Command(resume={"type": "reject", "message": "Refunds over 10 need a manager."})
|
|
259
|
+
# Needs allowed_decisions to include "edit". The tool name cannot change.
|
|
260
|
+
edit = Command(
|
|
261
|
+
resume={"type": "edit", "edited_action": {"name": "issue_refund", "args": {"order_id": "A-17", "amount": 10.0}}}
|
|
262
|
+
)
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
- `approve` runs the original call.
|
|
266
|
+
- `reject` denies it; the model is told a reviewer rejected it, with the message if one was given.
|
|
267
|
+
- `edit` runs the call with the reviewer's arguments after evaluating them again: if a blocking rule matches the
|
|
268
|
+
edited arguments the call is denied; if only review rules match, it runs, because a reviewer has already seen it.
|
|
269
|
+
- Any other answer (an unknown or disallowed `type`, a different tool name, arguments that are not a mapping) denies
|
|
270
|
+
the call.
|
|
271
|
+
|
|
272
|
+
When several tool calls in one model turn need review, each raises its own interrupt; resume them by ID with
|
|
273
|
+
`Command(resume={interrupt.id: decision, ...})`. Calls in the same turn that need no review run without waiting.
|
|
274
|
+
A call without a tool call ID cannot be matched to an answer, so it is denied instead of paused. If the interrupt
|
|
275
|
+
cannot be raised at all (for example when `wrap_tool_call` is called outside a LangGraph run), the call is denied.
|
|
276
|
+
|
|
277
|
+
Pass `on_review="deny"` to deny review verdicts without pausing.
|
|
278
|
+
|
|
279
|
+
### Order relative to other middleware
|
|
280
|
+
|
|
281
|
+
`create_agent` treats the first middleware in the list as the outermost wrapper of tool calls.
|
|
282
|
+
|
|
283
|
+
- Middleware listed **after** `ACGSMiddleware` runs inside it, so changes it makes to a tool call are not checked.
|
|
284
|
+
List `ACGSMiddleware` after any middleware that rewrites tool calls.
|
|
285
|
+
- When a call pauses for review, LangGraph re-runs the tool node on resume. Middleware listed **before**
|
|
286
|
+
`ACGSMiddleware` runs again up to the pause, so it must not have side effects before calling its handler.
|
|
287
|
+
`ACGSMiddleware` itself has none: it evaluates the call again (with the same result) and then applies the answer.
|
|
288
|
+
|
|
289
|
+
`HumanInTheLoopMiddleware` can be used alongside it, for example to ask about specific tools regardless of ACGS. In
|
|
290
|
+
its default `batched` mode it asks before tools run, so a person may be asked about a call that ACGS then denies.
|
|
291
|
+
|
|
292
|
+
## Custom constitutions
|
|
293
|
+
|
|
294
|
+
```python
|
|
295
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
296
|
+
|
|
297
|
+
from langchain_acgs import ACGSMiddleware
|
|
298
|
+
|
|
299
|
+
constitution = Constitution.from_rules(
|
|
300
|
+
[
|
|
301
|
+
Rule(
|
|
302
|
+
id="NO-DESTRUCTIVE-SQL",
|
|
303
|
+
text="No destructive SQL",
|
|
304
|
+
severity=Severity.CRITICAL,
|
|
305
|
+
keywords=["drop table", "truncate table"],
|
|
306
|
+
),
|
|
307
|
+
Rule(
|
|
308
|
+
id="REFUND-REVIEW",
|
|
309
|
+
text="Refunds need approval",
|
|
310
|
+
severity=Severity.HIGH,
|
|
311
|
+
keywords=["refund"],
|
|
312
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
313
|
+
),
|
|
314
|
+
],
|
|
315
|
+
name="payments",
|
|
316
|
+
)
|
|
317
|
+
middleware = ACGSMiddleware(constitution=constitution, agent_id="payments-agent", allowed_decisions=["approve", "edit", "reject"])
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
`Constitution.from_yaml("rules.yaml")` works as well. To add several `ACGSMiddleware` instances to one agent, give
|
|
321
|
+
each a distinct `name`.
|
|
322
|
+
|
|
323
|
+
## Options
|
|
324
|
+
|
|
325
|
+
| Argument | Default | Meaning |
|
|
326
|
+
|---|---|---|
|
|
327
|
+
| `constitution` | `Constitution.default()` | Rules to enforce |
|
|
328
|
+
| `agent_id` | `"langchain-agent"` | Agent identifier recorded by ACGS |
|
|
329
|
+
| `on_review` | `"interrupt"` | `"interrupt"` pauses for a person; `"deny"` denies review verdicts |
|
|
330
|
+
| `allowed_decisions` | `("approve", "reject")` | Accepted review answers: any of `"approve"`, `"edit"`, `"reject"` |
|
|
331
|
+
| `tool_call_formatter` | `format_tool_call` | `(tool_name, args) -> str` used as the evaluated text |
|
|
332
|
+
| `name` | `"ACGSMiddleware"` | Middleware name; must be unique per agent |
|
|
333
|
+
|
|
334
|
+
## Limitations
|
|
335
|
+
|
|
336
|
+
- Only tool calls are checked. Model input and output, and tool results, are not.
|
|
337
|
+
- `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
|
|
338
|
+
and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
|
|
339
|
+
patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
|
|
340
|
+
tools you expose. `tests/unit_tests/test_default_constitution.py` lists what the default rules do and do not catch.
|
|
341
|
+
- Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
|
|
342
|
+
("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
|
|
343
|
+
(`api-key` does not match the keyword `api_key`).
|
|
344
|
+
- Because argument names are part of the evaluated text, a tool with a parameter named `password` is denied under
|
|
345
|
+
the default constitution whenever it is called.
|
|
346
|
+
|
|
347
|
+
## Development
|
|
348
|
+
|
|
349
|
+
```bash
|
|
350
|
+
uv sync --all-groups
|
|
351
|
+
make format # ruff format + ruff check --fix
|
|
352
|
+
make lint # import checks, ruff, mypy --strict
|
|
353
|
+
make test # pytest with a 100% branch-coverage gate, network disabled
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
## License
|
|
357
|
+
|
|
358
|
+
Apache-2.0. See [LICENSE](LICENSE).
|