跳转到内容

Cloudflare 上的语音智能体

Cloudflare Workers 和其他 workerd 运行时无法使用全局 WebSocket 构造函数建立出站 WebSocket 连接。为简化从这些环境连接语音智能体的过程,扩展包提供了一种专用传输机制,在内部通过 fetch() 完成连接升级。

  1. 安装扩展包。

    终端窗口
    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-2.1',
    });
    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* 查看详细日志。