Skip to main content
Portkey works seamlessly as a drop-in replacement for the OpenAI SDK, requiring minimal code changes while adding production-grade routing, fallbacks, and observability.

Overview

Using Portkey with OpenAI SDK gives you:
  • Zero Code Changes: Works with existing OpenAI SDK code
  • 250+ LLMs: Route to any provider using OpenAI’s interface
  • Production Ready: Automatic fallbacks, retries, and load balancing
  • Observability: Complete logging and analytics
  • Cost Optimization: Smart caching and provider switching

Installation

Python Integration

Quick Start

1

Import Libraries

2

Create Portkey Headers

3

Initialize OpenAI Client

4

Use OpenAI SDK Normally

Complete Example (Python)

Streaming (Python)

Async Support (Python)

JavaScript Integration

Quick Start (JavaScript)

1

Import Libraries

2

Create Portkey Headers

3

Initialize OpenAI Client

4

Use OpenAI SDK Normally

Complete Example (JavaScript)

Streaming (JavaScript)

Switching Providers

The beauty of using Portkey with OpenAI SDK is you can easily switch to any provider:

Advanced Routing

Fallback Configuration

Add automatic fallbacks:

Load Balancing

Distribute traffic across multiple accounts:

Retries and Timeouts

Caching

Enable caching to reduce costs:

All OpenAI Features Supported

Function Calling

Vision

Embeddings

Image Generation

Audio

Observability

Add metadata for better tracking:

Migration Guide

Migrating existing OpenAI code to use Portkey:

Before (Plain OpenAI)

After (With Portkey)

That’s it! Only 2 extra parameters needed.

Best Practices

Store your provider API keys as Virtual Keys in Portkey for better security and rotation.
Always set up fallback providers for production applications:
Use semantic caching for cost savings on repeated queries:
Always include metadata for better observability:
Regularly check the Portkey dashboard for cost optimization opportunities.

Complete Production Example

Resources

Using OpenAI SDK with Portkey gives you the best of both worlds: familiar API + production-grade features.