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)
Best Practices
Use Virtual Keys
Use Virtual Keys
Store your provider API keys as Virtual Keys in Portkey for better security and rotation.
Configure Fallbacks
Configure Fallbacks
Always set up fallback providers for production applications:
Enable Caching
Enable Caching
Use semantic caching for cost savings on repeated queries:
Add Metadata
Add Metadata
Always include metadata for better observability:
Monitor in Dashboard
Monitor in Dashboard
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.