OpenAI SDK Integration

Govern OpenAI function/tool calls with Nomotic using the governed_tool_call() dispatch pattern.

Installation

pip install nomotic openai

Pattern

governed_tool_call() wraps an OpenAI tool dispatch loop. When governance denies a tool call, it returns a [GOVERNANCE VETO] string instead of raising — letting the model explain the denial to the user.

Example

from nomotic.governed_agent import GovernedAgentBase, GovernanceVetoError
from typing import Any, Callable


def governed_tool_call(
    governed_agent: GovernedAgentBase,
    tool_name: str,
    tool_args: dict[str, Any],
    tool_fn: Callable[..., str],
) -> str:
    """Wrap an OpenAI function/tool call with governance.

    Returns a governance veto message (instead of raising) so the
    model can explain the denial to the user.
    """
    try:
        return governed_agent.governed_run(
            action_type=tool_name,
            target=tool_args.get("target", tool_name),
            parameters=tool_args,
            execute_fn=lambda: tool_fn(**tool_args),
        )
    except GovernanceVetoError as e:
        return (
            f"[GOVERNANCE VETO] Action '{tool_name}' was denied. "
            f"Verdict: {e.verdict}, UCS: {e.ucs_score:.3f}. "
            f"Record: {e.record_id}"
        )


# Usage in an OpenAI tool dispatch loop
import openai

client = openai.OpenAI()

TOOLS = {
    "lookup_customer": lambda customer_id: f"Customer {customer_id}: Jane Doe",
    "update_record": lambda record_id, value: f"Updated {record_id}",
}

# When OpenAI returns a tool call:
tool_call = message.tool_calls[0]
result = governed_tool_call(
    governed_agent=agent,
    tool_name=tool_call.function.name,
    tool_args=json.loads(tool_call.function.arguments),
    tool_fn=TOOLS[tool_call.function.name],
)

The model receives the veto message as a tool result and can explain to the user why the action was blocked, rather than silently failing.

Last updated