TypeScript SDK

The official JavaScript/TypeScript SDK for interacting with the Skytells API. Works in Node.js, browsers, and edge runtimes (Cloudflare Workers, Vercel Edge, Netlify Edge). Generate text, photos, videos, avatars, audio, music, and more using Skytells' own models and partner models — all through a single API.

Installation

Adding to your project

The Skytells TypeScript SDK is distributed as an npm package and can be installed with your preferred package manager. It has zero dependencies and is optimized for edge environments.

After installation, you can import the SDK into your project and start making API calls with just a few lines of code.

npm install skytells

Package.json Setup

{
  "dependencies": {
    "skytells": "^1.0.3"
  }
}

Quick Start

Getting Started with Skytells

The SDK provides a simple and intuitive interface for interacting with the Skytells API. The main entry point is the default Skytells export, which returns a client instance with methods for running predictions, managing models, and more.

The example on the right demonstrates the basic workflow:

  1. Import and initialize the client with your API key
  2. Run a prediction using a model
  3. Process the results
Example
Basic Usage
import Skytells from 'skytells';

// Initialize the client with your API key
const skytells = Skytells('your-api-key');

Complete Example

import Skytells from 'skytells';

async function main() {
  const skytells = Skytells('your-api-key');

  // List available models
  const models = await skytells.models.list();
  console.log('Available models:', models.map(m => m.name));

  // Run a prediction and wait for the result
  const prediction = await skytells.run('truefusion', {
    input: { prompt: 'A sunset over mountains' },
  });

  console.log('Status:', prediction.status);    // "succeeded"
  console.log('Output:', prediction.outputs());  // "https://..."

  // Access full raw response
  const raw = prediction.raw();
  console.log('Predict time:', raw.metrics?.predict_time);
  console.log('Credits used:', raw.metadata?.billing?.credits_used);
}

main().catch(console.error);

Authentication

Setting Up Authentication

To access the Skytells API, you need an API key from your Skytells dashboard. API keys start with sk- and authenticate your requests.

The SDK supports both authenticated and unauthenticated clients, though most functionality requires authentication.

Authentication
Authentication Options
import Skytells from 'skytells';

// With API key (authenticated)
const skytells = Skytells('sk-your-api-key');

Environment Variables

In a Node.js environment, you can use environment variables to store your API key securely:

// .env file
SKYTELLS_API_KEY=sk-your-api-key

// In your code
import Skytells from 'skytells';

const skytells = Skytells(process.env.SKYTELLS_API_KEY);

Client Options

Pass an options object as the second argument to configure the client's behavior, including custom API URLs, timeouts, retry logic, and a custom fetch implementation.

ClientOptions

  • Name
    baseUrl
    Type
    string
    Description

    API base URL.

  • Name
    timeout
    Type
    number
    Description

    Request timeout in milliseconds.

  • Name
    headers
    Type
    Record<string, string>
    Description

    Custom headers included in every request.

  • Name
    retry
    Type
    RetryOptions
    Description

    Retry configuration (see below).

  • Name
    fetch
    Type
    typeof fetch
    Description

    Custom fetch implementation.

RetryOptions

  • Name
    retries
    Type
    number
    Description

    Number of retry attempts.

  • Name
    retryDelay
    Type
    number
    Description

    Base delay between retries (ms).

  • Name
    retryOn
    Type
    number[]
    Description

    HTTP status codes that trigger retry.

Options
Client Options
import Skytells from 'skytells';

const skytells = Skytells('sk-your-api-key', {
  // Custom API base URL
  baseUrl: 'https://api.skytells.ai/v1',

  // Request timeout in milliseconds (default: 60000)
  timeout: 30000,

  // Custom headers included in every request
  headers: {
    'X-Custom-Header': 'value',
  },

  // Retry configuration
  retry: {
    retries: 3,
    retryDelay: 1000,
    retryOn: [429, 500, 502, 503, 504],
  },

  // Custom fetch (e.g. Next.js cache workaround)
  fetch: (url, opts) =>
    fetch(url, { ...opts, cache: 'no-store' }),
});

Running Predictions

Basic Run

The run() method takes a model slug and options, creates a prediction, polls until completion, and returns a Prediction object.

Required attributes

  • Name
    model
    Type
    string
    Description

    Model slug (e.g. "truefusion", "flux-pro").

  • Name
    options
    Type
    RunOptions
    Description

    { input, stream?, webhook? }

Optional attributes

  • Name
    onProgress
    Type
    OnProgressCallback
    Description

    Called on each poll with latest status.

Returns: Promise<Prediction>

run()
Running Predictions
import Skytells from 'skytells';

const skytells = Skytells('sk-your-api-key');

const prediction = await skytells.run('truefusion', {
  input: { prompt: 'A cat wearing sunglasses' },
});

console.log(prediction.output);    // "https://..." or ["https://...", ...]
console.log(prediction.output[0]); // first output if array
console.log(prediction.id);        // "pred_abc123"
console.log(prediction.status);    // "succeeded"

Progress Tracking

Tracking Progress

Pass an onProgress callback as the third argument to run(). The SDK creates the prediction in the background and polls every 5 seconds, invoking the callback on each poll.

const prediction = await skytells.run(
  'truefusion',
  { input: { prompt: 'A detailed landscape painting' } },
  (p) => {
    console.log(`Status: ${p.status}`);
    if (p.metrics?.progress !== undefined) {
      console.log(`Progress: ${p.metrics.progress}%`);
    }
  },
);

console.log(prediction.outputs());

Run with Webhook

Webhook Notifications

Pass a webhook option to receive notifications when the prediction completes or fails.

const prediction = await skytells.run('truefusion', {
  input: { prompt: 'A robot painting a sunset' },
  webhook: {
    url: 'https://your-server.com/webhook',
    events: ['completed', 'failed'],
  },
});

Low-Level: predict()

Direct Predict

For fire-and-forget or full control, use skytells.predict() directly. Returns the raw PredictionResponse (no Prediction wrapper).

// Returns immediately, status: "pending"
const response = await skytells.predict({
  model: 'truefusion',
  input: { prompt: 'A sunset' },
});
console.log(response.id, response.status); // "pred_...", "pending"

The Prediction Object

skytells.run() returns a Prediction object wrapping the raw API response with getters and lifecycle methods.

Properties (Getters)

  • Name
    .id
    Type
    string
    Description

    Unique prediction ID.

  • Name
    .status
    Type
    PredictionStatus
    Description

    Current lifecycle status.

  • Name
    .output
    Type
    string | string[] | undefined
    Description

    Raw output (matches API JSON).

  • Name
    .response
    Type
    PredictionResponse
    Description

    Full API response object.

Methods

  • Name
    .outputs()
    Type
    string | string[] | undefined
    Description

    Normalized output — unwraps single-element arrays.

  • Name
    .raw()
    Type
    PredictionResponse
    Description

    Full raw response as plain object.

  • Name
    .cancel()
    Type
    Promise<PredictionResponse>
    Description

    Cancel the prediction.

  • Name
    .delete()
    Type
    Promise<PredictionResponse>
    Description

    Delete the prediction and its assets.

outputs() Behavior

API outputoutputs() returns
undefinedundefined
"https://...""https://..." (string)
["https://..."]"https://..." (unwrapped)
["a", "b"]["a", "b"] (kept as array)
Prediction
Prediction Object
const prediction = await skytells.run('truefusion', {
  input: { prompt: 'A cat' },
});

// Properties
prediction.id;       // "pred_abc123"
prediction.status;   // "succeeded"
prediction.output;   // "https://..." or ["https://...", ...]
prediction.output[0] // first output when array
prediction.response; // full PredictionResponse

Background Predictions

Creating Background Predictions

Use skytells.predictions.create() to start a prediction without waiting for it to finish. The prediction runs in the background and you can poll it later with skytells.wait().

// Create in background (returns immediately)
const response = await skytells.predictions.create({
  model: 'truefusion',
  input: { prompt: 'A landscape painting' },
});
console.log(response.id, response.status); // "pred_..." "pending"

// Poll until complete
const result = await skytells.wait(response);
console.log(result.output);

Waiting & Polling

skytells.wait() polls a prediction until it reaches a terminal status (succeeded, failed, or cancelled).

WaitOptions

  • Name
    interval
    Type
    number
    Description

    Polling interval in milliseconds.

  • Name
    maxWait
    Type
    number
    Description

    Max wait time (ms). Throws WAIT_TIMEOUT if exceeded.

const bg = await skytells.predictions.create({
  model: 'truefusion',
  input: { prompt: 'A landscape' },
});

// Wait for completion (polls every 5 seconds by default)
const result = await skytells.wait(bg);
console.log(result.output);

Queue & Dispatch

Queue multiple predictions locally, then dispatch them all concurrently. Items are NOT sent until dispatch() is called.

  • Name
    skytells.queue(request)
    Type
    void
    Description

    Adds a prediction request to the local queue.

  • Name
    skytells.dispatch()
    Type
    Promise<PredictionResponse[]>
    Description

    Dispatches all queued predictions concurrently.

skytells.queue({ model: 'truefusion-pro', input: { prompt: 'Cat' } });
skytells.queue({ model: 'truefusion-x', input: { prompt: 'Dog' } });
skytells.queue({ model: 'FLUX-2.0', input: { prompt: 'Bird' } });

const results = await skytells.dispatch();
for (const pred of results) {
  console.log(pred.id, pred.status); // all "pending" initially
}

// Wait for all to complete
const completed = await Promise.all(
  results.map((r) => skytells.wait(r)),
);
for (const result of completed) {
  console.log(result.output);
}

Predictions API

The skytells.predictions namespace provides direct access to prediction CRUD operations. For detailed information about prediction endpoints, see the Prediction API documentation.

Prediction Operations

  • Name
    predictions.create(payload)
    Type
    Promise<PredictionResponse>
    Description

    Create a background prediction.

  • Name
    predictions.get(id)
    Type
    Promise<PredictionResponse>
    Description

    Fetch a prediction by ID.

  • Name
    predictions.list(options?)
    Type
    Promise<PaginatedResponse<...>>
    Description

    List predictions with optional filters.

  • Name
    skytells.cancelPrediction(id)
    Type
    Promise<PredictionResponse>
    Description

    Cancel a running prediction by ID.

  • Name
    skytells.deletePrediction(id)
    Type
    Promise<PredictionResponse>
    Description

    Delete a prediction by ID.

  • Name
    skytells.streamPrediction(id)
    Type
    Promise<PredictionResponse>
    Description

    Get streaming endpoint for a prediction.

PredictionsListOptions

  • Name
    per_page
    Type
    number
    Description

    Results per page (default: 15, max: 50).

  • Name
    page
    Type
    number
    Description

    Page number (default: 1).

  • Name
    model
    Type
    string
    Description

    Filter by model slug (e.g. "truefusion").

  • Name
    from
    Type
    string
    Description

    Start date filter (YYYY-MM-DD).

  • Name
    to
    Type
    string
    Description

    End date filter (YYYY-MM-DD).

predictions
Predictions API
const prediction = await skytells.predictions.create({
  model: 'truefusion',
  input: { prompt: 'An astronaut' },
});
console.log(prediction.id, prediction.status); // "pred_..." "pending"

Models API

The skytells.models namespace provides access to model discovery and details. For detailed information about available models, see the Models documentation.

Model Operations

  • Name
    models.list(options?)
    Type
    Promise<Model[]>
    Description

    List all available models.

  • Name
    models.get(slug, options?)
    Type
    Promise<Model>
    Description

    Fetch a single model by slug.

ModelFieldsOptions

  • Name
    fields
    Type
    ('input_schema' | 'output_schema')[]
    Description

    Extra fields to include in the response.

Model Object Shape

  • Name
    name
    Type
    string
    Description

    Model display name.

  • Name
    description
    Type
    string
    Description

    Human-readable model description.

  • Name
    namespace
    Type
    string
    Description

    Model slug used in API calls (e.g. "truefusion").

  • Name
    type
    Type
    ModelType
    Description

    'image' | 'video' | 'audio' | 'music' | 'text' | 'code' | 'multimodal'

  • Name
    privacy
    Type
    ModelPrivacy
    Description

    'public' | 'private'

  • Name
    img_url
    Type
    string | null
    Description

    Model thumbnail image URL.

  • Name
    vendor
    Type
    Vendor
    Description

    Vendor info: name, description, image_url, verified, slug.

  • Name
    billable
    Type
    boolean
    Description

    Whether usage is billed.

  • Name
    pricing
    Type
    Pricing
    Description

    Pricing info: amount, currency, unit.

  • Name
    capabilities
    Type
    string[]
    Description

    e.g. ["text-to-image", "image-to-image"]

  • Name
    metadata
    Type
    ModelMetadata
    Description

    edge_compatible, openai_compatible, cold_boot.

  • Name
    status
    Type
    string
    Description

    Model availability status ("operational" or "offline").

  • Name
    service
    Type
    Service
    Description

    Service info: type, inference_party (when applicable).

  • Name
    input_schema
    Type
    ModelInputSchema | null
    Description

    JSON Schema describing model input parameters (when fields includes 'input_schema').

  • Name
    output_schema
    Type
    ModelOutputSchema | null
    Description

    JSON Schema describing model output (when fields includes 'output_schema').

models
Models API
const models = await skytells.models.list();
for (const m of models) {
  console.log(m.name, m.type, m.vendor.name);
}

Streaming

Stream Predictions

For predictions created with stream: true, you can retrieve the streaming endpoint URL using skytells.streamPrediction().

const bg = await skytells.predictions.create({
  model: 'truefusion',
  input: { prompt: 'A landscape' },
  stream: true,
});

const stream = await skytells.streamPrediction(bg.id);
console.log(stream.urls?.stream); // streaming endpoint URL

Framework Integration

Using with Popular Frameworks

The Skytells SDK integrates seamlessly with all popular JavaScript and TypeScript frameworks. Below are examples for the most common frameworks.

The key consideration when integrating is API key security — keep your API keys on the server side and never expose them to clients.

Frameworks
Framework Examples
// app/api/generate/route.ts
import Skytells from 'skytells';
import { NextResponse } from 'next/server';

// Disable Next.js fetch cache with custom fetch
const skytells = Skytells(process.env.SKYTELLS_API_KEY, {
  fetch: (url, opts) => fetch(url, { ...opts, cache: 'no-store' }),
});

export async function POST(request: Request) {
  const { prompt } = await request.json();

  const prediction = await skytells.run('truefusion', {
    input: { prompt },
  });

  return NextResponse.json({
    output: prediction.outputs(),
    id: prediction.id,
  });
}

UI Integration Example (React)

// TextGenerationForm.tsx — calls your API route
import { useState } from 'react';

export default function GenerateForm() {
  const [prompt, setPrompt] = useState('');
  const [output, setOutput] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch('/api/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt }),
      });
      const data = await res.json();
      setOutput(data.output);
    } catch {
      setOutput('Error generating content.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} />
      <button type="submit" disabled={loading}>
        {loading ? 'Generating...' : 'Generate'}
      </button>
      {output && <div>{output}</div>}
    </form>
  );
}

Edge Compatibility

The Skytells TypeScript SDK works in any environment with Fetch API support. No special configuration needed.

  • Cloudflare Workers / Pages
  • Vercel Edge Functions
  • Netlify Edge Functions
  • Deno Deploy
  • Node.js 18+
  • Browsers — use a backend proxy for API key security
import Skytells from 'skytells';

export default {
  async fetch(request, env) {
    const skytells = Skytells(env.SKYTELLS_API_KEY);

    const prediction = await skytells.run('flux-pro', {
      input: { prompt: 'A sunset over mountains' },
    });

    return new Response(JSON.stringify(prediction.output), {
      headers: { 'Content-Type': 'application/json' },
    });
  },
};
SkytellsErrorskytells

Error Handling

All API methods throw SkytellsError on failure. Import it as a named export from the SDK.

SkytellsError Properties

  • Name
    message
    Type
    string
    Description

    Human-readable error message.

  • Name
    errorId
    Type
    string
    Description

    Machine-readable error identifier (e.g. UNAUTHORIZED, MODEL_NOT_FOUND).

  • Name
    details
    Type
    string
    Description

    Detailed description of what went wrong.

  • Name
    httpStatus
    Type
    number
    Description

    HTTP status code from the API response.

For the complete list of error IDs and HTTP status codes, see the Errors reference.

import Skytells, { SkytellsError } from 'skytells';

const skytells = Skytells('sk-your-api-key');

try {
  const prediction = await skytells.run('truefusion', {
    input: { prompt: 'A cat' },
  });
} catch (error) {
  if (error instanceof SkytellsError) {
    console.error(error.message);    // Human-readable message
    console.error(error.errorId);    // e.g. "VALIDATION_ERROR"
    console.error(error.details);    // Detailed info
    console.error(error.httpStatus); // e.g. 422
  }
}

TypeScript Reference

Full type definitions are included with the package.

Imports

imports
Imports
import Skytells from 'skytells';

Enums

  • Name
    PredictionStatus
    Type
    enum
    Description

    pending · starting · started · processing · succeeded · failed · cancelled

  • Name
    PredictionType
    Type
    enum
    Description

    inference · training

  • Name
    PredictionSource
    Type
    enum
    Description

    api · cli · web

  • Name
    ModelType
    Type
    enum
    Description

    image · video · audio · music · text · code · multimodal

  • Name
    ModelPrivacy
    Type
    enum
    Description

    public · private

Key Type Shapes

interface PredictionResponse {
  id: string;
  status: PredictionStatus;
  type: PredictionType;
  stream: boolean;
  input: Record<string, any>;
  output?: string | string[];
  created_at: string;
  started_at: string;
  completed_at: string;
  updated_at: string;
  privacy: string;
  source?: PredictionSource;
  model?: { name: string; type: string };
  webhook?: { url: string | null; events: string[] };
  metrics?: {
    image_count?: number;
    predict_time?: number;
    total_time?: number;
    asset_count?: number;
    progress?: number;
  };
  metadata?: {
    billing?: { credits_used: number };
    storage?: {
      files: {
        name: string;
        type: string;
        size: number;
        url: string;
      }[];
    };
    data_available?: boolean;
  };
  urls?: {
    get?: string;
    cancel?: string;
    stream?: string;
    delete?: string;
  };
}

Was this page helpful?