หลายเซสชันบน WebSocket เดียว
WebSocket แบบ multiplex รองรับเซสชันเสียงพูดสดหรือถอดเสียงเรียลไทม์หลายเซสชันพร้อมกัน แต่ละเซสชันคือ context ที่มี id อีเวนต์ ค่าบริการ และโค้ดปิดของตัวเอง
WS /v1/tts/multi และ WS /v1/stt/multi รองรับหลายเซสชันบน WebSocket เดียวที่เปิดค้างไว้ แต่ละเซสชันเรียกว่า context หนึ่ง context เท่ากับการเชื่อมต่อ WS /v1/tts/live หรือ WS /v1/stt/live หนึ่งการเชื่อมต่อทุกประการ ทั้งเฟรม อีเวนต์ ค่าบริการ และลิมิต ทั้งสองเอนด์พอยต์ออกแบบมาสำหรับแอปพลิเคชันที่พูดหรือฟังหลายสายพร้อมกัน หากทำงานทีละบทสนทนา ให้ใช้เอนด์พอยต์แบบการเชื่อมต่อเดียว
| หนึ่ง WebSocket ต่อสาย | WebSocket แบบ multiplex | |
|---|---|---|
| เอนด์พอยต์ | /v1/tts/live, /v1/stt/live | /v1/tts/multi, /v1/stt/multi |
| สายใหม่ | อัปเกรดหนึ่งครั้ง | เฟรม start หนึ่งเฟรม |
| เฟรมและอีเวนต์ JSON | ตามข้อมูลอ้างอิงของการเชื่อมต่อสด | ชุดเดียวกัน โดยทุกรายการมี context_id |
| เฟรมไบนารี | เสียง | เฮดเดอร์ระบุ context ตามด้วยเสียง |
| เมื่อสายจบ | การเชื่อมต่อปิดพร้อมโค้ด | อีเวนต์ closed แจ้งโค้ด |
เปิด WebSocket และเริ่ม context#
- เชื่อมต่อเปิด WebSocket โดยส่งคีย์ API ในเฮดเดอร์
Authorizationหรือx-api-keyแบบเดียวกับคำขอ HTTP หากอัปเกรดไม่ผ่าน ระบบตอบเป็น problem+json ตามปกติ - ตั้ง id ของ contextกำหนด
context_idให้แต่ละสาย เช่น call id ของระบบคุณเอง ยาว 1 ถึง 64 ตัวอักษร ใช้ได้เฉพาะตัวอักษรภาษาอังกฤษ ตัวเลข และ._:-ทุกเฟรม JSON ที่ส่งและทุกอีเวนต์ที่ได้รับมีค่านี้ - startเฟรม
startที่ระบุ id ซึ่งยังไม่ได้เปิดอยู่จะเปิด context ใหม่ โดยรับฟิลด์ชุดเดียวกับstartของการเชื่อมต่อเดียว อีเวนต์startedตอบกลับพร้อมconnectionซึ่งเป็น id ของ context ฝั่งเรา ใช้อ้างอิงเมื่อติดต่อฝ่ายสนับสนุน - ส่งเฟรมส่งเฟรมอื่นของ context พร้อม
context_idของ context นั้น ฝั่งเสียงพูดรับtextflushcancelและendส่วนฝั่งถอดเสียงรับplaybackและendเสียงส่งเป็นเฟรมไบนารี
// Runs on Bun as-is; on Node, `import WebSocket from "ws"` accepts
// the same constructor options.
const socket = new WebSocket("wss://api.paxalabs.com/v1/tts/multi", {
headers: { Authorization: `Bearer ${process.env.PAXA_API_KEY}` },
});
socket.binaryType = "arraybuffer";
const send = (frame: object) => socket.send(JSON.stringify(frame));
// One context per call, named by your own call id.
function speak(contextId: string, text: string) {
send({
type: "start",
context_id: contextId,
model: "paxa-tts-flash-v2",
voice: "khanomkrok",
});
send({ type: "text", context_id: contextId, text });
send({ type: "end", context_id: contextId });
}
socket.onopen = () => {
speak("call-1042", "สวัสดีครับ ยินดีต้อนรับสู่ Paxa Labs");
speak("call-1043", "ขอบคุณที่รอสายครับ");
};
const ascii = new TextDecoder();
socket.onmessage = (event) => {
if (typeof event.data !== "string") {
// One byte counts the id, then the id in ASCII, then the audio.
const frame = new Uint8Array(event.data);
const audioAt = 1 + frame[0];
const contextId = ascii.decode(frame.subarray(1, audioAt));
players.get(contextId)?.feed(frame.subarray(audioAt));
return;
}
const message = JSON.parse(event.data);
switch (message.type) {
case "draining":
// The server is restarting: start new contexts on another socket
// and move each call there at its next turn boundary.
break;
case "closed":
// The context's last event. Its id is free for a new start.
players.delete(message.context_id);
}
};import json
import os
from websockets.sync.client import connect # pip install websockets
def speak(socket, context_id, text):
# One context per call, named by your own call id.
socket.send(json.dumps({
"type": "start",
"context_id": context_id,
"model": "paxa-tts-flash-v2",
"voice": "khanomkrok",
}))
socket.send(json.dumps({"type": "text", "context_id": context_id, "text": text}))
socket.send(json.dumps({"type": "end", "context_id": context_id}))
with connect(
"wss://api.paxalabs.com/v1/tts/multi",
additional_headers={"Authorization": f"Bearer {os.environ['PAXA_API_KEY']}"},
) as socket:
speak(socket, "call-1042", "สวัสดีครับ ยินดีต้อนรับสู่ Paxa Labs")
speak(socket, "call-1043", "ขอบคุณที่รอสายครับ")
audio = {"call-1042": bytearray(), "call-1043": bytearray()}
running = set(audio)
for frame in socket:
if isinstance(frame, bytes):
# One byte counts the id, then the id in ASCII, then the audio.
audio_at = 1 + frame[0]
audio[frame[1:audio_at].decode("ascii")] += frame[audio_at:]
continue
event = json.loads(frame)
if event["type"] == "draining":
# The server is restarting: start new contexts on another socket
# and move each call there at its next turn boundary.
continue
if event["type"] == "closed":
# The context's last event. Its id is free for a new start.
running.discard(event["context_id"])
if not running:
break
for context_id, data in audio.items():
with open(f"{context_id}.mp3", "wb") as f:
f.write(data)context ฝั่งเสียงพูดที่พูดหนึ่งประโยคส่งอีเวนต์ตามลำดับนี้ โดยทุกอีเวนต์ระบุ context ของตัวเอง
{"type":"started","context_id":"call-1042","connection":"7d9c2b7e-4a41-4c8e-9a35-1f26d8c04b7a","model":"paxa-tts-flash-v2","voice":"khanomkrok","format":"mp3","sample_rate":44100}
{"type":"charged","context_id":"call-1042","seq":1,"chars":36,"credits":0.36,"total_credits":0.36}
{"type":"flushed","context_id":"call-1042","seq":1}
{"type":"done","context_id":"call-1042","total_chars":36,"total_credits":0.36}
{"type":"closed","context_id":"call-1042","code":1000,"reason":"session complete"}เฮดเดอร์ของเฟรมไบนารี#
เฟรมไบนารีทุกเฟรมขึ้นต้นด้วยหนึ่งไบต์ที่บอกความยาวของ context id ตามด้วย id ในรูป ASCII แล้วจึงเป็นเสียง บน /v1/tts/multi เซิร์ฟเวอร์เป็นฝ่ายส่งเฟรมเหล่านี้ แต่ละเฟรมเป็นเสียงในรูปแบบของ context นั้น บน /v1/stt/multi ไคลเอนต์เป็นฝ่ายส่ง ตามการเข้ารหัสและ sample rate ที่ start ของ context นั้นระบุไว้ หนึ่งเฟรมมีขนาดไม่เกิน 64 KiB รวมเฮดเดอร์ และส่งเสียงตามหลัง start ได้ทันที
offset bytes content 0 1 9, the length of the id 1 9 "call-1042" in ASCII 10 rest audio
ไคลเอนต์ฝั่งถอดเสียงเขียนเฮดเดอร์นำหน้าเสียงทุกก้อนที่ส่ง
import { open } from "node:fs/promises";
// Runs on Bun as-is; on Node, `import WebSocket from "ws"` accepts
// the same constructor options.
const socket = new WebSocket("wss://api.paxalabs.com/v1/stt/multi", {
headers: { Authorization: `Bearer ${process.env.PAXA_API_KEY}` },
});
const send = (frame: object) => socket.send(JSON.stringify(frame));
const ascii = new TextEncoder();
// One byte counts the id, then the id in ASCII, then the audio.
function audioFrame(contextId: string, audio: Uint8Array) {
const id = ascii.encode(contextId);
const frame = new Uint8Array(1 + id.length + audio.length);
frame[0] = id.length;
frame.set(id, 1);
frame.set(audio, 1 + id.length);
return frame;
}
// One context per call, named by your own call id. Audio may follow
// start at once.
async function listen(contextId: string) {
send({
type: "start",
context_id: contextId,
model: "paxa-stt-lite-realtime-v1-preview",
audio: { encoding: "pcm_s16le", sample_rate: 16000 },
});
// 16 kHz signed 16-bit mono is 32,000 bytes a second. A call delivers
// frames at this pace on its own; a file has to be paced.
const file = await open(`${contextId}.pcm`);
const chunk = new Uint8Array(640); // 20 ms
for (;;) {
const { bytesRead } = await file.read(chunk, 0, chunk.length);
if (bytesRead === 0) break;
socket.send(audioFrame(contextId, chunk.subarray(0, bytesRead)));
await new Promise((resolve) => setTimeout(resolve, 20));
}
send({ type: "end", context_id: contextId });
}
const calls = new Set(["call-1042", "call-1043"]);
socket.onopen = () => {
for (const contextId of calls) void listen(contextId);
};
socket.onmessage = (event) => {
const message = JSON.parse(String(event.data));
switch (message.type) {
case "transcript":
if (message.is_final) console.log(`${message.context_id}: ${message.text}`);
break;
case "draining":
// The server is restarting: start new contexts on another socket
// and move each call there at its next turn boundary.
break;
case "closed":
// The context's last event. Its id is free for a new start.
calls.delete(message.context_id);
if (calls.size === 0) socket.close();
}
};import json
import os
import time
from websockets.sync.client import connect # pip install websockets
CALLS = ["call-1042", "call-1043"]
def audio_frame(context_id, audio):
# One byte counts the id, then the id in ASCII, then the audio.
header = context_id.encode("ascii")
return bytes([len(header)]) + header + audio
with connect(
"wss://api.paxalabs.com/v1/stt/multi",
additional_headers={"Authorization": f"Bearer {os.environ['PAXA_API_KEY']}"},
) as socket:
# One context per call, named by your own call id.
for context_id in CALLS:
socket.send(json.dumps({
"type": "start",
"context_id": context_id,
"model": "paxa-stt-lite-realtime-v1-preview",
"audio": {"encoding": "pcm_s16le", "sample_rate": 16000},
}))
# Audio may follow start at once.
# 16 kHz signed 16-bit mono is 32,000 bytes a second; a file
# has to be paced the way a call paces itself.
files = {context_id: open(f"{context_id}.pcm", "rb") for context_id in CALLS}
while files:
for context_id, audio in list(files.items()):
if chunk := audio.read(640): # 20 ms
socket.send(audio_frame(context_id, chunk))
continue
audio.close()
del files[context_id]
socket.send(json.dumps({"type": "end", "context_id": context_id}))
time.sleep(0.02)
running = set(CALLS)
for message in socket:
event = json.loads(message)
if event["type"] == "draining":
# The server is restarting: start new contexts on another socket
# and move each call there at its next turn boundary.
continue
if event["type"] == "transcript" and event["is_final"]:
print(event["context_id"], event["text"])
elif event["type"] == "closed":
# The context's last event. Its id is free for a new start.
running.discard(event["context_id"])
if not running:
breakcontext จบอย่างไร#
ทุก context จบด้วยอีเวนต์ closed หนึ่งครั้ง และเป็นสิ่งสุดท้ายที่ context นั้นส่ง เว้นแต่ WebSocket จะปิดก่อน ค่า code คือโค้ดปิดของ context นั้น ส่วน reason บอกสาเหตุเดียวกันเป็นข้อความ หลัง closed แล้ว id นั้นนำไปใช้กับ start ใหม่ได้ การปิดของ context หนึ่งไม่กระทบ context อื่น
context แจ้งโค้ด 1000, 1001, 4400, 4401, 4402, 4403, 4408, 4413, 4429, 4500 หรือ 4503 และ context ฝั่งถอดเสียงมี 4502 เพิ่มอีกหนึ่งโค้ด ความหมายของแต่ละโค้ดอยู่ในข้อมูลอ้างอิงของเสียงพูดและการถอดเสียง context ปิดด้วย 4408 เมื่อครบ 300 วินาทีโดยไม่มีเฟรมสำหรับ context นั้นเข้ามา และไม่มีอะไรส่งออกจาก context นั้น
เฟรม JSON ที่ไม่ใช่ start และระบุ id ซึ่งไม่ได้เปิดอยู่ จะได้ error ที่มีโค้ด live_protocol พร้อม context_id นั้น โดยไม่มีอะไรถูกปิด เสียงที่ส่งมาสำหรับ id ซึ่งไม่ได้เปิดอยู่จะถูกทิ้ง ส่วน start บน id ที่เปิดอยู่แล้วถือว่าผิดโปรโตคอล context นั้นส่ง error ตามด้วย closed โค้ด 4400 เฟรม start ที่ไม่ผ่านการตรวจสอบจะได้ error โค้ด validation ตามด้วย closed โค้ด 4400 ให้ส่ง start ที่แก้แล้วด้วย id เดิมหรือ id ใหม่ก็ได้
ข้อผิดพลาดที่ไม่ระบุ context#
บางเฟรมไม่ได้ระบุ context ใดเลย ได้แก่เฟรมที่ไม่ได้เป็นออบเจ็กต์ JSON เฟรมที่ context_id ขาดหายหรือผิดรูปแบบ และเฟรมไบนารีที่เฮดเดอร์ผิดรูปแบบ เฟรมไบนารีทุกเฟรมที่ส่งมายัง /v1/tts/multi ก็นับด้วย เพราะ WebSocket นั้นไม่รับเฟรมไบนารี แต่ละกรณีได้ error ที่มีโค้ด validation โดยไม่มี context_id และไม่มีอะไรถูกปิด
เมื่อเซิร์ฟเวอร์รีสตาร์ต#
ก่อนรีสตาร์ต เซิร์ฟเวอร์ส่งอีเวนต์ draining ที่ไม่มี context_id ไปยังทุก WebSocket ที่มี context เปิดอยู่ ส่วน WebSocket ที่ไม่มี context เปิดอยู่จะปิดด้วย 1001 ทันที ฟิลด์ grace ของอีเวนต์บอกจำนวนวินาทีก่อนที่เซิร์ฟเวอร์จะปิด context ที่ยังเปิดอยู่บน WebSocket นั้น นับจากอีเวนต์นี้ start ใหม่บน WebSocket เดิมจะได้ error ที่มีโค้ด provider_unavailable ตามด้วย closed โค้ด 1001 ส่วน context ที่เปิดอยู่แล้วยังทำงานต่อ
เมื่อได้รับ draining ให้เปิด WebSocket ใหม่และเริ่ม context ใหม่ที่นั่น แล้วย้ายแต่ละสายเมื่อถึงรอยต่อของรอบพูดถัดไป context ที่ยังเปิดอยู่หลังครบเวลา grace จะปิดด้วย 1001 รอบสังเคราะห์ที่กำลังทำงานอยู่จะทำจนจบหรือได้เครดิตคืน ส่วนการถอดเสียงคิดค่าบริการตามเสียงที่รับเข้ามาแล้ว
ลิมิตและค่าบริการ#
context ที่เปิดอยู่แต่ละตัวถือหนึ่งช่องคำขอพร้อมกันของแพ็กเกจในฝั่งผลิตภัณฑ์ของตัวเอง ตั้งแต่เฟรม start จนถึง closed context และการเชื่อมต่อเดียวนับรวมกันในโควตาของแพ็กเกจ ส่วนตัว WebSocket ไม่ถือช่องของตัวเอง start ที่เกินโควตาของแพ็กเกจจะได้ error ที่มีโค้ด concurrency_limited ตามด้วย closed โค้ด 4429
รอบสังเคราะห์เสียงแต่ละรอบนับเป็นหนึ่งคำขอในลิมิตอัตราคำขอต่อนาทีของบัญชี เหมือนบน /v1/tts/live ส่วน context ฝั่งถอดเสียงนับหนึ่งคำขอตอนส่ง start เฟรม start ที่เกินลิมิตจะได้ error โค้ด rate_limited พร้อม retry_after เป็นวินาที ตามด้วย closed โค้ด 4429
แต่ละ context คิดค่าบริการเหมือนเป็นการเชื่อมต่อของตัวเองหนึ่งการเชื่อมต่อ ขั้นต่ำต่อคำขอคิดครั้งเดียวต่อ context ส่วนใบเสร็จ charged และยอดรวมใน done นับเฉพาะ context นั้น อัตราค่าบริการเป็นอัตราเดียวกับเสียงพูดสดและการถอดเสียงแบบเรียลไทม์
ระบบอ่านแพ็กเกจของบัญชีและวงเงินเครดิตของคีย์ซ้ำระหว่างที่ WebSocket ยังเปิดอยู่ การเปลี่ยนแปลงจึงมีผลกับ context ใหม่โดยไม่ต้องเชื่อมต่อใหม่
การปิดที่จบทั้ง WebSocket#
เมื่อ WebSocket ปิด ทุก context ที่ยังเปิดอยู่บนนั้นจบไปด้วยโดยไม่มีอีเวนต์ closed ยกเว้นกรณีโค้ด 4401 และ 4403 WebSocket ปิดด้วยโค้ดต่อไปนี้
| โค้ด | WebSocket ปิดด้วยโค้ดนี้เมื่อ |
|---|---|
| 1001 | เซิร์ฟเวอร์กำลังรีสตาร์ต และไม่มี context เปิดอยู่บน WebSocket แล้ว WebSocket อาจปิดด้วย 1001 ขณะที่ยังมี context เปิดอยู่ได้เช่นกัน |
| 1009 | มีเฟรมที่ใหญ่เกิน 64 KiB |
| 4401 | คีย์ API ใช้ไม่ได้แล้ว โดยทุก context ที่เปิดอยู่แจ้ง closed โค้ด 4401 ก่อน |
| 4403 | คีย์ใช้เครดิตครบวงเงิน โดยทุก context ที่เปิดอยู่แจ้ง closed โค้ด 4403 ก่อน |
| 4408 | ครบ 300 วินาทีโดยไม่มี context เปิดอยู่และไม่มีเฟรมเข้ามา |
| 4413 | ไคลเอนต์อ่านข้อมูลช้าเกินไป |