如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

WebRTC

使用 WebRTC 連接語音應用程式。

選擇你使用的 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 和代管的網頁搜尋。關於後端指令與應用程式工具,請參閱委派與工具。關於語音與後端用量,請參閱成本最佳化。

瞭解連線流程

  1. 在使用者操作時要求麥克風存取權限,並將麥克風音軌加入對等連線。
  2. 先建立資料通道並註冊事件監聽器,再建立 SDP 提議。
  3. 設定本機描述,等待 ICE 候選位址收集完畢,再將提議傳送至伺服器。
  4. 讓伺服器透過 POST 將包含 session 和 transport: { type: "webrtc", sdp: ... } 的 JSON 傳送至 OpenAI。
  5. 將收到的 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 後,再關閉對等連線和麥克風音軌。範例會先註冊最終事件的監聽器,再傳送指令。如果連線在收到最終事件前失敗或逾時,就無法確認最終用量。關於如何處理最終用量,請參閱用量與正常關閉流程。