Skip to content

00Integration guide

OpenAI Agents SDK

A RunHooks subclass that records every tool call the runner executes.

Walkthrough · recorded against a local Ovelin

The runner calls RunHooks.on_tool_start and on_tool_end around every function tool it executes. Recording there means every tool call is on the record whether or not the model mentions it.

Prerequisites

  • An OpenAI API key in OPENAI_API_KEY.
  • Python 3.10+ and the Python Ovelin client from the Python guide.

1. Get an API key

  1. In Ovelin, open Settings → API keys.
  2. Under Ingest key, create a key and copy it. It is shown once; Ovelin keeps only a hash.
  3. Copy the Organization ID from the same page.

Put all three values in your environment, not in code:

sh
export OVELIN_URL="https://your-ovelin-host"   # http://localhost:3000 for a local instance
export OVELIN_ORG_ID="your-organization-id"
export OVELIN_API_KEY="agl_live_…"

An organization key can report for any agent. For production, give each agent its own key under Settings → API keys → Agent keys: a leaked agent key can then only write as that one agent, and you can revoke it alone.

2. Install

sh
pip install openai-agents requests

3. Minimal working example

examples/python/openai_agents.py
"""An OpenAI Agents SDK agent whose every tool call is recorded in Ovelin.

RunHooks fire around each tool the runner executes, so the record does not
depend on the model choosing to report anything.
"""

import asyncio
import json
import time

from agents import Agent, RunHooks, Runner, function_tool

from ovelin import RUN_ID, log_event

AGENT = "support-agent"


@function_tool
def lookup_order(customer_id: str) -> str:
    """Find a customer's most recent order."""
    return f"{customer_id}: order #8812, EUR 42.00, delivered"


@function_tool
def refund_order(customer_id: str, amount: float) -> str:
    """Refund part or all of a customer's latest order."""
    return f"Refunded EUR {amount:.2f} to {customer_id}"


class OvelinHooks(RunHooks):
    """Times each tool call and records it once it returns."""

    def __init__(self) -> None:
        self.started: dict[str, float] = {}

    async def on_tool_start(self, context, agent, tool) -> None:
        self.started[getattr(context, "tool_call_id", tool.name)] = time.monotonic()

    async def on_tool_end(self, context, agent, tool, result) -> None:
        call_id = getattr(context, "tool_call_id", tool.name)
        took = time.monotonic() - self.started.pop(call_id, time.monotonic())
        await asyncio.to_thread(
            log_event,
            agent.name,
            tool.name,
            actor="support@example.com",
            data_accessed=["customer_pii", "financial_data"],
            metadata={
                "tool_input": json.loads(getattr(context, "tool_arguments", "{}") or "{}"),
                "call_id": call_id,
                "duration_ms": round(took * 1000),
            },
        )


agent = Agent(
    name=AGENT,
    instructions="Look up the customer's order, then refund it.",
    tools=[lookup_order, refund_order],
)


async def main() -> None:
    result = await Runner.run(agent, "Customer cus_1042 wants a refund of EUR 42.", hooks=OvelinHooks())
    print(result.final_output)
    print(f"Recorded in Ovelin under run {RUN_ID}")


asyncio.run(main())

Pass hooks=OvelinHooks() to every Runner.run (or run_sync, run_streamed). To record only one agent's tools, subclass AgentHooks instead and set it as agent.hooks.

4. Run it

sh
cd examples/python
python openai_agents.py

5. Check it in Ovelin

  1. Open Activity. The newest rows are the events you just sent, each with a sequence number and a seal.
  2. Click one. The detail panel shows the payload as received; Recompute seal checks its seal again.
  3. One event per tool call: lookup_order, then refund_order, under the agent name support-agent. Open Agents: an agent name Ovelin had not seen before is registered automatically, without an owner. Give it one so someone is accountable for it.

To confirm nothing was altered later, open Integrity. It recomputes every seal and every link between records, and reports Trail intact.

Common errors

ResponseCauseFix
401 Invalid API keyThe key is wrong, revoked, or belongs to another organization.Create a key in Settings → API keys and check OVELIN_ORG_ID is the same organization's.
401 Missing API key (use Authorization: Bearer <key>)The Authorization header was not sent.Send Authorization: Bearer $OVELIN_API_KEY. The key never goes in the body.
422 Payload must include a 'source' fieldThe JSON has no source.Add "source": "custom" (or n8n, make_com, openai_api, zapier).
422 Invalid option: expected one of "success"|"failure"|"unknown"outcome has another value, such as warning.Use success, failure or unknown.
400 Invalid organization idOVELIN_ORG_ID is not the organization's UUID.Copy the Organization ID from Settings → API keys.
429 Rate limit exceededMore than 600 events a minute for one organization.Retry after the Retry-After header. To send many events, use the batch endpoint (up to 100 per request).
No events, run finishedhooks= not passed to this Runner.run call.Hooks are per run. Pass them on every call, or wrap Runner.run once in your code.

How this guide is tested

Every code block above is copied from examples/python/openai_agents.py by node scripts/sync-guide-snippets.mjs, and pnpm examples:test runs it against a local Ovelin and checks the events were sealed. The model is replaced by a local scripted stand-in (examples/_testing/scripted-model.mjs) that calls the tools in a fixed order, so the test needs no provider key; with a real key, unset ANTHROPIC_BASE_URL/OPENAI_BASE_URL and the same code talks to the provider.