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

Overview

The Python SDK offers:
  • OpenAI-Compatible API: Drop-in replacement for OpenAI SDK
  • 250+ LLMs: Access any LLM through a unified interface
  • Type Safety: Full type hints and IDE autocomplete
  • Advanced Routing: Fallbacks, load balancing, and conditional routing
  • Production Features: Caching, retries, timeouts, and guardrails
  • Observability: Built-in logging, tracing, and analytics

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 by changing the provider or virtual_key:

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:

Async Support

Use async/await for concurrent requests:

Async Streaming

Error Handling

Best Practices

Store provider API keys as Virtual Keys in Portkey for better security:
Always configure fallback providers for production:
Use caching for repeated queries to reduce costs:
Always add metadata for better tracking and debugging:
Use AsyncPortkey for applications with many concurrent requests.

Complete Example

Resources

Questions? Join our Discord community for help.