Stablev2.4.0

JavaScript / TypeScript SDK

@skyaiapp/sdk

Official JavaScript/TypeScript SDK with full type definitions. Works with Node.js, Deno, Bun, and browsers.

Installation

npm
yarn
pnpm
bun
npm install @skyaiapp/sdk
Requirements: Node.js 18+ or compatible runtime

Quick Start

import { SkyAI } from "@skyaiapp/sdk";

// Initialize the client
const sky = new SkyAI({
  apiKey: process.env.SKYAIAPP_API_KEY,
});

// Make a routing request
const response = await sky.route({
  goal: "cost",
  strategy: "balanced",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Hello, world!" }
  ],
});

console.log(response.choices[0].message.content);
console.log("Model:", response.model);
console.log("Cost:", response.routing.cost_usd);

Core Features

Smart Routing

// Cost-optimized routing
const response = await sky.route({
  goal: "cost",
  strategy: "cost-optimized",
  messages: [{ role: "user", content: "Quick question..." }],
  cache: true, // Enable semantic caching
});

// Quality-first routing
const response = await sky.route({
  goal: "quality",
  strategy: "quality-first",
  messages: [{ role: "user", content: "Complex analysis..." }],
  max_tokens: 2000,
});

// With fallback configuration
const response = await sky.route({
  goal: "stability",
  messages: [...],
  fallback: {
    models: ["claude-opus-4.5", "gpt-5.2-thinking"],
    maxRetries: 3,
  },
});

Streaming

// Stream responses
const stream = await sky.route({
  goal: "quality",
  messages: [{ role: "user", content: "Write a story..." }],
  stream: true,
});

// Process chunks
for await (const chunk of stream) {
  if (chunk.choices[0]?.delta?.content) {
    process.stdout.write(chunk.choices[0].delta.content);
  }
}

// Get final usage after stream completes
console.log("Usage:", stream.usage);

// Or use the helper method
const stream = await sky.route({ ..., stream: true });
const text = await stream.text(); // Collect all text
console.log(text);

Agent Runtime

// Create an agent
const agent = sky.createAgent({
  tools: ["web_search", "read_url", "calculator"],
  maxSteps: 10,
  timeout: 120000,
  sandbox: true,
});

// Run a task
const result = await agent.run({
  task: "Research the latest AI news and summarize",
  onStep: (step) => {
    console.log(`Step ${step.number}: ${step.action}`);
  },
});

console.log(result.output);
console.log("Steps:", result.steps.length);
console.log("Cost:", result.usage.total_cost_usd);

// Define custom tools
const agent = sky.createAgent({
  tools: [
    "web_search",
    {
      name: "get_weather",
      description: "Get current weather for a location",
      parameters: {
        type: "object",
        properties: {
          location: { type: "string" },
        },
        required: ["location"],
      },
      execute: async ({ location }) => {
        // Your implementation
        return { temp: 72, condition: "sunny" };
      },
    },
  ],
});

Guardrails

// PII filtering
const response = await sky.route({
  goal: "quality",
  messages: [{ role: "user", content: userInput }],
  guardrails: {
    pii: {
      enabled: true,
      types: ["email", "phone", "ssn", "credit_card"],
      action: "redact", // or "block"
    },
  },
});

// Content moderation
const response = await sky.route({
  goal: "quality",
  messages: [{ role: "user", content: userInput }],
  guardrails: {
    moderation: {
      enabled: true,
      categories: ["hate", "violence", "sexual"],
      threshold: 0.7,
    },
    topicFilter: {
      blocked: ["illegal_activities", "weapons"],
    },
  },
});

// Check if content was blocked
if (response.guardrails?.blocked) {
  console.log("Blocked:", response.guardrails.reason);
}

TypeScript Types

import type {
  SkyAI,
  RouteRequest,
  RouteResponse,
  StreamingResponse,
  Agent,
  AgentRunResult,
  Tool,
  Message,
  Goal,
  Strategy,
} from "@skyaiapp/sdk";

// Full type safety
const request: RouteRequest = {
  goal: "cost",
  strategy: "balanced",
  messages: [
    { role: "system", content: "..." },
    { role: "user", content: "..." },
  ],
  max_tokens: 500,
  temperature: 0.7,
};

const response: RouteResponse = await sky.route(request);

// Type-safe agent
const agent: Agent = sky.createAgent({
  tools: ["web_search"],
  maxSteps: 5,
});

const result: AgentRunResult = await agent.run({
  task: "...",
});

Error Handling

import { SkyAIError, RateLimitError, AuthError } from "@skyaiapp/sdk";

try {
  const response = await sky.route({ ... });
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log("Rate limited. Retry after:", error.retryAfter);
    // Implement backoff
  } else if (error instanceof AuthError) {
    console.log("Invalid API key");
  } else if (error instanceof SkyAIError) {
    console.log("API error:", error.message, error.code);
  } else {
    throw error;
  }
}

// With automatic retry
const sky = new SkyAI({
  apiKey: process.env.SKYAIAPP_API_KEY,
  maxRetries: 3,
  retryDelay: 1000,
});

Framework Integration

Next.js App Router

// app/api/chat/route.ts
import { SkyAI } from "@skyaiapp/sdk";
import { NextResponse } from "next/server";

const sky = new SkyAI({ apiKey: process.env.SKYAIAPP_API_KEY! });

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

  const stream = await sky.route({
    goal: "balanced",
    messages,
    stream: true,
  });

  return new Response(stream.toReadableStream(), {
    headers: { "Content-Type": "text/event-stream" },
  });
}

React Hook

// hooks/useChat.ts
"use client";
import { useChat } from "@skyaiapp/react";

export function ChatComponent() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
    api: "/api/chat",
    onError: (error) => console.error(error),
  });

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>{m.role}: {m.content}</div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit" disabled={isLoading}>Send</button>
      </form>
    </div>
  );
}

API Reference

sky.route(options)

Send a routing request

Details
sky.createAgent(config)

Create an Agent instance

Details
sky.models.list()

List available models

Details
sky.analytics.usage(params)

Get usage analytics

Details

See more examples

Full example projects available on GitHub

Was this page helpful?

Let us know how we can improve

JavaScript / TypeScript SDK | SkyAIApp Docs — SkyAIApp