recusal-llamaindex 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,44 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .venv/
12
+ venv/
13
+ env/
14
+
15
+ # Secrets, never commit
16
+ .env
17
+ .env.*
18
+ *.key
19
+ *.pem
20
+ *.p12
21
+ *service-account*.json
22
+ secrets/
23
+
24
+ # OS / IDE
25
+ .DS_Store
26
+ Thumbs.db
27
+ .vscode/
28
+ .idea/
29
+
30
+ # Local hook activation, the repo ships .claude/settings.json.example only;
31
+ # copying it to settings.json is a deliberate per-clone step, never committed
32
+ .claude/settings.json
33
+ .claude/settings.local.json
34
+
35
+ # Local working docs, not part of the published project
36
+ linkedin.md
37
+ NOTES.md
38
+ RUNBOOK.local.md
39
+ ESSAY.local.md
40
+ SOURCES.local.md
41
+ *.local.md
42
+
43
+ # Engineering Harness local state, internal planning notes
44
+ .claude/harness/
@@ -0,0 +1,201 @@
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 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 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 Derivative
95
+ 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 those 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 do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ 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
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Philip Paz
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: recusal-llamaindex
3
+ Version: 0.1.0
4
+ Summary: Recusal gate for LlamaIndex: judge every call of a function tool before it runs, refuse it with a reason the model reads, and optionally put each decision on a hash-chained audit log.
5
+ Project-URL: Homepage, https://recusal.io
6
+ Project-URL: Documentation, https://github.com/philpaz/recusal/tree/main/adapters/llamaindex
7
+ Project-URL: Repository, https://github.com/philpaz/recusal
8
+ Project-URL: Issues, https://github.com/philpaz/recusal/issues
9
+ Project-URL: Changelog, https://github.com/philpaz/recusal/blob/main/CHANGELOG.md
10
+ Author-email: Philip Paz <philip.paz@gmail.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agent-governance,ai-agents,guardrails,llamaindex,recusal,tool-use
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Software Development :: Quality Assurance
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: dirtyjson<2,>=1.0.8
24
+ Requires-Dist: llama-index-core<0.15,>=0.14.25
25
+ Requires-Dist: pydantic<3,>=2
26
+ Requires-Dist: recusal<1,>=0.19.0
27
+ Description-Content-Type: text/markdown
28
+
29
+ <p align="center">
30
+ <a href="https://recusal.io">
31
+ <picture>
32
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip.png">
33
+ <img alt="recusal, deterministic governance for AI agents" src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip-light.png" width="880">
34
+ </picture>
35
+ </a>
36
+ </p>
37
+
38
+ # recusal-llamaindex
39
+
40
+ [![Website](https://img.shields.io/badge/website-recusal.io-2453c4)](https://recusal.io)
41
+ [![PyPI](https://img.shields.io/pypi/v/recusal-llamaindex)](https://pypi.org/project/recusal-llamaindex/)
42
+ [![CI](https://github.com/philpaz/recusal/actions/workflows/ci.yml/badge.svg)](https://github.com/philpaz/recusal/actions/workflows/ci.yml)
43
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/philpaz/recusal/badge)](https://scorecard.dev/viewer/?uri=github.com/philpaz/recusal)
44
+ ![python](https://img.shields.io/badge/python-3.11%2B-blue)
45
+ ![license](https://img.shields.io/badge/license-Apache--2.0-green)
46
+
47
+ The [Recusal](https://github.com/philpaz/recusal) gate for
48
+ [LlamaIndex](https://github.com/run-llama/llama_index) function tools: your policy judges each
49
+ call of a tool you wrap before the function runs, and a refused call never runs.
50
+
51
+ **New to Recusal?** It checks each tool call an AI agent proposes against your policy and
52
+ refuses the unsafe or unapproved ones before the tool runs. No model makes that decision.
53
+ A policy is a plain Python function: it is given the tool's name and its arguments and
54
+ returns a list of findings. An empty list lets the call run; a failing finding refuses it
55
+ and gives the reason.
56
+ [Writing a policy](https://github.com/philpaz/recusal#write-the-policy-two-postures-one-principle)
57
+ covers the two postures, allowlist and deny-list.
58
+
59
+ <p align="center">
60
+ <picture>
61
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/gate-position.svg">
62
+ <img alt="Before the tool runs. An agent proposes a tool call. Recusal, your policy with no model in it, decides. With no objection the tool runs. On a failing finding, or when the policy itself raises, the call is refused: the tool never runs and the reason goes back to the model. Every decision can be written to a hash-chained audit log, if you pass one." src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/gate-position-light.svg" width="880">
63
+ </picture>
64
+ </p>
65
+
66
+ Install it from PyPI:
67
+
68
+ ```bash
69
+ pip install recusal-llamaindex
70
+ ```
71
+
72
+ ```python
73
+ from llama_index.core.agent.workflow import FunctionAgent
74
+ from llama_index.core.tools import FunctionTool
75
+ from recusal import Finding
76
+ from recusal_llamaindex import gated_tool
77
+
78
+
79
+ def policy(tool_name, tool_input):
80
+ if tool_input.get("sql", "").upper().startswith("DELETE"):
81
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
82
+ return []
83
+
84
+
85
+ def run_sql(sql: str) -> str:
86
+ """Run one SQL statement."""
87
+ ...
88
+
89
+
90
+ tool = gated_tool(FunctionTool.from_defaults(fn=run_sql), policy)
91
+ agent = FunctionAgent(tools=[tool], llm=llm)
92
+ ```
93
+
94
+ Requires Python 3.11+. It is tested on every pull request against exactly
95
+ `llama-index-core==0.14.25`, and weekly against the newest release. The package ships inline types
96
+ (`py.typed`). A runnable example that needs no model or key is
97
+ [`examples/llamaindex_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/llamaindex_gate.py).
98
+
99
+ The gate this package is built on is the work of
100
+ [@Varma0604](https://github.com/Varma0604) (Mouli Varma Sagi), in
101
+ [#311](https://github.com/philpaz/recusal/pull/311).
102
+
103
+ **Which tools it can judge.** Each parameter needs a plain type: `str`, `int`, `float`, `bool`,
104
+ `Optional` of one, `list[T]` or `dict[str, T]`. A tool that uses `Annotated`, `Literal` or
105
+ `Field(...)`, or leaves a parameter without a type, is refused when it is called, with the reason.
106
+
107
+ ## What is gated
108
+
109
+ Only the tools you wrap, when they are called through `call` or `acall`. `FunctionAgent` and
110
+ `ReActAgent` call a tool that way. `is_gated(tools)` is true when every tool of a list is
111
+ wrapped; it cannot see a tool added later.
112
+
113
+ **Not gated:**
114
+
115
+ - a tool you did not wrap, and a tool the model provider runs on its own servers;
116
+ - `CodeActAgent`, which runs the code the model writes with the functions your executor has;
117
+ - `real_fn`, which returns the function because LlamaIndex reads its signature there. Calling it
118
+ is not gated.
119
+
120
+ A gated tool does not hand out its function otherwise: `fn`, `async_fn`, `to_langchain_tool` and
121
+ `to_langchain_structured_tool` raise a `TypeError`, and so does building an `OnDemandLoaderTool`
122
+ from it. `LoadAndSearchToolSpec` is not supported: a refused load runs nothing, and LlamaIndex
123
+ still tells the model that content was loaded.
124
+
125
+ ## What the policy judges
126
+
127
+ The values the function is called with: defaults and `partial_params` filled in, and each value
128
+ converted to the type the function declares. A value that does not validate is refused, naming
129
+ the parameter only: `null` for `top_k: int = 5`, for example. A value in the call replaces the same name in `partial_params`, as in
130
+ LlamaIndex. The host's workflow `Context` is never shown to the policy, and the same parameter
131
+ given as plain data, which a model could have written, is refused.
132
+
133
+ Whether a tool can be judged is the Recusal kernel's one reading of it, which the other adapters
134
+ use too. Each judged parameter is annotated `str`, `int`, `float`, `bool`, `Optional` of one,
135
+ `list[T]` or `dict[str, T]`. Any other tool is refused when it is called, with the reason:
136
+ `Annotated`, `Literal`, a `Field(...)` default, a parameter with no annotation,
137
+ `functools.partial`, and an annotation that does not resolve at run time among them.
138
+
139
+ What a decorator's own code does after the policy is the tool's code, which no gate reads:
140
+ `pydantic.validate_call` with a `config` that strips or lowercases text changes the value after
141
+ judgment, and a wrapper that calls the function without `functools.wraps` can pass it other values.
142
+ `validate_call` also rejects the `None` of a parameter declared `str = None`.
143
+
144
+ ## With an audit log
145
+
146
+ ```python
147
+ from recusal import AuditLog
148
+ from recusal_llamaindex import audited_tool
149
+
150
+ log = AuditLog("audit.jsonl")
151
+ tool = audited_tool(FunctionTool.from_defaults(fn=run_sql), policy, log)
152
+ ```
153
+
154
+ Each call of the tool, allowed or refused, is on a hash-chained log with a fingerprint of its
155
+ arguments, never the arguments. The reason of a refusal can show a few names of arguments the
156
+ tool does not take. If the log cannot be written, the call is refused. An entry has
157
+ no call ID, because LlamaIndex does not pass one to the tool. A tool that waits for an event
158
+ (`ctx.wait_for_event`) is run again by LlamaIndex, so it is judged, and recorded, each time. A call to a tool you did not wrap,
159
+ or to one the agent does not have, is not on the log.
160
+
161
+ **Beyond the gate.** This gate judges the tool calls the framework routes through it;
162
+ the paths around it inside the framework are listed above. Like every Recusal gate, it
163
+ does not stop an agent that can reach a resource another way: a credential with wider
164
+ rights, a shell or network path outside the agent, or a file it can write that
165
+ configures the gate. Use it as one layer of several: least-privilege credentials for the
166
+ agent, a sandbox or container, limits on its network egress, and an audit anchor the
167
+ writer cannot reach ([the limits in
168
+ full](https://github.com/philpaz/recusal/blob/main/SECURITY.md#things-worth-knowing)).
169
+
170
+ ## Status
171
+
172
+ **In-depth review under way.** Its first release is 0.1.0, and the review continues. Recusal is a Beta (`0.x`) open-source project in active
173
+ development: it is not a finished or certified security product, and it is provided under
174
+ Apache-2.0 without warranty.
175
+ [What the reviews are, and where every adapter stands](https://github.com/philpaz/recusal#project-status).
176
+
177
+ **Help make it better.** Read the code, test this adapter against your own stack and tell
178
+ us what you find. Reviews, bug reports and pull requests are all welcome:
179
+ [how to contribute](https://github.com/philpaz/recusal/blob/main/CONTRIBUTING.md), [open issues](https://github.com/philpaz/recusal/issues).
180
+ Please report a security gap [privately](https://github.com/philpaz/recusal/security/advisories/new), not in a public
181
+ issue.
182
+
183
+ ## More
184
+
185
+ <p align="center">
186
+ <picture>
187
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/adapter-map.svg">
188
+ <img alt="One kernel, nine adapters. Each adapter package depends on recusal: recusal-crewai, recusal-google-adk, recusal-langchain, recusal-langgraph, recusal-llamaindex, recusal-openai, recusal-openai-agents, recusal-openai-agents-mcp and recusal-pydantic-ai. recusal-langchain also depends on recusal-langgraph, and recusal-openai-agents-mcp on recusal-openai-agents. The kernel depends on nothing." src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/adapter-map-light.svg" width="880">
189
+ </picture>
190
+ </p>
191
+
192
+ An arrow means "depends on". No arrow leaves the kernel, so a framework's breaking
193
+ change is answered by a release of that framework's adapter, not by a release of the
194
+ kernel.
195
+
196
+ - [Framework notes for LlamaIndex](https://github.com/philpaz/recusal/blob/main/docs/FRAMEWORKS.md#llamaindex):
197
+ the detail behind this page.
198
+ - [All nine adapter packages](https://github.com/philpaz/recusal/tree/main/adapters) and
199
+ [the kernel](https://github.com/philpaz/recusal), which has zero runtime dependencies.
200
+ - [Verifying a release](https://github.com/philpaz/recusal/blob/main/docs/VERIFY.md#adapter-packages):
201
+ each release is built in CI, signed with Sigstore and published to PyPI by trusted
202
+ publishing.
203
+ - [Changelog](https://github.com/philpaz/recusal/blob/main/CHANGELOG.md),
204
+ [issues](https://github.com/philpaz/recusal/issues),
205
+ [security policy](https://github.com/philpaz/recusal/blob/main/SECURITY.md) and
206
+ [support](https://github.com/philpaz/recusal/blob/main/SUPPORT.md).
207
+
208
+ Licensed under Apache-2.0.
@@ -0,0 +1,180 @@
1
+ <p align="center">
2
+ <a href="https://recusal.io">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip.png">
5
+ <img alt="recusal, deterministic governance for AI agents" src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip-light.png" width="880">
6
+ </picture>
7
+ </a>
8
+ </p>
9
+
10
+ # recusal-llamaindex
11
+
12
+ [![Website](https://img.shields.io/badge/website-recusal.io-2453c4)](https://recusal.io)
13
+ [![PyPI](https://img.shields.io/pypi/v/recusal-llamaindex)](https://pypi.org/project/recusal-llamaindex/)
14
+ [![CI](https://github.com/philpaz/recusal/actions/workflows/ci.yml/badge.svg)](https://github.com/philpaz/recusal/actions/workflows/ci.yml)
15
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/philpaz/recusal/badge)](https://scorecard.dev/viewer/?uri=github.com/philpaz/recusal)
16
+ ![python](https://img.shields.io/badge/python-3.11%2B-blue)
17
+ ![license](https://img.shields.io/badge/license-Apache--2.0-green)
18
+
19
+ The [Recusal](https://github.com/philpaz/recusal) gate for
20
+ [LlamaIndex](https://github.com/run-llama/llama_index) function tools: your policy judges each
21
+ call of a tool you wrap before the function runs, and a refused call never runs.
22
+
23
+ **New to Recusal?** It checks each tool call an AI agent proposes against your policy and
24
+ refuses the unsafe or unapproved ones before the tool runs. No model makes that decision.
25
+ A policy is a plain Python function: it is given the tool's name and its arguments and
26
+ returns a list of findings. An empty list lets the call run; a failing finding refuses it
27
+ and gives the reason.
28
+ [Writing a policy](https://github.com/philpaz/recusal#write-the-policy-two-postures-one-principle)
29
+ covers the two postures, allowlist and deny-list.
30
+
31
+ <p align="center">
32
+ <picture>
33
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/gate-position.svg">
34
+ <img alt="Before the tool runs. An agent proposes a tool call. Recusal, your policy with no model in it, decides. With no objection the tool runs. On a failing finding, or when the policy itself raises, the call is refused: the tool never runs and the reason goes back to the model. Every decision can be written to a hash-chained audit log, if you pass one." src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/gate-position-light.svg" width="880">
35
+ </picture>
36
+ </p>
37
+
38
+ Install it from PyPI:
39
+
40
+ ```bash
41
+ pip install recusal-llamaindex
42
+ ```
43
+
44
+ ```python
45
+ from llama_index.core.agent.workflow import FunctionAgent
46
+ from llama_index.core.tools import FunctionTool
47
+ from recusal import Finding
48
+ from recusal_llamaindex import gated_tool
49
+
50
+
51
+ def policy(tool_name, tool_input):
52
+ if tool_input.get("sql", "").upper().startswith("DELETE"):
53
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
54
+ return []
55
+
56
+
57
+ def run_sql(sql: str) -> str:
58
+ """Run one SQL statement."""
59
+ ...
60
+
61
+
62
+ tool = gated_tool(FunctionTool.from_defaults(fn=run_sql), policy)
63
+ agent = FunctionAgent(tools=[tool], llm=llm)
64
+ ```
65
+
66
+ Requires Python 3.11+. It is tested on every pull request against exactly
67
+ `llama-index-core==0.14.25`, and weekly against the newest release. The package ships inline types
68
+ (`py.typed`). A runnable example that needs no model or key is
69
+ [`examples/llamaindex_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/llamaindex_gate.py).
70
+
71
+ The gate this package is built on is the work of
72
+ [@Varma0604](https://github.com/Varma0604) (Mouli Varma Sagi), in
73
+ [#311](https://github.com/philpaz/recusal/pull/311).
74
+
75
+ **Which tools it can judge.** Each parameter needs a plain type: `str`, `int`, `float`, `bool`,
76
+ `Optional` of one, `list[T]` or `dict[str, T]`. A tool that uses `Annotated`, `Literal` or
77
+ `Field(...)`, or leaves a parameter without a type, is refused when it is called, with the reason.
78
+
79
+ ## What is gated
80
+
81
+ Only the tools you wrap, when they are called through `call` or `acall`. `FunctionAgent` and
82
+ `ReActAgent` call a tool that way. `is_gated(tools)` is true when every tool of a list is
83
+ wrapped; it cannot see a tool added later.
84
+
85
+ **Not gated:**
86
+
87
+ - a tool you did not wrap, and a tool the model provider runs on its own servers;
88
+ - `CodeActAgent`, which runs the code the model writes with the functions your executor has;
89
+ - `real_fn`, which returns the function because LlamaIndex reads its signature there. Calling it
90
+ is not gated.
91
+
92
+ A gated tool does not hand out its function otherwise: `fn`, `async_fn`, `to_langchain_tool` and
93
+ `to_langchain_structured_tool` raise a `TypeError`, and so does building an `OnDemandLoaderTool`
94
+ from it. `LoadAndSearchToolSpec` is not supported: a refused load runs nothing, and LlamaIndex
95
+ still tells the model that content was loaded.
96
+
97
+ ## What the policy judges
98
+
99
+ The values the function is called with: defaults and `partial_params` filled in, and each value
100
+ converted to the type the function declares. A value that does not validate is refused, naming
101
+ the parameter only: `null` for `top_k: int = 5`, for example. A value in the call replaces the same name in `partial_params`, as in
102
+ LlamaIndex. The host's workflow `Context` is never shown to the policy, and the same parameter
103
+ given as plain data, which a model could have written, is refused.
104
+
105
+ Whether a tool can be judged is the Recusal kernel's one reading of it, which the other adapters
106
+ use too. Each judged parameter is annotated `str`, `int`, `float`, `bool`, `Optional` of one,
107
+ `list[T]` or `dict[str, T]`. Any other tool is refused when it is called, with the reason:
108
+ `Annotated`, `Literal`, a `Field(...)` default, a parameter with no annotation,
109
+ `functools.partial`, and an annotation that does not resolve at run time among them.
110
+
111
+ What a decorator's own code does after the policy is the tool's code, which no gate reads:
112
+ `pydantic.validate_call` with a `config` that strips or lowercases text changes the value after
113
+ judgment, and a wrapper that calls the function without `functools.wraps` can pass it other values.
114
+ `validate_call` also rejects the `None` of a parameter declared `str = None`.
115
+
116
+ ## With an audit log
117
+
118
+ ```python
119
+ from recusal import AuditLog
120
+ from recusal_llamaindex import audited_tool
121
+
122
+ log = AuditLog("audit.jsonl")
123
+ tool = audited_tool(FunctionTool.from_defaults(fn=run_sql), policy, log)
124
+ ```
125
+
126
+ Each call of the tool, allowed or refused, is on a hash-chained log with a fingerprint of its
127
+ arguments, never the arguments. The reason of a refusal can show a few names of arguments the
128
+ tool does not take. If the log cannot be written, the call is refused. An entry has
129
+ no call ID, because LlamaIndex does not pass one to the tool. A tool that waits for an event
130
+ (`ctx.wait_for_event`) is run again by LlamaIndex, so it is judged, and recorded, each time. A call to a tool you did not wrap,
131
+ or to one the agent does not have, is not on the log.
132
+
133
+ **Beyond the gate.** This gate judges the tool calls the framework routes through it;
134
+ the paths around it inside the framework are listed above. Like every Recusal gate, it
135
+ does not stop an agent that can reach a resource another way: a credential with wider
136
+ rights, a shell or network path outside the agent, or a file it can write that
137
+ configures the gate. Use it as one layer of several: least-privilege credentials for the
138
+ agent, a sandbox or container, limits on its network egress, and an audit anchor the
139
+ writer cannot reach ([the limits in
140
+ full](https://github.com/philpaz/recusal/blob/main/SECURITY.md#things-worth-knowing)).
141
+
142
+ ## Status
143
+
144
+ **In-depth review under way.** Its first release is 0.1.0, and the review continues. Recusal is a Beta (`0.x`) open-source project in active
145
+ development: it is not a finished or certified security product, and it is provided under
146
+ Apache-2.0 without warranty.
147
+ [What the reviews are, and where every adapter stands](https://github.com/philpaz/recusal#project-status).
148
+
149
+ **Help make it better.** Read the code, test this adapter against your own stack and tell
150
+ us what you find. Reviews, bug reports and pull requests are all welcome:
151
+ [how to contribute](https://github.com/philpaz/recusal/blob/main/CONTRIBUTING.md), [open issues](https://github.com/philpaz/recusal/issues).
152
+ Please report a security gap [privately](https://github.com/philpaz/recusal/security/advisories/new), not in a public
153
+ issue.
154
+
155
+ ## More
156
+
157
+ <p align="center">
158
+ <picture>
159
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/adapter-map.svg">
160
+ <img alt="One kernel, nine adapters. Each adapter package depends on recusal: recusal-crewai, recusal-google-adk, recusal-langchain, recusal-langgraph, recusal-llamaindex, recusal-openai, recusal-openai-agents, recusal-openai-agents-mcp and recusal-pydantic-ai. recusal-langchain also depends on recusal-langgraph, and recusal-openai-agents-mcp on recusal-openai-agents. The kernel depends on nothing." src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/adapter-map-light.svg" width="880">
161
+ </picture>
162
+ </p>
163
+
164
+ An arrow means "depends on". No arrow leaves the kernel, so a framework's breaking
165
+ change is answered by a release of that framework's adapter, not by a release of the
166
+ kernel.
167
+
168
+ - [Framework notes for LlamaIndex](https://github.com/philpaz/recusal/blob/main/docs/FRAMEWORKS.md#llamaindex):
169
+ the detail behind this page.
170
+ - [All nine adapter packages](https://github.com/philpaz/recusal/tree/main/adapters) and
171
+ [the kernel](https://github.com/philpaz/recusal), which has zero runtime dependencies.
172
+ - [Verifying a release](https://github.com/philpaz/recusal/blob/main/docs/VERIFY.md#adapter-packages):
173
+ each release is built in CI, signed with Sigstore and published to PyPI by trusted
174
+ publishing.
175
+ - [Changelog](https://github.com/philpaz/recusal/blob/main/CHANGELOG.md),
176
+ [issues](https://github.com/philpaz/recusal/issues),
177
+ [security policy](https://github.com/philpaz/recusal/blob/main/SECURITY.md) and
178
+ [support](https://github.com/philpaz/recusal/blob/main/SUPPORT.md).
179
+
180
+ Licensed under Apache-2.0.
@@ -0,0 +1,60 @@
1
+ # The Recusal adapter for LlamaIndex, a separate distribution from `recusal`.
2
+ #
3
+ # Why separate: `recusal` has zero runtime dependencies and a frozen compatibility
4
+ # perimeter (STABILITY.md). An adapter follows a framework that releases on its own
5
+ # schedule, so it carries that dependency and its own version here, and a framework's
6
+ # breaking change never forces a release of the kernel.
7
+ #
8
+ # Build backend pinned exactly, the same pin as the kernel's pyproject.toml: a floating
9
+ # backend is unreviewed code in the release path.
10
+ [build-system]
11
+ requires = ["hatchling==1.27.0"]
12
+ build-backend = "hatchling.build"
13
+
14
+ [project]
15
+ name = "recusal-llamaindex"
16
+ dynamic = ["version"]
17
+ description = "Recusal gate for LlamaIndex: judge every call of a function tool before it runs, refuse it with a reason the model reads, and optionally put each decision on a hash-chained audit log."
18
+ readme = "README.md"
19
+ # LlamaIndex core itself runs on older Pythons; the gate is tested from 3.11.
20
+ requires-python = ">=3.11"
21
+ license = "Apache-2.0"
22
+ license-files = ["LICENSE"]
23
+ authors = [{ name = "Philip Paz", email = "philip.paz@gmail.com" }]
24
+ keywords = ["recusal", "llamaindex", "ai-agents", "agent-governance", "guardrails", "tool-use"]
25
+ classifiers = [
26
+ "Development Status :: 4 - Beta",
27
+ "Intended Audience :: Developers",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3 :: Only",
31
+ "Topic :: Security",
32
+ "Topic :: Software Development :: Quality Assurance",
33
+ "Typing :: Typed",
34
+ ]
35
+ dependencies = [
36
+ # 0.19.0 is the first release whose audit log ends in a deny when a sink fails after an
37
+ # allow was written. Beside an older kernel that refused call stays on the log as allowed.
38
+ "recusal>=0.19.0,<1",
39
+ # The lower bound is the version the pinned CI lane tests; the weekly latest lane
40
+ # (.github/workflows/compat.yml) tests the newest release. The upper bound is the next
41
+ # minor: LlamaIndex is before 1.0, and the gate builds on FunctionTool's own attributes.
42
+ "llama-index-core>=0.14.25,<0.15",
43
+ # imported directly (the containers LlamaIndex's ReAct parser makes)
44
+ "dirtyjson>=1.0.8,<2",
45
+ # imported directly (values are converted to the types a function declares)
46
+ "pydantic>=2,<3",
47
+ ]
48
+
49
+ [project.urls]
50
+ Homepage = "https://recusal.io"
51
+ Documentation = "https://github.com/philpaz/recusal/tree/main/adapters/llamaindex"
52
+ Repository = "https://github.com/philpaz/recusal"
53
+ Issues = "https://github.com/philpaz/recusal/issues"
54
+ Changelog = "https://github.com/philpaz/recusal/blob/main/CHANGELOG.md"
55
+
56
+ [tool.hatch.version]
57
+ path = "src/recusal_llamaindex/__init__.py"
58
+
59
+ [tool.hatch.build.targets.wheel]
60
+ packages = ["src/recusal_llamaindex"]
@@ -0,0 +1,114 @@
1
+ """Prove the INSTALLED recusal-llamaindex wheel gates a real LlamaIndex agent.
2
+
3
+ Run it from a directory outside the repository, with an interpreter that has the built
4
+ wheels installed:
5
+
6
+ python /path/to/adapters/llamaindex/smoke_test.py
7
+
8
+ It fails if the package it imports is the source tree and not an installed distribution:
9
+ a check run from the checkout would prove nothing about the wheel. A scripted model
10
+ proposes the calls; no provider, API key or network is used.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import os
17
+ import sys
18
+ import tempfile
19
+ from importlib import metadata
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ # Python puts this script's directory first on the import path. Drop it, so nothing in
24
+ # the source tree can stand in for the installed package.
25
+ _HERE = Path(__file__).resolve().parent
26
+ sys.path[:] = [entry for entry in sys.path if Path(entry or ".").resolve() != _HERE]
27
+
28
+ import recusal_llamaindex # noqa: E402
29
+ from llama_index.core.agent.workflow import FunctionAgent, ToolCallResult # noqa: E402
30
+ from llama_index.core.base.llms.types import ChatMessage, ToolCallBlock # noqa: E402
31
+ from llama_index.core.llms.mock import MockFunctionCallingLLM # noqa: E402
32
+ from llama_index.core.tools import FunctionTool # noqa: E402
33
+ from recusal_llamaindex import SURFACE, audited_tool, gated_tool # noqa: E402
34
+
35
+ import recusal # noqa: E402
36
+ from recusal import Finding # noqa: E402
37
+ from recusal.audit import AuditLog, verify # noqa: E402
38
+
39
+ EXECUTED: list[str] = []
40
+ CALLS = [("c1", "SELECT 1"), ("c2", "DELETE FROM t")]
41
+
42
+
43
+ def run_sql(sql: str) -> str:
44
+ """Record SQL text without connecting to a database."""
45
+ EXECUTED.append(sql)
46
+ return f"recorded: {sql}"
47
+
48
+
49
+ def policy(tool_name, tool_input):
50
+ if str(tool_input.get("sql", "")).upper().startswith("DELETE"):
51
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
52
+ return []
53
+
54
+
55
+ def respond(messages: Any, **_: Any) -> ChatMessage:
56
+ """Propose the scripted calls on the first turn, then answer "done"."""
57
+ if any(message.role == "tool" for message in messages):
58
+ return ChatMessage(role="assistant", content="done")
59
+ blocks = [
60
+ ToolCallBlock(tool_call_id=ident, tool_name="run_sql", tool_kwargs={"sql": sql})
61
+ for ident, sql in CALLS
62
+ ]
63
+ return ChatMessage(role="assistant", blocks=blocks)
64
+
65
+
66
+ async def run(tool: FunctionTool) -> dict[str, str]:
67
+ """Run one agent with the tool; return what the model received for each call, by id."""
68
+ EXECUTED.clear()
69
+ model = MockFunctionCallingLLM(response_generator=respond)
70
+ handler = FunctionAgent(tools=[tool], llm=model, streaming=False).run("go")
71
+ answers = {}
72
+ async for event in handler.stream_events():
73
+ if isinstance(event, ToolCallResult):
74
+ answers[event.tool_id] = str(event.tool_output.content)
75
+ await handler
76
+ return answers
77
+
78
+
79
+ def main() -> None:
80
+ for module in (recusal, recusal_llamaindex):
81
+ origin = Path(str(module.__file__)).resolve()
82
+ assert "site-packages" in origin.parts, f"{module.__name__} is not installed: {origin}"
83
+ assert metadata.version("recusal-llamaindex") == recusal_llamaindex.__version__
84
+ requires = metadata.requires("recusal-llamaindex") or []
85
+ assert any(r.startswith("recusal") for r in requires), requires
86
+
87
+ tool = FunctionTool.from_defaults(fn=run_sql)
88
+ # Negative control: ungated, the DELETE runs, so the refusals below are the gate's.
89
+ asyncio.run(run(tool))
90
+ assert sorted(EXECUTED) == ["DELETE FROM t", "SELECT 1"], EXECUTED
91
+
92
+ answers = asyncio.run(run(gated_tool(tool, policy)))
93
+ assert EXECUTED == ["SELECT 1"], EXECUTED
94
+ assert "recorded: SELECT 1" in answers["c1"], answers
95
+ assert "DELETE is not allowed" in answers["c2"], answers
96
+
97
+ with tempfile.TemporaryDirectory() as folder:
98
+ log = AuditLog(path=os.path.join(folder, "audit.jsonl"))
99
+ asyncio.run(run(audited_tool(tool, policy, log)))
100
+ assert EXECUTED == ["SELECT 1"], EXECUTED
101
+ decisions = sorted(entry["action"]["decision"] for entry in log.entries)
102
+ assert len(decisions) == 2 and decisions.count("deny") == 1, decisions
103
+ assert {entry["action"]["surface"] for entry in log.entries} == {SURFACE}
104
+ intact, problems = verify(log.entries)
105
+ assert intact, problems
106
+
107
+ print(
108
+ f"recusal-llamaindex {recusal_llamaindex.__version__} with recusal "
109
+ f"{recusal.__version__}: installed wheel gates and records"
110
+ )
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
@@ -0,0 +1,28 @@
1
+ """Recusal for LlamaIndex: judge every call of a function tool before it runs.
2
+
3
+ from recusal_llamaindex import gated_tool
4
+
5
+ agent = FunctionAgent(tools=[gated_tool(tool, policy) for tool in tools], llm=llm)
6
+
7
+ ``policy(tool_name, tool_input)`` is an ordinary Recusal policy returning findings. A refused
8
+ call does not run, and the model reads Recusal's reason as the tool's output. Only the tools
9
+ you wrap are gated. ``audited_tool`` puts each decision on a hash-chained audit log.
10
+
11
+ The decision is made by ``recusal.decide``, and whether a tool can be judged by
12
+ ``recusal.invocation``. This package adds only what is LlamaIndex's.
13
+ """
14
+
15
+ from ._audit import SURFACE, audited_tool
16
+ from ._gate import GatedFunctionTool, Policy, gated_tool, is_gated
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ __all__ = [
21
+ "SURFACE",
22
+ "GatedFunctionTool",
23
+ "Policy",
24
+ "__version__",
25
+ "audited_tool",
26
+ "gated_tool",
27
+ "is_gated",
28
+ ]
@@ -0,0 +1,50 @@
1
+ """The audited gate: the same decision, with every call on a hash-chained ``AuditLog``.
2
+
3
+ ``audited_tool(tool, policy, log)`` is ``gated_tool`` with recording arguments, which go to
4
+ ``recusal.decide``; it writes the entry before returning. There is no second decision path.
5
+
6
+ What each entry carries:
7
+
8
+ - no call id. LlamaIndex's workflow has one and does not pass it to the tool, so the record
9
+ does not invent one. Entries are told apart by their order, the tool and the fingerprint;
10
+ - for a judged call (allowed or refused by the policy): the fingerprint of the values the
11
+ function is called with, defaults completed and values converted;
12
+ - for a call refused before judgment: the fingerprint of the arguments as proposed.
13
+
14
+ The host's ``Context`` is in neither. Arguments that cannot be fingerprinted are refused,
15
+ with an entry that says so and has no fingerprint. If the log cannot be written, the call is
16
+ refused.
17
+
18
+ What is not on the log: a call to a tool you did not wrap, and a call to a tool the agent does
19
+ not have, which LlamaIndex answers itself.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Optional
25
+
26
+ from llama_index.core.tools import FunctionTool
27
+
28
+ from recusal.audit import AuditLog
29
+
30
+ from ._gate import GatedFunctionTool, Policy
31
+
32
+ #: The surface label every entry of an audited tool carries.
33
+ SURFACE = "llamaindex.function_tool"
34
+
35
+
36
+ def audited_tool(
37
+ tool: FunctionTool,
38
+ policy: Policy,
39
+ log: AuditLog,
40
+ *,
41
+ actor: Optional[str] = None,
42
+ control: Optional[dict[str, Any]] = None,
43
+ ) -> GatedFunctionTool:
44
+ """``gated_tool`` with every decision on ``log``."""
45
+ if log is None:
46
+ raise TypeError("audited_tool needs an AuditLog")
47
+ if control is not None and type(control) is not dict:
48
+ raise TypeError("audited_tool takes `control` as a dict")
49
+ record = {"audit": log, "surface": SURFACE, "actor": actor, "control": control}
50
+ return GatedFunctionTool(tool, policy, record)
@@ -0,0 +1,320 @@
1
+ """A fail-closed gate for LlamaIndex's local ``FunctionTool`` call surfaces.
2
+
3
+ LlamaIndex invokes a FunctionTool's callback only after its local function has run, so a
4
+ callback cannot enforce a policy. ``gated_tool`` instead returns a FunctionTool subclass
5
+ whose ``call`` and ``acall`` methods prepare the arguments before delegating to the stock
6
+ implementation. Only a tool wrapped by it, or by ``audited_tool``, is covered; hosted tools and
7
+ unwrapped FunctionTools are outside this adapter's boundary.
8
+
9
+ Whether a tool can be judged, and the parameters a call of it fills, is the kernel's one
10
+ reading (``recusal.invocation.judged_parameters``), asked the way LlamaIndex calls a tool.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import inspect
16
+ import typing
17
+ from typing import Any, Callable, List, NoReturn, Optional, Sequence
18
+
19
+ from dirtyjson.attributed_containers import ( # type: ignore[import-untyped]
20
+ AttributedDict,
21
+ AttributedList,
22
+ )
23
+ from llama_index.core.tools import FunctionTool
24
+ from llama_index.core.tools.function_tool import async_to_sync, sync_to_async
25
+ from llama_index.core.tools.types import ToolOutput
26
+ from pydantic import TypeAdapter, ValidationError
27
+
28
+ from recusal import Finding, decide
29
+ from recusal.invocation import KEYWORD, detached, judged_parameters, refusal_reason
30
+
31
+ Policy = Callable[[str, dict], List[Any]]
32
+
33
+ #: How LlamaIndex calls a tool, which is what the kernel is asked with: ``FunctionTool.call``
34
+ #: and ``acall`` run ``fn(*args, **all_kwargs)``, and this gate refuses a call that has
35
+ #: positional arguments, so every value goes by keyword. The workflow ``Context`` is among
36
+ #: those keywords, under its parameter's name, so it is a name to skip and no leading
37
+ #: argument.
38
+ _CALL: dict[str, Any] = {"call_style": KEYWORD, "leading": 0, "by_name": True}
39
+
40
+ #: What a FunctionTool keeps that a call of it uses. Copied by name into a tool of the gate's
41
+ #: own, so an attribute set on the source object (a ``call`` of its own, say) is left behind.
42
+ _KEPT = (
43
+ "_real_fn",
44
+ "_fn",
45
+ "_async_fn",
46
+ "requires_context",
47
+ "ctx_param_name",
48
+ "_metadata",
49
+ "_callback",
50
+ "_async_callback",
51
+ )
52
+
53
+ #: What parsed model output is made of. An agent puts its own ``Context`` in the context
54
+ #: parameter; a value of one of these types there can be the model's.
55
+ _DATA = (dict, list, str, int, float, bool, type(None))
56
+
57
+
58
+ def _plain(value: Any) -> Any:
59
+ """``value`` with the containers of LlamaIndex's ReAct parser made plain ones.
60
+
61
+ ``ReActAgent`` reads the model's arguments with ``dirtyjson``, whose two containers are
62
+ subclasses of ``dict`` and ``list``, which the kernel does not judge. Only those two are
63
+ made plain: any other subclass is refused.
64
+ """
65
+ if type(value) in (dict, AttributedDict):
66
+ return {name: _plain(item) for name, item in dict.items(value)}
67
+ if type(value) in (list, AttributedList):
68
+ return [_plain(item) for item in list.__iter__(value)]
69
+ return value
70
+
71
+
72
+ async def _nothing() -> None:
73
+ """Only its wrapper's code object is read."""
74
+
75
+
76
+ #: The two wrappers LlamaIndex puts around a tool's function to give it the other calling
77
+ #: form, and the name under which each holds that function.
78
+ _FORMS = (
79
+ (sync_to_async(lambda: None).__code__, "fn"),
80
+ (async_to_sync(_nothing).__code__, "func_async"),
81
+ )
82
+
83
+
84
+ def _own_function(fn: Any) -> Any:
85
+ """The application's function that ``fn`` runs: ``fn``, or what LlamaIndex wrapped."""
86
+ for code, name in _FORMS:
87
+ if getattr(fn, "__code__", None) is code:
88
+ return fn.__closure__[code.co_freevars.index(name)].cell_contents
89
+ return fn
90
+
91
+
92
+ def _converted(function: Any, values: dict[str, Any], unset: set[str]) -> dict[str, Any]:
93
+ """``values`` converted to the types the function declares, less the ``unset`` ones.
94
+
95
+ LlamaIndex passes the model's values as they are, and a plain ``pydantic.validate_call``
96
+ would convert them after judgment: ``"on"`` judged, ``True`` run. Raises ``ValueError``
97
+ naming the parameter and never its value.
98
+ """
99
+ hints = typing.get_type_hints(inspect.unwrap(function), include_extras=True)
100
+ made = {}
101
+ for name, value in values.items():
102
+ if name not in unset:
103
+ declared: TypeAdapter[Any] = TypeAdapter(hints[name])
104
+ try:
105
+ value = declared.validate_python(value)
106
+ except ValidationError:
107
+ raise ValueError(f"`{name}` does not validate against its type") from None
108
+ made[name] = value
109
+ return made
110
+
111
+
112
+ class FunctionNotHandedOut(TypeError, AttributeError):
113
+ """A gated tool was asked for its function. Also an ``AttributeError``, so that
114
+ ``hasattr`` and ``inspect.getmembers`` work on a gated tool."""
115
+
116
+
117
+ def _unknown(names: list[str]) -> str:
118
+ """The reason for arguments the tool does not take. The model wrote their names, and the
119
+ reason is on the audit log, so only a few that could be a parameter's name are shown."""
120
+ shown = [name for name in names if name.isidentifier() and len(name) <= 40][:5]
121
+ more = f" and {len(names) - len(shown)} more" if len(names) > len(shown) else ""
122
+ return f"unknown parameter(s) {shown!r}{more}"
123
+
124
+
125
+ def _unjudgeable(tool_name: str, detail: str, proposal: dict, record: dict[str, Any]) -> str:
126
+ """The reason for a call refused before any policy runs. With recording arguments the
127
+ refusal is one entry on the log, bound to the arguments as they were proposed."""
128
+ if not record:
129
+ return f"Recusal refused `{tool_name}`: {detail}"
130
+
131
+ def unjudgeable(_name: str, _input: dict) -> List[Any]:
132
+ return [Finding.fail("recusal_unjudgeable_input", severity="CRITICAL", message=detail)]
133
+
134
+ try:
135
+ return decide(tool_name, proposal, unjudgeable, safe_errors=True, **record)[1]
136
+ except Exception as exc: # noqa: BLE001, the refusal stands if it cannot be recorded
137
+ return f"Recusal refused `{tool_name}`: {detail} (not recorded: {type(exc).__name__})"
138
+
139
+
140
+ class GatedFunctionTool(FunctionTool):
141
+ """A stock FunctionTool that judges the exact named data it will receive.
142
+
143
+ Context is host input rather than model input and is deliberately omitted from policy
144
+ evidence. Positional arguments are refused because a policy cannot judge them by name.
145
+ A function the kernel does not read is refused before its policy or body runs.
146
+ """
147
+
148
+ def __init__(
149
+ self, source: FunctionTool, policy: Policy, record: Optional[dict[str, Any]] = None
150
+ ) -> None:
151
+ if type(source) is not FunctionTool:
152
+ raise TypeError("gated_tool supports a stock llama_index FunctionTool only")
153
+ # LlamaIndex reads a tool's ``_fn`` in places (``OnDemandLoaderTool``), so the function
154
+ # is kept by a stock tool of the gate's own and not by this object
155
+ inner = FunctionTool.__new__(FunctionTool)
156
+ for name in _KEPT:
157
+ setattr(inner, name, getattr(source, name))
158
+ inner.partial_params = {} # the gate fills these in, and defaults, before judgment
159
+ inner._field_defaults = {}
160
+ self._recusal_inner = inner
161
+ self._metadata = source.metadata
162
+ self.requires_context = source.requires_context
163
+ self.ctx_param_name = source.ctx_param_name
164
+ self.partial_params = dict(source.partial_params)
165
+ self._recusal_policy = policy
166
+ self._recusal_record = dict(record or {})
167
+ self._recusal_gated = True
168
+
169
+ def _hands_out_no_function(self) -> NoReturn:
170
+ raise FunctionNotHandedOut(
171
+ "a gated tool does not hand out its function, which would run unjudged; "
172
+ "call the tool itself"
173
+ )
174
+
175
+ @property
176
+ def real_fn(self) -> Callable[..., Any]:
177
+ """The function, whose signature LlamaIndex reads here. Calling it is not gated."""
178
+ return self._recusal_inner.real_fn
179
+
180
+ @property
181
+ def fn(self) -> Callable[..., Any]:
182
+ """Refused: the function alone runs without the policy."""
183
+ self._hands_out_no_function()
184
+
185
+ @property
186
+ def async_fn(self) -> Callable[..., Any]:
187
+ """Refused, as ``fn`` is."""
188
+ self._hands_out_no_function()
189
+
190
+ @property
191
+ def _fn(self) -> Callable[..., Any]: # type: ignore[override]
192
+ self._hands_out_no_function()
193
+
194
+ @property
195
+ def _async_fn(self) -> Callable[..., Any]: # type: ignore[override]
196
+ self._hands_out_no_function()
197
+
198
+ def to_langchain_tool(self, **langchain_tool_kwargs: Any) -> Any:
199
+ """Refused: LangChain would run the function without the policy."""
200
+ self._hands_out_no_function()
201
+
202
+ def to_langchain_structured_tool(self, **langchain_tool_kwargs: Any) -> Any:
203
+ """Refused, as ``to_langchain_tool`` is."""
204
+ self._hands_out_no_function()
205
+
206
+ def _shown(self, kwargs: dict[str, Any]) -> dict[str, Any]:
207
+ """The arguments without the host's Context."""
208
+ return {name: value for name, value in kwargs.items() if name != self.ctx_param_name}
209
+
210
+ def _refusal(self, reason: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> ToolOutput:
211
+ shown = self._shown(kwargs)
212
+ return ToolOutput(
213
+ content=reason,
214
+ tool_name=self.metadata.get_name(),
215
+ raw_input={"args": args, "kwargs": shown},
216
+ raw_output=None,
217
+ is_error=True,
218
+ )
219
+
220
+ def _prepare(
221
+ self, function: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
222
+ ) -> tuple[dict[str, Any], str | None]:
223
+ """The keywords to run ``function`` with, and None; or the reason it is refused."""
224
+ tool_name = self.metadata.get_name()
225
+
226
+ record = self._recusal_record
227
+ proposal = self._shown(kwargs)
228
+ if isinstance(kwargs.get(self.ctx_param_name or ""), _DATA):
229
+ proposal = dict(kwargs) # data in the context parameter is no host Context
230
+ if args:
231
+ proposal = {"args": list(args), "kwargs": proposal}
232
+
233
+ def refused(detail: str) -> tuple[dict[str, Any], str]:
234
+ return {}, _unjudgeable(tool_name, detail, proposal, record)
235
+
236
+ if args:
237
+ return refused(
238
+ "positional arguments are unsupported; every argument must be judged by name"
239
+ )
240
+ given = {**self.partial_params, **kwargs}
241
+ host: dict[str, Any] = {}
242
+ context_name = self.ctx_param_name if self.requires_context else None
243
+ if context_name is not None:
244
+ if context_name not in given:
245
+ return refused("Context is required for this tool")
246
+ host[context_name] = given.pop(context_name)
247
+ if isinstance(host[context_name], _DATA):
248
+ return refused(f"`{context_name}` is the host's Context and was given as data")
249
+
250
+ try:
251
+ parameters = judged_parameters(function, tuple(host), **_CALL)
252
+ except Exception as unread: # noqa: BLE001, every refusal of the kernel's is one here
253
+ return refused(refusal_reason(unread, call_style=_CALL["call_style"]))
254
+ if "self" in {name for name, _ in parameters} | set(host):
255
+ return refused("LlamaIndex cannot pass a parameter named `self`")
256
+ unknown = sorted(set(given) - {name for name, _ in parameters})
257
+ if unknown:
258
+ return refused(_unknown(unknown))
259
+ values: dict[str, Any] = {}
260
+ for name, default in parameters:
261
+ values[name] = given.get(name, default)
262
+ if values[name] is inspect.Parameter.empty:
263
+ return refused(f"required parameter `{name}` was not supplied")
264
+ # ``region: str = None``: the declared default, which its own type would not accept
265
+ unset = {name for name, default in parameters if default is None and values[name] is None}
266
+ try:
267
+ # the function gets a copy of its own, so nothing that still holds the caller's
268
+ # objects, a default or a partial parameter can change them after judgment
269
+ values = _converted(function, detached(_plain(values)), unset)
270
+ judged = detached(values)
271
+ except (TypeError, ValueError) as exc:
272
+ return refused(str(exc))
273
+ except Exception as exc: # noqa: BLE001, a preparation that fails is refused
274
+ return refused(f"the call cannot be prepared ({type(exc).__name__})")
275
+
276
+ try:
277
+ decision, reason = decide(
278
+ tool_name, judged, self._recusal_policy, safe_errors=True, **record
279
+ )
280
+ except Exception as exc: # noqa: BLE001, a policy that raises must not open the gate
281
+ return refused(
282
+ f"failed closed (policy error): RECUSAL_POLICY_ERROR ({type(exc).__name__})"
283
+ )
284
+ if decision == "deny":
285
+ return {}, reason
286
+ return {**values, **host}, None
287
+
288
+ # ``self`` by position only: a model may name an argument ``self``, and that call is
289
+ # refused, and recorded, like any other with an unknown parameter
290
+ def __call__(self, /, *args: Any, **kwargs: Any) -> ToolOutput:
291
+ return self.call(*args, **kwargs)
292
+
293
+ def call(self, /, *args: Any, **kwargs: Any) -> ToolOutput:
294
+ inner = self._recusal_inner
295
+ prepared, reason = self._prepare(_own_function(inner._fn), args, kwargs)
296
+ if reason is not None:
297
+ return self._refusal(reason, args, kwargs)
298
+ return inner.call(**prepared)
299
+
300
+ async def acall(self, /, *args: Any, **kwargs: Any) -> ToolOutput:
301
+ inner = self._recusal_inner
302
+ prepared, reason = self._prepare(_own_function(inner._async_fn), args, kwargs)
303
+ if reason is not None:
304
+ return self._refusal(reason, args, kwargs)
305
+ return await inner.acall(**prepared)
306
+
307
+
308
+ def gated_tool(tool: FunctionTool, policy: Policy) -> GatedFunctionTool:
309
+ """Return an explicit, fail-closed wrapper for one local ``FunctionTool``."""
310
+ return GatedFunctionTool(tool, policy)
311
+
312
+
313
+ def is_gated(tools: Sequence[object]) -> bool:
314
+ """True only when every supplied local tool came from ``gated_tool`` or
315
+ ``audited_tool``.
316
+
317
+ This checks only the list it is handed. It cannot see a tool added later or a
318
+ provider-hosted tool that never appears in this list.
319
+ """
320
+ return bool(tools) and all(isinstance(tool, GatedFunctionTool) for tool in tools)
@@ -0,0 +1 @@
1
+ llama-index-core==0.14.25