快速开始
项目设置与凭据
Section titled “项目设置与凭据”-
创建项目
在本快速开始中,我们将创建一个可在浏览器中使用的语音智能体。如果您想通过脚手架创建新项目,可以从
Next.js或Vite开始。终端窗口 npm create vite@latest my-project -- --template vanilla-ts -
安装推荐的包(需要 Zod v4)
终端窗口 npm install @openai/agents zod -
生成客户端临时令牌
由于此应用将在用户的浏览器中运行,我们需要一种安全的方式来通过 Realtime API 连接模型。推荐流程与官方的通过 WebRTC 使用 Realtime API 指南一致:您的后端创建一个短期有效的客户端临时令牌,然后浏览器使用该令牌建立 WebRTC 连接。测试时,您也可以使用
curl和常规的 OpenAI API 密钥生成令牌。终端窗口 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.1"}}'响应包含一个以
ek_为前缀的顶层value字段,以及生效的session对象。建立 WebRTC 连接时,请将value用作客户端机密信息。此令牌的有效期很短,因此后端应在需要时签发新令牌。如果浏览器会话需要使用带有authorization或自定义headers的托管 MCP 工具,请将该托管 MCP 配置包含在服务器端发送给POST /v1/realtime/client_secrets的session载荷中,而不是在浏览器代码中暴露这些凭据。
语音智能体的创建与连接
Section titled “语音智能体的创建与连接”-
创建您的第一个智能体
创建新的
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-2.1',});RealtimeSession构造函数接受一个agent作为第一个参数。该智能体将是用户首先与之交互的智能体。 -
连接会话
要连接会话,您需要传入之前生成的客户端临时令牌。
await session.connect({ apiKey: 'ek_...(put your own key here)' });在浏览器中,这会使用 WebRTC 连接到 Realtime API,并自动为您配置麦克风采集和音频播放。在此默认 WebRTC 连接方式下,SDK 会在数据通道打开后立即发送初始会话配置,并尝试等待相应的
session.updated确认后再让connect()完成;如果始终未收到该确认,则会通过超时回退机制完成连接。如果您在 Node.js 等服务器运行时中运行RealtimeSession,SDK 会自动回退到 WebSocket;在 WebSocket 连接方式下,connect()会在套接字打开且初始配置发送后完成,因此session.updated可能会稍晚到达。有关传输方式的更多信息,请参阅传输机制指南。
应用的运行与测试
Section titled “应用的运行与测试”-
完整示例
import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';async function main() {const agent = new RealtimeAgent({name: 'Assistant',instructions: 'You are a helpful assistant.',});const session = new RealtimeSession(agent, {model: 'gpt-realtime-2.1',});// 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.1"}}' | jq .valueapiKey: 'ek_...(put your own key here)',});console.log('You are connected!');} catch (e) {console.error(e);}}main().catch(console.error); -
启动应用并开始对话
启动 Web 服务器,并打开包含新语音智能体代码的页面。您应该会看到麦克风权限请求。授予访问权限后,您就可以开始与智能体对话了。
终端窗口 npm run dev
接下来,您可以开始设计并构建自己的语音智能体: