選擇你使用的 API,查看連線步驟和工作階段事件。
將伺服器連接至 GPT-Live
建議使用 WebRTC 建立 GPT-Live 音訊連線,伺服器對伺服器的整合也適用。
GPT-Live 也支援 WebSockets。主要 WebSocket 連線可雙向傳輸音訊和 JSON 事件。請將專案的 API 金鑰保存在受信任的伺服器上。
本指南說明如何將音訊串流傳送至 GPT-Live。如需監控或控制現有的工作階段,請參閱伺服器端控制。如需將負責推理和執行工具的後端連接至 Responses API,請參閱 Responses WebSocket 模式。
驗證身分並啟動工作階段
- 連接至
wss://api.openai.com/v1/live/sessions,不要加上任何查詢參數。使用Authorization: Bearer $OPENAI_API_KEY驗證身分,並帶入範例所示的連線標頭。 - 第一則訊息必須是
session.start。在session物件中指定模型、對話指示、音訊格式、語音和委派設定。 - 收到
session.started後再傳送音訊或應用程式指令。此事件包含實際生效的工作階段設定和工作階段 ID。
以下範例使用 Marin 語音、24 kHz 的 PCM16 音訊,以及支援網頁搜尋的 Responses 後端。請讓對話指示保持簡短。後端指示、工具和工具權限的設定方式,請參閱委派與工具。
使用 SDK 串流傳輸音訊
如果使用 Node.js,請使用 22.6 以上版本,安裝 openai 和 ws 套件,安裝指令為 npm install openai ws。接著將 TypeScript 範例儲存為 client.mts。如果在 macOS 或 Linux 上使用 Python,請安裝 openai[realtime],並將 Python 範例儲存為 client.py。在伺服器環境中設定 OPENAI_API_KEY。這些範例需要使用支援 Live 的 SDK 版本。範例會從標準輸入讀取 24 kHz 的單聲道 PCM16 原始音訊,再將回傳的音訊以相同格式寫入標準輸出。請將這兩個串流分別接到應用程式的音訊擷取和播放功能。記錄和轉錄事件會寫入標準錯誤輸出,以免破壞音訊串流。
如果使用 Go,請使用 Go 1.26 以上版本,將範例儲存為 main.go,並執行 go mod init live-demo 初始化模組。接著安裝 github.com/openai/openai-go/v3@v3.85.1 套件,使用的指令是 go get。如果使用 Java,請使用 Java 17 以上版本,加入 Maven 相依套件 com.openai:openai-java:4.95.0,並使用 LiveConnectionWebsocketExample 類別。如果使用 Ruby 3.3 以上版本,請執行 gem install openai -v 0.110.0 安裝 SDK,再執行 gem install async-websocket 安裝 SDK 所需的 WebSocket 套件,並將範例儲存為 client.rb。
import OpenAI from "openai";
import { LiveWS } from "openai/resources/live/ws";
// stdin and stdout carry raw mono PCM16 audio at 24 kHz, not WAV files.
// Supply microphone bytes continuously and play stdout in the same format.
process.stdin.pause();
const ws = new LiveWS(new OpenAI());
let started = false;
let closing = false;
let finalized = false;
let pendingByte = Buffer.alloc(0);
let closeTimeout: ReturnType<typeof setTimeout> | undefined;
ws.socket.on("open", () => {
ws.send({
type: "session.start",
event_id: "event_start",
session: {
model: "gpt-live-1",
instructions:
"Be concise. Delegate requests needing current information to the backend, which can search the web.",
audio: {
format: { type: "audio/pcm", rate: 24000 },
output: { voice: "marin" },
},
delegation: {
type: "responses",
responses: {
model: "gpt-5.6-luna",
tools: [{ type: "web_search" }],
tool_choice: "auto",
},
},
},
});
});
process.stdin.on("data", (chunk) => {
if (!started || closing || ws.socket.readyState !== 1) return;
const bytes = Buffer.concat([pendingByte, chunk]);
const completeLength = bytes.length - (bytes.length % 2);
pendingByte = bytes.subarray(completeLength);
if (completeLength) {
ws.send({
type: "session.input_audio.append",
audio: bytes.subarray(0, completeLength).toString("base64"),
});
}
});
// Register the final-event handler before any close command can be sent.
ws.on("event", (event) => {
if (event.type === "session.started") {
started = true;
console.error("Session ready", event.session.id);
process.stdin.resume();
} else if (event.type === "session.output_audio.delta") {
process.stdout.write(Buffer.from(event.delta, "base64"));
} else if (event.type === "session.closed") {
finalized = true;
clearTimeout(closeTimeout);
process.stdin.pause();
console.error("Final session usage", event.usage);
ws.close();
} else {
// Includes transcript deltas and nested response.event usage.
console.error(JSON.stringify(event));
}
});
process.on("SIGINT", () => {
if (closing) return;
if (!started || ws.socket.readyState !== 1) {
ws.socket.platformSocket.terminate();
return;
}
closing = true;
process.stdin.pause();
ws.send({ type: "session.close" });
closeTimeout = setTimeout(() => {
console.error("Incomplete finalization: session.closed was not received");
process.exitCode = 1;
ws.socket.platformSocket.terminate();
}, 15_000);
});
ws.on("error", (error) => {
console.error(error.message);
process.exitCode = 1;
});
ws.socket.on("close", () => {
clearTimeout(closeTimeout);
process.stdin.pause();
if (!finalized) {
console.error("Connection closed without final session usage");
process.exitCode = 1;
}
});接好音訊來源和播放器後,執行 node --experimental-strip-types client.mts、python client.py、go run .、ruby client.rb 或你的 Java 應用程式。看到 Session ready 後,依照錄音時的取樣率持續送入麥克風音訊。透過管線一次送入整個檔案,無法模擬即時麥克風輸入。音訊來源到達 EOF 時,對話仍會繼續。如要正常關閉連線,請向程序傳送 SIGINT。
範例負責連接音訊串流。擷取、緩衝、播放及必要時的重新取樣,都由你的應用程式負責。評估模型行為前,請先用實際裝置和網路測試這些功能。
選擇音訊格式
啟動時設定 session.audio.format。輸入和輸出共用同一種格式,工作階段期間無法變更。
{"type":"audio/pcm","rate":24000}:24 kHz 單聲道有號 16 位元 PCM,採小端序,為預設格式。{"type":"audio/pcm","rate":16000}:16 kHz 單聲道有號 16 位元 PCM,採小端序。{"type":"audio/pcmu","rate":8000}:8 kHz G.711 μ-law,每個樣本占一個位元組。{"type":"audio/pcma","rate":8000}:8 kHz G.711 A-law,每個樣本占一個位元組。
以 Base64 編碼原始位元組,不要包含 WAV 或其他容器格式的標頭。每個 PCM 區塊都必須包含完整的 16 位元樣本,因此位元組數必須是偶數。範例會將末尾多出的一個位元組留到下一個輸入區塊處理。除此之外,可以自由劃分區塊,只要串流連續且順序正確即可。
音訊取樣率與設定值不同時,請重新取樣。變更格式設定不會轉換輸入的位元組。如要讓範例支援 G.711,請直接轉送各區塊中已編碼的位元組,略過 PCM 專用的雙位元組對齊邏輯,並將輸出播放器設為使用相同的編解碼器。格式相符的 G.711 串流可直接傳輸,無須轉換為 PCM。如需接通電話,請參閱電話系統整合。
傳送與接收事件
將每個事件以一則 JSON 文字訊息傳送。音訊會以 Base64 編碼放在訊息中一併傳送。
- 傳送音訊: 傳送
session.input_audio.append,並在audio中放入以 Base64 編碼的原始位元組。附加音訊時不會收到確認訊息。 - 接收音訊: 解碼
delta欄位的內容。每收到一個session.output_audio.delta事件,就將解碼後的音訊加入佇列,以設定的格式依序播放。 - 接收轉錄文字: 將
delta欄位中的文字附加至對應的逐字稿。文字分別來自session.input_transcript.delta和session.output_transcript.delta事件。 - 接收後端事件: 使用 Responses 委派時,請處理巢狀的
event,每個response.event封裝訊息都包含此欄位。 - 處理錯誤: 透過
error事件處理遭拒的指令和工作階段錯誤。如果事件包含error.client_event_id,請用它識別對應的指令。
使用應用程式的音訊佇列追蹤播放進度。GPT-Live 的主要 WebSocket 連線會傳送輸出音訊,但不會提供時間欄位,也不會傳送表示音訊輸出完畢的事件。請使用逐字稿的時間戳記安排字幕,並透過後端事件追蹤委派任務。
音訊持續串流時,GPT-Live 會自行決定何時聆聽、何時說話。使用 response.create 啟動或繼續執行委派給後端的任務。相關流程請參閱委派與工具。
調整進行中的工作階段
Live 模型、初始對話指示、音訊格式、語音和委派模式都在啟動時確定,之後無法變更。使用 session.update 調整目前委派模式支援的設定,省略的設定會保留目前的值。更新成功後會回傳 session.updated,其中包含實際生效的工作階段設定。
使用 session.instructions.append 新增對話指示,並使用 session.input_audio.mute 或 session.input_audio.unmute 控制輸入音訊。將輸入設為靜音不會取消後端任務,也不會中斷模型的語音輸出。關於上下文更新、逐字稿、輸入控制和用量,請參閱管理工作階段。
關閉工作階段
對話結束時,傳送 session.close。請先註冊 session.closed 事件監聽器,持續接收事件,直到收到該事件後再釋放連線。範例最多會等待 15 秒,若仍未收到結束事件,就會回報收尾作業未完成。
請保留 session.closed 中的最終語音用量,以及先前收到的後端用量事件。每次更新的語音時長都是截至當時的累計值,請勿相加。如果在收到 session.closed 前發生傳輸失敗或逾時,就無法確認最終用量。完整的工作階段生命週期請參閱管理工作階段。
WebSockets 是廣受支援的即時資料傳輸 API,很適合在伺服器對伺服器的應用程式中用來連接 OpenAI Realtime API。對於瀏覽器和行動用戶端,建議透過 WebRTC 連線。
以伺服器對伺服器的方式整合 Realtime 時,後端系統會透過 WebSocket 直接連接至 Realtime API。你可以使用標準 API 金鑰 驗證這條連線,因為只有受保護的後端伺服器能存取這把金鑰。
透過 WebSocket 連線
以下範例示範如何透過 WebSocket 連接至 Realtime API。除了使用下方的 WebSocket URL,還需要在驗證標頭中傳入你的 OpenAI API 金鑰。如果應用程式會指派安全識別碼,請在 OpenAI-Safety-Identifier 標頭中傳入終端使用者的識別碼。此識別碼必須保持穩定,並能保護使用者隱私。
如 WebRTC 連線指南 所示,瀏覽器也可以搭配短效 API 權杖使用 WebSocket。不過,從瀏覽器或行動應用程式等用戶端連線時,WebRTC 在多數情況下更可靠。
ws 模組(Node.js)
import WebSocket from "ws";
const url = "wss://api.openai.com/v1/realtime?model=gpt-realtime-2.1";
const ws = new WebSocket(url, {
headers: {
Authorization: "Bearer " + process.env.OPENAI_API_KEY,
"OpenAI-Safety-Identifier": "hashed-user-id",
},
});
let connected = false;
ws.on("message", function incoming(message) {
const event = JSON.parse(message.toString());
if (event.type === "error") throw new Error(event.error.message);
if (event.type === "session.created") {
connected = true;
console.log(`Connected to the Realtime API: ${event.session.id}`);
ws.close(1000);
}
});
ws.on("close", () => {
if (!connected)
throw new Error("Connection closed before the session was created");
});# example requires websocket-client library:
# pip install websocket-client
import os
import json
import websocket
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
url = "wss://api.openai.com/v1/realtime?model=gpt-realtime-2.1"
headers = [
"Authorization: Bearer " + OPENAI_API_KEY,
"OpenAI-Safety-Identifier: hashed-user-id",
]
session_created = False
def on_message(ws, message):
global session_created
data = json.loads(message)
if data["type"] == "session.created":
session_created = True
print("Connected to the Realtime API:", data["session"]["id"])
ws.close()
elif data["type"] == "error":
ws.close()
ws = websocket.WebSocketApp(
url,
header=headers,
on_message=on_message,
)
ws.run_forever()
if not session_created:
raise RuntimeError("Connection closed before the Realtime session was created.")使用以下指令安裝所需的 gem 套件:
gem install openai async-websocket。
require "openai"
client = OpenAI::Client.new(
default_headers: { "OpenAI-Safety-Identifier" => "hashed-user-id" }
)
client.realtime.connect(model: "gpt-realtime-2.1") do |connection|
created = connection.find do |event|
raise event.error.message if event.is_a?(OpenAI::Realtime::RealtimeErrorEvent)
next unless event.is_a?(OpenAI::Realtime::SessionCreatedEvent)
puts("Connected to the Realtime API: #{event.session[:id]}")
true
end
raise "Connection closed before the session was created" unless created
end請使用 Java 17 以上版本,並搭配 com.openai:openai-java:4.75.1。
import com.openai.client.okhttp.OkHttpClient;
import com.openai.core.ClientOptions;
import com.openai.helpers.RealtimeConnection;
import com.openai.helpers.RealtimeWebSocketOptions;
import com.openai.models.realtime.*;
var http = OkHttpClient.builder().build();
var options =
ClientOptions.builder()
.fromEnv()
.httpClient(http)
.putHeader("OpenAI-Safety-Identifier", "hashed-user-id")
.build();
try (http;
var connection =
RealtimeConnection.connect(
options,
RealtimeWebSocketOptions.builder().model("gpt-realtime-2.1").build())) {
while (true) {
var event = connection.receive();
if (event.error().isPresent())
throw new IllegalStateException(event.error().orElseThrow().toString());
if (event.sessionCreated().isPresent()) {
System.out.println("Connected to server.");
System.out.println(event);
break;
}
}
}請使用 Go 1.26 以上版本,並執行
go get github.com/openai/openai-go/v3@v3.85.1 安裝 SDK。SDK 會管理通訊端的資料傳輸。你的應用程式負責處理事件、擷取及播放音訊,並在重新連線後還原工作階段狀態。
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
client := openai.NewClient()
conn, err := client.Realtime.Connect(ctx, realtime.RealtimeConnectionOptions{}, option.WithQuery("model", "gpt-realtime-2.1"), option.WithHeader("OpenAI-Safety-Identifier", "hashed-user-id"))
if err != nil {
return err
}
defer conn.Close()執行
dotnet add package OpenAI –version 2.14.0 安裝 SDK。Realtime API 使用實驗性的 SDK 型別,範例已包含必要的編譯器警告指示詞。
using OpenAI.Realtime;
#pragma warning disable OPENAI002
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
RealtimeClient client = new(key);
RealtimeSessionClientOptions options = new();
options.Headers["OpenAI-Safety-Identifier"] = "hashed-user-id";
using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(30));
using RealtimeSessionClient session = await client.StartConversationSessionAsync("gpt-realtime-2.1", options, cancellationToken: timeout.Token);
await foreach (RealtimeServerUpdate update in session.ReceiveUpdatesAsync(timeout.Token))
{
if (update is RealtimeServerUpdateError error)
throw new InvalidOperationException(error.Error.Message);
if (update is RealtimeServerUpdateSessionCreated)
{
Console.WriteLine("Connected to server.");
Console.WriteLine(System.ClientModel.Primitives.ModelReaderWriter.Write(update));
return;
}
}
throw new InvalidOperationException("Connection closed before session creation.");/*
Note that in client-side environments like web browsers, we recommend
using WebRTC instead. It is possible, however, to use the standard
WebSocket interface in browser-like environments like Deno and
Cloudflare Workers.
*/
const ws = new WebSocket(
"wss://api.openai.com/v1/realtime?model=gpt-realtime-2.1",
[
"realtime",
// Use a short-lived token fetched from your application server.
"openai-insecure-api-key." + OPENAI_REALTIME_EPHEMERAL_KEY,
]
);
ws.addEventListener("open", function open() {
console.log("Connected to server.");
});
ws.addEventListener("message", function incoming(event) {
console.log(event.data);
});傳送與接收事件
管理 Realtime API 工作階段時,會用到兩類事件。開發人員透過應用程式發出用戶端傳送的事件,而 Realtime API 會產生伺服器傳送的事件,用來通知工作階段生命週期中的變化。
透過 WebSocket 收發事件時,傳輸的是序列化為 JSON 的文字字串。以下 Node.js 範例示範這個做法,其他 WebSocket 函式庫也適用相同原則。
import WebSocket from "ws";
const url = "wss://api.openai.com/v1/realtime?model=gpt-realtime-2.1";
const ws = new WebSocket(url, {
headers: {
Authorization: "Bearer " + process.env.OPENAI_API_KEY,
"OpenAI-Safety-Identifier": "hashed-user-id",
},
});
ws.on("open", function open() {
console.log("Connected to server.");
// Send client events over the WebSocket once connected
ws.send(
JSON.stringify({
type: "session.update",
session: {
type: "realtime",
instructions: "Be extra nice today!",
},
})
);
});
// Listen for and parse server events
ws.on("message", function incoming(message) {
console.log(JSON.parse(message.toString()));
});WebSocket 介面可能是與 Realtime 模型互動時可用的最底層介面。你需要自行透過通訊端連線傳送並處理以 Base64 編碼的音訊區塊。
如需瞭解如何透過 WebSockets 收發音訊,請參閱 Realtime 對話指南。