Rivya TypeScript SDK
使用 Rivya TypeScript SDK 測試版呼叫 Public API v1,涵蓋模型、生成任務、檔案、點數、Webhook,以及支援 SSE 串流的 Chat。
最近審閱於 2026年11月5日
Rivya 提供測試版 TypeScript SDK,供伺服器端整合公開 API。
SDK 是 Rivya 公開 API v1 上的一層輕量用戶端。底層規格仍以 OpenAPI 與結構描述規格為準,SDK 方法必須與該結構描述保持一致。
本文介紹的是已實作的公開 API v1 規格。實際能否執行,仍取決於目前部署是否啟用公開 API、帳號是否有有效的 API 金鑰,以及所選模型在即時模型清單中是否標示為可透過 API 使用;有文件不代表每個環境都能呼叫。
狀態
@rivya/sdk 是尚未發佈到 npm 的私有測試版。執行範例前,需要取得 Rivya 私有 SDK 原始碼,並建立能解析 @rivya/sdk 的環境。
用戶端提供模型查詢、非同步生成任務建立與查詢、Files API 上傳與查詢、點數餘額查詢、Webhook 端點管理與測試投遞、事件與投遞紀錄查詢、密鑰輪換、簽章驗證,以及非串流和串流 Chat 與 API 工作階段方法。串流 Chat 使用伺服器端 SSE 解析;秘密 API 金鑰應留在伺服器端。
從本程式碼庫安裝
以下命令適用於已安裝相依套件的 Rivya 原始碼檢出目錄,只檢查 SDK 原始碼,不從 npm 下載私有測試版,也不建置匯出的套件:
pnpm --dir packages/rivya-sdk typecheck伺服器執行環境需要 fetch、Headers、FormData、Blob 和 AbortController;Webhook 驗證還需要 globalThis.crypto.subtle。套件匯入與秘密金鑰都應放在伺服器端:
import { RivyaClient } from "@rivya/sdk";
const rivya = new RivyaClient({
apiKey: process.env.RIVYA_API_KEY
});不要把秘密 API 金鑰放進瀏覽器套件、localStorage、分析事件、截圖或共用工單。
除 apiKey 外,RivyaClient 接受 baseURL、timeoutMs、fetch 和 defaultHeaders,預設基礎位址為 https://rivya.ai,逾時為 60,000 毫秒。請求選項支援 idempotencyKey、headers 和 signal;SDK 不會自動重試或輪詢。
列出模型
models.list 是公開介面,不需要 API 金鑰:
const models = await rivya.models.list();
for (const model of models.data) {
console.log(model.id, model.api_status, model.supported_api_inputs);
}清單也包含目前無法呼叫的探索紀錄。顯示模型或控制項前,檢查 api_status、supported_api_inputs、file_kinds 和 chat_capabilities。coming_soon、temporarily_unavailable 和 studio_only 模型無法透過 Public API 呼叫;SDK 不會額外開放供應商專有功能。
建立生成任務
對可用的非同步圖片、影片或音訊模型使用 generations.create;聊天模型使用獨立的 Chat 方法:
const generation = await rivya.generations.create(
{
model: "z-image",
prompt: "A clean editorial product image on a soft studio background",
client_request_id: "order-123-preview"
},
{
idempotencyKey: "order-123-preview"
}
);
console.log(generation.id, generation.status);generations.retrieve 讀取目前 API 金鑰所屬帳號的任務,並可能更新狀態,需要 generations:read。SDK 不會自動輪詢;狀態為 queued 或 processing 時需再次查詢:
const current = await rivya.generations.retrieve(generation.id);
console.log(current.status, current.result?.primary_url);succeeded 和 failed 是任務終態,不能證明點數已結算。成功結果的 primary_url 仍可能為 null;檢查 result.urls 和 settlement_status。HTTP 請求失敗也不代表生成任務失敗。參閱生成狀態與API 點數。
idempotencyKey 設定 Idempotency-Key 標頭。生成和 Chat POST 的每個新任務或新回合使用新鍵;核查結果不明的請求時,保持原 API 金鑰、冪等鍵與本文不變。已存回應可以重播;處理中紀錄或不同本文可傳回 idempotency_conflict。client_request_id 只是追蹤標籤,無法防止重複請求。
上傳檔案
使用具有 files:create 權限的金鑰呼叫 files.upload,上傳模型接受的參考素材類型。需要簽章中繼資料的模型須綁定該生成模型 ID:
import { readFile } from "node:fs/promises";
const file = new Blob([await readFile("./reference.png")], {
type: "image/png"
});
const uploaded = await rivya.files.upload({
file,
filename: "reference.png",
kind: "image",
model: "nano-banana-2-lite",
client_request_id: "asset-123"
});
console.log(uploaded.id, uploaded.url);files.retrieve 需要 files:read,讀取帳號擁有的可用檔案,可能重新簽發時長 token,但不會重複上傳回應的全部中繼資料:
const sameFile = await rivya.files.retrieve(uploaded.id);
console.log(sameFile.mime_type, sameFile.duration_token);保留原始上傳回應。目前 GET 中 width、height、image_dimensions_token、video_width、video_height、frames_per_second、video_bitrate_mbps、video_file_size_bytes 和 video_metadata_token 一律為 null。GET 簽發的音訊時長 token 不綁定 MIME 或位元組數,不能取代要求這些欄位的原始上傳 token。
接受 referenceMediaItems 的生成請求須把原始回應對應至 params.referenceMediaItems。下例沿用同一次 nano-banana-2-lite 上傳,不能更改簽章欄位對應的 URL、模型、MIME、尺寸或大小:
await rivya.generations.create({
model: "nano-banana-2-lite",
prompt: "Restyle this product photo for a clean editorial catalog page",
params: {
referenceMediaItems: [
{
url: uploaded.url,
kind: uploaded.kind,
name: uploaded.file_name,
mimeType: uploaded.mime_type,
durationSeconds: uploaded.duration_seconds ?? undefined,
durationToken: uploaded.duration_token ?? undefined,
width: uploaded.video_width ?? uploaded.width ?? undefined,
height: uploaded.video_height ?? uploaded.height ?? undefined,
sizeBytes: uploaded.video_file_size_bytes ?? uploaded.size_bytes,
imageDimensionsToken: uploaded.image_dimensions_token ?? undefined,
framesPerSecond: uploaded.frames_per_second ?? undefined,
videoBitrateMbps: uploaded.video_bitrate_mbps ?? undefined,
videoMetadataToken: uploaded.video_metadata_token ?? undefined
}
]
}
});seedream-5-pro、seedream-5-pro-layer-decomposition、nano-banana-2-lite、qwen-image-3、qwen-image-3-pro 和 grok-imagine-image-2-0 的參考圖需要原始模型綁定上傳的 mime_type、width、height、size_bytes、image_dimensions_token,依序對應為 mimeType、width、height、sizeBytes、imageDimensionsToken。token 過期或原回應遺失時,以相同模型 ID 重新上傳,不猜測中繼資料。
圖層拆分只接受一張圖片並檢查幾何邊界;Grok Imagine Image 2.0 編輯接受 1–5 張已簽章的 JPEG、PNG 或 WebP 參考圖。查看模型參考了解目前模式與限制。
seedance-2-mini、seedance-2-5、minimax-h3、gemini-omni-video、gemini-omni-flash-1-1 和 volcengine-video-lip-sync 的參考影片需要原上傳的 video_width、video_height、frames_per_second、video_bitrate_mbps、video_file_size_bytes、video_metadata_token,依序傳為 width、height、framesPerSecond、videoBitrateMbps、sizeBytes、videoMetadataToken。另保留 durationSeconds 和 durationToken 時長證明。證明缺失或過期須重新上傳;GET 無法還原 video_metadata_token。選擇影片輸入前查看API 模型。
Wan 3.0 每份參考素材均須以 model: "wan-3-0-video" 上傳。text、frames、reference 三個場景互斥;圖片需要上述簽章圖片欄位,影片同時需要時長與影片中繼資料證明,音訊需要原始 POST 回應中對應 mimeType、sizeBytes、durationSeconds、durationToken 的值。音訊 token 必須綁定 MIME 與大小,GET 重簽 token 不能取代。
在 params 設定 seedance_scene、variant、resolution、aspect_ratio、duration、audio 及選用 seed。duration: -1 為智慧時長,按 30 秒輸出預留點數,不能搭配參考影片;有參考影片時,計費時長包括輸出與已驗證的輸入影片秒數。不提供檔案轉影片或連結轉影片捷徑。
上傳 URL 有時效性。保留來源檔案,URL 或必要 token 無法使用時重新上傳;Files 紀錄不保證永久儲存媒體。
檢查點數
credits.retrieve 需要 credits:read,傳回與 Studio 共用的錢包餘額,不提供請求報價,也不能確認某筆退款:
const credits = await rivya.credits.retrieve();
console.log(credits.current_credits);管理 Webhooks
部署啟用 Webhook 且帳號金鑰具有 webhooks:manage 時,可使用符合規則的公開 URL 建立端點:
const endpoint = await rivya.webhooks.create({
name: "Production webhook",
url: "https://example.com/rivya/webhook",
event_types: ["generation.succeeded", "generation.failed"]
});
const signingSecret = endpoint.signing_secret;
console.log(endpoint.id);建立或輪換時把 signing_secret 安全儲存在伺服器端;一般清單與查詢回應不包含它。
僅對啟用中的端點使用 webhooks.test,它會向註冊 URL 嘗試真實投遞。儲存 webhooks.rotateSecret 傳回的新密鑰;輪換不為舊密鑰提供寬限期:
await rivya.webhooks.list();
await rivya.webhooks.retrieve(endpoint.id);
await rivya.webhooks.test(endpoint.id);
await rivya.webhooks.update(endpoint.id, { status: "disabled" });
const rotatedEndpoint = await rivya.webhooks.rotateSecret(endpoint.id);
const rotatedSigningSecret = rotatedEndpoint.signing_secret;
await rivya.webhooks.deliveries.list(endpoint.id, { limit: 20 });
await rivya.webhookEvents.list({ limit: 20 });信任 Webhook 本文前先驗證簽章。下例 rawBody 是未修改的請求本文字串,request 是收到的請求,驗證後再解析:
import { verifyRivyaWebhookSignature } from "@rivya/sdk";
const ok = await verifyRivyaWebhookSignature({
rawBody,
timestamp: request.headers.get("rivya-webhook-timestamp") || "",
signatureHeader: request.headers.get("rivya-webhook-signature") || "",
signingSecret: process.env.RIVYA_WEBHOOK_SIGNING_SECRET || ""
});
if (!ok) {
throw new Error("Invalid Rivya webhook signature");
}輔助方法驗證時間戳記與原始本文的 HMAC-SHA256,預設拒絕與本機時鐘相差超過 300 秒的時間戳記。需要 Web Crypto,缺少該 API 時可能擲出錯誤。簽章格式見 API Webhooks。
Chat
使用 chat:create 與可用聊天模型,透過 chat.completions.create 傳送一回合非串流請求。目前可呼叫的 Claude 模型支援文字與思考模式,不支援圖片附件、網路搜尋或可選推理強度;以 chat_capabilities 為準:
const completion = await rivya.chat.completions.create(
{
model: "claude-sonnet-5-chat",
message: "Write a concise launch plan for a new product image campaign",
client_request_id: "chat-001"
},
{
idempotencyKey: "chat-001"
}
);
console.log(completion.session_id, completion.message.content);使用傳回的 session_id、相同模型及下一回合的新冪等鍵繼續:
await rivya.chat.completions.create(
{
model: "claude-sonnet-5-chat",
session_id: completion.session_id,
message: "Now turn that into a 5-step execution checklist."
},
{
idempotencyKey: "chat-002"
}
);讀取工作階段需要 chat:read。僅傳回帳號的 API 工作階段,不能讀取僅在 Studio 建立的工作階段;相同帳號的瀏覽器聊天紀錄也可能包含 API 工作階段:
await rivya.chat.sessions.list({ limit: 20 });
await rivya.chat.sessions.retrieve(completion.session_id);用 chat.completions.stream 的非同步迭代器讀取 SSE,同時處理初始呼叫與後續迭代的錯誤:
const stream = await rivya.chat.completions.stream(
{
model: "claude-sonnet-5-chat",
message: "Write a concise launch plan for a new product image campaign",
client_request_id: "chat-stream-001"
},
{
idempotencyKey: "chat-stream-001"
}
);
for await (const event of stream) {
if (event.event === "message.delta") {
process.stdout.write(event.data.delta);
}
if (event.event === "message.completed") {
console.log(event.data.message.id);
}
}message.delta 用於顯示,不能證明回覆已儲存;message.completed 確認助理訊息已提交。斷線或錯誤後以工作階段 ID 呼叫 chat.sessions.retrieve 核查。斷線或迭代器直接到達 EOF 都不能證明未儲存。
usage.completed 包含 credits.settlement_status。done 代表串流成功結束,不保證點數已結算。測試版迭代器不強制要求 done,並靜默略過無法解析的 SSE 影格;需明確核查訊息與結算,部分回應或中斷不保證退款。參閱 Chat API。
錯誤
SDK 對能讀取的非 2xx HTTP 回應擲出 RivyaAPIError;缺少本機 API 金鑰、解析到 Chat 錯誤事件及部分串流檢查也使用此類型:
import { RivyaAPIError } from "@rivya/sdk";
try {
await rivya.generations.retrieve("task_missing");
} catch (error) {
if (error instanceof RivyaAPIError) {
console.log(error.status, error.code, error.requestId);
} else {
throw error;
}
}它包含訊息、狀態、選用錯誤碼與請求 ID,以及允許公開的回應標頭子集。非 2xx 時 status 為 HTTP 狀態;Chat 串流錯誤事件使用 SDK 狀態 500,即使串流以 HTTP 200 開始。缺少回應串流本文或出現非預期事件名稱也可能產生 SDK 錯誤。
網路、中止與本文讀取錯誤可能以其他錯誤類型傳播。成功 HTTP 回應盡可能按 JSON 解析,失敗則傳回文字,不按 TypeScript 類型驗證;識別到的 SSE 影格也不做 schema 驗證。錯誤類型不能證明寫入是否生效,重試前核查原任務或工作階段。
驗證
維護者在 Rivya 原始碼目錄修改用戶端後執行:
pnpm sdk:check
pnpm --dir packages/rivya-sdk typecheck
pnpm content:api-docspnpm sdk:check 結合 SDK/OpenAPI/文件靜態比對與無網路模擬執行檢查,涵蓋錯誤解析、安全錯誤標頭、冪等標頭、Bearer 驗證、公開模型清單、Chat SSE 解析與錯誤事件、Webhook 簽章。它不呼叫供應商,也不證明模型可用、退款結算或 SSE 完整送達。
