> ## Documentation Index
> Fetch the complete documentation index at: https://www.sentrial.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI Agents SDK Integration

> One line of setup to automatically mirror every OpenAI Agents SDK run into a Sentrial session — LLM calls, tool calls, handoffs, and guardrails.

> [!NOTE]
>
> **Available in both SDKs.** Python (`pip install 'sentrial[openai-agents]'`) and TypeScript (`@sentrial/sdk` with `@openai/agents` as an optional peer). Both register a trace processor with the Agents SDK's tracing pipeline — registration is additive, so the default OpenAI-dashboard exporter keeps running alongside.

## What Gets Tracked Automatically

> **Sessions**
>
> One session per agent run (trace) — agent name from the root agent span, aggregated tokens and cost, final output.

> **LLM Calls**
>
> Every generation/response span as a per-call event — model, prompt/completion tokens, auto-calculated cost, duration.

> **Tool Calls**
>
> Each function span with the tool name, parsed arguments, result, and errors.

> **Handoffs**
>
> Agent-to-agent handoffs recorded as decisions ("Handoff from X to Y").

> **Guardrails**
>
> A triggered guardrail is recorded as an error (and fails the session); a passed guardrail is recorded as a decision.

> **Errors**
>
> A failed run's root agent span error becomes the session's failure reason.

## Installation

```bash Python theme={null}
pip install 'sentrial[openai-agents]'
# The extra installs openai-agents>=0.1.0,<1.0.0 — the tested/supported window
```

```bash TypeScript theme={null}
npm install @sentrial/sdk @openai/agents
# @openai/agents is an optional peer dependency (supported range: >=0.1.0 <1.0.0)
```

## Quick Start

One function call. Then run your agents exactly like before.

```python Python theme={null}
import sentrial
from agents import Agent, Runner
from sentrial.openai_agents import instrument_openai_agents

sentrial.configure(api_key="sentrial_live_xxx")
instrument_openai_agents(user_id="user_123")

agent = Agent(name="Assistant", instructions="You are a helpful assistant")
result = Runner.run_sync(agent, "Write a haiku about recursion.")
# The run is now a Sentrial session with LLM events, tool calls, handoffs.
```

```typescript TypeScript theme={null}
import { Agent, run, addTraceProcessor } from '@openai/agents';
import { sentrial, instrumentOpenAIAgents } from '@sentrial/sdk';

sentrial.configure({ apiKey: process.env.SENTRIAL_API_KEY });
instrumentOpenAIAgents({ addTraceProcessor }, { userId: 'user_123' });

const agent = new Agent({ name: 'Assistant', instructions: 'Be helpful.' });
const result = await run(agent, 'Write a haiku about recursion.');
// The run is now a Sentrial session with LLM events, tool calls, handoffs.
```

> [!NOTE]
>
> **TypeScript:** `@sentrial/sdk` never imports `@openai/agents` itself — you hand it the SDK's `addTraceProcessor` (or the whole module namespace: `import * as agents from '@openai/agents'; instrumentOpenAIAgents(agents, options)`). **Python:** `instrument_openai_agents()` is the only entry point that imports the `openai-agents` package.

## Configuration Options

```python Python theme={null}
instrument_openai_agents(
    client=my_client,           # optional — explicit SentrialClient;
                                # defaults to the module-level client from sentrial.configure()
    default_agent="my-agent",   # optional — explicit agent/event name
                                # (defaults to the root agent span's name per run)
    user_id="user_123",         # optional — default "anonymous"
    extra_metadata={"env": "prod"},  # optional — merged into every session
)
```

```typescript TypeScript theme={null}
instrumentOpenAIAgents(agents, {
  client: myClient,           // optional — explicit SentrialClient;
                              // defaults to an env-configured client (SENTRIAL_API_KEY)
  defaultAgent: 'my-agent',   // optional — explicit agent/event name
                              // (defaults to the root agent span's name per run)
  userId: 'user_123',         // optional — default 'anonymous'
  extraMetadata: { env: 'prod' },  // optional — merged into every session
});
```

> [!TIP]
>
> **Idempotent registration** — Calling `instrument_openai_agents()` / `instrumentOpenAIAgents()` again for the same client returns the first registered processor instead of registering a duplicate (which would mirror every run into two sessions). The first duplicate call logs a warning. Keep the returned processor if you plan to call `shutdown()` or `force_flush()` / `forceFlush()` yourself.

## How Runs Map to Sessions

| OpenAI Agents SDK | Sentrial |
| - | - |
| Trace (one agent run) | Session — agent/event name from the root agent span (falling back to the trace's workflow name), session title from the trace name |
| Generation / response spans | Per-call LLM events (`llm:{model}`) with prompt/completion tokens, auto-calculated cost, and duration from the span timestamps |
| Function spans | Tool calls with name, parsed arguments, result, and errors |
| Handoff spans | Decisions ("Handoff from X to Y") |
| Guardrail spans | Error when triggered (fails the session), decision when passed |
| Trace `group_id` | `convoId` — the Agents SDK's conversation grouping links sessions into a thread |
| Trace end | `finish()` — aggregated tokens/cost, last LLM output as the session output, failure state from root agent span errors or triggered guardrails |

Additional mapping notes:

* Session metadata carries `integration: "openai-agents"` plus the OpenAI `trace_id`, so you can cross-reference the run in the OpenAI traces dashboard.
* The session's own input is not populated — the Agents SDK does not expose the run input on the trace object; the first user message rides in each generation span's LLM event instead.
* `finish()` records `llm_calls`, `tool_calls`, and `handoffs` as custom metrics.
* Speech, transcription, MCP-list, and custom spans are ignored — they carry no fields Sentrial models.

## Don't Combine with `wrap_openai` / `wrapOpenAI`

> [!WARNING]
>
> `wrap_openai()` / `wrapOpenAI()` wrap a **raw** OpenAI client so each LLM call is tracked inside a session you manage with `begin()`. This integration instead observes the OpenAI **Agents SDK** runtime from the outside — each agent run becomes a full Sentrial session automatically. If you use the Agents SDK, prefer this integration; do **not** combine both on the same run, or LLM calls will be double-counted.

## Batching, Explicit Clients & Short-Lived Processes

The Agents SDK invokes processor callbacks inline on the run's path, so an explicit client with **batching enabled** is recommended — each `track` call then enqueues and returns immediately instead of waiting on a network round-trip per span:

```python Python theme={null}
from sentrial import SentrialClient
from sentrial.openai_agents import SentrialTraceProcessor
from agents import add_trace_processor

client = SentrialClient(api_key="sentrial_live_xxx", batching=True)
add_trace_processor(SentrialTraceProcessor(client=client, user_id="user_123"))
```

```typescript TypeScript theme={null}
import { addTraceProcessor } from '@openai/agents';
import { SentrialClient, SentrialOpenAIAgentsProcessor } from '@sentrial/sdk';

const client = new SentrialClient({
  apiKey: process.env.SENTRIAL_API_KEY,
  batching: { enabled: true },
});
addTraceProcessor(new SentrialOpenAIAgentsProcessor({ client, userId: 'user_123' }));
```

At application stop, the Agents SDK calls the processor's `shutdown()`, which finishes any still-open sessions as interrupted (failure reason "Trace not ended before processor shutdown") and flushes the client's event queue. In short-lived processes (scripts, serverless functions), don't exit before queued events are sent — call `force_flush()` / `forceFlush()` on the processor (or `flush()` on the client) after your last run when batching is enabled.

Tracking is fail-safe by design: every processor callback is containment-wrapped, so a Sentrial error is logged and swallowed — it never crashes your agent run.

## Next Steps

> **[Python SDK Reference](https://www.sentrial.com/docs/sdk/python.md)**
>
> Full SDK documentation with all methods and options.

> **[TypeScript SDK Reference](https://www.sentrial.com/docs/sdk/typescript.md)**
>
> Full SDK documentation with all methods and options.

> **[Google ADK](https://www.sentrial.com/docs/integrations/google-adk.md)**
>
> The same Plugin-style integration for Google's Agent Development Kit.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.