跳转到内容

快速开始

  1. 创建项目

    在本快速上手指南中,我们将创建一个可在浏览器中使用的语音智能体。如果你想搭建一个新项目脚手架,可以从 Next.jsVite 开始。

    Terminal window
    npm create vite@latest my-project -- --template vanilla-ts
  2. 安装推荐的软件包(需要 Zod v4)

    Terminal window
    npm install @openai/agents zod
  3. 生成客户端临时令牌

    由于此应用将在用户的浏览器中运行,我们需要一种安全的方式通过 Realtime API 连接到模型。推荐流程与官方 Realtime API with WebRTC 指南一致:你的后端创建一个短生命周期的客户端临时令牌,然后浏览器使用该令牌建立 WebRTC 连接。出于测试目的,你也可以使用 curl 和常规 OpenAI API 密钥生成令牌。

    Terminal window
    export OPENAI_API_KEY="sk-proj-...(your own key here)"
    curl -X POST https://api.openai.com/v1/realtime/client_secrets \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "session": {
    "type": "realtime",
    "model": "gpt-realtime-2"
    }
    }'

    响应包含一个顶层 value 字段,该字段以 ek_ 前缀开头,同时还包含实际生效的 session 对象。建立 WebRTC 连接时,请将 value 用作客户端密钥。此令牌的生命周期很短,因此你的后端应在需要时生成新的令牌。如果你的浏览器会话需要带有 authorization 或自定义 headers 的托管 MCP 工具,请将该托管 MCP 配置包含在你发送给 POST /v1/realtime/client_secrets 的服务器端 session 载荷中,而不是在浏览器代码中暴露这些凭据。

  1. 创建你的第一个智能体

    创建新的 RealtimeAgent 与创建常规 Agent 非常相似。

    import { RealtimeAgent } from '@openai/agents/realtime';
    const agent = new RealtimeAgent({
    name: 'Assistant',
    instructions: 'You are a helpful assistant.',
    });
  2. 创建会话

    与常规智能体不同,语音智能体会在 RealtimeSession 中持续运行,随着时间推移处理对话以及与模型的连接。此会话还会管理音频处理、打断以及更广泛的对话生命周期,你将在后续进行配置。

    import { RealtimeSession } from '@openai/agents/realtime';
    const session = new RealtimeSession(agent, {
    model: 'gpt-realtime-2',
    });

    RealtimeSession 构造函数将 agent 作为第一个参数。该智能体将是用户首先交互的对象。

  3. 连接到会话

    要连接到会话,需要传入你之前生成的客户端临时令牌。

    await session.connect({ apiKey: 'ek_...(put your own key here)' });

    在浏览器中,这会使用 WebRTC 连接到 Realtime API,并自动为你配置麦克风采集和音频播放。在该默认 WebRTC 路径上,SDK 会在数据通道打开后立即发送初始会话配置,并在 connect() 完成前尝试等待匹配的 session.updated 确认;如果该确认一直没有到达,则使用超时回退。如果你在 Node.js 等服务器运行时中运行 RealtimeSession,SDK 会自动回退到 WebSocket;在 WebSocket 路径上,connect() 会在套接字打开且初始配置已发送后完成,因此 session.updated 可能会稍晚到达。你可以在传输机制指南中了解有关传输选择的更多信息。

  1. 整合所有内容

    import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
    export async function setupCounter(element: HTMLButtonElement) {
    // ....
    // for quickly start, you can append the following code to the auto-generated TS code
    const agent = new RealtimeAgent({
    name: 'Assistant',
    instructions: 'You are a helpful assistant.',
    });
    const session = new RealtimeSession(agent);
    // Automatically connects your microphone and audio output in the browser via WebRTC.
    try {
    await session.connect({
    // To get this ephemeral key string, you can run the following command or implement the equivalent on the server side:
    // curl -s -X POST https://api.openai.com/v1/realtime/client_secrets -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" -d '{"session": {"type": "realtime", "model": "gpt-realtime-2"}}' | jq .value
    apiKey: 'ek_...(put your own key here)',
    });
    console.log('You are connected!');
    } catch (e) {
    console.error(e);
    }
    }
  2. 启动应用并开始对话

    启动你的 Web 服务器,并打开包含新实时智能体代码的页面。你应该会看到麦克风权限请求。授予访问权限后,你就可以开始与智能体对话了。

    Terminal window
    npm run dev

从这里开始,你可以设计并构建自己的语音智能体: