English
主导航

旧版 API

通过 WebSocket 使用 Realtime API

在服务器上使用 WebSocket 连接到 Realtime API。

WebSockets 是一种被广泛支持的实时数据传输 API,也是在服务器到服务器应用程序中连接 OpenAI Realtime API 的绝佳选择。对于浏览器和移动客户端,我们建议通过以下方式进行连接: WebRTC.

在服务器到服务器的 Realtime 集成中,您的后端系统将通过 WebSocket 直接连接到 Realtime API。您可以使用 标准 API 密钥进行身份验证 来验证此连接,因为该令牌仅在您安全的后端服务器上可用。

connect directly to realtime API

通过 WebSocket 连接

以下是通过 WebSocket 连接到 Realtime API 的几个示例。除了使用下面的 WebSocket URL 外,您还需要使用 OpenAI API 密钥传递身份验证标头。如果您的应用程序分配了 安全标识符,在以下字段中传入面向终端用户的稳定且保护隐私的标识符: OpenAI-Safety-Identifier header.

如以下示例所示,可以在浏览器中将临时 API 令牌与 WebSocket 结合使用 WebRTC 连接指南,但如果您从浏览器或移动应用等客户端进行连接,在大多数情况下,WebRTC 将是更稳健的解决方案。

使用 ws 模块连接 (Node.js)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import WebSocket from "ws";

const url = "wss://api.openai.com/v1/realtime?model=gpt-realtime-2";
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.");
});

ws.on("message", function incoming(message) {
  console.log(JSON.parse(message.toString()));
});

发送和接收事件

Realtime API 会话通过结合使用以下两者来进行管理: 客户端发送的事件 (由你作为开发者发出)以及 服务器发送事件 由 Realtime API 创建,用于指示会话生命周期事件。

通过 WebSocket,您将以文本字符串的形式发送和接收 JSON 序列化事件,如下面的 Node.js 示例所示(相同的原则也适用于其他 WebSocket 库):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import WebSocket from "ws";

const url = "wss://api.openai.com/v1/realtime?model=gpt-realtime-2";
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 编码的音频块。

要了解如何通过 WebSocket 发送和接收音频,请参阅 Realtime 对话指南.