Skip to main content

Overview

The Router class provides intelligent load balancing, fallbacks, and retries across multiple LLM deployments. It’s the core of LiteLLM’s reliability features.

Class Definition

Constructor Parameters

Model Configuration

List[Dict]
required
List of model deployments with their configurations.

Caching

bool
default:"false"
Enable response caching to reduce costs and latency.
string
Redis connection string for distributed caching.
string
Redis host (alternative to redis_url).
int
Redis port.
string
Redis password.

Routing Strategy

string
default:"simple-shuffle"
Strategy for selecting deployments.Options:
  • "simple-shuffle": Random selection
  • "least-busy": Route to deployment with fewest ongoing requests
  • "usage-based-routing": Based on TPM/RPM limits
  • "latency-based-routing": Route to fastest deployment
  • "cost-based-routing": Route to cheapest deployment
  • "usage-based-routing-v2": Improved TPM/RPM routing
dict
Additional arguments for routing strategies.

Reliability

int
default:"0"
Number of retry attempts on failure.
float
default:"600"
Default timeout for requests in seconds.
List[Dict]
Fallback configurations for handling failures.
List[Dict]
Fallbacks specifically for context window exceeded errors.
int
default:"3"
Number of failures before a deployment enters cooldown.
float
default:"60"
Cooldown period in seconds after allowed_fails is reached.
int
default:"0"
Minimum time to wait before retrying a failed request.
dict
Custom retry policy for different exception types.

Rate Limiting

int
Maximum parallel requests per deployment.

Observability

bool
default:"false"
Enable verbose logging.
Literal
default:"INFO"
Log level: “DEBUG” or “INFO”.

Core Methods

completion()

Make a completion request with routing and fallbacks.
Supports all parameters from litellm.completion().

acompletion()

Async version of completion().

embedding()

Generate embeddings with routing.

aembedding()

Async version of embedding().

image_generation()

Generate images with routing.

aimage_generation()

Async version of image_generation().

Usage Examples

Basic Setup

Load Balancing with Rate Limits

Fallbacks

Context Window Fallbacks

Latency-Based Routing

With Redis Caching

Cooldown on Failures

Cost-Based Routing

Health Checks

Model Aliases

Advanced Features

Custom Callbacks

Router with Authentication

Best Practices

  1. Use rate limits: Set TPM/RPM to prevent hitting provider limits
  2. Enable fallbacks: Always have backup models configured
  3. Use caching: Reduce costs and latency with Redis caching
  4. Set timeouts: Appropriate timeouts prevent hanging requests
  5. Monitor health: Enable health checks for production
  6. Use aliases: Abstract model names for easier updates
  7. Configure retries: Set appropriate retry policies per error type