recusal-openai
The Recusal gate for a loop you own on the OpenAI API: every function call the model proposes is judged by your policy before your code runs it, and a refused call never runs. It covers the Responses API and Chat Completions with one decision function.
New to Recusal? It checks each tool call an AI agent proposes against your policy and refuses the unsafe or unapproved ones before the tool runs. No model makes that decision. A policy is a plain Python function: it is given the tool's name and its arguments and returns a list of findings. An empty list lets the call run; a failing finding refuses it and gives the reason. Writing a policy covers the two postures, allowlist and deny-list.
This is a separate distribution from recusal. The kernel has zero runtime dependencies
and a frozen compatibility perimeter; this package carries the OpenAI SDK dependency and
its own version, so an SDK release never forces a release of the kernel.
Install it from PyPI:
pip install recusal-openai
Requires Python 3.10+ (the SDK's minimum), recusal>=0.17.1 and openai>=3.49.0. It is
tested on every pull request against exactly openai==3.49.0, and weekly against the
newest release. The kernel floor is what checks a decorated tool: beside an older
kernel the package raises ImportError instead of gating without that check.
The package ships inline types (py.typed) for your editor and type checker.
Use
from openai import OpenAI
from recusal import Finding
from recusal_openai import gate_function_calls
def run_sql(sql: str) -> str: ...
def policy(tool_name, tool_input):
sql = tool_input.get("sql", "")
if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
return []
client = OpenAI()
response = client.responses.create(model=..., input=..., tools=...)
answers = gate_function_calls(response, {"run_sql": run_sql}, policy)
# pass ``answers`` as the next request's input
gate_tool_calls(completion, tools, policy) does the same for Chat Completions and
returns role: "tool" messages. A completion requested with n > 1 carries alternative
messages, so pass choice=<list position>; without it the gate refuses the completion
before anything runs.
Each proposed call gets exactly one answer under its own id: the tool's result, or
Recusal's reason. A policy that raises refuses the call (fail closed). The gate always
fails closed: fail_closed is not a keyword it takes.
The gate calls your tools synchronously, so each tool is an ordinary function. An
async def tool and a generator function (one whose body has a yield) are refused with
a reason before the policy runs, so the policy is not consulted for them. The gate reads
how a tool is declared through a functools.partial, a staticmethod, a bound method
and functools.lru_cache. It does not look through a wrapper of your own,
functools.wraps included, because such a wrapper may await or consume what it wraps:
that tool is judged and called like any other.
What a tool returns is answered as its str, with two exceptions. If it returns a
coroutine, the answer says so and that the gate did not run the coroutine. If it returns
a generator or any other iterator (an async generator, iter(...), map(...), an open
file), the answer is Tool `name` ran and returned a generator, which this gate does not consume: its result is not available (an iterator or an async generator for
the other kinds). The function's own body ran, with whatever side effects it has, so the
answer never says the tool did not run. Return a list or a string instead.
A tool that raises: by default the exception reaches your loop, as it always has. Calls
earlier in the turn have already run and their answers are lost with it; calls later in
the turn do not run. Pass answer_tool_errors=True to answer the failed call instead,
with Tool `name` raised <ExceptionClass> under its own id. The class named is the
exception's nearest built-in one (TimeoutError, ValueError, Exception at worst):
never the message, and never a class name your application or a library chose. The rest
of the turn is then judged and run as usual, including the calls after the failed
one, and the traceback goes to the recusal_openai logger (to stderr, if your
application configures no logging), not to the model.
The gate binds the decoded arguments to the tool's signature with its defaults applied, judges that invocation, and calls the tool with exactly those arguments. A default the model omitted is therefore judged at the value the function would use.
Put every decision on the record
from recusal.audit import AuditLog
from recusal_openai import audited_function_calls
log = AuditLog(path="decisions.jsonl")
answers = audited_function_calls(response, tools, policy, log)
audited_tool_calls is the Chat Completions form. Each call the model proposes, run or
refused, is one hash-chained entry labeled openai.responses.function_call or
openai.chat_completions.tool_call with the API's own call id and a SHA-256 fingerprint
of the arguments (never the arguments). The call id is on the entry exactly as the API
sent it, and is at most 256 characters (see call ids below). A refusal's reason on the
log never quotes an
argument's key or value: a call that does not bind names the parameters the tool declares
and counts the arguments it does not take. A tool you have is on the entry under the
name you gave it. A name you have no tool for is the model's text: it is on the entry,
and in the reason, as sent only if it is 1 to 64 printable characters with no backtick,
and otherwise as a description of its length, such as
<a tool name of 1000000 characters, not shown>. If the log cannot be written the call
is refused.
Check the log with recusal audit verify decisions.jsonl.
The audited functions call the plain ones, so there is one decision path:
audited_function_calls(response, tools, policy, log) is
gate_function_calls(response, tools, policy, audit=log, surface="openai.responses.function_call"),
and both forms take actor= and control= for the entry. Called directly, the plain
functions also take allow_on_pass=True, which records a passing call as allow
instead of defer and changes nothing about what runs.
A loop whose log is optional is one call to the plain function:
from recusal_openai import SURFACE_RESPONSES, gate_function_calls
maybe_log = AuditLog(path="decisions.jsonl") if recording else None
answers = gate_function_calls(response, tools, policy, audit=maybe_log, surface=SURFACE_RESPONSES)
audit=None, passed explicitly, is the plain gate: nothing is recorded, and surface=,
actor= and control= are accepted and not used. When audit= is not passed at
all, surface=, actor= or control= with a value raises TypeError before anything
is judged, so a loop that believes it is recording is never silently not recording.
audit= with a log and no surface= raises the same way. The two audited functions
need a log: audited_function_calls(response, tools, policy, None) raises TypeError
and runs nothing, because a function named "audited" that recorded nothing would
mislead.
A surface= or control= the kernel would not record raises ValueError naming the
keyword, before any tool call is looked at, with a log and with audit=None: a surface
that is empty, starts or ends with a space, is not a string or is the reserved
claude_code.pretooluse, and a control that is not a dict. The rule is
recusal.decide's own: the gate asks it and restates nothing. tool_use_id= and
fail_closed= are not taken and raise TypeError: each call is recorded under its own
call id, and the gate always fails closed.
What the gate refuses, and what it does not see
-
Refused with a reason, never run. Each of these is answered under the call's own id before the policy runs, and is one entry on the audit log in the audited loop:
- The arguments. Arguments that are not a string (an empty string is a call with no
arguments), not valid JSON, or not a JSON object.
NaN,Infinityand-Infinityare not JSON and are refused. So are a number Python reads as infinity (1e999) and arguments nested more than 64 levels below the arguments object. - A call that is not finished. A Responses
function_callitem whosestatusis anything butcompleted(in_progress,incomplete); an item with nostatuspasses. Every function call of a response whose ownstatusis anything butcompleted(incomplete,failed,cancelled,in_progress,queued, a value a later SDK adds), the finished items in it included; a response with nostatuspasses. Every tool call of a Chat Completions choice whosefinish_reasonis anything butstop,tool_callsorfunction_call: that islength(the message was cut off at the token limit),content_filterand a missingfinish_reason. Request the turn again with a higher token limit instead of running a call that may have been cut off. - A namespaced function call. A Responses
function_callitem that carries a non-emptynamespaceis refused: namespaced calls are not supported. The tools you pass and the name the policy sees are bare names, so the gate could not tell two functions of the same name in different namespaces apart. Declare such functions without a namespace, under names that are unique. - The tool. A tool the application does not have (a name that is not a string is
one), arguments that do not bind to the tool, an
async deftool, a generator function, afunctools.lru_cachetool handed a list or an object, and a tool whose signature cannot be judged by name: see the next point.
- The arguments. Arguments that are not a string (an empty string is a call with no
arguments), not valid JSON, or not a JSON object.
-
Which tools the gate can judge. A tool is a plain function, a bound method or a
functools.lru_cacheof one, whose every parameter can be passed by name and is annotated with a supported data type:str,int,float,bool,Optionalof a supported type (also writtenT | None),list[T], anddict[str, T], whereTis a supported type in turn (list[dict[str, int]]is supported). Every default must be JSON data. A tool cached withfunctools.lru_cache(orfunctools.cache) needs arguments the cache can hash: a call that hands it a list or an object, for alist[T]ordict[str, T]parameter or in place of astr, is refused with a reason before the policy runs. Give a cached toolstr,int,floatandboolparameters only. A cache behind a wrapper of your own is not seen: there such a call raisesTypeErroras any tool that raises does (seeanswer_tool_errorsabove). Everything else is refused with a reason, among them:- a parameter with no annotation,
Any,Literal[...], a union of two types such asint | float, a barelistordict, anEnum,Annotated[...], a dataclass or a model; - variadic (
*args,**kwargs) and positional-only parameters; - a
functools.partial, and a callable object (an instance with__call__) unless its class annotates the names__call__takes (a dataclass whose fields are those names, for example), because the kernel reads annotations from the class; - a
functools.wrapswrapper that adds a parameter of its own to the function it wraps, and one that takes*args, **kwargsand also names a parameter the function has: either would run with a value the policy never judged; - a decorated tool whose wrappers the kernel's walk cannot all read, and a method decorator that names the method's parameters where the object may not be handed on: see below.
Whether a tool's signature can be judged is the kernel's answer. Whatever reason it gives, and any error it raises while reading the tool, refuses that one call before the policy runs. A refusal its walk makes by a class of its own gets a reason of the gate's: what was found, why it is refused and what to write instead.
What to do instead: write a plain function with supported annotations and resolve richer types inside its body. Take a
strand check it against the allowed values in place ofLiteralor anEnum, pickfloatin place ofint | float, writedict[str, str]in place ofdict, and replace afunctools.partialor a callable object with a plain function that does its work in its own body. The annotations decide only whether the gate can judge the tool: the gate binds arguments by name and does not check or convert a value's type. - a parameter with no annotation,
-
The tool's name in a refusal. A refusal names a tool you have by the name you gave it. A name you have no tool for is quoted only if it is 1 to 64 printable characters with no backtick. Any other (longer, empty, or holding a backtick, a newline, a control or formatting character or a lone surrogate) is described by its length, in the answer and on the audit log, as
<a tool name of 70 characters, not shown>, and a name that is not a string as<a tool name that is not a string>. So a tool name cannot close the backticks a refusal sets it in, start a new line, or put more than 64 characters of the model's text into an answer or an entry. -
Call ids. A call id is the model's text too, and it has to go back exactly as sent: in the answer, which is how the API matches it to the call, and on the audit entry, which is how the entry is tied to the call. So the gate does not shorten or describe it there. It takes a call id of at most 256 characters instead: a longer one raises
ValueErrorbefore anything in the turn runs, and writes no entry. That bounds what one id can add to an answer or an entry at 256 characters. An id may hold any character; on the log it is JSON-escaped, so it cannot start a line. A message the gate raises (a duplicate id) quotes an id only if it is printable with no backtick, names at most four, and otherwise describes each by its length, as<a call id of 17 characters, not shown>. -
Refused by raising, before anything in the turn runs: an output item or tool call of a type the gate does not handle (
custom_tool_call, the provider's record of a hosted tool call, a type a later SDK adds), a Chat Completions message that carries the legacyfunction_callfield (alone or besidetool_calls; the gate readstool_callsonly, so declare functions withtools, notfunctions), a call without an id, a call id of more than 256 characters, a duplicate id, and a keyword argument the gate does not take (TypeErrornaming it, whether or not the turn has calls): a mistyped one,fail_closed,tool_use_id,surface,actororcontrolwith a value whenauditis not passed at all, andauditwith a log and nosurface. Asurfaceorcontrolthe kernel would not record raisesValueErrornaming it. A turn refused this way writes no audit entry. -
Not seen: what a wrapper does in its own body. The gate reads signatures, not code. A
functools.wrapswrapper that restates the function's parameters is judged by them, and if its body then does not pass one on, or passes them on in other places, the function runs with values the policy did not judge:def logged(fn): @functools.wraps(fn) def wrapper(path: str, dry_run: bool = False): return fn(path) # dry_run is not passed on return wrapper @logged def delete_tree(path: str, dry_run: bool = False) -> str: ...
A call with
dry_run=trueis judged withdry_runtrue anddelete_treeruns withdry_runfalse. No check of a signature can see this. Give the gate the function itself, or a wrapper that passes on every parameter it names. On a method, where the object goes in by position, a wrapper that names parameters is held to a rule of the gate's own (two points below), which refuses it where a body that kept the object could run without failing; the body itself is read there no more than here. -
A decorated tool whose wrappers cannot all be read. Whether a tool's signature can be judged is the kernel's answer: its walk (
recusal.invocation) reads every callable a call reaches, and refuses what it cannot follow to the end. The gate gives each of its refusals a reason of its own, which says what was found, why it is refused and what to write instead. Refused:- a decorator that holds a second wrapper of the function (in its closure, in a module
global it names, or on the decorator object) and calls it, where the held wrapper has
a parameter of its own, takes the tool's parameters in other places, takes the object
of a method under another name than the function it wraps has for that place, names
a chain of
__wrapped__that comes back on itself, or reaches the function through a single-dispatch function, a weak proxy or a cache named again; - a
functools.lru_cachenamed again for another function, whose function cannot be told from what the cache refers to; - a
functools.singledispatchfunction orsingledispatchmethodon the way, with an implementation registered, or with nothing registered but its base (one can be registered between the check and the call); - a
functools.partialmethodover a callable object or a class-based decorator; - a wrapper handed a bound argument (the object of a method, a positional argument of
a
functools.partial) that takes it under another name than the function it wraps has for that place, or passes a value of its own there: its signature does not show whether it hands the argument on; - a declared signature, also where it matches the real parameters: a
__signature__, a__text_signature__that is not the interpreter's own, or a callable object that shows a__code__and names nothing as__wrapped__; - a
weakref.proxyanywhere on the way; - a callable that answers for
__wrapped__without holding one (a class-based decorator that hands every attribute on with__getattr__), or that shows another class than its own and has a__call__of its own that takes a parameter by name; - a class-based decorator that is also a descriptor (its class defines
__get__); - more wrappers than the walk reads;
- a
functools.partialas the tool, and a tool whose annotationstyping.get_type_hintscannot resolve.
Read to the end, so that a wrapper with a parameter of its own is refused, naming the parameter, and one that only passes its arguments on is accepted:
functools.wrapswrappers andfunctools.lru_cacheapplied directly, a decorator written asfunctools.wraps(f)(functools.partial(helper, f)),@functools.wraps(f)written above@functools.lru_cache, and a class-based decorator built withfunctools.update_wrapper(on a method, a class-based decorator with no__get__and afunctools.partialdo not bind the object, and itsselfis refused as not annotated). No reason advises calling the refused function from a plain function and registering that one: the gate reads a plain function's parameters and never its body, so the cause would run inside it as before. Every reason that says what to write ends by saying so. - a decorator that holds a second wrapper of the function (in its closure, in a module
global it names, or on the decorator object) and calls it, where the held wrapper has
a parameter of its own, takes the tool's parameters in other places, takes the object
of a method under another name than the function it wraps has for that place, names
a chain of
-
How this gate calls a tool, and what that means for a shifted call. The gate binds the decoded arguments to the tool's signature by name and calls
func(**invocation)(_judgein_gate.py): every argument is passed by keyword, the defaults included, and nothing the model sent goes in by position. The only values that go in by position are the ones a callable on the way binds itself: the object of a bound method (self, orclsfor a class method) and the positional arguments of afunctools.partial. The tools ofexamples/openai_responses_gate.pyare plain functions, called the same way. So where the kernel refuses a wrapper that may keep a bound argument because a call by keyword would then fail and a call by position would run each judged value one place off, a call this gate makes would fail with aTypeError, and nothing would run: under this gate such a tool, refused, either runs correctly or fails. Such aTypeErrorleaves the gate as any tool's exception does (seeanswer_tool_errorsabove). Two reasons pass on the kernel's text for a bound argument, which can end with the advice to take the argument under the name the function has for it and hand it on by position. Where another wrapper on the way keeps the object (a method decorator that does not passselfon), the tool written that way is refused by the gate's rule below, or is gated and does not run as judged: called by keyword, as this gate calls it, it raises aTypeError, and called by position it would run every judged value one place off. Each reason says so before the kernel's text, and the gate's own advice comes first. -
A method decorator that names the method's parameters and passes them on without the object.
def wrapper(self, table, limit=10): return fn(table, limit)underfunctools.wraps(fn), overdef purge(self, table: str, limit: int = 10), is read by the kernel's walk (its changelog entry for 0.17.1 states it under "Still read, by design"): nothing in the wrapper's signature tells it from one that hands the object on. This gate calls the method by keyword, the object goes in by position, and the body passes the values on by position: judged{table: "t", limit: 5}, it ranself="t",table=5,limit=10under 0.2.2. The gate refuses it by a rule of its own, after the onerecusal-pydantic-aihas: a bound object handed in by position past a wrapper that names a positional parameter is refused where- that wrapper takes a parameter as another kind than the method does (
def wrapper(self, *, account, amount=7, memo="m0")overdef transfer(self, account: str, amount: int = 7, memo: str = "m0"), which, passing the values on by position, ranself="ACCT",account=55,amount="MEMO"for judgedaccount="ACCT",amount=55,memo="MEMO", also over a requiredamount); or - a wrapper that kept the object would not make the call fail: the method's leading parameter has a default, the parameter the last value moved up a place would leave empty has one, or the values fill every positional place and a keyword-only parameter of the method has one.
The rule is asked of every bound method on the way: under a
functools.lru_cache, a cache named again, on a class method and behind a facade that passes everything on. It reads the method's function on its own with the kernel's walk; where that walk refuses it there although it reads the bound method (a decorator that holds a second method wrapper takingself), the tool is refused with a reason that says the refusal is this gate's. Where a wrapper that kept the object would make the call fail, the tool is gated, and a body that drops the object makes that call raise aTypeError, with nothing run: a keyword-only wrapper over a method whose parameters are keyword-only and have no default is read, runs as judged where it hands the object on, and fails where it drops it. Give the wrapper only*argsand**kwargsand hand every argument on, the object with them, or register the method without the decorator. Not read by the rule: a wrapper a decorator holds (see Open). - that wrapper takes a parameter as another kind than the method does (
-
No state between turns. Within one turn a duplicate or empty call id raises. The gate remembers nothing from one turn to the next, so a call id used again in a later turn is not detected: each turn is judged, answered and recorded on its own.
-
No helper for streaming. The gate takes a complete
ResponseorChatCompletion. An application that streams must assemble the complete response first (the SDK's stream helpers return it once the stream ends:get_final_response()for Responses,get_final_completion()for Chat Completions), then hand it to the gate, and must not run a function call from a stream event. -
Never judged: hosted tools. Web search, file search, code interpreter, image generation and remote MCP run on the provider's side. What arrives in your loop is the provider's record of the call (
web_search_call,mcp_calland the others inHOSTED_RECORD_TYPES, which also holdscompaction, the provider's summary of earlier context). By default such an item raises like any other unhandled one. Passallow_hosted_records=Trueto let finished records through: they are not judged, not answered and not on the audit log, and the function calls beside them are judged as usual. A record whosestatussays it is still in progress raises either way. -
Not gated yet: remote MCP approvals. A remote MCP server set to require approval sends an
mcp_approval_requestfor your loop to answer. This gate does not judge it: it raises, with or withoutallow_hosted_records, so the call is never approved through this gate. -
Not read:
asyncandcaller. A Responsesfunction_callitem can be markedasyncand can carry acallerof typeprogram. The gate reads neither field: such a call is judged by your policy and run like any other. -
After the decision. An audit entry records the gate's decision, not what the tool then did. A call the gate allowed whose tool raised, returned a coroutine that nothing ran, or returned an iterator the gate did not consume, is on the log as allowed. The async and generator checks read how a tool is declared; a wrapper of your own that hides an
async defor a generator function behind an ordinary function is caught only by what it returns, after the policy has allowed the call and the wrapper has been called.
Refused although it runs correctly. The kernel's walk reads parameters and not
bodies, so it refuses some signatures a correct tool can have. Each of these runs
correctly when called by keyword, as this gate calls it; 0.2.2 beside recusal 0.15.1
gated each, and beside recusal 0.17.1 this gate refuses each, before the policy is
asked and before anything runs. Each was run through this gate, and so was each remedy
below.
- New with
recusal0.16.0:- A class-based decorator that keeps the function in an attribute and answers every
other attribute from it with
__getattr__, over a plain function, which then shows its__code__. Callfunctools.update_wrapper(self, fn)in its__init__. - A single-dispatch function that is called with its first argument by position, as a method's object goes in, or every value a wrapper that restates the parameters passes on in order, with implementations registered only for other types than that argument's: it always runs its base. Register the method, or the function, without the single-dispatch function.
- A
__text_signature__that matches the parameters, under a decorator written asfunctools.wraps(f)(functools.partial(helper, f))(without that decorator, 0.2.2 refused it too). Delete it. - A facade method that hands its object on to a function that names that place
otherwise (
return execute(self, *args, **kwargs)underfunctools.wraps(execute), overdef execute(database="main", sql: str = "SELECT 1", note: str = "")), or passes a value of its own there (return search(self.tenant, *args, **kwargs)overdef search(tenant: str = "main", limit: int = 10)), where that parameter has a default. Register the function itself, or write the method out, its parameters passed on to the function by keyword.
- A class-based decorator that keeps the function in an attribute and answers every
other attribute from it with
- New with
recusal0.17.0:- A
weakref.proxyof a plain function under a decorator that hands its arguments on. Put the function in the proxy's place. - A decorator that holds a
weakref.proxyof a helper that hands its arguments on. Hold the helper itself. - The same single-dispatch function with nothing ever registered on it. Register the method, or the function, without the single-dispatch function.
- A class-based decorator that answers every other attribute with
__getattr__, over a function that names a__wrapped__(anyfunctools.wrapsdecorator, anyfunctools.lru_cache). Callfunctools.update_wrapper(self, fn)in its__init__. - An object that shows another class than its own and holds a
__wrapped__(the shape of awraptproxy), whose own__call__names the parameters and hands each on in order. Give its__call__only*argsand**kwargs, handing them all on. - A decorator that holds a wrapper which takes the tool's parameters in another order and hands them on by keyword: this gate's call by keyword reaches each by name (0.16.0 refuses it already under a wrapper that restates the tool's parameters). Give the held wrapper the tool's parameters in the tool's order, or as keyword-only ones.
- A
- New with
recusal0.17.1:- A method decorator that takes the object under another name than the method has for
it and hands it on (
def wrapper(this, *args, **kwargs): return m(this, *args, **kwargs)overdef run_sql(self, ...), orselfover a class method'scls). Take the object under the name the method has for it (self, orclsfor a class method) and hand it on by position. - A held
functools.wrapswrapper that does the same (def forward(receiver, *args, **kwargs): return run(receiver, *args, **kwargs)overdef run(self, ...), called by a pass-through). Take the object in*argswith the rest. - A held helper whose chain of
__wrapped__comes back on itself (helper.__wrapped__ = helper). Name the function it wraps, once. - The two facades under 0.16.0 where that parameter has no default (
def execute(database, sql: str = "SELECT 1", note: str = ""),def search(tenant: str, limit: int = 10)). Register the function itself, or write the method out.
- A method decorator that takes the object under another name than the method has for
it and hands it on (
- New with this package's 0.2.3, by the gate's own rule above: a method decorator that
restates the method's parameters, the object's place with them, and hands each on
(
def wrapper(self, table, limit=10): return fn(self, table, limit)), on a method, a class method or a facade; a method decorator that takes the method's parameters as another kind and hands the object on (def wrapper(self, *, account, amount=7, memo="m0"): return fn(self, account=account, amount=amount, memo=memo)over a method that takes them by position); and a method decorator that takes the object asselfand hands it on, above two or more class-based decorators or decorators written asfunctools.wraps(f)(functools.partial(helper, f)), since the rule counts each value such a callable binds as one that could move into the object's place. Give the wrapper only*argsand**kwargsand hand every argument on, or register the method without the decorator. - New with this package's 0.2.3, by the same rule's reading of the method's function on
its own: a decorator that holds a second method wrapper and hands the object on to it
(
def outer(self, *args, **kwargs): return inner(self, *args, **kwargs)holdingdef inner(self, *args, **kwargs), or holding a keyword-only wrapper that hands the object on), on a method or a class method. The kernel's walk reads the bound method; read on its own, the held wrapper'sselfis refused. Take the object in*argsin the held wrapper (def inner(*args, **kwargs): return fn(*args, **kwargs)). - New with
recusal0.16.0, missed above: a class-based decorator that binds as a method (its class defines__get__) underfunctools.wraps(f)(functools.partial(helper, f))applied to it, whose name the partial now carries to it. Give its class no__get__.
Refused too, and changing nothing that runs, since this gate's call fails there either
way: such a wrapper that drops the object where the place it leaves has no default (def method(self, *args, **kwargs): return execute(*args, **kwargs) over def execute(database: str, ...), and a held def forward(receiver, *args, **kwargs): return run(*args, **kwargs) under functools.wraps). 0.2.2 beside recusal 0.15.1 gated
both, and the call raised TypeError. The kernel's entries for 0.16.0, 0.17.0 and 0.17.1
in the changelog have the whole lists for its walk.
Open, stated so you can judge them. A test named test_open_ holds each.
- A method decorator that forgets to pass the object on.
@functools.wraps(m) def method(self, *args, **kwargs): return m(*args, **kwargs)overdef run_sql(self, sql: str, force: bool = False), and the same where the decorator takes the object in*args(return m(*args[1:], **kwargs)) or sits underclassmethod. It is gated, and the policy judges the call; this gate calls it by keyword, so the method is missing its object, the call raises aTypeErrorout of the gate (or is answered as a tool that raised, withanswer_tool_errors=True), and none of it runs. Called by position, as a loop of your own might call it, it would run every judged value one place off. From the signature nothing tells it from the ordinary decorated method, which the kernel's entry for 0.17.1 states under "Still read, by design". So is a wrapper of the method's kinds that drops the object over parameters with no default (above, under the gate's rule): gated, and the call raises aTypeError. Passselfon in the decorator. - A held method wrapper that drops the object, under a pass-through.
def outer(*args, **kwargs): return inner(*args, **kwargs), holdingdef inner(self, account, amount=7, memo="m0"): return fn(account, amount, memo)overdef transfer(self, account: str, amount: int = 7, memo: str = "m0"): the kernel's walk reads it, since the held wrapper takes the object asself, the method's own name, and the gate's rule reads the levels of the walk, not what a wrapper holds. It is gated, and it runs every judged value one place off: judgedaccount="ACCT",amount=55,memo="MEMO", it ranself="ACCT",account=55,amount="MEMO". The same held underdef outer(self, *args, **kwargs)is refused (above). Pass the object on in the held wrapper, or give it only*argsand**kwargs. - The same, where the place the object leaves has a default. A facade that drops its
object in
*argsoverdef execute(database: str = "main", sql: str = "SELECT 1", note: str = "")is gated, and called by keyworddatabaseruns at its default, which no policy judged; the judged values run in their places. Hand the object on, or register the function itself. - A held wrapper without
functools.wrapsthat takes the object under another name and drops it (def forward(receiver, *args, **kwargs): return run(*args, **kwargs), called by afunctools.wrapspass-through): the kernel reads it by design, since every correct held wrapper written withoutfunctools.wrapshas the same shape. It is gated, and this gate's call raises aTypeError(over a facade whose first parameter has a default, that parameter runs at its default). The same withfunctools.wrapsis refused. - A held wrapper the kernel's walk does not find. One that names nothing as
__wrapped__, with a parameter of its own, runs that parameter at its default, which no policy judged. The kernel's entry for 0.17.0 lists the other held wrappers its walk does not find (one built on first use, one in a slot, a container, a settings object or a function's own attribute, one behind aweakref.ref).
Beyond the gate. This gate judges the tool calls the framework routes through it; the paths around it inside the framework are listed above. Like every Recusal gate, it does not stop an agent that can reach a resource another way: a credential with wider rights, a shell or network path outside the agent, or a file it can write that configures the gate. Use it as one layer of several: least-privilege credentials for the agent, a sandbox or container, limits on its network egress, and an audit anchor the writer cannot reach (the limits in full).
Status
In-depth review complete. Its fixes are released in 0.2.3. Recusal is a Beta (0.x) open-source project in active
development: it is not a finished or certified security product, and it is provided under
Apache-2.0 without warranty.
What the reviews are, and where every adapter stands.
What 0.2.3 changes. It requires recusal 0.17.1 (0.2.2 allowed 0.15.0). Beside
recusal 0.15.1, 0.2.2 gated decorated tools that then ran a value no policy judged: a
decorator that holds a second wrapper with a parameter of its own (also with a
weakref.proxy or a single-dispatch function on the way), a held helper with a
parameter of its own whose __wrapped__ names itself, and a held wrapper that takes the
object under another name and drops it where the place it leaves has a default; the walk
of 0.17.1 refuses each. Every refusal of that walk has a reason of its own, and
no reason advises calling the refused function from a plain function. And a method
decorator that names the method's parameters, of the method's kinds or not, and passes
them on without the object is refused by a rule of the gate's own wherever a body that
kept the object could run without failing; held by another wrapper under a pass-through,
it is not (Open). It is not a new review round.
Help make it better. Read the code, test this adapter against your own stack and tell us what you find. Reviews, bug reports and pull requests are all welcome: how to contribute, open issues. Please report a security gap privately, not in a public issue.
How it was tested
The in-depth review was four review rounds against openai==3.49.0, and it is the
project's own work. The threat model: the model is untrusted, and it chooses every tool
name, argument, call id, item type and status the gate reads. The application's own
code (its tools, its policy, the keywords it passes) is trusted but ordinary, so the
review also asked what an ordinary mistake in it does to the gate.
Each number below is printed by the command after it, from a clone with
requirements/adapter-openai.txt installed, with no API key and no network:
- A generated corpus, through both loops. 44,148 turns a model could send (258
single forms, and a grid of 43,890 crossing tool names, forms of the arguments, and
status, namespace and
finish_reasonvalues), each run through the plain and the audited loop from the same input. Counted: turns where the two loops disagree on what ran, where a tool ran under a name the application does not have, or where the audit entries are not one per call. None.python tools/review/openai/corpus.py --summary - A keyword matrix. 35,280 combinations of the recording keywords through
gate_function_calls,gate_tool_callsandjudge_and_run. Counted: combinations that raised after a tool had run, recorded a call they refused, or answered without running a tool the policy allowed. None.python tools/review/openai/keyword_matrix.py --summary - Mutation testing. 148 hand-written mutations, each switching off one check in a
copy of the package. A mutation is caught when at least one of the package's tests
then fails. All 148 are caught.
python tools/review/openai/mutate.py --summary - Probes written against the pinned SDK, among them tools decorated the ways applications decorate them. What a probe found is kept as a test.
What each round found. The findings of rounds one to three are fixed in 0.2.2, are in
the changelog, and are each
pinned by the test named, in
tests/test_openai_responses_gate.py:
- Round one: the plain loop ran a call the audited loop refused,
{"amount": NaN}past a policy written asamount > 100(test_a_number_that_is_not_json_or_not_finite_is_refused_before_the_policy). - Round two: a recording keyword without an audit log refused every call as a policy
error, though no policy had run (
test_no_audit_log_is_the_plain_gate). - Round three: the package still allowed a kernel without the check of a decorated
tool's wrappers (
test_the_package_requires_the_kernel_that_walks_every_callable), and asurface=the kernel does not record refused every call with no audit entry (test_a_recording_value_decide_would_refuse_raises_naming_the_keyword). - Round four: no changelog item. Its tests pin
judge_and_runcalled directly and the error raised when the stack runs out during the keyword check (test_judge_and_run_called_directly_answers_a_tool_error_only_when_asked,test_a_stack_that_runs_out_while_a_recording_value_is_checked_is_not_the_values_fault).
What this does not show: a large number of generated cases is not a proof. The corpus is the inputs the review thought of, the mutations are a hand-written list, and the numbers are for one SDK version. Recusal is a Beta project, not a finished or certified security product. The results are for the code as it stands: a test reruns a part of each where the SDK is installed, and the full runs are the commands above. What the gate refuses, and what it does not see lists what stays outside the gate whatever the tests say, and What a review consisted of has the method in full, the other findings of each round and what each script checks.
Compatibility
This package is outside the kernel's frozen perimeter (STABILITY.md, Integrations). Its
public names are the ones in recusal_openai.__all__. When an SDK release changes the
response types the gate reads, this package gets a release and the kernel does not.
A runnable offline demonstration, with SDK-validated responses and no API key, is
examples/openai_responses_gate.py
and
examples/openai_responses_audit.py.
More
An arrow means "depends on". No arrow leaves the kernel, so a framework's breaking change is answered by a release of that framework's adapter, not by a release of the kernel.
- Framework notes for the OpenAI API: the detail behind this page.
- All eight adapter packages and the kernel, which has zero runtime dependencies.
- Verifying a release: each release is built in CI, signed with Sigstore and published to PyPI by trusted publishing.
- Changelog, issues, security policy and support.
Licensed under Apache-2.0.
Metadata
Release files for recusal-openai 0.2.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| recusal_openai-0.2.3.tar.gz | 62.6 kB | With provenance | Details for recusal_openai-0.2.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| recusal_openai-0.2.3-py3-none-any.whl | Python 3 | none | any | Details for recusal_openai-0.2.3-py3-none-any.whl |
Total release size: 110.5 kB
Release files / recusal_openai-0.2.3.tar.gz
| Download URL | recusal_openai-0.2.3.tar.gz |
|---|---|
| Size | 62.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
fbb5c0af9037e0f4926636b33c8938b7aae4c94a508be7d0e85133fbc523790b
|
|
BLAKE2b-256 checksum How to use checksums |
f08a93215a719bbca2266579d9da09a64acaf0ad36486aedc5603daa5ff802fd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logRelease files / recusal_openai-0.2.3-py3-none-any.whl
| Download URL | recusal_openai-0.2.3-py3-none-any.whl |
|---|---|
| Size | 47.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
30678906b121a1555341ec97b9a12096c24345426ff747dd97b6bfd35e0259db
|
|
BLAKE2b-256 checksum How to use checksums |
722aeead6da3f9c1479a9472ec6343f272956f4649d833179023ea8127cbe01e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logSecurity for recusal-openai 0.2.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for recusal_openai-0.2.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.