如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .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 请求向 OpenAI 发送包含 session 和 transport: { type: "webrtc", sdp: ... } 的 JSON。
  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.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 后再关闭对等连接和麦克风音轨。示例会在发送指令之前注册用于接收最终事件的监听器。如果连接在收到最终事件之前失败或超时,就无法确认最终用量。有关如何处理最终用量,请参阅用量与正常关闭会话。