选择您使用的 API,查看相应的连接步骤和会话事件。
将浏览器连接到 GPT-Live
对于浏览器、移动端和服务器端应用,我们建议使用 WebRTC 与 GPT-Live 建立音频连接。本指南以浏览器为例介绍连接步骤。麦克风输入和生成的语音通过协商建立的媒体轨道传输。数据通道则传输与转写文本、会话更新和委派任务相关的 JSON 事件。
浏览器会创建一个会话描述协议(SDP)提议。应用服务器使用项目 API 密钥调用 POST /v1/live/sessions,提交该提议并获取应答。请将密钥和会话配置保存在受信任的服务器上。
开始之前
您需要准备:
- 有权访问 GPT-Live 的项目 API 密钥。
- 适用于所选 SDK 示例的服务器运行时。Node.js 示例需要 Node.js 22.6 或更高版本。
- 已获准使用麦克风的浏览器,并通过 HTTPS 或 localhost 访问页面。
本示例使用 Responses 委派机制,调用 gpt-5.6-terra 并使用托管网页搜索。有关后端指令和应用工具,请参阅委派与工具。有关语音和后端用量,请参阅成本优化。
了解连接流程
- 在用户触发操作时请求麦克风访问权限,并将麦克风音轨添加到对等连接。
- 先创建数据通道并注册事件监听器,再创建 SDP 提议。
- 设置本地描述,等待 ICE 候选项收集完毕,然后将提议发送到您的服务器。
- 让服务器通过 POST 请求向 OpenAI 发送包含
session和transport: { type: "webrtc", sdp: ... }的 JSON。 - 将返回的 SDP 应答设为远端描述。等到数据通道收到
session.started后,再发送应用指令。
HTTP 请求会启动会话。请勿通过数据通道发送 session.start。 示例中的 oai-events 字符串是数据通道的标签。如果希望等到用户开口后再开始推理,请配置待机模式。
采用默认启动方式时,使用 POST /v1/live/sessions 创建 WebRTC 会话会在初始化阶段先按 15 秒语音时长计费。会话开始运行后,这笔费用会抵扣会话的时长费用,因此不会在实际运行时长之外再计费 15 秒。有关费用计算方式,请参阅 WebRTC 初始化费用。
创建应用服务器
将服务器示例保存到新目录,并在服务器的运行环境中设置 OPENAI_API_KEY。如果使用 TypeScript,请使用 Node.js 22.6 或更高版本,将示例保存为 server.ts,先运行 npm install openai express,再运行 npm pkg set type=module。如果使用 Python,请安装 openai。此示例监听 127.0.0.1,接受来自 http://localhost:3000 的会话请求,并从启动服务器的目录提供 index.html。
如果使用 Go,请将示例保存为 main.go,使用 go mod init live-demo 初始化模块,再将 github.com/openai/openai-go/v3@v3.85.1 作为参数传给 go get 进行安装。使用 Go 1.26 或更高版本运行 go run .。如果使用 Java,请使用 Java 17 或更高版本,添加 Maven 依赖项 com.openai:openai-java:4.95.0,然后运行 LiveConnectionWebrtcExample 类。如果使用 Ruby 3.3 或更高版本,请安装 openai 0.110.0 和 webrick,对应的安装命令为 gem install openai -v 0.110.0 和 gem install webrick。将示例保存为 server.rb,然后运行 ruby server.rb。
在下方选择服务器端语言。每个版本都在端口 3000 上提供 index.html 和相同的 /api/session 端点。请使用支持 Live 的 SDK 版本,每次只运行一个版本的示例。
import express from "express";
import OpenAI from "openai";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
const app = express();
const client = new OpenAI({ maxRetries: 0 });
const port = 3000;
const origin = `http://localhost:${port}`;
const indexPath = resolve("index.html");
app.use(express.json({ limit: "64kb" }));
app.get("/", async (_request, response) => {
response.type("html").send(await readFile(indexPath, "utf8"));
});
// Local-only demo. Add your application's authentication and authorization
// before exposing session creation to other users.
app.post("/api/session", async (request, response) => {
if (request.headers.origin !== origin) {
response.status(403).json({ error: "Unexpected request origin" });
return;
}
if (typeof request.body?.sdp !== "string" || !request.body.sdp.trim()) {
response.status(400).json({ error: "An SDP offer is required" });
return;
}
if (!process.env.OPENAI_API_KEY) {
response.status(503).json({ error: "Set OPENAI_API_KEY on the server" });
return;
}
try {
const result = await client.live.create({
session: {
model: "gpt-live-1.1",
instructions:
"Be concise. Delegate requests needing current information to the backend, which can search the web.",
delegation: {
type: "responses",
responses: {
model: "gpt-5.6-terra",
instructions:
"Use web search when current facts are needed. Return concise, grounded results for a spoken conversation.",
tools: [{ type: "web_search" }],
tool_choice: "auto",
},
},
},
transport: {
type: "webrtc",
sdp: request.body.sdp,
},
});
// Preserve the SDK's typed session ID and SDP answer.
response.status(201).json(result);
} catch (error) {
if (!(error instanceof OpenAI.APIError)) throw error;
console.error("Live session creation failed", error.status);
response
.status(error.status ?? 502)
.json({ error: "Live session creation failed" });
}
});
app.listen(port, "127.0.0.1", () => console.log(`Open ${origin}`));在向其他用户开放服务器之前,请使用应用的身份验证、授权、请求限制和 HTTPS 来保护 /api/session。此本地示例中的来源检查无法验证用户身份。
创建浏览器客户端
在启动服务器的目录中创建 index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GPT-Live connection</title>
</head>
<body>
<script type="module">
// Paste the compiled contents of browser.js here.
</script>
</body>
</html>将以下 TypeScript 代码保存为 browser.ts。这段代码会添加开始和结束对话的控件,接入麦克风和音频输出,并处理会话事件。/api/session 是应用服务器上的路由。
const start = document.createElement("button");
start.textContent = "Start conversation";
const stop = document.createElement("button");
stop.textContent = "End conversation";
stop.disabled = true;
const status = document.createElement("p");
const audio = new Audio();
audio.autoplay = true;
audio.controls = true;
document.body.append(start, stop, status, audio);
let peer: RTCPeerConnection;
let events: RTCDataChannel | undefined;
let microphone: MediaStream;
let closeTimeout: ReturnType<typeof setTimeout> | undefined;
let ready = false;
let finalized = false;
function cleanup() {
clearTimeout(closeTimeout);
microphone?.getTracks().forEach((track) => track.stop());
const closingEvents = events;
events = undefined;
closingEvents?.close();
peer?.close();
audio.srcObject = null;
ready = false;
start.disabled = false;
stop.disabled = true;
}
start.addEventListener("click", async () => {
start.disabled = true;
finalized = false;
status.textContent = "Connecting…";
try {
const connection = new RTCPeerConnection();
peer = connection;
connection.addEventListener("track", (event) => {
audio.srcObject = new MediaStream([event.track]);
audio.play().catch(() => {
status.textContent =
"Select play on the audio controls to hear the assistant.";
});
});
microphone = await navigator.mediaDevices.getUserMedia({ audio: true });
for (const track of microphone.getAudioTracks()) {
connection.addTrack(track, microphone);
}
// Create the event channel before creating the SDP offer.
events = connection.createDataChannel("oai-events");
events.addEventListener("message", ({ data }) => {
const event = JSON.parse(data);
if (event.type === "session.started") {
ready = true;
stop.disabled = false;
status.textContent = "Connected: " + event.session.id;
} else if (event.type === "session.closed") {
finalized = true;
console.log("Final session usage", event.usage);
status.textContent = "Conversation ended.";
cleanup();
} else {
// Save transcript and nested Responses events as needed by your app.
console.log(event);
}
});
events.addEventListener("close", (event) => {
if (event.target !== events) return;
if (!finalized) {
status.textContent = "Disconnected without final session usage.";
cleanup();
}
});
const offer = await connection.createOffer();
await connection.setLocalDescription(offer);
if (connection.iceGatheringState !== "complete") {
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
connection.removeEventListener("icegatheringstatechange", onState);
reject(new Error("Timed out while gathering ICE candidates"));
}, 10_000);
function onState() {
if (connection.iceGatheringState !== "complete") return;
clearTimeout(timeout);
connection.removeEventListener("icegatheringstatechange", onState);
resolve(undefined);
}
connection.addEventListener("icegatheringstatechange", onState);
onState();
});
}
const sdp = connection.localDescription?.sdp;
if (!sdp) throw new Error("Missing local SDP offer");
const response = await fetch("/api/session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sdp }),
});
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
console.log("Created session", result.session.id);
await connection.setRemoteDescription({
type: "answer",
sdp: result.transport.sdp,
});
// The HTTP request started this session. Do not send session.start here.
} catch (error) {
status.textContent =
error instanceof Error ? error.message : String(error);
cleanup();
}
});
stop.addEventListener("click", () => {
if (!ready || !events || events.readyState !== "open") return;
stop.disabled = true;
status.textContent = "Finishing the conversation…";
// The session.closed handler is already registered. Keep media and events
// alive while pending work drains; only clean up after the final event.
events.send(JSON.stringify({ type: "session.close" }));
closeTimeout = setTimeout(() => {
status.textContent = "Incomplete finalization: no session.closed event.";
cleanup();
}, 15_000);
});运行以下命令编译 browser.ts,然后用生成的 browser.js 文件的内容替换模块脚本中的占位注释:
npm install --save-dev esbuild
npx esbuild browser.ts --format=esm --outfile=browser.js启动您选择的服务器(node --experimental-strip-types server.ts 或 python server.py),打开 http://localhost:3000,然后选择 Start conversation。状态变为 Connected 后,提出一个需要查询最新信息才能回答的问题,以测试托管网页搜索。如果浏览器阻止自动播放,请使用音频控件播放语音。
读取会话响应
请求成功后,服务器会返回 HTTP 201,响应正文为包含会话 ID 和 SDP 应答的 JSON:
{
"session": { "id": "live_123" },
"transport": { "type": "webrtc", "sdp": "<SDP answer>" }
}读取 result.session.id,并将 result.transport.sdp 传给 setRemoteDescription。请将会话 ID 视为不透明标识符,原样保留整个值,包括前缀。
要缩短建立连接所需的时间,请参阅在 WebRTC 中使用 WARP。
处理媒体和事件
通过媒体轨道发送麦克风音频并接收生成的语音。WebRTC 通过 SDP 协商音频格式,因此会话配置中应省略 audio.format。请勿在数据通道上发送 session.input_audio.append,该通道也不会收到 session.output_audio.delta。
使用数据通道传输转写文本的增量更新、会话指令和嵌套的 response.event 消息。有关转写文本处理和生命周期事件,请参阅管理会话。如果服务器需要单独建立事件连接,请参阅服务器端控制。
要结束对话,请发送 session.close 并继续接收事件,直到收到 session.closed 后再关闭对等连接和麦克风音轨。示例会在发送指令之前注册用于接收最终事件的监听器。如果连接在收到最终事件之前失败或超时,就无法确认最终用量。有关如何处理最终用量,请参阅用量与正常关闭会话。
WebRTC 提供了一组功能强大的标准接口,可用于构建实时应用。OpenAI Realtime API 支持通过 WebRTC 对等连接访问实时模型。
如果您要构建基于浏览器的语音到语音应用,建议先阅读语音智能体,了解 Agents SDK 提供的用于管理 Realtime 会话的高级辅助函数和 API。WebRTC 接口功能强大、灵活,但比 Agents SDK 更底层。
从客户端(例如浏览器或移动设备)连接到 Realtime 模型时,建议优先使用 WebRTC。与 WebSockets 相比,WebRTC 的性能更稳定。
有关基于 WebRTC 构建用户界面的更多指导,请参阅 MDN 文档。
概述
Realtime API 支持两种浏览器连接方式:使用统一接口,或使用临时 API 密钥(通过 OpenAI REST API 生成)。使用统一接口可以简化设置并缩短建立连接所需的时间。采用这种方式时,会话初始化需要经过您的应用服务器。
使用统一接口连接
以浏览器作为客户端时,使用统一接口初始化 WebRTC 连接的流程如下:
- 浏览器使用其 WebRTC 对等连接的 SDP 数据,向开发者控制的服务器发起请求。
- 服务器将 SDP 数据和会话配置放入同一个多部分表单,发送到 OpenAI Realtime API,并使用服务器的标准 API 密钥对请求进行身份验证。
通过统一接口创建会话
要通过统一接口创建 Realtime API 会话,您需要构建一个小型服务器端应用(或在现有应用中集成这一功能),向 /v1/realtime/calls 发起请求。在后端服务器上使用标准 API 密钥对该请求进行身份验证。
从应用服务器创建 Realtime API 会话:
import express from "express";
const app = express();
// Parse raw SDP payloads posted from the browser
app.use(express.text({ type: ["application/sdp", "text/plain"] }));
const sessionConfig = JSON.stringify({
type: "realtime",
model: "gpt-realtime-2.1",
audio: { output: { voice: "marin" } },
});
// An endpoint which creates a Realtime API session.
app.post("/session", async (req, res) => {
const fd = new FormData();
fd.set("sdp", req.body);
fd.set("session", sessionConfig);
try {
const r = await fetch("https://api.openai.com/v1/realtime/calls", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"OpenAI-Safety-Identifier": "hashed-user-id",
},
body: fd,
});
// Send back the SDP we received from the OpenAI REST API
const sdp = await r.text();
res.set(
"Content-Type",
r.ok ? "application/sdp" : (r.headers.get("Content-Type") ?? "text/plain")
);
const location = r.headers.get("Location");
if (location) res.set("Location", location);
res.status(r.status).send(sdp);
} catch (error) {
console.error("Session creation error:", error);
res.status(500).json({ error: "Failed to create session" });
}
});
app.listen(3000);如果您的应用为每位最终用户分配了安全标识符,请将该标识符作为 OpenAI-Safety-Identifier 请求头的值,随此服务器端请求一起发送。请选择稳定且能保护隐私的值,例如内部用户 ID 的哈希值。该请求头应由受信任的后端设置,请勿在浏览器中设置。
连接到服务器
在浏览器中,您可以使用标准 WebRTC API,通过应用服务器连接到 Realtime API。客户端通过 POST 请求将 SDP 数据发送到您的服务器。
// Create a peer connection
const pc = new RTCPeerConnection();
// Set up to play remote audio from the model
audioElement.current = document.createElement("audio");
audioElement.current.autoplay = true;
pc.ontrack = (e) => (audioElement.current.srcObject = e.streams[0]);
// Add local audio track for microphone input in the browser
const ms = await navigator.mediaDevices.getUserMedia({
audio: true,
});
pc.addTrack(ms.getTracks()[0]);
// Set up data channel for sending and receiving events
const dc = pc.createDataChannel("oai-events");
// Start the session using the Session Description Protocol (SDP)
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const sdpResponse = await fetch("/session", {
method: "POST",
body: offer.sdp,
headers: {
"Content-Type": "application/sdp",
},
});
const answer = {
type: "answer",
sdp: await sdpResponse.text(),
};
await pc.setRemoteDescription(answer);使用临时令牌连接
以浏览器作为客户端时,使用临时 API 密钥初始化 WebRTC 连接的流程如下:
- 浏览器向开发者控制的服务器发起请求,要求生成临时 API 密钥。
- 开发者的服务器使用标准 API 密钥向 OpenAI REST API 请求临时密钥,然后将新密钥返回给浏览器。
- 浏览器使用临时密钥直接向 OpenAI Realtime API 进行身份验证,并通过 WebRTC 对等连接建立会话。
创建临时令牌
要创建供客户端使用的临时令牌,您需要构建一个小型服务器端应用(或在现有应用中集成这一功能),向 OpenAI REST API 请求临时密钥。在后端服务器上使用标准 API 密钥对该请求进行身份验证。
在应用服务器上通过 REST API 创建临时 API 密钥:
import express from "express";
const app = express();
const sessionConfig = JSON.stringify({
session: {
type: "realtime",
model: "gpt-realtime-2.1",
audio: {
output: {
voice: "marin",
},
},
},
});
// An endpoint which would work with the client code above - it returns
// the contents of a REST API request to this protected endpoint
app.get("/token", async (req, res) => {
res.set("Cache-Control", "no-store");
try {
const response = await fetch(
"https://api.openai.com/v1/realtime/client_secrets",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
"OpenAI-Safety-Identifier": "hashed-user-id",
},
body: sessionConfig,
}
);
const data = await response.json();
res.status(response.status).json(data);
} catch (error) {
console.error("Token generation error:", error);
res.status(500).json({ error: "Failed to generate token" });
}
});
app.listen(3000);您可以在任何能够收发 HTTP 请求的平台上创建这样的服务器端点。请确保仅在服务器上使用标准 OpenAI API 密钥,切勿在浏览器中使用。
使用临时令牌时,请在创建客户端密钥的服务器端请求中设置 OpenAI-Safety-Identifier。Realtime API 会将该标识符绑定到生成的临时令牌,因此浏览器随后使用该令牌连接时,无需再发送安全标识符。
连接到服务器
在浏览器中,您可以通过标准 WebRTC API 使用临时令牌连接到 Realtime API。客户端先从您的服务器端点获取令牌,再通过 POST 请求将 SDP 数据连同临时令牌发送到 Realtime API。
// Get a session token for OpenAI Realtime API
const tokenResponse = await fetch("/token");
const data = await tokenResponse.json();
const EPHEMERAL_KEY = data.value;
// Create a peer connection
const pc = new RTCPeerConnection();
// Set up to play remote audio from the model
audioElement.current = document.createElement("audio");
audioElement.current.autoplay = true;
pc.ontrack = (e) => (audioElement.current.srcObject = e.streams[0]);
// Add local audio track for microphone input in the browser
const ms = await navigator.mediaDevices.getUserMedia({
audio: true,
});
pc.addTrack(ms.getTracks()[0]);
// Set up data channel for sending and receiving events
const dc = pc.createDataChannel("oai-events");
// Start the session using the Session Description Protocol (SDP)
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const sdpResponse = await fetch("https://api.openai.com/v1/realtime/calls", {
method: "POST",
body: offer.sdp,
headers: {
Authorization: `Bearer ${EPHEMERAL_KEY}`,
"Content-Type": "application/sdp",
},
});
const answer = {
type: "answer",
sdp: await sdpResponse.text(),
};
await pc.setRemoteDescription(answer);使用 WARP 降低连接延迟
WebRTC 精简往返协议(WARP)可缩短启动 Realtime API 语音会话所需的时间。您可以单独启用各项优化,也可以组合使用这些优化来执行完整的 WARP 握手。
有关原生客户端设置、浏览器支持情况、源试用说明以及统一接口的连接流程,请参阅在 WebRTC 中使用 WARP。
发送和接收事件
管理 Realtime API 会话时会用到两类事件:客户端发送的事件由您作为开发者发出,服务器发送的事件由 Realtime API 生成,用于通知客户端会话生命周期中的变化。
通过 WebRTC 连接到 Realtime 模型时,您无需像使用 WebSockets 时那样逐个处理模型的音频事件。按上述步骤配置后,WebRTC 对等连接对象会自动完成这些工作。
要收发其他客户端和服务器事件,可以使用 WebRTC 对等连接的数据通道。
// Reuse dc from the preceding browser connection example.
// Listen for server events
dc.addEventListener("message", (e) => {
const event = JSON.parse(e.data);
console.log(event);
});
// Send client events
const event = {
type: "conversation.item.create",
item: {
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "hello there!",
},
],
},
};
const sendGreeting = () => dc.send(JSON.stringify(event));
if (dc.readyState === "open") {
sendGreeting();
} else if (dc.readyState === "connecting") {
dc.addEventListener("open", sendGreeting, { once: true });
} else {
throw new Error("The data channel has closed before greeting was sent.");
}要详细了解如何管理 Realtime 对话,请参阅 Realtime 对话指南。
通过这个轻量级示例应用,了解如何通过 WebRTC 使用 Realtime API。