快速开始
项目设置与凭据
Section titled “项目设置与凭据”-
创建项目
在本快速开始中,我们将创建一个可在浏览器中使用的语音智能体。如果你想快速搭建一个新项目,可以从
Next.js或Vite开始。Terminal window npm create vite@latest my-project -- --template vanilla-ts -
安装推荐包(需要 Zod v4)
Terminal window npm install @openai/agents zod -
生成客户端临时令牌
由于此应用将在用户浏览器中运行,我们需要一种安全方式通过 Realtime API 连接到模型。推荐流程与官方 Realtime API with WebRTC 指南一致:你的后端创建一个短期有效的临时客户端令牌,然后浏览器使用该令牌建立 WebRTC 连接。出于测试目的,你也可以使用
curl和常规 OpenAI API key 生成令牌。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"}}'响应包含一个顶层
value字段(以ek_前缀开头),以及生效的session对象。建立 WebRTC 连接时,请将value用作客户端密钥。该令牌生命周期很短,因此后端应在需要时签发新的令牌。如果你的浏览器会话需要带有authorization或自定义headers的远程 MCP 服务器工具,请将该托管 MCP 配置放在服务端发送到POST /v1/realtime/client_secrets的session负载中,而不是在浏览器代码中暴露这些凭据。
语音智能体的创建与连接
Section titled “语音智能体的创建与连接”-
创建第一个 Agent
创建新的
RealtimeAgent与创建常规Agent非常相似。import { RealtimeAgent } from '@openai/agents/realtime';const agent = new RealtimeAgent({name: 'Assistant',instructions: 'You are a helpful assistant.',}); -
创建会话
与常规智能体不同,语音智能体会持续运行在
RealtimeSession中,由它负责会话处理以及随时间与模型保持连接。该会话还管理音频处理、中断以及你稍后会配置的更完整会话生命周期。import { RealtimeSession } from '@openai/agents/realtime';const session = new RealtimeSession(agent, {model: 'gpt-realtime',});RealtimeSession构造函数将agent作为第一个参数。这个智能体将是用户首先交互的对象。 -
连接到会话
要连接到会话,你需要传入此前生成的客户端临时令牌。
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可能稍后才到达。你可以在传输机制指南中了解更多传输方式选择。
应用运行与测试
Section titled “应用运行与测试”-
整体集成
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 codeconst 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 .valueapiKey: 'ek_...(put your own key here)',});console.log('You are connected!');} catch (e) {console.error(e);}} -
启动应用并开始对话
启动你的 Web 服务器并打开包含新 Realtime Agent 代码的页面。你应会看到麦克风权限请求。授予访问权限后,你就可以开始与你的智能体对话了。
Terminal window npm run dev
接下来,你可以开始设计并构建自己的语音智能体: