跳转到内容

快速开始

  1. 创建项目

    在本快速上手中,我们将创建一个可在浏览器中使用的语音智能体。如果您想从一个新项目开始,可以尝试使用Next.js 或者 Vite

    Terminal window
    npm create vite@latest my-project -- --template vanilla-ts
  2. 安装 Agents SDK

    Terminal window
    npm install @openai/agents zod@3

    或者,您也可以安装 @openai/agents-realtime 作为独立的浏览器包。

  3. 生成客户端临时令牌

    由于该应用将在用户的浏览器中运行,我们需要一种安全的方式通过 Realtime API 连接模型。为此,我们可以使用一种短期客户端密钥,它应在您的后端服务器上生成。出于测试目的,您也可以使用 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"
    }
    }'

    响应会在顶层包含一个以 “ek_” 前缀开头的 “value” 字符串。稍后您可以使用这个临时密钥建立 WebRTC 连接。请注意,该密钥仅在短时间内有效,需要重新生成。

  4. 创建您的第一个智能体

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

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

    与常规智能体不同,语音智能体会在一个持续运行并监听的 RealtimeSession 中工作,该会话会随时间处理与模型的对话与连接。此会话还将处理音频处理、打断,以及我们稍后将介绍的许多其他生命周期功能。

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

    RealtimeSession 构造函数将 agent 作为第一个参数。此智能体将是用户最先能够交互的智能体。

  6. 连接到会话

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

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

    这将在浏览器中使用 WebRTC 连接到 Realtime API,并自动配置麦克风与扬声器用于音频输入与输出。如果您在后端服务器(如 Node.js)上运行 RealtimeSession,SDK 将自动使用 WebSocket 作为连接。您可以在传输机制指南中了解不同的传输层。

  7. 将以上内容整合在一起

    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"}}' | jq .value
    apiKey: 'ek_...(put your own key here)',
    });
    console.log('You are connected!');
    } catch (e) {
    console.error(e);
    }
    }
  8. 启动并开始对话

    启动您的 web 服务器并导航到包含新 Realtime Agent 代码的页面。您应该会看到麦克风访问请求。授权后即可开始与智能体对话。

    Terminal window
    npm run dev

从这里开始,您可以设计并构建自己的语音智能体。语音智能体包含与常规智能体相同的许多功能,但也有一些独特特性。