actiongate-langchain 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.
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ dist/
3
+ *.egg-info/
4
+ .DS_Store
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 ActionGate OSS
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: actiongate-langchain
3
+ Version: 0.1.0
4
+ Summary: Gate LangChain tool execution through ActionGate primitives.
5
+ Project-URL: Homepage, https://github.com/actiongate-oss/actiongate-langchain
6
+ Project-URL: Documentation, https://github.com/actiongate-oss/actiongate-langchain#readme
7
+ Project-URL: Repository, https://github.com/actiongate-oss/actiongate-langchain
8
+ Author-email: ActionGate OSS <actiongate-oss@users.noreply.github.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: actiongate,ai-agents,guardrails,langchain,tool-use
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: actiongate>=0.2.0
21
+ Requires-Dist: langchain-core>=0.2.0
22
+ Provides-Extra: all
23
+ Requires-Dist: auditgate>=0.1.0; extra == 'all'
24
+ Requires-Dist: budgetgate>=0.2.0; extra == 'all'
25
+ Requires-Dist: rulegate>=0.2.0; extra == 'all'
26
+ Provides-Extra: audit
27
+ Requires-Dist: auditgate>=0.1.0; extra == 'audit'
28
+ Provides-Extra: budget
29
+ Requires-Dist: budgetgate>=0.2.0; extra == 'budget'
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=8.0; extra == 'dev'
32
+ Provides-Extra: rules
33
+ Requires-Dist: rulegate>=0.2.0; extra == 'rules'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # actiongate-langchain
37
+
38
+ Gate LangChain tool execution through [ActionGate](https://github.com/actiongate-oss/actiongate) primitives.
39
+
40
+ ```
41
+ pip install actiongate-langchain
42
+ ```
43
+
44
+ ## Quick start
45
+
46
+ ```python
47
+ from actiongate import Engine, Gate, Policy
48
+ from actiongate_langchain import gated_tool
49
+
50
+ ag = Engine()
51
+
52
+ @gated_tool(
53
+ actiongate=ag,
54
+ gate=Gate("tools", "search", "agent:1"),
55
+ policy=Policy(max_calls=10, window=60),
56
+ )
57
+ def search_web(query: str) -> str:
58
+ """Search the web for a query."""
59
+ return api.search(query)
60
+
61
+ # Use with any LangChain agent
62
+ agent = create_react_agent(llm, [search_web], prompt)
63
+ ```
64
+
65
+ The tool checks all gates before execution. If any gate blocks, it raises `ToolException` with the block reason — LangChain agents handle this automatically.
66
+
67
+ ## Add more gates
68
+
69
+ ```
70
+ pip install actiongate-langchain[all]
71
+ ```
72
+
73
+ ```python
74
+ from actiongate import Engine as AG, Gate, Policy
75
+ from budgetgate import Engine as BG, Ledger, Budget
76
+ from rulegate import Engine as RG, Rule, Ruleset, Context
77
+ from actiongate_langchain import gated_tool
78
+ from decimal import Decimal
79
+
80
+ def no_pii(ctx: Context) -> bool:
81
+ return "ssn" not in str(ctx.kwargs).lower()
82
+
83
+ ag, bg, rg = AG(), BG(), RG()
84
+
85
+ @gated_tool(
86
+ actiongate=ag,
87
+ gate=Gate("tools", "search", "agent:1"),
88
+ policy=Policy(max_calls=10, window=60),
89
+ budgetgate=bg,
90
+ ledger=Ledger("openai", "search", "agent:1"),
91
+ budget=Budget(max_spend=Decimal("5.00"), window=3600),
92
+ cost=Decimal("0.01"),
93
+ rulegate=rg,
94
+ rule=Rule("tools", "search"),
95
+ ruleset=Ruleset(predicates=(no_pii,)),
96
+ )
97
+ def search_web(query: str) -> str:
98
+ """Search the web for a query."""
99
+ return api.search(query)
100
+ ```
101
+
102
+ Gates evaluate in order: ActionGate → BudgetGate → RuleGate → execute → AuditGate.
103
+
104
+ ## GatedTool class
105
+
106
+ For more control, use `GatedTool.from_function()` directly:
107
+
108
+ ```python
109
+ from actiongate_langchain import GatedTool
110
+
111
+ tool = GatedTool.from_function(
112
+ func=search_fn,
113
+ name="search_web",
114
+ description="Search the web",
115
+ actiongate=ag,
116
+ gate=Gate("tools", "search", "agent:1"),
117
+ policy=Policy(max_calls=10, window=60),
118
+ )
119
+ ```
120
+
121
+ ## License
122
+
123
+ Apache-2.0. ActionGate and BudgetGate are Apache-2.0. RuleGate and AuditGate are BSL-1.1.
@@ -0,0 +1,88 @@
1
+ # actiongate-langchain
2
+
3
+ Gate LangChain tool execution through [ActionGate](https://github.com/actiongate-oss/actiongate) primitives.
4
+
5
+ ```
6
+ pip install actiongate-langchain
7
+ ```
8
+
9
+ ## Quick start
10
+
11
+ ```python
12
+ from actiongate import Engine, Gate, Policy
13
+ from actiongate_langchain import gated_tool
14
+
15
+ ag = Engine()
16
+
17
+ @gated_tool(
18
+ actiongate=ag,
19
+ gate=Gate("tools", "search", "agent:1"),
20
+ policy=Policy(max_calls=10, window=60),
21
+ )
22
+ def search_web(query: str) -> str:
23
+ """Search the web for a query."""
24
+ return api.search(query)
25
+
26
+ # Use with any LangChain agent
27
+ agent = create_react_agent(llm, [search_web], prompt)
28
+ ```
29
+
30
+ The tool checks all gates before execution. If any gate blocks, it raises `ToolException` with the block reason — LangChain agents handle this automatically.
31
+
32
+ ## Add more gates
33
+
34
+ ```
35
+ pip install actiongate-langchain[all]
36
+ ```
37
+
38
+ ```python
39
+ from actiongate import Engine as AG, Gate, Policy
40
+ from budgetgate import Engine as BG, Ledger, Budget
41
+ from rulegate import Engine as RG, Rule, Ruleset, Context
42
+ from actiongate_langchain import gated_tool
43
+ from decimal import Decimal
44
+
45
+ def no_pii(ctx: Context) -> bool:
46
+ return "ssn" not in str(ctx.kwargs).lower()
47
+
48
+ ag, bg, rg = AG(), BG(), RG()
49
+
50
+ @gated_tool(
51
+ actiongate=ag,
52
+ gate=Gate("tools", "search", "agent:1"),
53
+ policy=Policy(max_calls=10, window=60),
54
+ budgetgate=bg,
55
+ ledger=Ledger("openai", "search", "agent:1"),
56
+ budget=Budget(max_spend=Decimal("5.00"), window=3600),
57
+ cost=Decimal("0.01"),
58
+ rulegate=rg,
59
+ rule=Rule("tools", "search"),
60
+ ruleset=Ruleset(predicates=(no_pii,)),
61
+ )
62
+ def search_web(query: str) -> str:
63
+ """Search the web for a query."""
64
+ return api.search(query)
65
+ ```
66
+
67
+ Gates evaluate in order: ActionGate → BudgetGate → RuleGate → execute → AuditGate.
68
+
69
+ ## GatedTool class
70
+
71
+ For more control, use `GatedTool.from_function()` directly:
72
+
73
+ ```python
74
+ from actiongate_langchain import GatedTool
75
+
76
+ tool = GatedTool.from_function(
77
+ func=search_fn,
78
+ name="search_web",
79
+ description="Search the web",
80
+ actiongate=ag,
81
+ gate=Gate("tools", "search", "agent:1"),
82
+ policy=Policy(max_calls=10, window=60),
83
+ )
84
+ ```
85
+
86
+ ## License
87
+
88
+ Apache-2.0. ActionGate and BudgetGate are Apache-2.0. RuleGate and AuditGate are BSL-1.1.
@@ -0,0 +1,6 @@
1
+ """ActionGate LangChain Integration — gate tool execution with ActionGate primitives."""
2
+
3
+ from .actiongate_langchain import GatedTool, gated_tool
4
+
5
+ __all__ = ["GatedTool", "gated_tool"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,229 @@
1
+ """ActionGate LangChain Integration — gate tool execution with ActionGate primitives.
2
+
3
+ Two integration patterns:
4
+
5
+ 1. @gated_tool decorator (simplest):
6
+
7
+ from actiongate_langchain import gated_tool
8
+ from actiongate import Engine, Gate, Policy
9
+
10
+ ag = Engine()
11
+
12
+ @gated_tool(
13
+ actiongate=ag,
14
+ gate=Gate("tools", "search", "agent:1"),
15
+ policy=Policy(max_calls=10, window=60),
16
+ )
17
+ def search_web(query: str) -> str:
18
+ '''Search the web for a query.'''
19
+ return api.search(query)
20
+
21
+ # Use directly with LangChain agents
22
+ agent = create_react_agent(llm, [search_web], prompt)
23
+
24
+ 2. GatedTool class (full control):
25
+
26
+ from actiongate_langchain import GatedTool
27
+
28
+ tool = GatedTool.from_function(
29
+ func=search_fn,
30
+ name="search_web",
31
+ description="Search the web",
32
+ actiongate=ag,
33
+ gate=Gate("tools", "search", "agent:1"),
34
+ policy=Policy(max_calls=10, window=60),
35
+ )
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import json
41
+ from decimal import Decimal
42
+ from functools import wraps
43
+ from typing import Any, Callable, Optional, Type, TYPE_CHECKING
44
+
45
+ from langchain_core.tools import BaseTool, ToolException
46
+ from pydantic import BaseModel, ConfigDict, PrivateAttr
47
+
48
+ if TYPE_CHECKING:
49
+ from actiongate import Engine as ActionEngine, Gate, Policy
50
+ from budgetgate import Engine as BudgetEngine, Ledger, Budget
51
+ from rulegate import Engine as RuleEngine, Rule, Ruleset
52
+ from auditgate import Engine as AuditEngine, Trail, AuditPolicy
53
+
54
+
55
+ class GatedTool(BaseTool):
56
+ """A LangChain tool that runs through ActionGate primitives before execution.
57
+
58
+ Gates evaluate in order: ActionGate → BudgetGate → RuleGate → execute → AuditGate.
59
+ First block raises ToolException with the gate's block message.
60
+ """
61
+
62
+ model_config = ConfigDict(arbitrary_types_allowed=True)
63
+
64
+ # Tool metadata
65
+ name: str = ""
66
+ description: str = ""
67
+ args_schema: Optional[Type[BaseModel]] = None
68
+
69
+ # Private attributes — not Pydantic model fields
70
+ _fn: Callable[..., Any] = PrivateAttr(default=None)
71
+ _ag: Optional[Any] = PrivateAttr(default=None)
72
+ _bg: Optional[Any] = PrivateAttr(default=None)
73
+ _rg: Optional[Any] = PrivateAttr(default=None)
74
+ _audit: Optional[Any] = PrivateAttr(default=None)
75
+ _gate: Optional[Any] = PrivateAttr(default=None)
76
+ _policy: Optional[Any] = PrivateAttr(default=None)
77
+ _ledger: Optional[Any] = PrivateAttr(default=None)
78
+ _budget: Optional[Any] = PrivateAttr(default=None)
79
+ _cost: Optional[Decimal] = PrivateAttr(default=None)
80
+ _rule: Optional[Any] = PrivateAttr(default=None)
81
+ _ruleset: Optional[Any] = PrivateAttr(default=None)
82
+ _trail: Optional[Any] = PrivateAttr(default=None)
83
+ _audit_policy: Optional[Any] = PrivateAttr(default=None)
84
+
85
+ def _run(self, **kwargs: Any) -> Any:
86
+ """Run the tool through the gate pipeline."""
87
+ decisions: dict[str, Any] = {}
88
+
89
+ # ActionGate: rate limiting
90
+ if self._ag and self._gate:
91
+ decision = self._ag.check(self._gate, self._policy)
92
+ decisions["actiongate"] = decision.to_dict()
93
+ if decision.blocked:
94
+ self._audit_log("BLOCK", "actiongate", decisions)
95
+ raise ToolException(f"[actiongate] {decision.message}")
96
+
97
+ # BudgetGate: spend control
98
+ if self._bg and self._ledger and self._cost is not None:
99
+ decision = self._bg.check(self._ledger, self._cost, self._budget)
100
+ decisions["budgetgate"] = decision.to_dict()
101
+ if decision.blocked:
102
+ self._audit_log("BLOCK", "budgetgate", decisions)
103
+ raise ToolException(f"[budgetgate] {decision.message}")
104
+
105
+ # RuleGate: policy enforcement
106
+ if self._rg and self._rule and self._ruleset:
107
+ decision = self._rg.check(self._rule, self._ruleset, kwargs=kwargs)
108
+ decisions["rulegate"] = decision.to_dict()
109
+ if decision.blocked:
110
+ self._audit_log("BLOCK", "rulegate", decisions)
111
+ raise ToolException(f"[rulegate] {decision.message}")
112
+
113
+ # Execute
114
+ result = self._fn(**kwargs)
115
+
116
+ # AuditGate: log success
117
+ self._audit_log("ALLOW", "pipeline", decisions)
118
+
119
+ return result
120
+
121
+ def _audit_log(self, verdict_str: str, gate_type: str,
122
+ decisions: dict[str, Any]) -> None:
123
+ if self._audit is None or self._trail is None:
124
+ return
125
+ try:
126
+ from auditgate import Verdict, Severity
127
+ verdict_map = {"ALLOW": Verdict.ALLOW, "BLOCK": Verdict.BLOCK}
128
+ severity_map = {"ALLOW": Severity.INFO, "BLOCK": Severity.WARN}
129
+ self._audit.record(
130
+ self._trail,
131
+ verdict=verdict_map.get(verdict_str, Verdict.ERROR),
132
+ severity=severity_map.get(verdict_str, Severity.ERROR),
133
+ gate_type=gate_type,
134
+ gate_identity=str(self._trail),
135
+ reason=f"{verdict_str} by {gate_type}",
136
+ detail=decisions,
137
+ policy=self._audit_policy,
138
+ )
139
+ except Exception:
140
+ pass
141
+
142
+ @classmethod
143
+ def from_function(
144
+ cls,
145
+ func: Callable[..., Any],
146
+ name: str,
147
+ description: str,
148
+ *,
149
+ args_schema: Optional[Type[BaseModel]] = None,
150
+ actiongate: "ActionEngine | None" = None,
151
+ gate: "Gate | None" = None,
152
+ policy: "Policy | None" = None,
153
+ budgetgate: "BudgetEngine | None" = None,
154
+ ledger: "Ledger | None" = None,
155
+ budget: "Budget | None" = None,
156
+ cost: Decimal | None = None,
157
+ rulegate: "RuleEngine | None" = None,
158
+ rule: "Rule | None" = None,
159
+ ruleset: "Ruleset | None" = None,
160
+ auditgate: "AuditEngine | None" = None,
161
+ trail: "Trail | None" = None,
162
+ audit_policy: "AuditPolicy | None" = None,
163
+ ) -> "GatedTool":
164
+ """Create a GatedTool from a function with gate configurations."""
165
+ tool = cls(
166
+ name=name,
167
+ description=description,
168
+ args_schema=args_schema,
169
+ )
170
+ tool._fn = func
171
+ tool._ag = actiongate
172
+ tool._gate = gate
173
+ tool._policy = policy
174
+ tool._bg = budgetgate
175
+ tool._ledger = ledger
176
+ tool._budget = budget
177
+ tool._cost = cost
178
+ tool._rg = rulegate
179
+ tool._rule = rule
180
+ tool._ruleset = ruleset
181
+ tool._audit = auditgate
182
+ tool._trail = trail
183
+ tool._audit_policy = audit_policy
184
+ return tool
185
+
186
+
187
+ def gated_tool(
188
+ *,
189
+ actiongate: "ActionEngine | None" = None,
190
+ gate: "Gate | None" = None,
191
+ policy: "Policy | None" = None,
192
+ budgetgate: "BudgetEngine | None" = None,
193
+ ledger: "Ledger | None" = None,
194
+ budget: "Budget | None" = None,
195
+ cost: Decimal | None = None,
196
+ rulegate: "RuleEngine | None" = None,
197
+ rule: "Rule | None" = None,
198
+ ruleset: "Ruleset | None" = None,
199
+ auditgate: "AuditEngine | None" = None,
200
+ trail: "Trail | None" = None,
201
+ audit_policy: "AuditPolicy | None" = None,
202
+ args_schema: Optional[Type[BaseModel]] = None,
203
+ ) -> Callable[[Callable[..., Any]], GatedTool]:
204
+ """Decorator that converts a function into a gated LangChain tool.
205
+
206
+ Uses the function's name and docstring for the tool's name and description.
207
+
208
+ Example:
209
+ @gated_tool(
210
+ actiongate=ag,
211
+ gate=Gate("tools", "search", "agent:1"),
212
+ policy=Policy(max_calls=10, window=60),
213
+ )
214
+ def search_web(query: str) -> str:
215
+ '''Search the web for a query.'''
216
+ return api.search(query)
217
+ """
218
+ def decorator(fn: Callable[..., Any]) -> GatedTool:
219
+ return GatedTool.from_function(
220
+ func=fn,
221
+ name=fn.__name__,
222
+ description=fn.__doc__ or fn.__name__,
223
+ args_schema=args_schema,
224
+ actiongate=actiongate, gate=gate, policy=policy,
225
+ budgetgate=budgetgate, ledger=ledger, budget=budget, cost=cost,
226
+ rulegate=rulegate, rule=rule, ruleset=ruleset,
227
+ auditgate=auditgate, trail=trail, audit_policy=audit_policy,
228
+ )
229
+ return decorator
@@ -0,0 +1,55 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "actiongate-langchain"
7
+ version = "0.1.0"
8
+ description = "Gate LangChain tool execution through ActionGate primitives."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.12"
12
+ authors = [
13
+ { name = "ActionGate OSS", email = "actiongate-oss@users.noreply.github.com" }
14
+ ]
15
+ keywords = [
16
+ "actiongate",
17
+ "langchain",
18
+ "ai-agents",
19
+ "guardrails",
20
+ "tool-use",
21
+ ]
22
+ classifiers = [
23
+ "Development Status :: 3 - Alpha",
24
+ "Intended Audience :: Developers",
25
+ "License :: OSI Approved :: Apache Software License",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Typing :: Typed",
30
+ ]
31
+ dependencies = [
32
+ "actiongate>=0.2.0",
33
+ "langchain-core>=0.2.0",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ budget = ["budgetgate>=0.2.0"]
38
+ rules = ["rulegate>=0.2.0"]
39
+ audit = ["auditgate>=0.1.0"]
40
+ all = [
41
+ "budgetgate>=0.2.0",
42
+ "rulegate>=0.2.0",
43
+ "auditgate>=0.1.0",
44
+ ]
45
+ dev = [
46
+ "pytest>=8.0",
47
+ ]
48
+
49
+ [project.urls]
50
+ Homepage = "https://github.com/actiongate-oss/actiongate-langchain"
51
+ Documentation = "https://github.com/actiongate-oss/actiongate-langchain#readme"
52
+ Repository = "https://github.com/actiongate-oss/actiongate-langchain"
53
+
54
+ [tool.hatch.build.targets.wheel]
55
+ packages = ["actiongate_langchain"]
@@ -0,0 +1,181 @@
1
+ """Tests for actiongate-langchain integration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import traceback
7
+ from decimal import Decimal
8
+
9
+ sys.path.insert(0, ".")
10
+
11
+ passed = 0
12
+ failed = 0
13
+ errors: list[str] = []
14
+
15
+ def test(name):
16
+ def decorator(fn):
17
+ global passed, failed
18
+ try:
19
+ fn()
20
+ passed += 1
21
+ print(f" PASS {name}")
22
+ except Exception as e:
23
+ failed += 1
24
+ errors.append(f" FAIL {name}: {e}\n{traceback.format_exc()}")
25
+ print(f" FAIL {name}: {e}")
26
+ return fn
27
+ return decorator
28
+
29
+ _clk = 1.0
30
+ def fake_clock():
31
+ return _clk
32
+
33
+
34
+ print("── GatedTool.from_function ──")
35
+
36
+ @test("allowed call returns result")
37
+ def _():
38
+ from actiongate import Engine, Gate, Policy
39
+ from actiongate_langchain import GatedTool
40
+
41
+ ag = Engine(clock=fake_clock)
42
+ tool = GatedTool.from_function(
43
+ func=lambda query: f"results for {query}",
44
+ name="search", description="Search the web",
45
+ actiongate=ag,
46
+ gate=Gate("test", "search"),
47
+ policy=Policy(max_calls=5, window=60),
48
+ )
49
+ result = tool.invoke({"query": "hello"})
50
+ assert result == "results for hello", f"got {result}"
51
+
52
+
53
+ @test("rate limited raises ToolException")
54
+ def _():
55
+ global _clk
56
+ _clk = 1.0
57
+ from actiongate import Engine, Gate, Policy
58
+ from langchain_core.tools import ToolException
59
+ from actiongate_langchain import GatedTool
60
+
61
+ ag = Engine(clock=fake_clock)
62
+ tool = GatedTool.from_function(
63
+ func=lambda: "pong",
64
+ name="ping", description="Ping",
65
+ actiongate=ag,
66
+ gate=Gate("test", "ping"),
67
+ policy=Policy(max_calls=1, window=60),
68
+ )
69
+ tool.handle_tool_error = True
70
+ tool.invoke({})
71
+
72
+ _clk = 2.0
73
+ result = tool.invoke({})
74
+ assert "actiongate" in str(result).lower(), f"expected actiongate block, got {result}"
75
+
76
+
77
+ @test("budget exceeded raises ToolException")
78
+ def _():
79
+ global _clk
80
+ _clk = 1.0
81
+ from actiongate import Engine as AG, Gate, Policy
82
+ from budgetgate import Engine as BG, Ledger, Budget
83
+ from actiongate_langchain import GatedTool
84
+
85
+ ag = AG(clock=fake_clock)
86
+ bg = BG(clock=fake_clock)
87
+ tool = GatedTool.from_function(
88
+ func=lambda: "done",
89
+ name="expensive", description="Costly op",
90
+ actiongate=ag,
91
+ gate=Gate("test", "exp"),
92
+ policy=Policy(max_calls=100, window=60),
93
+ budgetgate=bg,
94
+ ledger=Ledger("test", "api", "user:1"),
95
+ budget=Budget(max_spend=Decimal("1.00"), window=60),
96
+ cost=Decimal("0.60"),
97
+ )
98
+ tool.handle_tool_error = True
99
+ tool.invoke({})
100
+
101
+ _clk = 2.0
102
+ result = tool.invoke({})
103
+ assert "budgetgate" in str(result).lower(), f"expected budget block, got {result}"
104
+
105
+
106
+ @test("policy violation raises ToolException")
107
+ def _():
108
+ global _clk
109
+ _clk = 1.0
110
+ from actiongate import Engine as AG, Gate, Policy
111
+ from rulegate import Engine as RG, Rule, Ruleset, Context
112
+ from actiongate_langchain import GatedTool
113
+
114
+ def no_bad(ctx: Context) -> bool:
115
+ return "bad" not in str(ctx.kwargs).lower()
116
+
117
+ ag = AG(clock=fake_clock)
118
+ rg = RG(clock=fake_clock)
119
+ tool = GatedTool.from_function(
120
+ func=lambda query: f"results for {query}",
121
+ name="search", description="Search",
122
+ actiongate=ag,
123
+ gate=Gate("test", "search2"),
124
+ policy=Policy(max_calls=100, window=60),
125
+ rulegate=rg,
126
+ rule=Rule("test", "search"),
127
+ ruleset=Ruleset(predicates=(no_bad,)),
128
+ )
129
+ tool.handle_tool_error = True
130
+
131
+ result = tool.invoke({"query": "bad stuff"})
132
+ assert "rulegate" in str(result).lower(), f"expected rule block, got {result}"
133
+
134
+
135
+ print("\n── @gated_tool decorator ──")
136
+
137
+ @test("decorator creates working tool")
138
+ def _():
139
+ global _clk
140
+ _clk = 1.0
141
+ from actiongate import Engine, Gate, Policy
142
+ from actiongate_langchain import gated_tool
143
+
144
+ ag = Engine(clock=fake_clock)
145
+
146
+ @gated_tool(
147
+ actiongate=ag,
148
+ gate=Gate("test", "dec"),
149
+ policy=Policy(max_calls=5, window=60),
150
+ )
151
+ def my_search(query: str) -> str:
152
+ """Search for things."""
153
+ return f"found: {query}"
154
+
155
+ assert my_search.name == "my_search"
156
+ assert my_search.description == "Search for things."
157
+ result = my_search.invoke({"query": "test"})
158
+ assert result == "found: test"
159
+
160
+
161
+ @test("decorator preserves function name and docstring")
162
+ def _():
163
+ from actiongate_langchain import gated_tool
164
+
165
+ @gated_tool()
166
+ def calculate_tax(amount: float, rate: float) -> float:
167
+ """Calculate tax on an amount."""
168
+ return amount * rate
169
+
170
+ assert calculate_tax.name == "calculate_tax"
171
+ assert calculate_tax.description == "Calculate tax on an amount."
172
+
173
+
174
+ print(f"\n{'═' * 50}")
175
+ print(f"Results: {passed} passed, {failed} failed")
176
+ if errors:
177
+ print("\nFailures:")
178
+ for e in errors:
179
+ print(e)
180
+ print(f"{'═' * 50}")
181
+ sys.exit(1 if failed else 0)