Skip to main content

JavaScript SDK

The official JavaScript/TypeScript SDK for PolarGrid.

Installation

npm install @polargrid/polargrid-sdk

Quick Start

import { PolarGrid } from '@polargrid/polargrid-sdk';

// Auto-select best region by latency (recommended)
const client = await PolarGrid.create({
  apiKey: 'pg_your_api_key',
});

console.log(`Connected to: ${client.getRegionName()}`); // e.g., "Toronto"

// Chat completion
const response = await client.chatCompletion({
  model: 'qwen-3.5-27b',
  messages: [
    { role: 'user', content: 'Hello!' }
  ]
});

console.log(response.choices[0].message.content);

Configuration

// Sync constructor (uses default region)
const client = new PolarGrid({
  // API key (or set POLARGRID_API_KEY env var)
  apiKey: 'pg_your_api_key',

  // Region alias: 'toronto', 'montreal', 'vancouver', 'new-york', 'dallas', 'san-francisco'
  // Or explicit ID: yto-01, yto-02, yul-01, yul-02, yvr-02, nyc-01, nyc-02, dal-01, dal-02, sfo-01
  region: 'toronto',

  // Request timeout in ms (default: 30000)
  timeout: 30000,

  // Max retry attempts (default: 3)
  maxRetries: 3,

  // Enable debug logging
  debug: true,

  // Use mock data for development
  useMockData: false,
});

// Async factory with auto-routing (recommended)
const client = await PolarGrid.create({
  apiKey: 'pg_your_api_key',
  debug: true,
});

Auto-Routing

The PolarGrid.create() factory calls the autorouter (GET https://autorouter.polargrid.ai/v1/route), which returns the optimal edge based on your origin:
const client = await PolarGrid.create({
  apiKey: 'pg_your_api_key',
  debug: true, // See selected region
});

// [PolarGrid] Auto-routing: selected Toronto (yto-01)

console.log(client.getRegionId());   // 'yto-01'
console.log(client.getRegionName()); // 'Toronto'

Streaming

for await (const chunk of client.chatCompletionStream({
  model: 'qwen-3.5-27b',
  messages: [{ role: 'user', content: 'Tell me a story' }],
})) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) {
    process.stdout.write(content);
  }
}

Mock Mode

Perfect for frontend development without a backend:
const client = new PolarGrid({
  useMockData: true,  // No API calls, instant realistic responses
  debug: true,
});

// All methods work with realistic mock data
const response = await client.chatCompletion({
  model: 'qwen-3.5-27b',
  messages: [{ role: 'user', content: 'Hello!' }]
});

Environment Variables

POLARGRID_API_KEY=pg_your_api_key
POLARGRID_BASE_URL=https://api.yto-01.edge.polargrid.ai  # Optional. Pins the SDK to a specific edge. Leave unset and call PolarGrid.create() to auto-discover the fastest region via https://autorouter.polargrid.ai/v1/route.

Next Steps

Full Reference

Complete API reference

Voice Guide

Text-to-speech and speech-to-text