↓
Rivya AI Docs

Rivya TypeScript SDK

Use Rivya's private beta TypeScript SDK for model discovery, generation polling, signed uploads, credits, webhooks, Chat streaming, and error handling.

Last reviewed on November 11, 2026

Rivya's TypeScript SDK is a private beta for server-side Public API v1 integrations.

It wraps the HTTP endpoints below. OpenAPI and Schema Contract describes request and response shapes; the endpoint guides explain validation and model-specific requirements.

Except for public model listing, requests need Public API access, an active, unexpired API key with the endpoint's scope, and an account allowed to use the API. Model requests also need api_status: "available" and support for the selected inputs.

Prompt units and complete layer results

Read prompt_length_unit together with max_prompt_length from GET /api/v1/models. utf8_bytes counts the original text bytes, including spaces and line breaks; utf16_code_units counts JavaScript UTF-16 units. A null limit does not mean unlimited or optional text. Gemini TTS uses the byte unit.

A completed layer-decomposition result can include result.layers alongside the complete result.urls list. Keep each layer’s z_index, URL, size, name, description and bounding box when provided; index zero is the base image. The TypeScript SDK exposes these fields. Upload references for the selected model and pass its original signed metadata; declared dimensions or duration alone do not replace verification.

Status

The package is named @rivya/sdk and remains private. It has not been published to npm. You need access to Rivya's private SDK source and a build that resolves @rivya/sdk to use these examples.

The client provides methods for:

  • model listing

  • asynchronous generation create and retrieve

  • Files API upload and retrieve

  • credit balance retrieval

  • webhook endpoint management, test deliveries, event listing, delivery listing, and secret rotation

  • webhook signature verification

  • non-streaming and streaming Chat completions, plus API-created chat sessions

Chat streaming is available in this private beta through server-side SSE parsing. Keep secret API keys on your server.

Install In This Repo

These setup commands apply to an existing Rivya source checkout with its dependencies installed. They check the SDK source; they do not download the private beta from npm or build its exported package:

pnpm --dir packages/rivya-sdk typecheck

The examples use a server runtime with fetch, Headers, FormData, Blob, and AbortController. Webhook verification also needs globalThis.crypto.subtle. Keep the package import and secret key on the server:

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

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

Do not place secret API keys in browser bundles, localStorage, analytics events, screenshots, or shared tickets.

RivyaClient accepts baseURL, timeoutMs, fetch, and defaultHeaders in addition to apiKey. It defaults to https://rivya.ai and a 60,000 ms timeout. Request options support idempotencyKey, headers, and signal; the SDK does not automatically retry or poll.

List Models

models.list is public and does not require an 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);
}

The list includes discovery records that cannot currently be called. Check api_status, supported_api_inputs, file_kinds, and chat_capabilities before exposing a model or control. Models marked coming_soon, temporarily_unavailable, or studio_only cannot be called through Public API. The SDK does not grant access to provider-only features.

Create A Generation

Use generations.create for an available asynchronous image, video, or audio model. Chat models use the separate Chat methods:

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 reads a task owned by the API key's account and can refresh its status. It requires generations:read. The SDK does not poll automatically; call it again while the returned status is queued or processing:

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

succeeded and failed are terminal task states, not proof of credit settlement. A successful result can still have primary_url: null; inspect result.urls and settlement_status. A failed HTTP request does not mean the generation task itself failed. See Generation Status and API Credits.

The SDK's idempotencyKey option sets the Idempotency-Key header. For generation and Chat POST requests, use a new key for each new job or turn and keep the key and body unchanged when checking an uncertain request. A stored response can replay; a pending record or a different body can return idempotency_conflict. client_request_id is a tracking label, not a duplicate-request guard.

Upload Files

Use files.upload with files:create for a reference kind accepted by the selected model. Bind the upload to the generation's model ID when that model requires signed metadata:

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 requires files:read and reads an available file owned by the account. It returns the file record and may issue a new duration token, but it does not repeat all metadata from the upload response:

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

Keep the original files.upload response. In the current files.retrieve response, width, height, image_dimensions_token, video_width, video_height, frames_per_second, video_bitrate_mbps, video_file_size_bytes, and video_metadata_token are always null. An audio duration token issued by this GET contains no MIME-type or byte-size binding, so it cannot replace the original upload token for models that require those fields.

For a generation that accepts referenceMediaItems, map the fields from the original upload response into params.referenceMediaItems. The example below uses the same nano-banana-2-lite upload; send signed fields without changing their URL, model, MIME type, dimensions, or size:

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

Reference images for seedream-5-pro, seedream-5-pro-layer-decomposition, nano-banana-2-lite, qwen-image-3, qwen-image-3-pro, and grok-imagine-image-2-0 need the original model-bound upload's mime_type, width, height, size_bytes, and image_dimensions_token. Use them as mimeType, width, height, sizeBytes, and imageDimensionsToken. If the token has expired or the original response is unavailable, re-upload the source image with the same model ID; do not guess its metadata.

Layer Decomposition accepts one image and enforces its geometry limits. Grok Imagine Image 2.0 accepts one to five signed JPEG, PNG, or WebP reference images for editing. Check the model reference pages for the current limits and supported modes.

Signed reference videos for seedance-2-mini, seedance-2-5, minimax-h3, gemini-omni-video, gemini-omni-flash-1-1, and volcengine-video-lip-sync need the original upload's video_width, video_height, frames_per_second, video_bitrate_mbps, video_file_size_bytes, and video_metadata_token. Pass them as width, height, framesPerSecond, videoBitrateMbps, sizeBytes, and videoMetadataToken. Keep durationSeconds and durationToken as a separate signed duration proof. Re-upload if required proof is missing or expired; files.retrieve cannot restore video_metadata_token. Check API Models before choosing video inputs.

For Wan 3.0, upload every reference with model: "wan-3-0-video". Its text, frames, and reference scenes are mutually exclusive. Images require the signed image fields above; videos require both duration and video-metadata proofs. Audio references require mimeType, sizeBytes, durationSeconds, and durationToken from the original model-bound POST upload. The token must bind the MIME type and size, so a token reissued by files.retrieve is not a substitute.

Set seedance_scene, variant, resolution, aspect_ratio, duration, audio, and optional seed inside params. The duration value -1 selects intelligent duration and reserves credits for 30 seconds of output; it cannot be combined with reference video. With reference video, the billable duration includes both output and verified input-video seconds. File-to-video and link-to-video shortcuts are not available.

Upload URLs are temporary. Save your source files and re-upload when a URL or required token is no longer usable. A Files record does not guarantee permanent media storage.

Check Credits

credits.retrieve requires credits:read and returns the account balance from the same credit wallet used by Studio. It does not quote a request or confirm a specific refund:

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

Manage Webhooks

When webhook access is enabled for the deployment and the account's key has webhooks:manage, create an endpoint with an allowed public 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);

Save the signing_secret on your server when creating an endpoint or rotating its secret. Ordinary list and retrieve responses do not include it.

Use webhooks.test only while the endpoint is active; it attempts a delivery to the registered URL. Save the new signing_secret returned by 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 });

Verify delivery signatures before trusting webhook payloads. In this example, rawBody is the unmodified request body string and request is the incoming webhook request; parse the body only after verification:

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

The helper checks HMAC-SHA256 over the timestamp and raw body and, by default, rejects timestamps more than 300 seconds from the local clock. It needs Web Crypto and can throw if that API is unavailable. See API Webhooks for the signature format.

Chat

Use chat.completions.create with chat:create and an available chat model for one non-streaming turn. The currently callable Claude models accept text and thought mode, but not image attachments, web search, or selectable reasoning effort. Check chat_capabilities rather than assuming the provider's features are exposed:

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

Continue with the returned session_id, the same model, and a new key for the next turn:

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

Read sessions with chat:read. These methods return only the account's API-created sessions; they cannot read Studio-only chats. The same account's browser chat history can include API-created sessions:

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

Use chat.completions.stream to consume Server-Sent Events as an async iterator. Handle errors from both the initial call and the subsequent iteration:

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 is display text, not confirmation of a committed reply. message.completed confirms a saved assistant message. Use chat.sessions.retrieve with its session ID to check a reply after a disconnect or error; neither a disconnected stream nor an iterator that simply reaches EOF proves that nothing was saved.

usage.completed includes credits.settlement_status. done marks the successful stream ending, not necessarily settled credits. In this beta, the iterator does not enforce a terminal done event and silently skips unparseable SSE frames. Check completed messages and settlement explicitly; a partial or interrupted stream does not guarantee a refund. See Chat API.

Errors

For non-2xx HTTP responses that the SDK can read, it throws RivyaAPIError. The same class is used for a missing local API key, parsed Chat error events, and SDK stream checks:

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

RivyaAPIError carries a message, status, optional error code and request ID, and an allowed subset of response headers. For a non-2xx response, status is the HTTP status. A parsed Chat stream error event uses SDK status 500 even though streaming began with HTTP 200. Missing stream bodies and unexpected event names can also produce SDK errors.

Network, abort, and response-body read errors can propagate as other errors. A successful HTTP response is parsed as JSON when possible; if parsing fails, the SDK returns the text without validating it against its TypeScript type. Recognized SSE frames are also not schema-validated. An error type alone does not tell you whether a write took effect: check the original task or session before retrying.

Validation

For maintainers with a Rivya source checkout, run the SDK checks after changing the client:

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

pnpm sdk:check combines a static SDK/OpenAPI/docs comparison with mocked, no-network runtime checks for error parsing, safe error headers, idempotency headers, Bearer auth, public model listing, Chat SSE parsing, stream error events, and webhook signature verification. These checks do not call providers or prove model availability, refund settlement, or complete SSE delivery.