跳转到内容

Cloudflare Workers 传输

Cloudflare Workers 及其他 workerd 运行时无法使用全局 WebSocket 构造函数发起出站 WebSocket 连接。为便于在这些环境中连接 Realtime Agents,扩展包提供了一个专用传输层,在内部通过基于 fetch() 的升级完成连接。

  1. 安装扩展包。

    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: websocketfetch(),并跳过等待套接字的 open 事件,以匹配 workerd API。
  • 使用该传输时,所有 RealtimeSession 功能(tools、护栏等)均可正常工作。
  • 使用 DEBUG=openai-agents* 在开发期间查看详细日志。