> ## Documentation Index
> Fetch the complete documentation index at: https://polargrid.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript Reference

> Complete JavaScript SDK API reference

# JavaScript SDK Reference

Full API reference for the PolarGrid JavaScript SDK.

## Client Methods

### Text Inference

| Method                          | Description                            |
| ------------------------------- | -------------------------------------- |
| `chatCompletion(request)`       | Generate chat completion               |
| `chatCompletionStream(request)` | Streaming chat completion              |
| `completion(request)`           | Generate text completion               |
| `completionStream(request)`     | Streaming text completion              |
| `generate(request)`             | Legacy generate (wraps chatCompletion) |

### Voice / Audio

| Method                        | Description                                                                                                                                                                                                                       |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `textToSpeech(request)`       | Convert text to audio (returns ArrayBuffer)                                                                                                                                                                                       |
| `textToSpeechStream(request)` | Streaming TTS over chunked HTTP. Yields `Uint8Array` chunks. Default `responseFormat` is `'opus'`. WebSocket transport is not supported — see the [TTS API streaming section](/api-reference/text-to-speech#streaming).           |
| `transcribe(request)`         | Transcribe audio to text                                                                                                                                                                                                          |
| `transcribeStream(request)`   | Streaming transcription. Async iterator of `TranscriptionStreamEvent` (`transcript.text.delta`, `transcript.text.done`, `error`). See the [STT API streaming section](/api-reference/speech-to-text#streaming-transcription-sse). |
| `translate(request)`          | Translate audio to English                                                                                                                                                                                                        |

### Models

| Method                 | Description                  |
| ---------------------- | ---------------------------- |
| `listModels()`         | List available models        |
| `loadModel(request)`   | Load a model into GPU memory |
| `unloadModel(request)` | Unload a model               |
| `unloadAllModels()`    | Unload all models            |
| `getModelStatus()`     | Get model loading status     |

### GPU

| Method              | Description                |
| ------------------- | -------------------------- |
| `getGPUStatus()`    | Detailed GPU status        |
| `getGPUMemory()`    | Simplified GPU memory info |
| `purgeGPU(request)` | Clear GPU memory           |

### Health & Region

| Method            | Description                                 |
| ----------------- | ------------------------------------------- |
| `health()`        | Service health check                        |
| `getRegionId()`   | Get current region ID (e.g., 'yvr-02')      |
| `getRegionName()` | Get current region name (e.g., 'Vancouver') |

## Error Handling

```typescript theme={null}
import {
  PolarGrid,
  isPolarGridError,
  AuthenticationError,
  BillingError,
  ValidationError,
  RateLimitError,
  NetworkError,
  TimeoutError,
  NotFoundError,
  ServerError,
} from '@polargrid/polargrid-sdk';

try {
  const response = await client.chatCompletion(request);
} catch (error) {
  if (isPolarGridError(error)) {
    console.error(`Error: ${error.message}`);
    console.error(`Request ID: ${error.requestId}`);

    if (error instanceof AuthenticationError) {
      // Invalid or expired API key
    } else if (error instanceof BillingError) {
      // Insufficient credits or payment required (HTTP 402)
    } else if (error instanceof ValidationError) {
      // Invalid request parameters
      console.error('Details:', error.details);
    } else if (error instanceof RateLimitError) {
      // Rate limited - wait and retry
      console.error(`Retry after: ${error.retryAfter}s`);
    } else if (error instanceof NetworkError) {
      // Network/connection error
    } else if (error instanceof TimeoutError) {
      // Request timed out
    } else if (error instanceof NotFoundError) {
      // Resource not found
    } else if (error instanceof ServerError) {
      // Server error (5xx)
    }
  }
}
```

## Types

```typescript theme={null}
import type {
  // Config
  PolarGridConfig,
  
  // Text Inference
  ChatCompletionRequest,
  ChatCompletionResponse,
  ChatCompletionChunk,
  CompletionRequest,
  CompletionResponse,
  CompletionChunk,
  GenerateRequest,
  GenerateResponse,
  
  // Voice
  TextToSpeechRequest,
  TranscriptionRequest,
  TranscriptionResponse,
  VerboseTranscriptionResponse,
  TranslationRequest,
  TranslationResponse,
  TTSVoice,
  STTModel,
  AudioFormat,
  
  // Models
  ModelInfo,
  ListModelsResponse,
  LoadModelRequest,
  LoadModelResponse,
  UnloadModelRequest,
  UnloadModelResponse,
  UnloadAllModelsResponse,
  ModelStatusResponse,
  
  // GPU
  GPUStatusResponse,
  GPUMemoryResponse,
  GPUPurgeRequest,
  GPUPurgeResponse,
  GPUInfo,
  GPUMemoryInfo,
  GPUProcess,
  
  // Health
  HealthResponse,
  
  // Errors
  ApiError,
} from '@polargrid/polargrid-sdk';
```

## Regions

```typescript theme={null}
import { POLARGRID_REGIONS } from '@polargrid/polargrid-sdk';

// Available regions
console.log(POLARGRID_REGIONS);
// {
//   'yto-01': { id: 'yto-01', name: 'Toronto', url: 'https://api.yto-01.edge.polargrid.ai' },
//   'yul-01': { id: 'yul-01', name: 'Montreal', url: 'https://api.yul-01.edge.polargrid.ai' },
//   'yul-02': { id: 'yul-02', name: 'Montreal 02', url: 'https://api.yul-02.edge.polargrid.ai' },
//   'yvr-02': { id: 'yvr-02', name: 'Vancouver', url: 'https://api.yvr-02.edge.polargrid.ai' },
//   'nyc-01': { id: 'nyc-01', name: 'New York', url: 'https://api.nyc-01.edge.polargrid.ai' },
//   'nyc-02': { id: 'nyc-02', name: 'New York 02', url: 'https://api.nyc-02.edge.polargrid.ai' },
//   'dfw-01': { id: 'dfw-01', name: 'Dallas', url: 'https://api.dfw-01.edge.polargrid.ai' },
//   'dfw-02': { id: 'dfw-02', name: 'Dallas 02', url: 'https://api.dfw-02.edge.polargrid.ai' },
//   'sfo-01': { id: 'sfo-01', name: 'San Francisco', url: 'https://api.sfo-01.edge.polargrid.ai' },
//   'lax-01': { id: 'lax-01', name: 'Los Angeles', url: 'https://api.lax-01.edge.polargrid.ai' },
//   'sea-01': { id: 'sea-01', name: 'Seattle', url: 'https://api.sea-01.edge.polargrid.ai' },
//   'chi-01': { id: 'chi-01', name: 'Chicago', url: 'https://api.chi-01.edge.polargrid.ai' },
//   'phx-01': { id: 'phx-01', name: 'Phoenix', url: 'https://api.phx-01.edge.polargrid.ai' },
//   'was-01': { id: 'was-01', name: 'Washington DC', url: 'https://api.was-01.edge.polargrid.ai' },
//   'mia-01': { id: 'mia-01', name: 'Miami', url: 'https://api.mia-01.edge.polargrid.ai' },
//   'sfo-03': { id: 'sfo-03', name: 'San Francisco', url: 'https://api.sfo-03.edge.polargrid.ai' },
// }

// Region aliases supported: 'toronto', 'yto', 'vancouver', 'yvr', 'montreal', 'yul',
//   'new-york', 'nyc', 'dallas', 'dfw', 'san-francisco', 'sf', 'sfo'
```

## Default Export

```typescript theme={null}
// Named import (recommended)
import { PolarGrid } from '@polargrid/polargrid-sdk';

// Default import also works
import PolarGrid from '@polargrid/polargrid-sdk';
```
