Docs Rivya AI

Rivya TypeScript SDK

Dùng Rivya TypeScript SDK beta để gọi Public API v1 cho models, generations, files, credits, webhooks và Chat bao gồm SSE streaming.

Đánh giá lần cuối vào 2026/05/11

Rivya cung cấp TypeScript SDK beta cho tích hợp Public API phía server.

SDK là client mỏng trên Rivya Public API v1. Hợp đồng cấp thấp hơn vẫn là OpenAPI và hợp đồng schema, và các phương thức SDK phải luôn khớp với schema đó.

Trạng thái

Package hiện được duy trì trong repository này dưới dạng private beta. Nó chưa được publish lên npm cho đến khi tên package, metadata, changelog và quy trình phát hành được phê duyệt rõ ràng.

SDK hỗ trợ:

  • liệt kê mô hình
  • tạo và lấy lại generation bất đồng bộ
  • tải lên và lấy lại Files API
  • lấy số dư credits
  • quản lý webhook endpoint, test deliveries, liệt kê event, liệt kê delivery và xoay vòng secret
  • xác minh chữ ký webhook
  • Chat completions không streaming và streaming, cùng chat sessions do API tạo

Chat streaming có trong private beta này thông qua phân tích SSE phía server. Hãy giữ secret API keys trên server của bạn.

Cài trong repo này

Dùng nguồn package cục bộ khi SDK còn ở beta:

pnpm --dir packages/rivya-sdk typecheck

Mã ứng dụng nên giữ secret API key trên server:

import { RivyaClient } from "@rivya/sdk";

const rivya = new RivyaClient({
  apiKey: process.env.RIVYA_API_KEY
});

Đừng đặt secret API keys trong browser bundles, localStorage, sự kiện analytics, ảnh chụp màn hình hoặc ticket chia sẻ.

Liệt kê mô hình

models.list là public và không cần API key:

const models = await rivya.models.list();

for (const model of models.data) {
  console.log(model.id, model.api_status, model.supported_api_inputs);
}

Tạo generation

Dùng generations.create cho generation hình ảnh, video hoặc âm thanh bất đồng bộ:

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);

Sau đó poll bằng generations.retrieve:

const current = await rivya.generations.retrieve(generation.id);
console.log(current.status, current.result?.primary_url);

Dùng Idempotency-Key cho các yêu cầu ghi production. SDK expose trường này dưới dạng idempotencyKey.

Tải tệp lên

Dùng files.upload cho ảnh, video hoặc âm thanh tham chiếu:

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",
  client_request_id: "asset-123"
});

console.log(uploaded.id, uploaded.url);

Dùng files.retrieve để đọc lại metadata đã tải lên:

const sameFile = await rivya.files.retrieve(uploaded.id);
console.log(sameFile.mime_type, sameFile.duration_token);

Khi dùng một tệp trong generation, hãy truyền các trường công khai được trả về qua params.referenceMediaItems:

await rivya.generations.create({
  model: "nano-banana-2",
  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
      }
    ]
  }
});

Kiểm tra credits

const credits = await rivya.credits.retrieve();
console.log(credits.current_credits);

Quản lý Webhooks

Tạo một webhook endpoint:

const endpoint = await rivya.webhooks.create({
  name: "Production webhook",
  url: "https://example.com/rivya/webhook",
  event_types: ["generation.succeeded", "generation.failed"]
});

console.log(endpoint.id, endpoint.signing_secret);

signing_secret chỉ được trả về sau lệnh create hoặc rotate. Hãy lưu nó trên server của bạn.

Các webhook helper khác:

await rivya.webhooks.list();
await rivya.webhooks.retrieve(endpoint.id);
await rivya.webhooks.update(endpoint.id, { status: "disabled" });
await rivya.webhooks.test(endpoint.id);
await rivya.webhooks.rotateSecret(endpoint.id);
await rivya.webhooks.deliveries.list(endpoint.id, { limit: 20 });
await rivya.webhookEvents.list({ limit: 20 });

Xác minh chữ ký delivery trước khi tin webhook payload:

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");
}

SDK helper dùng cùng hợp đồng HMAC-SHA256 được ghi trong API Webhooks.

Chat

Dùng chat.completions.create cho một lượt Chat API không streaming:

const completion = await rivya.chat.completions.create(
  {
    model: "gpt-5-2-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);

Tiếp tục bằng session_id được trả về:

await rivya.chat.completions.create({
  model: "gpt-5-2-chat",
  session_id: completion.session_id,
  message: "Now turn that into a 5-step execution checklist."
});

Đọc sessions do API tạo:

await rivya.chat.sessions.list({ limit: 20 });
await rivya.chat.sessions.retrieve(completion.session_id);

Dùng chat.completions.stream để tiêu thụ Server-Sent Events như một async iterator:

const stream = await rivya.chat.completions.stream(
  {
    model: "gpt-5-2-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 chỉ dùng để hiển thị. Kết quả đã commit có sau message.completed, và có thể đọc lại sau bằng chat.sessions.retrieve.

Lỗi

SDK ném RivyaAPIError cho phản hồi Public API không phải 2xx:

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);
  }
}

RivyaAPIError bao gồm HTTP status, mã lỗi công khai, message, request id khi có và một tập con response-header an toàn.

Kiểm tra

Chạy các kiểm tra SDK trước khi xem một thay đổi là hoàn tất:

pnpm sdk:check
pnpm --dir packages/rivya-sdk typecheck
pnpm content:api-docs

pnpm sdk:check bao gồm kiểm tra hợp đồng tĩnh và kiểm tra runtime không dùng mạng cho phân tích lỗi, safe error headers, idempotency headers, Bearer auth, liệt kê mô hình công khai, phân tích Chat streaming SSE, sự kiện lỗi Chat streaming và xác minh chữ ký webhook.

Trang liên quan

Mục lục