リアルタイムトランスポート
デフォルトのトランスポート層
Section titled “デフォルトのトランスポート層”WebRTC 接続
Section titled “WebRTC 接続”既定のトランスポート層は WebRTC を使用します。音声はマイクから録音され、自動的に再生されます。
独自のメディアストリームや audio 要素を使用するには、セッション作成時に OpenAIRealtimeWebRTC インスタンスを指定します。
import { RealtimeAgent, RealtimeSession, OpenAIRealtimeWebRTC } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Greeter', instructions: 'Greet the user with cheer and answer questions.',});
async function main() { const transport = new OpenAIRealtimeWebRTC({ mediaStream: await navigator.mediaDevices.getUserMedia({ audio: true }), audioElement: document.createElement('audio'), });
const customSession = new RealtimeSession(agent, { transport });}WebSocket 接続
Section titled “WebSocket 接続”WebRTC の代わりに WebSocket 接続を使用するには、セッション作成時に transport: 'websocket' または OpenAIRealtimeWebSocket のインスタンスを渡します。これはサーバーサイドのユースケース、たとえば Twilio で電話エージェントを構築する場合に有効です。
import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Greeter', instructions: 'Greet the user with cheer and answer questions.',});
const myRecordedArrayBuffer = new ArrayBuffer(0);
const wsSession = new RealtimeSession(agent, { transport: 'websocket', model: 'gpt-realtime',});await wsSession.connect({ apiKey: process.env.OPENAI_API_KEY! });
wsSession.on('audio', (event) => { // event.data is a chunk of PCM16 audio});
wsSession.sendAudio(myRecordedArrayBuffer);任意の録音/再生ライブラリを使用して、元 PCM16 音声バイトを処理します。
Cloudflare Workers(workerd)に関する注意
Section titled “Cloudflare Workers(workerd)に関する注意”Cloudflare Workers やその他の workerd ランタイムでは、グローバルな WebSocket コンストラクターを使って外向きの WebSocket を開くことはできません。extensions パッケージの Cloudflare トランスポートを使用してください。これは内部で fetch() ベースのアップグレードを実行します。
import { CloudflareRealtimeTransportLayer } from '@openai/agents-extensions';import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'My Agent',});
// Create a transport that connects to OpenAI Realtime via Cloudflare/workerd's fetch-based upgrade.const cfTransport = new CloudflareRealtimeTransportLayer({ url: 'wss://api.openai.com/v1/realtime?model=gpt-realtime',});
const session = new RealtimeSession(agent, { // Set your own transport. transport: cfTransport,});独自トランスポート機構の構築
Section titled “独自トランスポート機構の構築”別の音声対音声 API を使いたい場合や、独自のカスタムトランスポート機構を持っている場合は、RealtimeTransportLayer インターフェースを実装し、RealtimeTransportEventTypes イベントを発火することで独自に作成できます。
Realtime API とのより直接的なやり取り
Section titled “Realtime API とのより直接的なやり取り”OpenAI Realtime API を使用しつつ、Realtime API へより直接的にアクセスしたい場合は、次の 2 つの選択肢があります。
オプション 1 - トランスポート層へのアクセス
Section titled “オプション 1 - トランスポート層へのアクセス”RealtimeSession のあらゆる機能を活用したい場合は、session.transport からトランスポート層にアクセスできます。
トランスポート層は受信したすべてのイベントを * イベントで発火し、sendEvent() メソッドを使って元のイベントを送信できます。
import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Greeter', instructions: 'Greet the user with cheer and answer questions.',});
const session = new RealtimeSession(agent, { model: 'gpt-realtime',});
session.transport.on('*', (event) => { // JSON parsed version of the event received on the connection});
// Send any valid event as JSON. For example triggering a new responsesession.transport.sendEvent({ type: 'response.create', // ...});オプション 2 — トランスポート層のみの利用
Section titled “オプション 2 — トランスポート層のみの利用”自動ツール実行やガードレールなどが不要な場合は、接続と割り込みのみを管理する「薄い」クライアントとしてトランスポート層だけを使用できます。
import { OpenAIRealtimeWebRTC } from '@openai/agents/realtime';
const client = new OpenAIRealtimeWebRTC();const audioBuffer = new ArrayBuffer(0);
await client.connect({ apiKey: '<api key>', model: 'gpt-4o-mini-realtime-preview', initialSessionConfig: { instructions: 'Speak like a pirate', voice: 'ash', modalities: ['text', 'audio'], inputAudioFormat: 'pcm16', outputAudioFormat: 'pcm16', },});
// optionally for WebSocketsclient.on('audio', (newAudio) => {});
client.sendAudio(audioBuffer);