Thanks to visit codestin.com
Credit goes to openai.github.io

跳转到内容

Cloudflare Workers 传输

Cloudflare Workers 和其他 workerd 运行时无法使用全局 WebSocket 构造函数发起出站 WebSocket 连接。为便于在这些环境中连接 实时智能体,扩展包提供了一个专用的传输适配器,在内部使用基于 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 功能(工具、护栏等)均可照常使用。
  • 在开发过程中使用 DEBUG=openai-agents* 查看详细日志。