Metadata-Version: 2.4
Name: recusal-openai
Version: 0.2.3
Summary: Recusal gate for the OpenAI API: judge every function call of a Responses or Chat Completions loop you own, refuse before it runs, and optionally put each decision on a hash-chained audit log.
Project-URL: Homepage, https://recusal.io
Project-URL: Documentation, https://github.com/philpaz/recusal/tree/main/adapters/openai
Project-URL: Repository, https://github.com/philpaz/recusal
Project-URL: Issues, https://github.com/philpaz/recusal/issues
Project-URL: Changelog, https://github.com/philpaz/recusal/blob/main/CHANGELOG.md
Author-email: Philip Paz <philip.paz@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agent-governance,ai-agents,guardrails,openai,recusal,tool-use
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: openai<4,>=3.49.0
Requires-Dist: recusal<1,>=0.17.1
Description-Content-Type: text/markdown

<p align="center">
  <a href="https://recusal.io">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip.png">
      <img alt="recusal, deterministic governance for AI agents" src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip-light.png" width="880">
    </picture>
  </a>
</p>

# recusal-openai

[![Website](https://img.shields.io/badge/website-recusal.io-2453c4)](https://recusal.io)
[![PyPI](https://img.shields.io/pypi/v/recusal-openai)](https://pypi.org/project/recusal-openai/)
[![CI](https://github.com/philpaz/recusal/actions/workflows/ci.yml/badge.svg)](https://github.com/philpaz/recusal/actions/workflows/ci.yml)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/philpaz/recusal/badge)](https://scorecard.dev/viewer/?uri=github.com/philpaz/recusal)
![python](https://img.shields.io/badge/python-3.10%2B-blue)
![license](https://img.shields.io/badge/license-Apache--2.0-green)

The [Recusal](https://github.com/philpaz/recusal) gate for a loop you own on the
[OpenAI API](https://platform.openai.com/docs/api-reference): 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](https://github.com/philpaz/recusal#write-the-policy-two-postures-one-principle)
covers the two postures, allowlist and deny-list.

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/gate-position.svg">
    <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">
  </picture>
</p>

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:

```bash
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

```python
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

```python
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:

```python
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`, `Infinity` and `-Infinity`
    are 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_call` item whose `status` is
    anything but `completed` (`in_progress`, `incomplete`); an item with no `status`
    passes. Every function call of a response whose own `status` is anything but
    `completed` (`incomplete`, `failed`, `cancelled`, `in_progress`, `queued`, a value
    a later SDK adds), the finished items in it included; a response with no `status`
    passes. Every tool call of a Chat Completions choice whose `finish_reason` is
    anything but `stop`,
    `tool_calls` or `function_call`: that is `length` (the message was cut off at the
    token limit), `content_filter` and a missing `finish_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_call` item that carries a
    non-empty `namespace` is 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 def` tool, a generator
    function, a `functools.lru_cache` tool handed a list or an object, and a tool whose
    signature cannot be judged by name: see the next point.
- **Which tools the gate can judge.** A tool is a plain function, a bound method or a
  `functools.lru_cache` of one, whose every parameter can be passed by name
  and is annotated with a supported data type: `str`, `int`, `float`, `bool`, `Optional`
  of a supported type (also written `T | None`), `list[T]`, and `dict[str, T]`, where
  `T` is a supported type in turn (`list[dict[str, int]]` is supported). Every default
  must be JSON data. A tool cached with `functools.lru_cache` (or `functools.cache`)
  needs arguments the cache can hash: a call that hands it a list or an object, for a
  `list[T]` or `dict[str, T]` parameter or in place of a `str`, is refused with a reason
  before the policy runs. Give a cached tool `str`, `int`, `float` and `bool` parameters
  only. A cache behind a wrapper of your own is not seen: there such a call raises
  `TypeError` as any tool that raises does (see `answer_tool_errors` above). Everything
  else is refused with a reason, among them:
  - a parameter with no annotation, `Any`, `Literal[...]`, a union of two types such as
    `int | float`, a bare `list` or `dict`, an `Enum`, `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.wraps` wrapper that adds a parameter of its own to the function it
    wraps, and one that takes `*args, **kwargs` and 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 `str` and check it against the allowed values in
  place of `Literal` or an `Enum`, pick `float` in place of `int | float`, write
  `dict[str, str]` in place of `dict`, and replace a `functools.partial` or 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.
- **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 `ValueError` before 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 legacy `function_call` field (alone or beside `tool_calls`; the gate reads
  `tool_calls` only, so declare functions with `tools`, not `functions`), 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 (`TypeError` naming it, whether or not the turn has calls): a
  mistyped one, `fail_closed`, `tool_use_id`, `surface`, `actor` or `control` with a
  value when `audit` is not passed at all, and `audit` with a log and no `surface`. A
  `surface` or `control` the kernel would not record raises `ValueError` naming 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.wraps` wrapper 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:

  ```python
  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=true` is judged with `dry_run` true and `delete_tree` runs with
  `dry_run` false. 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_cache` named again for another function, whose function cannot be
    told from what the cache refers to;
  - a `functools.singledispatch` function or `singledispatchmethod` on 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.partialmethod` over 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.proxy` anywhere 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.partial` as the tool, and a tool whose annotations
    `typing.get_type_hints` cannot 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.wraps`
  wrappers and `functools.lru_cache` applied directly, a decorator written as
  `functools.wraps(f)(functools.partial(helper, f))`, `@functools.wraps(f)` written above
  `@functools.lru_cache`, and a class-based decorator built with
  `functools.update_wrapper` (on a method, a class-based decorator with no `__get__` and
  a `functools.partial` do not bind the object, and its `self` is 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.
- **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)`
  (`_judge` in `_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`,
  or `cls` for a class method) and the positional arguments of a `functools.partial`.
  The tools of
  [`examples/openai_responses_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/openai_responses_gate.py)
  are 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 a `TypeError`, and nothing would run: under this gate such a tool, refused, either
  runs correctly or fails. Such a `TypeError` leaves the gate as any tool's exception
  does (see `answer_tool_errors` above). 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 pass `self` on), 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 a `TypeError`, 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)` under
  `functools.wraps(fn)`, over `def 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 ran `self="t"`,
  `table=5`, `limit=10` under 0.2.2. The gate refuses it by a rule of its own, after the
  one `recusal-pydantic-ai` has: 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")` over `def transfer(self, account:
    str, amount: int = 7, memo: str = "m0")`, which, passing the values on by position,
    ran `self="ACCT"`, `account=55`, `amount="MEMO"` for judged `account="ACCT"`,
    `amount=55`, `memo="MEMO"`, also over a required `amount`); 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 taking `self`), 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 a `TypeError`, 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 `*args` and `**kwargs` and 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).
- **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 `Response` or `ChatCompletion`.
  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_call` and the others in
  `HOSTED_RECORD_TYPES`, which also holds `compaction`, the provider's summary of earlier
  context). By default such an item raises like any other unhandled one. Pass
  `allow_hosted_records=True` to 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 whose `status` says 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_request` for your loop to answer. This gate does not judge it:
  it raises, with or without `allow_hosted_records`, so the call is never approved
  through this gate.
- **Not read: `async` and `caller`.** A Responses `function_call` item can be marked
  `async` and can carry a `caller` of type `program`. 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 def` or 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 `recusal` 0.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__`. Call `functools.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 as
    `functools.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)` under `functools.wraps(execute)`,
    over `def execute(database="main", sql: str = "SELECT 1", note: str = "")`), or
    passes a value of its own there (`return search(self.tenant, *args, **kwargs)` over
    `def 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.
- New with `recusal` 0.17.0:
  - A `weakref.proxy` of 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.proxy` of 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__` (any `functools.wraps` decorator, any
    `functools.lru_cache`). Call `functools.update_wrapper(self, fn)` in its `__init__`.
  - An object that shows another class than its own and holds a `__wrapped__` (the shape
    of a `wrapt` proxy), whose own `__call__` names the parameters and hands each on in
    order. Give its `__call__` only `*args` and `**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.
- New with `recusal` 0.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)` over `def run_sql(self, ...)`, or `self` over a class method's `cls`). Take
    the object under the name the method has for it (`self`, or `cls` for a class
    method) and hand it on by position.
  - A held `functools.wraps` wrapper that does the same (`def forward(receiver, *args,
    **kwargs): return run(receiver, *args, **kwargs)` over `def run(self, ...)`, called
    by a pass-through). Take the object in `*args` with 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.
- 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 as `self`
  and hands it on, above two or more class-based decorators or decorators written as
  `functools.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 `*args` and `**kwargs` and 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)` holding `def
  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's `self` is refused. Take the object in `*args` in the held
  wrapper (`def inner(*args, **kwargs): return fn(*args, **kwargs)`).
- New with `recusal` 0.16.0, missed above: a class-based decorator that binds as a method
  (its class defines `__get__`) under `functools.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)` over
  `def 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 under
  `classmethod`. 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 a `TypeError` out of the
  gate (or is answered as a tool that raised, with `answer_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 a
  `TypeError`. Pass `self` on in the decorator.
- **A held method wrapper that drops the object, under a pass-through.** `def
  outer(*args, **kwargs): return inner(*args, **kwargs)`, holding `def inner(self,
  account, amount=7, memo="m0"): return fn(account, amount, memo)` over `def
  transfer(self, account: str, amount: int = 7, memo: str = "m0")`: the kernel's walk
  reads it, since the held wrapper takes the object as `self`, 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: judged `account="ACCT"`, `amount=55`,
  `memo="MEMO"`, it ran `self="ACCT"`, `account=55`, `amount="MEMO"`. The same held
  under `def outer(self, *args, **kwargs)` is refused (above). Pass the object on in the
  held wrapper, or give it only `*args` and `**kwargs`.
- **The same, where the place the object leaves has a default.** A facade that drops its
  object in `*args` over `def execute(database: str = "main", sql: str = "SELECT 1",
  note: str = "")` is gated, and called by keyword `database` runs 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.wraps` that takes the object under another name and
  drops it** (`def forward(receiver, *args, **kwargs): return run(*args, **kwargs)`,
  called by a `functools.wraps` pass-through): the kernel reads it by design, since every
  correct held wrapper written without `functools.wraps` has the same shape. It is gated,
  and this gate's call raises a `TypeError` (over a facade whose first parameter has a
  default, that parameter runs at its default). The same with `functools.wraps` is
  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 a `weakref.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](https://github.com/philpaz/recusal/blob/main/SECURITY.md#things-worth-knowing)).

## 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](https://github.com/philpaz/recusal#project-status).

**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](https://github.com/philpaz/recusal/blob/main/CONTRIBUTING.md), [open issues](https://github.com/philpaz/recusal/issues).
Please report a security gap [privately](https://github.com/philpaz/recusal/security/advisories/new), 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_reason` values), 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_calls` and `judge_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](https://github.com/philpaz/recusal/blob/main/CHANGELOG.md), and are each
pinned by the test named, in
[`tests/test_openai_responses_gate.py`](https://github.com/philpaz/recusal/blob/main/tests/test_openai_responses_gate.py):

- Round one: the plain loop ran a call the audited loop refused, `{"amount": NaN}` past
  a policy written as `amount > 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 a `surface=` 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_run` called 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](https://github.com/philpaz/recusal/blob/main/adapters/openai/README.md#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](https://github.com/philpaz/recusal/blob/main/docs/REVIEW.md#recusal-openai)
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`](https://github.com/philpaz/recusal/blob/main/examples/openai_responses_gate.py)
and
[`examples/openai_responses_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/openai_responses_audit.py).

## More

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/adapter-map.svg">
    <img alt="One kernel, eight adapters. Each adapter package depends on recusal: recusal-crewai, recusal-google-adk, recusal-langchain, recusal-langgraph, 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">
  </picture>
</p>

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](https://github.com/philpaz/recusal/blob/main/docs/FRAMEWORKS.md#openai-api-your-own-loop):
  the detail behind this page.
- [All eight adapter packages](https://github.com/philpaz/recusal/tree/main/adapters) and
  [the kernel](https://github.com/philpaz/recusal), which has zero runtime dependencies.
- [Verifying a release](https://github.com/philpaz/recusal/blob/main/docs/VERIFY.md#adapter-packages):
  each release is built in CI, signed with Sigstore and published to PyPI by trusted
  publishing.
- [Changelog](https://github.com/philpaz/recusal/blob/main/CHANGELOG.md),
  [issues](https://github.com/philpaz/recusal/issues),
  [security policy](https://github.com/philpaz/recusal/blob/main/SECURITY.md) and
  [support](https://github.com/philpaz/recusal/blob/main/SUPPORT.md).

Licensed under Apache-2.0.
