Quantum Realtime AI logoQuantum Realtime AI
Developer documentation

Quantum Realtime AI.

Build interactive video experiences with live camera input, character references, and realtime generation.

See what you can build

Explore realtime video use cases. These sample clips illustrate the experiences customers can build with the SDK.

1. Get access through Telegram

Your Quantum customer key is issued for your account through the Quantum API bot.

Open the Quantum API bot

Send /start to activate your account. Use the SDK guides and downloads on this page, and contact support to request your individual customer key.

Open Telegram

Keep your permanent key on your backend only. Do not send it in browser code or commit it to a public repository.

Quickstart

Connect a browser-based JavaScript or TypeScript app to Quantum through your authenticated backend.

1

Get a customer key

Request your Quantum API key from the Telegram bot. Keep the permanent key on your server; never put it in browser code.

2

Install the browser SDK

In your web app project, run:

npm install quantum-realtime-web-sdk
3

Add the authenticated backend proxy

Use the included FastAPI proxy example or implement the same authenticated routes in your backend. Store the key in a private file such as secrets/Quantum_key.txt, outside the public website directory.

4

Connect your app controls

Provide an output element, a prompt input, and an optional image file input. Call start() from your Start button and stop() when the user ends the session.

Compatibility: The JavaScript SDK runs in browser-based JavaScript/TypeScript apps. It can use a Python/FastAPI backend; the browser SDK and server proxy have different jobs.

For the complete copy-ready integration, open SDK Reference → Web → Installation.

SDK Reference · Web · Installation

Copy this complete guide into a coding assistant or use it as the implementation checklist for your app.

Prerequisites

  • A browser-based JavaScript or TypeScript application.
  • HTTPS in production; localhost works during local development.
  • A backend route protected by your app’s real user login.
  • A Quantum customer API key stored privately on the backend.

Installation

npm install quantum-realtime-web-sdk

Backend setup (FastAPI example)

Copy backend/quantum_realtime_proxy.py from the npm package into your backend, then mount it behind your real authenticated-user dependency:

# Python / FastAPI backend
from backend.quantum_realtime_proxy import create_quantum_realtime_router

app.include_router(
  create_quantum_realtime_router(require_customer_login)
)

Set QUANTUM_API_ORIGIN=https://quantum-api-gateway.netlify.app and QUANTUM_API_KEY_FILE to the private key file path. Keep Quantum_key.txt outside the public directory and add it to .gitignore. Do not replace the login dependency with a no-op.

Browser integration

Add an output element, status element, prompt field, and optional image file input to your page. Import the client from the installed package in your JavaScript module:

// JavaScript / TypeScript module
import { QuantumRealtimeClient } from "quantum-realtime-web-sdk";

const sdk = new QuantumRealtimeClient({
  viewElement: document.getElementById("output"),
  backendUrl: "/api/quantum/realtime",
  onStatus: (message) => {
   document.getElementById("status").textContent = message;
  },
});

document.getElementById("start").addEventListener("click", async () => {
  await sdk.start({
   prompt: document.getElementById("prompt").value,
   referenceFile: document.getElementById("reference-image").files[0],
   cameraPosition: "front",
  });
});

document.getElementById("stop").addEventListener("click", async () => {
  const receipt = await sdk.stop();
  console.log(receipt.billed_credits);
});

What the client receives

The browser receives a short-lived session credential through the authenticated same-origin proxy. The permanent Quantum key stays on your server. The realtime camera stream is sent while generation is active, the generated video is rendered inside viewElement, and stop() closes the session and returns the billing receipt.

Reference image

An optional JPG, PNG, or WebP image up to 5 MB can be selected. The SDK uploads it when generation starts and passes it to the realtime session.

Security: Never place the permanent Quantum API key in browser JavaScript, frontend environment variables, browser storage, a mobile app package, or a public repository.

Web · Media Stream

Quantum’s browser SDK captures the selected camera and sends its video track to the realtime engine during generation.

Camera access requires the user’s browser permission. Use HTTPS in production; localhost is allowed for development. Set cameraPosition to front or rear when starting a session.

Web · Realtime Generation

Create a session through your authenticated backend, then start the browser realtime engine with a prompt.

await sdk.start({ prompt, referenceFile, cameraPosition: "front" });

Quantum billing begins once the realtime engine confirms generation is active. Prevent multiple active sessions in your app and always call stop() when the user ends generation.

Web · Video Rendering

Pass the page element where you want the generated realtime video to appear as viewElement.

const sdk = new QuantumRealtimeClient({ viewElement: document.getElementById("output"), backendUrl: "/api/quantum/realtime" });

The SDK attaches the local camera preview and generated remote video to this element. When you call stop(), the SDK detaches the video and returns the billing receipt.

Web · File Upload

Provide an optional reference image as a browser File in the call to start().

Accepted formats are JPG, PNG, and WebP, up to 5 MB. The selected reference image uploads when generation starts. The SDK example does not upload arbitrary video files.

await sdk.start({ prompt, referenceFile: imageInput.files[0], cameraPosition: "front" });

SDK Reference · Python

Use this Python client from a trusted Python server to check your Quantum account, create realtime credentials, and manage billing. It does not capture camera video or render the transformed stream.

Before you begin: A realtime media engine is still required. For browser apps, use the Web SDK for camera capture and video display. Use this Python client when your server needs to call Quantum directly.

Step 1 · Get your Quantum key

Open the Quantum API Telegram bot, start your account, and obtain your customer API key. Store the key only on your trusted server. Never add it to browser JavaScript, a mobile app, or a public repository.

Step 2 · Add the SDK files to your Python project

Add the two Python module files to your backend source tree and copy each code block into its matching file. The optional pyproject.toml is for installing this as a standalone package; if your project already has one, merge the package settings instead of replacing your file.

quantum_sdk/client.py

"""Small dependency-free client for Quantum account and realtime session APIs."""

from __future__ import annotations

import json
from pathlib import Path
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Any


class QuantumError(RuntimeError):
    """An HTTP or API error returned by the Quantum service."""

    def __init__(self, status: int, message: str):
        super().__init__(message)
        self.status = status


@dataclass(frozen=True)
class RealtimeSession:
    session_id: str
    status: str
    expires_at: str
    billing_rate: int
    billing_unit: str
    client_credential: str


class QuantumClient:
    """Client for Quantum APIs. Keep api_key on a trusted server only."""

    def __init__(self, api_key: str, base_url: str, timeout: float = 20):
        if not api_key or not api_key.strip():
            raise ValueError("api_key is required")
        if not base_url or not base_url.strip():
            raise ValueError("base_url is required")
        self._api_key = api_key.strip()
        self._base_url = base_url.rstrip("/")
        self._timeout = timeout

    @classmethod
    def from_key_file(
        cls, key_file: str | Path = "Quantum_key.txt", base_url: str = "", timeout: float = 20
    ) -> "QuantumClient":
        """Create a client from a private text file on the trusted server."""
        path = Path(key_file).expanduser()
        try:
            api_key = path.read_text(encoding="utf-8").strip()
        except OSError as exc:
            raise ValueError(f"Could not read Quantum key file: {path}") from exc
        if not api_key:
            raise ValueError(f"Quantum key file is empty: {path}")
        return cls(api_key=api_key, base_url=base_url, timeout=timeout)

    def _post(self, path: str) -> dict[str, Any]:
        request = urllib.request.Request(
            f"{self._base_url}{path}",
            data=b"{}",
            headers={
                "X-Quantum-Key": self._api_key,
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=self._timeout) as response:
                payload = response.read().decode("utf-8")
        except urllib.error.HTTPError as exc:
            try:
                detail = json.loads(exc.read().decode("utf-8")).get("detail", "Quantum request failed")
            except Exception:
                detail = "Quantum request failed"
            raise QuantumError(exc.code, str(detail)) from exc
        except urllib.error.URLError as exc:
            raise QuantumError(0, "Could not reach the Quantum API") from exc

        try:
            result = json.loads(payload)
        except json.JSONDecodeError as exc:
            raise QuantumError(502, "Quantum returned an invalid response") from exc
        if not isinstance(result, dict):
            raise QuantumError(502, "Quantum returned an unexpected response")
        return result

    def account(self) -> dict[str, Any]:
        request = urllib.request.Request(
            f"{self._base_url}/api/v1/account",
            headers={"X-Quantum-Key": self._api_key, "Accept": "application/json"},
            method="GET",
        )
        try:
            with urllib.request.urlopen(request, timeout=self._timeout) as response:
                result = json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            raise QuantumError(exc.code, "Quantum account request failed") from exc
        except urllib.error.URLError as exc:
            raise QuantumError(0, "Could not reach the Quantum API") from exc
        if not isinstance(result, dict):
            raise QuantumError(502, "Quantum returned an unexpected response")
        return result

    def create_realtime_session(self) -> RealtimeSession:
        result = self._post("/api/v1/realtime/sessions")
        credential = result.get("client_credential")
        if not result.get("session_id") or not credential:
            raise QuantumError(502, "Quantum did not return a session credential")
        return RealtimeSession(
            session_id=result["session_id"],
            status=result.get("status", "issued"),
            expires_at=result.get("expires_at", ""),
            billing_rate=int(result.get("billing_rate", 2)),
            billing_unit=result.get("billing_unit", "Quantum credits per active second"),
            client_credential=credential,
        )

    def start_realtime_session(self, session_id: str) -> dict[str, Any]:
        """Call only after the realtime engine confirms generation is active."""
        return self._post(f"/api/v1/realtime/sessions/{session_id}/start")

    def end_realtime_session(self, session_id: str) -> dict[str, Any]:
        """End billing and ask Quantum to revoke the temporary connection credential."""
        return self._post(f"/api/v1/realtime/sessions/{session_id}/end")

quantum_sdk/__init__.py

"""Quantum API client for server-side Python applications."""

from .client import QuantumClient, QuantumError, RealtimeSession

__all__ = ["QuantumClient", "QuantumError", "RealtimeSession"]

pyproject.toml

[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"

[project]
name = "quantum-api-sdk"
version = "0.1.0"
description = "Quantum API SDK for server-side Python applications"
requires-python = ">=3.10"
dependencies = []

[tool.setuptools.packages.find]
where = ["."]

Step 3 · Install it in your server environment

If you added the SDK folder inside your application’s importable source tree, you can import it there directly. To install it as a standalone local package instead, run this from the directory containing its pyproject.toml, using the same Python environment as your backend:

python -m pip install .

Use Python 3.10 or newer. The client uses Python’s standard library and has no runtime dependencies.

Step 4 · Store the key and configure the API address

Save the key text in a private file such as secrets/Quantum_key.txt, outside any public web folder. Restrict access to the server process and add the file path to .gitignore. Configure these values in the server environment:

QUANTUM_API_ORIGIN=https://quantum-api-gateway.netlify.app
QUANTUM_API_KEY_FILE=/absolute/private/path/secrets/Quantum_key.txt

Step 5 · Create the Quantum client and check the account

Run these calls on the server, after authenticating the app user through your own application:

import os
from quantum_sdk import QuantumClient

quantum = QuantumClient.from_key_file(
    os.environ["QUANTUM_API_KEY_FILE"],
    base_url=os.environ["QUANTUM_API_ORIGIN"],
)

account = quantum.account()
print("Quantum account:", account)

Step 6 · Connect session creation to your realtime engine

Create a short-lived session and pass its temporary credential to the realtime media engine your app uses. The engine-specific calls below are placeholders: replace them with the methods and active/stop events from your engine.

session = quantum.create_realtime_session()

try:
    # Application-specific: connect your realtime engine with this temporary credential.
    engine.connect(client_credential=session.client_credential, prompt=prompt)
    # Wait for the engine to confirm that generation is active.
    engine.wait_until_active()
    quantum.start_realtime_session(session.session_id)

    # Keep the session open while the user is receiving generated output.
    engine.wait_until_stopped()
finally:
    # Attempt both cleanup steps if the realtime engine stops unexpectedly.
    try:
        engine.stop()
    finally:
        receipt = quantum.end_realtime_session(session.session_id)
        print("Billed credits:", receipt["billed_credits"])

Call start_realtime_session() only after generation is confirmed active. Always call end_realtime_session() when generation stops so Quantum can close billing and return the receipt. Quantum’s API response provides the active rate.

Step 7 · For a web app, connect the browser SDK too

The Python client does not send browser camera frames. In a web app, install the quantum-realtime-web-sdk, use the authenticated backend proxy, and point the browser SDK’s backendUrl to your route. The browser JavaScript captures the camera and displays generated video; the server keeps the permanent key private. Follow the Web SDK installation guide for the complete browser and FastAPI setup.

Security: Protect your backend route with your app’s real login. Do not expose the permanent Quantum key or return it to the browser. The app’s login identifies its own users; the Quantum key identifies the customer account billed by Quantum.

If your server is not Python, use the equivalent Quantum API calls from that server language. For help, contact Quantum support. Never send your API key in a support message.

3. Set up your backend

The permanent customer key belongs on the customer’s server. The included example proxy is for FastAPI.

1

Store the key privately

Save it in a private file such as secrets/Quantum_key.txt, outside the public website folder. Add that path to .gitignore.

2

Mount the authenticated proxy

Copy backend/quantum_realtime_proxy.py from the SDK and mount it behind your application’s real login dependency. Do not use a no-op login check.

3

Set server configuration

Configure QUANTUM_API_ORIGIN=https://quantum-api-gateway.netlify.app and QUANTUM_API_KEY_FILE to the private key file path.

Important: Never put the permanent Quantum API key in browser JavaScript, a public folder, a mobile app package, or source control.

Browser setup

Serve your app over HTTPS in production (localhost works during development) and expose the authenticated Quantum proxy at /api/quantum/realtime on the same origin.

Install the npm package in your browser app’s project and import QuantumRealtimeClient from quantum-realtime-web-sdk. Keep the package’s runtime assets and subfolders intact when building or deploying.

The Web Installation reference contains a complete copy-ready browser sample and authenticated FastAPI proxy setup.

Reference images and camera

The JavaScript SDK accepts an optional JPG, PNG, or WebP reference image. It uploads the selected image when generation starts so the realtime service can use it.

Camera access

Browser camera permission is required. Use HTTPS in deployed apps; localhost is allowed for local development.

Session lifecycle

Start generation only when ready. Call stop() when finished so the session closes and the Quantum billing receipt is returned.

Security and key handling

The browser receives only a short-lived session credential from the authenticated backend proxy. Your permanent key stays server-side.

  • Use the app’s real authentication dependency on the proxy.
  • Keep Quantum_key.txt outside public directories and source control.
  • Do not expose the permanent key in frontend bundles, browser storage, or client apps.

Need help?

Contact our support account on Telegram. Include your programming language and a short description of your backend framework. Never include your API key in a support message.

Contact support on Telegram ↗