88API88API
使用指南AI 應用API 文件幫助支援
實時對話(Realtime)

OpenAI 實時對話介面

📝 概述

簡介

OpenAI Realtime API 提供兩種連線方式:

  1. WebRTC - 適用於瀏覽器和移動客戶端的實時音影片互動

  2. WebSocket - 適用於伺服器到伺服器的應用程式整合

使用場景

  • 實時語音對話
  • 音視訊會議
  • 實時翻譯
  • 語音轉寫
  • 實時程式碼生成
  • 伺服器端實時整合

主要特性

  • 雙向音訊流傳輸
  • 文字和音訊混合對話
  • 函式呼叫支援
  • 自動語音檢測(VAD)
  • 音訊轉寫功能
  • WebSocket 伺服器端整合

🔐 認證與安全

認證方式

  1. 標準 API 金鑰 (僅伺服器端使用)
  2. 臨時令牌 (客戶端使用)

臨時令牌

  • 有效期: 1分鐘
  • 使用限制: 單個連線
  • 獲取方式: 透過伺服器端 API 建立
POST https://88api.ai/v1/realtime/sessions
Content-Type: application/json
Authorization: Bearer $NEW_API_KEY

{
  "model": "gpt-4o-realtime-preview-2024-12-17",
  "voice": "verse"
}

安全建議

  • 永遠不要在客戶端暴露標準 API 金鑰
  • 使用 HTTPS/WSS 進行通訊
  • 實現適當的訪問控制
  • 監控異常活動

🔌 連線建立

WebRTC 連線

  • URL: https://88api.ai/v1/realtime
  • 查詢引數: model
  • 請求頭:
    • Authorization: Bearer EPHEMERAL_KEY
    • Content-Type: application/sdp

WebSocket 連線

  • URL: wss://88api.ai/v1/realtime
  • 查詢引數: model
  • 請求頭:
    • Authorization: Bearer YOUR_API_KEY
    • OpenAI-Beta: realtime=v1

連線流程

sequenceDiagram
    participant Client
    participant Server
    participant OpenAI

    alt WebRTC 連線
        Client->>Server: 請求臨時令牌
        Server->>OpenAI: 建立會話
        OpenAI-->>Server: 返回臨時令牌
        Server-->>Client: 返回臨時令牌

        Client->>OpenAI: 建立 WebRTC offer
        OpenAI-->>Client: 返回 answer

        Note over Client,OpenAI: 建立 WebRTC 連線

        Client->>OpenAI: 建立資料通道
        OpenAI-->>Client: 確認資料通道
    else WebSocket 連線
        Server->>OpenAI: 建立 WebSocket 連線
        OpenAI-->>Server: 確認連線

        Note over Server,OpenAI: 開始實時對話
    end

資料通道

  • 名稱: oai-events
  • 用途: 事件傳輸
  • 格式: JSON

音訊流

  • 輸入: addTrack()
  • 輸出: ontrack 事件

💬 對話互動

對話模式

  1. 純文字對話
  2. 語音對話
  3. 混合對話

會話管理

  • 建立會話
  • 更新會話
  • 結束會話
  • 會話配置

事件型別

  • 文字事件
  • 音訊事件
  • 函式呼叫
  • 狀態更新
  • 錯誤事件

⚙️ 配置選項

音訊配置

  • 輸入格式
    • pcm16
    • g711_ulaw
    • g711_alaw
  • 輸出格式
    • pcm16
    • g711_ulaw
    • g711_alaw
  • 語音型別
    • alloy
    • echo
    • shimmer

模型配置

  • 溫度
  • 最大輸出長度
  • 系統提示詞
  • 工具配置

VAD 配置

  • 閾值
  • 靜音時長
  • 字首填充

💡 請求示例

WebRTC 連線 ❌

客戶端實現 (瀏覽器)

async function init() {
  // 從伺服器獲取臨時金鑰 - 參見下方伺服器程式碼
  const tokenResponse = await fetch('/session');
  const data = await tokenResponse.json();
  const EPHEMERAL_KEY = data.client_secret.value;

  // 建立對等連線
  const pc = new RTCPeerConnection();

  // 設定播放模型返回的遠端音訊
  const audioEl = document.createElement('audio');
  audioEl.autoplay = true;
  pc.ontrack = (e) => (audioEl.srcObject = e.streams[0]);

  // 新增瀏覽器麥克風輸入的本地音訊軌道
  const ms = await navigator.mediaDevices.getUserMedia({
    audio: true,
  });
  pc.addTrack(ms.getTracks()[0]);

  // 設定用於傳送和接收事件的資料通道
  const dc = pc.createDataChannel('oai-events');
  dc.addEventListener('message', (e) => {
    // 這裡接收實時伺服器事件!
    console.log(e);
  });

  // 使用會話描述協議(SDP)啟動會話
  const offer = await pc.createOffer();
  await pc.setLocalDescription(offer);

  const baseUrl = 'https://88api.ai/v1/realtime';
  const model = 'gpt-4o-realtime-preview-2024-12-17';
  const sdpResponse = await fetch(`${baseUrl}?model=${model}`, {
    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);
}

init();

伺服器端實現 (Node.js)

import express from 'express';

const app = express();

// 建立一個端點用於生成臨時令牌
// 該端點與上面的客戶端程式碼配合使用
app.get('/session', async (req, res) => {
  const r = await fetch('https://88api.ai/v1/realtime/sessions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.NEW_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-4o-realtime-preview-2024-12-17',
      voice: 'verse',
    }),
  });
  const data = await r.json();

  // 將從OpenAI REST API收到的JSON傳送回客戶端
  res.send(data);
});

app.listen(3000);

WebRTC 事件收發示例

// 從對等連線建立資料通道
const dc = pc.createDataChannel('oai-events');

// 監聽資料通道上的伺服器事件
// 事件資料需要從JSON字串解析
dc.addEventListener('message', (e) => {
  const realtimeEvent = JSON.parse(e.data);
  console.log(realtimeEvent);
});

// 傳送客戶端事件:將有效的客戶端事件序列化為
// JSON,並透過資料通道傳送
const responseCreate = {
  type: 'response.create',
  response: {
    modalities: ['text'],
    instructions: 'Write a haiku about code',
  },
};
dc.send(JSON.stringify(responseCreate));

WebSocket 連線 ✅

Node.js (ws模組)

import WebSocket from 'ws';

const url =
  'wss://88api.ai/v1/realtime?model=gpt-4o-realtime-preview-2024-12-17';
const ws = new WebSocket(url, {
  headers: {
    Authorization: 'Bearer ' + process.env.NEW_API_KEY,
    'OpenAI-Beta': 'realtime=v1',
  },
});

ws.on('open', function open() {
  console.log('Connected to server.');
});

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

Python (websocket-client)

# 需要安裝 websocket-client 庫:
# pip install websocket-client

import os
import json
import websocket

NEW_API_KEY = os.environ.get("NEW_API_KEY")

url = "wss://88api.ai/v1/realtime?model=gpt-4o-realtime-preview-2024-12-17"
headers = [
    "Authorization: Bearer " + NEW_API_KEY,
    "OpenAI-Beta: realtime=v1"
]

def on_open(ws):
    print("Connected to server.")

def on_message(ws, message):
    data = json.loads(message)
    print("Received event:", json.dumps(data, indent=2))

ws = websocket.WebSocketApp(
    url,
    header=headers,
    on_open=on_open,
    on_message=on_message,
)

ws.run_forever()

瀏覽器 (標準WebSocket)

/*
注意:在瀏覽器等客戶端環境中,我們建議使用WebRTC。
但在Deno和Cloudflare Workers等類瀏覽器環境中,
也可以使用標準WebSocket介面。
*/

const ws = new WebSocket(
  'wss://88api.ai/v1/realtime?model=gpt-4o-realtime-preview-2024-12-17',
  [
    'realtime',
    // 認證
    'openai-insecure-api-key.' + NEW_API_KEY,
    // 可選
    'openai-organization.' + OPENAI_ORG_ID,
    'openai-project.' + OPENAI_PROJECT_ID,
    // Beta協議,必需
    'openai-beta.realtime-v1',
  ]
);

ws.on('open', function open() {
  console.log('Connected to server.');
});

ws.on('message', function incoming(message) {
  console.log(message.data);
});

訊息收發示例

Node.js/瀏覽器
// 接收伺服器事件
ws.on('message', function incoming(message) {
  // 需要從JSON解析訊息資料
  const serverEvent = JSON.parse(message.data);
  console.log(serverEvent);
});

// 傳送事件,建立符合客戶端事件格式的JSON資料結構
const event = {
  type: 'response.create',
  response: {
    modalities: ['audio', 'text'],
    instructions: 'Give me a haiku about code.',
  },
};
ws.send(JSON.stringify(event));
Python
# 傳送客戶端事件,將字典序列化為JSON
def on_open(ws):
    print("Connected to server.")

    event = {
        "type": "response.create",
        "response": {
            "modalities": ["text"],
            "instructions": "Please assist the user."
        }
    }
    ws.send(json.dumps(event))

# 接收訊息需要從JSON解析訊息負載
def on_message(ws, message):
    data = json.loads(message)
    print("Received event:", json.dumps(data, indent=2))

⚠️ 錯誤處理

常見錯誤

  1. 連線錯誤
    • 網路問題
    • 認證失敗
    • 配置錯誤
  2. 音訊錯誤
    • 裝置許可權
    • 格式不支援
    • 編解碼問題
  3. 會話錯誤
    • 令牌過期
    • 會話超時
    • 併發限制

錯誤恢復

  1. 自動重連
  2. 會話恢復
  3. 錯誤重試
  4. 降級處理

📝 事件參考

通用請求頭

所有事件都需要包含以下請求頭:

請求頭型別說明示例值
Authorization字串認證令牌Bearer $NEW_API_KEY
OpenAI-Beta字串API 版本realtime=v1

客戶端事件

session.update

更新會話的預設配置。

引數型別必需說明示例值/可選值
event_id字串客戶端生成的事件識別符號event_123
type字串事件型別session.update
modalities字串陣列模型可以響應的模態型別["text", "audio"]
instructions字串預置到模型呼叫前的系統指令"Your knowledge cutoff is 2023-10..."
voice字串模型使用的語音型別alloy、echo、shimmer
input_audio_format字串輸入音訊格式pcm16、g711_ulaw、g711_alaw
output_audio_format字串輸出音訊格式pcm16、g711_ulaw、g711_alaw
input_audio_transcription.model字串用於轉寫的模型whisper-1
turn_detection.type字串語音檢測型別server_vad
turn_detection.threshold數字VAD 啟用閾值(0.0-1.0)0.8
turn_detection.prefix_padding_ms整數語音開始前包含的音訊時長500
turn_detection.silence_duration_ms整數檢測語音停止的靜音持續時間1000
tools陣列模型可用的工具列表[]
tool_choice字串模型選擇工具的方式auto/none/required
temperature數字模型取樣溫度0.8
max_output_tokens字串/整數單次響應最大token數"inf"/4096

input_audio_buffer.append

向輸入音訊緩衝區追加音訊資料。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_456
type字串事件型別input_audio_buffer.append
audio字串Base64編碼的音訊資料Base64EncodedAudioData

input_audio_buffer.commit

將緩衝區中的音訊資料提交為使用者訊息。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_789
type字串事件型別input_audio_buffer.commit

input_audio_buffer.clear

清空輸入音訊緩衝區中的所有音訊資料。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_012
type字串事件型別input_audio_buffer.clear

conversation.item.create

向對話中新增新的對話項。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_345
type字串事件型別conversation.item.create
previous_item_id字串新對話項將插入在此ID之後null
item.id字串對話項的唯一識別符號msg_001
item.type字串對話項型別message/function_call/function_call_output
item.status字串對話項狀態completed/in_progress/incomplete
item.role字串訊息傳送者的角色user/assistant/system
item.content陣列訊息內容[text/audio/transcript]
item.call_id字串函式呼叫的IDcall_001
item.name字串被呼叫的函式名稱function_name
item.arguments字串函式呼叫的引數{"param": "value"}
item.output字串函式呼叫的輸出結果{"result": "value"}

conversation.item.truncate

截斷助手訊息中的音訊內容。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_678
type字串事件型別conversation.item.truncate
item_id字串要截斷的助手訊息項的IDmsg_002
content_index整數要截斷的內容部分的索引0
audio_end_ms整數音訊截斷的結束時間點1500

conversation.item.delete

從對話歷史中刪除指定的對話項。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_901
type字串事件型別conversation.item.delete
item_id字串要刪除的對話項的IDmsg_003

response.create

觸發響應生成。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_234
type字串事件型別response.create
response.modalities字串陣列響應的模態型別["text", "audio"]
response.instructions字串給模型的指令"Please assist the user."
response.voice字串模型使用的語音型別alloy/echo/shimmer
response.output_audio_format字串輸出音訊格式pcm16
response.tools陣列模型可用的工具列表["type", "name", "description"]
response.tool_choice字串模型選擇工具的方式auto
response.temperature數字取樣溫度0.7
response.max_output_tokens整數/字串最大輸出token數150/"inf"

response.cancel

取消正在進行中的響應生成。

引數型別必需說明示例值
event_id字串客戶端生成的事件識別符號event_567
type字串事件型別response.cancel

服務端事件

error

當發生錯誤時返回的事件。

引數型別必需說明示例值
event_id字串陣列服務端事件的唯一識別符號["event_890"]
type字串事件型別error
error.type字串錯誤型別invalid_request_error/server_error
error.code字串錯誤程式碼invalid_event
error.message字串人類可讀的錯誤訊息"The 'type' field is missing."
error.param字串與錯誤相關的引數null
error.event_id字串相關事件的IDevent_567

conversation.item.input_audio_transcription.completed

當啟用輸入音訊轉寫功能並且轉寫成功時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_2122
type字串事件型別conversation.item.input_audio_transcription.completed
item_id字串使用者訊息項的IDmsg_003
content_index整數包含音訊的內容部分的索引0
transcript字串轉寫的文字內容"Hello, how are you?"

conversation.item.input_audio_transcription.failed

當配置了輸入音訊轉寫功能,但使用者訊息的轉寫請求失敗時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_2324
type字串陣列事件型別["conversation.item.input_audio_transcription.failed"]
item_id字串使用者訊息項的IDmsg_003
content_index整數包含音訊的內容部分的索引0
error.type字串錯誤型別transcription_error
error.code字串錯誤程式碼audio_unintelligible
error.message字串人類可讀的錯誤訊息"The audio could not be transcribed."
error.param字串與錯誤相關的引數null

conversation.item.truncated

當客戶端截斷了之前的助手音訊訊息項時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_2526
type字串事件型別conversation.item.truncated
item_id字串被截斷的助手訊息項的IDmsg_004
content_index整數被截斷的內容部分的索引0
audio_end_ms整數音訊被截斷的時間點(毫秒)1500

conversation.item.deleted

當對話中的某個專案被刪除時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_2728
type字串事件型別conversation.item.deleted
item_id字串被刪除的對話項的IDmsg_005

input_audio_buffer.committed

當音訊緩衝區中的資料被提交時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_1121
type字串事件型別input_audio_buffer.committed
previous_item_id字串新對話項將插入在此ID對應的對話項之後msg_001
item_id字串將要建立的使用者訊息項的IDmsg_002

input_audio_buffer.cleared

當客戶端清空輸入音訊緩衝區時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_1314
type字串事件型別input_audio_buffer.cleared

input_audio_buffer.speech_started

在伺服器語音檢測模式下,當檢測到語音輸入時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_1516
type字串事件型別input_audio_buffer.speech_started
audio_start_ms整數從會話開始到檢測到語音的毫秒數1000
item_id字串語音停止時將建立的使用者訊息項的IDmsg_003

input_audio_buffer.speech_stopped

在伺服器語音檢測模式下,當檢測到語音輸入停止時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_1718
type字串事件型別input_audio_buffer.speech_stopped
audio_start_ms整數從會話開始到檢測到語音停止的毫秒數2000
item_id字串將要建立的使用者訊息項的IDmsg_003

response.created

當建立新的響應時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_2930
type字串事件型別response.created
response.id字串響應的唯一識別符號resp_001
response.object字串物件型別realtime.response
response.status字串響應的狀態in_progress
response.status_details物件狀態的附加詳細資訊null
response.output字串陣列響應生成的輸出項列表["[]"]
response.usage物件響應的使用統計資訊null

response.done

當響應完成流式傳輸時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_3132
type字串事件型別response.done
response.id字串響應的唯一識別符號resp_001
response.object字串物件型別realtime.response
response.status字串響應的最終狀態completed/cancelled/failed/incomplete
response.status_details物件狀態的附加詳細資訊null
response.output字串陣列響應生成的輸出項列表["[...]"]
response.usage.total_tokens整數總token數50
response.usage.input_tokens整數輸入token數20
response.usage.output_tokens整數輸出token數30

response.output_item.added

當響應生成過程中建立新的輸出項時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_3334
type字串事件型別response.output_item.added
response_id字串輸出項所屬的響應IDresp_001
output_index字串輸出項在響應中的索引0
item.id字串輸出項的唯一識別符號msg_007
item.object字串物件型別realtime.item
item.type字串輸出項型別message/function_call/function_call_output
item.status字串輸出項狀態in_progress/completed
item.role字串與輸出項關聯的角色assistant
item.content陣列輸出項的內容["type", "text", "audio", "transcript"]

response.output_item.done

當輸出項完成流式傳輸時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_3536
type字串事件型別response.output_item.done
response_id字串輸出項所屬的響應IDresp_001
output_index字串輸出項在響應中的索引0
item.id字串輸出項的唯一識別符號msg_007
item.object字串物件型別realtime.item
item.type字串輸出項型別message/function_call/function_call_output
item.status字串輸出項的最終狀態completed/incomplete
item.role字串與輸出項關聯的角色assistant
item.content陣列輸出項的內容["type", "text", "audio", "transcript"]

response.content_part.added

當響應生成過程中向助手訊息項新增新的內容部分時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_3738
type字串事件型別response.content_part.added
response_id字串響應的IDresp_001
item_id字串新增內容部分的訊息項IDmsg_007
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0
part.type字串內容型別text/audio
part.text字串文字內容"Hello"
part.audio字串Base64編碼的音訊資料"base64_encoded_audio_data"
part.transcript字串音訊的轉寫文字"Hello"

response.content_part.done

當助手訊息項中的內容部分完成流式傳輸時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_3940
type字串事件型別response.content_part.done
response_id字串響應的IDresp_001
item_id字串新增內容部分的訊息項IDmsg_007
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0
part.type字串內容型別text/audio
part.text字串文字內容"Hello"
part.audio字串Base64編碼的音訊資料"base64_encoded_audio_data"
part.transcript字串音訊的轉寫文字"Hello"

response.text.delta

當"text"型別內容部分的文字值更新時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_4142
type字串事件型別response.text.delta
response_id字串響應的IDresp_001
item_id字串訊息項的IDmsg_007
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0
delta字串文字增量更新內容"Sure, I can h"

response.text.done

當"text"型別內容部分的文字流式傳輸完成時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_4344
type字串事件型別response.text.done
response_id字串響應的IDresp_001
item_id字串訊息項的IDmsg_007
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0
delta字串最終的完整文字內容"Sure, I can help with that."

response.audio_transcript.delta

當模型生成的音訊輸出轉寫內容更新時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_4546
type字串事件型別response.audio_transcript.delta
response_id字串響應的IDresp_001
item_id字串訊息項的IDmsg_008
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0
delta字串轉寫文字的增量更新內容"Hello, how can I a"

response.audio_transcript.done

當模型生成的音訊輸出轉寫完成流式傳輸時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_4748
type字串事件型別response.audio_transcript.done
response_id字串響應的IDresp_001
item_id字串訊息項的IDmsg_008
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0
transcript字串音訊的最終完整轉寫文字"Hello, how can I assist you today?"

response.audio.delta

當模型生成的音訊內容更新時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_4950
type字串事件型別response.audio.delta
response_id字串響應的IDresp_001
item_id字串訊息項的IDmsg_008
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0
delta字串Base64編碼的音訊資料增量"Base64EncodedAudioDelta"

response.audio.done

當模型生成的音訊完成時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_5152
type字串事件型別response.audio.done
response_id字串響應的IDresp_001
item_id字串訊息項的IDmsg_008
output_index整數輸出項在響應中的索引0
content_index整數內容部分在訊息項內容陣列中的索引0

函式呼叫

response.function_call_arguments.delta

當模型生成的函式呼叫引數更新時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_5354
type字串事件型別response.function_call_arguments.delta
response_id字串響應的IDresp_002
item_id字串訊息項的IDfc_001
output_index整數輸出項在響應中的索引0
call_id字串函式呼叫的IDcall_001
delta字串JSON格式的函式呼叫引數增量{"location": "San"}

response.function_call_arguments.done

當模型生成的函式呼叫引數完成流式傳輸時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_5556
type字串事件型別response.function_call_arguments.done
response_id字串響應的IDresp_002
item_id字串訊息項的IDfc_001
output_index整數輸出項在響應中的索引0
call_id字串函式呼叫的IDcall_001
arguments字串最終的完整函式呼叫引數(JSON格式){"location": "San Francisco"}

其他狀態更新

rate_limits.updated

在每個 "response.done" 事件之後觸發,用於指示更新後的速率限制。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_5758
type字串事件型別rate_limits.updated
rate_limits物件陣列速率限制資訊列表[{"name": "requests_per_min", "limit": 60, "remaining": 45, "reset_seconds": 35}]

conversation.created

當對話建立時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_9101
type字串事件型別conversation.created
conversation物件對話資源物件{"id": "conv_001", "object": "realtime.conversation"}

conversation.item.created

當對話項建立時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_1920
type字串事件型別conversation.item.created
previous_item_id字串前一個對話項的IDmsg_002
item物件對話項物件{"id": "msg_003", "object": "realtime.item", "type": "message", "status": "completed", "role": "user", "content": [{"type": "text", "text": "Hello"}]}

session.created

當會話建立時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_1234
type字串事件型別session.created
session物件會話物件{"id": "sess_001", "object": "realtime.session", "model": "gpt-4", "modalities": ["text", "audio"]}

session.updated

當會話更新時返回此事件。

引數型別必需說明示例值
event_id字串服務端事件的唯一識別符號event_5678
type字串事件型別session.updated
session物件更新後的會話物件{"id": "sess_001", "object": "realtime.session", "model": "gpt-4", "modalities": ["text", "audio"]}

速率限制事件參數列

引數型別必需說明示例值
name字串限制名稱requests_per_min
limit整數限制值60
remaining整數剩餘可用量45
reset_seconds整數重置時間(秒)35

函式呼叫參數列

引數型別必需說明示例值
type字串函式型別function
name字串函式名稱get_weather
description字串函式描述Get the current weather
parameters物件函式引數定義{"type": "object", "properties": {...}}

音訊格式參數列

引數型別說明可選值
sample_rate整數取樣率8000, 16000, 24000, 44100, 48000
channels整數聲道數1 (單聲道), 2 (立體聲)
bits_per_sample整數取樣位數16 (pcm16), 8 (g711)
encoding字串編碼方式pcm16, g711_ulaw, g711_alaw

語音檢測參數列

引數型別說明預設值範圍
threshold浮點數VAD 啟用閾值0.50.0-1.0
prefix_padding_ms整數語音字首填充(毫秒)5000-5000
silence_duration_ms整數靜音檢測時長(毫秒)1000100-10000

工具選擇參數列

引數型別說明可選值
tool_choice字串工具選擇方式auto, none, required
tools陣列可用工具列表[{type, name, description, parameters}]

模型配置參數列

引數型別說明範圍/可選值預設值
temperature浮點數取樣溫度0.0-2.01.0
max_output_tokens整數/字串最大輸出長度1-4096/"inf""inf"
modalities字串陣列響應模態["text", "audio"]["text"]
voice字串語音型別alloy, echo, shimmeralloy

事件通用參數列

引數型別必需說明示例值
event_id字串事件的唯一識別符號event_123
type字串事件型別session.update
timestamp整數事件發生的時間戳(毫秒)1677649363000

會話狀態參數列

引數型別說明可選值
status字串會話狀態active, ended, error
error物件錯誤資訊{"type": "error_type", "message": "error message"}
metadata物件會話後設資料{"client_id": "web", "session_type": "chat"}

對話項狀態參數列

引數型別說明可選值
status字串對話項狀態completed, in_progress, incomplete
role字串傳送者角色user, assistant, system
type字串對話項型別message, function_call, function_call_output

內容型別參數列

引數型別說明可選值
type字串內容型別text, audio, transcript
format字串內容格式plain, markdown, html
encoding字串編碼方式utf-8, base64

響應狀態參數列

引數型別說明可選值
status字串響應狀態completed, cancelled, failed, incomplete
status_details物件狀態詳情{"reason": "user_cancelled"}
usage物件使用統計{"total_tokens": 50, "input_tokens": 20, "output_tokens": 30}

音訊轉寫參數列

引數型別說明示例值
enabled布林值是否啟用轉寫true
model字串轉寫模型whisper-1
language字串轉寫語言en, zh, auto
prompt字串轉寫提示詞"Transcript of a conversation"

音訊流參數列

引數型別說明可選值
chunk_size整數音訊塊大小(位元組)1024, 2048, 4096
latency字串延遲模式low, balanced, high
compression字串壓縮方式none, opus, mp3

WebRTC 配置參數列

引數型別說明預設值
ice_servers陣列ICE 伺服器列表[{"urls": "stun:stun.l.google.com:19302"}]
audio_constraints物件音訊約束{"echoCancellation": true}
connection_timeout整數連線超時(毫秒)30000

目錄

📝 概述
簡介
使用場景
主要特性
🔐 認證與安全
認證方式
臨時令牌
安全建議
🔌 連線建立
WebRTC 連線
WebSocket 連線
連線流程
資料通道
音訊流
💬 對話互動
對話模式
會話管理
事件型別
⚙️ 配置選項
音訊配置
模型配置
VAD 配置
💡 請求示例
WebRTC 連線 ❌
客戶端實現 (瀏覽器)
伺服器端實現 (Node.js)
WebRTC 事件收發示例
WebSocket 連線 ✅
Node.js (ws模組)
Python (websocket-client)
瀏覽器 (標準WebSocket)
訊息收發示例
Node.js/瀏覽器
Python
⚠️ 錯誤處理
常見錯誤
錯誤恢復
📝 事件參考
通用請求頭
客戶端事件
session.update
input_audio_buffer.append
input_audio_buffer.commit
input_audio_buffer.clear
conversation.item.create
conversation.item.truncate
conversation.item.delete
response.create
response.cancel
服務端事件
error
conversation.item.input_audio_transcription.completed
conversation.item.input_audio_transcription.failed
conversation.item.truncated
conversation.item.deleted
input_audio_buffer.committed
input_audio_buffer.cleared
input_audio_buffer.speech_started
input_audio_buffer.speech_stopped
response.created
response.done
response.output_item.added
response.output_item.done
response.content_part.added
response.content_part.done
response.text.delta
response.text.done
response.audio_transcript.delta
response.audio_transcript.done
response.audio.delta
response.audio.done
函式呼叫
response.function_call_arguments.delta
response.function_call_arguments.done
其他狀態更新
rate_limits.updated
conversation.created
conversation.item.created
session.created
session.updated
速率限制事件參數列
函式呼叫參數列
音訊格式參數列
語音檢測參數列
工具選擇參數列
模型配置參數列
事件通用參數列
會話狀態參數列
對話項狀態參數列
內容型別參數列
響應狀態參數列
音訊轉寫參數列
音訊流參數列
WebRTC 配置參數列