Realtime API 构建语音对话代理的入门要点

介绍用 Realtime API 搭建语音到语音代理的基本流程,模型直接处理音频并维护会话状态,支持工具调用;同时说明安全标识符的传递方式与从 Beta 迁移到 GA 的关键改动。

# 启动实时 API > 完整的文件索引见 [页:1](<https://developers.openai.com/llms.txt>)。可附加文档页的下图版 `.md` 转到页面 URL。 构建一个speech-to-speech带有实时语音代理API。该模型与音频直接工作,保持对话状态,并可以调用工具。此指南从代理开始SDK对于浏览器应用程序; 当需要直接控制时使用低级连接指南。 关于与单独授权的后端进行完全重复的谈话,见 [GPT - 生活( GPT- Live)](https://developers.openai.com/api/docs/guides/live)比较语音架构和连锁管道,参见: [语音代理](https://developers.openai.com/api/docs/guides/voice-agents). ## 构建一个 speech-to-speech 语音代理 当交互时使用实时 API , 它应该感觉对讲和即时。 这是语音代理的最佳起点 。 语音代理需要驳船、 低一级自动休息、 自然转弯、 实时工具使用 。 通常浏览器流量为: 1. 您的应用程序服务器为实时会话创建了电子客户端秘密 。 2. 您的前端创建 `RealtimeSession`. 3. 会话在浏览器的WebRTC或服务器的WebSocket上连接. 4. 代理处理音频转动,工具,中断,以及该会话内部的交接. 启动实时语音会话 ```typescript import { RealtimeAgent, RealtimeSession } from "@openai/agents/realtime"; const ephemeralKey = process.env.OPENAI_REALTIME_EPHEMERAL_KEY; if (!ephemeralKey) throw new Error("Set OPENAI_REALTIME_EPHEMERAL_KEY from your server."); const agent = new RealtimeAgent({ name: "Assistant", instructions: "You are a helpful voice assistant.", }); const session = new RealtimeSession(agent, { model: "gpt-realtime-2.1", }); await session.connect({ apiKey: ephemeralKey, }); ``` ```python import asyncio import os from agents.realtime import RealtimeAgent, RealtimeRunner, RealtimeSessionEvent def ephemeral_key() -> str: try: key = os.environ["OPENAI_REALTIME_EPHEMERAL_KEY"].strip() except KeyError: raise ValueError( "Set OPENAI_REALTIME_EPHEMERAL_KEY from your server." ) from None if not key: raise ValueError("Set OPENAI_REALTIME_EPHEMERAL_KEY from your server.") return key def configuration_accepted( event: RealtimeSessionEvent, model_name: str, instructions: str ) -> bool: if event.type == "error": raise RuntimeError("Realtime session configuration failed.") if event.type != "raw_model_event" or event.data.type != "raw_server_event": return False # Agents wraps the raw server dictionary in two typed event envelopes. server_event = event.data.data if ( not isinstance(server_event, dict) or server_event.get("type") != "session.updated" ): return False accepted = server_event.get("session") return ( isinstance(accepted, dict) and accepted.get("model") == model_name and accepted.get("instructions") == instructions ) async def main() -> None: # Obtain a short-lived client secret from your server before running this file. key = ephemeral_key() model_name = "gpt-realtime-2.1" instructions = "You are a helpful voice assistant." agent = RealtimeAgent(name="Assistant", instructions=instructions) runner = RealtimeRunner( agent, config={"model_settings": {"model_name": model_name}, "tracing_disabled": True}, ) # The server transport uses WebSocket with Bearer authentication. # Close after configuration acknowledgment; this example captures no audio. async with asyncio.timeout(20): async with await runner.run(model_config={"api_key": key}) as session: async for event in session: if configuration_accepted(event, model_name, instructions): return raise RuntimeError( "Realtime session closed before configuration acceptance." ) if __name__ == "__main__": asyncio.run(main()) ``` 从那里,将工具、手递和护栏放在 `RealtimeAgent` 将音频传输关切保留在会话层中,并将业务逻辑保留在代理定义中。 当您需要下级控制时, 请从传送文件开始 : - [音频和语音概览](https://developers.openai.com/api/docs/guides/audio) - [实时 API 与 WebRTC](https://developers.openai.com/api/docs/guides/voice-webrtc?api=realtime) - [实时 API 与 WebSocket](https://developers.openai.com/api/docs/guides/voice-websockets?api=realtime) ## 安全识别器 如果您的应用程序识别了单个终端用户,请包括 [安全标识符](https://developers.openai.com/api/docs/guides/safety-best-practices#implement-safety-identifiers) 包含实时 API 请求. OpenAI 推荐安全识别符但不需要它们. 它们帮助 OpenAI 检测有害行为,并将执行目标瞄准一个个人用户而不是整个组织. 使用稳定,隐私保存值,例如散列的内部用户 ID . 对于实时 API 请求,请在 `OpenAI-Safety-Identifier` 头部 。 使用 128 字符的标识符。 当使用 ephemeral 符时, 在服务器侧请求上设置头部, 创建客户端的密件, 将标识符与会话连接起来。 当从信任的服务器连接到 WebSocket 或统一的 WebRTC 接口时, 在连接请求上设置头部 。 安全识别符不会从响应 API 请求或其他会话中结转。如果您使用响应 API `safety_identifier` 参数,当您创建或连接每个实时会话时,通过相同的稳定值。 ## Beta 到 GA 迁移 如果您仍然拥有β实时集成,请在推进新工作前将其迁移到GA接口。最重要的变化是: - 删除 `OpenAI-Beta: realtime=v1` 调用GA接口时,其标题为. - 使用( U) [`POST /v1/realtime/client_secrets`](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets/methods/create) 为浏览器或移动客户端创建电子证书。 - 使用( U) `/v1/realtime/calls` 当建立WebRTC会话时。 - 更新 GA 接口的会话和事件形状。 特别是设置 `session.type`,将输出音频配置移动到 `session.audio.output`,并使用新的响应事件名称,例如 `response.output_text.delta`, `response.output_audio.delta`,以及 `response.output_audio_transcript.delta`. - 如果您要向前移动一个 speech-to-speech 应用程序, 请从 [浏览器示例](#build-a-speech-to-speech-voice-agent)。如果您正在向前移动一个转录工作流程,请使用 [实时转录](https://developers.openai.com/api/docs/guides/realtime-transcription). 见 [实时客户端事件参考](https://developers.openai.com/api/reference/resources/realtime/client-events), [实时会议参考](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets),以及 [浏览器示例](#build-a-speech-to-speech-voice-agent) 用于当前GA流。 ## 今后的步骤 - [管理对话](https://developers.openai.com/api/docs/guides/realtime-conversations): 配置会话并处理音频,文本和事件. - [语音活动检测](https://developers.openai.com/api/docs/guides/realtime-vad): 配置自动转弯检测. - [工具和 MCP](https://developers.openai.com/api/docs/guides/realtime-mcp): 添加函数, MCP服务器, 以及连接器. - [提示语音模型](https://developers.openai.com/api/docs/guides/voice-prompting): 将指南用于您的实时模型。 - [成本优化](https://developers.openai.com/api/docs/guides/voice-latency-cost?api=realtime):理解实时会计和缓存. - [服务器端控制](https://developers.openai.com/api/docs/guides/voice-server-controls?api=realtime):在您的服务器上保留工具执行和会话控制. ## 其他音频工作流程 工作流程选择器和共享音频词汇表现已存在 [音频和语音](https://developers.openai.com/api/docs/guides/audio)。用于连续翻译,使用 [实时翻译](https://developers.openai.com/api/docs/guides/realtime-translation)。用于实时字幕,使用 [实时复制](https://developers.openai.com/api/docs/guides/realtime-transcription); 用于录制的音频 [文件复制](https://developers.openai.com/api/docs/guides/speech-to-text).

查看原始来源