OpenAI SDK Integration

The OpenAI SDK powers agents built on GPT-4, GPT-4o, and OpenAI’s Assistants API. The managed-agents package wraps governance around every tool call your OpenAI agent makes before it executes.

Installation

pip install managed-agents openai

Governing OpenAI function calls

When OpenAI returns a tool call, govern it before executing the corresponding function:

python

from managed_agents import NomoticHarness, GovernanceDenied
from openai import AsyncOpenAI
import json

harness = NomoticHarness(
    api_key="nm_live_...",
    agent_id="nmc-...",
    platform="openai",
)

client = AsyncOpenAI()

async def run_agent(user_message: str):
    messages = [{"role": "user", "content": user_message}]

    response = await client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=your_tool_definitions,
    )

    for choice in response.choices:
        if choice.finish_reason == "tool_calls":
            for tool_call in choice.message.tool_calls:
                tool_name  = tool_call.function.name
                tool_input = json.loads(tool_call.function.arguments)

                try:
                    # Govern before executing
                    await harness.govern(tool_name, tool_input)
                    result = await execute_tool(tool_name, tool_input)
                except GovernanceDenied as e:
                    result = f"Tool call blocked by governance: {e}"

                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": result,
                })

OpenAI Assistants API

For the Assistants API, govern each tool call in your run polling loop:

python

async def process_tool_calls(run, thread_id):
    tool_outputs = []

    for tool_call in run.required_action.submit_tool_outputs.tool_calls:
        tool_name  = tool_call.function.name
        tool_input = json.loads(tool_call.function.arguments)

        try:
            await harness.govern(tool_name, tool_input)
            output = await execute_tool(tool_name, tool_input)
        except GovernanceDenied as e:
            output = f"Blocked: {e}"

        tool_outputs.append({
            "tool_call_id": tool_call.id,
            "output": output,
        })

    return tool_outputs

Platform tagging

The platform="openai" tag in your harness lets you filter OpenAI agent evaluations separately from other frameworks in Governance → Audit Trail. If you have both GPT-4 and Claude agents, each shows up under its own platform filter.

Fail open vs fail closed

For production OpenAI agents, consider your failure mode carefully. The default fail_open=True means a Nomotic service outage allows tool calls through. For high-stakes agents:

python

harness = NomoticHarness(
    api_key="nm_live_...",
    agent_id="nmc-...",
    platform="openai",
    fail_open=False,   # Block on service error
)

Was this article helpful?

On this page