LiteLLM

repository·litellm_internal_staging·Indexed 13 days ago

https://github.com/BerriAI/litellm

An open-source AI Gateway that unifies access to over 100 LLM providers using the OpenAI API format. It provides a Python SDK for direct integration and a Proxy Server for centralized, enterprise-ready management, including features like model fallbacks, guardrails, and observability.

Tokens
190.4K
Snippets
569
Records
763
Agent score
99%

What's inside LiteLLM

  1. What is CodeLlama Server

    litellm_internal_staging

    CodeLlama Server is a specialized implementation of LiteLLM designed for coding-related tasks. It provides a consistent OpenAI-compatible interface for multiple LLM providers (Anthropic, TogetherAI, OpenAI, etc.) with several built-in features:

    • Model Fallbacks: Automatically switches to backup models (e.g., GPT-4 or Claude-2) if the primary model (e.g., CodeLlama) fails, including support for retries and cooldowns.
    • Guardrails: Uses a default system prompt to restrict responses to coding questions only: system_prompt = "Only respond to questions about code. Say 'I don't know' to anything outside of that."
    • Consistent I/O: All models are called using the OpenAI format. Text responses are always at ['choices'][0]['message']['content'] and stream responses are at ['choices'][0]['delta']['content'].
    • Observability: Integrates with Promptlayer for prompt tracking and provides token usage/spend tracking.
    • Caching: Supports in-memory caching and GPT-Cache integration.
  2. What is LiteLLM

    litellm_internal_staging

    LiteLLM is an open source AI Gateway that provides a single, unified interface to call over 100 LLM providers (including OpenAI, Anthropic, Gemini, Bedrock, and Azure) using the standard OpenAI format.

    It can be used in two primary ways:

    1. Python SDK: For direct library integration within your Python applications.
    2. AI Gateway (Proxy Server): As a centralized, self-hosted service for teams or organizations to manage LLM access.
  3. Overview of LiteLLM Rust AI Gateway

    litellm_internal_staging

    The LiteLLM Rust AI Gateway is a minimal Axum-based service designed to front OpenAI's realtime API. It acts as a WebSocket proxy: clients connect via wss://<host>/v1/realtime?model=<model>, and the gateway authenticates the request, selects the appropriate deployment from a configuration, and splices the client and OpenAI sockets frame-by-frame.

    Key Characteristics:

    • High Performance: The realtime hot path is implemented in pure Rust. Python is only used at load time to read the configuration.
    • Authentication: Requires a Bearer token via the Authorization header using the LITELLM_MASTER_KEY.
    • Observability: Provides health endpoints (/health/readiness, /health/liveness, /health/gil) and sends session logs to a LiteLLM proxy via a non-blocking background worker.
  4. Supported caching mechanisms in LiteLLM

    litellm_internal_staging

    LiteLLM provides several caching mechanisms to optimize LLM calls, ranging from simple in-memory storage to advanced semantic caching using vector databases. You can choose a mechanism based on your requirements for persistence, latency, and semantic similarity matching.

    Supported cache types:

    • RedisCache: Standard key-value caching using Redis.
    • RedisSemanticCache: Semantic caching using Redis (typically involves vector similarity).
    • QdrantSemanticCache: Semantic caching using the Qdrant vector database.
    • InMemoryCache: Fast, non-persistent caching in local memory.
    • DiskCache: Persistent caching stored on the local file system.
    • S3Cache: Persistent caching stored in AWS S3.
    • AzureBlobCache: Persistent caching stored in Azure Blob Storage.
    • DualCache: A hybrid approach that updates both a Redis cache and an in-memory cache simultaneously for high performance and shared state.
  5. Use LiteLLM for OpenAI Realtime API abstraction and routing

    litellm_internal_staging

    LiteLLM provides an abstraction and routing layer for OpenAI's /v1/realtime endpoints. This allows you to interact with real-time audio/text capabilities across multiple providers using a unified interface.

    Supported Endpoints

    • WebSocket: /v1/realtime (Note: Use intent=transcription for sessions requiring transcription only).
    • HTTP: /v1/realtime/client_secrets and /v1/realtime/transcription_sessions.

    Supported Providers

    You can route real-time requests to the following providers:

    • OpenAI
    • Azure OpenAI
    • Bedrock
    • Vertex AI
    • xAI
  6. What the liteLLM Proxy Server does

    litellm_internal_staging

    The liteLLM Proxy Server provides a unified interface to interact with over 50+ LLM models from providers like Azure, OpenAI, Replicate, Anthropic, and Hugging Face.

    Key capabilities include:

    • Consistent Input/Output: All models are called using the OpenAI format (completion(model, messages)). Text responses are always accessible via ['choices'][0]['message']['content'].
    • Error Handling: Supports model fallbacks (e.g., if GPT-4 fails, automatically try llama2).
    • Logging: Integrates with providers like Supabase, Posthog, Mixpanel, Sentry, Lunary, Athina, and Helicone to log requests, responses, and errors.
    • Observability: Tracks token usage, spend per model, and implements semantic caching.
    • Streaming & Async: Supports streaming text responses via generators.
  7. How WebSearch Interception works

    litellm_internal_staging

    WebSearch Interception provides a server-side agentic loop for models that do not natively support web search (like Amazon Bedrock).

    The Workflow:

    1. Request: The user sends a single litellm.messages.acreate() call containing a web search tool.
    2. Conversion: If the user sent a native tool (e.g., Claude Code's web_search), LiteLLM converts it to the litellm_web_search standard format before the provider sees it. This prevents the provider from attempting to execute the tool natively and failing.
    3. Interception: The model returns a tool_use block. The WebSearchInterceptionLogger detects this.
    4. Execution: LiteLLM executes litellm.asearch() using the configured search provider.
    5. Completion: LiteLLM automatically performs the follow-up API call with the search results and returns the final, synthesized answer to the user.

    Key Benefit: The user only makes one API call instead of manually managing the tool-call/tool-result loop.

  8. How Dotprompt converts templates to chat messages

    litellm_internal_staging

    The Dotprompt manager automatically converts rendered text into structured chat messages based on the template content:

    1. Simple Text: A template containing only text (e.g., Tell me about {{topic}}.) is converted into a single user role message.
    2. Role-Based Format: If you use explicit role prefixes like System: and User:, the manager parses them into multiple messages.

    Example Conversion: Template:

    System: You are a {{role}}.
    User: {{question}}

    Becomes:

    [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is AI?"}
    ]
  9. How Pass-Through Endpoint Guardrail Translation works

    litellm_internal_staging

    The PassThroughEndpointHandler enables guardrails to run on requests sent through passthrough endpoints. It operates using three main mechanisms:

    1. Field Targeting: It uses JSONPath expressions (configured via request_fields and response_fields) to extract specific data from the request or response for guardrail evaluation.
    2. Full Payload Fallback: If no specific JSONPath fields are provided in the configuration, the handler processes the entire request/response payload.
    3. Config Access: The handler retrieves guardrail configurations from request metadata using get_passthrough_guardrails_config() and set_passthrough_guardrails_config() helpers.

    This module is designed for auto-discovery by the load_guardrail_translation_mappings() function in litellm/llms/__init__.py.

  10. Understand the LiteLLM UI file structure and routing

    litellm_internal_staging

    The LiteLLM UI uses a strict NextJS file-based routing system. Pages are defined by folders containing a page.tsx file. Routing is automatically determined by the directory path.

    To create routes that do not appear in the URL path but still allow for shared layouts and organizational structure, use parentheses around the directory name (e.g., (dashboard)).

    // Example: Visiting /settings/admin-settings renders this file
    . 
    ├── settings
    │   ├── admin-settings
    │   │   └── page.tsx