Cloudflare 上の Realtime Agent
Cloudflare Workers やその他の workerd ランタイムでは、グローバルな WebSocket コンストラクターを使用してアウトバウンド WebSockets を開くことはできません。これらの環境からリアルタイムエージェントに簡単に接続できるように、extensions パッケージは内部で fetch() ベースのアップグレードを実行する専用 transport を提供します。
セットアップ
Section titled “セットアップ”-
extensions パッケージのインストール
Terminal window npm install @openai/agents-extensions -
transport の作成と session への接続
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-2',});const session = new RealtimeSession(agent, {// Set your own transport.transport: cfTransport,}); -
RealtimeSessionの接続await session.connect({ apiKey: 'your-openai-ephemeral-or-server-key' });
- Cloudflare transport は内部で
Upgrade: websocketを指定したfetch()を使用し、socket のopenイベントの待機をスキップして、workerd API に合わせます。 - この transport を使用している場合も、すべての
RealtimeSession機能(tools、ガードレールなど)は通常どおり動作します。 - 開発中に詳細なログを確認するには、
DEBUG=openai-agents*を使用してください。