Skip to main content
The Portkey JavaScript SDK provides a fully-typed interface to access 250+ LLMs through a unified API with production-grade routing, fallbacks, and observability.

Overview

The JavaScript/TypeScript SDK offers:
  • OpenAI-Compatible API: Drop-in replacement for OpenAI SDK
  • 250+ LLMs: Access any LLM through a unified interface
  • TypeScript Support: Full type definitions and autocomplete
  • Cross-Platform: Works in Node.js, Deno, and modern browsers
  • Advanced Routing: Fallbacks, load balancing, and retries
  • Production Features: Caching, guardrails, and observability

Installation

Quick Start

1

Get Your API Keys

Sign up at Portkey and get your API key. Add your provider API keys as Virtual Keys.
2

Import and Initialize

3

Make Your First Request

Basic Usage

Chat Completions

Streaming Responses

Completions (Legacy)

Using Different Providers

Switch between providers easily:

Advanced Routing with Configs

Fallback Strategy

Automatically fallback to backup providers:

Load Balancing

Distribute traffic across multiple providers:

Automatic Retries

Request Timeouts

Caching

Enable caching to reduce costs and latency:

Simple Caching

Semantic Caching

Guardrails

Add input/output guardrails:

Metadata and Tracking

Add custom metadata for better observability:

Embeddings

Generate embeddings:

Image Generation

Generate images:

Audio

Speech to Text

Text to Speech

Function Calling

Vision

Analyze images:

Error Handling

Browser Usage

Next.js API Route

React Hook

Best Practices

Store API keys in environment variables:
Always configure fallback providers for production:
Use caching for repeated queries to reduce costs:
Always add metadata for better tracking:
Implement proper error handling for production applications.

Complete Example

Resources

Questions? Join our Discord community for help.