コンテンツにスキップ

Cloudflare Workers 用トランスポート

Cloudflare Workers とその他の workerd ランタイムでは、グローバルな WebSocket コンストラクターを使ってアウトバウンド WebSocket を開くことはできません。これらの環境から リアルタイムエージェント を簡単に接続できるようにするため、extensions パッケージは内部で fetch() ベースのアップグレードを行う専用トランスポートを提供します。

  1. extensions パッケージをインストールします。

    Terminal window
    npm install @openai/agents-extensions
  2. トランスポートを作成し、セッションにアタッチします。

    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,
    });
  3. RealtimeSession を接続します。

    await session.connect({ apiKey: 'your-openai-ephemeral-or-server-key' });
  • Cloudflare トランスポートは内部で Upgrade: websocket を伴う fetch() を使用し、ソケットの open イベント待ちをスキップします。workerd の API と揃えています
  • このトランスポート使用時も、すべての RealtimeSession 機能(ツール、ガードレールなど)が通常どおり動作します
  • 開発中の詳細ログ確認には DEBUG=openai-agents* を使用してください