即時翻譯可讓你將來源音訊串流傳送至專用的翻譯工作階段,在說話者發言的同時,就能陸續收到譯後音訊和逐字稿片段。這項功能適用於現場口譯、多語通話、直播、會議、授課和視訊聊天室。
如果應用程式需要翻譯使用者說的話,請使用 gpt-realtime-translate。如果需要能回答問題、呼叫工具並管理對話的助理,請在標準即時工作階段中使用 gpt-realtime-2.1。
即時翻譯工作階段與語音智慧體工作階段採用不同的架構:
| 語音智慧體工作階段 |
翻譯工作階段 |
連線至 /v1/realtime。 |
連線至 /v1/realtime/translations。 |
| 模型擔任助理。 |
模型擔任口譯員。 |
| 依照對話和回應的生命週期運作。 |
隨著音訊傳入,持續以串流方式輸出翻譯。 |
| 可以呼叫工具,並在對話中產生助理回合。 |
產生譯後音訊和逐字稿片段。 |
可以呼叫 response.create。 |
不呼叫 response.create。 |
音訊串流一傳入,翻譯就會開始。請持續附加音訊,包括語句之間的靜音,並在收到輸出事件時立即處理。
如果由瀏覽器擷取或播放音訊,請使用 WebRTC。WebRTC 會以媒體軌傳送來源音訊,並透過遠端音軌接收譯後語音,因此你無須自行重新取樣或播放 PCM 音訊區塊。
如果伺服器已在接收原始音訊,例如來自 Twilio Media Streams、SIP 媒體、直播訊號輸入或媒體處理程序的音訊,請使用 WebSocket。使用 WebSocket 時,請傳送以 base64 編碼的 24 kHz PCM16 音訊,並自行播放傳回的音訊片段。
開發瀏覽器應用程式時,請在伺服器上建立短效用戶端密鑰。請勿在瀏覽器中暴露標準 API 金鑰。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25app.post("/session", async (req, res) => {
const language = req.body.targetLanguage ?? "es";
const response = await fetch(
"https://api.openai.com/v1/realtime/translations/client_secrets",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
"OpenAI-Safety-Identifier": "hashed-user-id",
},
body: JSON.stringify({
session: {
model: "gpt-realtime-translate",
audio: {
output: { language },
},
},
}),
}
);
res.status(response.status).json(await response.json());
});
在瀏覽器中擷取音訊、建立對等連線,再以 POST 將 SDP offer 傳送至翻譯通話端點:
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50const { value: clientSecret } = await fetch("/session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ targetLanguage: "es" }),
}).then((response) => response.json());
const sourceStream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
const pc = new RTCPeerConnection();
pc.addTrack(sourceStream.getAudioTracks()[0], sourceStream);
const translatedAudio = new Audio();
translatedAudio.autoplay = true;
pc.ontrack = ({ streams }) => {
translatedAudio.srcObject = streams[0];
};
const events = pc.createDataChannel("oai-events");
events.onmessage = ({ data }) => {
const event = JSON.parse(data);
if (event.type === "session.output_transcript.delta") {
subtitles.textContent += event.delta;
}
};
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const sdpResponse = await fetch(
"https://api.openai.com/v1/realtime/translations/calls",
{
method: "POST",
headers: {
Authorization: `Bearer ${clientSecret}`,
"Content-Type": "application/sdp",
},
body: offer.sdp,
}
);
if (!sdpResponse.ok) {
throw new Error(await sdpResponse.text());
}
await pc.setRemoteDescription({
type: "answer",
sdp: await sdpResponse.text(),
});
連線至翻譯專用端點,並在 URL 中指定模型。
執行範例前,請依使用的語言安裝所需套件。Node.js 需要 ws,Python 需要 websocket-client 和 sounddevice,Ruby 則需要 async-websocket(執行 gem install async-websocket)。如果使用 Java,請加入 Maven 相依套件 com.openai:openai-java:4.75.1。
Java 範例分別示範如何建立連線、設定語言和輸入音訊。Java SDK 也支援接收事件和結束工作階段,但本指南未提供這兩個步驟的 Java 範例。如要依序完成下方的整個翻譯流程,請使用 Node.js 或 Python 範例。
1
2
3
4
5
6
7
8
9
10
11import WebSocket from "ws";
const ws = new WebSocket(
"wss://api.openai.com/v1/realtime/translations?model=gpt-realtime-translate",
{
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"OpenAI-Safety-Identifier": "hashed-user-id",
},
}
);
1
2
3
4
5
6
7
8
9
10
11import os
import websocket
ws = websocket.WebSocket()
ws.connect(
"wss://api.openai.com/v1/realtime/translations?model=gpt-realtime-translate",
header=[
f"Authorization: Bearer {os.environ['OPENAI_API_KEY']}",
"OpenAI-Safety-Identifier: hashed-user-id",
],
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
client := openai.NewClient()
session, err := client.Realtime.ConnectTranslation(ctx, "gpt-realtime-translate", realtime.TranslationConnectionOptions{}, option.WithHeader("OpenAI-Safety-Identifier", "hashed-user-id"))
if err != nil {
return err
}
defer session.Abort()
created, err := session.Recv(ctx)
if err != nil {
return err
}
fmt.Println(created.Type)
if created.Type != "session.created" {
return fmt.Errorf("expected session.created, got %s", created.Type)
}
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
30
31
32import com.openai.client.okhttp.OkHttpClient;
import com.openai.core.ClientOptions;
import com.openai.helpers.TranslationConnection;
import com.openai.helpers.TranslationWebSocketOptions;
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 =
TranslationConnection.connect(
options,
TranslationWebSocketOptions.builder()
.model("gpt-realtime-translate")
.sendTimeout(java.time.Duration.ofSeconds(30))
.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 translation session.");
System.out.println(event);
break;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21require "async"
require "async/http/endpoint"
require "async/websocket/client"
require "json"
endpoint = Async::HTTP::Endpoint.parse("wss://api.openai.com/v1/realtime/translations?model=gpt-realtime-translate", timeout: 10, alpn_protocols: ["http/1.1"])
headers = {
"Authorization" => "Bearer #{ENV.fetch("OPENAI_API_KEY")}",
"OpenAI-Safety-Identifier" => "hashed-user-id"
}
Sync do |task|
task.with_timeout(120) do
Async::WebSocket::Client.connect(endpoint, headers: headers) do |connection|
message = connection.read or raise "Connection closed before session creation"
event = JSON.parse(message.to_str)
raise "Expected session.created: #{event}" unless event["type"] == "session.created"
puts(event.fetch("type"))
end
end
end
如果使用 Ruby,請將下方用來設定語言和附加音訊的程式碼片段放在 Async::WebSocket::Client.connect 區塊內,位置在確認工作階段已建立之後、區塊結束之前。傳送音訊和接收翻譯事件時,請保持連線開啟。
Java 連線範例會在 try 區塊結束時關閉通訊端。Java 的語言設定和音訊輸入範例都需要已開啟的 TranslationConnection,因此傳送音訊和接收輸出時,請保持連線開啟。離開區塊前,請先結束工作階段,並持續讀取事件,直到收到 session.closed。詳見關閉 WebSocket 工作階段。
通訊端開啟後,設定目標語言:
1
2
3
4
5
6
7
8
9
10
11
12
13
14ws.on("open", () => {
ws.send(
JSON.stringify({
type: "session.update",
session: {
audio: {
output: {
language: "es",
},
},
},
})
);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import json
ws.send(
json.dumps(
{
"type": "session.update",
"session": {
"audio": {
"output": {
"language": "es",
},
},
},
}
)
)
1
2
3
4
5
6
7
8
9if err := session.Send(ctx, realtime.RealtimeTranslationClientEventParamOfSessionUpdate(realtime.RealtimeTranslationSessionUpdateRequestParam{
Audio: realtime.RealtimeTranslationSessionUpdateRequestAudioParam{
Output: realtime.RealtimeTranslationSessionUpdateRequestAudioOutputParam{
Language: openai.String("es"),
},
},
})); err != nil {
return err
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import com.openai.client.okhttp.OkHttpClient;
import com.openai.core.ClientOptions;
import com.openai.helpers.TranslationConnection;
import com.openai.helpers.TranslationWebSocketOptions;
import com.openai.models.realtime.*;
connection.send(
RealtimeTranslationClientEvent.ofSessionUpdate(
RealtimeTranslationSessionUpdateEvent.builder()
.session(
RealtimeTranslationSessionUpdateRequest.builder()
.audio(
RealtimeTranslationSessionUpdateRequest.Audio.builder()
.output(
RealtimeTranslationSessionUpdateRequest.Audio.Output.builder()
.language("es")
.build())
.build())
.build())
.build()));
1
2connection.write(JSON.generate(type: "session.update", session: { audio: { output: { language: "es" } } }))
connection.flush
接著持續附加音訊:
1
2
3
4
5
6ws.send(
JSON.stringify({
type: "session.input_audio_buffer.append",
audio: base64Pcm16,
})
);
1
2
3
4
5
6
7
8ws.send(
json.dumps(
{
"type": "session.input_audio_buffer.append",
"audio": base64_pcm16,
}
)
)
1
2
3
4
5
6
7// audio contains mono PCM16 samples at 24 kHz.
for start := 0; start < len(audio); start += 4800 {
end := min(start+4800, len(audio))
if err := session.Send(ctx, realtime.RealtimeTranslationClientEventParamOfSessionInputAudioBufferAppend(base64.StdEncoding.EncodeToString(audio[start:end]))); err != nil {
return err
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14import com.openai.client.okhttp.OkHttpClient;
import com.openai.core.ClientOptions;
import com.openai.helpers.TranslationConnection;
import com.openai.helpers.TranslationWebSocketOptions;
import com.openai.models.realtime.*;
import java.util.Base64;
// Call for each PCM16, 24 kHz, mono chunk supplied by your audio source.
static void appendAudio(TranslationConnection connection, byte[] pcmAudio) {
String base64Pcm16 = Base64.getEncoder().encodeToString(pcmAudio);
connection.send(
RealtimeTranslationClientEvent.ofSessionInputAudioBufferAppend(
RealtimeTranslationInputAudioBufferAppendEvent.builder().audio(base64Pcm16).build()));
}
1
2
3
4
5
6
7
8require "base64"
File.open("speech.pcm", "rb") do |audio|
while (chunk = audio.read(4_800))
connection.write(JSON.generate(type: "session.input_audio_buffer.append", audio: Base64.strict_encode64(chunk)))
connection.flush
end
end
監聽譯後音訊和逐字稿事件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15ws.on("message", (data) => {
const event = JSON.parse(data.toString());
if (event.type === "session.output_audio.delta") {
playPcm16(event.delta);
}
if (event.type === "session.output_transcript.delta") {
process.stdout.write(event.delta);
}
if (event.type === "session.input_transcript.delta") {
updateSourceTranscript(event.delta);
}
});
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50import base64
import json
from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from queue import SimpleQueue
import sounddevice as sd
audio_queue = SimpleQueue()
def play_audio():
try:
# Closing the stream waits for PortAudio's pending buffers to finish.
with sd.RawOutputStream(samplerate=24000, channels=1, dtype="int16") as stream:
while (pcm := audio_queue.get()) is not None:
stream.write(pcm)
except Exception:
# The receiver may have already closed the socket.
with suppress(OSError):
ws.abort() # Wake recv() so the receiver can report the playback failure.
raise
with ThreadPoolExecutor(max_workers=1) as executor:
playback = executor.submit(play_audio)
try:
while True:
event = json.loads(ws.recv())
if playback.done():
playback.result() # Report a playback failure on the receiver.
if event["type"] == "session.output_audio.delta":
audio_queue.put(base64.b64decode(event["delta"]))
if event["type"] in (
"session.output_transcript.delta",
"session.input_transcript.delta",
):
print(event["delta"], end="", flush=True)
if event["type"] == "error":
raise RuntimeError(f"Translation error: {event['error']['code']}")
if event["type"] == "session.closed":
break
finally:
ws.close()
audio_queue.put(None)
playback.result()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24// Run this listener while another goroutine sends audio into the session.
func listen(ctx context.Context, session *realtime.TranslationSession) error {
for {
event, err := session.Recv(ctx)
if err != nil {
return err
}
switch event.Type {
case "error":
return fmt.Errorf("translation error: %s", event.OfRealtimeErrorEvent.Error.Message)
case "session.output_transcript.delta":
fmt.Print(event.OfRealtimeTranslationOutputTranscriptDeltaEvent.Delta)
case "session.output_audio.delta":
pcm, err := base64.StdEncoding.DecodeString(event.OfRealtimeTranslationOutputAudioDeltaEvent.Delta)
if err != nil {
return err
}
// Feed pcm into your application's 24 kHz audio player.
fmt.Fprintln(log.Writer(), "Received audio bytes:", len(pcm))
case "session.closed":
return session.Close()
}
}
}
如果使用 Go,請在傳送音訊的同時執行 listen。它會在收到 session.closed 後關閉傳輸連線。
來源串流結束時,請先傳送 session.close 事件,再關閉 WebSocket。收到這個事件後,服務會處理完剩餘的輸入音訊,輸出尚未送出的譯後音訊和逐字稿,再傳送 session.closed 事件。只有翻譯工作階段支援 session.close 事件。
傳送 session.close 後,請停止附加音訊,並在原有的接收迴圈中繼續讀取事件,直到收到 session.closed。如果立即關閉通訊端,可能會遺失工作階段尚未傳送完畢的翻譯結果。
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59let translationSessionClosing = false;
let gotTranslationClosed = false;
let drainDeadline: ReturnType<typeof setTimeout> | undefined;
ws.on("close", () => {
clearTimeout(drainDeadline);
if (!gotTranslationClosed) {
console.error("Translation disconnected before final session.closed");
process.exitCode = 1;
}
});
function closeTranslationSession() {
if (translationSessionClosing) {
return;
}
translationSessionClosing = true;
// Adjust this deadline for your application's finalization requirements.
drainDeadline = setTimeout(() => {
console.error("Translation finalization timed out");
process.exitCode = 1;
ws.close();
}, 15_000);
ws.send(JSON.stringify({ type: "session.close" }));
}
// Use this in place of the earlier output handler, so audio plays only once.
ws.on("message", (data) => {
const event = JSON.parse(data.toString());
if (event.type === "session.output_audio.delta") {
playPcm16(event.delta);
}
if (event.type === "session.output_transcript.delta") {
process.stdout.write(event.delta);
}
if (event.type === "session.input_transcript.delta") {
updateSourceTranscript(event.delta);
}
if (event.type === "error") {
clearTimeout(drainDeadline);
console.error("Translation error", event.error?.code);
process.exitCode = 1;
ws.close();
}
if (event.type === "session.closed") {
clearTimeout(drainDeadline);
gotTranslationClosed = true;
ws.close();
}
});
// Call this when the source stream ends.
closeTranslationSession();
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76import base64
import json
import time
from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from queue import SimpleQueue
import sounddevice as sd
audio_queue = SimpleQueue()
def play_audio():
try:
# Closing the stream waits for PortAudio's pending buffers to finish.
with sd.RawOutputStream(samplerate=24000, channels=1, dtype="int16") as stream:
while (pcm := audio_queue.get()) is not None:
stream.write(pcm)
except Exception:
# The receiver may have already closed the socket.
with suppress(OSError):
ws.abort() # Wake recv() so the receiver can report the playback failure.
raise
translation_session_closing = False
def close_translation_session():
global translation_session_closing
if translation_session_closing:
return
translation_session_closing = True
ws.send(json.dumps({"type": "session.close"}))
with ThreadPoolExecutor(max_workers=1) as executor:
playback = executor.submit(play_audio)
try:
# Call this when the source stream ends.
close_translation_session()
# Adjust this deadline for your application's finalization requirements.
drain_deadline = time.monotonic() + 15.0
while True:
remaining = drain_deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("Translation finalization timed out")
ws.settimeout(remaining)
data = ws.recv()
if not data:
raise RuntimeError("Translation disconnected before session.closed")
event = json.loads(data)
if playback.done():
playback.result() # Report a playback failure on the receiver.
if event["type"] == "error":
raise RuntimeError(f"Translation error: {event['error']['code']}")
if event["type"] == "session.output_audio.delta":
audio_queue.put(base64.b64decode(event["delta"]))
if event["type"] in (
"session.output_transcript.delta",
"session.input_transcript.delta",
):
print(event["delta"], end="", flush=True)
if event["type"] == "session.closed":
break
finally:
# The server deadline covers receiving events, not local playback.
ws.close()
audio_queue.put(None)
playback.result()
1
2
3
4
5
6// Stop sending audio first. The listener closes the transport after session.closed.
if err := session.Send(ctx, realtime.RealtimeTranslationClientEventUnionParam{
OfSessionClose: &realtime.RealtimeTranslationSessionCloseEventParam{},
}); err != nil {
return err
}
如果需要將單一說話者的語音或單一串流的音訊翻譯給聽眾,可使用這種翻譯方式。常見情境包括直播、大會演講、網路研討會、財報電話會議、課堂講授和影片。
典型架構如下:
source audio -> translation session -> translated audio + subtitles
請為每種目標語言各建立一個翻譯工作階段。如果同一段英語音訊需要西班牙語和法語輸出,請分別建立英語譯為西班牙語和英語譯為法語的工作階段。
如果聽眾透過瀏覽器應用程式收聽翻譯,請使用 getDisplayMedia() 擷取分頁音訊,透過 WebRTC 傳送音訊,再播放遠端傳回的譯後音軌。正式播出時,請在伺服器端的媒體處理程序中執行翻譯,並向聽眾發布譯後音軌或字幕。
當兩位以上的參與者使用不同語言交談時,請使用對話翻譯。常見情境包括客服通話、業務通話、課業輔導和視訊聊天室。
請保留每位參與者的獨立音軌。將多位說話者混入同一個串流後,就更難辨識發言者、為各人顯示對應的字幕,也更難處理多人同時說話的情況。
雙人通話的兩個翻譯方向各需要一個工作階段:
Caller A audio -> translate into Caller B language -> play to Caller B
Caller B audio -> translate into Caller A language -> play to Caller A
在多人聊天室中,工作階段數量取決於目前的發言人數和目標語言數量:
translation sessions ~= active source speaker tracks x distinct target languages
在小型聊天室中,每位聽眾可以選擇要聽哪些遠端發言者的翻譯,並在瀏覽器端為這些發言者各建立一個翻譯輔助元件。在較大的聊天室中,請使用伺服器端的參與者或媒體處理程序。由它訂閱每位發言者的來源音軌一次,為每種目標語言各建立一個翻譯工作階段,再重新發布譯後音軌。
請使用真實音訊測試翻譯,並請熟悉兩種語言的人員審查結果。自動化指標有助於評估品質,但仍可能漏掉使用者會察覺的錯誤。
測試項目包括:
- 各語言組合的翻譯品質
- 姓名、數字、日期、貨幣和電話號碼的翻譯
- 特定領域的術語
- 交談中切換語言或混用多種語言的情況
- 不同口音、快速發言和多人同時說話的情況
- 收到第一段譯後音訊所需的時間
- 一句話說完後,收到其剩餘翻譯結果所需的時間
- 字幕顯示時機
- 聲音的一致性
- 重新連線時的行為
如果使用情境要求名稱或領域術語的翻譯完全準確,請在上線前建立一組附有標準答案的測試案例,並逐一人工審查未通過的案例。
- 瀏覽器端的媒體傳輸使用 WebRTC,伺服器端的媒體傳輸使用 WebSocket。
- 使用專用的
/v1/realtime/translations 端點。
- 持續串流傳送音訊,包括語句之間的靜音。
- 傳送
session.close,等到收到 session.closed 後再關閉 WebSocket 工作階段。
- 進行對話翻譯時,保留每位說話者的獨立音軌。
- 每種輸出語言各使用一個工作階段。
- 視需要同時顯示原文和譯文的逐字稿。
- 提供原音、譯後音訊、字幕、靜音和音量控制項。
- 顯示正在重新連線、發生延遲和服務無法使用等狀態。
- 分別追蹤延遲和翻譯品質。