快速开始
项目设置和凭据
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 连接到模型。推荐流程与官方通过 WebRTC 使用 Realtime API指南一致:后端创建一个短期有效的客户端临时令牌,然后浏览器使用该令牌建立 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.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 服务器,并打开包含新实时智能体代码的页面。您应该会看到麦克风权限请求。授予访问权限后,您就可以开始与智能体对话。
Terminal window npm run dev
接下来,您可以开始设计和构建自己的实时智能体: