Skip to content

OpenAI Agents

Turn an OpenAI Agents SDK run into run events: handoffs, tool calls and approvals.

OpenAI Agents SDK

The adapter turns the events of run(agent, input, { stream: true }) into run events. The first agent_updated_stream_event brings in You and the agent. A handoff_occurred item ends the current agent's task handed off to the next one (the same handoffs AgentHandoff draws), and that agent starts its own task. tool_called and tool_output become a call to a tool actor (brand tools such as stripe_create_refund share one actor with the brand's logo). The SDK's "An error occurred while running the tool" text fails the call. Tools made with agent.asTool() can be drawn as agents.

tool_approval_requested becomes an approval and the agent shows as blocked. The run pauses there: applyDecisions(state, interruptions) calls state.approve / state.reject for what was decided in the UI, and the resumed stream continues the same run. Usage from each response_done becomes spend when you pass a price, otherwise a token count. A guardrail tripwire passed to fail(err) shows as a tripped guardrail and a denied record.

It has no runtime import of @openai/agents: it declares the event fields it reads, so the registry item depends on Knowns core only.

Replay a recorded run

Hand-written SDK events: Triage reads the Zendesk ticket and hands off to Billing, which lists Stripe charges (an invoice lookup fails) and asks before refunding. They're played through the adapter into AgentGraph, AgentMonitor and AgentHandoff. Nothing leaves the page.

Preview

Stream it from a Next.js route

app/api/support/route.ts
// app/api/support/route.ts: runs the agents on the server, streams Knowns events (NDJSON)
import { Agent, run, tool, type RunState } from "@openai/agents";
import { z } from "zod";
import { createOpenAIAgentsAdapter, toReadableStream, type OpenAIAgentsAdapter } from "@/lib/knowns/adapters/openai-agents";

const createRefund = tool({
  name: "stripe_create_refund",
  description: "Refund a charge.",
  parameters: z.object({ charge: z.string(), amount: z.number() }),
  needsApproval: true, // the run pauses; Allow / Decline happens in the UI
  execute: async ({ charge, amount }) => stripe.refunds.create({ charge, amount }),
});

const billing = new Agent({ name: "Billing", model: "gpt-5-mini", instructions: "…", tools: [listCharges, createRefund] });
const triage = Agent.create({ name: "Triage", instructions: "Route billing questions to Billing.", handoffs: [billing] });

// Kept per conversation so a decision can resume the paused run.
const sessions = new Map<string, { adapter: OpenAIAgentsAdapter; state?: RunState<any, any> }>();

export async function POST(req: Request) {
  const { id, input } = await req.json();
  const adapter = createOpenAIAgentsAdapter({
    prompt: input,
    pricing: { "gpt-5": { input: 1.25, output: 10, cacheRead: 0.125 }, "gpt-5-mini": { input: 0.25, output: 2, cacheRead: 0.025 } },
  });
  const result = await run(triage, input, { stream: true });
  sessions.set(id, { adapter, state: result.state });
  // A StreamedRunResult is an AsyncIterable of RunStreamEvents.
  return new Response(toReadableStream(result, { adapter }), { headers: { "content-type": "application/x-ndjson" } });
}

// app/api/support/[id]/resume/route.ts: called after Allow / Deny (sent with forwardDecisions)
export async function POST_resume(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const s = sessions.get((await params).id)!;
  const event = await req.json(); // { type: "approval.resolve", id, decision }
  s.adapter.emit(event);
  // Apply what the UI decided to the paused RunState, then resume streaming into the same run.
  s.adapter.applyDecisions(s.state!, s.state!.getInterruptions());
  if (s.adapter.pendingApprovals().length) return new Response(null, { status: 204 });
  const result = await run(triage, s.state!, { stream: true });
  s.state = result.state;
  return new Response(toReadableStream(result, { adapter: s.adapter }), { headers: { "content-type": "application/x-ndjson" } });
}
components/support-run.tsx
// components/support-run.tsx: any Knowns UI component, fed by the stream
"use client";
import { useEffect } from "react";
import { useAgentRun } from "@/lib/knowns/run";
import { connectEventStream, forwardDecisions } from "@/lib/knowns/adapters/openai-agents";
import { AgentGraph } from "@/components/ui/knowns/agent-graph/agent-graph";
import { AgentHandoff } from "@/components/ui/knowns/agent-handoff/agent-handoff";

export function SupportRun({ id, input }: { id: string; input: string }) {
  const run = useAgentRun();

  useEffect(() => {
    const ctl = new AbortController();
    connectEventStream(run, "/api/support", { signal: ctl.signal, init: { method: "POST", body: JSON.stringify({ id, input }) } });
    // Each Allow / Deny resumes the paused run; its events stream into the same run.
    const stop = forwardDecisions(run, async (event) => {
      const res = await fetch(`/api/support/${id}/resume`, { method: "POST", body: JSON.stringify(event) });
      if (res.status === 200) connectEventStream(run, res, { signal: ctl.signal });
    });
    return () => { ctl.abort(); stop(); };
  }, [run, id, input]);

  return (
    <>
      <AgentGraph run={run} layout="center" />
      <AgentHandoff run={run} />
    </>
  );
}
TypeScript
// Same process (a script, a test): skip the stream
import { adaptStream } from "@/lib/knowns/adapters/openai-agents";

const result = await run(triage, "I was charged twice", { stream: true });
const adapter = await adaptStream(knownsRun, result, { prompt: "I was charged twice" });
// Guardrail tripwires thrown by the run show as a tripped guardrail instead of rethrowing.

Installation is part of Pro

Pro components install from a licensed registry. The live preview stays open to everyone.

createOpenAIAgentsAdapter(opts)
{ run?, you?, youLabel?, prompt?, agents?, agentTools?, pricing?, now? }
Defaultnew run, "you"
Returns { run, push, end, fail, emit, onEvent, resolve, waitForApproval, pendingApprovals, applyDecisions }.
push(event)
RunStreamEvent
agent_updated_stream_event, run_item_stream_event (tool_called, tool_output, handoff_requested, handoff_occurred, message_output_created, reasoning_item_created, tool_approval_requested), raw_model_stream_event (output_text_delta, response_done usage). Unknown events are ignored.
end(reason?)
string
The stream ended. With an approval pending, the run stays paused (agent blocked, calls open); a reason fails it.
fail(error)
unknown
Guardrail tripwires (Input/Output/Tool…GuardrailTripwireTriggered) show as a tripped guardrail and a denied record; other errors fail the run.
agents
Record<agentName, { label?, model?, description? }>
Labels, and the model for the logo and pricing when the agent's model is not a plain string.
agentTools
Record<toolName, { label?, model? }>
Tools made with agent.asTool(): their calls go to an agent actor.
pricing
Record<modelId, { input, output, cacheRead? }>
USD per million tokens. Each response_done usage adds to its agent's spend (cached input at cacheRead). Without it: "Done · 1.8k tokens".
resolve / waitForApproval
(callId, approved, message?) / (callId, signal?)
Decide on the server, or wait for a decision made anywhere. Abort denies.
applyDecisions(state, interruptions)
RunState-like, interruption items
Calls state.approve(item) or state.reject(item, { message }) for each decided interruption. Returns how many were applied.
adaptStream(run, result, opts?)
AsyncIterable of events
In-process: pushes the whole stream, then end(). Guardrail tripwires are mapped, other errors rethrown.
toEventStream / toReadableStream(result, { adapter?, format? })
AsyncIterable → lines / bytes
Defaultformat "ndjson"
Server: Knowns event lines (NDJSON or SSE). Same bridge as the other adapters.

Need help?

Stuck on OpenAI Agents, or found something off? We read every message.