TypeScript SDK

The official JavaScript/TypeScript SDK for interacting with the Skytells API. Edge-compatible with Cloudflare Pages, Vercel Edge Functions, and more.

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.0"
  }
}

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 createClient function, which returns a client instance with methods for making predictions, managing models, and more.

The example on the right demonstrates the basic workflow:

  1. Initialize the client with your API key
  2. Make a prediction using a model
  3. Process the results
Example
Basic Usage
import { createClient } from 'skytells';

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

Complete Example

import { createClient } from 'skytells';

async function main() {
  // Initialize the client
  const skytells = createClient('your-api-key-here');
  
  // List available models
  const models = await skytells.listModels();
  console.log('Available models:', models);
  
  // Make a prediction
  const prediction = await skytells.predict({
    model: models[0].id, // Use the first available model
    input: {
      prompt: 'Generate a creative story about AI'
    }
  });
  
  // Check prediction status
  console.log('Prediction status:', prediction.status);
  
  // Get the prediction result when it's ready
  if (prediction.status === 'succeeded') {
    console.log('Prediction output:', prediction.output);
  } else {
    // Poll for the result
    const result = await skytells.getPrediction(prediction.id);
    console.log('Final output:', result.output);
  }
}

main().catch(console.error);

Authentication

Setting Up Authentication

To access the Skytells API, you need an API key from your Skytells dashboard. This key authenticates your requests and determines your access level to different features and models.

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

Authentication
Authentication Options
import { createClient } from 'skytells';

// With API key (authenticated)
const client = createClient('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=your-api-key-here

// In your code
import { createClient } from 'skytells';

const client = createClient(process.env.SKYTELLS_API_KEY);

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 - API Route
import { createClient } from 'skytells';
import { NextResponse } from 'next/server';

// Initialize client outside of handler for connection reuse
const skytells = createClient(process.env.SKYTELLS_API_KEY);

export async function POST(request: Request) {
  try {
    const { prompt } = await request.json();
    
    const prediction = await skytells.predict({
      model: 'text-generation',
      input: { prompt }
    });
    
    return NextResponse.json(prediction);
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to generate text' },
      { status: 500 }
    );
  }
}

UI Integration Example (React)

// TextGenerationForm.tsx
import { useState } from 'react';

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    
    try {
      // Call your API endpoint that uses the SDK
      const response = await fetch('/api/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt })
      });
      
      if (!response.ok) {
        throw new Error('Failed to generate text');
      }
      
      const data = await response.json();
      setOutput(data.output);
    } catch (err) {
      setError('Error generating text. Please try again.');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-4">
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="prompt" className="block text-sm font-medium">
            Enter your prompt:
          </label>
          <textarea
            id="prompt"
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            className="w-full mt-1 p-2 border rounded-md"
            rows={4}
            required
          />
        </div>
        
        <button
          type="submit"
          disabled={loading}
          className="px-4 py-2 bg-blue-600 text-white rounded-md"
        >
          {loading ? 'Generating...' : 'Generate Text'}
        </button>
        
        {error && (
          <div className="text-red-500">{error}</div>
        )}
        
        {output && (
          <div className="mt-6">
            <h3 className="text-lg font-medium">Generated Output:</h3>
            <div className="mt-2 p-4 bg-gray-50 border rounded-md whitespace-pre-wrap">
              {output}
            </div>
          </div>
        )}
      </form>
    </div>
  );
}

Edge Compatibility

Running Everywhere

The Skytells TypeScript SDK is designed to work in any JavaScript environment, with special focus on modern edge environments. This means you can use the same SDK across your entire application stack.

The SDK automatically adapts to the runtime environment, using the appropriate networking APIs and optimization strategies.

Supported Environments

  • Cloudflare Workers and Pages - Full support with optimized performance
  • Vercel Edge Functions - Optimized for serverless edge environments
  • Netlify Edge Functions - Fully compatible
  • Deno Deploy - Native support
  • Node.js - Full support across all versions
  • Browsers - Works in modern browsers (with backend for API key security)
Examples
Environment Examples
// In Cloudflare Worker
import { createClient } from 'skytells';

export default {
  async fetch(request, env) {
    const client = createClient(env.SKYTELLS_API_KEY);
    
    const models = await client.listModels();
    return new Response(JSON.stringify(models), {
      headers: { 'Content-Type': 'application/json' },
    });
  }
};

API Reference

Creating a Client

Client Configuration

The client is the main entry point for interacting with the Skytells API. You can configure it with various options to customize its behavior.

Available options include:

  • baseUrl: Custom API endpoint URL
  • timeout: Request timeout in milliseconds
  • headers: Additional headers to include in requests
  • fetch: Custom fetch implementation
Client
Client Creation
import { createClient } from 'skytells';

// With API key (authenticated)
const client = createClient('your-api-key');

Predictions

Make a Prediction

Creating Predictions

The predict method is used to create a new prediction with a specified model and input parameters. The input structure varies depending on the model being used.

Common input parameters include:

  • prompt: The text prompt for the model
  • temperature: Controls randomness (0-1)
  • max_tokens: Maximum tokens to generate
  • seed: Random seed for reproducibility
Prediction
Making Predictions
const prediction = await client.predict({
  model: 'model-name',
  input: {
    prompt: 'Your prompt here'
  }
});

console.log('Prediction ID:', prediction.id);
console.log('Status:', prediction.status);
console.log('Output:', prediction.output);

Response Structure

{
  "id": "pred_abc123",
  "status": "succeeded",
  "created_at": "2023-06-15T14:30:00Z",
  "started_at": "2023-06-15T14:30:01Z",
  "completed_at": "2023-06-15T14:30:05Z",
  "model": "model-name",
  "input": {
    "prompt": "Your prompt here"
  },
  "output": "Generated content based on your prompt",
  "metrics": {
    "predict_time": 4.2
  }
}

Get a Prediction by ID

Retrieving Predictions

Use the getPrediction method to retrieve an existing prediction by its ID. This is useful for checking the status of a prediction or retrieving its output after it has completed.

Prediction statuses include:

  • queued: The prediction is waiting to be processed
  • processing: The prediction is currently being processed
  • succeeded: The prediction completed successfully
  • failed: The prediction failed with an error
  • canceled: The prediction was canceled
const prediction = await client.getPrediction('pred_abc123');

// Check the prediction status
if (prediction.status === 'succeeded') {
  console.log('Output:', prediction.output);
} else if (prediction.status === 'processing') {
  console.log('Prediction is still processing...');
} else if (prediction.status === 'failed') {
  console.error('Prediction failed:', prediction.error);
}

Stream a Prediction

Real-time Outputs

For models that support streaming, you can use the streamPrediction method to receive partial outputs in real-time as they are generated.

This is particularly useful for interactive applications where you want to display results to users as they become available, rather than waiting for the entire prediction to complete.

const stream = await client.streamPrediction('pred_abc123');

// In browser environments
for await (const chunk of stream) {
  console.log('New chunk:', chunk);
  // Append chunk to UI
  document.getElementById('output').textContent += chunk;
}

Cancel a Prediction

Stopping Predictions

The cancelPrediction method allows you to cancel an in-progress prediction that hasn't completed yet. This can be useful for long-running predictions that are no longer needed.

const result = await client.cancelPrediction('pred_abc123');

if (result.success) {
  console.log('Prediction canceled successfully');
} else {
  console.error('Failed to cancel prediction');
}

Delete a Prediction

Cleaning Up

Use the deletePrediction method to remove a prediction from your account. This is useful for managing storage or removing sensitive data.

const result = await client.deletePrediction('pred_abc123');

if (result.success) {
  console.log('Prediction deleted successfully');
} else {
  console.error('Failed to delete prediction');
}

Models

List All Models

Discovering Models

The listModels method returns information about all available models, including their capabilities, parameters, and pricing.

You can use this information to:

  • Discover new models
  • Check model versions
  • Understand model capabilities
  • See pricing information
const models = await client.listModels();

// Display available models
console.log('Available models:');
models.forEach(model => {
  console.log(`- ${model.name} (${model.id}): ${model.description}`);
});

Model Response Structure

[
  {
    "id": "text-generation",
    "name": "Text Generation",
    "description": "General purpose text generation model",
    "version": "1.0",
    "capabilities": ["text-generation", "translation", "summarization"],
    "parameters": {
      "temperature": {
        "type": "float",
        "default": 0.7,
        "min": 0,
        "max": 1
      },
      "max_tokens": {
        "type": "integer",
        "default": 256,
        "min": 1,
        "max": 4096
      }
    },
    "pricing": {
      "input": "0.001 / 1K tokens",
      "output": "0.002 / 1K tokens"
    }
  },
  // More models...
]

Webhooks

Event Notifications

Webhooks allow you to receive notifications when certain events occur in your account, such as when a prediction completes or fails.

The SDK provides methods for registering and managing webhooks.

const webhook = await client.createWebhook({
  url: 'https://your-server.com/webhook',
  events: ['prediction.succeeded', 'prediction.failed'],
  secret: 'your-webhook-secret'  // Used to validate the webhook payload
});

console.log('Webhook created:', webhook.id);

Webhook Handler Example (Express)

import express from 'express';
import crypto from 'crypto';

const app = express();
app.use(express.json());

// Your webhook secret from Skytells dashboard
const WEBHOOK_SECRET = 'your-webhook-secret';

app.post('/webhook', (req, res) => {
  // Verify webhook signature
  const signature = req.headers['skytells-signature'];
  const payload = JSON.stringify(req.body);
  
  const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
  hmac.update(payload);
  const expectedSignature = hmac.digest('hex');
  
  if (signature !== expectedSignature) {
    console.error('Invalid signature');
    return res.status(401).send('Invalid signature');
  }
  
  // Process the webhook event
  const event = req.body;
  
  switch (event.type) {
    case 'prediction.succeeded':
      console.log(`Prediction ${event.data.id} succeeded:`, event.data.output);
      // Update your database, notify users, etc.
      break;
      
    case 'prediction.failed':
      console.error(`Prediction ${event.data.id} failed:`, event.data.error);
      // Handle the error, retry, etc.
      break;
      
    default:
      console.log(`Received unknown event type: ${event.type}`);
  }
  
  // Acknowledge receipt of the webhook
  res.status(200).send('Webhook received');
});

app.listen(3000, () => {
  console.log('Webhook server listening on port 3000');
});

TypeScript Support

The Skytells TypeScript SDK provides comprehensive type definitions for all API resources, request parameters, and response objects. This ensures you get autocompletion, inline documentation, and type checking in your IDE.

Core Types

The SDK exports various TypeScript interfaces and types that represent the core concepts of the Skytells API:

  • Client Types: Types related to client creation and configuration
  • Prediction Types: Interfaces for prediction requests and responses
  • Model Types: Interfaces describing model metadata and capabilities
  • Webhook Types: Types for webhook configuration and events
  • Error Types: Structured error types for different API errors

Using Types in Your Code

You can import and use these types in your TypeScript code for better type safety:

import { 
  SkytellsClient,
  PredictionRequest,
  PredictionResponse,
  Model,
  WebhookEvent, 
  SkytellsError 
} from 'skytells';

// Type your variables and function parameters
function processCompletedPrediction(prediction: PredictionResponse) {
  if (prediction.status === 'succeeded') {
    // TypeScript knows that output exists when status is 'succeeded'
    return prediction.output;
  }
  
  return null;
}

Type Reference

// Client creation and configuration
type SkytellsClient = {
  predict: (request: PredictionRequest) => Promise<PredictionResponse>;
  getPrediction: (id: string) => Promise<PredictionResponse>;
  cancelPrediction: (id: string) => Promise<{ success: boolean }>;
  deletePrediction: (id: string) => Promise<{ success: boolean }>;
  streamPrediction: (id: string) => Promise<PredictionStream>;
  listModels: () => Promise<Model[]>;
  createWebhook: (config: WebhookConfig) => Promise<Webhook>;
  listWebhooks: () => Promise<Webhook[]>;
  deleteWebhook: (id: string) => Promise<{ success: boolean }>;
};

type ClientOptions = {
  baseUrl?: string;
  timeout?: number;
  headers?: Record<string, string>;
  fetch?: typeof fetch;
};

Error Handling

Handling API Errors

The Skytells SDK provides structured error handling to help you catch and respond to different types of errors that may occur during API interactions.

Main error categories include:

  • Authentication errors: Invalid or missing API key
  • Validation errors: Invalid input parameters
  • Rate limit errors: Too many requests
  • Resource errors: Resource not found or unavailable
  • Server errors: Internal server errors
  • Network errors: Connection issues
try {
  const prediction = await client.predict({
    model: 'text-generation',
    input: { prompt: 'Hello, world!' }
  });
  
  console.log('Prediction created:', prediction.id);
} catch (error) {
  console.error('Failed to create prediction:', error.message);
  
  // You can check for specific error types
  if (error.name === 'SkytellsAuthError') {
    console.error('Authentication error - check your API key');
  } else if (error.name === 'SkytellsValidationError') {
    console.error('Invalid parameters:', error.details);
  } else if (error.name === 'SkytellsRateLimitError') {
    console.error('Rate limited - retry after:', error.retryAfter);
  }
}

Was this page helpful?