選擇你使用的 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 將包含
session和transport: { type: "webrtc", sdp: ... }的 JSON 傳送至 OpenAI。 - 將收到的 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",
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,並在 JSON 中提供工作階段 ID 和 SDP 回覆:
{
"session": { "id": "live_123" },
"transport": { "type": "webrtc", "sdp": "<SDP answer>" }
}讀取 result.session.id,並將 result.transport.sdp 傳入 setRemoteDescription。請將工作階段 ID 視為不透明的識別碼,完整保留原值及其前綴。
如要縮短建立連線所需的時間,請參閱搭配 WARP 使用 WebRTC。
處理媒體與事件
透過媒體軌傳送麥克風音訊並接收模型產生的語音。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 提供的高階輔助功能與 API,可用來管理 Realtime 工作階段。WebRTC 介面功能強大且靈活,但比 Agents SDK 更接近底層。
從網頁瀏覽器或行動裝置等用戶端連線至 Realtime 模型時,建議優先使用 WebRTC 而非 WebSockets,以獲得較穩定的效能。
如需更多使用 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 Abridged Roundtrip Protocol(WARP)可縮短啟動 Realtime API 語音工作階段所需的時間。你可以個別啟用各項最佳化功能,也可以一起啟用,以執行完整的 WARP 交握流程。
關於原生用戶端設定、瀏覽器支援情形、來源試用說明及統一介面的連線流程,請參閱搭配 WARP 使用 WebRTC。
傳送與接收事件
管理 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。