Skip to main content

JavaScript SDK

The official JavaScript/TypeScript SDK for PolarGrid.

Installation

npm install @polargrid/sdk

Quick Start

import { PolarGrid } from '@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., "Vancouver"

// Chat completion
const response = await client.chatCompletion({
  model: 'llama-3.1-8b',
  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: 'vancouver', 'montreal', 'washington' (or yvr-01, ymq-01, was-01)
  region: 'vancouver',

  // 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 tests latency to all regions and picks the fastest:
const client = await PolarGrid.create({
  apiKey: 'pg_your_api_key',
  debug: true, // See latency test results
});

// [PolarGrid] Auto-routing: latency results: yvr-01=45ms, ymq-01=82ms, was-01=67ms
// [PolarGrid] Auto-routing: selected Vancouver (yvr-01) with 45ms latency

console.log(client.getRegionId());   // 'yvr-01'
console.log(client.getRegionName()); // 'Vancouver'

Streaming

for await (const chunk of client.chatCompletionStream({
  model: 'llama-3.1-8b',
  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: 'llama-3.1-8b',
  messages: [{ role: 'user', content: 'Hello!' }]
});

Environment Variables

POLARGRID_API_KEY=pg_your_api_key
POLARGRID_BASE_URL=https://api.ymq-01.edge.polargrid.ai:55111  # Optional override

Next Steps