快速开始
项目设置和凭据
Section titled “项目设置和凭据”-
创建项目
在本快速开始中,我们将创建一个可在浏览器中使用的语音智能体。如果你想从一个新项目开始,可以尝试
Next.js或Vite。Terminal window npm create vite@latest my-project -- --template vanilla-ts -
安装 Agents SDK(需要 Zod v4)
Terminal window npm install @openai/agents zod或者,你也可以安装
@openai/agents-realtime来使用独立的浏览器包。 -
生成客户端临时令牌
由于应用将在用户的浏览器中运行,我们需要一种安全的方式通过 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 连接。注意该密钥仅在短时间内有效,需要定期重新生成。
创建并连接语音智能体
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',});RealtimeSession构造函数将agent作为第一个参数。此智能体将成为用户首先可以交互的智能体。 -
连接到会话
要连接到会话,你需要传入之前生成的客户端临时令牌。
await session.connect({ apiKey: 'ek_...(put your own key here)' });这将在浏览器中使用 WebRTC 连接到 Realtime API,并自动配置你的麦克风与扬声器以进行音频输入与输出。如果你在后端服务器(如 Node.js)上运行
RealtimeSession,SDK 将自动使用 WebSocket 作为连接。你可以在传输机制指南中了解更多不同的传输层。
运行并测试应用
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
从这里开始,你可以设计并构建自己的语音智能体。语音智能体包含许多与常规智能体相同的功能,但也有一些独特特性。