+
## Supported Providers ([Website Supported Models](https://models.litellm.ai/) | [Docs](https://docs.litellm.ai/docs/providers))
| Provider | `/chat/completions` | `/messages` | `/responses` | `/embeddings` | `/image/generations` | `/audio/transcriptions` | `/audio/speech` | `/moderations` | `/batches` | `/rerank` |
@@ -296,7 +309,7 @@ Support for more providers. Missing a provider or LLM Platform, raise a [feature
| [Deepgram (`deepgram`)](https://docs.litellm.ai/docs/providers/deepgram) | ✅ | ✅ | ✅ | | | ✅ | | | | |
| [DeepInfra (`deepinfra`)](https://docs.litellm.ai/docs/providers/deepinfra) | ✅ | ✅ | ✅ | | | | | | | |
| [Deepseek (`deepseek`)](https://docs.litellm.ai/docs/providers/deepseek) | ✅ | ✅ | ✅ | | | | | | | |
-| [ElevenLabs (`elevenlabs`)](https://docs.litellm.ai/docs/providers/elevenlabs) | ✅ | ✅ | ✅ | | | | ✅ | | | |
+| [ElevenLabs (`elevenlabs`)](https://docs.litellm.ai/docs/providers/elevenlabs) | ✅ | ✅ | ✅ | | | ✅ | ✅ | | | |
| [Empower (`empower`)](https://docs.litellm.ai/docs/providers/empower) | ✅ | ✅ | ✅ | | | | | | | |
| [Fal AI (`fal_ai`)](https://docs.litellm.ai/docs/providers/fal_ai) | ✅ | ✅ | ✅ | | ✅ | | | | | |
| [Featherless AI (`featherless_ai`)](https://docs.litellm.ai/docs/providers/featherless_ai) | ✅ | ✅ | ✅ | | | | | | | |
diff --git a/ci_cd/.grype.yaml b/ci_cd/.grype.yaml
index 642e2dd9d03..b9bc9db58f5 100644
--- a/ci_cd/.grype.yaml
+++ b/ci_cd/.grype.yaml
@@ -1,3 +1,36 @@
ignore:
- vulnerability: CVE-2026-22184
reason: no fixed zlib package is available yet in the Wolfi repositories, so this is ignored temporarily until an upstream release exists
+ # Wolfi base image: Python 3.13 and Node from apk have no fixed builds in Wolfi yet / not applicable
+ - vulnerability: CVE-2025-55130
+ reason: Node in Wolfi apk; only used for Admin UI build/prisma
+ - vulnerability: CVE-2025-59465
+ reason: Node in Wolfi apk; only used for Admin UI build/prisma
+ - vulnerability: CVE-2025-55131
+ reason: Node in Wolfi apk; only used for Admin UI build/prisma
+ - vulnerability: CVE-2025-59466
+ reason: Node in Wolfi apk; only used for Admin UI build/prisma
+ - vulnerability: CVE-2026-21637
+ reason: Node in Wolfi apk; only used for Admin UI build/prisma
+ - vulnerability: CVE-2025-55132
+ reason: Node in Wolfi apk; only used for Admin UI build/prisma
+ - vulnerability: GHSA-hx9q-6w63-j58v
+ reason: orjson dumps recursion; allowlisted
+ - vulnerability: GHSA-73rr-hh4g-fpgx
+ reason: diff npm transitive dep; override in package.json, allowlisted
+ - vulnerability: CVE-2026-0865
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
+ - vulnerability: CVE-2025-15282
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
+ - vulnerability: CVE-2026-0672
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
+ - vulnerability: CVE-2025-15366
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
+ - vulnerability: CVE-2025-15367
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
+ - vulnerability: CVE-2025-11468
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
+ - vulnerability: CVE-2025-12781
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
+ - vulnerability: CVE-2026-1299
+ reason: Python 3.13 in Wolfi base; no fixed apk build yet
diff --git a/ci_cd/security_scans.sh b/ci_cd/security_scans.sh
index 04f3e27a944..2db72ae5c69 100755
--- a/ci_cd/security_scans.sh
+++ b/ci_cd/security_scans.sh
@@ -81,10 +81,10 @@ run_trivy_scans() {
echo "Running Trivy scans..."
echo "Scanning LiteLLM Docs..."
- trivy fs --scanners vuln --dependency-tree --exit-code 1 --severity HIGH,CRITICAL,MEDIUM ./docs/
+ trivy fs --ignorefile .trivyignore --scanners vuln --dependency-tree --exit-code 1 --severity HIGH,CRITICAL,MEDIUM ./docs/
echo "Scanning LiteLLM UI..."
- trivy fs --scanners vuln --dependency-tree --exit-code 1 --severity HIGH,CRITICAL,MEDIUM ./ui/
+ trivy fs --ignorefile .trivyignore --scanners vuln --dependency-tree --exit-code 1 --severity HIGH,CRITICAL,MEDIUM ./ui/
echo "Trivy scans completed successfully"
}
@@ -137,7 +137,27 @@ run_grype_scans() {
"CVE-2019-1010025" # glibc pthread heap address leak - awaiting patched Wolfi glibc build
"CVE-2026-22184" # zlib untgz buffer overflow - untgz unused + no fixed Wolfi build yet
"GHSA-58pv-8j8x-9vj2" # jaraco.context path traversal - setuptools vendored only (v5.3.0), not used in application code (using v6.1.0+)
+ "GHSA-34x7-hfp2-rc4v" # node-tar hardlink path traversal - not applicable, tar CLI not exposed in application code
"GHSA-r6q2-hw4h-h46w" # node-tar not used by application runtime, Linux-only container, not affect by macOS APFS-specific exploit
+ "GHSA-8rrh-rw8j-w5fx" # wheel is from chainguard and will be handled by then TODO: Remove this after Chainguard updates the wheel
+ "CVE-2025-59465" # Node only used for Admin UI build/prisma
+ "CVE-2025-55131" # Node only used for Admin UI build/prisma
+ "CVE-2025-59466" # Node only used for Admin UI build/prisma
+ "CVE-2025-55130" # Node only used for Admin UI build/prisma
+ "CVE-2025-59467" # Node only used for Admin UI build/prisma
+ "CVE-2026-21637" # Node only used for Admin UI build/prisma
+ "CVE-2025-55132" # Node only used for Admin UI build/prisma
+ "GHSA-hx9q-6w63-j58v" # orjson dumps recursion; allowlisted
+ "CVE-2025-15281" # No fix available yet
+ "CVE-2026-0865" # No fix available yet
+ "CVE-2025-15282" # No fix available yet
+ "CVE-2026-0672" # No fix available yet
+ "CVE-2025-15366" # No fix available yet
+ "CVE-2025-15367" # No fix available yet
+ "CVE-2025-12781" # No fix available yet
+ "CVE-2025-11468" # No fix available yet
+ "CVE-2026-1299" # Python 3.13 email module header injection - not applicable, LiteLLM doesn't use BytesGenerator for email serialization
+ "CVE-2026-0775" # npm cli incorrect permission assignment - no fix available yet, npm is only used at build/prisma-generate time
)
# Build JSON array of allowlisted CVE IDs for jq
diff --git a/cookbook/anthropic_agent_sdk/README.md b/cookbook/anthropic_agent_sdk/README.md
new file mode 100644
index 00000000000..294d949e24e
--- /dev/null
+++ b/cookbook/anthropic_agent_sdk/README.md
@@ -0,0 +1,144 @@
+# Claude Agent SDK with LiteLLM Gateway
+
+A simple example showing how to use Claude's Agent SDK with LiteLLM as a proxy. This lets you use any LLM provider (OpenAI, Bedrock, Azure, etc.) through the Agent SDK.
+
+## Quick Start
+
+### 1. Install dependencies
+
+```bash
+pip install anthropic claude-agent-sdk litellm
+```
+
+### 2. Start LiteLLM proxy
+
+```bash
+# Simple start with Claude
+litellm --model claude-sonnet-4-20250514
+
+# Or with a config file
+litellm --config config.yaml
+```
+
+### 3. Run the chat
+
+**Basic Agent (no MCP):**
+
+```bash
+python main.py
+```
+
+**Agent with MCP (DeepWiki2 for research):**
+
+```bash
+python agent_with_mcp.py
+```
+
+If MCP connection fails, you can disable it:
+
+```bash
+USE_MCP=false python agent_with_mcp.py
+```
+
+That's it! You can now chat with the agent in your terminal.
+
+### Chat Commands
+
+While chatting, you can use these commands:
+- `models` - List all available models (fetched from your LiteLLM proxy)
+- `model` - Switch to a different model
+- `clear` - Start a new conversation
+- `quit` or `exit` - End the chat
+
+The chat automatically fetches available models from your LiteLLM proxy's `/models` endpoint, so you'll always see what's currently configured.
+
+## Configuration
+
+Set these environment variables if needed:
+
+```bash
+export LITELLM_PROXY_URL="http://localhost:4000"
+export LITELLM_API_KEY="sk-1234"
+export LITELLM_MODEL="bedrock-claude-sonnet-4.5"
+```
+
+Or just use the defaults - it'll connect to `http://localhost:4000` by default.
+
+## Files
+
+- `main.py` - Basic interactive agent without MCP
+- `agent_with_mcp.py` - Agent with MCP server integration (DeepWiki2)
+- `common.py` - Shared utilities and functions
+- `config.example.yaml` - Example LiteLLM configuration
+- `requirements.txt` - Python dependencies
+
+## Example Config File
+
+If you want to use multiple models, create a `config.yaml` (see `config.example.yaml`):
+
+```yaml
+model_list:
+ - model_name: bedrock-claude-sonnet-4
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-claude-sonnet-4.5
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0"
+ aws_region_name: "us-east-1"
+```
+
+Then start LiteLLM with: `litellm --config config.yaml`
+
+## How It Works
+
+The key is pointing the Agent SDK to LiteLLM instead of directly to Anthropic:
+
+```python
+# Point to LiteLLM gateway (not Anthropic)
+os.environ["ANTHROPIC_BASE_URL"] = "http://localhost:4000"
+os.environ["ANTHROPIC_API_KEY"] = "sk-1234" # Your LiteLLM key
+
+# Use any model configured in LiteLLM
+options = ClaudeAgentOptions(
+ model="bedrock-claude-sonnet-4", # or gpt-4, or anything else
+ system_prompt="You are a helpful assistant.",
+ max_turns=50,
+)
+```
+
+Note: Don't add `/anthropic` to the base URL - LiteLLM handles the routing automatically.
+
+## Why Use This?
+
+- **Switch providers easily**: Use the same code with OpenAI, Bedrock, Azure, etc.
+- **Cost tracking**: LiteLLM tracks spending across all your agent conversations
+- **Rate limiting**: Set budgets and limits on your agent usage
+- **Load balancing**: Distribute requests across multiple API keys or regions
+- **Fallbacks**: Automatically retry with a different model if one fails
+
+## Troubleshooting
+
+**Connection errors?**
+- Make sure LiteLLM is running: `litellm --model your-model`
+- Check the URL is correct (default: `http://localhost:4000`)
+
+**Authentication errors?**
+- Verify your LiteLLM API key is correct
+- Make sure the model is configured in your LiteLLM setup
+
+**Model not found?**
+- Check the model name matches what's in your LiteLLM config
+- Run `litellm --model your-model` to test it works
+
+**Agent with MCP stuck or failing?**
+- The MCP server might not be available at `http://localhost:4000/mcp/deepwiki2`
+- Try disabling MCP: `USE_MCP=false python agent_with_mcp.py`
+- Or use the basic agent: `python main.py`
+
+## Learn More
+
+- [LiteLLM Docs](https://docs.litellm.ai/)
+- [Claude Agent SDK](https://github.com/anthropics/anthropic-agent-sdk)
+- [LiteLLM Proxy Guide](https://docs.litellm.ai/docs/proxy/quick_start)
diff --git a/cookbook/anthropic_agent_sdk/agent_with_mcp.py b/cookbook/anthropic_agent_sdk/agent_with_mcp.py
new file mode 100644
index 00000000000..ff25feb777f
--- /dev/null
+++ b/cookbook/anthropic_agent_sdk/agent_with_mcp.py
@@ -0,0 +1,140 @@
+"""
+Interactive Claude Agent SDK CLI with MCP Support
+
+This example demonstrates an interactive CLI chat with the Anthropic Agent SDK using LiteLLM as a proxy,
+with MCP (Model Context Protocol) server integration for enhanced capabilities.
+"""
+
+import asyncio
+import os
+from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
+from common import (
+ Config,
+ fetch_available_models,
+ setup_litellm_env,
+ print_header,
+ handle_model_list,
+ handle_model_switch,
+ stream_response,
+)
+
+
+async def interactive_chat_with_mcp():
+ """
+ Interactive CLI chat with the agent and MCP server
+ """
+ config = Config()
+
+ # Configure Anthropic SDK to point to LiteLLM gateway
+ litellm_base_url = setup_litellm_env(config)
+
+ # Fetch available models from proxy
+ available_models = await fetch_available_models(litellm_base_url, config.LITELLM_API_KEY)
+
+ current_model = config.LITELLM_MODEL
+
+ # MCP server configuration
+ mcp_server_url = f"{litellm_base_url}/mcp/deepwiki2"
+ use_mcp = os.getenv("USE_MCP", "true").lower() == "true"
+
+ if not use_mcp:
+ print("⚠️ MCP disabled via USE_MCP=false")
+
+ print_header(litellm_base_url, current_model, has_mcp=use_mcp)
+
+ while True:
+ # Configure agent options
+ if use_mcp:
+ try:
+ # Try with MCP server (HTTP transport)
+ # Using McpHttpServerConfig format from Agent SDK
+ options = ClaudeAgentOptions(
+ system_prompt="You are a helpful AI assistant with access to DeepWiki for research. Be concise, accurate, and friendly.",
+ model=current_model,
+ max_turns=50,
+ mcp_servers={
+ "deepwiki2": {
+ "type": "http",
+ "url": mcp_server_url,
+ "headers": {
+ "Authorization": f"Bearer {config.LITELLM_API_KEY}"
+ }
+ }
+ },
+ )
+ except Exception as e:
+ print(f"⚠️ Warning: Could not configure MCP server: {e}")
+ print("Continuing without MCP...\n")
+ use_mcp = False
+ options = ClaudeAgentOptions(
+ system_prompt="You are a helpful AI assistant. Be concise, accurate, and friendly.",
+ model=current_model,
+ max_turns=50,
+ )
+ else:
+ # Without MCP
+ options = ClaudeAgentOptions(
+ system_prompt="You are a helpful AI assistant. Be concise, accurate, and friendly.",
+ model=current_model,
+ max_turns=50,
+ )
+
+ # Create agent client
+ try:
+ async with ClaudeSDKClient(options=options) as client:
+ conversation_active = True
+
+ while conversation_active:
+ # Get user input
+ try:
+ user_input = input("\n👤 You: ").strip()
+ except (EOFError, KeyboardInterrupt):
+ print("\n\n👋 Goodbye!")
+ return
+
+ # Handle commands
+ if user_input.lower() in ['quit', 'exit']:
+ print("\n👋 Goodbye!")
+ return
+
+ if user_input.lower() == 'clear':
+ print("\n🔄 Starting new conversation...\n")
+ conversation_active = False
+ continue
+
+ if user_input.lower() == 'models':
+ handle_model_list(available_models, current_model)
+ continue
+
+ if user_input.lower() == 'model':
+ new_model, should_restart = handle_model_switch(available_models, current_model)
+ if should_restart:
+ current_model = new_model
+ conversation_active = False
+ continue
+
+ if not user_input:
+ continue
+
+ # Stream response from agent
+ await stream_response(client, user_input)
+
+ except Exception as e:
+ print(f"\n❌ Error creating agent client: {e}")
+ print("This might be an MCP configuration issue. Try running without MCP:")
+ print(" USE_MCP=false python agent_with_mcp.py")
+ print("\nOr use the basic agent:")
+ print(" python main.py")
+ return
+
+
+def main():
+ """Run interactive chat with MCP"""
+ try:
+ asyncio.run(interactive_chat_with_mcp())
+ except KeyboardInterrupt:
+ print("\n\n👋 Goodbye!")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/cookbook/anthropic_agent_sdk/common.py b/cookbook/anthropic_agent_sdk/common.py
new file mode 100644
index 00000000000..d9ee65cb58d
--- /dev/null
+++ b/cookbook/anthropic_agent_sdk/common.py
@@ -0,0 +1,160 @@
+"""
+Common utilities for Claude Agent SDK examples
+"""
+
+import os
+import httpx
+
+
+class Config:
+ """Configuration for LiteLLM Gateway connection"""
+
+ # LiteLLM proxy URL (default to local instance)
+ LITELLM_PROXY_URL = os.getenv("LITELLM_PROXY_URL", "http://localhost:4000")
+
+ # LiteLLM API key (master key or virtual key)
+ LITELLM_API_KEY = os.getenv("LITELLM_API_KEY", "sk-1234")
+
+ # Model name as configured in LiteLLM (e.g., "bedrock-claude-sonnet-4", "gpt-4", etc.)
+ LITELLM_MODEL = os.getenv("LITELLM_MODEL", "bedrock-claude-sonnet-4.5")
+
+
+async def fetch_available_models(base_url: str, api_key: str) -> list[str]:
+ """
+ Fetch available models from LiteLLM proxy /models endpoint
+ """
+ try:
+ async with httpx.AsyncClient() as client:
+ response = await client.get(
+ f"{base_url}/models",
+ headers={"Authorization": f"Bearer {api_key}"},
+ timeout=10.0
+ )
+ response.raise_for_status()
+ data = response.json()
+ return [model["id"] for model in data.get("data", [])]
+ except Exception as e:
+ print(f"⚠️ Warning: Could not fetch models from proxy: {e}")
+ print("Using default model list...")
+ # Fallback to default models
+ return [
+ "bedrock-claude-sonnet-3.5",
+ "bedrock-claude-sonnet-4",
+ "bedrock-claude-sonnet-4.5",
+ "bedrock-claude-opus-4.5",
+ "bedrock-nova-premier",
+ ]
+
+
+def setup_litellm_env(config: Config):
+ """
+ Configure environment variables to point Agent SDK to LiteLLM
+ """
+ litellm_base_url = config.LITELLM_PROXY_URL.rstrip('/')
+ os.environ["ANTHROPIC_BASE_URL"] = litellm_base_url
+ os.environ["ANTHROPIC_API_KEY"] = config.LITELLM_API_KEY
+ return litellm_base_url
+
+
+def print_header(base_url: str, current_model: str, has_mcp: bool = False):
+ """
+ Print the chat header
+ """
+ mcp_indicator = " + MCP" if has_mcp else ""
+ print("=" * 70)
+ print(f"🤖 Claude Agent SDK with LiteLLM Gateway{mcp_indicator} - Interactive Chat")
+ print("=" * 70)
+ print(f"🚀 Connected to: {base_url}")
+ print(f"📦 Current model: {current_model}")
+ if has_mcp:
+ print("🔌 MCP: deepwiki2 enabled")
+ print("\nType your messages below. Commands:")
+ print(" - 'quit' or 'exit' to end the conversation")
+ print(" - 'clear' to start a new conversation")
+ print(" - 'model' to switch models")
+ print(" - 'models' to list available models")
+ print("=" * 70)
+ print()
+
+
+def handle_model_list(available_models: list[str], current_model: str):
+ """
+ Display available models
+ """
+ print("\n📋 Available models:")
+ for i, model in enumerate(available_models, 1):
+ marker = "✓" if model == current_model else " "
+ print(f" {marker} {i}. {model}")
+
+
+def handle_model_switch(available_models: list[str], current_model: str) -> tuple[str, bool]:
+ """
+ Handle model switching
+
+ Returns:
+ tuple: (new_model, should_restart_conversation)
+ """
+ print("\n📋 Select a model:")
+ for i, model in enumerate(available_models, 1):
+ marker = "✓" if model == current_model else " "
+ print(f" {marker} {i}. {model}")
+
+ try:
+ choice = input("\nEnter number (or press Enter to cancel): ").strip()
+ if choice:
+ idx = int(choice) - 1
+ if 0 <= idx < len(available_models):
+ new_model = available_models[idx]
+ print(f"\n✅ Switched to: {new_model}")
+ print("🔄 Starting new conversation with new model...\n")
+ return new_model, True
+ else:
+ print("❌ Invalid choice")
+ except (ValueError, IndexError):
+ print("❌ Invalid input")
+
+ return current_model, False
+
+
+async def stream_response(client, user_input: str):
+ """
+ Stream response from the agent
+ """
+ print("\n🤖 Assistant: ", end='', flush=True)
+
+ try:
+ await client.query(user_input)
+
+ # Show loading indicator
+ print("⏳ thinking...", end='', flush=True)
+
+ # Stream the response
+ first_chunk = True
+ async for msg in client.receive_response():
+ # Clear loading indicator on first message
+ if first_chunk:
+ print("\r🤖 Assistant: ", end='', flush=True)
+ first_chunk = False
+
+ # Handle different message types
+ if hasattr(msg, 'type'):
+ if msg.type == 'content_block_delta':
+ # Streaming text delta
+ if hasattr(msg, 'delta') and hasattr(msg.delta, 'text'):
+ print(msg.delta.text, end='', flush=True)
+ elif msg.type == 'content_block_start':
+ # Start of content block
+ if hasattr(msg, 'content_block') and hasattr(msg.content_block, 'text'):
+ print(msg.content_block.text, end='', flush=True)
+
+ # Fallback to original content handling
+ if hasattr(msg, 'content'):
+ for content_block in msg.content:
+ if hasattr(content_block, 'text'):
+ print(content_block.text, end='', flush=True)
+
+ print() # New line after response
+
+ except Exception as e:
+ print(f"\r\n❌ Error: {e}")
+ print("Please check your LiteLLM gateway is running and configured correctly.")
diff --git a/cookbook/anthropic_agent_sdk/config.example.yaml b/cookbook/anthropic_agent_sdk/config.example.yaml
new file mode 100644
index 00000000000..eb1984fc4ea
--- /dev/null
+++ b/cookbook/anthropic_agent_sdk/config.example.yaml
@@ -0,0 +1,25 @@
+model_list:
+ - model_name: bedrock-claude-sonnet-3.5
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-claude-sonnet-4
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-claude-sonnet-4.5
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-claude-opus-4.5
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-opus-4-5-20251101-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-nova-premier
+ litellm_params:
+ model: "bedrock/amazon.nova-premier-v1:0"
+ aws_region_name: "us-east-1"
diff --git a/cookbook/anthropic_agent_sdk/main.py b/cookbook/anthropic_agent_sdk/main.py
new file mode 100644
index 00000000000..231b57ca97b
--- /dev/null
+++ b/cookbook/anthropic_agent_sdk/main.py
@@ -0,0 +1,95 @@
+"""
+Simple Interactive Claude Agent SDK CLI using LiteLLM Gateway
+
+This example demonstrates an interactive CLI chat with the Anthropic Agent SDK using LiteLLM as a proxy.
+LiteLLM acts as a unified interface, allowing you to use any LLM provider (OpenAI, Azure, Bedrock, etc.)
+through the Claude Agent SDK by pointing it to the LiteLLM gateway.
+"""
+
+import asyncio
+from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
+from common import (
+ Config,
+ fetch_available_models,
+ setup_litellm_env,
+ print_header,
+ handle_model_list,
+ handle_model_switch,
+ stream_response,
+)
+
+
+async def interactive_chat():
+ """
+ Interactive CLI chat with the agent
+ """
+ config = Config()
+
+ # Configure Anthropic SDK to point to LiteLLM gateway
+ litellm_base_url = setup_litellm_env(config)
+
+ # Fetch available models from proxy
+ available_models = await fetch_available_models(litellm_base_url, config.LITELLM_API_KEY)
+
+ current_model = config.LITELLM_MODEL
+
+ print_header(litellm_base_url, current_model)
+
+ while True:
+ # Configure agent options for each conversation
+ options = ClaudeAgentOptions(
+ system_prompt="You are a helpful AI assistant. Be concise, accurate, and friendly.",
+ model=current_model,
+ max_turns=50,
+ )
+
+ # Create agent client
+ async with ClaudeSDKClient(options=options) as client:
+ conversation_active = True
+
+ while conversation_active:
+ # Get user input
+ try:
+ user_input = input("\n👤 You: ").strip()
+ except (EOFError, KeyboardInterrupt):
+ print("\n\n👋 Goodbye!")
+ return
+
+ # Handle commands
+ if user_input.lower() in ['quit', 'exit']:
+ print("\n👋 Goodbye!")
+ return
+
+ if user_input.lower() == 'clear':
+ print("\n🔄 Starting new conversation...\n")
+ conversation_active = False
+ continue
+
+ if user_input.lower() == 'models':
+ handle_model_list(available_models, current_model)
+ continue
+
+ if user_input.lower() == 'model':
+ new_model, should_restart = handle_model_switch(available_models, current_model)
+ if should_restart:
+ current_model = new_model
+ conversation_active = False
+ continue
+
+ if not user_input:
+ continue
+
+ # Stream response from agent
+ await stream_response(client, user_input)
+
+
+def main():
+ """Run interactive chat"""
+ try:
+ asyncio.run(interactive_chat())
+ except KeyboardInterrupt:
+ print("\n\n👋 Goodbye!")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/cookbook/anthropic_agent_sdk/requirements.txt b/cookbook/anthropic_agent_sdk/requirements.txt
new file mode 100644
index 00000000000..1e810bb7d99
--- /dev/null
+++ b/cookbook/anthropic_agent_sdk/requirements.txt
@@ -0,0 +1,2 @@
+claude-agent-sdk
+httpx>=0.27.0
diff --git a/cookbook/livekit_agent_sdk/README.md b/cookbook/livekit_agent_sdk/README.md
new file mode 100644
index 00000000000..1c3f0bf9564
--- /dev/null
+++ b/cookbook/livekit_agent_sdk/README.md
@@ -0,0 +1,114 @@
+# LiveKit Voice Agent with LiteLLM Gateway
+
+Simple example showing how to use LiveKit's xAI realtime plugin with LiteLLM as a proxy. This lets you switch between xAI, OpenAI, and Azure realtime APIs without changing your code.
+
+## Quick Start
+
+### 1. Install dependencies
+
+```bash
+pip install livekit-agents[xai] websockets
+```
+
+### 2. Start LiteLLM proxy
+
+```bash
+# With xAI
+export XAI_API_KEY="your-xai-key"
+litellm --config config.yaml --port 4000
+```
+
+### 3. Run the voice agent
+
+```bash
+python main.py
+```
+
+Type your message and get a voice response from Grok!
+
+## Configuration
+
+Set these environment variables if needed:
+
+```bash
+export LITELLM_PROXY_URL="http://localhost:4000"
+export LITELLM_API_KEY="sk-1234"
+export LITELLM_MODEL="grok-voice-agent"
+```
+
+Or use the defaults - connects to `http://localhost:4000` by default.
+
+## Example Config File
+
+Create a `config.yaml` with your realtime models:
+
+```yaml
+model_list:
+ - model_name: grok-voice-agent
+ litellm_params:
+ model: xai/grok-2-vision-1212
+ api_key: os.environ/XAI_API_KEY
+ model_info:
+ mode: realtime
+
+ - model_name: openai-voice-agent
+ litellm_params:
+ model: gpt-4o-realtime-preview
+ api_key: os.environ/OPENAI_API_KEY
+ model_info:
+ mode: realtime
+
+general_settings:
+ master_key: sk-1234
+```
+
+Then start: `litellm --config config.yaml --port 4000`
+
+## How It Works
+
+LiveKit's xAI plugin connects through LiteLLM proxy by setting `base_url`:
+
+```python
+from livekit.plugins import xai
+
+model = xai.realtime.RealtimeModel(
+ voice="ara",
+ api_key="sk-1234", # LiteLLM proxy key
+ base_url="http://localhost:4000", # Point to LiteLLM
+)
+```
+
+## Switching Providers
+
+Just change the model in your config - no code changes needed:
+
+**xAI Grok:**
+```yaml
+model: xai/grok-2-vision-1212
+```
+
+**OpenAI:**
+```yaml
+model: gpt-4o-realtime-preview
+```
+
+**Azure OpenAI:**
+```yaml
+model: azure/gpt-4o-realtime-preview
+api_base: https://your-endpoint.openai.azure.com/
+```
+
+## Why Use LiteLLM?
+
+- ✅ **Switch providers** without changing agent code
+- ✅ **Cost tracking** across all voice sessions
+- ✅ **Rate limiting** and budgets
+- ✅ **Load balancing** across multiple API keys
+- ✅ **Fallbacks** to backup models
+
+## Learn More
+
+- [LiveKit xAI Realtime Tutorial](/docs/tutorials/livekit_xai_realtime)
+- [xAI Realtime Docs](/docs/providers/xai_realtime)
+- [LiveKit Agents Documentation](https://docs.livekit.io/agents/)
+- [LiteLLM Realtime API](/docs/realtime)
diff --git a/cookbook/livekit_agent_sdk/config.example.yaml b/cookbook/livekit_agent_sdk/config.example.yaml
new file mode 100644
index 00000000000..1361f36af34
--- /dev/null
+++ b/cookbook/livekit_agent_sdk/config.example.yaml
@@ -0,0 +1,21 @@
+model_list:
+ - model_name: grok-voice-agent
+ litellm_params:
+ model: xai/grok-2-vision-1212
+ api_key: os.environ/XAI_API_KEY
+ model_info:
+ mode: realtime
+
+ - model_name: openai-voice-agent
+ litellm_params:
+ model: gpt-4o-realtime-preview
+ api_key: os.environ/OPENAI_API_KEY
+ model_info:
+ mode: realtime
+
+litellm_settings:
+ drop_params: True
+ telemetry: False
+
+general_settings:
+ master_key: sk-1234 # Change this to a secure key
diff --git a/cookbook/livekit_agent_sdk/main.py b/cookbook/livekit_agent_sdk/main.py
new file mode 100644
index 00000000000..0e2d7ebdfaf
--- /dev/null
+++ b/cookbook/livekit_agent_sdk/main.py
@@ -0,0 +1,112 @@
+"""
+Simple xAI Voice Agent using LiveKit SDK with LiteLLM Gateway
+
+This example shows how to use LiveKit's xAI realtime plugin through LiteLLM proxy.
+LiteLLM acts as a unified interface, allowing you to switch between xAI, OpenAI,
+and Azure realtime APIs without changing your agent code.
+"""
+import asyncio
+import json
+import os
+import websockets
+
+# Configuration
+PROXY_URL = os.getenv("LITELLM_PROXY_URL", "http://localhost:4000")
+API_KEY = os.getenv("LITELLM_API_KEY", "sk-1234")
+MODEL = os.getenv("LITELLM_MODEL", "grok-voice-agent")
+
+
+async def run_voice_agent():
+ """
+ Simple voice agent that:
+ 1. Connects to xAI realtime API through LiteLLM proxy
+ 2. Sends a user message
+ 3. Streams back the response
+ """
+
+ url = f"ws://{PROXY_URL.replace('http://', '').replace('https://', '')}/v1/realtime?model={MODEL}"
+ headers = {"Authorization": f"Bearer {API_KEY}"}
+
+ print(f"🎙️ Connecting to voice agent...")
+ print(f" Model: {MODEL}")
+ print(f" Proxy: {PROXY_URL}")
+ print()
+
+ async with websockets.connect(url, additional_headers=headers) as ws:
+ # Receive initial connection event
+ initial = json.loads(await ws.recv())
+ print(f"✅ Connected! Event: {initial['type']}\n")
+
+ # Get user input
+ user_message = input("💬 Your message: ").strip()
+ if not user_message:
+ user_message = "Tell me a fun fact about AI!"
+
+ print(f"\n🤖 Sending to {MODEL}...\n")
+
+ # Send user message
+ await ws.send(json.dumps({
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [{"type": "input_text", "text": user_message}]
+ }
+ }))
+
+ # Request response
+ await ws.send(json.dumps({
+ "type": "response.create",
+ "response": {"modalities": ["text", "audio"]}
+ }))
+
+ # Stream response
+ print("🎤 Response: ", end='', flush=True)
+ transcript = []
+
+ try:
+ while True:
+ msg = await asyncio.wait_for(ws.recv(), timeout=15.0)
+ event = json.loads(msg)
+
+ # Capture transcript deltas
+ if event['type'] == 'response.output_audio_transcript.delta':
+ delta = event.get('delta', '')
+ if delta:
+ print(delta, end='', flush=True)
+ transcript.append(delta)
+
+ # Done when response completes
+ elif event['type'] == 'response.done':
+ break
+
+ except asyncio.TimeoutError:
+ pass
+
+ print("\n")
+
+ if transcript:
+ print(f"✅ Complete response: {''.join(transcript)}")
+
+ await ws.close()
+
+
+def main():
+ """Run the voice agent"""
+ print("=" * 70)
+ print("LiveKit xAI Voice Agent via LiteLLM Proxy")
+ print("=" * 70)
+ print()
+
+ try:
+ asyncio.run(run_voice_agent())
+ except KeyboardInterrupt:
+ print("\n\n👋 Goodbye!")
+ except Exception as e:
+ print(f"\n❌ Error: {e}")
+ print("\nMake sure LiteLLM proxy is running:")
+ print(f" litellm --config config.yaml --port 4000")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/cookbook/livekit_agent_sdk/requirements.txt b/cookbook/livekit_agent_sdk/requirements.txt
new file mode 100644
index 00000000000..9e3542fac27
--- /dev/null
+++ b/cookbook/livekit_agent_sdk/requirements.txt
@@ -0,0 +1,2 @@
+livekit-agents[xai]>=1.3.12
+websockets>=15.0.1
diff --git a/cookbook/mock_prompt_management_server/README.md b/cookbook/mock_prompt_management_server/README.md
new file mode 100644
index 00000000000..9ec76baacf7
--- /dev/null
+++ b/cookbook/mock_prompt_management_server/README.md
@@ -0,0 +1,293 @@
+# Mock Prompt Management Server
+
+A reference implementation of the [LiteLLM Generic Prompt Management API](https://docs.litellm.ai/docs/adding_provider/generic_prompt_management_api).
+
+This FastAPI server demonstrates how to build a prompt management API that integrates with LiteLLM without requiring a PR to the LiteLLM repository.
+
+## Quick Start
+
+### 1. Install Dependencies
+
+```bash
+pip install fastapi uvicorn pydantic
+```
+
+### 2. Start the Server
+
+```bash
+python mock_prompt_management_server.py
+```
+
+The server will start on `http://localhost:8080`
+
+### 3. Test the Endpoint
+
+```bash
+# Get a prompt
+curl "http://localhost:8080/beta/litellm_prompt_management?prompt_id=hello-world-prompt"
+
+# Get a prompt with authentication
+curl "http://localhost:8080/beta/litellm_prompt_management?prompt_id=hello-world-prompt" \
+ -H "Authorization: Bearer test-token-12345"
+
+# List all prompts
+curl "http://localhost:8080/prompts"
+
+# Get prompt variables
+curl "http://localhost:8080/prompts/hello-world-prompt/variables"
+```
+
+## Using with LiteLLM
+
+### Configuration
+
+Create a `config.yaml` file:
+
+```yaml
+model_list:
+ - model_name: gpt-3.5-turbo
+ litellm_params:
+ model: openai/gpt-3.5-turbo
+ api_key: os.environ/OPENAI_API_KEY
+
+prompts:
+ - prompt_id: "hello-world-prompt"
+ litellm_params:
+ prompt_integration: "generic_prompt_management"
+ api_base: http://localhost:8080
+ api_key: test-token-12345
+```
+
+### Start LiteLLM Proxy
+
+```bash
+litellm --config config.yaml
+```
+
+### Make a Request
+
+```bash
+curl http://0.0.0.0:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-3.5-turbo",
+ "prompt_id": "hello-world-prompt",
+ "prompt_variables": {
+ "domain": "data science",
+ "task": "analyzing customer behavior"
+ },
+ "messages": [
+ {"role": "user", "content": "Please help me get started"}
+ ]
+ }'
+```
+
+## Available Prompts
+
+The server includes several example prompts:
+
+| Prompt ID | Description | Variables |
+|-----------|-------------|-----------|
+| `hello-world-prompt` | Basic helpful assistant | `domain`, `task` |
+| `code-review-prompt` | Code review assistant | `years_experience`, `language`, `code` |
+| `customer-support-prompt` | Customer support agent | `company_name`, `customer_message` |
+| `data-analysis-prompt` | Data analysis expert | `analysis_type`, `dataset_name`, `data` |
+| `creative-writing-prompt` | Creative writing assistant | `genre`, `length`, `topic` |
+
+## Authentication
+
+The server supports optional Bearer token authentication. Valid tokens for testing:
+
+- `test-token-12345`
+- `dev-token-67890`
+- `prod-token-abcdef`
+
+If no `Authorization` header is provided, requests are allowed (for testing purposes).
+
+## API Endpoints
+
+### LiteLLM Spec Endpoints
+
+#### `GET /beta/litellm_prompt_management`
+
+Get a prompt by ID (required by LiteLLM).
+
+**Query Parameters:**
+- `prompt_id` (required): The prompt ID
+- `project_name` (optional): Project filter
+- `slug` (optional): Slug filter
+- `version` (optional): Version filter
+
+**Response:**
+```json
+{
+ "prompt_id": "hello-world-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant specialized in {domain}."
+ },
+ {
+ "role": "user",
+ "content": "Help me with: {task}"
+ }
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.7,
+ "max_tokens": 500
+ }
+}
+```
+
+### Convenience Endpoints (Not in LiteLLM Spec)
+
+#### `GET /health`
+
+Health check endpoint.
+
+#### `GET /prompts`
+
+List all available prompts.
+
+#### `GET /prompts/{prompt_id}/variables`
+
+Get all variables used in a prompt template.
+
+#### `POST /prompts`
+
+Create a new prompt (in-memory only, for testing).
+
+## Example: Full Integration Test
+
+### 1. Start the Mock Server
+
+```bash
+python mock_prompt_management_server.py
+```
+
+### 2. Test with Python
+
+```python
+from litellm import completion
+
+# The completion will:
+# 1. Fetch the prompt from your API
+# 2. Replace {domain} with "machine learning"
+# 3. Replace {task} with "building a recommendation system"
+# 4. Merge with your messages
+# 5. Use the model and params from the prompt
+
+response = completion(
+ model="gpt-4",
+ prompt_id="hello-world-prompt",
+ prompt_variables={
+ "domain": "machine learning",
+ "task": "building a recommendation system"
+ },
+ messages=[
+ {"role": "user", "content": "I have user behavior data from the past year."}
+ ],
+ # Configure the generic prompt manager
+ generic_prompt_config={
+ "api_base": "http://localhost:8080",
+ "api_key": "test-token-12345",
+ }
+)
+
+print(response.choices[0].message.content)
+```
+
+## Customization
+
+### Adding New Prompts
+
+Edit the `PROMPTS_DB` dictionary in `mock_prompt_management_server.py`:
+
+```python
+PROMPTS_DB = {
+ "my-custom-prompt": {
+ "prompt_id": "my-custom-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a {role}."
+ },
+ {
+ "role": "user",
+ "content": "{user_input}"
+ }
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.8,
+ "max_tokens": 1000
+ }
+ }
+}
+```
+
+### Using a Database
+
+Replace the `PROMPTS_DB` dictionary with database queries:
+
+```python
+@app.get("/beta/litellm_prompt_management")
+async def get_prompt(prompt_id: str):
+ # Fetch from database
+ prompt = await db.prompts.find_one({"prompt_id": prompt_id})
+
+ if not prompt:
+ raise HTTPException(status_code=404, detail="Prompt not found")
+
+ return PromptResponse(**prompt)
+```
+
+### Adding Access Control
+
+Use the custom query parameters for access control:
+
+```python
+@app.get("/beta/litellm_prompt_management")
+async def get_prompt(
+ prompt_id: str,
+ project_name: Optional[str] = None,
+ user_id: Optional[str] = None,
+ authorization: Optional[str] = Header(None)
+):
+ token = verify_api_key(authorization)
+
+ # Check if user has access to this project
+ if not has_project_access(token, project_name):
+ raise HTTPException(status_code=403, detail="Access denied")
+
+ # Fetch and return prompt
+ ...
+```
+
+## Production Considerations
+
+Before deploying to production:
+
+1. **Use a real database** instead of in-memory storage
+2. **Implement proper authentication** with JWT tokens or API keys
+3. **Add rate limiting** to prevent abuse
+4. **Use HTTPS** for encrypted communication
+5. **Add logging and monitoring** for observability
+6. **Implement caching** for frequently accessed prompts
+7. **Add versioning** for prompt management
+8. **Implement access control** based on teams/users
+9. **Add input validation** for all parameters
+10. **Use environment variables** for configuration
+
+## Related Documentation
+
+- [Generic Prompt Management API Documentation](https://docs.litellm.ai/docs/adding_provider/generic_prompt_management_api)
+- [LiteLLM Prompt Management](https://docs.litellm.ai/docs/proxy/prompt_management)
+- [Generic Guardrail API](https://docs.litellm.ai/docs/adding_provider/generic_guardrail_api)
+
+## Questions?
+
+This is a reference implementation for the LiteLLM Generic Prompt Management API. For questions or issues, please open an issue on the [LiteLLM GitHub repository](https://github.com/BerriAI/litellm).
+
diff --git a/cookbook/mock_prompt_management_server/mock_prompt_management_server.py b/cookbook/mock_prompt_management_server/mock_prompt_management_server.py
new file mode 100644
index 00000000000..295a96e12a9
--- /dev/null
+++ b/cookbook/mock_prompt_management_server/mock_prompt_management_server.py
@@ -0,0 +1,390 @@
+#!/usr/bin/env python3
+"""
+Mock Prompt Management API Server
+
+This is a FastAPI server that implements the LiteLLM Generic Prompt Management API
+for testing and demonstration purposes.
+
+Usage:
+ python mock_prompt_management_server.py
+
+The server will start on http://localhost:8080
+
+Test the endpoint:
+ curl "http://localhost:8080/beta/litellm_prompt_management?prompt_id=hello-world-prompt"
+"""
+
+import os
+import json
+from typing import Any, Dict, List, Optional
+
+from fastapi import FastAPI, HTTPException, Header, Query, status
+from fastapi.responses import JSONResponse
+from pydantic import BaseModel, Field
+
+# ============================================================================
+# Response Models
+# ============================================================================
+
+
+class MessageContent(BaseModel):
+ """A single message in the prompt template"""
+
+ role: str = Field(..., description="Message role (system, user, assistant)")
+ content: str = Field(
+ ..., description="Message content with optional {variable} placeholders"
+ )
+
+
+class PromptResponse(BaseModel):
+ """Response format for the prompt management API"""
+
+ prompt_id: str = Field(..., description="The ID of the prompt")
+ prompt_template: List[MessageContent] = Field(
+ ..., description="Array of messages in OpenAI format"
+ )
+ prompt_template_model: Optional[str] = Field(
+ None, description="Optional model to use for this prompt"
+ )
+ prompt_template_optional_params: Optional[Dict[str, Any]] = Field(
+ None, description="Optional parameters like temperature, max_tokens, etc."
+ )
+
+
+# ============================================================================
+# Mock Prompt Database
+# ============================================================================
+
+PROMPTS_DB = {
+ "hello-world-prompt": {
+ "prompt_id": "hello-world-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant specialized in {domain}.",
+ },
+ {"role": "user", "content": "Help me with: {task}"},
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {"temperature": 0.7, "max_tokens": 500},
+ },
+ "code-review-prompt": {
+ "prompt_id": "code-review-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are an expert code reviewer with {years_experience} years of experience in {language}.",
+ },
+ {
+ "role": "user",
+ "content": "Please review the following code for bugs, security issues, and best practices:\n\n{code}",
+ },
+ ],
+ "prompt_template_model": "gpt-4-turbo",
+ "prompt_template_optional_params": {
+ "temperature": 0.3,
+ "max_tokens": 1500,
+ },
+ },
+ "customer-support-prompt": {
+ "prompt_id": "customer-support-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a friendly customer support agent for {company_name}. Always be professional, empathetic, and solution-oriented.",
+ },
+ {
+ "role": "user",
+ "content": "Customer inquiry: {customer_message}",
+ },
+ ],
+ "prompt_template_model": "gpt-3.5-turbo",
+ "prompt_template_optional_params": {
+ "temperature": 0.8,
+ "max_tokens": 800,
+ "top_p": 0.9,
+ },
+ },
+ "data-analysis-prompt": {
+ "prompt_id": "data-analysis-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a data scientist expert in {analysis_type} analysis.",
+ },
+ {
+ "role": "user",
+ "content": "Analyze the following data and provide insights:\n\nDataset: {dataset_name}\nData: {data}",
+ },
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.5,
+ "max_tokens": 2000,
+ },
+ },
+ "creative-writing-prompt": {
+ "prompt_id": "creative-writing-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a creative writer specializing in {genre} fiction.",
+ },
+ {
+ "role": "user",
+ "content": "Write a {length} story about: {topic}",
+ },
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.9,
+ "max_tokens": 3000,
+ "top_p": 0.95,
+ },
+ },
+}
+
+# Valid API tokens for authentication (in production, use a secure token store)
+VALID_API_TOKENS = {
+ "test-token-12345",
+ "dev-token-67890",
+ "prod-token-abcdef",
+}
+
+# ============================================================================
+# FastAPI App
+# ============================================================================
+
+app = FastAPI(
+ title="Mock Prompt Management API",
+ description="A mock server implementing the LiteLLM Generic Prompt Management API",
+ version="1.0.0",
+)
+
+
+def verify_api_key(authorization: Optional[str] = Header(None)) -> bool:
+ """
+ Verify the API key from the Authorization header.
+
+ Args:
+ authorization: Authorization header (Bearer token)
+
+ Returns:
+ True if valid, raises HTTPException if invalid
+ """
+ if authorization is None:
+ # Allow requests without authentication for testing
+ return True
+
+ # Extract token from "Bearer "
+ if not authorization.startswith("Bearer "):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid authorization header format. Expected 'Bearer '",
+ )
+
+ token = authorization.replace("Bearer ", "").strip()
+
+ if token not in VALID_API_TOKENS:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid API key",
+ )
+
+ return True
+
+
+@app.get("/beta/litellm_prompt_management", response_model=PromptResponse)
+async def get_prompt(
+ prompt_id: str = Query(..., description="The ID of the prompt to fetch"),
+ project_name: Optional[str] = Query(
+ None, description="Optional project name filter"
+ ),
+ slug: Optional[str] = Query(None, description="Optional slug filter"),
+ version: Optional[str] = Query(None, description="Optional version filter"),
+ authorization: Optional[str] = Header(None),
+) -> PromptResponse:
+ """
+ Get a prompt by ID with optional filtering.
+
+ This endpoint implements the LiteLLM Generic Prompt Management API specification.
+
+ Args:
+ prompt_id: The ID of the prompt to fetch
+ project_name: Optional project name for filtering
+ slug: Optional slug for filtering
+ version: Optional version for filtering
+ authorization: Optional Bearer token for authentication
+
+ Returns:
+ PromptResponse with the prompt template and configuration
+
+ Raises:
+ HTTPException: 401 if authentication fails, 404 if prompt not found
+ """
+ # Verify authentication
+ verify_api_key(authorization)
+
+ # Log the request parameters (useful for debugging)
+ print(f"Fetching prompt: {prompt_id}")
+ if project_name:
+ print(f" Project: {project_name}")
+ if slug:
+ print(f" Slug: {slug}")
+ if version:
+ print(f" Version: {version}")
+
+ # Check if prompt exists
+ if prompt_id not in PROMPTS_DB:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Prompt '{prompt_id}' not found. Available prompts: {list(PROMPTS_DB.keys())}",
+ )
+
+ # Get the prompt from the database
+ prompt_data = PROMPTS_DB[prompt_id]
+
+ # Optional: Apply filtering based on project_name, slug, or version
+ # In a real implementation, you might use these to filter prompts by access control
+ # or to fetch specific versions from your database
+
+ return PromptResponse(**prompt_data)
+
+
+@app.get("/health")
+async def health_check():
+ """Health check endpoint"""
+ return {
+ "status": "healthy",
+ "service": "mock-prompt-management-api",
+ "version": "1.0.0",
+ }
+
+
+@app.get("/prompts")
+async def list_prompts(authorization: Optional[str] = Header(None)):
+ """
+ List all available prompts.
+
+ This is a convenience endpoint (not part of the LiteLLM spec) for
+ discovering available prompts.
+ """
+ # Verify authentication
+ verify_api_key(authorization)
+
+ prompts_list = [
+ {
+ "prompt_id": pid,
+ "model": p.get("prompt_template_model"),
+ "has_variables": any(
+ "{" in msg.get("content", "") for msg in p.get("prompt_template", [])
+ ),
+ }
+ for pid, p in PROMPTS_DB.items()
+ ]
+
+ return {"prompts": prompts_list, "total": len(prompts_list)}
+
+
+@app.get("/prompts/{prompt_id}/variables")
+async def get_prompt_variables(
+ prompt_id: str, authorization: Optional[str] = Header(None)
+):
+ """
+ Get all variables in a prompt template.
+
+ This is a convenience endpoint (not part of the LiteLLM spec) for
+ discovering what variables a prompt expects.
+ """
+ # Verify authentication
+ verify_api_key(authorization)
+
+ if prompt_id not in PROMPTS_DB:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Prompt '{prompt_id}' not found",
+ )
+
+ prompt_data = PROMPTS_DB[prompt_id]
+ variables = set()
+
+ # Extract variables from the prompt template
+ import re
+
+ for message in prompt_data["prompt_template"]:
+ content = message.get("content", "")
+ # Find all {variable} patterns
+ found_vars = re.findall(r"\{(\w+)\}", content)
+ variables.update(found_vars)
+
+ return {
+ "prompt_id": prompt_id,
+ "variables": sorted(list(variables)),
+ "example_usage": {
+ "prompt_id": prompt_id,
+ "prompt_variables": {var: f"<{var}_value>" for var in variables},
+ },
+ }
+
+
+@app.post("/prompts")
+async def create_prompt(
+ prompt: PromptResponse, authorization: Optional[str] = Header(None)
+):
+ """
+ Create a new prompt (convenience endpoint for testing).
+
+ This is NOT part of the LiteLLM spec - it's just for testing purposes.
+ """
+ # Verify authentication
+ verify_api_key(authorization)
+
+ if prompt.prompt_id in PROMPTS_DB:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=f"Prompt '{prompt.prompt_id}' already exists",
+ )
+
+ PROMPTS_DB[prompt.prompt_id] = prompt.dict()
+
+ return {
+ "status": "created",
+ "prompt_id": prompt.prompt_id,
+ "message": "Prompt created successfully (in-memory only)",
+ }
+
+
+# ============================================================================
+# Main
+# ============================================================================
+
+if __name__ == "__main__":
+ import uvicorn
+
+ print("=" * 70)
+ print("Mock Prompt Management API Server")
+ print("=" * 70)
+ print(f"\nStarting server on http://localhost:8080")
+ print(f"\nAvailable prompts: {len(PROMPTS_DB)}")
+ for prompt_id in PROMPTS_DB.keys():
+ print(f" - {prompt_id}")
+ print(f"\nValid API tokens: {len(VALID_API_TOKENS)}")
+ print(" - test-token-12345")
+ print(" - dev-token-67890")
+ print(" - prod-token-abcdef")
+ print("\nEndpoints:")
+ print(" GET /beta/litellm_prompt_management?prompt_id= (LiteLLM spec)")
+ print(" GET /health (health check)")
+ print(" GET /prompts (list all prompts)")
+ print(
+ " GET /prompts/{id}/variables (get prompt variables)"
+ )
+ print(" POST /prompts (create prompt)")
+ print("\nExample usage:")
+ print(
+ ' curl "http://localhost:8080/beta/litellm_prompt_management?prompt_id=hello-world-prompt"'
+ )
+ print("\nPress CTRL+C to stop the server")
+ print("=" * 70)
+
+ uvicorn.run(app, host="0.0.0.0", port=8080, log_level="info")
diff --git a/cookbook/nova_sonic_realtime.py b/cookbook/nova_sonic_realtime.py
new file mode 100644
index 00000000000..c7a73c1d00f
--- /dev/null
+++ b/cookbook/nova_sonic_realtime.py
@@ -0,0 +1,288 @@
+"""
+Client script to test Nova Sonic realtime API through LiteLLM proxy.
+
+This script connects to LiteLLM proxy's realtime endpoint and enables
+speech-to-speech conversation with Bedrock Nova Sonic.
+
+Prerequisites:
+- LiteLLM proxy running with Bedrock configured
+- pyaudio installed: pip install pyaudio
+- websockets installed: pip install websockets
+
+Usage:
+ python nova_sonic_realtime.py
+"""
+
+import asyncio
+import base64
+import json
+import os
+import pyaudio
+import websockets
+from typing import Optional
+
+# Bounded queue size for audio chunks (configurable via env to avoid unbounded memory)
+AUDIO_QUEUE_MAXSIZE = int(os.getenv("LITELLM_ASYNCIO_QUEUE_MAXSIZE", 10_000))
+
+# Audio configuration (matching Nova Sonic requirements)
+INPUT_SAMPLE_RATE = 16000 # Nova Sonic expects 16kHz input
+OUTPUT_SAMPLE_RATE = 24000 # Nova Sonic outputs 24kHz
+CHANNELS = 1
+FORMAT = pyaudio.paInt16
+CHUNK_SIZE = 1024
+
+# LiteLLM proxy configuration
+LITELLM_PROXY_URL = "ws://localhost:4000/v1/realtime?model=bedrock-sonic"
+LITELLM_API_KEY = "sk-12345" # Your LiteLLM API key
+
+
+class RealtimeClient:
+ """Client for LiteLLM realtime API with audio support."""
+
+ def __init__(self, url: str, api_key: str):
+ self.url = url
+ self.api_key = api_key
+ self.ws: Optional[websockets.WebSocketClientProtocol] = None
+ self.is_active = False
+ self.audio_queue = asyncio.Queue(maxsize=AUDIO_QUEUE_MAXSIZE)
+ self.pyaudio = pyaudio.PyAudio()
+ self.input_stream = None
+ self.output_stream = None
+
+ async def connect(self):
+ """Connect to LiteLLM proxy realtime endpoint."""
+ print(f"Connecting to {self.url}...")
+
+ headers = {}
+ if self.api_key:
+ headers["Authorization"] = f"Bearer {self.api_key}"
+
+ self.ws = await websockets.connect(
+ self.url,
+ additional_headers=headers,
+ max_size=10 * 1024 * 1024, # 10MB max message size
+ )
+ self.is_active = True
+ print("✓ Connected to LiteLLM proxy")
+
+ async def send_session_update(self):
+ """Send session configuration."""
+ session_update = {
+ "type": "session.update",
+ "session": {
+ "instructions": "You are a friendly assistant. Keep your responses short and conversational.",
+ "voice": "matthew",
+ "temperature": 0.8,
+ "max_response_output_tokens": 1024,
+ "modalities": ["text", "audio"],
+ "input_audio_format": "pcm16",
+ "output_audio_format": "pcm16",
+ "turn_detection": {
+ "type": "server_vad",
+ "threshold": 0.5,
+ "prefix_padding_ms": 300,
+ "silence_duration_ms": 500,
+ },
+ },
+ }
+ await self.ws.send(json.dumps(session_update))
+ print("✓ Session configuration sent")
+
+ async def receive_messages(self):
+ """Receive and process messages from the server."""
+ try:
+ async for message in self.ws:
+ if not self.is_active:
+ break
+
+ try:
+ data = json.loads(message)
+ event_type = data.get("type")
+
+ if event_type == "session.created":
+ print(f"✓ Session created: {data.get('session', {}).get('id')}")
+
+ elif event_type == "response.created":
+ print("🤖 Assistant is responding...")
+
+ elif event_type == "response.text.delta":
+ # Print text transcription
+ delta = data.get("delta", "")
+ print(delta, end="", flush=True)
+
+ elif event_type == "response.audio.delta":
+ # Queue audio for playback
+ audio_b64 = data.get("delta", "")
+ if audio_b64:
+ audio_bytes = base64.b64decode(audio_b64)
+ await self.audio_queue.put(audio_bytes)
+
+ elif event_type == "response.text.done":
+ print() # New line after text
+
+ elif event_type == "response.done":
+ print("✓ Response complete")
+
+ elif event_type == "error":
+ print(f"❌ Error: {data.get('error', {})}")
+
+ else:
+ # Debug: print other event types
+ print(f"[{event_type}]", end=" ")
+
+ except json.JSONDecodeError:
+ print(f"Failed to parse message: {message[:100]}")
+
+ except websockets.exceptions.ConnectionClosed:
+ print("\n✗ Connection closed")
+ except Exception as e:
+ print(f"\n✗ Error receiving messages: {e}")
+ finally:
+ self.is_active = False
+
+ async def send_audio_chunk(self, audio_bytes: bytes):
+ """Send audio chunk to server."""
+ if not self.is_active or not self.ws:
+ return
+
+ audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
+ message = {
+ "type": "input_audio_buffer.append",
+ "audio": audio_b64,
+ }
+ await self.ws.send(json.dumps(message))
+
+ async def commit_audio_buffer(self):
+ """Commit the audio buffer to trigger processing."""
+ if not self.is_active or not self.ws:
+ return
+
+ message = {"type": "input_audio_buffer.commit"}
+ await self.ws.send(json.dumps(message))
+
+ async def capture_audio(self):
+ """Capture audio from microphone and send to server."""
+ print("\n🎤 Starting audio capture...")
+ print("Speak into your microphone. Press Ctrl+C to stop.\n")
+
+ self.input_stream = self.pyaudio.open(
+ format=FORMAT,
+ channels=CHANNELS,
+ rate=INPUT_SAMPLE_RATE,
+ input=True,
+ frames_per_buffer=CHUNK_SIZE,
+ )
+
+ try:
+ while self.is_active:
+ audio_data = self.input_stream.read(CHUNK_SIZE, exception_on_overflow=False)
+ await self.send_audio_chunk(audio_data)
+ await asyncio.sleep(0.01) # Small delay to prevent overwhelming
+ except Exception as e:
+ print(f"Error capturing audio: {e}")
+ finally:
+ if self.input_stream:
+ self.input_stream.stop_stream()
+ self.input_stream.close()
+
+ async def play_audio(self):
+ """Play audio responses from the server."""
+ print("🔊 Starting audio playback...")
+
+ self.output_stream = self.pyaudio.open(
+ format=FORMAT,
+ channels=CHANNELS,
+ rate=OUTPUT_SAMPLE_RATE,
+ output=True,
+ frames_per_buffer=CHUNK_SIZE,
+ )
+
+ try:
+ while self.is_active:
+ try:
+ audio_data = await asyncio.wait_for(
+ self.audio_queue.get(), timeout=0.1
+ )
+ if audio_data:
+ self.output_stream.write(audio_data)
+ except asyncio.TimeoutError:
+ continue
+ except Exception as e:
+ print(f"Error playing audio: {e}")
+ finally:
+ if self.output_stream:
+ self.output_stream.stop_stream()
+ self.output_stream.close()
+
+ async def close(self):
+ """Close the connection and cleanup."""
+ self.is_active = False
+
+ if self.ws:
+ await self.ws.close()
+
+ if self.input_stream:
+ self.input_stream.stop_stream()
+ self.input_stream.close()
+
+ if self.output_stream:
+ self.output_stream.stop_stream()
+ self.output_stream.close()
+
+ self.pyaudio.terminate()
+ print("\n✓ Connection closed")
+
+
+async def main():
+ """Main function to run the realtime client."""
+ print("=" * 80)
+ print("Bedrock Nova Sonic Realtime Client")
+ print("=" * 80)
+ print()
+
+ client = RealtimeClient(LITELLM_PROXY_URL, LITELLM_API_KEY)
+
+ try:
+ # Connect to server
+ await client.connect()
+
+ # Send session configuration
+ await client.send_session_update()
+
+ # Wait a moment for session to be established
+ await asyncio.sleep(0.5)
+
+ # Start tasks
+ receive_task = asyncio.create_task(client.receive_messages())
+ capture_task = asyncio.create_task(client.capture_audio())
+ playback_task = asyncio.create_task(client.play_audio())
+
+ # Wait for user to interrupt
+ await asyncio.gather(
+ receive_task,
+ capture_task,
+ playback_task,
+ return_exceptions=True,
+ )
+
+ except KeyboardInterrupt:
+ print("\n\n⚠ Interrupted by user")
+ except Exception as e:
+ print(f"\n❌ Error: {e}")
+ import traceback
+ traceback.print_exc()
+ finally:
+ await client.close()
+
+
+if __name__ == "__main__":
+ print("\nMake sure:")
+ print("1. LiteLLM proxy is running on port 4000")
+ print("2. Bedrock is configured in proxy_server_config.yaml")
+ print("3. AWS credentials are set")
+ print()
+
+ try:
+ asyncio.run(main())
+ except KeyboardInterrupt:
+ print("\n\nGoodbye!")
diff --git a/deploy/charts/litellm-helm/Chart.yaml b/deploy/charts/litellm-helm/Chart.yaml
index 8a08f0b4e29..0f6db331e50 100644
--- a/deploy/charts/litellm-helm/Chart.yaml
+++ b/deploy/charts/litellm-helm/Chart.yaml
@@ -26,6 +26,10 @@ version: 1.1.0
# It is recommended to use it with quotes.
appVersion: v1.80.12
+annotations:
+ org.opencontainers.image.source: "https://github.com/BerriAI/litellm"
+ org.opencontainers.image.url: "https://docs.litellm.ai/"
+
dependencies:
- name: "postgresql"
version: ">=13.3.0"
diff --git a/deploy/charts/litellm-helm/templates/deployment.yaml b/deploy/charts/litellm-helm/templates/deployment.yaml
index c3e0055e380..4ac5582d060 100644
--- a/deploy/charts/litellm-helm/templates/deployment.yaml
+++ b/deploy/charts/litellm-helm/templates/deployment.yaml
@@ -38,6 +38,10 @@ spec:
serviceAccountName: {{ include "litellm.serviceAccountName" . }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
+ {{- with .Values.extraInitContainers }}
+ initContainers:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
containers:
- name: {{ include "litellm.name" . }}
securityContext:
diff --git a/deploy/charts/litellm-helm/templates/migrations-job.yaml b/deploy/charts/litellm-helm/templates/migrations-job.yaml
index f8893a47afe..3459fa12d1c 100644
--- a/deploy/charts/litellm-helm/templates/migrations-job.yaml
+++ b/deploy/charts/litellm-helm/templates/migrations-job.yaml
@@ -35,6 +35,10 @@ spec:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "litellm.serviceAccountName" . }}
+ {{- with .Values.migrationJob.extraInitContainers }}
+ initContainers:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
containers:
- name: prisma-migrations
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default (printf "main-%s" .Chart.AppVersion) }}"
diff --git a/deploy/charts/litellm-helm/values.yaml b/deploy/charts/litellm-helm/values.yaml
index 54271756998..cea25974bb0 100644
--- a/deploy/charts/litellm-helm/values.yaml
+++ b/deploy/charts/litellm-helm/values.yaml
@@ -234,6 +234,14 @@ db:
# instance. See the "postgresql" top level key for additional configuration.
deployStandalone: true
+# Lifecycle hooks for the LiteLLM container
+# Example:
+# lifecycle:
+# preStop:
+# exec:
+# command: ["/bin/sh", "-c", "sleep 10"]
+lifecycle: {}
+
# Settings for Bitnami postgresql chart (if db.deployStandalone is true, ignored
# otherwise)
postgresql:
@@ -273,6 +281,7 @@ migrationJob:
# cpu: 100m
# memory: 100Mi
extraContainers: []
+ extraInitContainers: []
# Hook configuration
hooks:
diff --git a/docker/Dockerfile.custom_ui b/docker/Dockerfile.custom_ui
index c437929a27e..177d7b7b12a 100644
--- a/docker/Dockerfile.custom_ui
+++ b/docker/Dockerfile.custom_ui
@@ -5,7 +5,19 @@ FROM ghcr.io/berriai/litellm:litellm_fwd_server_root_path-dev
WORKDIR /app
# Install Node.js and npm (adjust version as needed)
-RUN apt-get update && apt-get install -y nodejs npm
+RUN apt-get update && apt-get install -y nodejs npm && \
+ npm install -g npm@latest tar@7.5.7 glob@11.1.0 @isaacs/brace-expansion@5.0.1 && \
+ GLOBAL="$(npm root -g)" && \
+ find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \
+ done && \
+ find "$GLOBAL/npm" -type d -name "glob" -path "*/node_modules/glob" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \
+ done && \
+ find "$GLOBAL/npm" -type d -name "brace-expansion" -path "*/node_modules/@isaacs/brace-expansion" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \
+ done && \
+ npm cache clean --force
# Copy the UI source into the container
COPY ./ui/litellm-dashboard /app/ui/litellm-dashboard
diff --git a/docker/Dockerfile.database b/docker/Dockerfile.database
index 49655129506..a6fcd98ab6d 100644
--- a/docker/Dockerfile.database
+++ b/docker/Dockerfile.database
@@ -49,7 +49,19 @@ FROM $LITELLM_RUNTIME_IMAGE AS runtime
USER root
# Install runtime dependencies
-RUN apk add --no-cache bash openssl tzdata nodejs npm python3 py3-pip libsndfile
+RUN apk add --no-cache bash openssl tzdata nodejs npm python3 py3-pip libsndfile && \
+ npm install -g npm@latest tar@7.5.7 glob@11.1.0 @isaacs/brace-expansion@5.0.1 && \
+ GLOBAL="$(npm root -g)" && \
+ find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \
+ done && \
+ find "$GLOBAL/npm" -type d -name "glob" -path "*/node_modules/glob" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \
+ done && \
+ find "$GLOBAL/npm" -type d -name "brace-expansion" -path "*/node_modules/@isaacs/brace-expansion" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \
+ done && \
+ npm cache clean --force
WORKDIR /app
# Copy the current directory contents into the container at /app
@@ -63,6 +75,20 @@ COPY --from=builder /wheels/ /wheels/
# Install the built wheel using pip; again using a wildcard if it's the only file
RUN pip install *.whl /wheels/* --no-index --find-links=/wheels/ && rm -f *.whl && rm -rf /wheels
+# SECURITY FIX: nodejs-wheel-binaries (pip package used by Prisma) bundles a complete
+# npm with old vulnerable deps at /usr/lib/python3.*/site-packages/nodejs_wheel/.
+# Patch every copy of tar, glob, and brace-expansion inside that tree.
+RUN GLOBAL="$(npm root -g)" && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/tar" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \
+ done && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/glob" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \
+ done && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/@isaacs/brace-expansion" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \
+ done
+
# Install semantic_router and aurelio-sdk using script
# Convert Windows line endings to Unix and make executable
RUN sed -i 's/\r$//' docker/install_auto_router.sh && chmod +x docker/install_auto_router.sh && ./docker/install_auto_router.sh
diff --git a/docker/Dockerfile.dev b/docker/Dockerfile.dev
index 67966f9c739..bc1d22d5e05 100644
--- a/docker/Dockerfile.dev
+++ b/docker/Dockerfile.dev
@@ -61,7 +61,19 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libatomic1 \
nodejs \
npm \
- && rm -rf /var/lib/apt/lists/*
+ && rm -rf /var/lib/apt/lists/* \
+ && npm install -g npm@latest tar@7.5.7 glob@11.1.0 @isaacs/brace-expansion@5.0.1 \
+ && GLOBAL="$(npm root -g)" \
+ && find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \
+ done \
+ && find "$GLOBAL/npm" -type d -name "glob" -path "*/node_modules/glob" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \
+ done \
+ && find "$GLOBAL/npm" -type d -name "brace-expansion" -path "*/node_modules/@isaacs/brace-expansion" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \
+ done \
+ && npm cache clean --force
WORKDIR /app
@@ -79,6 +91,20 @@ RUN pip install --no-cache-dir *.whl /wheels/* --no-index --find-links=/wheels/
rm -f *.whl && \
rm -rf /wheels
+# SECURITY FIX: nodejs-wheel-binaries (pip package used by Prisma) bundles a complete
+# npm with old vulnerable deps at /usr/lib/python3.*/site-packages/nodejs_wheel/.
+# Patch every copy of tar, glob, and brace-expansion inside that tree.
+RUN GLOBAL="$(npm root -g)" && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/tar" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \
+ done && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/glob" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \
+ done && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/@isaacs/brace-expansion" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \
+ done
+
# Generate prisma client and set permissions
# Convert Windows line endings to Unix for entrypoint scripts
RUN prisma generate && \
diff --git a/docker/Dockerfile.non_root b/docker/Dockerfile.non_root
index 8c795f3b17f..004377e19b3 100644
--- a/docker/Dockerfile.non_root
+++ b/docker/Dockerfile.non_root
@@ -47,7 +47,6 @@ RUN mkdir -p /var/lib/litellm/ui && \
if [ -f "/app/enterprise/enterprise_ui/enterprise_colors.json" ]; then \
cp /app/enterprise/enterprise_ui/enterprise_colors.json ./ui_colors.json; \
fi && \
- rm -f package-lock.json && \
npm install --legacy-peer-deps && \
npm run build && \
cp -r /app/ui/litellm-dashboard/out/* /var/lib/litellm/ui/ && \
@@ -60,7 +59,8 @@ RUN mkdir -p /var/lib/litellm/ui && \
mkdir -p "$folder_name" && \
mv "$html_file" "$folder_name/index.html"; \
fi; \
- done ) && \
+ done && \
+ touch .litellm_ui_ready ) && \
cd /app/ui/litellm-dashboard && rm -rf ./out
# Build litellm wheel and place it in wheels dir (replace any PyPI wheels)
@@ -104,7 +104,19 @@ RUN for i in 1 2 3; do \
done \
&& for i in 1 2 3; do \
apk add --no-cache python3 py3-pip bash openssl tzdata nodejs npm supervisor && break || sleep 5; \
- done
+ done \
+ && npm install -g npm@latest tar@7.5.7 glob@11.1.0 @isaacs/brace-expansion@5.0.1 \
+ && GLOBAL="$(npm root -g)" \
+ && find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \
+ done \
+ && find "$GLOBAL/npm" -type d -name "glob" -path "*/node_modules/glob" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \
+ done \
+ && find "$GLOBAL/npm" -type d -name "brace-expansion" -path "*/node_modules/@isaacs/brace-expansion" | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \
+ done \
+ && npm cache clean --force
# Copy artifacts from builder
COPY --from=builder /app/requirements.txt /app/requirements.txt
@@ -146,6 +158,20 @@ RUN pip install --no-index --find-links=/wheels/ -r requirements.txt && \
fi; \
fi
+# SECURITY FIX: nodejs-wheel-binaries (pip package used by Prisma) bundles a complete
+# npm with old vulnerable deps at /usr/lib/python3.*/site-packages/nodejs_wheel/.
+# Patch every copy of tar, glob, and brace-expansion inside that tree.
+RUN GLOBAL="$(npm root -g)" && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/tar" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \
+ done && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/glob" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \
+ done && \
+ find /usr/lib -path "*/nodejs_wheel/*/node_modules/@isaacs/brace-expansion" -type d | while read d; do \
+ rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \
+ done
+
# Permissions, cleanup, and Prisma prep
# Convert Windows line endings to Unix for entrypoint scripts
RUN sed -i 's/\r$//' docker/entrypoint.sh && \
@@ -170,12 +196,14 @@ RUN sed -i 's/\r$//' docker/entrypoint.sh && \
[ -n "$LITELLM_PROXY_EXTRAS_PATH" ] && chmod -R g+w $LITELLM_PROXY_EXTRAS_PATH || true && \
chmod -R g+rX $PRISMA_PATH && \
chmod -R g+rX /app/.cache && \
- mkdir -p /tmp/.npm /nonexistent /.npm && \
- prisma generate
+ mkdir -p /tmp/.npm /nonexistent /.npm
# Switch to non-root user for runtime
USER nobody
+# Generate Prisma client as nobody user to ensure correct file ownership
+RUN prisma generate
+
# Prisma runtime knobs for offline containers
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=1 \
PRISMA_HIDE_UPDATE_MESSAGE=1 \
diff --git a/docker/README.md b/docker/README.md
index 6d81276bb4b..7027a30fdd7 100644
--- a/docker/README.md
+++ b/docker/README.md
@@ -70,9 +70,12 @@ docker compose -f docker-compose.yml -f docker-compose.hardened.yml up -d
This setup:
- Builds from `docker/Dockerfile.non_root` with Prisma engines and Node toolchain baked into the image.
-- Runs the proxy as a non-root user with a read-only rootfs and only two writable tmpfs mounts:
+- Runs the proxy as a non-root user with a read-only rootfs and only writable tmpfs mounts:
- `/app/cache` (Prisma/NPM cache; backing `PRISMA_BINARY_CACHE_DIR`, `NPM_CONFIG_CACHE`, `XDG_CACHE_HOME`)
- `/app/migrations` (Prisma migration workspace; backing `LITELLM_MIGRATION_DIR`)
+- Pre-builds and serves the admin UI from read-only paths:
+ - `/var/lib/litellm/ui` (pre-restructured Next.js UI with `.litellm_ui_ready` marker)
+ - `/var/lib/litellm/assets` (UI logos and assets)
- Routes all outbound traffic through a local Squid proxy that denies egress, so Prisma migrations must use the cached CLI and engines.
You should also verify offline Prisma behaviour with:
diff --git a/docs/my-website/blog/anthropic_opus_4_5_and_advanced_features/index.md b/docs/my-website/blog/anthropic_opus_4_5_and_advanced_features/index.md
index 7015918e924..8a54426dfb0 100644
--- a/docs/my-website/blog/anthropic_opus_4_5_and_advanced_features/index.md
+++ b/docs/my-website/blog/anthropic_opus_4_5_and_advanced_features/index.md
@@ -15,6 +15,7 @@ authors:
title: "CTO, LiteLLM"
url: https://www.linkedin.com/in/reffajnaahsi/
image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+description: "Guide to Claude Opus 4.5 and advanced features in LiteLLM: Tool Search, Programmatic Tool Calling, and Effort Parameter."
tags: [anthropic, claude, tool search, programmatic tool calling, effort, advanced features]
hide_table_of_contents: false
---
diff --git a/docs/my-website/blog/claude_code_beta_headers/index.md b/docs/my-website/blog/claude_code_beta_headers/index.md
new file mode 100644
index 00000000000..44567f616aa
--- /dev/null
+++ b/docs/my-website/blog/claude_code_beta_headers/index.md
@@ -0,0 +1,177 @@
+---
+slug: claude-code-beta-headers-incident
+title: "Incident Report: Invalid beta headers with Claude Code"
+date: 2026-02-16T10:00:00
+authors:
+ - name: Sameer Kankute
+ title: SWE @ LiteLLM (LLM Translation)
+ url: https://www.linkedin.com/in/sameer-kankute/
+ image_url: https://pbs.twimg.com/profile_images/2001352686994907136/ONgNuSk5_400x400.jpg
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+tags: [incident-report, anthropic, stability]
+hide_table_of_contents: false
+---
+
+**Date:** February 13, 2026
+**Duration:** ~3 hours
+**Severity:** High
+**Status:** Resolved
+
+> **Note:** This fix will be available starting from `v1.81.13-nightly` or higher of LiteLLM.
+
+## Summary
+
+Claude Code began sending unsupported Anthropic beta headers to non-Anthropic providers (Bedrock, Azure AI, Vertex AI), causing `invalid beta flag` errors. LiteLLM was forwarding all beta headers without provider-specific validation. Users experienced request failures when routing Claude Code requests through LiteLLM to these providers.
+
+- **LLM calls to Anthropic:** No impact.
+- **LLM calls to Bedrock/Azure/Vertex:** Failed with `invalid beta flag` errors when unsupported headers were present.
+- **Cost tracking and routing:** No impact.
+
+{/* truncate */}
+
+---
+
+## Background
+
+Anthropic uses beta headers to enable experimental features in Claude. When Claude Code makes API requests, it includes headers like `anthropic-beta: prompt-caching-scope-2026-01-05,advanced-tool-use-2025-11-20`. However, not all providers support all Anthropic beta features.
+
+Before this incident, LiteLLM forwarded all beta headers to all providers without validation:
+
+```mermaid
+sequenceDiagram
+ participant CC as Claude Code
+ participant LP as LiteLLM (old behavior)
+ participant Provider as Provider (Bedrock/Azure/Vertex)
+
+ CC->>LP: Request with beta headers
+ Note over CC,LP: anthropic-beta: header1,header2,header3
+
+ LP->>Provider: Forward ALL headers (no validation)
+ Note over LP,Provider: anthropic-beta: header1,header2,header3
+
+ Provider-->>LP: ❌ Error: invalid beta flag
+ LP-->>CC: Request fails
+```
+
+Requests succeeded for Anthropic (native support) but failed for other providers when Claude Code sent headers those providers didn't support.
+
+---
+
+## Root cause
+
+LiteLLM lacked provider-specific beta header validation. When Claude Code introduced new beta features or sent headers that specific providers didn't support, those headers were blindly forwarded, causing provider API errors.
+
+---
+
+## Remediation
+
+| # | Action | Status | Code |
+|---|---|---|---|
+| 1 | Create `anthropic_beta_headers_config.json` with provider-specific mappings | ✅ Done | [`anthropic_beta_headers_config.json`](https://github.com/BerriAI/litellm/blob/main/litellm/anthropic_beta_headers_config.json) |
+| 2 | Implement strict validation: headers must be explicitly mapped to be forwarded | ✅ Done | [`litellm_logging.py`](https://github.com/BerriAI/litellm/blob/main/litellm/litellm_core_utils/litellm_logging.py) |
+| 3 | Add `/reload/anthropic_beta_headers` endpoint for dynamic config updates | ✅ Done | Proxy management endpoints |
+| 4 | Add `/schedule/anthropic_beta_headers_reload` for automatic periodic updates | ✅ Done | Proxy management endpoints |
+| 5 | Support `LITELLM_ANTHROPIC_BETA_HEADERS_URL` for custom config sources | ✅ Done | Environment configuration |
+| 6 | Support `LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS` for air-gapped deployments | ✅ Done | Environment configuration |
+
+Now LiteLLM validates and transforms headers per-provider:
+
+```mermaid
+sequenceDiagram
+ participant CC as Claude Code
+ participant LP as LiteLLM (new behavior)
+ participant Config as Beta Headers Config
+ participant Provider as Provider (Bedrock/Azure/Vertex)
+
+ CC->>LP: Request with beta headers
+ Note over CC,LP: anthropic-beta: header1,header2,header3
+
+ LP->>Config: Load header mapping for provider
+ Config-->>LP: Returns mapping (header→value or null)
+
+ Note over LP: Validate & Transform: 1. Check if header exists in mapping 2. Filter out null values 3. Map to provider-specific names
+
+ LP->>Provider: Request with filtered & mapped headers
+ Note over LP,Provider: anthropic-beta: mapped-header2 (header1, header3 filtered out)
+
+ Provider-->>LP: ✅ Success response
+ LP-->>CC: Response
+```
+
+---
+
+## Dynamic configuration updates
+
+A key improvement is zero-downtime configuration updates. When Anthropic releases new beta features, users can update their configuration without restarting:
+
+```bash
+# Manually trigger reload (no restart needed)
+curl -X POST "https://your-proxy-url/reload/anthropic_beta_headers" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+
+# Or schedule automatic reloads every 24 hours
+curl -X POST "https://your-proxy-url/schedule/anthropic_beta_headers_reload?hours=24" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+```
+
+This prevents future incidents where Claude Code introduces new headers before LiteLLM configuration is updated.
+
+---
+
+## Configuration format
+
+The `anthropic_beta_headers_config.json` file maps input headers to provider-specific output headers:
+
+```json
+{
+ "description": "Mapping of Anthropic beta headers for each provider.",
+ "anthropic": {
+ "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
+ "computer-use-2025-01-24": "computer-use-2025-01-24"
+ },
+ "bedrock_converse": {
+ "advanced-tool-use-2025-11-20": null,
+ "computer-use-2025-01-24": "computer-use-2025-01-24"
+ },
+ "azure_ai": {
+ "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
+ "computer-use-2025-01-24": "computer-use-2025-01-24"
+ }
+}
+```
+
+**Validation rules:**
+1. Headers must exist in the mapping for the target provider
+2. Headers with `null` values are filtered out (unsupported)
+3. Header names can be transformed per-provider (e.g., Bedrock uses different names for some features)
+
+---
+
+## Resolution steps for users
+
+For users still experiencing issues, update to the latest LiteLLM version if < v1.81.11-nightly:
+
+```bash
+pip install --upgrade litellm
+```
+
+Or manually reload the configuration without restarting:
+
+```bash
+curl -X POST "https://your-proxy-url/reload/anthropic_beta_headers" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+```
+
+---
+
+## Related documentation
+
+- [Managing Anthropic Beta Headers](../proxy/sync_anthropic_beta_headers.md) - Complete configuration guide
+- [`anthropic_beta_headers_config.json`](https://github.com/BerriAI/litellm/blob/main/litellm/anthropic_beta_headers_config.json) - Current configuration file
diff --git a/docs/my-website/blog/claude_opus_4_6/index.md b/docs/my-website/blog/claude_opus_4_6/index.md
new file mode 100644
index 00000000000..e44420bd570
--- /dev/null
+++ b/docs/my-website/blog/claude_opus_4_6/index.md
@@ -0,0 +1,730 @@
+---
+slug: claude_opus_4_6
+title: "Day 0 Support: Claude Opus 4.6"
+date: 2026-02-05T10:00:00
+authors:
+ - name: Sameer Kankute
+ title: SWE @ LiteLLM (LLM Translation)
+ url: https://www.linkedin.com/in/sameer-kankute/
+ image_url: https://pbs.twimg.com/profile_images/2001352686994907136/ONgNuSk5_400x400.jpg
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+description: "Day 0 support for Claude Opus 4.6 on LiteLLM AI Gateway - use across Anthropic, Azure, Vertex AI, and Bedrock."
+tags: [anthropic, claude, opus 4.6]
+hide_table_of_contents: false
+---
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+LiteLLM now supports Claude Opus 4.6 on Day 0. Use it across Anthropic, Azure, Vertex AI, and Bedrock through the LiteLLM AI Gateway.
+
+## Docker Image
+
+```bash
+docker pull ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6
+```
+
+## Usage - Anthropic
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-opus-4-6
+ litellm_params:
+ model: anthropic/claude-opus-4-6
+ api_key: os.environ/ANTHROPIC_API_KEY
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+## Usage - Azure
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-opus-4-6
+ litellm_params:
+ model: azure_ai/claude-opus-4-6
+ api_key: os.environ/AZURE_AI_API_KEY
+ api_base: os.environ/AZURE_AI_API_BASE # https://.services.ai.azure.com
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e AZURE_AI_API_KEY=$AZURE_AI_API_KEY \
+ -e AZURE_AI_API_BASE=$AZURE_AI_API_BASE \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+## Usage - Vertex AI
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-opus-4-6
+ litellm_params:
+ model: vertex_ai/claude-opus-4-6
+ vertex_project: os.environ/VERTEX_PROJECT
+ vertex_location: us-east5
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e VERTEX_PROJECT=$VERTEX_PROJECT \
+ -e GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ -v $(pwd)/credentials.json:/app/credentials.json \
+ ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+## Usage - Bedrock
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-opus-4-6
+ litellm_params:
+ model: bedrock/anthropic.claude-opus-4-6-v1
+ aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
+ aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
+ aws_region_name: us-east-1
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
+ -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+## Advanced Features
+
+### Compaction
+
+
+
+
+Litellm supports enabling compaction for the new claude-opus-4-6.
+
+**Enabling Compaction**
+
+To enable compaction, add the `context_management` parameter with the `compact_20260112` edit type:
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "What is the weather in San Francisco?"
+ }
+ ],
+ "context_management": {
+ "edits": [
+ {
+ "type": "compact_20260112"
+ }
+ ]
+ },
+ "max_tokens": 100
+}'
+```
+All the parameters supported for context_management by anthropic are supported and can be directly added. Litellm automatically adds the `compact-2026-01-12` beta header in the request.
+
+
+
+
+Enable compaction to reduce context size while preserving key information. LiteLLM automatically adds the `compact-2026-01-12` beta header when compaction is enabled.
+
+:::info
+**Provider Support:** Compaction is supported on Anthropic, Azure AI, and Vertex AI. It is **not supported** on Bedrock (Invoke or Converse APIs).
+:::
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'x-api-key: sk-12345' \
+--header 'content-type: application/json' \
+--data '{
+ "model": "claude-opus-4-6",
+ "max_tokens": 4096,
+ "messages": [
+ {
+ "role": "user",
+ "content": "Hi"
+ }
+ ],
+ "context_management": {
+ "edits": [
+ {
+ "type": "compact_20260112"
+ }
+ ]
+ }
+}'
+```
+
+
+
+
+
+**Response with Compaction Block**
+
+The response will include the compaction summary in `provider_specific_fields.compaction_blocks`:
+
+```json
+{
+ "id": "chatcmpl-a6c105a3-4b25-419e-9551-c800633b6cb2",
+ "created": 1770357619,
+ "model": "claude-opus-4-6",
+ "object": "chat.completion",
+ "choices": [
+ {
+ "finish_reason": "length",
+ "index": 0,
+ "message": {
+ "content": "I don't have access to real-time data, so I can't provide the current weather in San Francisco. To get up-to-date weather information, I'd recommend checking:\n\n- **Weather websites** like weather.com, accuweather.com, or wunderground.com\n- **Search engines** – just Google \"San Francisco weather\"\n- **Weather apps** on your phone (e.g., Apple Weather, Google Weather)\n- **National",
+ "role": "assistant",
+ "provider_specific_fields": {
+ "compaction_blocks": [
+ {
+ "type": "compaction",
+ "content": "Summary of the conversation: The user requested help building a web scraper..."
+ }
+ ]
+ }
+ }
+ }
+ ],
+ "usage": {
+ "completion_tokens": 100,
+ "prompt_tokens": 86,
+ "total_tokens": 186
+ }
+}
+```
+
+**Using Compaction Blocks in Follow-up Requests**
+
+To continue the conversation with compaction, include the compaction block in the assistant message's `provider_specific_fields`:
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "How can I build a web scraper?"
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "Certainly! To build a basic web scraper, you'll typically use a programming language like Python along with libraries such as `requests` (for fetching web pages) and `BeautifulSoup` (for parsing HTML). Here's a basic example:\n\n```python\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://example.com'\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'html.parser')\n\n# Extract and print all text\ntext = soup.get_text()\nprint(text)\n```\n\nLet me know what you're interested in scraping or if you need help with a specific website!"
+ }
+ ],
+ "provider_specific_fields": {
+ "compaction_blocks": [
+ {
+ "type": "compaction",
+ "content": "Summary of the conversation: The user asked how to build a web scraper, and the assistant gave an overview using Python with requests and BeautifulSoup."
+ }
+ ]
+ }
+ },
+ {
+ "role": "user",
+ "content": "How do I use it to scrape product prices?"
+ }
+ ],
+ "context_management": {
+ "edits": [
+ {
+ "type": "compact_20260112"
+ }
+ ]
+ },
+ "max_tokens": 100
+}'
+```
+
+**Streaming Support**
+
+Compaction blocks are also supported in streaming mode. You'll receive:
+- `compaction_start` event when a compaction block begins
+- `compaction_delta` events with the compaction content
+- The accumulated `compaction_blocks` in `provider_specific_fields`
+
+### Adaptive Thinking
+
+:::note
+When using `reasoning_effort` with Claude Opus 4.6, all values (`low`, `medium`, `high`) are mapped to `thinking: {type: "adaptive"}`. To use explicit thinking budgets with `type: "enabled"`, pass the native `thinking` parameter directly (see "Native thinking param" tab below).
+:::
+
+
+
+
+LiteLLM supports adaptive thinking through the `reasoning_effort` parameter:
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "Solve this complex problem: What is the optimal strategy for..."
+ }
+ ],
+ "reasoning_effort": "high"
+}'
+```
+
+
+
+
+Use the `thinking` parameter with `type: "adaptive"` to enable adaptive thinking mode:
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'x-api-key: sk-12345' \
+--header 'content-type: application/json' \
+--data '{
+ "model": "claude-opus-4-6",
+ "max_tokens": 16000,
+ "thinking": {
+ "type": "adaptive"
+ },
+ "messages": [
+ {
+ "role": "user",
+ "content": "Explain why the sum of two even numbers is always even."
+ }
+ ]
+}'
+```
+
+
+
+
+Use the `thinking` parameter directly for adaptive thinking via the SDK:
+
+```python
+import litellm
+
+response = litellm.completion(
+ model="anthropic/claude-opus-4-6",
+ messages=[{"role": "user", "content": "Solve this complex problem: What is the optimal strategy for..."}],
+ thinking={"type": "adaptive"},
+)
+```
+
+
+
+
+### Effort Levels
+
+
+
+
+Four effort levels available: `low`, `medium`, `high` (default), and `max`. Pass directly via the `output_config` parameter:
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "Explain quantum computing"
+ }
+ ],
+ "output_config": {
+ "effort": "medium"
+ }
+}'
+```
+
+You can use reasoning effort plus output_config to have more control on the model.
+
+
+
+
+Four effort levels available: `low`, `medium`, `high` (default), and `max`. Pass directly via the `output_config` parameter:
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'x-api-key: sk-12345' \
+--header 'content-type: application/json' \
+--data '{
+ "model": "claude-opus-4-6",
+ "max_tokens": 4096,
+ "messages": [
+ {
+ "role": "user",
+ "content": "Explain quantum computing"
+ }
+ ],
+ "output_config": {
+ "effort": "medium"
+ }
+}'
+```
+
+
+
+
+### 1M Token Context (Beta)
+
+Opus 4.6 supports 1M token context. Premium pricing applies for prompts exceeding 200k tokens ($10/$37.50 per million input/output tokens). LiteLLM supports cost calculations for 1M token contexts.
+
+
+
+
+To use the 1M token context window, you need to forward the `anthropic-beta` header from your client to the LLM provider.
+
+**Step 1: Enable header forwarding in your config**
+
+```yaml
+general_settings:
+ forward_client_headers_to_llm_api: true
+```
+
+**Step 2: Send requests with the beta header**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--header 'anthropic-beta: context-1m-2025-08-07' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "Analyze this large document..."
+ }
+ ]
+}'
+```
+
+
+
+
+To use the 1M token context window, you need to forward the `anthropic-beta` header from your client to the LLM provider.
+
+**Step 1: Enable header forwarding in your config**
+
+```yaml
+general_settings:
+ forward_client_headers_to_llm_api: true
+```
+
+**Step 2: Send requests with the beta header**
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'x-api-key: sk-12345' \
+--header 'anthropic-beta: context-1m-2025-08-07' \
+--header 'content-type: application/json' \
+--data '{
+ "model": "claude-opus-4-6",
+ "max_tokens": 16000,
+ "messages": [
+ {
+ "role": "user",
+ "content": "Analyze this large document..."
+ }
+ ]
+}'
+```
+
+:::tip
+You can combine multiple beta headers by separating them with commas:
+```bash
+--header 'anthropic-beta: context-1m-2025-08-07,compact-2026-01-12'
+```
+:::
+
+
+
+
+### US-Only Inference
+
+Available at 1.1× token pricing. LiteLLM automatically tracks costs for US-only inference.
+
+
+
+
+Use the `inference_geo` parameter to specify US-only inference:
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "What is the capital of France?"
+ }
+ ],
+ "inference_geo": "us"
+}'
+```
+
+LiteLLM will automatically apply the 1.1× pricing multiplier for US-only inference in cost tracking.
+
+
+
+
+Use the `inference_geo` parameter to specify US-only inference:
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'x-api-key: sk-12345' \
+--header 'content-type: application/json' \
+--data '{
+ "model": "claude-opus-4-6",
+ "max_tokens": 4096,
+ "messages": [
+ {
+ "role": "user",
+ "content": "What is the capital of France?"
+ }
+ ],
+ "inference_geo": "us"
+}'
+```
+
+LiteLLM will automatically apply the 1.1× pricing multiplier for US-only inference in cost tracking.
+
+
+
+
+### Fast Mode
+
+:::info
+Fast mode is **only supported on the Anthropic provider** (`anthropic/claude-opus-4-6`). It is not available on Azure AI, Vertex AI, or Bedrock.
+:::
+
+**Pricing:**
+- Standard: $5 input / $25 output per MTok
+- Fast: $30 input / $150 output per MTok (6× premium)
+
+
+
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-opus-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "Refactor this module..."
+ }
+ ],
+ "max_tokens": 4096,
+ "speed": "fast"
+}'
+```
+
+**Using OpenAI SDK:**
+
+```python
+import openai
+
+client = openai.OpenAI(
+ api_key="your-litellm-key",
+ base_url="http://0.0.0.0:4000"
+)
+
+response = client.chat.completions.create(
+ model="claude-opus-4-6",
+ messages=[{"role": "user", "content": "Refactor this module..."}],
+ max_tokens=4096,
+ extra_body={"speed": "fast"}
+)
+```
+
+**Using LiteLLM SDK:**
+
+```python
+from litellm import completion
+
+response = completion(
+ model="anthropic/claude-opus-4-6",
+ messages=[{"role": "user", "content": "Refactor this module..."}],
+ max_tokens=4096,
+ speed="fast"
+)
+```
+
+LiteLLM automatically tracks the higher costs for fast mode in usage and cost calculations.
+
+
+
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'x-api-key: sk-12345' \
+--header 'content-type: application/json' \
+--data '{
+ "model": "claude-opus-4-6",
+ "max_tokens": 4096,
+ "speed": "fast",
+ "messages": [
+ {
+ "role": "user",
+ "content": "Refactor this module..."
+ }
+ ]
+}'
+```
+
+LiteLLM automatically:
+- Adds the `fast-mode-2026-02-01` beta header
+- Tracks the 6× premium pricing in cost calculations
+
+
+
diff --git a/docs/my-website/blog/claude_sonnet_4_6/index.md b/docs/my-website/blog/claude_sonnet_4_6/index.md
new file mode 100644
index 00000000000..df54fa09792
--- /dev/null
+++ b/docs/my-website/blog/claude_sonnet_4_6/index.md
@@ -0,0 +1,283 @@
+---
+slug: claude_sonnet_4_6
+title: "Day 0 Support: Claude Sonnet 4.6"
+date: 2026-02-17T10:00:00
+authors:
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+description: "Day 0 support for Claude Sonnet 4.6 on LiteLLM AI Gateway - use across Anthropic, Azure, Vertex AI, and Bedrock."
+tags: [anthropic, claude, sonnet 4.6]
+hide_table_of_contents: false
+---
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+LiteLLM now supports Claude Sonnet 4.6 on Day 0. Use it across Anthropic, Azure, Vertex AI, and Bedrock through the LiteLLM AI Gateway.
+
+## Docker Image
+
+```bash
+docker pull ghcr.io/berriai/litellm:v1.81.3-stable.sonnet-4-6
+```
+
+## Usage - Anthropic
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-sonnet-4-6
+ litellm_params:
+ model: anthropic/claude-sonnet-4-6
+ api_key: os.environ/ANTHROPIC_API_KEY
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:v1.81.3-stable.sonnet-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-sonnet-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+
+```python
+from litellm import completion
+
+response = completion(
+ model="anthropic/claude-sonnet-4-6",
+ messages=[{"role": "user", "content": "what llm are you"}]
+)
+print(response.choices[0].message.content)
+```
+
+
+
+
+## Usage - Azure
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-sonnet-4-6
+ litellm_params:
+ model: azure_ai/claude-sonnet-4-6
+ api_key: os.environ/AZURE_AI_API_KEY
+ api_base: os.environ/AZURE_AI_API_BASE # https://.services.ai.azure.com
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e AZURE_AI_API_KEY=$AZURE_AI_API_KEY \
+ -e AZURE_AI_API_BASE=$AZURE_AI_API_BASE \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:v1.81.3-stable.sonnet-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-sonnet-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+
+```python
+from litellm import completion
+
+response = completion(
+ model="azure_ai/claude-sonnet-4-6",
+ api_key="your-azure-api-key",
+ api_base="https://.services.ai.azure.com",
+ messages=[{"role": "user", "content": "what llm are you"}]
+)
+print(response.choices[0].message.content)
+```
+
+
+
+
+## Usage - Vertex AI
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-sonnet-4-6
+ litellm_params:
+ model: vertex_ai/claude-sonnet-4-6
+ vertex_project: os.environ/VERTEX_PROJECT
+ vertex_location: us-east5
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e VERTEX_PROJECT=$VERTEX_PROJECT \
+ -e GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ -v $(pwd)/credentials.json:/app/credentials.json \
+ ghcr.io/berriai/litellm:v1.81.3-stable.sonnet-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-sonnet-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+
+```python
+from litellm import completion
+
+response = completion(
+ model="vertex_ai/claude-sonnet-4-6",
+ vertex_project="your-project-id",
+ vertex_location="us-east5",
+ messages=[{"role": "user", "content": "what llm are you"}]
+)
+print(response.choices[0].message.content)
+```
+
+
+
+
+## Usage - Bedrock
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: claude-sonnet-4-6
+ litellm_params:
+ model: bedrock/anthropic.claude-sonnet-4-6-v1
+ aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
+ aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
+ aws_region_name: us-east-1
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
+ -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:v1.81.3-stable.sonnet-4-6 \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "claude-sonnet-4-6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+
+```python
+from litellm import completion
+
+response = completion(
+ model="bedrock/anthropic.claude-sonnet-4-6-v1",
+ aws_access_key_id="your-access-key",
+ aws_secret_access_key="your-secret-key",
+ aws_region_name="us-east-1",
+ messages=[{"role": "user", "content": "what llm are you"}]
+)
+print(response.choices[0].message.content)
+```
+
+
+
diff --git a/docs/my-website/blog/fastapi_middleware_performance/index.mdx b/docs/my-website/blog/fastapi_middleware_performance/index.mdx
new file mode 100644
index 00000000000..b0c5ba13634
--- /dev/null
+++ b/docs/my-website/blog/fastapi_middleware_performance/index.mdx
@@ -0,0 +1,220 @@
+---
+slug: fastapi-middleware-performance
+title: "Your Middleware Could Be a Bottleneck"
+date: 2026-02-07T10:00:00
+authors:
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+ - name: Ryan Crabbe
+ title: "Performance Engineer, LiteLLM"
+ url: https://www.linkedin.com/in/ryan-crabbe-0b9687214
+ image_url: https://media.licdn.com/dms/image/v2/D5603AQHt1t9Z4BJ6Gw/profile-displayphoto-shrink_400_400/profile-displayphoto-shrink_400_400/0/1724453682340?e=1772064000&v=beta&t=VXdmr13rsNB05wyA2F1TENOB5UuDHUZ0FCHTolNyR5M
+description: "How we improved LiteLLM proxy latency and throughput by replacing a single middleware base class"
+tags: [performance, fastapi, middleware]
+hide_table_of_contents: false
+---
+
+import { BaseHTTPMiddlewareAnimation, PureASGIAnimation, BenchmarkVisualization } from '@site/src/components/MiddlewareDiagrams';
+
+> How we improved LiteLLM proxy latency and throughput by replacing a single, simple middleware base class
+
+---
+
+## Our Setup
+
+The LiteLLM proxy server has two middleware layers. The first is Starlette's `CORSMiddleware` (re-exported by FastAPI), which is a pure ASGI middleware. Then we have a simple BaseHTTPMiddleware called PrometheusAuthMiddleware.
+
+The job of `PrometheusAuthMiddleware` is to authenticate requests to the `/metrics` endpoint. It's not on by default, you enable it with a flag in your proxy config:
+
+
+Proxy config flag
+
+```yaml
+litellm_settings:
+ require_auth_for_metrics_endpoint: true
+```
+
+
+
+The middleware checks two things: is the request hitting `/metrics`, and is auth even enabled? If both checks fail, which they do for the vast majority of requests, it just passes the request through unchanged.
+
+
+PrometheusAuthMiddleware source
+
+```python
+class PrometheusAuthMiddleware(BaseHTTPMiddleware):
+ async def dispatch(self, request: Request, call_next):
+ if self._is_prometheus_metrics_endpoint(request):
+ if self._should_run_auth_on_metrics_endpoint() is True:
+ try:
+ await user_api_key_auth(request=request, api_key=...)
+ except Exception as e:
+ return JSONResponse(status_code=401, content=...)
+ response = await call_next(request)
+ return response
+
+ @staticmethod
+ def _is_prometheus_metrics_endpoint(request: Request):
+ if "/metrics" in request.url.path:
+ return True
+ return False
+```
+
+
+
+Looks harmless. Subclass `BaseHTTPMiddleware`, implement `dispatch()`, done. This is what you will see in Starlette's documentation[1](#footnote-1).
+
+{/* truncate */}
+
+---
+
+## What BaseHTTPMiddleware Actually Does
+
+When you write a `dispatch()` method, you'd expect the request to flow straight through your function and out the other side. What actually happens is much more involved.
+
+On every request, even a pure passthrough (meaning nothing happens), `BaseHTTPMiddleware` creates **7 intermediate objects and tasks**:
+
+
+
+It wraps the request in a new object to track body state, creates a synchronization event, allocates an in-memory channel to pass messages between your middleware and the inner app, sets up a task group to manage the lifecycle, and then runs your actual route handler in a *separate background task* when you call `call_next()`. The response body then flows back through that in-memory channel, gets re-wrapped in a streaming response object, and finally reaches the caller. That's a lot.
+
+For a middleware that for us, does nothing on 99.9% of requests, paying this cost doesn't make sense.
+
+Compare that to a pure ASGI middleware, which we can have just check the request path and continue along.
+
+
+
+Our middleware is doing something really simple. For the vast majority of requests it doesn't need to do anything at all but just let the request pass through. It doesn't need task groups, memory streams, or cancel scopes. It needs a function call.
+
+---
+
+## Comparing Both
+
+We replaced the `BaseHTTPMiddleware` subclass with a pure ASGI middleware. To benchmark the difference, we used Apache Bench[2](#footnote-2) to compare both configurations of LiteLLM's middleware stack: the old setup (1 pure ASGI + 1 `BaseHTTPMiddleware`) against the new setup (2 pure ASGI).
+
+A minimal FastAPI app serves `GET /health` → `PlainTextResponse("ok")`. The endpoint does zero work to isolate the middleware overhead: any difference between configs is purely the cost of the middleware plumbing itself. Both middlewares are just calling the next layer. Same work, different base class.
+
+Apache Bench (`ab`) fires requests at the server with 1,000 concurrent connections and a single uvicorn worker. One worker means one event loop, so the benchmark directly measures how each middleware design handles concurrent load on a single thread.
+
+
+
+
+Try it yourself
+
+Save the script below as `benchmark_middleware.py`, then run:
+
+```bash
+# Terminal 1 — start the "before" server (1 ASGI + 1 BaseHTTPMiddleware)
+python benchmark_middleware.py --middleware mixed
+
+# Terminal 2 — benchmark it
+ab -n 50000 -c 1000 http://localhost:8000/health
+
+# Stop the server, then start the "after" server (2x pure ASGI)
+python benchmark_middleware.py --middleware asgi
+
+# Terminal 2 — benchmark again
+ab -n 50000 -c 1000 http://localhost:8000/health
+```
+
+```python
+import argparse
+import uvicorn
+from fastapi import FastAPI
+from fastapi.responses import PlainTextResponse
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.requests import Request
+from starlette.types import ASGIApp, Receive, Scope, Send
+
+
+class NoOpBaseHTTPMiddleware(BaseHTTPMiddleware):
+ async def dispatch(self, request: Request, call_next):
+ return await call_next(request)
+
+
+class NoOpPureASGIMiddleware:
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ await self.app(scope, receive, send)
+
+
+def create_app(middleware_type: str | None = None, layers: int = 2) -> FastAPI:
+ app = FastAPI()
+
+ @app.get("/health")
+ async def health():
+ return PlainTextResponse("ok")
+
+ if middleware_type == "mixed":
+ app.add_middleware(NoOpBaseHTTPMiddleware)
+ app.add_middleware(NoOpPureASGIMiddleware)
+ elif middleware_type == "asgi":
+ for _ in range(layers):
+ app.add_middleware(NoOpPureASGIMiddleware)
+
+ return app
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--middleware", choices=["asgi", "mixed"], default=None)
+ parser.add_argument("--layers", type=int, default=2)
+ parser.add_argument("--port", type=int, default=8000)
+ args = parser.parse_args()
+
+ app = create_app(middleware_type=args.middleware, layers=args.layers)
+ uvicorn.run(app, host="0.0.0.0", port=args.port, workers=1, log_level="warning")
+```
+
+
+
+---
+
+## Our Change
+
+Here's what we replaced it with:
+
+```python
+class PrometheusAuthMiddleware:
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http" or "/metrics" not in scope.get("path", ""):
+ await self.app(scope, receive, send)
+ return
+
+ if litellm.require_auth_for_metrics_endpoint is True:
+ request = Request(scope, receive)
+ api_key = request.headers.get("Authorization") or ""
+ try:
+ await user_api_key_auth(request=request, api_key=api_key)
+ except Exception as e:
+ # send 401 directly via ASGI protocol
+ ...
+ return
+
+ await self.app(scope, receive, send)
+```
+
+For the 99.9% of requests that aren't hitting `/metrics`, the middleware is now one dict lookup, one string check, and one function call. No objects allocated, no tasks spawned.
+
+It's important to evaluate if the tools you're using are the right fit for the job as your software grows and handles more responsiblity. We're now putting in a static analysis check to prevent this from happening again with any newly introduced middlewares. If we find the use case is necessary then that's okay and we'll reevalute but for everything LiteLLM needs to do at the moment it's not.
+
+This middleware change was one part of a broader optimization effort on the LiteLLM proxy. Across all optimizations combined, we've measured about a **30% reduction in proxy overhead** over the past two weeks.
+
+---
+
+
+1 [Starlette Middleware — BaseHTTPMiddleware](https://starlette.dev/middleware/#basehttpmiddleware)
+
+
+2 [Apache HTTP server benchmarking tool (`ab`)](https://httpd.apache.org/docs/2.4/programs/ab.html)
diff --git a/docs/my-website/blog/gemini_3/index.md b/docs/my-website/blog/gemini_3/index.md
index 26dbc2d02b5..7263acc12c9 100644
--- a/docs/my-website/blog/gemini_3/index.md
+++ b/docs/my-website/blog/gemini_3/index.md
@@ -15,6 +15,7 @@ authors:
title: "CTO, LiteLLM"
url: https://www.linkedin.com/in/reffajnaahsi/
image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+description: "Common questions and best practices for using gemini-3-pro-preview with LiteLLM Proxy and SDK."
tags: [gemini, day 0 support, llms]
hide_table_of_contents: false
---
diff --git a/docs/my-website/blog/gemini_3_flash/index.md b/docs/my-website/blog/gemini_3_flash/index.md
index 6cb8ddad992..830c21e5f66 100644
--- a/docs/my-website/blog/gemini_3_flash/index.md
+++ b/docs/my-website/blog/gemini_3_flash/index.md
@@ -15,6 +15,7 @@ authors:
title: "CTO, LiteLLM"
url: https://www.linkedin.com/in/reffajnaahsi/
image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+description: "Guide to using Gemini 3 Flash on LiteLLM Proxy and SDK with day 0 support."
tags: [gemini, day 0 support, llms]
hide_table_of_contents: false
---
diff --git a/docs/my-website/blog/litellm_observatory/index.md b/docs/my-website/blog/litellm_observatory/index.md
new file mode 100644
index 00000000000..4554f77fb85
--- /dev/null
+++ b/docs/my-website/blog/litellm_observatory/index.md
@@ -0,0 +1,136 @@
+---
+slug: litellm-observatory
+title: "Improve release stability with 24 hour load tests"
+date: 2026-02-06T10:00:00
+authors:
+ - name: Alexsander Hamir
+ title: "Performance Engineer, LiteLLM"
+ url: https://www.linkedin.com/in/alexsander-baptista/
+ image_url: https://github.com/AlexsanderHamir.png
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+description: "How we built a long-running, release-validation system to catch regressions before they reach users."
+tags: [testing, observability, reliability, releases]
+hide_table_of_contents: false
+---
+
+
+
+# Improve release stability with 24 hour load tests
+
+As LiteLLM adoption has grown, so have expectations around reliability, performance, and operational safety. Meeting those expectations requires more than correctness-focused tests, it requires validating how the system behaves over time, under real-world conditions.
+
+This post introduces **LiteLLM Observatory**, a long-running release-validation system we built to catch regressions before they reach users.
+
+---
+
+## Why We Built the Observatory
+
+LiteLLM operates at the intersection of external providers, long-lived network connections, and high-throughput workloads. While our unit and integration tests do an excellent job validating correctness, they are not designed to surface issues that only appear after extended operation.
+
+A subtle lifecycle edge case discovered in v1.81.3 reinforced the need for stronger release validation in this area.
+
+---
+
+## A Real-World Lifecycle Edge Case
+
+In v1.81.3, we shipped a fix for an HTTP client memory leak. The change passed unit and integration tests and behaved correctly in short-lived runs.
+
+The issue that surfaced was not caused by a single incorrect line of logic, but by how multiple components interacted over time:
+
+- A cached `httpx` client was configured with a 1-hour TTL
+- When the cache expired, the underlying HTTP connection was closed as expected
+- A higher-level client continued to hold a reference to that connection
+- Subsequent requests failed with:
+
+```
+Cannot send a request, as the client has been closed
+```
+
+**Before (with bug):**
+
+| Provider | Requests | Success | Failures | Fail % |
+|----------|----------|---------|----------|--------|
+| OpenAI | 720,000 | 432,000 | 288,000 | 40% |
+| Azure | 692,000 | 415,200 | 276,800 | 40% |
+
+**After (fixed):**
+
+| Provider | Requests | Success | Failures | Fail % |
+|----------|------------|-----------|----------|---------|
+| OpenAI | 1,200,000 | 1,199,988 | 12 | 0.001% |
+| Azure | 1,150,000 | 1,149,982 | 18 | 0.002% |
+
+Our focus moving forward is on being the first to detect issues, even when they aren’t covered by unit tests. LiteLLM Observatory is designed to surface latency regressions, OOMs, and failure modes that only appear under real traffic patterns in **our own production deployments** during release validation.
+
+
+---
+
+### How the Observatory Works
+
+[LiteLLM Observatory](https://github.com/BerriAI/litellm-observatory) is a testing service that runs long-running tests against our LiteLLM deployments. We trigger tests by sending API requests, and results are automatically sent to Slack when tests complete.
+
+#### How Tests Run
+
+1. **Start a Test**: We send a request to the Observatory API with:
+ - Which LiteLLM deployment to test (URL and API key)
+ - Which test to run (e.g., `TestOAIAzureRelease`)
+ - Test settings (which models to test, how long to run, failure thresholds)
+
+2. **Smart Queueing**:
+ - The system checks whether we are attempting to run the exact same test more than once
+ - If a duplicate test is already running or queued, we receive an error to avoid wasting resources
+ - Otherwise, the test is added to a queue and runs when capacity is available (up to 5 tests can run concurrently by default)
+
+3. **Instant Response**: The API responds immediately—we do not wait for the test to finish. Tests may run for hours, but the request itself completes in milliseconds.
+
+4. **Background Execution**:
+ - The test runs in the background, issuing requests against our LiteLLM deployment
+ - It tracks request success and failure rates over time
+ - When the test completes, results are automatically posted to our Slack channel
+
+#### Example: The OpenAI / Azure Reliability Test
+
+The `TestOAIAzureRelease` test is designed to catch a class of bugs that only surface after sustained runtime:
+
+- **Duration**: Runs continuously for 3 hours
+- **Behavior**: Cycles through specified models (such as `gpt-4` and `gpt-3.5-turbo`), issuing requests continuously
+- **Why 3 Hours**: This helps catch issues where HTTP clients degrade or fail after extended use (for example, a bug observed in LiteLLM v1.81.3)
+- **Pass / Fail Criteria**: The test passes if fewer than 1% of requests fail. If the failure rate exceeds 1%, the test fails and we are notified in Slack
+- **Key Detail**: The same HTTP client is reused for the entire run, allowing us to detect lifecycle-related bugs that only appear under prolonged reuse
+
+#### When We Use It
+
+- **Before Deployments**: Run tests before promoting a new LiteLLM version to production
+- **Routine Validation**: Schedule regular runs (daily or weekly) to catch regressions early
+- **Issue Investigation**: Run tests on demand when we suspect a deployment issue
+- **Long-Running Failure Detection**: Identify bugs that only appear under sustained load, beyond what short smoke tests can reveal
+
+
+### Complementing Unit Tests
+
+Unit tests remain a foundational part of our development process. They are fast and precise, but they don’t cover:
+
+- Real provider behavior
+- Long-lived network interactions
+- Resource lifecycle edge cases
+- Time-dependent regressions
+
+LiteLLM Observatory complements unit tests by validating the system as it actually runs in production-like environments.
+
+---
+
+### Looking Ahead
+
+Reliability is an ongoing investment.
+
+LiteLLM Observatory is one of several systems we’re building to continuously raise the bar on release quality and operational safety. As LiteLLM evolves, so will our validation tooling, informed by real-world usage and lessons learned.
+
+We’ll continue to share those improvements openly as we go.
+
diff --git a/docs/my-website/blog/minimax_m2_5/index.md b/docs/my-website/blog/minimax_m2_5/index.md
new file mode 100644
index 00000000000..50084fcc1e5
--- /dev/null
+++ b/docs/my-website/blog/minimax_m2_5/index.md
@@ -0,0 +1,394 @@
+---
+slug: minimax_m2_5
+title: "Day 0 Support: MiniMax-M2.5"
+date: 2026-02-12T10:00:00
+authors:
+ - name: Sameer Kankute
+ title: SWE @ LiteLLM (LLM Translation)
+ url: https://www.linkedin.com/in/sameer-kankute/
+ image_url: https://pbs.twimg.com/profile_images/2001352686994907136/ONgNuSk5_400x400.jpg
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+description: "Day 0 support for MiniMax-M2.5 on LiteLLM"
+tags: [minimax, M2.5, llm]
+hide_table_of_contents: false
+---
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+LiteLLM now supports MiniMax-M2.5 on Day 0. Use it across OpenAI-compatible and Anthropic-compatible APIs through the LiteLLM AI Gateway.
+
+## Supported Models
+
+LiteLLM supports the following MiniMax models:
+
+| Model | Description | Input Cost | Output Cost | Context Window |
+|-------|-------------|------------|-------------|----------------|
+| **MiniMax-M2.5** | Advanced reasoning, Agentic capabilities | $0.3/M tokens | $1.2/M tokens | 1M tokens |
+| **MiniMax-M2.5-lightning** | Faster and More Agile (~100 tps) | $0.3/M tokens | $2.4/M tokens | 1M tokens |
+
+## Features Supported
+
+- **Prompt Caching**: Reduce costs with cached prompts ($0.03/M tokens for cache read, $0.375/M tokens for cache write)
+- **Function Calling**: Built-in tool calling support
+- **Reasoning**: Advanced reasoning capabilities with thinking support
+- **System Messages**: Full system message support
+- **Cost Tracking**: Automatic cost calculation for all requests
+
+## Docker Image
+
+```bash
+docker pull litellm/litellm:v1.81.3-stable
+```
+
+## Usage - OpenAI Compatible API (/v1/chat/completions)
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: minimax-m2-5
+ litellm_params:
+ model: minimax/MiniMax-M2.5
+ api_key: os.environ/MINIMAX_API_KEY
+ api_base: https://api.minimax.io/v1
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e MINIMAX_API_KEY=$MINIMAX_API_KEY \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:v1.81.3-stable \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "minimax-m2-5",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+### With Reasoning Split
+
+```bash
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "minimax-m2-5",
+ "messages": [
+ {
+ "role": "user",
+ "content": "Solve: 2+2=?"
+ }
+ ],
+ "extra_body": {
+ "reasoning_split": true
+ }
+}'
+```
+
+## Usage - Anthropic Compatible API (/v1/messages)
+
+
+
+
+**1. Setup config.yaml**
+
+```yaml
+model_list:
+ - model_name: minimax-m2-5
+ litellm_params:
+ model: minimax/MiniMax-M2.5
+ api_key: os.environ/MINIMAX_API_KEY
+ api_base: https://api.minimax.io/anthropic/v1/messages
+```
+
+**2. Start the proxy**
+
+```bash
+docker run -d \
+ -p 4000:4000 \
+ -e MINIMAX_API_KEY=$MINIMAX_API_KEY \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ ghcr.io/berriai/litellm:v1.81.3-stable \
+ --config /app/config.yaml
+```
+
+**3. Test it!**
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "minimax-m2-5",
+ "max_tokens": 1000,
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
+```
+
+
+
+
+### With Thinking
+
+```bash
+curl --location 'http://0.0.0.0:4000/v1/messages' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer $LITELLM_KEY' \
+--data '{
+ "model": "minimax-m2-5",
+ "max_tokens": 1000,
+ "thinking": {
+ "type": "enabled",
+ "budget_tokens": 1000
+ },
+ "messages": [
+ {
+ "role": "user",
+ "content": "Solve: 2+2=?"
+ }
+ ]
+}'
+```
+
+## Usage - LiteLLM SDK
+
+### OpenAI-compatible API
+
+```python
+import litellm
+
+response = litellm.completion(
+ model="minimax/MiniMax-M2.5",
+ messages=[
+ {"role": "user", "content": "Hello, how are you?"}
+ ],
+ api_key="your-minimax-api-key",
+ api_base="https://api.minimax.io/v1"
+)
+
+print(response.choices[0].message.content)
+```
+
+### Anthropic-compatible API
+
+```python
+import litellm
+
+response = litellm.anthropic.messages.acreate(
+ model="minimax/MiniMax-M2.5",
+ messages=[{"role": "user", "content": "Hello, how are you?"}],
+ api_key="your-minimax-api-key",
+ api_base="https://api.minimax.io/anthropic/v1/messages",
+ max_tokens=1000
+)
+
+print(response.choices[0].message.content)
+```
+
+### With Thinking
+
+```python
+response = litellm.anthropic.messages.acreate(
+ model="minimax/MiniMax-M2.5",
+ messages=[{"role": "user", "content": "Solve: 2+2=?"}],
+ thinking={"type": "enabled", "budget_tokens": 1000},
+ api_key="your-minimax-api-key"
+)
+
+# Access thinking content
+for block in response.choices[0].message.content:
+ if hasattr(block, 'type') and block.type == 'thinking':
+ print(f"Thinking: {block.thinking}")
+```
+
+### With Reasoning Split (OpenAI API)
+
+```python
+response = litellm.completion(
+ model="minimax/MiniMax-M2.5",
+ messages=[
+ {"role": "user", "content": "Solve: 2+2=?"}
+ ],
+ extra_body={"reasoning_split": True},
+ api_key="your-minimax-api-key",
+ api_base="https://api.minimax.io/v1"
+)
+
+# Access thinking and response
+if hasattr(response.choices[0].message, 'reasoning_details'):
+ print(f"Thinking: {response.choices[0].message.reasoning_details}")
+print(f"Response: {response.choices[0].message.content}")
+```
+
+## Cost Tracking
+
+LiteLLM automatically tracks costs for MiniMax-M2.5 requests. The pricing is:
+
+- **Input**: $0.3 per 1M tokens
+- **Output**: $1.2 per 1M tokens
+- **Cache Read**: $0.03 per 1M tokens
+- **Cache Write**: $0.375 per 1M tokens
+
+### Accessing Cost Information
+
+```python
+response = litellm.completion(
+ model="minimax/MiniMax-M2.5",
+ messages=[{"role": "user", "content": "Hello!"}],
+ api_key="your-minimax-api-key"
+)
+
+# Access cost information
+print(f"Cost: ${response._hidden_params.get('response_cost', 0)}")
+```
+
+## Streaming Support
+
+### OpenAI API
+
+```python
+response = litellm.completion(
+ model="minimax/MiniMax-M2.5",
+ messages=[{"role": "user", "content": "Tell me a story"}],
+ stream=True,
+ api_key="your-minimax-api-key",
+ api_base="https://api.minimax.io/v1"
+)
+
+for chunk in response:
+ if chunk.choices[0].delta.content:
+ print(chunk.choices[0].delta.content, end="")
+```
+
+### Streaming with Reasoning Split
+
+```python
+stream = litellm.completion(
+ model="minimax/MiniMax-M2.5",
+ messages=[
+ {"role": "user", "content": "Tell me a story"},
+ ],
+ extra_body={"reasoning_split": True},
+ stream=True,
+ api_key="your-minimax-api-key",
+ api_base="https://api.minimax.io/v1"
+)
+
+reasoning_buffer = ""
+text_buffer = ""
+
+for chunk in stream:
+ if hasattr(chunk.choices[0].delta, "reasoning_details") and chunk.choices[0].delta.reasoning_details:
+ for detail in chunk.choices[0].delta.reasoning_details:
+ if "text" in detail:
+ reasoning_text = detail["text"]
+ new_reasoning = reasoning_text[len(reasoning_buffer):]
+ if new_reasoning:
+ print(new_reasoning, end="", flush=True)
+ reasoning_buffer = reasoning_text
+
+ if chunk.choices[0].delta.content:
+ content_text = chunk.choices[0].delta.content
+ new_text = content_text[len(text_buffer):] if text_buffer else content_text
+ if new_text:
+ print(new_text, end="", flush=True)
+ text_buffer = content_text
+```
+
+## Using with Native SDKs
+
+### Anthropic SDK via LiteLLM Proxy
+
+```python
+import os
+os.environ["ANTHROPIC_BASE_URL"] = "http://localhost:4000"
+os.environ["ANTHROPIC_API_KEY"] = "sk-1234" # Your LiteLLM proxy key
+
+import anthropic
+
+client = anthropic.Anthropic()
+
+message = client.messages.create(
+ model="minimax-m2-5",
+ max_tokens=1000,
+ system="You are a helpful assistant.",
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "Hi, how are you?"
+ }
+ ]
+ }
+ ]
+)
+
+for block in message.content:
+ if block.type == "thinking":
+ print(f"Thinking:\n{block.thinking}\n")
+ elif block.type == "text":
+ print(f"Text:\n{block.text}\n")
+```
+
+### OpenAI SDK via LiteLLM Proxy
+
+```python
+import os
+os.environ["OPENAI_BASE_URL"] = "http://localhost:4000"
+os.environ["OPENAI_API_KEY"] = "sk-1234" # Your LiteLLM proxy key
+
+from openai import OpenAI
+
+client = OpenAI()
+
+response = client.chat.completions.create(
+ model="minimax-m2-5",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "Hi, how are you?"},
+ ],
+ extra_body={"reasoning_split": True},
+)
+
+# Access thinking and response
+if hasattr(response.choices[0].message, 'reasoning_details'):
+ print(f"Thinking:\n{response.choices[0].message.reasoning_details[0]['text']}\n")
+print(f"Text:\n{response.choices[0].message.content}\n")
+```
diff --git a/docs/my-website/blog/model_cost_map_incident/index.md b/docs/my-website/blog/model_cost_map_incident/index.md
new file mode 100644
index 00000000000..b9ff20e4128
--- /dev/null
+++ b/docs/my-website/blog/model_cost_map_incident/index.md
@@ -0,0 +1,95 @@
+---
+slug: model-cost-map-incident
+title: "Incident Report: Invalid model cost map on main"
+date: 2026-02-10T10:00:00
+authors:
+ - name: Ishaan Jaffer
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/ishaanjaffer/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+tags: [incident-report, stability]
+hide_table_of_contents: false
+---
+
+**Date:** January 27, 2026
+**Duration:** ~20 minutes
+**Severity:** Low
+**Status:** Resolved
+
+## Summary
+
+A malformed JSON entry in `model_prices_and_context_window.json` was merged to `main` ([`562f0a0`](https://github.com/BerriAI/litellm/commit/562f0a028251750e3d75386bee0e630d9796d0df)). This caused LiteLLM to silently fall back to a stale local copy of the model cost map. Users on older package versions lost cost tracking for newer models only (e.g. `azure/gpt-5.2`). No LLM calls were blocked.
+
+- **LLM calls and proxy routing:** No impact.
+- **Cost tracking:** Impacted for newer models not present in the local backup. Older models were unaffected. The incident lasted ~20 minutes until the commit was reverted.
+
+{/* truncate */}
+
+---
+
+## Background
+
+The model cost map is not in the request path. It is used after the LLM response comes back, inside a try/catch, to calculate spend. A missing entry never blocks a call.
+
+```mermaid
+flowchart TD
+ A["1. litellm.completion() receives request
+ litellm/main.py"] --> B["2. Route to provider
+ litellm/litellm_core_utils/get_llm_provider_logic.py"]
+ B --> C["3. LLM returns response
+ litellm/main.py"]
+ C --> D["4. Post-call: look up model in cost map
+ litellm/cost_calculator.py"]
+ D -->|"found"| E["5a. Attach cost to response"]
+ D -->|"not found (try/catch)"| F["5b. Log warning, set cost=0"]
+ E --> G["6. Return response to caller"]
+ F --> G
+
+ style D fill:#fff3cd,stroke:#ffc107
+ style F fill:#fff3cd,stroke:#ffc107
+ style E fill:#d4edda,stroke:#28a745
+ style G fill:#d4edda,stroke:#28a745
+```
+
+Both paths return a response to the caller. When the cost map lookup fails, the only difference is `cost=0` on that request.
+
+---
+
+## Root cause
+
+LiteLLM fetches the model cost map from GitHub `main` at import time. If the fetch fails, it falls back to a local backup bundled with the package. Before this incident, the fallback was completely silent -- no warning was logged.
+
+A contributor PR introduced an extra `{` bracket, producing invalid JSON. The remote fetch failed with `JSONDecodeError`, triggering the silent fallback. Users on older package versions had backup files missing newer models.
+
+**Timeline:**
+
+1. Malformed JSON merged to `main`
+2. LiteLLM installations fall back to local backup on next import
+3. Users report `"This model isn't mapped yet"` for newer models
+4. Bad commit identified and reverted (~20 minutes)
+
+---
+
+## Remediation
+
+| # | Action | Status | Code |
+|---|---|---|---|
+| 1 | CI validation on `model_prices_and_context_window.json` | ✅ Done | [`test-model-map.yaml`](https://github.com/BerriAI/litellm/blob/main/.github/workflows/test-model-map.yaml) |
+| 2 | Warning log on fallback to local backup | ✅ Done | [`get_model_cost_map.py#L57-L68`](https://github.com/BerriAI/litellm/blob/main/litellm/litellm_core_utils/get_model_cost_map.py#L57-L68) |
+| 3 | `GetModelCostMap` class with integrity validation helpers | ✅ Done | [`get_model_cost_map.py#L24-L149`](https://github.com/BerriAI/litellm/blob/main/litellm/litellm_core_utils/get_model_cost_map.py#L24-L149) |
+| 4 | Resilience test suite (bad hosted map, fallback, completion) | ✅ Done | [`test_model_cost_map_resilience.py#L150-L291`](https://github.com/BerriAI/litellm/blob/main/tests/llm_translation/test_model_cost_map_resilience.py#L150-L291) |
+| 5 | Test that backup model cost map always exists and contains common models | ✅ Done | [`test_model_cost_map_resilience.py#L213-L228`](https://github.com/BerriAI/litellm/blob/main/tests/llm_translation/test_model_cost_map_resilience.py#L213-L228) |
+
+Enterprises that require zero external dependencies at import time can set `LITELLM_LOCAL_MODEL_COST_MAP=True` to skip the GitHub fetch entirely.
+
+---
+
+## Other dependencies on external resources
+
+| Dependency | Impact if unavailable | Fallback |
+|---|---|---|
+| Model cost map (GitHub) | Cost tracking for newer models | Local backup (now with warning) |
+| JWT public keys (IDP/SSO) | Auth fails | None |
+| OIDC UserInfo (IDP/SSO) | Auth fails | None |
+| HuggingFace model API | HF provider calls fail | None |
+| Ollama tags (localhost) | Ollama model list stale | Static list |
diff --git a/docs/my-website/blog/sub_millisecond_proxy_overhead/index.md b/docs/my-website/blog/sub_millisecond_proxy_overhead/index.md
new file mode 100644
index 00000000000..1857383363c
--- /dev/null
+++ b/docs/my-website/blog/sub_millisecond_proxy_overhead/index.md
@@ -0,0 +1,92 @@
+---
+slug: sub-millisecond-proxy-overhead
+title: "Achieving Sub-Millisecond Proxy Overhead"
+date: 2026-02-02T10:00:00
+authors:
+ - name: Alexsander Hamir
+ title: "Performance Engineer, LiteLLM"
+ url: https://www.linkedin.com/in/alexsander-baptista/
+ image_url: https://github.com/AlexsanderHamir.png
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+description: "Our Q1 performance target and architectural direction for achieving sub-millisecond proxy overhead on modest hardware."
+tags: [performance, architecture]
+hide_table_of_contents: false
+---
+
+
+
+# Achieving Sub-Millisecond Proxy Overhead
+
+## Introduction
+
+Our Q1 performance target is to aggressively move toward sub-millisecond proxy overhead on a single instance with 4 CPUs and 8 GB of RAM, and to continue pushing that boundary over time. Our broader goal is to make LiteLLM inexpensive to deploy, lightweight, and fast. This post outlines the architectural direction behind that effort.
+
+Proxy overhead refers to the latency introduced by LiteLLM itself, independent of the upstream provider.
+
+To measure it, we run the same workload directly against the provider and through LiteLLM at identical QPS (for example, 1,000 QPS) and compare the latency delta. To reduce noise, the load generator, LiteLLM, and a mock LLM endpoint all run on the same machine, ensuring the difference reflects proxy overhead rather than network latency.
+
+---
+
+## Where We're Coming From
+
+Under the same benchmark originally conducted by [TensorZero](https://www.tensorzero.com/docs/gateway/benchmarks), LiteLLM previously failed at around 1,000 QPS.
+
+That is no longer the case. Today, LiteLLM can be stress-tested at 1,000 QPS with no failures and can scale up to 5,000 QPS without failures on a 4-CPU, 8-GB RAM single instance setup.
+
+This establishes a more up to date baseline and provides useful context as we continue working on proxy overhead and overall performance.
+
+---
+
+## Design Choice
+
+Achieving sub-millisecond proxy overhead with a Python-based system requires being deliberate about where work happens.
+
+Python is a strong fit for flexibility and extensibility: provider abstraction, configuration-driven routing, and a rich callback ecosystem. These are areas where development velocity and correctness matter more than raw throughput.
+
+At higher request rates, however, certain classes of work become expensive when executed inside the Python process on every request. Rather than rewriting LiteLLM or introducing complex deployment requirements, we adopt an optional **sidecar architecture**.
+
+This architectural change is how we intend to make LiteLLM **permanently fast**. While it supports our near-term performance targets, it is a long-term investment.
+
+Python continues to own:
+
+- Request validation and normalization
+- Model and provider selection
+- Callbacks and integrations
+
+The sidecar owns **performance-critical execution**, such as:
+
+- Efficient request forwarding
+- Connection reuse and pooling
+- Enforcing timeouts and limits
+- Aggregating high-frequency metrics
+
+This separation allows each component to focus on what it does best: Python acts as the control plane, while the sidecar handles the hot path.
+
+---
+
+### Why the Sidecar Is Optional
+
+The sidecar is intentionally **optional**.
+
+This allows us to ship it incrementally, validate it under real-world workloads, and avoid making it a hard dependency before it is fully battle-tested across all LiteLLM features.
+
+Just as importantly, this ensures that self-hosting LiteLLM remains simple. The sidecar is bundled and started automatically, requires no additional infrastructure, and can be disabled entirely. From a user's perspective, LiteLLM continues to behave like a single service.
+
+As of today, the sidecar is an optimization, not a requirement.
+
+---
+
+## Conclusion
+
+Sub-millisecond proxy overhead is not achieved through a single optimization, but through architectural changes.
+
+By keeping Python focused on orchestration and extensibility, and offloading performance-critical execution to a sidecar, we establish a foundation for making LiteLLM **permanently fast over time**—even on modest hardware such as a 1-CPU, 2-GB RAM instance, while keeping deployment and self-hosting simple.
+
+This work extends beyond Q1, and we will continue sharing benchmarks and updates as the architecture evolves.
diff --git a/docs/my-website/blog/vllm_embeddings_incident/index.md b/docs/my-website/blog/vllm_embeddings_incident/index.md
new file mode 100644
index 00000000000..a1ce8152857
--- /dev/null
+++ b/docs/my-website/blog/vllm_embeddings_incident/index.md
@@ -0,0 +1,117 @@
+---
+slug: vllm-embeddings-incident
+title: "Incident Report: vLLM Embeddings Broken by encoding_format Parameter"
+date: 2026-02-18T10:00:00
+authors:
+ - name: Sameer Kankute
+ title: SWE @ LiteLLM (LLM Translation)
+ url: https://www.linkedin.com/in/sameer-kankute/
+ image_url: https://pbs.twimg.com/profile_images/2001352686994907136/ONgNuSk5_400x400.jpg
+ - name: Krrish Dholakia
+ title: "CEO, LiteLLM"
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: "CTO, LiteLLM"
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+tags: [incident-report, embeddings, vllm]
+hide_table_of_contents: false
+---
+
+**Date:** Feb 16, 2026
+**Duration:** ~3 hours
+**Severity:** High (for vLLM embedding users)
+**Status:** Resolved
+
+## Summary
+
+A commit ([`dbcae4a`](https://github.com/BerriAI/litellm/commit/dbcae4aca5836770d0e9cd43abab0333c3d61ab2)) intended to fix OpenAI SDK behavior broke vLLM embeddings by explicitly passing `encoding_format=None` in API requests. vLLM rejects this with error: `"unknown variant \`\`, expected float or base64"`.
+
+- **vLLM embedding calls:** Complete failure - all requests rejected
+- **Other providers:** No impact - OpenAI and other providers functioned normally
+- **Other vLLM functionality:** No impact - only embeddings were affected
+
+{/* truncate */}
+
+---
+
+## Background
+
+The `encoding_format` parameter for embeddings specifies whether vectors should be returned as `float` arrays or `base64` encoded strings. Different providers have different expectations:
+
+- **OpenAI SDK:** If `encoding_format` is omitted, the SDK adds a default value of `"float"`
+- **vLLM:** Strictly validates `encoding_format` - only accepts `"float"`, `"base64"`, or complete omission. Rejects `None` or empty string values.
+
+```mermaid
+flowchart TD
+ A["1. User calls litellm.embedding()
+ litellm/main.py"] --> B["2. Transform request for provider
+ litellm/llms/openai_like/embedding/handler.py"]
+ B --> C["3. Send request to vLLM endpoint"]
+ C -->|"encoding_format omitted"| D["4a. ✅ vLLM processes request"]
+ C -->|"encoding_format='float' or 'base64'"| D
+ C -->|"encoding_format=None or ''"| E["4b. ❌ vLLM rejects with error:
+ 'unknown variant, expected float or base64'"]
+
+ style D fill:#d4edda,stroke:#28a745
+ style E fill:#f8d7da,stroke:#dc3545
+ style B fill:#fff3cd,stroke:#ffc107
+```
+
+---
+
+## Root cause
+
+A well-intentioned fix for OpenAI SDK behavior inadvertently broke vLLM embeddings:
+
+**The Breaking Change ([`dbcae4a`](https://github.com/BerriAI/litellm/commit/dbcae4aca5836770d0e9cd43abab0333c3d61ab2)):**
+
+In `litellm/main.py`, the code was changed to explicitly set `encoding_format=None` instead of omitting it:
+
+```python
+# Added in dbcae4a
+if encoding_format is not None:
+ optional_params["encoding_format"] = encoding_format
+else:
+ # Omitting causes openai sdk to add default value of "float"
+ optional_params["encoding_format"] = None
+```
+
+This fix worked correctly for OpenAI - explicitly passing `None` prevented the SDK from adding its default value. However, vLLM's strict parameter validation rejected `None` values, causing all embedding requests to fail.
+
+---
+
+## The Fix
+
+Fix deployed ([`55348dd`](https://github.com/BerriAI/litellm/commit/55348dd9c51b5b028f676d25ad023b8f052fc071)). The solution filters out `None` and empty string values from `optional_params` before sending requests to OpenAI-like providers (including vLLM).
+
+**In `litellm/llms/openai_like/embedding/handler.py`:**
+
+```python
+# Before (broken)
+data = {"model": model, "input": input, **optional_params}
+
+# After (fixed)
+filtered_optional_params = {k: v for k, v in optional_params.items() if v not in (None, '')}
+data = {"model": model, "input": input, **filtered_optional_params}
+```
+
+This ensures:
+- Valid values (`"float"`, `"base64"`) are preserved and sent
+- `None` and empty string values are filtered out (parameter omitted entirely)
+- OpenAI SDK no longer adds defaults because liteLLM handles the parameter upstream
+
+---
+
+## Remediation
+
+| # | Action | Status | Code |
+|---|---|---|---|
+| 1 | Filter `None` and empty string values in OpenAI-like embedding handler | ✅ Done | [`handler.py#L108`](https://github.com/BerriAI/litellm/blob/main/litellm/llms/openai_like/embedding/handler.py#L108) |
+| 2 | Unit tests for parameter filtering (None, empty string, valid values) | ✅ Done | [`test_openai_like_embedding.py`](https://github.com/BerriAI/litellm/blob/main/tests/test_litellm/llms/openai_like/embedding/test_openai_like_embedding.py) |
+| 3 | Transformation tests for hosted_vllm embedding config | ✅ Done | [`test_hosted_vllm_embedding_transformation.py`](https://github.com/BerriAI/litellm/blob/main/tests/test_litellm/llms/hosted_vllm/embedding/test_hosted_vllm_embedding_transformation.py) |
+| 4 | E2E tests with actual vLLM endpoint | ✅ Done | [`test_hosted_vllm_embedding_e2e.py`](https://github.com/BerriAI/litellm/blob/main/tests/test_litellm/llms/hosted_vllm/embedding/test_hosted_vllm_embedding_e2e.py) |
+| 5 | Validate JSON payload structure matches vLLM expectations | ✅ Done | Tests verify exact JSON sent to endpoint |
+
+---
diff --git a/docs/my-website/docs/a2a.md b/docs/my-website/docs/a2a.md
index d7145e4b83c..b1166a7809c 100644
--- a/docs/my-website/docs/a2a.md
+++ b/docs/my-website/docs/a2a.md
@@ -68,116 +68,9 @@ Follow [this guide, to add your pydantic ai agent to LiteLLM Agent Gateway](./pr
## Invoking your Agents
-Use the [A2A Python SDK](https://pypi.org/project/a2a/) to invoke agents through LiteLLM.
-
-This example shows how to:
-1. **List available agents** - Query `/v1/agents` to see which agents your key can access
-2. **Select an agent** - Pick an agent from the list
-3. **Invoke via A2A** - Use the A2A protocol to send messages to the agent
-
-```python showLineNumbers title="invoke_a2a_agent.py"
-from uuid import uuid4
-import httpx
-import asyncio
-from a2a.client import A2ACardResolver, A2AClient
-from a2a.types import MessageSendParams, SendMessageRequest
-
-# === CONFIGURE THESE ===
-LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL
-LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key
-# =======================
-
-async def main():
- headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"}
-
- async with httpx.AsyncClient(headers=headers) as client:
- # Step 1: List available agents
- response = await client.get(f"{LITELLM_BASE_URL}/v1/agents")
- agents = response.json()
-
- print("Available agents:")
- for agent in agents:
- print(f" - {agent['agent_name']} (ID: {agent['agent_id']})")
-
- if not agents:
- print("No agents available for this key")
- return
-
- # Step 2: Select an agent and invoke it
- selected_agent = agents[0]
- agent_id = selected_agent["agent_id"]
- agent_name = selected_agent["agent_name"]
- print(f"\nInvoking: {agent_name}")
-
- # Step 3: Use A2A protocol to invoke the agent
- base_url = f"{LITELLM_BASE_URL}/a2a/{agent_id}"
- resolver = A2ACardResolver(httpx_client=client, base_url=base_url)
- agent_card = await resolver.get_agent_card()
- a2a_client = A2AClient(httpx_client=client, agent_card=agent_card)
-
- request = SendMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(
- message={
- "role": "user",
- "parts": [{"kind": "text", "text": "Hello, what can you do?"}],
- "messageId": uuid4().hex,
- }
- ),
- )
- response = await a2a_client.send_message(request)
- print(f"Response: {response.model_dump(mode='json', exclude_none=True, indent=4)}")
-
-if __name__ == "__main__":
- asyncio.run(main())
-```
-
-### Streaming Responses
-
-For streaming responses, use `send_message_streaming`:
-
-```python showLineNumbers title="invoke_a2a_agent_streaming.py"
-from uuid import uuid4
-import httpx
-import asyncio
-from a2a.client import A2ACardResolver, A2AClient
-from a2a.types import MessageSendParams, SendStreamingMessageRequest
-
-# === CONFIGURE THESE ===
-LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL
-LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key
-LITELLM_AGENT_NAME = "ij-local" # Agent name registered in LiteLLM
-# =======================
-
-async def main():
- base_url = f"{LITELLM_BASE_URL}/a2a/{LITELLM_AGENT_NAME}"
- headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"}
-
- async with httpx.AsyncClient(headers=headers) as httpx_client:
- # Resolve agent card and create client
- resolver = A2ACardResolver(httpx_client=httpx_client, base_url=base_url)
- agent_card = await resolver.get_agent_card()
- client = A2AClient(httpx_client=httpx_client, agent_card=agent_card)
-
- # Send a streaming message
- request = SendStreamingMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(
- message={
- "role": "user",
- "parts": [{"kind": "text", "text": "Hello, what can you do?"}],
- "messageId": uuid4().hex,
- }
- ),
- )
-
- # Stream the response
- async for chunk in client.send_message_streaming(request):
- print(chunk.model_dump(mode="json", exclude_none=True))
-
-if __name__ == "__main__":
- asyncio.run(main())
-```
+See the [Invoking A2A Agents](./a2a_invoking_agents) guide to learn how to call your agents using:
+- **A2A SDK** - Native A2A protocol with full support for tasks and artifacts
+- **OpenAI SDK** - Familiar `/chat/completions` interface with `a2a/` model prefix
## Tracking Agent Logs
@@ -193,6 +86,120 @@ The logs show:
style={{width: '100%', display: 'block', margin: '2rem auto'}}
/>
+
+## Forwarding LiteLLM Context Headers
+
+When LiteLLM invokes your A2A agent, it sends special headers that enable:
+- **Trace Grouping**: All LLM calls from the same agent execution appear under one trace
+- **Agent Spend Tracking**: Costs are attributed to the specific agent
+
+| Header | Purpose |
+|--------|---------|
+| `X-LiteLLM-Trace-Id` | Links all LLM calls to the same execution flow |
+| `X-LiteLLM-Agent-Id` | Attributes spend to the correct agent |
+
+
+To enable these features, your A2A server must **forward these headers** to any LLM calls it makes back to LiteLLM.
+
+### Implementation Steps
+
+**Step 1: Extract headers from incoming A2A request**
+```python def get_litellm_headers(request) -> dict:
+ """Extract X-LiteLLM-* headers from incoming A2A request."""
+ all_headers = request.call_context.state.get('headers', {})
+ return {
+ k: v for k, v in all_headers.items()
+ if k.lower().startswith('x-litellm-')
+ }
+```
+
+**Step 2: Forward headers to your LLM calls**
+Pass the extracted headers when making calls back to LiteLLM:
+
+
+
+```python from openai import OpenAI
+
+headers = get_litellm_headers(request)
+
+client = OpenAI(
+ api_key="sk-your-litellm-key",
+ base_url="http://localhost:4000",
+ default_headers=headers, # Forward headers
+)
+
+response = client.chat.completions.create(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "Hello"}]
+)
+```
+
+
+
+
+```python
+from langchain_openai import ChatOpenAI
+
+headers = get_litellm_headers(request)
+
+llm = ChatOpenAI(
+ model="gpt-4o",
+ openai_api_key="sk-your-litellm-key",
+ base_url="http://localhost:4000",
+ default_headers=headers, # Forward headers
+)
+```
+
+
+
+```python
+import litellm
+
+headers = get_litellm_headers(request)
+
+response = litellm.completion(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "Hello"}],
+ api_base="http://localhost:4000",
+ extra_headers=headers, # Forward headers
+)
+```
+
+
+
+```python
+import httpx
+
+headers = get_litellm_headers(request)
+headers["Authorization"] = "Bearer sk-your-litellm-key"
+
+response = httpx.post(
+ "http://localhost:4000/v1/chat/completions",
+ headers=headers,
+ json={"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}
+)
+```
+
+
+
+### Result
+
+With header forwarding enabled, you'll see:
+
+**Trace Grouping in Langfuse:**
+
+
+
+**Agent Spend Attribution:**
+
+
+
## API Reference
### Endpoint
diff --git a/docs/my-website/docs/a2a_invoking_agents.md b/docs/my-website/docs/a2a_invoking_agents.md
new file mode 100644
index 00000000000..3bb248e4561
--- /dev/null
+++ b/docs/my-website/docs/a2a_invoking_agents.md
@@ -0,0 +1,280 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Invoking A2A Agents
+
+Learn how to invoke A2A agents through LiteLLM using different methods.
+
+:::tip Deploy Your Own A2A Agent
+
+Want to test with your own agent? Deploy this template A2A agent powered by Google Gemini:
+
+[**shin-bot-litellm/a2a-gemini-agent**](https://github.com/shin-bot-litellm/a2a-gemini-agent) - Simple deployable A2A agent with streaming support
+
+:::
+
+## A2A SDK
+
+Use the [A2A Python SDK](https://pypi.org/project/a2a-sdk) to invoke agents through LiteLLM using the A2A protocol.
+
+### Non-Streaming
+
+This example shows how to:
+1. **List available agents** - Query `/v1/agents` to see which agents your key can access
+2. **Select an agent** - Pick an agent from the list
+3. **Invoke via A2A** - Use the A2A protocol to send messages to the agent
+
+```python showLineNumbers title="invoke_a2a_agent.py"
+from uuid import uuid4
+import httpx
+import asyncio
+from a2a.client import A2ACardResolver, A2AClient
+from a2a.types import MessageSendParams, SendMessageRequest
+
+# === CONFIGURE THESE ===
+LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL
+LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key
+# =======================
+
+async def main():
+ headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"}
+
+ async with httpx.AsyncClient(headers=headers) as client:
+ # Step 1: List available agents
+ response = await client.get(f"{LITELLM_BASE_URL}/v1/agents")
+ agents = response.json()
+
+ print("Available agents:")
+ for agent in agents:
+ print(f" - {agent['agent_name']} (ID: {agent['agent_id']})")
+
+ if not agents:
+ print("No agents available for this key")
+ return
+
+ # Step 2: Select an agent and invoke it
+ selected_agent = agents[0]
+ agent_id = selected_agent["agent_id"]
+ agent_name = selected_agent["agent_name"]
+ print(f"\nInvoking: {agent_name}")
+
+ # Step 3: Use A2A protocol to invoke the agent
+ base_url = f"{LITELLM_BASE_URL}/a2a/{agent_id}"
+ resolver = A2ACardResolver(httpx_client=client, base_url=base_url)
+ agent_card = await resolver.get_agent_card()
+ a2a_client = A2AClient(httpx_client=client, agent_card=agent_card)
+
+ request = SendMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(
+ message={
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Hello, what can you do?"}],
+ "messageId": uuid4().hex,
+ }
+ ),
+ )
+ response = await a2a_client.send_message(request)
+ print(f"Response: {response.model_dump(mode='json', exclude_none=True, indent=4)}")
+
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+### Streaming
+
+For streaming responses, use `send_message_streaming`:
+
+```python showLineNumbers title="invoke_a2a_agent_streaming.py"
+from uuid import uuid4
+import httpx
+import asyncio
+from a2a.client import A2ACardResolver, A2AClient
+from a2a.types import MessageSendParams, SendStreamingMessageRequest
+
+# === CONFIGURE THESE ===
+LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL
+LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key
+LITELLM_AGENT_NAME = "ij-local" # Agent name registered in LiteLLM
+# =======================
+
+async def main():
+ base_url = f"{LITELLM_BASE_URL}/a2a/{LITELLM_AGENT_NAME}"
+ headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"}
+
+ async with httpx.AsyncClient(headers=headers) as httpx_client:
+ # Resolve agent card and create client
+ resolver = A2ACardResolver(httpx_client=httpx_client, base_url=base_url)
+ agent_card = await resolver.get_agent_card()
+ client = A2AClient(httpx_client=httpx_client, agent_card=agent_card)
+
+ # Send a streaming message
+ request = SendStreamingMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(
+ message={
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Tell me a long story"}],
+ "messageId": uuid4().hex,
+ }
+ ),
+ )
+
+ # Stream the response
+ async for chunk in client.send_message_streaming(request):
+ print(chunk.model_dump(mode="json", exclude_none=True))
+
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+## /chat/completions API (OpenAI SDK)
+
+You can also invoke A2A agents using the familiar OpenAI SDK by using the `a2a/` model prefix.
+
+### Non-Streaming
+
+
+
+
+```python showLineNumbers title="openai_non_streaming.py"
+import openai
+
+client = openai.OpenAI(
+ api_key="sk-1234", # Your LiteLLM Virtual Key
+ base_url="http://localhost:4000" # Your LiteLLM proxy URL
+)
+
+response = client.chat.completions.create(
+ model="a2a/my-agent", # Use a2a/ prefix with your agent name
+ messages=[
+ {"role": "user", "content": "Hello, what can you do?"}
+ ]
+)
+
+print(response.choices[0].message.content)
+```
+
+
+
+
+```typescript showLineNumbers title="openai_non_streaming.ts"
+import OpenAI from 'openai';
+
+const client = new OpenAI({
+ apiKey: 'sk-1234', // Your LiteLLM Virtual Key
+ baseURL: 'http://localhost:4000' // Your LiteLLM proxy URL
+});
+
+const response = await client.chat.completions.create({
+ model: 'a2a/my-agent', // Use a2a/ prefix with your agent name
+ messages: [
+ { role: 'user', content: 'Hello, what can you do?' }
+ ]
+});
+
+console.log(response.choices[0].message.content);
+```
+
+
+
+
+```bash showLineNumbers title="curl_non_streaming.sh"
+curl -X POST http://localhost:4000/v1/chat/completions \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "a2a/my-agent",
+ "messages": [
+ {"role": "user", "content": "Hello, what can you do?"}
+ ]
+ }'
+```
+
+
+
+
+### Streaming
+
+
+
+
+```python showLineNumbers title="openai_streaming.py"
+import openai
+
+client = openai.OpenAI(
+ api_key="sk-1234", # Your LiteLLM Virtual Key
+ base_url="http://localhost:4000" # Your LiteLLM proxy URL
+)
+
+stream = client.chat.completions.create(
+ model="a2a/my-agent", # Use a2a/ prefix with your agent name
+ messages=[
+ {"role": "user", "content": "Tell me a long story"}
+ ],
+ stream=True
+)
+
+for chunk in stream:
+ if chunk.choices[0].delta.content:
+ print(chunk.choices[0].delta.content, end="", flush=True)
+```
+
+
+
+
+```typescript showLineNumbers title="openai_streaming.ts"
+import OpenAI from 'openai';
+
+const client = new OpenAI({
+ apiKey: 'sk-1234', // Your LiteLLM Virtual Key
+ baseURL: 'http://localhost:4000' // Your LiteLLM proxy URL
+});
+
+const stream = await client.chat.completions.create({
+ model: 'a2a/my-agent', // Use a2a/ prefix with your agent name
+ messages: [
+ { role: 'user', content: 'Tell me a long story' }
+ ],
+ stream: true
+});
+
+for await (const chunk of stream) {
+ const content = chunk.choices[0]?.delta?.content;
+ if (content) {
+ process.stdout.write(content);
+ }
+}
+```
+
+
+
+
+```bash showLineNumbers title="curl_streaming.sh"
+curl -X POST http://localhost:4000/v1/chat/completions \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "a2a/my-agent",
+ "messages": [
+ {"role": "user", "content": "Tell me a long story"}
+ ],
+ "stream": true
+ }'
+```
+
+
+
+
+## Key Differences
+
+| Method | Use Case | Advantages |
+|--------|----------|------------|
+| **A2A SDK** | Native A2A protocol integration | • Full A2A protocol support • Access to task states and artifacts • Context management |
+| **OpenAI SDK** | Familiar OpenAI-style interface | • Drop-in replacement for OpenAI calls • Easier migration from LLM to agent workflows • Works with existing OpenAI tooling |
+
+:::tip Model Prefix
+
+When using the OpenAI SDK, always prefix your agent name with `a2a/` (e.g., `a2a/my-agent`) to route requests to the A2A agent instead of an LLM provider.
+
+:::
diff --git a/docs/my-website/docs/adding_provider/generic_guardrail_api.md b/docs/my-website/docs/adding_provider/generic_guardrail_api.md
index 482dedaa8a9..eb567a69fcb 100644
--- a/docs/my-website/docs/adding_provider/generic_guardrail_api.md
+++ b/docs/my-website/docs/adding_provider/generic_guardrail_api.md
@@ -93,6 +93,12 @@ Implement `POST /beta/litellm_basic_guardrail_api`
"user_api_key_end_user_id": "end user id associated with the litellm virtual key used",
"user_api_key_org_id": "org id associated with the litellm virtual key used"
},
+ "request_headers": { // optional: inbound request headers (allowlist). Allowed headers show their value; all others show "[present]" to indicate the header existed.
+ "User-Agent": "OpenAI/Python 2.17.0",
+ "Content-Type": "application/json",
+ "X-Request-Id": "[present]"
+ },
+ "litellm_version": "1.x.y", // optional: LiteLLM library version running this proxy
"input_type": "request", // "request" or "response"
"litellm_call_id": "unique_call_id", // the call id of the individual LLM call
"litellm_trace_id": "trace_id", // the trace id of the LLM call - useful if there are multiple LLM calls for the same conversation
@@ -231,6 +237,7 @@ litellm_settings:
mode: pre_call # or post_call, during_call
api_base: https://your-guardrail-api.com
api_key: os.environ/YOUR_GUARDRAIL_API_KEY # optional
+ unreachable_fallback: fail_closed # default: fail_closed. Set to fail_open to proceed if the guardrail endpoint is unreachable (network errors, or HTTP 502/503/504 from an upstream proxy/LB).
additional_provider_specific_params:
# your custom parameters
threshold: 0.8
diff --git a/docs/my-website/docs/adding_provider/generic_prompt_management_api.md b/docs/my-website/docs/adding_provider/generic_prompt_management_api.md
new file mode 100644
index 00000000000..d1b119d94c5
--- /dev/null
+++ b/docs/my-website/docs/adding_provider/generic_prompt_management_api.md
@@ -0,0 +1,576 @@
+# [BETA] Generic Prompt Management API - Integrate Without a PR
+
+## The Problem
+
+As a prompt management provider, integrating with LiteLLM traditionally requires:
+- Making a PR to the LiteLLM repository
+- Waiting for review and merge
+- Maintaining provider-specific code in LiteLLM's codebase
+- Updating the integration for changes to your API
+
+## The Solution
+
+The **Generic Prompt Management API** lets you integrate with LiteLLM **instantly** by implementing a simple API endpoint. No PR required.
+
+### Key Benefits
+
+1. **No PR Needed** - Deploy and integrate immediately
+3. **Simple Contract** - One GET endpoint, standard JSON response
+4. **Variable Substitution** - Support for prompt variables with `{variable}` syntax
+5. **Custom Parameters** - Pass provider-specific query params via config
+6. **Full Control** - You own and maintain your prompt management API
+7. **Model & Parameters Override** - Optionally override model and parameters from your prompts
+
+## Get Started in 3 Steps
+
+### Step 1: Configure LiteLLM
+
+Add to your `config.yaml`:
+
+```yaml
+prompts:
+ - prompt_id: "simple_prompt"
+ litellm_params:
+ prompt_integration: "generic_prompt_management"
+ api_base: http://localhost:8080
+ api_key: os.environ/YOUR_API_KEY
+```
+
+### Step 2: Implement Your API Endpoint
+
+```python
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+@app.get("/beta/litellm_prompt_management")
+async def get_prompt(prompt_id: str):
+ return {
+ "prompt_id": prompt_id,
+ "prompt_template": [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "Help me with {task}"}
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {"temperature": 0.7}
+ }
+```
+
+### Step 3: Use in Your App
+
+```python
+from litellm import completion
+
+response = completion(
+ model="gpt-4",
+ prompt_id="simple_prompt",
+ prompt_variables={"task": "data analysis"},
+ messages=[{"role": "user", "content": "I have sales data"}]
+)
+```
+
+That's it! LiteLLM fetches your prompt, applies variables, and makes the request
+
+## API Contract
+
+### Endpoint
+
+Implement `GET /beta/litellm_prompt_management`
+
+### Request Format
+
+Your endpoint will receive a GET request with query parameters:
+
+```
+GET /beta/litellm_prompt_management?prompt_id={prompt_id}&{custom_params}
+```
+
+**Query Parameters:**
+- `prompt_id` (required): The ID of the prompt to fetch
+- Custom parameters: Any additional parameters you configured in `provider_specific_query_params`
+
+**Example:**
+```
+GET /beta/litellm_prompt_management?prompt_id=hello-world-prompt-2bac&project_name=litellm&slug=hello-world-prompt-2bac
+```
+
+### Response Format
+
+```json
+{
+ "prompt_id": "hello-world-prompt-2bac",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant specialized in {domain}."
+ },
+ {
+ "role": "user",
+ "content": "Help me with {task}"
+ }
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.7,
+ "max_tokens": 500,
+ "top_p": 0.9
+ }
+}
+```
+
+**Response Fields:**
+- `prompt_id` (string, required): The ID of the prompt
+- `prompt_template` (array, required): Array of OpenAI-format messages with optional `{variable}` placeholders
+- `prompt_template_model` (string, optional): Model to use for this prompt (overrides client model unless `ignore_prompt_manager_model: true`)
+- `prompt_template_optional_params` (object, optional): Additional parameters like temperature, max_tokens, etc. (merged with client params unless `ignore_prompt_manager_optional_params: true`)
+
+## LiteLLM Configuration
+
+Add to `config.yaml`:
+
+```yaml
+model_list:
+ - model_name: gpt-3.5-turbo
+ litellm_params:
+ model: openai/gpt-3.5-turbo
+ api_key: os.environ/OPENAI_API_KEY
+
+prompts:
+ - prompt_id: "simple_prompt"
+ litellm_params:
+ prompt_integration: "generic_prompt_management"
+ provider_specific_query_params:
+ project_name: litellm
+ slug: hello-world-prompt-2bac
+ api_base: http://localhost:8080
+ api_key: os.environ/YOUR_PROMPT_API_KEY # optional
+ ignore_prompt_manager_model: true # optional, keep client's model
+ ignore_prompt_manager_optional_params: true # optional, don't merge prompt manager's params (e.g. temperature, max_tokens, etc.)
+```
+
+### Configuration Parameters
+
+- `prompt_integration`: Must be `"generic_prompt_management"`
+- `provider_specific_query_params`: Custom query parameters sent to your API (optional)
+- `api_base`: Base URL of your prompt management API
+- `api_key`: Optional API key for authentication (sent as `Bearer` token)
+- `ignore_prompt_manager_model`: If `true`, use the model specified by client instead of prompt's model (default: `false`)
+- `ignore_prompt_manager_optional_params`: If `true`, don't merge prompt's optional params with client params (default: `false`)
+
+## Usage
+
+### Using with LiteLLM SDK
+
+**Basic usage with prompt ID:**
+
+```python
+from litellm import completion
+
+response = completion(
+ model="gpt-4",
+ prompt_id="simple_prompt",
+ messages=[{"role": "user", "content": "Additional message"}]
+)
+```
+
+**With prompt variables:**
+
+```python
+response = completion(
+ model="gpt-4",
+ prompt_id="simple_prompt",
+ prompt_variables={
+ "domain": "data science",
+ "task": "analyzing customer churn"
+ },
+ messages=[{"role": "user", "content": "Please provide a detailed analysis"}]
+)
+```
+
+The prompt template will have `{domain}` replaced with "data science" and `{task}` replaced with "analyzing customer churn".
+
+### Using with LiteLLM Proxy
+
+**1. Start the proxy with your config:**
+
+```bash
+litellm --config /path/to/config.yaml
+```
+
+**2. Make requests with prompt_id:**
+
+```bash
+curl http://0.0.0.0:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-4",
+ "prompt_id": "simple_prompt",
+ "prompt_variables": {
+ "domain": "healthcare",
+ "task": "patient risk assessment"
+ },
+ "messages": [
+ {"role": "user", "content": "Analyze the following data..."}
+ ]
+ }'
+```
+
+**3. Using with OpenAI SDK:**
+
+```python
+from openai import OpenAI
+
+client = OpenAI(
+ base_url="http://0.0.0.0:4000",
+ api_key="sk-1234"
+)
+
+response = client.chat.completions.create(
+ model="gpt-4",
+ messages=[
+ {"role": "user", "content": "Analyze the data"}
+ ],
+ extra_body={
+ "prompt_id": "simple_prompt",
+ "prompt_variables": {
+ "domain": "finance",
+ "task": "fraud detection"
+ }
+ }
+)
+```
+
+## Implementation Example
+
+See [mock_prompt_management_server.py](https://github.com/BerriAI/litellm/blob/main/cookbook/mock_prompt_management_server/mock_prompt_management_server.py) for a complete reference implementation with multiple example prompts, authentication, and convenience endpoints.
+
+**Minimal FastAPI example:**
+
+```python
+from fastapi import FastAPI, HTTPException, Header
+from typing import Optional, Dict, Any, List
+from pydantic import BaseModel
+
+app = FastAPI()
+
+# In-memory prompt storage (replace with your database)
+PROMPTS = {
+ "hello-world-prompt": {
+ "prompt_id": "hello-world-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant specialized in {domain}."
+ },
+ {
+ "role": "user",
+ "content": "Help me with: {task}"
+ }
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.7,
+ "max_tokens": 500
+ }
+ },
+ "code-review-prompt": {
+ "prompt_id": "code-review-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are an expert code reviewer. Review code for {language}."
+ },
+ {
+ "role": "user",
+ "content": "Review the following code:\n\n{code}"
+ }
+ ],
+ "prompt_template_model": "gpt-4-turbo",
+ "prompt_template_optional_params": {
+ "temperature": 0.3,
+ "max_tokens": 1000
+ }
+ }
+}
+
+class PromptResponse(BaseModel):
+ prompt_id: str
+ prompt_template: List[Dict[str, str]]
+ prompt_template_model: Optional[str] = None
+ prompt_template_optional_params: Optional[Dict[str, Any]] = None
+
+@app.get("/beta/litellm_prompt_management", response_model=PromptResponse)
+async def get_prompt(
+ prompt_id: str,
+ authorization: Optional[str] = Header(None),
+ project_name: Optional[str] = None,
+ slug: Optional[str] = None,
+):
+ """
+ Get a prompt by ID with optional filtering by project_name and slug.
+
+ Args:
+ prompt_id: The ID of the prompt to fetch
+ authorization: Optional Bearer token for authentication
+ project_name: Optional project name filter
+ slug: Optional slug filter
+ """
+
+ # Optional: Validate authorization
+ if authorization:
+ token = authorization.replace("Bearer ", "")
+ # Validate your token here
+ if not is_valid_token(token):
+ raise HTTPException(status_code=401, detail="Invalid API key")
+
+ # Optional: Apply additional filtering based on custom params
+ if project_name or slug:
+ # You can use these parameters to filter or validate access
+ # For example, check if the user has access to this project
+ pass
+
+ # Fetch the prompt from your storage
+ if prompt_id not in PROMPTS:
+ raise HTTPException(
+ status_code=404,
+ detail=f"Prompt '{prompt_id}' not found"
+ )
+
+ prompt_data = PROMPTS[prompt_id]
+
+ return PromptResponse(**prompt_data)
+
+def is_valid_token(token: str) -> bool:
+ """Validate API token - implement your logic here"""
+ # Example: Check against your database or secret store
+ valid_tokens = ["your-secret-token", "another-valid-token"]
+ return token in valid_tokens
+
+# Optional: Health check endpoint
+@app.get("/health")
+async def health_check():
+ return {"status": "healthy"}
+
+# Optional: List all prompts endpoint
+@app.get("/prompts")
+async def list_prompts(authorization: Optional[str] = Header(None)):
+ """List all available prompts"""
+ if authorization:
+ token = authorization.replace("Bearer ", "")
+ if not is_valid_token(token):
+ raise HTTPException(status_code=401, detail="Invalid API key")
+
+ return {
+ "prompts": [
+ {"prompt_id": pid, "model": p.get("prompt_template_model")}
+ for pid, p in PROMPTS.items()
+ ]
+ }
+
+if __name__ == "__main__":
+ import uvicorn
+ uvicorn.run(app, host="0.0.0.0", port=8080)
+```
+
+### Running the Example Server
+
+1. Install dependencies:
+```bash
+pip install fastapi uvicorn
+```
+
+2. Save the code above to `prompt_server.py`
+
+3. Run the server:
+```bash
+python prompt_server.py
+```
+
+4. Test the endpoint:
+```bash
+curl "http://localhost:8080/beta/litellm_prompt_management?prompt_id=hello-world-prompt&project_name=litellm&slug=hello-world-prompt-2bac"
+```
+
+Expected response:
+```json
+{
+ "prompt_id": "hello-world-prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant specialized in {domain}."
+ },
+ {
+ "role": "user",
+ "content": "Help me with: {task}"
+ }
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.7,
+ "max_tokens": 500
+ }
+}
+```
+
+## Advanced Features
+
+### Variable Substitution
+
+LiteLLM automatically substitutes variables in your prompt templates using the `{variable}` syntax. Both `{variable}` and `{{variable}}` formats are supported.
+
+**Example prompt template:**
+```json
+{
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are an expert in {domain} with {years} years of experience."
+ }
+ ]
+}
+```
+
+**Client request:**
+```python
+completion(
+ model="gpt-4",
+ prompt_id="expert_prompt",
+ prompt_variables={
+ "domain": "machine learning",
+ "years": "10"
+ }
+)
+```
+
+**Result:**
+```
+"You are an expert in machine learning with 10 years of experience."
+```
+
+### Caching
+
+LiteLLM automatically caches fetched prompts in memory. The cache key includes:
+- `prompt_id`
+- `prompt_label` (if provided)
+- `prompt_version` (if provided)
+
+This means your API endpoint is only called once per unique prompt configuration.
+
+### Model Override Behavior
+
+**Default behavior (without `ignore_prompt_manager_model`):**
+```yaml
+prompts:
+ - prompt_id: "my_prompt"
+ litellm_params:
+ prompt_integration: "generic_prompt_management"
+ api_base: http://localhost:8080
+```
+
+If your API returns `"prompt_template_model": "gpt-4"`, LiteLLM will use `gpt-4` regardless of what the client specified.
+
+**With `ignore_prompt_manager_model: true`:**
+```yaml
+prompts:
+ - prompt_id: "my_prompt"
+ litellm_params:
+ prompt_integration: "generic_prompt_management"
+ api_base: http://localhost:8080
+ ignore_prompt_manager_model: true
+```
+
+LiteLLM will use the model specified by the client, ignoring the prompt's model.
+
+### Parameter Merging Behavior
+
+**Default behavior (without `ignore_prompt_manager_optional_params`):**
+
+Client params are merged with prompt params, with prompt params taking precedence:
+```python
+# Prompt returns: {"temperature": 0.7, "max_tokens": 500}
+# Client sends: {"temperature": 0.9, "top_p": 0.95}
+# Final params: {"temperature": 0.7, "max_tokens": 500, "top_p": 0.95}
+```
+
+**With `ignore_prompt_manager_optional_params: true`:**
+
+Only client params are used:
+```python
+# Prompt returns: {"temperature": 0.7, "max_tokens": 500}
+# Client sends: {"temperature": 0.9, "top_p": 0.95}
+# Final params: {"temperature": 0.9, "top_p": 0.95}
+```
+
+## Security Considerations
+
+1. **Authentication**: Use the `api_key` parameter to secure your prompt management API
+2. **Authorization**: Implement team/user-based access control using the custom query parameters
+3. **Rate Limiting**: Add rate limiting to prevent abuse of your API
+4. **Input Validation**: Validate all query parameters before processing
+5. **HTTPS**: Always use HTTPS in production for encrypted communication
+6. **Secrets**: Store API keys in environment variables, not in config files
+
+## Use Cases
+
+✅ **Use Generic Prompt Management API when:**
+- You want instant integration without waiting for PRs
+- You maintain your own prompt management service
+- You need full control over prompt versioning and updates
+- You want to build custom prompt management features
+- You need to integrate with your internal systems
+
+✅ **Common scenarios:**
+- Internal prompt management system for your organization
+- Multi-tenant prompt management with team-based access control
+- A/B testing different prompt versions
+- Prompt experimentation and analytics
+- Integration with existing prompt engineering workflows
+
+## When to Use This
+
+✅ **Use Generic Prompt Management API when:**
+- You want instant integration without waiting for PRs
+- You maintain your own prompt management service
+- You need full control over updates and features
+- You want custom prompt storage and versioning logic
+
+❌ **Make a PR when:**
+- You want deeper integration with LiteLLM internals
+- Your integration requires complex LiteLLM-specific logic
+- You want to be featured as a built-in provider
+- You're building a reusable integration for the community
+
+## Troubleshooting
+
+### Prompt not found
+- Verify the `prompt_id` matches exactly (case-sensitive)
+- Check that your API endpoint is accessible from LiteLLM
+- Verify authentication if using `api_key`
+
+### Variables not substituted
+- Ensure variables use `{variable}` or `{{variable}}` syntax
+- Check that variable names in `prompt_variables` match template exactly
+- Variables are case-sensitive
+
+### Model not being overridden
+- Check if `ignore_prompt_manager_model: true` is set in config
+- Verify your API is returning `prompt_template_model` in the response
+
+### Parameters not being applied
+- Check if `ignore_prompt_manager_optional_params: true` is set
+- Verify your API is returning `prompt_template_optional_params`
+- Ensure parameter names match OpenAI's parameter names
+
+## Questions?
+
+This is a **beta API**. We're actively improving it based on feedback. Open an issue or PR if you need additional capabilities.
+
+## Related Documentation
+
+- [Prompt Management Overview](../proxy/prompt_management.md)
+- [Generic Guardrail API](./generic_guardrail_api.md)
+- [LiteLLM Proxy Setup](../proxy/quick_start.md)
+
diff --git a/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md b/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md
index 9c654cd1560..884a7397bde 100644
--- a/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md
+++ b/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md
@@ -101,12 +101,11 @@ model_list:
- model_name: gpt-4
litellm_params:
model: gpt-4
- api_key: os.environ/OPENAI_API_KEY
+ api_key: os.environ/OPENAI_API_KEY
-litellm_settings:
- guardrails:
+guardrails:
- guardrail_name: my_guardrail
- litellm_params:
+ litellm_params:
guardrail: my_guardrail
mode: during_call
api_key: os.environ/MY_GUARDRAIL_API_KEY
diff --git a/docs/my-website/docs/benchmarks.md b/docs/my-website/docs/benchmarks.md
index 640212808bd..1f818cef498 100644
--- a/docs/my-website/docs/benchmarks.md
+++ b/docs/my-website/docs/benchmarks.md
@@ -5,6 +5,13 @@ import Image from '@theme/IdealImage';
Benchmarks for LiteLLM Gateway (Proxy Server) tested against a fake OpenAI endpoint.
+## Setting Up a Fake OpenAI Endpoint
+
+For load testing and benchmarking, you can use a fake OpenAI proxy server. LiteLLM provides:
+
+1. **Hosted endpoint**: Use our free hosted fake endpoint at `https://exampleopenaiendpoint-production.up.railway.app/`
+2. **Self-hosted**: Set up your own fake OpenAI proxy server using [github.com/BerriAI/example_openai_endpoint](https://github.com/BerriAI/example_openai_endpoint)
+
Use this config for testing:
```yaml
@@ -12,7 +19,7 @@ model_list:
- model_name: "fake-openai-endpoint"
litellm_params:
model: openai/any
- api_base: https://your-fake-openai-endpoint.com/chat/completions
+ api_base: https://exampleopenaiendpoint-production.up.railway.app/ # or your self-hosted endpoint
api_key: "test"
```
@@ -48,6 +55,28 @@ In these tests the baseline latency characteristics are measured against a fake-
- High-percentile latencies drop significantly: P95 630 ms → 150 ms, P99 1,200 ms → 240 ms.
- Setting workers equal to CPU count gives optimal performance.
+## `/realtime` API Benchmarks
+
+End-to-end latency benchmarks for the `/realtime` endpoint tested against a fake realtime endpoint.
+
+### Performance Metrics
+
+| Metric | Value |
+| --------------- | ---------- |
+| Median latency | 59 ms |
+| p95 latency | 67 ms |
+| p99 latency | 99 ms |
+| Average latency | 63 ms |
+| RPS | 1,207 |
+
+### Test Setup
+
+| Category | Specification |
+|----------|---------------|
+| **Load Testing** | Locust: 1,000 concurrent users, 500 ramp-up |
+| **System** | 4 vCPUs, 8 GB RAM, 4 workers, 4 instances |
+| **Database** | PostgreSQL (Redis unused) |
+
## Machine Spec used for testing
Each machine deploying LiteLLM had the following specs:
diff --git a/docs/my-website/docs/completion/message_sanitization.md b/docs/my-website/docs/completion/message_sanitization.md
new file mode 100644
index 00000000000..17482c59339
--- /dev/null
+++ b/docs/my-website/docs/completion/message_sanitization.md
@@ -0,0 +1,465 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Message Sanitization for Tool Calling for anthropic models
+
+**Automatically fix common message formatting issues when using tool calling with `modify_params=True`**
+
+LiteLLM can automatically sanitize messages to handle common issues that occur during tool calling workflows, especially when using OpenAI-compatible clients with providers that have strict message format requirements (like Anthropic Claude).
+
+## Overview
+
+When `litellm.modify_params = True` is enabled, LiteLLM automatically sanitizes messages to fix three common issues:
+
+1. **Orphaned Tool Calls** - Assistant messages with tool_calls but missing tool results
+2. **Orphaned Tool Results** - Tool messages that reference non-existent tool_call_ids
+3. **Empty Message Content** - Messages with empty or whitespace-only text content
+
+This ensures your tool calling workflows work seamlessly across different LLM providers without manual message validation.
+
+## Why Message Sanitization?
+
+Different LLM providers have varying requirements for message formats, especially during tool calling:
+
+- **Anthropic Claude** requires every tool_call to have a corresponding tool result
+- Some providers reject messages with empty content
+- OpenAI-compatible clients may not always maintain perfect message consistency
+
+Without sanitization, these issues cause API errors that interrupt your workflows. With `modify_params=True`, LiteLLM handles these edge cases automatically.
+
+## Quick Start
+
+
+
+
+```python
+import litellm
+
+# Enable automatic message sanitization
+litellm.modify_params = True
+
+# This will work even if messages have formatting issues
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=[
+ {"role": "user", "content": "What's the weather in Boston?"},
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": "call_123",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Boston"}'}
+ }
+ ]
+ # Missing tool result - LiteLLM will add a dummy result automatically
+ },
+ {"role": "user", "content": "Thanks!"}
+ ],
+ tools=[{
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get weather for a city",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"]
+ }
+ }
+ }]
+)
+```
+
+
+
+
+```yaml
+litellm_settings:
+ modify_params: true # Enable automatic message sanitization
+
+model_list:
+ - model_name: claude-3-5-sonnet
+ litellm_params:
+ model: anthropic/claude-3-5-sonnet-20241022
+```
+
+
+
+
+## Sanitization Cases
+
+### Case A: Orphaned Tool Calls (Missing Tool Results)
+
+**Problem:** An assistant message contains `tool_calls`, but no corresponding tool result messages follow.
+
+**Solution:** LiteLLM automatically adds dummy tool result messages for any missing tool results.
+
+**Example:**
+
+```python
+import litellm
+litellm.modify_params = True
+
+# Messages with orphaned tool calls
+messages = [
+ {"role": "user", "content": "Search for Python tutorials"},
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": "call_abc123",
+ "type": "function",
+ "function": {"name": "web_search", "arguments": '{"query": "Python tutorials"}'}
+ }
+ ]
+ },
+ # Missing tool result here!
+ {"role": "user", "content": "What about JavaScript?"}
+]
+
+# LiteLLM automatically adds:
+# {
+# "role": "tool",
+# "tool_call_id": "call_abc123",
+# "content": "[System: Tool execution skipped/interrupted by user. No result provided for tool 'web_search'.]"
+# }
+
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=messages,
+ tools=[...]
+)
+```
+
+**When this happens:**
+- User interrupts tool execution
+- Client loses tool results due to network issues
+- Conversation flow changes before tool completes
+- Multi-turn conversations where tools are optional
+
+### Case B: Orphaned Tool Results (Invalid tool_call_id)
+
+**Problem:** A tool message references a `tool_call_id` that doesn't exist in any previous assistant message.
+
+**Solution:** LiteLLM automatically removes these orphaned tool result messages.
+
+**Example:**
+
+```python
+import litellm
+litellm.modify_params = True
+
+# Messages with orphaned tool result
+messages = [
+ {"role": "user", "content": "Hello"},
+ {"role": "assistant", "content": "Hi! How can I help?"},
+ {
+ "role": "tool",
+ "tool_call_id": "call_nonexistent", # This tool_call_id doesn't exist!
+ "content": "Some result"
+ }
+]
+
+# LiteLLM automatically removes the orphaned tool message
+
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=messages
+)
+```
+
+**When this happens:**
+- Message history is manually edited
+- Tool results are duplicated or mismatched
+- Conversation state is restored incorrectly
+- Messages are merged from different conversations
+
+### Case C: Empty Message Content
+
+**Problem:** User or assistant messages have empty or whitespace-only content.
+
+**Solution:** LiteLLM replaces empty content with a system placeholder message.
+
+**Example:**
+
+```python
+import litellm
+litellm.modify_params = True
+
+# Messages with empty content
+messages = [
+ {"role": "user", "content": ""}, # Empty content
+ {"role": "assistant", "content": " "}, # Whitespace only
+]
+
+# LiteLLM automatically replaces with:
+# {"role": "user", "content": "[System: Empty message content sanitised to satisfy protocol]"}
+# {"role": "assistant", "content": "[System: Empty message content sanitised to satisfy protocol]"}
+
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=messages
+)
+```
+
+**When this happens:**
+- UI sends empty messages
+- Content is stripped during preprocessing
+- Placeholder messages in conversation history
+- Edge cases in message construction
+
+## Configuration
+
+### Enable Globally
+
+
+
+
+```python
+import litellm
+
+# Enable for all completion calls
+litellm.modify_params = True
+```
+
+
+
+
+```yaml
+litellm_settings:
+ modify_params: true
+```
+
+
+
+
+```bash
+export LITELLM_MODIFY_PARAMS=True
+```
+
+
+
+
+### Enable Per-Request
+
+```python
+import litellm
+
+# Enable only for specific requests
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=messages,
+ modify_params=True # Override global setting
+)
+```
+
+## Supported Providers
+
+Message sanitization currently works with:
+
+- ✅ Anthropic (Claude)
+
+**Note:** While the sanitization logic is provider-agnostic, it is currently only applied in the Anthropic message transformation pipeline. Support for additional providers may be added in future releases.
+
+## Implementation Details
+
+### How It Works
+
+The message sanitization process runs **before** messages are converted to provider-specific formats:
+
+1. **Input:** OpenAI-format messages with potential issues
+2. **Sanitization:** Three helper functions process the messages:
+ - `_sanitize_empty_text_content()` - Fixes empty content
+ - `_add_missing_tool_results()` - Adds dummy tool results
+ - `_is_orphaned_tool_result()` - Identifies orphaned results
+3. **Output:** Clean, provider-compatible messages
+
+### Code Reference
+
+The sanitization logic is implemented in:
+- `litellm/litellm_core_utils/prompt_templates/factory.py`
+- Function: `sanitize_messages_for_tool_calling()`
+
+### Logging
+
+When sanitization occurs, LiteLLM logs debug messages:
+
+```python
+import litellm
+litellm.set_verbose = True # Enable debug logging
+
+# You'll see logs like:
+# "_add_missing_tool_results: Found 1 orphaned tool calls. Adding dummy tool results."
+# "_is_orphaned_tool_result: Found orphaned tool result with tool_call_id=call_123"
+# "_sanitize_empty_text_content: Replaced empty text content in user message"
+```
+
+## Best Practices
+
+### 1. Enable for Production Workflows
+
+```python
+# Recommended for production
+litellm.modify_params = True
+
+# Ensures robust handling of edge cases
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=messages,
+ tools=tools
+)
+```
+
+### 2. Preserve Tool Results When Possible
+
+While sanitization handles missing tool results, it's better to provide actual results:
+
+```python
+# Good: Provide actual tool results
+messages = [
+ {"role": "user", "content": "Search for Python"},
+ {"role": "assistant", "tool_calls": [...]},
+ {"role": "tool", "tool_call_id": "call_123", "content": "Actual search results"}
+]
+
+# Fallback: Sanitization adds dummy result if missing
+messages = [
+ {"role": "user", "content": "Search for Python"},
+ {"role": "assistant", "tool_calls": [...]},
+ # Missing tool result - sanitization adds dummy
+]
+```
+
+### 3. Monitor Sanitization Events
+
+Use logging to track when sanitization occurs:
+
+```python
+import litellm
+import logging
+
+# Enable debug logging
+litellm.set_verbose = True
+logging.basicConfig(level=logging.DEBUG)
+
+# Track sanitization events in your application
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=messages
+)
+```
+
+### 4. Test Edge Cases
+
+Ensure your application handles sanitized messages correctly:
+
+```python
+import litellm
+litellm.modify_params = True
+
+# Test orphaned tool calls
+test_messages = [
+ {"role": "user", "content": "Test"},
+ {"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "test", "arguments": "{}"}}]},
+ {"role": "user", "content": "Continue"} # No tool result
+]
+
+response = litellm.completion(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ messages=test_messages,
+ tools=[...]
+)
+
+# Verify the response handles the dummy tool result appropriately
+```
+
+## Related Features
+
+- **[Drop Params](./drop_params.md)** - Drop unsupported parameters for specific providers
+- **[Message Trimming](./message_trimming.md)** - Trim messages to fit token limits
+- **[Function Calling](./function_call.md)** - Complete guide to tool/function calling
+- **[Reasoning Content](../reasoning_content.md)** - Extended thinking with tool calling
+
+## Troubleshooting
+
+### Sanitization Not Working
+
+**Issue:** Messages still cause errors despite `modify_params=True`
+
+**Solution:**
+1. Verify `modify_params` is enabled:
+ ```python
+ import litellm
+ print(litellm.modify_params) # Should be True
+ ```
+
+2. Check if the issue is provider-specific:
+ ```python
+ litellm.set_verbose = True # Enable debug logging
+ ```
+
+3. Ensure you're using a recent version of LiteLLM:
+ ```bash
+ pip install --upgrade litellm
+ ```
+
+### Unexpected Dummy Tool Results
+
+**Issue:** Dummy tool results appear when you expect actual results
+
+**Cause:** Tool result messages are missing or have incorrect `tool_call_id`
+
+**Solution:**
+1. Verify tool result messages have correct `tool_call_id`:
+ ```python
+ # Correct
+ {"role": "tool", "tool_call_id": "call_123", "content": "result"}
+
+ # Incorrect - will be treated as orphaned
+ {"role": "tool", "tool_call_id": "wrong_id", "content": "result"}
+ ```
+
+2. Ensure tool results immediately follow assistant messages with tool_calls
+
+### Performance Impact
+
+**Issue:** Concerned about performance overhead
+
+**Details:** Message sanitization has minimal performance impact:
+- Runs in O(n) time where n = number of messages
+- Only processes messages when `modify_params=True`
+- Typically adds < 1ms to request processing time
+
+## FAQ
+
+**Q: Does sanitization modify my original messages?**
+
+A: No, sanitization creates a new list of messages. Your original messages remain unchanged.
+
+**Q: Can I disable specific sanitization cases?**
+
+A: Currently, all three cases are handled together when `modify_params=True`. To disable sanitization entirely, set `modify_params=False`.
+
+**Q: What happens to the dummy tool results?**
+
+A: Dummy tool results are sent to the LLM provider along with other messages. The model sees them as regular tool results with informative error messages.
+
+**Q: Does this work with streaming?**
+
+A: Yes, message sanitization works with both streaming and non-streaming requests.
+
+**Q: Is this related to `drop_params`?**
+
+A: No, they're separate features:
+- `modify_params` - Modifies/fixes message content and structure
+- `drop_params` - Removes unsupported API parameters
+
+Both can be enabled simultaneously.
+
+## See Also
+
+- [Reasoning Content with Tool Calling](../reasoning_content.md)
+- [Function Calling Guide](./function_call.md)
+- [Bedrock Provider Documentation](../providers/bedrock.md)
+- [Anthropic Provider Documentation](../providers/anthropic.md)
diff --git a/docs/my-website/docs/completion/web_search.md b/docs/my-website/docs/completion/web_search.md
index db50c7b5bc5..1f5ba2dee4e 100644
--- a/docs/my-website/docs/completion/web_search.md
+++ b/docs/my-website/docs/completion/web_search.md
@@ -18,16 +18,46 @@ Each provider uses their own search backend:
| Provider | Search Engine | Notes |
|----------|---------------|-------|
-| **OpenAI** (`gpt-4o-search-preview`) | OpenAI's internal search | Real-time web data |
+| **OpenAI** (`gpt-5-search-api`, `gpt-4o-search-preview`, `gpt-4o-mini-search-preview`) | OpenAI's internal search | Real-time web data |
| **xAI** (`grok-3`) | xAI's search + X/Twitter | Real-time social media data |
| **Google AI/Vertex** (`gemini-2.0-flash`) | **Google Search** | Uses actual Google search results |
| **Anthropic** (`claude-3-5-sonnet`) | Anthropic's web search | Real-time web data |
| **Perplexity** | Perplexity's search engine | AI-powered search and reasoning |
+:::warning Important: Only Search Models Support `web_search_options`
+For OpenAI, only dedicated search models support the `web_search_options` parameter:
+- `gpt-4o-search-preview`
+- `gpt-4o-mini-search-preview`
+- `gpt-5-search-api`
+
+**Regular models like `gpt-5`, `gpt-4.1`, `gpt-4o` do not support `web_search_options`**
+:::
+
+:::tip The `web_search_options` parameter is optional
+Search models (like `gpt-4o-search-preview`) **automatically search the web** even without the `web_search_options` parameter.
+
+Use `web_search_options` when you need to:
+- Adjust `search_context_size` (`"low"`, `"medium"`, `"high"`)
+- Specify `user_location` for localized results
+:::
+
:::info
**Anthropic Web Search Models**: Claude models that support web search: `claude-3-5-sonnet-latest`, `claude-3-5-sonnet-20241022`, `claude-3-5-haiku-latest`, `claude-3-5-haiku-20241022`, `claude-3-7-sonnet-20250219`
:::
+## OpenAI Web Search: Two Approaches
+
+OpenAI offers two distinct ways to use web search depending on the endpoint and model:
+
+| Approach | Endpoint | Models | How to enable |
+|----------|----------|--------|---------------|
+| **Search Models** | `/chat/completions` | `gpt-5-search-api`, `gpt-4o-search-preview`, `gpt-4o-mini-search-preview` | Pass `web_search_options` parameter |
+| **Web Search Tool** | `/responses` | `gpt-5`, `gpt-4.1`, `gpt-4o`, and other regular models | Pass `web_search_preview` tool |
+
+:::tip Search models search automatically
+Search models like `gpt-5-search-api` **automatically search the web** even without the `web_search_options` parameter. Use `web_search_options` to set `search_context_size` (`"low"`, `"medium"`, `"high"`) or specify `user_location` for localized results.
+:::
+
## `/chat/completions` (litellm.completion)
### Quick Start
@@ -39,7 +69,7 @@ Each provider uses their own search backend:
from litellm import completion
response = completion(
- model="openai/gpt-4o-search-preview",
+ model="openai/gpt-5-search-api",
messages=[
{
"role": "user",
@@ -59,31 +89,36 @@ response = completion(
```yaml
model_list:
- # OpenAI
+ # OpenAI search models
+ - model_name: gpt-5-search-api
+ litellm_params:
+ model: openai/gpt-5-search-api
+ api_key: os.environ/OPENAI_API_KEY
+
- model_name: gpt-4o-search-preview
litellm_params:
model: openai/gpt-4o-search-preview
api_key: os.environ/OPENAI_API_KEY
-
+
# xAI
- model_name: grok-3
litellm_params:
model: xai/grok-3
api_key: os.environ/XAI_API_KEY
-
+
# Anthropic
- model_name: claude-3-5-sonnet-latest
litellm_params:
model: anthropic/claude-3-5-sonnet-latest
api_key: os.environ/ANTHROPIC_API_KEY
-
+
# VertexAI
- model_name: gemini-2-flash
litellm_params:
model: gemini-2.0-flash
vertex_project: your-project-id
vertex_location: us-central1
-
+
# Google AI Studio
- model_name: gemini-2-flash-studio
litellm_params:
@@ -91,13 +126,13 @@ model_list:
api_key: os.environ/GOOGLE_API_KEY
```
-2. Start the proxy
+2. Start the proxy
```bash
litellm --config /path/to/config.yaml
```
-3. Test it!
+3. Test it!
```python showLineNumbers
from openai import OpenAI
@@ -109,13 +144,18 @@ client = OpenAI(
)
response = client.chat.completions.create(
- model="grok-3", # or any other web search enabled model
+ model="gpt-5-search-api", # or any other web search enabled model
messages=[
{
"role": "user",
"content": "What was a positive news story from today?"
}
- ]
+ ],
+ extra_body={
+ "web_search_options": {
+ "search_context_size": "medium"
+ }
+ }
)
```
@@ -132,7 +172,7 @@ from litellm import completion
# Customize search context size
response = completion(
- model="openai/gpt-4o-search-preview",
+ model="openai/gpt-5-search-api",
messages=[
{
"role": "user",
@@ -240,6 +280,12 @@ response = client.chat.completions.create(
## `/responses` (litellm.responses)
+Use the `web_search_preview` tool with models like `gpt-5`, `gpt-4.1`, `gpt-4o`, etc.
+
+:::info
+Search-dedicated models like `gpt-5-search-api` and `gpt-4o-search-preview` do **not** support the `/responses` endpoint. Use them with `/chat/completions` + `web_search_options` instead (see above).
+:::
+
### Quick Start
@@ -249,18 +295,14 @@ response = client.chat.completions.create(
from litellm import responses
response = responses(
- model="openai/gpt-4o",
- input=[
- {
- "role": "user",
- "content": "What was a positive news story from today?"
- }
- ],
+ model="openai/gpt-5",
+ input="What is the capital of France?",
tools=[{
"type": "web_search_preview" # enables web search with default medium context size
}]
)
```
+
@@ -268,19 +310,24 @@ response = responses(
```yaml
model_list:
- - model_name: gpt-4o
+ - model_name: gpt-5
litellm_params:
- model: openai/gpt-4o
+ model: openai/gpt-5
+ api_key: os.environ/OPENAI_API_KEY
+
+ - model_name: gpt-4.1
+ litellm_params:
+ model: openai/gpt-4.1
api_key: os.environ/OPENAI_API_KEY
```
-2. Start the proxy
+2. Start the proxy
```bash
litellm --config /path/to/config.yaml
```
-3. Test it!
+3. Test it!
```python showLineNumbers
from openai import OpenAI
@@ -292,11 +339,11 @@ client = OpenAI(
)
response = client.responses.create(
- model="gpt-4o",
+ model="gpt-5",
tools=[{
"type": "web_search_preview"
}],
- input="What was a positive news story from today?",
+ input="What is the capital of France?",
)
print(response.output_text)
@@ -314,13 +361,8 @@ from litellm import responses
# Customize search context size
response = responses(
- model="openai/gpt-4o",
- input=[
- {
- "role": "user",
- "content": "What was a positive news story from today?"
- }
- ],
+ model="openai/gpt-5",
+ input="What is the capital of France?",
tools=[{
"type": "web_search_preview",
"search_context_size": "low" # Options: "low", "medium" (default), "high"
@@ -341,12 +383,12 @@ client = OpenAI(
# Customize search context size
response = client.responses.create(
- model="gpt-4o",
+ model="gpt-5",
tools=[{
"type": "web_search_preview",
"search_context_size": "low" # Options: "low", "medium" (default), "high"
}],
- input="What was a positive news story from today?",
+ input="What is the capital of France?",
)
print(response.output_text)
@@ -400,14 +442,14 @@ model_list:
web_search_options:
search_context_size: "high" # Options: "low", "medium", "high"
- # Different context size for different models
- - model_name: gpt-4o-search-preview
+ # OpenAI search model with custom context size
+ - model_name: gpt-5-search-api
litellm_params:
- model: openai/gpt-4o-search-preview
+ model: openai/gpt-5-search-api
api_key: os.environ/OPENAI_API_KEY
web_search_options:
search_context_size: "low"
-
+
# Gemini with medium context (default)
- model_name: gemini-2-flash
litellm_params:
@@ -432,6 +474,7 @@ Use `litellm.supports_web_search(model="model_name")` -> returns `True` if model
```python showLineNumbers
# Check OpenAI models
+assert litellm.supports_web_search(model="openai/gpt-5-search-api") == True
assert litellm.supports_web_search(model="openai/gpt-4o-search-preview") == True
# Check xAI models
@@ -455,13 +498,20 @@ assert litellm.supports_web_search(model="gemini/gemini-2.0-flash") == True
```yaml
model_list:
# OpenAI
+ - model_name: gpt-5-search-api
+ litellm_params:
+ model: openai/gpt-5-search-api
+ api_key: os.environ/OPENAI_API_KEY
+ model_info:
+ supports_web_search: True
+
- model_name: gpt-4o-search-preview
litellm_params:
model: openai/gpt-4o-search-preview
api_key: os.environ/OPENAI_API_KEY
model_info:
supports_web_search: True
-
+
# xAI
- model_name: grok-3
litellm_params:
@@ -516,6 +566,12 @@ Expected Response
```json showLineNumbers
{
"data": [
+ {
+ "model_group": "gpt-5-search-api",
+ "providers": ["openai"],
+ "max_tokens": 128000,
+ "supports_web_search": true
+ },
{
"model_group": "gpt-4o-search-preview",
"providers": ["openai"],
diff --git a/docs/my-website/docs/enterprise.md b/docs/my-website/docs/enterprise.md
index 2eed0f53e59..0a1b47f0621 100644
--- a/docs/my-website/docs/enterprise.md
+++ b/docs/my-website/docs/enterprise.md
@@ -74,6 +74,18 @@ You can find [supported data regions litellm here](../docs/data_security#support
## Frequently Asked Questions
+### How to set up and verify your Enterprise License
+
+1. Add your license key to the environment:
+
+```env
+LITELLM_LICENSE="eyJ..."
+```
+
+2. Restart LiteLLM Proxy.
+
+3. Open `http://:/` — the Swagger page should show **"Enterprise Edition"** in the description. If it doesn't, check that the key is correct, unexpired, and that the proxy was fully restarted.
+
### SLA's + Professional Support
Professional Support can assist with LLM/Provider integrations, deployment, upgrade management, and LLM Provider troubleshooting. We can’t solve your own infrastructure-related issues but we will guide you to fix them.
diff --git a/docs/my-website/docs/evals_api.md b/docs/my-website/docs/evals_api.md
new file mode 100644
index 00000000000..bb66e9fdc0a
--- /dev/null
+++ b/docs/my-website/docs/evals_api.md
@@ -0,0 +1,441 @@
+# /evals
+
+LiteLLM Proxy supports OpenAI's Evaluations (Evals) API, allowing you to create, manage, and run evaluations to measure model performance against defined testing criteria.
+
+## What are Evals?
+
+OpenAI Evals API provides a structured way to:
+- **Create Evaluations**: Define testing criteria and data sources for evaluating model outputs
+- **Run Evaluations**: Execute evaluations against specific models and datasets
+- **Track Results**: Monitor evaluation progress and review detailed results
+
+## Quick Start
+
+### Setup LiteLLM Proxy
+
+First, start your LiteLLM Proxy server:
+
+```bash
+litellm --config config.yaml
+
+# Proxy will run on http://localhost:4000
+```
+
+### Initialize OpenAI Client
+
+```python
+from openai import OpenAI
+
+# Point to your LiteLLM Proxy
+client = OpenAI(
+ api_key="sk-1234", # Your LiteLLM proxy API key
+ base_url="http://localhost:4000" # Your proxy URL
+)
+```
+
+
+For async operations:
+
+```python
+from openai import AsyncOpenAI
+
+client = AsyncOpenAI(
+ api_key="sk-1234",
+ base_url="http://localhost:4000"
+)
+```
+
+---
+
+## Evaluation Management
+
+### Create an Evaluation
+
+Create an evaluation with testing criteria and data source configuration.
+
+#### Example: Sentiment Classification Eval
+
+```python
+from openai import OpenAI
+
+client = OpenAI(
+ api_key="sk-1234",
+ base_url="http://localhost:4000"
+)
+
+# Create evaluation with label model grader
+eval_obj = client.evals.create(
+ name="Sentiment Classification",
+ data_source_config={
+ "type": "stored_completions",
+ "metadata": {"usecase": "chatbot"}
+ },
+ testing_criteria=[
+ {
+ "type": "label_model",
+ "model": "gpt-4o-mini",
+ "input": [
+ {
+ "role": "developer",
+ "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'"
+ },
+ {
+ "role": "user",
+ "content": "Statement: {{item.input}}"
+ }
+ ],
+ "passing_labels": ["positive"],
+ "labels": ["positive", "neutral", "negative"],
+ "name": "Sentiment Grader"
+ }
+ ]
+)
+
+# Note: If you want to use model-specific credentials for this evaluation, you can specify the model name in the extra body parameters.
+
+print(f"Created eval: {eval_obj.id}")
+print(f"Eval name: {eval_obj.name}")
+```
+
+#### Example: Push Notifications Summarizer Monitoring
+
+This example shows how to monitor prompt changes for regressions in a push notifications summarizer:
+
+```python
+from openai import AsyncOpenAI
+
+client = AsyncOpenAI(
+ api_key="sk-1234",
+ base_url="http://localhost:4000"
+)
+
+# Define data source for stored completions
+data_source_config = {
+ "type": "stored_completions",
+ "metadata": {
+ "usecase": "push_notifications_summarizer"
+ }
+}
+
+# Define grader criteria
+GRADER_DEVELOPER_PROMPT = """
+Label the following push notification summary as either correct or incorrect.
+The push notification and the summary will be provided below.
+A good push notification summary is concise and snappy.
+If it is good, then label it as correct, if not, then incorrect.
+"""
+
+GRADER_TEMPLATE_PROMPT = """
+Push notifications: {{item.input}}
+Summary: {{sample.output_text}}
+"""
+
+push_notification_grader = {
+ "name": "Push Notification Summary Grader",
+ "type": "label_model",
+ "model": "gpt-4o-mini",
+ "input": [
+ {
+ "role": "developer",
+ "content": GRADER_DEVELOPER_PROMPT,
+ },
+ {
+ "role": "user",
+ "content": GRADER_TEMPLATE_PROMPT,
+ },
+ ],
+ "passing_labels": ["correct"],
+ "labels": ["correct", "incorrect"],
+}
+
+# Create the evaluation
+eval_result = await client.evals.create(
+ name="Push Notification Completion Monitoring",
+ metadata={"description": "This eval monitors completions"},
+ data_source_config=data_source_config,
+ testing_criteria=[push_notification_grader],
+)
+
+eval_id = eval_result.id
+print(f"Created eval: {eval_id}")
+```
+
+### List Evaluations
+
+Retrieve a list of all your evaluations with pagination support.
+
+```python
+# List all evaluations
+evals_response = client.evals.list(
+ limit=20,
+ order="desc"
+)
+
+for eval in evals_response.data:
+ print(f"Eval ID: {eval.id}, Name: {eval.name}")
+
+# Check if there are more evals
+if evals_response.has_more:
+ # Fetch next page
+ next_evals = client.evals.list(
+ after=evals_response.last_id,
+ limit=20
+ )
+```
+
+### Get a Specific Evaluation
+
+Retrieve details of a specific evaluation by ID.
+
+```python
+eval = client.evals.retrieve(
+ eval_id="eval_abc123"
+)
+
+print(f"Eval ID: {eval.id}")
+print(f"Name: {eval.name}")
+print(f"Data Source: {eval.data_source_config}")
+print(f"Testing Criteria: {eval.testing_criteria}")
+```
+
+### Update an Evaluation
+
+Update evaluation metadata or name.
+
+```python
+updated_eval = client.evals.update(
+ eval_id="eval_abc123",
+ name="Updated Evaluation Name",
+ metadata={
+ "version": "2.0",
+ "updated_by": "user@example.com"
+ }
+)
+
+print(f"Updated eval: {updated_eval.name}")
+```
+
+### Delete an Evaluation
+
+Permanently delete an evaluation.
+
+```python
+delete_response = client.evals.delete(
+ eval_id="eval_abc123"
+)
+
+print(f"Deleted: {delete_response.deleted}") # True
+```
+
+---
+
+## Evaluation Runs
+
+### Create a Run
+
+Execute an evaluation by creating a run. The run processes your data through the model and applies testing criteria.
+
+#### Using Stored Completions
+
+First, generate some test data by making chat completions with metadata:
+
+```python
+from openai import AsyncOpenAI
+import asyncio
+
+client = AsyncOpenAI(
+ api_key="sk-1234",
+ base_url="http://localhost:4000"
+)
+
+# Generate test data with different prompt versions
+push_notification_data = [
+ """
+- New message from Sarah: "Can you call me later?"
+- Your package has been delivered!
+- Flash sale: 20% off electronics for the next 2 hours!
+""",
+ """
+- Weather alert: Thunderstorm expected in your area.
+- Reminder: Doctor's appointment at 3 PM.
+- John liked your photo on Instagram.
+"""
+]
+
+PROMPTS = [
+ (
+ """
+ You are a helpful assistant that summarizes push notifications.
+ You are given a list of push notifications and you need to collapse them into a single one.
+ Output only the final summary, nothing else.
+ """,
+ "v1"
+ ),
+ (
+ """
+ You are a helpful assistant that summarizes push notifications.
+ You are given a list of push notifications and you need to collapse them into a single one.
+ The summary should be longer than it needs to be and include more information than is necessary.
+ Output only the final summary, nothing else.
+ """,
+ "v2"
+ )
+]
+
+# Create completions with metadata for tracking
+tasks = []
+for notifications in push_notification_data:
+ for (prompt, version) in PROMPTS:
+ tasks.append(client.chat.completions.create(
+ model="gpt-4o-mini",
+ messages=[
+ {"role": "developer", "content": prompt},
+ {"role": "user", "content": notifications},
+ ],
+ metadata={
+ "prompt_version": version,
+ "usecase": "push_notifications_summarizer"
+ }
+ ))
+
+await asyncio.gather(*tasks)
+```
+
+Now create runs to evaluate different prompt versions:
+
+```python
+# Grade prompt_version=v1
+eval_run_result = await client.evals.runs.create(
+ eval_id=eval_id,
+ name="v1-run",
+ data_source={
+ "type": "completions",
+ "source": {
+ "type": "stored_completions",
+ "metadata": {
+ "prompt_version": "v1",
+ }
+ }
+ }
+)
+
+print(f"Run ID: {eval_run_result.id}")
+print(f"Status: {eval_run_result.status}")
+print(f"Report URL: {eval_run_result.report_url}")
+
+# Grade prompt_version=v2
+eval_run_result_v2 = await client.evals.runs.create(
+ eval_id=eval_id,
+ name="v2-run",
+ data_source={
+ "type": "completions",
+ "source": {
+ "type": "stored_completions",
+ "metadata": {
+ "prompt_version": "v2",
+ }
+ }
+ }
+)
+
+print(f"Run ID: {eval_run_result_v2.id}")
+print(f"Report URL: {eval_run_result_v2.report_url}")
+```
+
+#### Using Completions with Different Models
+
+Test how different models perform on the same inputs:
+
+```python
+# Test with GPT-4o using stored completions as input
+tasks = []
+for prompt_version in ["v1", "v2"]:
+ tasks.append(client.evals.runs.create(
+ eval_id=eval_id,
+ name=f"gpt-4o-run-{prompt_version}",
+ data_source={
+ "type": "completions",
+ "input_messages": {
+ "type": "item_reference",
+ "item_reference": "item.input",
+ },
+ "model": "gpt-4o",
+ "source": {
+ "type": "stored_completions",
+ "metadata": {
+ "prompt_version": prompt_version,
+ }
+ }
+ }
+ ))
+
+results = await asyncio.gather(*tasks)
+for run in results:
+ print(f"Report URL: {run.report_url}")
+```
+
+### List Runs
+
+Get all runs for a specific evaluation.
+
+```python
+# List all runs for an evaluation
+runs_response = client.evals.runs.list(
+ eval_id="eval_abc123",
+ limit=20,
+ order="desc"
+)
+
+for run in runs_response.data:
+ print(f"Run ID: {run.id}")
+ print(f"Status: {run.status}")
+ print(f"Name: {run.name}")
+ if run.result_counts:
+ print(f"Results: {run.result_counts.passed}/{run.result_counts.total} passed")
+```
+
+### Get Run Details
+
+Retrieve detailed information about a specific run, including results.
+
+```python
+run = client.evals.runs.retrieve(
+ eval_id="eval_abc123",
+ run_id="run_def456"
+)
+
+print(f"Run ID: {run.id}")
+print(f"Status: {run.status}")
+print(f"Started: {run.started_at}")
+print(f"Completed: {run.completed_at}")
+
+# Check results
+if run.result_counts:
+ print(f"\nOverall Results:")
+ print(f"Total: {run.result_counts.total}")
+ print(f"Passed: {run.result_counts.passed}")
+ print(f"Failed: {run.result_counts.failed}")
+ print(f"Error: {run.result_counts.errored}")
+
+# Per-criteria results
+if run.per_testing_criteria_results:
+ for criteria_result in run.per_testing_criteria_results:
+ print(f"\nCriteria {criteria_result.testing_criteria_index}:")
+ print(f" Passed: {criteria_result.result_counts.passed}")
+ print(f" Average Score: {criteria_result.average_score}")
+```
+
+### Delete a Run
+
+Permanently delete a run and its results.
+
+```python
+delete_response = await client.evals.runs.delete(
+ eval_id="eval_abc123",
+ run_id="run_def456"
+)
+
+print(f"Deleted: {delete_response.deleted}") # True
+print(f"Run ID: {delete_response.run_id}")
+```
+
diff --git a/docs/my-website/docs/extras/contributing_code.md b/docs/my-website/docs/extras/contributing_code.md
index 930a47eec7e..673a83aca05 100644
--- a/docs/my-website/docs/extras/contributing_code.md
+++ b/docs/my-website/docs/extras/contributing_code.md
@@ -1,27 +1,36 @@
# Contributing Code
-## **Checklist before submitting a PR**
+## Checklist before submitting a PR
-Here are the core requirements for any PR submitted to LiteLLM
+Here are the core requirements for any PR submitted to LiteLLM:
-- [ ] Sign the Contributor License Agreement (CLA) - [see details](#contributor-license-agreement-cla)
-- [ ] Add testing, **Adding at least 1 test is a hard requirement** - [see details](#2-adding-testing-to-your-pr)
-- [ ] Ensure your PR passes the following tests:
- - [ ] [Unit Tests](#3-running-unit-tests)
- - [ ] [Formatting / Linting Tests](#35-running-linting-tests)
-- [ ] Keep scope as isolated as possible. As a general rule, your changes should address 1 specific problem at a time
+- [ ] Sign the [Contributor License Agreement (CLA)](#contributor-license-agreement-cla)
+- [ ] Keep scope as isolated as possible — your changes should address **one specific problem** at a time
-## **Contributor License Agreement (CLA)**
+### Proxy (Backend) PRs
+
+- [ ] Add testing — **at least 1 test is a hard requirement** ([details](#2-adding-tests))
+- [ ] Ensure your PR passes:
+ - [ ] [Unit Tests](#3-running-unit-tests) — `make test-unit`
+ - [ ] [Formatting / Linting Tests](#4-running-linting-tests) — `make lint`
+
+### UI PRs
+
+- [ ] Ensure the UI builds successfully — `npm run build`
+- [ ] Ensure all UI unit tests pass — `npm run test`
+- [ ] If you are adding a **new component** or **new logic**, add corresponding tests
+
+## Contributor License Agreement (CLA)
Before contributing code to LiteLLM, you must sign our [Contributor License Agreement (CLA)](https://cla-assistant.io/BerriAI/litellm). This is a legal requirement for all contributions to be merged into the main repository. The CLA helps protect both you and the project by clearly defining the terms under which your contributions are made.
-**Important:** We strongly recommend reviewing and signing the CLA before starting work on your contribution to avoid any delays in the PR process. You can find the CLA [here](https://cla-assistant.io/BerriAI/litellm) and sign it through our CLA management system when you submit your first PR.
+**Important:** We strongly recommend signing the CLA **before** starting work on your contribution to avoid delays in the review process. You can find and sign the CLA [here](https://cla-assistant.io/BerriAI/litellm).
-## Quick start
+---
-## 1. Setup your local dev environment
+## Proxy (Backend)
-Here's how to modify the repo locally:
+### 1. Setting up your local dev environment
Step 1: Clone the repo
@@ -29,56 +38,53 @@ Step 1: Clone the repo
git clone https://github.com/BerriAI/litellm.git
```
-Step 2: Install dev dependencies:
+Step 2: Install dev dependencies
```shell
poetry install --with dev --extras proxy
```
-That's it, your local dev environment is ready!
+### 2. Adding tests
-## 2. Adding Testing to your PR
+- Add your tests to the [`tests/test_litellm/` directory](https://github.com/BerriAI/litellm/tree/main/tests/litellm).
+- This directory mirrors the `litellm/` directory 1:1 and should **only** contain mocked tests.
+- **Do not** add real LLM API calls to this directory.
-- Add your test to the [`tests/test_litellm/` directory](https://github.com/BerriAI/litellm/tree/main/tests/litellm)
+#### File naming convention for `tests/test_litellm/`
-- This directory 1:1 maps the the `litellm/` directory, and can only contain mocked tests.
-- Do not add real llm api calls to this directory.
+The test directory follows the same structure as `litellm/`:
-### 2.1 File Naming Convention for `tests/test_litellm/`
-
-The `tests/test_litellm/` directory follows the same directory structure as `litellm/`.
-
-- `litellm/proxy/test_caching_routes.py` maps to `litellm/proxy/caching_routes.py`
- `test_{filename}.py` maps to `litellm/{filename}.py`
+- `litellm/proxy/test_caching_routes.py` maps to `litellm/proxy/caching_routes.py`
-## 3. Running Unit Tests
+### 3. Running unit tests
-run the following command on the root of the litellm directory
+Run the following command from the root of the `litellm` directory:
```shell
make test-unit
```
-## 3.5 Running Linting Tests
+### 4. Running linting tests
-run the following command on the root of the litellm directory
+Run the following command from the root of the `litellm` directory:
```shell
make lint
```
-LiteLLM uses mypy for linting. On ci/cd we also run `black` for formatting.
+LiteLLM uses `mypy` for type checking. CI/CD also runs `black` for formatting.
-## 4. Submit a PR with your changes!
+### 5. Submit a PR
-- push your fork to your GitHub repo
-- submit a PR from there
+- Push your changes to your fork on GitHub
+- Open a Pull Request from your fork
-## Advanced
+---
-### Building LiteLLM Docker Image
+## UI
-Some people might want to build the LiteLLM docker image themselves. Follow these instructions if you want to build / run the LiteLLM Docker Image yourself.
+### 1. Setting up your local dev environment
Step 1: Clone the repo
@@ -86,17 +92,72 @@ Step 1: Clone the repo
git clone https://github.com/BerriAI/litellm.git
```
-Step 2: Build the Docker Image
+Step 2: Navigate to the UI dashboard directory
-Build using Dockerfile.non_root
+```shell
+cd ui/litellm-dashboard
+```
+
+Step 3: Install dependencies
+
+```shell
+npm install
+```
+
+Step 4: Start the development server
+
+```shell
+npm run dev
+```
+
+### 2. Adding tests
+
+If you are adding a **new component** or **new logic**, you must add corresponding tests.
+
+### 3. Running UI unit tests
+
+```shell
+npm run test
+```
+
+### 4. Building the UI
+
+Ensure the UI builds successfully before submitting your PR:
+
+```shell
+npm run build
+```
+
+### 5. Submit a PR
+
+- Push your changes to your fork on GitHub
+- Open a Pull Request from your fork
+
+---
+
+## Advanced
+
+### Building the LiteLLM Docker Image
+
+Follow these instructions if you want to build and run the LiteLLM Docker image yourself.
+
+Step 1: Clone the repo
+
+```shell
+git clone https://github.com/BerriAI/litellm.git
+```
+
+Step 2: Build the Docker image
+
+Build using `Dockerfile.non_root`:
```shell
docker build -f docker/Dockerfile.non_root -t litellm_test_image .
```
-Step 3: Run the Docker Image
+Step 3: Run the Docker image
-Make sure config.yaml is present in the root directory. This is your litellm proxy config file.
+Make sure `config.yaml` is present in the root directory. This is your LiteLLM proxy config file.
```shell
docker run \
@@ -107,18 +168,19 @@ docker run \
litellm_test_image \
--config /app/config.yaml --detailed_debug
```
-### Running LiteLLM Proxy Locally
-1. cd into the `proxy/` directory
+### Running the LiteLLM Proxy Locally
-```
+1. Navigate to the `proxy/` directory:
+
+```shell
cd litellm/litellm/proxy
```
-2. Run the proxy
+2. Run the proxy:
```shell
python3 proxy_cli.py --config /path/to/config.yaml
# RUNNING on http://0.0.0.0:4000
-```
\ No newline at end of file
+```
diff --git a/docs/my-website/docs/integrations/websearch_interception.md b/docs/my-website/docs/integrations/websearch_interception.md
new file mode 100644
index 00000000000..0c5d8927013
--- /dev/null
+++ b/docs/my-website/docs/integrations/websearch_interception.md
@@ -0,0 +1,411 @@
+# Web Search Integration
+
+Enable transparent server-side web search execution for any LLM provider. LiteLLM automatically intercepts web search tool calls and executes them using your configured search provider (Perplexity, Tavily, etc.).
+
+## Quick Start
+
+### 1. Configure Web Search Interception
+
+Add to your `config.yaml`:
+
+```yaml
+model_list:
+ - model_name: gpt-4o
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: os.environ/OPENAI_API_KEY
+
+litellm_settings:
+ callbacks:
+ - websearch_interception:
+ enabled_providers:
+ - openai
+ - minimax
+ - anthropic
+ search_tool_name: perplexity-search # Optional
+
+search_tools:
+ - search_tool_name: perplexity-search
+ litellm_params:
+ search_provider: perplexity
+ api_key: os.environ/PERPLEXITY_API_KEY
+```
+
+### 2. Use with Any Provider
+
+```python
+import litellm
+
+response = await litellm.acompletion(
+ model="gpt-4o",
+ messages=[
+ {"role": "user", "content": "What's the weather in San Francisco today?"}
+ ],
+ tools=[
+ {
+ "type": "function",
+ "function": {
+ "name": "litellm_web_search",
+ "description": "Search the web for information",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query"}
+ },
+ "required": ["query"]
+ }
+ }
+ }
+ ]
+)
+
+# Response includes search results automatically!
+print(response.choices[0].message.content)
+```
+
+## How It Works
+
+When a model makes a web search tool call, LiteLLM:
+
+1. **Detects** the `litellm_web_search` tool call in the response
+2. **Executes** the search using your configured search provider
+3. **Makes a follow-up request** with the search results
+4. **Returns** the final answer to the user
+
+```mermaid
+sequenceDiagram
+ participant User
+ participant LiteLLM
+ participant LLM as LLM Provider
+ participant Search as Search Provider
+
+ User->>LiteLLM: Request with web_search tool
+ LiteLLM->>LLM: Forward request
+ LLM-->>LiteLLM: Response with tool_call
+ Note over LiteLLM: Detect web search tool call
+ LiteLLM->>Search: Execute search
+ Search-->>LiteLLM: Search results
+ LiteLLM->>LLM: Follow-up with results
+ LLM-->>LiteLLM: Final answer
+ LiteLLM-->>User: Final answer with search results
+```
+
+**Result**: One API call from user → Complete answer with search results
+
+## Supported Providers
+
+Web search integration works with **all providers** that use:
+- ✅ **Base HTTP Handler** (`BaseLLMHTTPHandler`)
+- ✅ **OpenAI Completion Handler** (`OpenAIChatCompletion`)
+
+### Providers Using Base HTTP Handler
+
+| Provider | Status | Notes |
+|----------|--------|-------|
+| **OpenAI** | ✅ Supported | GPT-4, GPT-3.5, etc. |
+| **Anthropic** | ✅ Supported | Claude models via HTTP handler |
+| **MiniMax** | ✅ Supported | All MiniMax models |
+| **Mistral** | ✅ Supported | Mistral AI models |
+| **Cohere** | ✅ Supported | Command models |
+| **Fireworks AI** | ✅ Supported | All Fireworks models |
+| **Together AI** | ✅ Supported | All Together AI models |
+| **Groq** | ✅ Supported | All Groq models |
+| **Perplexity** | ✅ Supported | Perplexity models |
+| **DeepSeek** | ✅ Supported | DeepSeek models |
+| **xAI** | ✅ Supported | Grok models |
+| **Hugging Face** | ✅ Supported | Inference API models |
+| **OCI** | ✅ Supported | Oracle Cloud models |
+| **Vertex AI** | ✅ Supported | Google Vertex AI models |
+| **Bedrock** | ✅ Supported | AWS Bedrock models (converse_like route) |
+| **Azure OpenAI** | ✅ Supported | Azure-hosted OpenAI models |
+| **Sagemaker** | ✅ Supported | AWS Sagemaker models |
+| **Databricks** | ✅ Supported | Databricks models |
+| **DataRobot** | ✅ Supported | DataRobot models |
+| **Hosted VLLM** | ✅ Supported | Self-hosted VLLM |
+| **Heroku** | ✅ Supported | Heroku-hosted models |
+| **RAGFlow** | ✅ Supported | RAGFlow models |
+| **Compactif** | ✅ Supported | Compactif models |
+| **Cometapi** | ✅ Supported | Comet API models |
+| **A2A** | ✅ Supported | Agent-to-Agent models |
+| **Bytez** | ✅ Supported | Bytez models |
+
+### Providers Using OpenAI Handler
+
+| Provider | Status | Notes |
+|----------|--------|-------|
+| **OpenAI** | ✅ Supported | Native OpenAI API |
+| **Azure OpenAI** | ✅ Supported | Azure-hosted OpenAI |
+| **OpenAI-Compatible** | ✅ Supported | Any OpenAI-compatible API |
+
+## Configuration
+
+### WebSearch Interception Parameters
+
+| Parameter | Type | Required | Description | Example |
+|-----------|------|----------|-------------|---------|
+| `enabled_providers` | List[String] | Yes | List of providers to enable web search for | `[openai, minimax, anthropic]` |
+| `search_tool_name` | String | No | Specific search tool from `search_tools` config. If not set, uses first available. | `perplexity-search` |
+
+### Provider Values
+
+Use these values in `enabled_providers`:
+
+| Provider | Value | Provider | Value |
+|----------|-------|----------|-------|
+| OpenAI | `openai` | Anthropic | `anthropic` |
+| MiniMax | `minimax` | Mistral | `mistral` |
+| Cohere | `cohere` | Fireworks AI | `fireworks_ai` |
+| Together AI | `together_ai` | Groq | `groq` |
+| Perplexity | `perplexity` | DeepSeek | `deepseek` |
+| xAI | `xai` | Hugging Face | `huggingface` |
+| OCI | `oci` | Vertex AI | `vertex_ai` |
+| Bedrock | `bedrock` | Azure | `azure` |
+| Sagemaker | `sagemaker_chat` | Databricks | `databricks` |
+| DataRobot | `datarobot` | VLLM | `hosted_vllm` |
+| Heroku | `heroku` | RAGFlow | `ragflow` |
+| Compactif | `compactif` | Cometapi | `cometapi` |
+| A2A | `a2a` | Bytez | `bytez` |
+
+## Search Providers
+
+Configure which search provider to use. LiteLLM supports multiple search providers:
+
+| Provider | `search_provider` Value | Environment Variable |
+|----------|------------------------|----------------------|
+| **Perplexity AI** | `perplexity` | `PERPLEXITYAI_API_KEY` |
+| **Tavily** | `tavily` | `TAVILY_API_KEY` |
+| **Exa AI** | `exa_ai` | `EXA_API_KEY` |
+| **Parallel AI** | `parallel_ai` | `PARALLEL_AI_API_KEY` |
+| **Google PSE** | `google_pse` | `GOOGLE_PSE_API_KEY`, `GOOGLE_PSE_ENGINE_ID` |
+| **DataForSEO** | `dataforseo` | `DATAFORSEO_LOGIN`, `DATAFORSEO_PASSWORD` |
+| **Firecrawl** | `firecrawl` | `FIRECRAWL_API_KEY` |
+| **SearXNG** | `searxng` | `SEARXNG_API_BASE` (required) |
+| **Linkup** | `linkup` | `LINKUP_API_KEY` |
+
+See [Search Providers Documentation](../search/index.md) for detailed setup instructions.
+
+## Complete Configuration Example
+
+```yaml
+model_list:
+ # OpenAI
+ - model_name: gpt-4o
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: os.environ/OPENAI_API_KEY
+
+ # MiniMax
+ - model_name: minimax
+ litellm_params:
+ model: minimax/MiniMax-M2.1
+ api_key: os.environ/MINIMAX_API_KEY
+
+ # Anthropic
+ - model_name: claude
+ litellm_params:
+ model: anthropic/claude-sonnet-4-5
+ api_key: os.environ/ANTHROPIC_API_KEY
+
+ # Azure OpenAI
+ - model_name: azure-gpt4
+ litellm_params:
+ model: azure/gpt-4
+ api_base: https://my-azure.openai.azure.com
+ api_key: os.environ/AZURE_API_KEY
+
+litellm_settings:
+ callbacks:
+ - websearch_interception:
+ enabled_providers:
+ - openai
+ - minimax
+ - anthropic
+ - azure
+ search_tool_name: perplexity-search
+
+search_tools:
+ - search_tool_name: perplexity-search
+ litellm_params:
+ search_provider: perplexity
+ api_key: os.environ/PERPLEXITY_API_KEY
+
+ - search_tool_name: tavily-search
+ litellm_params:
+ search_provider: tavily
+ api_key: os.environ/TAVILY_API_KEY
+```
+
+## Usage Examples
+
+### Python SDK
+
+```python
+import litellm
+
+# Configure callbacks
+litellm.callbacks = ["websearch_interception"]
+
+# Make completion with web search tool
+response = await litellm.acompletion(
+ model="gpt-4o",
+ messages=[
+ {"role": "user", "content": "What are the latest AI news?"}
+ ],
+ tools=[
+ {
+ "type": "function",
+ "function": {
+ "name": "litellm_web_search",
+ "description": "Search the web for current information",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Search query"
+ }
+ },
+ "required": ["query"]
+ }
+ }
+ }
+ ]
+)
+
+print(response.choices[0].message.content)
+```
+
+### Proxy Server
+
+```bash
+# Start proxy with config
+litellm --config config.yaml
+
+# Make request
+curl http://localhost:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-4o",
+ "messages": [
+ {"role": "user", "content": "What is the weather in San Francisco?"}
+ ],
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "litellm_web_search",
+ "description": "Search the web",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string"}
+ },
+ "required": ["query"]
+ }
+ }
+ }
+ ]
+ }'
+```
+
+## How Search Tool Selection Works
+
+1. **If `search_tool_name` is specified** → Uses that specific search tool
+2. **If `search_tool_name` is not specified** → Uses first search tool in `search_tools` list
+
+```yaml
+search_tools:
+ - search_tool_name: perplexity-search # ← This will be used if no search_tool_name specified
+ litellm_params:
+ search_provider: perplexity
+ api_key: os.environ/PERPLEXITY_API_KEY
+
+ - search_tool_name: tavily-search
+ litellm_params:
+ search_provider: tavily
+ api_key: os.environ/TAVILY_API_KEY
+```
+
+## Troubleshooting
+
+### Web Search Not Working
+
+1. **Check provider is enabled**:
+ ```yaml
+ enabled_providers:
+ - openai # Make sure your provider is in this list
+ ```
+
+2. **Verify search tool is configured**:
+ ```yaml
+ search_tools:
+ - search_tool_name: perplexity-search
+ litellm_params:
+ search_provider: perplexity
+ api_key: os.environ/PERPLEXITY_API_KEY
+ ```
+
+3. **Check API keys are set**:
+ ```bash
+ export PERPLEXITY_API_KEY=your-key
+ ```
+
+4. **Enable debug logging**:
+ ```python
+ litellm.set_verbose = True
+ ```
+
+### Common Issues
+
+**Issue**: Model returns tool_calls instead of final answer
+- **Cause**: Provider not in `enabled_providers` list
+- **Solution**: Add provider to `enabled_providers`
+
+**Issue**: "No search tool configured" error
+- **Cause**: No search tools in `search_tools` config
+- **Solution**: Add at least one search tool configuration
+
+**Issue**: "Invalid function arguments json string" error (MiniMax)
+- **Cause**: Fixed in latest version - arguments weren't properly JSON serialized
+- **Solution**: Update to latest LiteLLM version
+
+## Related Documentation
+
+- [Search Providers](../search/index.md) - Detailed search provider setup
+- [Claude Code WebSearch](../tutorials/claude_code_websearch.md) - Using with Claude Code
+- [Tool Calling](../completion/function_call.md) - General tool calling documentation
+- [Callbacks](./custom_callback.md) - Custom callback documentation
+
+## Technical Details
+
+### Architecture
+
+Web search integration is implemented as a custom callback (`WebSearchInterceptionLogger`) that:
+
+1. **Pre-request Hook**: Converts native web search tools to LiteLLM standard format
+2. **Post-response Hook**: Detects web search tool calls in responses
+3. **Agentic Loop**: Executes searches and makes follow-up requests automatically
+
+### Supported APIs
+
+- ✅ **Chat Completions API** (OpenAI format)
+- ✅ **Anthropic Messages API** (Anthropic format)
+- ✅ **Streaming** (automatically converted)
+- ✅ **Non-streaming**
+
+### Response Format Detection
+
+The handler automatically detects response format:
+- **OpenAI format**: `tool_calls` in assistant message
+- **Anthropic format**: `tool_use` blocks in content
+
+### Performance
+
+- **Latency**: Adds one additional LLM call (follow-up request with search results)
+- **Caching**: Search results can be cached (depends on search provider)
+- **Parallel Searches**: Multiple search queries executed in parallel
+
+## Contributing
+
+Found a bug or want to add support for a new provider? See our [Contributing Guide](https://github.com/BerriAI/litellm/blob/main/CONTRIBUTING.md).
diff --git a/docs/my-website/docs/load_test.md b/docs/my-website/docs/load_test.md
index 4641a70366c..071b097904b 100644
--- a/docs/my-website/docs/load_test.md
+++ b/docs/my-website/docs/load_test.md
@@ -4,8 +4,9 @@ import Image from '@theme/IdealImage';
## Locust Load Test LiteLLM Proxy
-1. Add `fake-openai-endpoint` to your proxy config.yaml and start your litellm proxy
-litellm provides a free hosted `fake-openai-endpoint` you can load test against
+1. Add `fake-openai-endpoint` to your proxy config.yaml and start your litellm proxy.
+
+LiteLLM provides a free hosted `fake-openai-endpoint` you can load test against. You can also self-host your own fake OpenAI proxy server using [github.com/BerriAI/example_openai_endpoint](https://github.com/BerriAI/example_openai_endpoint).
```yaml
model_list:
diff --git a/docs/my-website/docs/load_test_advanced.md b/docs/my-website/docs/load_test_advanced.md
index 3171bc33594..d35b5f74784 100644
--- a/docs/my-website/docs/load_test_advanced.md
+++ b/docs/my-website/docs/load_test_advanced.md
@@ -29,12 +29,16 @@ Tutorial on how to get to 1K+ RPS with LiteLLM Proxy on locust
**Note:** we're currently migrating to aiohttp which has 10x higher throughput. We recommend using the `openai/` provider for load testing.
+:::tip Setting Up a Fake OpenAI Endpoint
+You can use our hosted fake endpoint or self-host your own using [github.com/BerriAI/example_openai_endpoint](https://github.com/BerriAI/example_openai_endpoint).
+:::
+
```yaml
model_list:
- model_name: "fake-openai-endpoint"
litellm_params:
model: openai/any
- api_base: https://your-fake-openai-endpoint.com/chat/completions
+ api_base: https://exampleopenaiendpoint-production.up.railway.app/ # or your self-hosted endpoint
api_key: "test"
```
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.md
index d63b55ee29e..84d10c25931 100644
--- a/docs/my-website/docs/mcp.md
+++ b/docs/my-website/docs/mcp.md
@@ -506,7 +506,14 @@ Your OpenAPI specification should follow standard OpenAPI/Swagger conventions:
- **Operation IDs**: Each operation should have a unique `operationId` (this becomes the tool name)
- **Parameters**: Request parameters should be properly documented with types and descriptions
-## MCP Oauth
+## MCP OAuth
+
+LiteLLM supports OAuth 2.0 for MCP servers -- both interactive (PKCE) flows for user-facing clients and machine-to-machine (M2M) `client_credentials` for backend services.
+
+See the **[MCP OAuth guide](./mcp_oauth.md)** for setup instructions, sequence diagrams, and a test server.
+
+
+Detailed OAuth reference (click to expand)
LiteLLM v 1.77.6 added support for OAuth 2.0 Client Credentials for MCP servers.
@@ -588,6 +595,8 @@ sequenceDiagram
See the official [MCP Authorization Flow](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#authorization-flow-steps) for additional reference.
+
+
## Forwarding Custom Headers to MCP Servers
@@ -1486,7 +1495,7 @@ async with stdio_client(server_params) as (read, write):
**Q: How do I use OAuth2 client_credentials (machine-to-machine) with MCP servers behind LiteLLM?**
-At the moment LiteLLM only forwards whatever `Authorization` header/value you configure for the MCP server; it does not issue OAuth2 tokens by itself. If your MCP requires the Client Credentials grant, obtain the access token directly from the authorization server and set that bearer token as the MCP server’s Authorization header value. LiteLLM does not yet fetch or refresh those machine-to-machine tokens on your behalf, but we plan to add first-class client_credentials support in a future release so the proxy can manage those tokens automatically.
+LiteLLM supports automatic token management for the `client_credentials` grant. Configure `client_id`, `client_secret`, and `token_url` on your MCP server and LiteLLM will fetch, cache, and refresh tokens automatically. See the [MCP OAuth M2M guide](./mcp_oauth.md#machine-to-machine-m2m-auth) for setup instructions.
**Q: When I fetch an OAuth token from the LiteLLM UI, where is it stored?**
diff --git a/docs/my-website/docs/mcp_oauth.md b/docs/my-website/docs/mcp_oauth.md
new file mode 100644
index 00000000000..5c4b70cc5b3
--- /dev/null
+++ b/docs/my-website/docs/mcp_oauth.md
@@ -0,0 +1,337 @@
+# MCP OAuth
+
+LiteLLM supports two OAuth 2.0 flows for MCP servers:
+
+| Flow | Use Case | How It Works |
+|------|----------|--------------|
+| **Interactive (PKCE)** | User-facing apps (Claude Code, Cursor) | Browser-based consent, per-user tokens |
+| **Machine-to-Machine (M2M)** | Backend services, CI/CD, automated agents | `client_credentials` grant, proxy-managed tokens |
+
+## Interactive OAuth (PKCE)
+
+For user-facing MCP clients (Claude Code, Cursor), LiteLLM supports the full OAuth 2.0 authorization code flow with PKCE.
+
+### Setup
+
+```yaml title="config.yaml" showLineNumbers
+mcp_servers:
+ github_mcp:
+ url: "https://api.githubcopilot.com/mcp"
+ auth_type: oauth2
+ client_id: os.environ/GITHUB_OAUTH_CLIENT_ID
+ client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET
+```
+
+[**See Claude Code Tutorial**](./tutorials/claude_responses_api#connecting-mcp-servers)
+
+### How It Works
+
+```mermaid
+sequenceDiagram
+ participant Browser as User-Agent (Browser)
+ participant Client as Client
+ participant LiteLLM as LiteLLM Proxy
+ participant MCP as MCP Server (Resource Server)
+ participant Auth as Authorization Server
+
+ Note over Client,LiteLLM: Step 1 – Resource discovery
+ Client->>LiteLLM: GET /.well-known/oauth-protected-resource/{mcp_server_name}/mcp
+ LiteLLM->>Client: Return resource metadata
+
+ Note over Client,LiteLLM: Step 2 – Authorization server discovery
+ Client->>LiteLLM: GET /.well-known/oauth-authorization-server/{mcp_server_name}
+ LiteLLM->>Client: Return authorization server metadata
+
+ Note over Client,Auth: Step 3 – Dynamic client registration
+ Client->>LiteLLM: POST /{mcp_server_name}/register
+ LiteLLM->>Auth: Forward registration request
+ Auth->>LiteLLM: Issue client credentials
+ LiteLLM->>Client: Return client credentials
+
+ Note over Client,Browser: Step 4 – User authorization (PKCE)
+ Client->>Browser: Open authorization URL + code_challenge + resource
+ Browser->>Auth: Authorization request
+ Note over Auth: User authorizes
+ Auth->>Browser: Redirect with authorization code
+ Browser->>LiteLLM: Callback to LiteLLM with code
+ LiteLLM->>Browser: Redirect back with authorization code
+ Browser->>Client: Callback with authorization code
+
+ Note over Client,Auth: Step 5 – Token exchange
+ Client->>LiteLLM: Token request + code_verifier + resource
+ LiteLLM->>Auth: Forward token request
+ Auth->>LiteLLM: Access (and refresh) token
+ LiteLLM->>Client: Return tokens
+
+ Note over Client,MCP: Step 6 – Authenticated MCP call
+ Client->>LiteLLM: MCP request with access token + LiteLLM API key
+ LiteLLM->>MCP: MCP request with Bearer token
+ MCP-->>LiteLLM: MCP response
+ LiteLLM-->>Client: Return MCP response
+```
+
+**Participants**
+
+- **Client** -- The MCP-capable AI agent (e.g., Claude Code, Cursor, or another IDE/agent) that initiates OAuth discovery, authorization, and tool invocations on behalf of the user.
+- **LiteLLM Proxy** -- Mediates all OAuth discovery, registration, token exchange, and MCP traffic while protecting stored credentials.
+- **Authorization Server** -- Issues OAuth 2.0 tokens via dynamic client registration, PKCE authorization, and token endpoints.
+- **MCP Server (Resource Server)** -- The protected MCP endpoint that receives LiteLLM's authenticated JSON-RPC requests.
+- **User-Agent (Browser)** -- Temporarily involved so the end user can grant consent during the authorization step.
+
+**Flow Steps**
+
+1. **Resource Discovery**: The client fetches MCP resource metadata from LiteLLM's `.well-known/oauth-protected-resource` endpoint to understand scopes and capabilities.
+2. **Authorization Server Discovery**: The client retrieves the OAuth server metadata (token endpoint, authorization endpoint, supported PKCE methods) through LiteLLM's `.well-known/oauth-authorization-server` endpoint.
+3. **Dynamic Client Registration**: The client registers through LiteLLM, which forwards the request to the authorization server (RFC 7591). If the provider doesn't support dynamic registration, you can pre-store `client_id`/`client_secret` in LiteLLM (e.g., GitHub MCP) and the flow proceeds the same way.
+4. **User Authorization**: The client launches a browser session (with code challenge and resource hints). The user approves access, the authorization server sends the code through LiteLLM back to the client.
+5. **Token Exchange**: The client calls LiteLLM with the authorization code, code verifier, and resource. LiteLLM exchanges them with the authorization server and returns the issued access/refresh tokens.
+6. **MCP Invocation**: With a valid token, the client sends the MCP JSON-RPC request (plus LiteLLM API key) to LiteLLM, which forwards it to the MCP server and relays the tool response.
+
+See the official [MCP Authorization Flow](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#authorization-flow-steps) for additional reference.
+
+## Machine-to-Machine (M2M) Auth
+
+LiteLLM automatically fetches, caches, and refreshes OAuth2 tokens using the `client_credentials` grant. No manual token management required.
+
+### Setup
+
+You can configure M2M OAuth via the LiteLLM UI or `config.yaml`.
+
+### UI Setup
+
+Navigate to the **MCP Servers** page and click **+ Add New MCP Server**.
+
+
+
+Enter a name for your server and select **HTTP** as the transport type.
+
+
+
+Paste the MCP server URL.
+
+
+
+Under **Authentication**, select **OAuth**.
+
+
+
+
+
+Choose **Machine-to-Machine (M2M)** as the OAuth flow type. This is for server-to-server authentication using the `client_credentials` grant — no browser interaction required.
+
+
+
+
+
+Fill in the **Client ID** and **Client Secret** provided by your OAuth provider.
+
+
+
+Enter the **Token URL** — this is the endpoint LiteLLM will call to fetch access tokens using `client_credentials`.
+
+
+
+
+
+Scroll down and review the server URL and all fields, then click **Create MCP Server**.
+
+
+
+
+
+
+
+Once created, open the server and navigate to the **MCP Tools** tab to verify that LiteLLM can connect and list available tools.
+
+
+
+
+
+Select a tool (e.g. **echo**) to test it. Fill in the required parameters and click **Call Tool**.
+
+
+
+
+
+
+
+LiteLLM automatically fetches an OAuth token behind the scenes and calls the tool. The result confirms the M2M OAuth flow is working end-to-end.
+
+
+
+### Config.yaml Setup
+
+```yaml title="config.yaml" showLineNumbers
+mcp_servers:
+ my_mcp_server:
+ url: "https://my-mcp-server.com/mcp"
+ auth_type: oauth2
+ client_id: os.environ/MCP_CLIENT_ID
+ client_secret: os.environ/MCP_CLIENT_SECRET
+ token_url: "https://auth.example.com/oauth/token"
+ scopes: ["mcp:read", "mcp:write"] # optional
+```
+
+### How It Works
+
+1. On first MCP request, LiteLLM POSTs to `token_url` with `grant_type=client_credentials`
+2. The access token is cached in-memory with TTL = `expires_in - 60s`
+3. Subsequent requests reuse the cached token
+4. When the token expires, LiteLLM fetches a new one automatically
+
+```mermaid
+sequenceDiagram
+ participant Client as Client
+ participant LiteLLM as LiteLLM Proxy
+ participant Auth as Authorization Server
+ participant MCP as MCP Server
+
+ Client->>LiteLLM: MCP request + LiteLLM API key
+ LiteLLM->>Auth: POST /oauth/token (client_credentials)
+ Auth->>LiteLLM: access_token (expires_in: 3600)
+ LiteLLM->>MCP: MCP request + Bearer token
+ MCP-->>LiteLLM: MCP response
+ LiteLLM-->>Client: MCP response
+
+ Note over LiteLLM: Token cached for subsequent requests
+ Client->>LiteLLM: Next MCP request
+ LiteLLM->>MCP: MCP request + cached Bearer token
+ MCP-->>LiteLLM: MCP response
+ LiteLLM-->>Client: MCP response
+```
+
+### Test with Mock Server
+
+Use [BerriAI/mock-oauth2-mcp-server](https://github.com/BerriAI/mock-oauth2-mcp-server) to test locally:
+
+```bash title="Terminal 1 - Start mock server" showLineNumbers
+pip install fastapi uvicorn
+python mock_oauth2_mcp_server.py # starts on :8765
+```
+
+```yaml title="config.yaml" showLineNumbers
+mcp_servers:
+ test_oauth2:
+ url: "http://localhost:8765/mcp"
+ auth_type: oauth2
+ client_id: "test-client"
+ client_secret: "test-secret"
+ token_url: "http://localhost:8765/oauth/token"
+```
+
+```bash title="Terminal 2 - Start proxy and test" showLineNumbers
+litellm --config config.yaml --port 4000
+
+# List tools
+curl http://localhost:4000/mcp-rest/tools/list \
+ -H "Authorization: Bearer sk-1234"
+
+# Call a tool
+curl http://localhost:4000/mcp-rest/tools/call \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{"name": "echo", "arguments": {"message": "hello"}}'
+```
+
+### Config Reference
+
+| Field | Required | Description |
+|-------|----------|-------------|
+| `auth_type` | Yes | Must be `oauth2` |
+| `client_id` | Yes | OAuth2 client ID. Supports `os.environ/VAR_NAME` |
+| `client_secret` | Yes | OAuth2 client secret. Supports `os.environ/VAR_NAME` |
+| `token_url` | Yes | Token endpoint URL |
+| `scopes` | No | List of scopes to request |
+
+## Debugging OAuth
+
+When the LiteLLM proxy is hosted remotely and you cannot access server logs, enable **debug headers** to get masked authentication diagnostics in the HTTP response.
+
+### Enable Debug Mode
+
+Add the `x-litellm-mcp-debug: true` header to your MCP client request.
+
+**Claude Code:**
+
+```bash
+claude mcp add --transport http litellm_proxy http://proxy.example.com/atlassian_mcp/mcp \
+ --header "x-litellm-api-key: Bearer sk-..." \
+ --header "x-litellm-mcp-debug: true"
+```
+
+**curl:**
+
+```bash
+curl -X POST http://localhost:4000/atlassian_mcp/mcp \
+ -H "Content-Type: application/json" \
+ -H "x-litellm-api-key: Bearer sk-..." \
+ -H "x-litellm-mcp-debug: true" \
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
+```
+
+### Reading the Debug Response Headers
+
+The response includes these headers (all sensitive values are masked):
+
+| Header | Description |
+|--------|-------------|
+| `x-mcp-debug-inbound-auth` | Which inbound auth headers were present. |
+| `x-mcp-debug-oauth2-token` | The OAuth2 token (masked). Shows `SAME_AS_LITELLM_KEY` if the LiteLLM key is leaking. |
+| `x-mcp-debug-auth-resolution` | Which auth method was used: `oauth2-passthrough`, `m2m-client-credentials`, `per-request-header`, `static-token`, or `no-auth`. |
+| `x-mcp-debug-outbound-url` | The upstream MCP server URL. |
+| `x-mcp-debug-server-auth-type` | The `auth_type` configured on the server. |
+
+**Example — healthy OAuth2 passthrough:**
+
+```
+x-mcp-debug-inbound-auth: x-litellm-api-key=Bearer****1234; authorization=Bearer****ef01
+x-mcp-debug-oauth2-token: Bearer****ef01
+x-mcp-debug-auth-resolution: oauth2-passthrough
+x-mcp-debug-outbound-url: https://mcp.atlassian.com/v1/mcp
+x-mcp-debug-server-auth-type: oauth2
+```
+
+**Example — LiteLLM key leaking (misconfigured):**
+
+```
+x-mcp-debug-inbound-auth: authorization=Bearer****1234
+x-mcp-debug-oauth2-token: Bearer****1234 (SAME_AS_LITELLM_KEY - likely misconfigured)
+x-mcp-debug-auth-resolution: oauth2-passthrough
+x-mcp-debug-outbound-url: https://mcp.atlassian.com/v1/mcp
+x-mcp-debug-server-auth-type: oauth2
+```
+
+### Common Issues
+
+#### LiteLLM API key leaking to the MCP server
+
+**Symptom:** `x-mcp-debug-oauth2-token` shows `SAME_AS_LITELLM_KEY`.
+
+The `Authorization` header carries the LiteLLM API key instead of an OAuth2 token. The OAuth2 flow never ran because the client already had an `Authorization` header set.
+
+**Fix:** Move the LiteLLM key to `x-litellm-api-key`:
+
+```bash
+# WRONG — blocks OAuth2 discovery
+claude mcp add --transport http my_server http://proxy/mcp/server \
+ --header "Authorization: Bearer sk-..."
+
+# CORRECT — LiteLLM key in dedicated header, Authorization free for OAuth2
+claude mcp add --transport http my_server http://proxy/mcp/server \
+ --header "x-litellm-api-key: Bearer sk-..."
+```
+
+#### No OAuth2 token present
+
+**Symptom:** `x-mcp-debug-oauth2-token` shows `(none)` and `x-mcp-debug-auth-resolution` shows `no-auth`.
+
+Check that:
+1. The `Authorization` header is NOT set as a static header in the client config.
+2. The MCP server in LiteLLM config has `auth_type: oauth2`.
+3. The `.well-known/oauth-protected-resource` endpoint returns valid metadata.
+
+#### M2M token used instead of user token
+
+**Symptom:** `x-mcp-debug-auth-resolution` shows `m2m-client-credentials`.
+
+The server has `client_id`/`client_secret`/`token_url` configured so LiteLLM is fetching a machine-to-machine token instead of using the per-user OAuth2 token. To use per-user tokens, remove the client credentials from the server config.
diff --git a/docs/my-website/docs/mcp_public_internet.md b/docs/my-website/docs/mcp_public_internet.md
new file mode 100644
index 00000000000..69dd7464657
--- /dev/null
+++ b/docs/my-website/docs/mcp_public_internet.md
@@ -0,0 +1,251 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Exposing MCPs on the Public Internet
+
+Control which MCP servers are visible to external callers (e.g., ChatGPT, Claude Desktop) vs. internal-only callers. This is useful when you want a subset of your MCP servers available publicly while keeping sensitive servers restricted to your private network.
+
+## Overview
+
+| Property | Details |
+|-------|-------|
+| Description | IP-based access control for MCP servers — external callers only see servers marked as public |
+| Setting | `available_on_public_internet` on each MCP server |
+| Network Config | `mcp_internal_ip_ranges` in `general_settings` |
+| Supported Clients | ChatGPT, Claude Desktop, Cursor, OpenAI API, or any MCP client |
+
+## How It Works
+
+When a request arrives at LiteLLM's MCP endpoints, LiteLLM checks the caller's IP address to determine whether they are an **internal** or **external** caller:
+
+1. **Extract the client IP** from the incoming request (supports `X-Forwarded-For` when configured behind a reverse proxy).
+2. **Classify the IP** as internal or external by checking it against the configured private IP ranges (defaults to RFC 1918: `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `127.0.0.0/8`).
+3. **Filter the server list**:
+ - **Internal callers** see all MCP servers (public and private).
+ - **External callers** only see servers with `available_on_public_internet: true`.
+
+This filtering is applied at every MCP access point: the MCP registry, tool listing, tool calling, dynamic server routes, and OAuth discovery endpoints.
+
+```mermaid
+flowchart TD
+ A[Incoming MCP Request] --> B[Extract Client IP Address]
+ B --> C{Is IP in private ranges?}
+ C -->|Yes - Internal caller| D[Return ALL MCP servers]
+ C -->|No - External caller| E[Return ONLY servers with available_on_public_internet = true]
+```
+
+## Walkthrough
+
+This walkthrough covers two flows:
+1. **Adding a public MCP server** (DeepWiki) and connecting to it from ChatGPT
+2. **Making an existing server private** (Exa) and verifying ChatGPT no longer sees it
+
+### Flow 1: Add a Public MCP Server (DeepWiki)
+
+DeepWiki is a free MCP server — a good candidate to expose publicly so AI gateway users can access it from ChatGPT.
+
+#### Step 1: Create the MCP Server
+
+Navigate to the MCP Servers page and click **"+ Add New MCP Server"**.
+
+
+
+The create dialog opens. Enter **"DeepWiki"** as the server name.
+
+
+
+For the transport type dropdown, select **HTTP** since DeepWiki uses the Streamable HTTP transport.
+
+
+
+Now scroll down to the MCP Server URL field.
+
+
+
+Enter the DeepWiki MCP URL: `https://mcp.deepwiki.com/mcp`.
+
+
+
+With the name, transport, and URL filled in, the basic server configuration is complete.
+
+
+
+#### Step 2: Enable "Available on Public Internet"
+
+Before creating, scroll down and expand the **Permission Management / Access Control** section. This is where you control who can see this server.
+
+
+
+Toggle **"Available on Public Internet"** on. This is the key setting — it tells LiteLLM that external callers (like ChatGPT connecting from the public internet) should be able to discover and use this server.
+
+
+
+With the toggle enabled, click **"Create"** to save the server.
+
+
+
+#### Step 3: Connect from ChatGPT
+
+Now let's verify it works. Open ChatGPT and look for the MCP server icon to add a new connection. The endpoint to use is `/mcp`.
+
+
+
+In the dropdown, select **"Add an MCP server"** to configure a new connection.
+
+
+
+ChatGPT asks for a server label. Give it a recognizable name like "LiteLLM".
+
+
+
+Next, enter the Server URL. This should be your LiteLLM proxy's MCP endpoint — `/mcp`.
+
+
+
+Paste your LiteLLM URL and confirm it looks correct.
+
+
+
+ChatGPT also needs authentication. Enter your LiteLLM API key in the authentication field so it can connect to the proxy.
+
+
+
+Click **"Connect"** to establish the connection.
+
+
+
+ChatGPT connects and shows the available tools. Since both DeepWiki and Exa are currently marked as public, ChatGPT can see tools from both servers.
+
+
+
+---
+
+### Flow 2: Make an Existing Server Private (Exa)
+
+Now let's do the reverse — take an existing MCP server (Exa) that's currently public and restrict it to internal access only. After this change, ChatGPT should no longer see Exa's tools.
+
+#### Step 1: Edit the Server
+
+Go to the MCP Servers table and click on the Exa server to open its detail view.
+
+
+
+Switch to the **"Settings"** tab to access the edit form.
+
+
+
+The edit form loads with Exa's current configuration.
+
+
+
+#### Step 2: Toggle Off "Available on Public Internet"
+
+Scroll down and expand the **Permission Management / Access Control** section to find the public internet toggle.
+
+
+
+Toggle **"Available on Public Internet"** off. This will hide Exa from any caller outside your private network.
+
+
+
+Click **"Save Changes"** to apply. The change takes effect immediately — no proxy restart needed.
+
+
+
+#### Step 3: Verify in ChatGPT
+
+Go back to ChatGPT to confirm Exa is no longer visible. You'll need to reconnect for ChatGPT to re-fetch the tool list.
+
+
+
+Open the MCP server settings and select to add or reconnect a server.
+
+
+
+Enter the same LiteLLM MCP URL as before.
+
+
+
+Set the server label.
+
+
+
+Enter your API key for authentication.
+
+
+
+Click **"Connect"** to re-establish the connection.
+
+
+
+This time, only DeepWiki's tools appear — Exa is gone. LiteLLM detected that ChatGPT is calling from a public IP and filtered out Exa since it's no longer marked as public. Internal users on your private network would still see both servers.
+
+
+
+## Configuration Reference
+
+### Per-Server Setting
+
+
+
+
+Toggle **"Available on Public Internet"** in the Permission Management section when creating or editing an MCP server.
+
+
+
+
+```yaml title="config.yaml" showLineNumbers
+mcp_servers:
+ deepwiki:
+ url: https://mcp.deepwiki.com/mcp
+ available_on_public_internet: true # visible to external callers
+
+ exa:
+ url: https://exa.ai/mcp
+ auth_type: api_key
+ auth_value: os.environ/EXA_API_KEY
+ available_on_public_internet: false # internal only (default)
+```
+
+
+
+
+```bash title="Create a public MCP server" showLineNumbers
+curl -X POST /v1/mcp/server \
+ -H "Authorization: Bearer sk-..." \
+ -H "Content-Type: application/json" \
+ -d '{
+ "server_name": "DeepWiki",
+ "url": "https://mcp.deepwiki.com/mcp",
+ "transport": "http",
+ "available_on_public_internet": true
+ }'
+```
+
+```bash title="Update an existing server" showLineNumbers
+curl -X PUT /v1/mcp/server \
+ -H "Authorization: Bearer sk-..." \
+ -H "Content-Type: application/json" \
+ -d '{
+ "server_id": "",
+ "available_on_public_internet": false
+ }'
+```
+
+
+
+
+### Custom Private IP Ranges
+
+By default, LiteLLM treats RFC 1918 private ranges as internal. You can customize this in the **Network Settings** tab under MCP Servers, or via config:
+
+```yaml title="config.yaml" showLineNumbers
+general_settings:
+ mcp_internal_ip_ranges:
+ - "10.0.0.0/8"
+ - "172.16.0.0/12"
+ - "192.168.0.0/16"
+ - "100.64.0.0/10" # Add your VPN/Tailscale range
+```
+
+When empty, the standard private ranges are used (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `127.0.0.0/8`).
diff --git a/docs/my-website/docs/mcp_semantic_filter.md b/docs/my-website/docs/mcp_semantic_filter.md
new file mode 100644
index 00000000000..c58be80a680
--- /dev/null
+++ b/docs/my-website/docs/mcp_semantic_filter.md
@@ -0,0 +1,158 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# MCP Semantic Tool Filter
+
+Automatically filter MCP tools by semantic relevance. When you have many MCP tools registered, LiteLLM semantically matches the user's query against tool descriptions and sends only the most relevant tools to the LLM.
+
+## How It Works
+
+Tool search shifts tool selection from a prompt-engineering problem to a retrieval problem. Instead of injecting a large static list of tools into every prompt, the semantic filter:
+
+1. Builds a semantic index of all available MCP tools on startup
+2. On each request, semantically matches the user's query against tool descriptions
+3. Returns only the top-K most relevant tools to the LLM
+
+This approach improves context efficiency, increases reliability by reducing tool confusion, and enables scalability to ecosystems with hundreds or thousands of MCP tools.
+
+```mermaid
+sequenceDiagram
+ participant Client
+ participant LiteLLM as LiteLLM Proxy
+ participant SemanticFilter as Semantic Filter
+ participant MCP as MCP Registry
+ participant LLM as LLM Provider
+
+ Note over LiteLLM,MCP: Startup: Build Semantic Index
+ LiteLLM->>MCP: Fetch all registered MCP tools
+ MCP->>LiteLLM: Return all tools (e.g., 50 tools)
+ LiteLLM->>SemanticFilter: Build semantic router with embeddings
+ SemanticFilter->>LLM: Generate embeddings for tool descriptions
+ LLM->>SemanticFilter: Return embeddings
+ Note over SemanticFilter: Index ready for fast lookup
+
+ Note over Client,LLM: Request: Semantic Tool Filtering
+ Client->>LiteLLM: POST /v1/responses with MCP tools
+ LiteLLM->>SemanticFilter: Expand MCP references (50 tools available)
+ SemanticFilter->>SemanticFilter: Extract user query from request
+ SemanticFilter->>LLM: Generate query embedding
+ LLM->>SemanticFilter: Return query embedding
+ SemanticFilter->>SemanticFilter: Match query against tool embeddings
+ SemanticFilter->>LiteLLM: Return top-K tools (e.g., 3 most relevant)
+ LiteLLM->>LLM: Forward request with filtered tools (3 tools)
+ LLM->>LiteLLM: Return response
+ LiteLLM->>Client: Response with headers x-litellm-semantic-filter: 50->3 x-litellm-semantic-filter-tools: tool1,tool2,tool3
+```
+
+## Configuration
+
+Enable semantic filtering in your LiteLLM config:
+
+```yaml title="config.yaml" showLineNumbers
+litellm_settings:
+ mcp_semantic_tool_filter:
+ enabled: true
+ embedding_model: "text-embedding-3-small" # Model for semantic matching
+ top_k: 5 # Max tools to return
+ similarity_threshold: 0.3 # Min similarity score
+```
+
+**Configuration Options:**
+- `enabled` - Enable/disable semantic filtering (default: `false`)
+- `embedding_model` - Model for generating embeddings (default: `"text-embedding-3-small"`)
+- `top_k` - Maximum number of tools to return (default: `10`)
+- `similarity_threshold` - Minimum similarity score for matches (default: `0.3`)
+
+## Usage
+
+Use MCP tools normally with the Responses API or Chat Completions. The semantic filter runs automatically:
+
+
+
+
+```bash title="Responses API with Semantic Filtering" showLineNumbers
+curl --location 'http://localhost:4000/v1/responses' \
+--header 'Content-Type: application/json' \
+--header "Authorization: Bearer sk-1234" \
+--data '{
+ "model": "gpt-4o",
+ "input": [
+ {
+ "role": "user",
+ "content": "give me TLDR of what BerriAI/litellm repo is about",
+ "type": "message"
+ }
+ ],
+ "tools": [
+ {
+ "type": "mcp",
+ "server_url": "litellm_proxy",
+ "require_approval": "never"
+ }
+ ],
+ "tool_choice": "required"
+}'
+```
+
+
+
+
+```bash title="Chat Completions with Semantic Filtering" showLineNumbers
+curl --location 'http://localhost:4000/v1/chat/completions' \
+--header 'Content-Type: application/json' \
+--header "Authorization: Bearer sk-1234" \
+--data '{
+ "model": "gpt-4o",
+ "messages": [
+ {"role": "user", "content": "Search Wikipedia for LiteLLM"}
+ ],
+ "tools": [
+ {
+ "type": "mcp",
+ "server_url": "litellm_proxy"
+ }
+ ]
+}'
+```
+
+
+
+
+## Response Headers
+
+The semantic filter adds diagnostic headers to every response:
+
+```
+x-litellm-semantic-filter: 10->3
+x-litellm-semantic-filter-tools: wikipedia-fetch,github-search,slack-post
+```
+
+- **`x-litellm-semantic-filter`** - Shows before→after tool count (e.g., `10->3` means 10 tools were filtered down to 3)
+- **`x-litellm-semantic-filter-tools`** - CSV list of the filtered tool names (max 150 chars, clipped with `...` if longer)
+
+These headers help you understand which tools were selected for each request and verify the filter is working correctly.
+
+## Example
+
+If you have 50 MCP tools registered and make a request asking about Wikipedia, the semantic filter will:
+
+1. Semantically match your query `"Search Wikipedia for LiteLLM"` against all 50 tool descriptions
+2. Select the top 5 most relevant tools (e.g., `wikipedia-fetch`, `wikipedia-search`, etc.)
+3. Pass only those 5 tools to the LLM
+4. Add headers showing `x-litellm-semantic-filter: 50->5`
+
+This dramatically reduces prompt size while ensuring the LLM has access to the right tools for the task.
+
+## Performance
+
+The semantic filter is optimized for production:
+- Router builds once on startup (no per-request overhead)
+- Semantic matching typically takes under 50ms
+- Fails gracefully - returns all tools if filtering fails
+- No impact on latency for requests without MCP tools
+
+## Related
+
+- [MCP Overview](./mcp.md) - Learn about MCP in LiteLLM
+- [MCP Permission Management](./mcp_control.md) - Control tool access by key/team
+- [Using MCP](./mcp_usage.md) - Complete MCP usage guide
diff --git a/docs/my-website/docs/mcp_troubleshoot.md b/docs/my-website/docs/mcp_troubleshoot.md
index 27ba0e4d787..57e7bfa674d 100644
--- a/docs/my-website/docs/mcp_troubleshoot.md
+++ b/docs/my-website/docs/mcp_troubleshoot.md
@@ -6,6 +6,39 @@ When LiteLLM acts as an MCP proxy, traffic normally flows `Client → LiteLLM Pr
For provisioning steps, transport options, and configuration fields, refer to [mcp.md](./mcp.md).
+## Quick Start: Debug with One Command
+
+The fastest way to debug MCP issues is to enable **debug headers**. Run this curl against your LiteLLM proxy and check the response headers:
+
+```bash
+curl -si -X POST http://localhost:4000/{your_mcp_server}/mcp \
+ -H "Content-Type: application/json" \
+ -H "x-litellm-api-key: Bearer sk-YOUR_KEY" \
+ -H "x-litellm-mcp-debug: true" \
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \
+ 2>&1 | grep -i "x-mcp-debug"
+```
+
+This returns masked diagnostic headers that tell you exactly what's happening with authentication:
+
+```
+x-mcp-debug-inbound-auth: x-litellm-api-key=Bearer****1234
+x-mcp-debug-oauth2-token: Bearer****ef01
+x-mcp-debug-auth-resolution: oauth2-passthrough
+x-mcp-debug-outbound-url: https://mcp.atlassian.com/v1/mcp
+x-mcp-debug-server-auth-type: oauth2
+```
+
+If you see `SAME_AS_LITELLM_KEY` in `x-mcp-debug-oauth2-token`, your LiteLLM API key is leaking to the MCP server instead of an OAuth2 token. See [Debugging OAuth](./mcp_oauth#debugging-oauth) for the fix and other common issues.
+
+For Claude Code, add the debug header to your MCP config:
+
+```bash
+claude mcp add --transport http my_server http://localhost:4000/my_mcp/mcp \
+ --header "x-litellm-api-key: Bearer sk-..." \
+ --header "x-litellm-mcp-debug: true"
+```
+
## Locate the Error Source
Pin down where the failure occurs before adjusting settings so you do not mix symptoms from separate hops.
@@ -13,7 +46,7 @@ Pin down where the failure occurs before adjusting settings so you do not mix sy
### LiteLLM UI / Playground Errors (LiteLLM → MCP)
Failures shown on the MCP creation form or within the MCP Tool Testing Playground mean the LiteLLM proxy cannot reach the MCP server. Typical causes are misconfiguration (transport, headers, credentials), MCP/server outages, network/firewall blocks, or inaccessible OAuth metadata.
-
@@ -22,7 +55,7 @@ Failures shown on the MCP creation form or within the MCP Tool Testing Playgroun
**Actions**
- Capture LiteLLM proxy logs alongside MCP-server logs (see [Error Log Example](./mcp_troubleshoot#error-log-example-failed-mcp-call)) to inspect the request/response pair and stack traces.
-- From the LiteLLM server, run Method 2 ([`curl` smoke test](./mcp_troubleshoot#curl-smoke-test)) against the MCP endpoint to confirm basic connectivity.
+- From the LiteLLM server, run a [`curl` smoke test](./mcp_troubleshoot#curl-smoke-test) against the MCP endpoint to confirm basic connectivity.
### Client Traffic Issues (Client → LiteLLM)
If only real client requests fail, determine whether LiteLLM ever reaches the MCP hop.
@@ -43,7 +76,7 @@ During `/responses` or `/chat/completions`, LiteLLM may trigger MCP tool calls m
- Validate MCP connectivity with the [MCP Inspector](./mcp_troubleshoot#mcp-inspector) to ensure the server responds.
- Reproduce the same MCP call via the LiteLLM Playground to confirm LiteLLM can complete the MCP hop independently.
-
@@ -55,6 +88,10 @@ LiteLLM performs metadata discovery per the MCP spec ([section 2.3](https://mode
- Use `curl ` (or similar) from the LiteLLM host to ensure the discovery document is reachable and contains the expected authorization/token endpoints.
- Record the exact metadata URL, requested scopes, and any static client credentials so support can replay the discovery step if needed.
+## Debugging OAuth
+
+For detailed OAuth2 debugging — including debug header reference, common misconfigurations, and example output — see [Debugging OAuth](./mcp_oauth#debugging-oauth).
+
## Verify Connectivity
Run lightweight validations before impacting production traffic.
@@ -66,7 +103,7 @@ Use the MCP Inspector when you need to test both `Client → LiteLLM` and `Clien
2. Configure and connect:
- **Transport Type:** choose the transport the client uses (Streamable HTTP for LiteLLM).
- **URL:** the endpoint under test (LiteLLM MCP URL for `Client → LiteLLM`, or the MCP server URL for `Client → MCP`).
- - **Custom Headers:** e.g., `Authorization: Bearer `.
+ - **Custom Headers:** e.g., `x-litellm-api-key: Bearer `.
3. Open the **Tools** tab and click **List Tools** to verify the MCP alias responds.
### `curl` Smoke Test
@@ -79,7 +116,7 @@ curl -X POST https://your-target-domain.example.com/mcp \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
```
-Add `-H "Authorization: Bearer "` when the target is a LiteLLM endpoint that requires authentication. Adjust the headers, or payload to target other MCP methods. Matching failures between `curl` and LiteLLM confirm that the MCP server or network/OAuth layer is the culprit.
+Add `-H "x-litellm-api-key: Bearer "` when the target is a LiteLLM endpoint that requires authentication. Adjust the headers or payload to target other MCP methods. Matching failures between `curl` and LiteLLM confirm that the MCP server or network/OAuth layer is the culprit.
## Review Logs
diff --git a/docs/my-website/docs/observability/datadog.md b/docs/my-website/docs/observability/datadog.md
index 6f785be1013..9385b0020cf 100644
--- a/docs/my-website/docs/observability/datadog.md
+++ b/docs/my-website/docs/observability/datadog.md
@@ -253,3 +253,12 @@ LiteLLM supports customizing the following Datadog environment variables
\* **Required when using Direct API** (default): `DD_API_KEY` and `DD_SITE` are required
\* **Optional when using DataDog Agent**: Set `LITELLM_DD_AGENT_HOST` to use agent mode; `DD_API_KEY` and `DD_SITE` are not required for **Datadog Logs**. (**Note: `DD_API_KEY` IS REQUIRED for Datadog LLM Observability**)
+## Automatic Tags
+
+LiteLLM automatically adds the following tags to your Datadog logs and metrics if the information is available in the request:
+
+| Tag | Description | Source |
+|-----|-------------|--------|
+| `team` | The team alias or ID associated with the API Key | `user_api_key_team_alias`, `team_alias`, `user_api_key_team_id`, or `team_id` in metadata |
+| `request_tag` | Custom tags passed in the request | `request_tags` in logging payload |
+
diff --git a/docs/my-website/docs/observability/langfuse_integration.md b/docs/my-website/docs/observability/langfuse_integration.md
index a81336c5bc6..d3c5a44d481 100644
--- a/docs/my-website/docs/observability/langfuse_integration.md
+++ b/docs/my-website/docs/observability/langfuse_integration.md
@@ -215,6 +215,66 @@ The following parameters can be updated on a continuation of a trace by passing
Any other key value pairs passed into the metadata not listed in the above spec for a `litellm` completion will be added as a metadata key value pair for the generation.
+#### Multiple Langfuse Projects (Per-Request Credentials)
+
+You can send traces to different Langfuse projects per request by passing credentials directly to `completion()` or `acompletion()`. This works alongside (or instead of) the global env vars and is useful when different teams or business processes use different Langfuse projects.
+
+Pass **`langfuse_public_key`**, **`langfuse_secret_key`** (or **`langfuse_secret`**), and optionally **`langfuse_host`** as keyword arguments:
+
+```python
+import litellm
+from litellm import completion
+
+# Optional: set a default via env for requests that don't pass credentials
+# os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-default..."
+# os.environ["LANGFUSE_SECRET_KEY"] = "sk-default..."
+
+litellm.success_callback = ["langfuse"]
+litellm.failure_callback = ["langfuse"]
+
+# Request 1 → Langfuse Project A
+response_a = completion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hello from team A"}],
+ langfuse_public_key="pk-lf-project-a...",
+ langfuse_secret_key="sk-lf-project-a...",
+ langfuse_host="https://us.cloud.langfuse.com", # optional
+)
+
+# Request 2 → Langfuse Project B (different project)
+response_b = completion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hello from team B"}],
+ langfuse_public_key="pk-lf-project-b...",
+ langfuse_secret_key="sk-lf-project-b...",
+ langfuse_host="https://eu.cloud.langfuse.com", # optional, can differ per project
+)
+```
+
+Async usage with per-request credentials:
+
+```python
+import litellm
+from litellm import acompletion
+
+litellm.success_callback = ["langfuse"]
+litellm.failure_callback = ["langfuse"]
+
+response = await acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hi"}],
+ langfuse_public_key="pk-lf-...",
+ langfuse_secret_key="sk-lf-...",
+ langfuse_host="https://us.cloud.langfuse.com", # optional
+)
+```
+
+- **`langfuse_public_key`** – Langfuse project public key (required for per-request override).
+- **`langfuse_secret_key`** or **`langfuse_secret`** – Langfuse secret key (either name is accepted).
+- **`langfuse_host`** – Langfuse host URL (e.g. `https://us.cloud.langfuse.com`); optional, defaults to env or Langfuse cloud.
+
+When these are passed, that request uses this project (and host) for the Langfuse callback; when omitted, the callback uses the global Langfuse client (from env vars if set). LiteLLM caches a Langfuse client per credential set to avoid creating a new client on every request.
+
#### Disable Logging - Specific Calls
To disable logging for specific calls use the `no-log` flag.
diff --git a/docs/my-website/docs/pass_through/bedrock.md b/docs/my-website/docs/pass_through/bedrock.md
index b8d20d77da0..65c5d8caadc 100644
--- a/docs/my-website/docs/pass_through/bedrock.md
+++ b/docs/my-website/docs/pass_through/bedrock.md
@@ -556,3 +556,147 @@ for event in response.get("completion"):
print(completion)
```
+
+## Using LangChain AWS SDK with LiteLLM
+
+You can use the [LangChain AWS SDK](https://python.langchain.com/docs/integrations/chat/bedrock/) with LiteLLM Proxy to get cost tracking, load balancing, and other LiteLLM features.
+
+### Quick Start
+
+**1. Install LangChain AWS**:
+
+```bash showLineNumbers
+pip install langchain-aws
+```
+
+**2. Setup LiteLLM Proxy**:
+
+Create a `config.yaml`:
+
+```yaml showLineNumbers
+model_list:
+ - model_name: claude-sonnet
+ litellm_params:
+ model: bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0
+ aws_region_name: us-east-1
+ custom_llm_provider: bedrock
+```
+
+Start the proxy:
+
+```bash showLineNumbers
+export AWS_ACCESS_KEY_ID="your-access-key"
+export AWS_SECRET_ACCESS_KEY="your-secret-key"
+
+litellm --config config.yaml
+
+# RUNNING on http://0.0.0.0:4000
+```
+
+**3. Use LangChain with LiteLLM**:
+
+```python showLineNumbers
+from langchain_aws import ChatBedrockConverse
+from langchain_core.messages import HumanMessage
+
+# Your LiteLLM API key
+API_KEY = "Bearer sk-1234"
+
+# Initialize ChatBedrockConverse pointing to LiteLLM proxy
+llm = ChatBedrockConverse(
+ model_id="us.anthropic.claude-3-7-sonnet-20250219-v1:0",
+ endpoint_url="http://localhost:4000/bedrock",
+ region_name="us-east-1",
+ aws_access_key_id=API_KEY,
+ aws_secret_access_key="bedrock" # Any non-empty value works
+)
+
+# Invoke the model
+messages = [HumanMessage(content="Hello, how are you?")]
+response = llm.invoke(messages)
+
+print(response.content)
+```
+
+### Advanced Example: PDF Document Processing with Citations
+
+LangChain AWS SDK supports Bedrock's document processing features. Here's how to use it with LiteLLM:
+
+```python showLineNumbers
+import os
+import json
+from langchain_aws import ChatBedrockConverse
+from langchain_core.messages import HumanMessage
+
+# Your LiteLLM API key
+API_KEY = "Bearer sk-1234"
+
+def get_llm() -> ChatBedrockConverse:
+ """Initialize LLM pointing to LiteLLM proxy"""
+ llm = ChatBedrockConverse(
+ model_id="us.anthropic.claude-3-7-sonnet-20250219-v1:0",
+ base_model_id="anthropic.claude-3-7-sonnet-20250219-v1:0",
+ endpoint_url="http://localhost:4000/bedrock",
+ region_name="us-east-1",
+ aws_access_key_id=API_KEY,
+ aws_secret_access_key="bedrock"
+ )
+ return llm
+
+if __name__ == "__main__":
+ # Initialize the LLM
+ llm = get_llm()
+
+ # Read PDF file as bytes (Converse API requires raw bytes)
+ with open("your-document.pdf", "rb") as file:
+ file_bytes = file.read()
+
+ # Prepare messages with document attachment
+ messages = [
+ HumanMessage(content=[
+ {"text": "What is the policy number in this document?"},
+ {
+ "document": {
+ "format": "pdf",
+ "name": "PolicyDocument",
+ "source": {"bytes": file_bytes},
+ "citations": {"enabled": True}
+ }
+ }
+ ])
+ ]
+
+ # Invoke the LLM
+ response = llm.invoke(messages)
+
+ # Print response with citations
+ print(json.dumps(response.content, indent=4))
+```
+
+### Supported LangChain Features
+
+All LangChain AWS features work with LiteLLM:
+
+| Feature | Supported | Notes |
+|---------|-----------|-------|
+| Text Generation | ✅ | Full support |
+| Streaming | ✅ | Use `stream()` method |
+| Document Processing | ✅ | PDF, images, etc. |
+| Citations | ✅ | Enable in document config |
+| Tool Use | ✅ | Function calling support |
+| Multi-modal | ✅ | Text + images + documents |
+
+### Troubleshooting
+
+**Issue**: `UnknownOperationException` error
+
+**Solution**: Make sure you're using the correct endpoint URL format:
+- ✅ Correct: `http://localhost:4000/bedrock`
+- ❌ Wrong: `http://localhost:4000/bedrock/v2`
+
+**Issue**: Authentication errors
+
+**Solution**: Ensure your API key is in the correct format:
+```python
+aws_access_key_id="Bearer sk-1234" # Include "Bearer " prefix
+```
diff --git a/docs/my-website/docs/pass_through/openai_passthrough.md b/docs/my-website/docs/pass_through/openai_passthrough.md
index d7c98eba7b3..49026f8aa2d 100644
--- a/docs/my-website/docs/pass_through/openai_passthrough.md
+++ b/docs/my-website/docs/pass_through/openai_passthrough.md
@@ -1,6 +1,6 @@
# OpenAI Passthrough
-Pass-through endpoints for `/openai`
+Pass-through endpoints for direct OpenAI API access
## Overview
@@ -10,12 +10,27 @@ Pass-through endpoints for `/openai`
| Logging | ✅ | Works across all integrations |
| Streaming | ✅ | Fully supported |
-### When to use this?
+## Available Endpoints
+
+### `/openai_passthrough` - Recommended
+Dedicated passthrough endpoint that guarantees direct routing to OpenAI without conflicts.
+
+**Use this for:**
+- OpenAI Responses API (`/v1/responses`)
+- Any endpoint where you need guaranteed passthrough
+- When `/openai` routes are conflicting with LiteLLM's native implementations
+
+### `/openai` - Legacy
+Standard passthrough endpoint that may conflict with LiteLLM's native implementations.
+
+**Note:** Some endpoints like `/openai/v1/responses` will be routed to LiteLLM's native implementation instead of OpenAI.
+
+## When to use this?
- For 90% of your use cases, you should use the [native LiteLLM OpenAI Integration](https://docs.litellm.ai/docs/providers/openai) (`/chat/completions`, `/embeddings`, `/completions`, `/images`, `/batches`, etc.)
-- Use this passthrough to call less popular or newer OpenAI endpoints that LiteLLM doesn't fully support yet, such as `/assistants`, `/threads`, `/vector_stores`
+- Use `/openai_passthrough` to call less popular or newer OpenAI endpoints that LiteLLM doesn't fully support yet, such as `/assistants`, `/threads`, `/vector_stores`, `/responses`
-Simply replace `https://api.openai.com` with `LITELLM_PROXY_BASE_URL/openai`
+Simply replace `https://api.openai.com` with `LITELLM_PROXY_BASE_URL/openai_passthrough`
## Usage Examples
@@ -34,7 +49,7 @@ Make sure you do the following:
import openai
client = openai.OpenAI(
- base_url="http://0.0.0.0:4000/openai", # /openai
+ base_url="http://0.0.0.0:4000/openai_passthrough", # /openai_passthrough
api_key="sk-anything" #
)
```
diff --git a/docs/my-website/docs/projects/openai-agents.md b/docs/my-website/docs/projects/openai-agents.md
index 95a2191b883..86983e7e510 100644
--- a/docs/my-website/docs/projects/openai-agents.md
+++ b/docs/my-website/docs/projects/openai-agents.md
@@ -1,22 +1,121 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
# OpenAI Agents SDK
-The [OpenAI Agents SDK](https://github.com/openai/openai-agents-python) is a lightweight framework for building multi-agent workflows.
-It includes an official LiteLLM extension that lets you use any of the 100+ supported providers (Anthropic, Gemini, Mistral, Bedrock, etc.)
+Use OpenAI Agents SDK with any LLM provider through LiteLLM Proxy.
+
+The [OpenAI Agents SDK](https://github.com/openai/openai-agents-python) is a lightweight framework for building multi-agent workflows. It includes an official LiteLLM extension that lets you use any of the 100+ supported providers.
+
+## Quick Start
+
+### 1. Install Dependencies
+
+```bash
+pip install "openai-agents[litellm]"
+```
+
+### 2. Add Model to Config
+
+```yaml title="config.yaml"
+model_list:
+ - model_name: gpt-4o
+ litellm_params:
+ model: "openai/gpt-4o"
+ api_key: "os.environ/OPENAI_API_KEY"
+
+ - model_name: claude-sonnet
+ litellm_params:
+ model: "anthropic/claude-3-5-sonnet-20241022"
+ api_key: "os.environ/ANTHROPIC_API_KEY"
+
+ - model_name: gemini-pro
+ litellm_params:
+ model: "gemini/gemini-2.0-flash-exp"
+ api_key: "os.environ/GEMINI_API_KEY"
+```
+
+### 3. Start LiteLLM Proxy
+
+```bash
+litellm --config config.yaml
+```
+
+### 4. Use with Proxy
+
+
+
```python
from agents import Agent, Runner
from agents.extensions.models.litellm_model import LitellmModel
+# Point to LiteLLM proxy
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant.",
- model=LitellmModel(model="provider/model-name")
+ model=LitellmModel(
+ model="claude-sonnet", # Model from config.yaml
+ api_key="sk-1234", # LiteLLM API key
+ base_url="http://localhost:4000"
+ )
)
-result = Runner.run_sync(agent, "your_prompt_here")
-print("Result:", result.final_output)
+result = await Runner.run(agent, "What is LiteLLM?")
+print(result.final_output)
```
-- [GitHub](https://github.com/openai/openai-agents-python)
-- [LiteLLM Extension Docs](https://openai.github.io/openai-agents-python/ref/extensions/litellm/)
+
+
+
+```python
+from agents import Agent, Runner
+from agents.extensions.models.litellm_model import LitellmModel
+
+# Use any provider directly
+agent = Agent(
+ name="Assistant",
+ instructions="You are a helpful assistant.",
+ model=LitellmModel(
+ model="anthropic/claude-3-5-sonnet-20241022",
+ api_key="your-anthropic-key"
+ )
+)
+
+result = await Runner.run(agent, "What is LiteLLM?")
+print(result.final_output)
+```
+
+
+
+
+## Track Usage
+
+Enable usage tracking to monitor token consumption:
+
+```python
+from agents import Agent, ModelSettings
+from agents.extensions.models.litellm_model import LitellmModel
+
+agent = Agent(
+ name="Assistant",
+ model=LitellmModel(model="claude-sonnet", api_key="sk-1234"),
+ model_settings=ModelSettings(include_usage=True)
+)
+
+result = await Runner.run(agent, "Hello")
+print(result.context_wrapper.usage) # Token counts
+```
+
+## Environment Variables
+
+| Variable | Value | Description |
+|----------|-------|-------------|
+| `LITELLM_BASE_URL` | `http://localhost:4000` | LiteLLM proxy URL |
+| `LITELLM_API_KEY` | `sk-1234` | Your LiteLLM API key |
+
+## Related Resources
+
+- [OpenAI Agents SDK Documentation](https://openai.github.io/openai-agents-python/)
+- [LiteLLM Extension Docs](https://openai.github.io/openai-agents-python/models/litellm/)
+- [LiteLLM Proxy Quick Start](../proxy/quick_start)
diff --git a/docs/my-website/docs/providers/anthropic.md b/docs/my-website/docs/providers/anthropic.md
index 446d663c5ac..de5a4dc610c 100644
--- a/docs/my-website/docs/providers/anthropic.md
+++ b/docs/my-website/docs/providers/anthropic.md
@@ -1473,6 +1473,20 @@ LiteLLM translates OpenAI's `reasoning_effort` to Anthropic's `thinking` paramet
| "medium" | "budget_tokens": 2048 |
| "high" | "budget_tokens": 4096 |
+:::note
+For Claude Opus 4.6, all `reasoning_effort` values (`low`, `medium`, `high`) are mapped to `thinking: {type: "adaptive"}`. To use explicit thinking budgets, pass the native `thinking` parameter directly:
+
+```python
+from litellm import completion
+
+resp = completion(
+ model="anthropic/claude-opus-4-6",
+ messages=[{"role": "user", "content": "What is the capital of France?"}],
+ thinking={"type": "enabled", "budget_tokens": 1024},
+)
+```
+:::
+
@@ -1614,8 +1628,65 @@ curl http://0.0.0.0:4000/v1/chat/completions \
+#### Adaptive Thinking (Claude Opus 4.6)
+
+
+```python
+response = litellm.completion(
+ model="anthropic/claude-opus-4-6",
+ messages=[{"role": "user", "content": "What is the optimal strategy for solving this problem?"}],
+ thinking={"type": "adaptive"},
+)
+```
+
+
+
+
+```bash
+curl http://0.0.0.0:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $LITELLM_KEY" \
+ -d '{
+ "model": "anthropic/claude-opus-4-6",
+ "messages": [{"role": "user", "content": "What is the optimal strategy for solving this problem?"}],
+ "thinking": {"type": "adaptive"}
+ }'
+```
+
+
+
+
+#### Enabled Thinking with Budget
+
+
+
+
+```python
+response = litellm.completion(
+ model="anthropic/claude-opus-4-6",
+ messages=[{"role": "user", "content": "What is the capital of France?"}],
+ thinking={"type": "enabled", "budget_tokens": 5000},
+)
+```
+
+
+
+
+```bash
+curl http://0.0.0.0:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $LITELLM_KEY" \
+ -d '{
+ "model": "anthropic/claude-opus-4-6",
+ "messages": [{"role": "user", "content": "What is the capital of France?"}],
+ "thinking": {"type": "enabled", "budget_tokens": 5000}
+ }'
+```
+
+
+
## **Passing Extra Headers to Anthropic API**
diff --git a/docs/my-website/docs/providers/anthropic_tool_search.md b/docs/my-website/docs/providers/anthropic_tool_search.md
index 28ce5688eeb..203a2947ebc 100644
--- a/docs/my-website/docs/providers/anthropic_tool_search.md
+++ b/docs/my-website/docs/providers/anthropic_tool_search.md
@@ -1,43 +1,46 @@
-# Anthropic Tool Search
+# Tool Search
Tool search enables Claude to dynamically discover and load tools on-demand from large tool catalogs (10,000+ tools). Instead of loading all tool definitions into the context window upfront, Claude searches your tool catalog and loads only the tools it needs.
+## Supported Providers
+
+| Provider | Chat Completions API | Messages API |
+|----------|---------------------|--------------|
+| **Anthropic API** | ✅ | ✅ |
+| **Azure Anthropic** (Microsoft Foundry) | ✅ | ✅ |
+| **Google Cloud Vertex AI** | ✅ | ✅ |
+| **Amazon Bedrock** | ✅ (Invoke API only, Opus 4.5 only) | ✅ (Invoke API only, Opus 4.5 only) |
+
+
## Benefits
- **Context efficiency**: Avoid consuming massive portions of your context window with tool definitions
- **Better tool selection**: Claude's tool selection accuracy degrades with more than 30-50 tools. Tool search maintains accuracy even with thousands of tools
- **On-demand loading**: Tools are only loaded when Claude needs them
-## Supported Models
-
-Tool search is available on:
-- Claude Opus 4.5
-- Claude Sonnet 4.5
-
-## Supported Platforms
-
-- Anthropic API (direct)
-- Azure Anthropic (Microsoft Foundry)
-- Google Cloud Vertex AI
-- Amazon Bedrock (invoke API only, not converse API)
-
## Tool Search Variants
LiteLLM supports both tool search variants:
### 1. Regex Tool Search (`tool_search_tool_regex_20251119`)
-Claude constructs regex patterns to search for tools.
+Claude constructs regex patterns to search for tools. Best for exact pattern matching (faster).
### 2. BM25 Tool Search (`tool_search_tool_bm25_20251119`)
-Claude uses natural language queries to search for tools using the BM25 algorithm.
+Claude uses natural language queries to search for tools using the BM25 algorithm. Best for natural language semantic search.
-## Quick Start
+**Note**: BM25 variant is not supported on Bedrock.
-### Basic Example with Regex Tool Search
+---
-```python
+## Chat Completions API
+
+### SDK Usage
+
+#### Basic Example with Regex Tool Search
+
+```python showLineNumbers title="Basic Tool Search Example"
import litellm
response = litellm.completion(
@@ -70,26 +73,6 @@ response = litellm.completion(
}
},
"defer_loading": True # Mark for deferred loading
- },
- # Another deferred tool
- {
- "type": "function",
- "function": {
- "name": "search_files",
- "description": "Search through files in the workspace",
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string"},
- "file_types": {
- "type": "array",
- "items": {"type": "string"}
- }
- },
- "required": ["query"]
- }
- },
- "defer_loading": True
}
]
)
@@ -97,9 +80,9 @@ response = litellm.completion(
print(response.choices[0].message.content)
```
-### BM25 Tool Search Example
+#### BM25 Tool Search Example
-```python
+```python showLineNumbers title="BM25 Tool Search"
import litellm
response = litellm.completion(
@@ -134,9 +117,9 @@ response = litellm.completion(
)
```
-## Using with Azure Anthropic
+#### Azure Anthropic Example
-```python
+```python showLineNumbers title="Azure Anthropic Tool Search"
import litellm
response = litellm.completion(
@@ -170,9 +153,9 @@ response = litellm.completion(
)
```
-## Using with Vertex AI
+#### Vertex AI Example
-```python
+```python showLineNumbers title="Vertex AI Tool Search"
import litellm
response = litellm.completion(
@@ -192,11 +175,9 @@ response = litellm.completion(
)
```
-## Streaming Support
+#### Streaming Support
-Tool search works with streaming:
-
-```python
+```python showLineNumbers title="Streaming with Tool Search"
import litellm
response = litellm.completion(
@@ -233,13 +214,13 @@ for chunk in response:
print(chunk.choices[0].delta.content, end="")
```
-## LiteLLM Proxy
+### AI Gateway Usage
-Tool search works automatically through the LiteLLM proxy:
+Tool search works automatically through the LiteLLM proxy.
-### Proxy Config
+#### Proxy Configuration
-```yaml
+```yaml showLineNumbers title="config.yaml"
model_list:
- model_name: claude-sonnet
litellm_params:
@@ -247,18 +228,19 @@ model_list:
api_key: os.environ/ANTHROPIC_API_KEY
```
-### Client Request
+#### Client Request
-```python
-import openai
+```python showLineNumbers title="Client Request via Proxy"
+from anthropic import Anthropic
-client = openai.OpenAI(
+client = Anthropic(
api_key="your-litellm-proxy-key",
base_url="http://0.0.0.0:4000"
)
-response = client.chat.completions.create(
+response = client.messages.create(
model="claude-sonnet",
+ max_tokens=1024,
messages=[
{"role": "user", "content": "What's the weather?"}
],
@@ -268,17 +250,14 @@ response = client.chat.completions.create(
"name": "tool_search_tool_regex"
},
{
- "type": "function",
- "function": {
- "name": "get_weather",
- "description": "Get weather information",
- "parameters": {
- "type": "object",
- "properties": {
- "location": {"type": "string"}
- },
- "required": ["location"]
- }
+ "name": "get_weather",
+ "description": "Get weather information",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "location": {"type": "string"}
+ },
+ "required": ["location"]
},
"defer_loading": True
}
@@ -286,127 +265,278 @@ response = client.chat.completions.create(
)
```
-## Important Notes
+---
-### Beta Header
+## Messages API
-LiteLLM automatically detects tool search tools and adds the appropriate beta header based on your provider:
+The Messages API provides native Anthropic-style tool search support via the `litellm.anthropic.messages` interface.
-- **Anthropic API & Microsoft Foundry**: `advanced-tool-use-2025-11-20`
-- **Google Cloud Vertex AI**: `tool-search-tool-2025-10-19`
-- **Amazon Bedrock** (Invoke API, Opus 4.5 only): `tool-search-tool-2025-10-19`
+### SDK Usage
-You don't need to manually specify beta headers—LiteLLM handles this automatically.
+#### Basic Example
-### Deferred Loading
+```python showLineNumbers title="Messages API - Basic Tool Search"
+import litellm
-- Tools with `defer_loading: true` are only loaded when Claude discovers them via search
-- At least one tool must be non-deferred (the tool search tool itself)
-- Keep your 3-5 most frequently used tools as non-deferred for optimal performance
-
-### Tool Descriptions
-
-Write clear, descriptive tool names and descriptions that match how users describe tasks. The search algorithm uses:
-- Tool names
-- Tool descriptions
-- Argument names
-- Argument descriptions
-
-### Usage Tracking
-
-Tool search requests are tracked in the usage object:
-
-```python
-response = litellm.completion(
- model="anthropic/claude-sonnet-4-5-20250929",
- messages=[{"role": "user", "content": "Search for tools"}],
- tools=[...]
+response = await litellm.anthropic.messages.acreate(
+ model="anthropic/claude-sonnet-4-20250514",
+ messages=[
+ {
+ "role": "user",
+ "content": "What's the weather in San Francisco?"
+ }
+ ],
+ tools=[
+ {
+ "type": "tool_search_tool_regex_20251119",
+ "name": "tool_search_tool_regex"
+ },
+ {
+ "name": "get_weather",
+ "description": "Get the current weather for a location",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": "The city and state, e.g. San Francisco, CA"
+ }
+ },
+ "required": ["location"]
+ },
+ "defer_loading": True
+ }
+ ],
+ max_tokens=1024,
+ extra_headers={"anthropic-beta": "advanced-tool-use-2025-11-20"}
)
-# Check tool search usage
-if response.usage.server_tool_use:
- print(f"Tool search requests: {response.usage.server_tool_use.tool_search_requests}")
+print(response)
```
-## Error Handling
+#### Azure Anthropic Messages Example
-### All Tools Deferred
+```python showLineNumbers title="Azure Anthropic Messages API"
+import litellm
-```python
-# ❌ This will fail - at least one tool must be non-deferred
-tools = [
- {
- "type": "function",
- "function": {...},
- "defer_loading": True
- }
-]
-
-# ✅ Correct - tool search tool is non-deferred
-tools = [
- {
- "type": "tool_search_tool_regex_20251119",
- "name": "tool_search_tool_regex"
- },
- {
- "type": "function",
- "function": {...},
- "defer_loading": True
- }
-]
+response = await litellm.anthropic.messages.acreate(
+ model="azure_anthropic/claude-sonnet-4-20250514",
+ messages=[
+ {
+ "role": "user",
+ "content": "What's the stock price of Apple?"
+ }
+ ],
+ tools=[
+ {
+ "type": "tool_search_tool_regex_20251119",
+ "name": "tool_search_tool_regex"
+ },
+ {
+ "name": "get_stock_price",
+ "description": "Get the current stock price for a ticker symbol",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "ticker": {
+ "type": "string",
+ "description": "The stock ticker symbol, e.g. AAPL"
+ }
+ },
+ "required": ["ticker"]
+ },
+ "defer_loading": True
+ }
+ ],
+ max_tokens=1024,
+ extra_headers={"anthropic-beta": "advanced-tool-use-2025-11-20"}
+)
```
-### Missing Tool Definition
+#### Vertex AI Messages Example
-If Claude references a tool that isn't in your deferred tools list, you'll get an error. Make sure all tools that might be discovered are included in the tools parameter with `defer_loading: true`.
+```python showLineNumbers title="Vertex AI Messages API"
+import litellm
-## Best Practices
+response = await litellm.anthropic.messages.acreate(
+ model="vertex_ai/claude-sonnet-4@20250514",
+ messages=[
+ {
+ "role": "user",
+ "content": "Search the web for information about AI"
+ }
+ ],
+ tools=[
+ {
+ "type": "tool_search_tool_bm25_20251119",
+ "name": "tool_search_tool_bm25"
+ },
+ {
+ "name": "search_web",
+ "description": "Search the web for information",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "The search query"
+ }
+ },
+ "required": ["query"]
+ },
+ "defer_loading": True
+ }
+ ],
+ max_tokens=1024,
+ extra_headers={"anthropic-beta": "tool-search-tool-2025-10-19"}
+)
+```
-1. **Keep frequently used tools non-deferred**: Your 3-5 most common tools should not have `defer_loading: true`
+#### Bedrock Messages Example
-2. **Use semantic descriptions**: Tool descriptions should use natural language that matches user queries
+```python showLineNumbers title="Bedrock Messages API (Invoke)"
+import litellm
-3. **Choose the right variant**:
- - Use **regex** for exact pattern matching (faster)
- - Use **BM25** for natural language semantic search
+response = await litellm.anthropic.messages.acreate(
+ model="bedrock/invoke/anthropic.claude-opus-4-20250514-v1:0",
+ messages=[
+ {
+ "role": "user",
+ "content": "What's the weather?"
+ }
+ ],
+ tools=[
+ {
+ "type": "tool_search_tool_regex_20251119",
+ "name": "tool_search_tool_regex"
+ },
+ {
+ "name": "get_weather",
+ "description": "Get weather information",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "location": {"type": "string"}
+ },
+ "required": ["location"]
+ },
+ "defer_loading": True
+ }
+ ],
+ max_tokens=1024,
+ extra_headers={"anthropic-beta": "tool-search-tool-2025-10-19"}
+)
+```
-4. **Monitor usage**: Track `tool_search_requests` in the usage object to understand search patterns
+#### Streaming Support
-5. **Optimize tool catalog**: Remove unused tools and consolidate similar functionality
+```python showLineNumbers title="Messages API - Streaming"
+import litellm
+import json
-## When to Use Tool Search
+response = await litellm.anthropic.messages.acreate(
+ model="anthropic/claude-sonnet-4-20250514",
+ messages=[
+ {
+ "role": "user",
+ "content": "What's the weather in Tokyo?"
+ }
+ ],
+ tools=[
+ {
+ "type": "tool_search_tool_regex_20251119",
+ "name": "tool_search_tool_regex"
+ },
+ {
+ "name": "get_weather",
+ "description": "Get weather information",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "location": {"type": "string"}
+ },
+ "required": ["location"]
+ },
+ "defer_loading": True
+ }
+ ],
+ max_tokens=1024,
+ stream=True,
+ extra_headers={"anthropic-beta": "advanced-tool-use-2025-11-20"}
+)
-**Good use cases:**
-- 10+ tools available in your system
-- Tool definitions consuming >10K tokens
-- Experiencing tool selection accuracy issues
-- Building systems with multiple tool categories
-- Tool library growing over time
+async for chunk in response:
+ if isinstance(chunk, bytes):
+ chunk_str = chunk.decode("utf-8")
+ for line in chunk_str.split("\n"):
+ if line.startswith("data: "):
+ try:
+ json_data = json.loads(line[6:])
+ print(json_data)
+ except json.JSONDecodeError:
+ pass
+```
-**When traditional tool calling is better:**
-- Less than 10 tools total
-- All tools are frequently used
-- Very small tool definitions (\<100 tokens total)
+### AI Gateway Usage
-## Limitations
+Configure the proxy to use Messages API endpoints.
-- Not compatible with tool use examples
-- Requires Claude Opus 4.5 or Sonnet 4.5
-- On Bedrock, only available via invoke API (not converse API)
-- On Bedrock, only supported for Claude Opus 4.5 (not Sonnet 4.5)
-- BM25 variant (`tool_search_tool_bm25_20251119`) is not supported on Bedrock
-- Maximum 10,000 tools in catalog
-- Returns 3-5 most relevant tools per search
+#### Proxy Configuration
-### Bedrock-Specific Notes
+```yaml showLineNumbers title="config.yaml"
+model_list:
+ - model_name: claude-sonnet-messages
+ litellm_params:
+ model: anthropic/claude-sonnet-4-20250514
+ api_key: os.environ/ANTHROPIC_API_KEY
+```
-When using Bedrock's Invoke API:
-- The regex variant (`tool_search_tool_regex_20251119`) is automatically normalized to `tool_search_tool_regex`
-- The BM25 variant (`tool_search_tool_bm25_20251119`) is automatically filtered out as it's not supported
-- Tool search is only available for Claude Opus 4.5 models
+#### Client Request
+
+```python showLineNumbers title="Client Request via Proxy (Messages API)"
+from anthropic import Anthropic
+
+client = Anthropic(
+ api_key="your-litellm-proxy-key",
+ base_url="http://0.0.0.0:4000"
+)
+
+response = client.messages.create(
+ model="claude-sonnet-messages",
+ max_tokens=1024,
+ messages=[
+ {
+ "role": "user",
+ "content": "What's the weather?"
+ }
+ ],
+ tools=[
+ {
+ "type": "tool_search_tool_regex_20251119",
+ "name": "tool_search_tool_regex"
+ },
+ {
+ "name": "get_weather",
+ "description": "Get weather information",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "location": {"type": "string"}
+ },
+ "required": ["location"]
+ },
+ "defer_loading": True
+ }
+ ],
+ extra_headers={"anthropic-beta": "advanced-tool-use-2025-11-20"}
+)
+
+print(response)
+```
+
+---
## Additional Resources
- [Anthropic Tool Search Documentation](https://docs.anthropic.com/en/docs/build-with-claude/tool-use/tool-search)
- [LiteLLM Tool Calling Guide](https://docs.litellm.ai/docs/completion/function_call)
-
diff --git a/docs/my-website/docs/providers/azure_ai/azure_model_router.md b/docs/my-website/docs/providers/azure_ai/azure_model_router.md
index 5e14c7283f6..16bc1afb70e 100644
--- a/docs/my-website/docs/providers/azure_ai/azure_model_router.md
+++ b/docs/my-website/docs/providers/azure_ai/azure_model_router.md
@@ -5,19 +5,38 @@ Azure Model Router is a feature in Azure AI Foundry that automatically routes yo
## Key Features
- **Automatic Model Selection**: Azure Model Router dynamically selects the best model for your request
-- **Cost Tracking**: LiteLLM automatically tracks costs based on the actual model used (e.g., `gpt-4.1-nano`), not the router endpoint
+- **Cost Tracking**: LiteLLM automatically tracks costs based on the actual model used (e.g., `gpt-4.1-nano`), plus the Model Router infrastructure fee
- **Streaming Support**: Full support for streaming responses with accurate cost calculation
+- **Simple Configuration**: Easy to set up via UI or config file
+
+## Model Naming Pattern
+
+Use the pattern: `azure_ai/model_router/`
+
+**Components:**
+- `azure_ai` - The provider identifier
+- `model_router` - Indicates this is a Model Router deployment
+- `` - Your actual deployment name from Azure AI Foundry (e.g., `azure-model-router`)
+
+**Example:** `azure_ai/model_router/azure-model-router`
+
+**How it works:**
+- LiteLLM automatically strips the `model_router/` prefix when sending requests to Azure
+- Only your deployment name (e.g., `azure-model-router`) is sent to the Azure API
+- The full path is preserved in responses and logs for proper cost tracking
## LiteLLM Python SDK
### Basic Usage
+Use the pattern `azure_ai/model_router/` where `` is your Azure deployment name:
+
```python
import litellm
import os
response = litellm.completion(
- model="azure_ai/azure-model-router",
+ model="azure_ai/model_router/azure-model-router", # Use your deployment name
messages=[{"role": "user", "content": "Hello!"}],
api_base="https://your-endpoint.cognitiveservices.azure.com/openai/v1/",
api_key=os.getenv("AZURE_MODEL_ROUTER_API_KEY"),
@@ -26,6 +45,13 @@ response = litellm.completion(
print(response)
```
+**Pattern Explanation:**
+- `azure_ai` - The provider
+- `model_router` - Indicates this is a model router deployment
+- `azure-model-router` - Your actual deployment name from Azure AI Foundry
+
+LiteLLM will automatically strip the `model_router/` prefix when sending the request to Azure, so only `azure-model-router` is sent to the API.
+
### Streaming with Usage Tracking
```python
@@ -33,7 +59,7 @@ import litellm
import os
response = await litellm.acompletion(
- model="azure_ai/azure-model-router",
+ model="azure_ai/model_router/azure-model-router", # Use your deployment name
messages=[{"role": "user", "content": "hi"}],
api_base="https://your-endpoint.cognitiveservices.azure.com/openai/v1/",
api_key=os.getenv("AZURE_MODEL_ROUTER_API_KEY"),
@@ -51,13 +77,15 @@ async for chunk in response:
```yaml
model_list:
- - model_name: azure-model-router
+ - model_name: azure-model-router # Public name for your users
litellm_params:
- model: azure_ai/azure-model-router
+ model: azure_ai/model_router/azure-model-router # Use your deployment name
api_base: https://your-endpoint.cognitiveservices.azure.com/openai/v1/
api_key: os.environ/AZURE_MODEL_ROUTER_API_KEY
```
+**Note:** Replace `azure-model-router` in the model path with your actual deployment name from Azure AI Foundry.
+
### Start Proxy
```bash
@@ -80,49 +108,42 @@ curl -X POST http://localhost:4000/chat/completions \
This walkthrough shows how to add an Azure Model Router endpoint to LiteLLM using the Admin Dashboard.
-### Select Provider
+### Quick Start
+
+1. Navigate to the **Models** page in the LiteLLM UI
+2. Select **"Azure AI Foundry (Studio)"** as the provider
+3. Enter your deployment name (e.g., `azure-model-router`)
+4. LiteLLM will automatically format it as `azure_ai/model_router/azure-model-router`
+5. Add your API base URL and API key
+6. Test and save
+
+### Detailed Walkthrough
+
+#### Step 1: Select Provider
Navigate to the Models page and select "Azure AI Foundry (Studio)" as the provider.
-#### Navigate to Models Page
+##### Navigate to Models Page

-#### Click Provider Dropdown
+##### Click Provider Dropdown

-#### Choose Azure AI Foundry
+##### Choose Azure AI Foundry

-### Configure Model Name
+#### Step 2: Enter Deployment Name
-Set up the model name by entering `azure_ai/` followed by your model router deployment name from Azure.
+**New Simplified Method:** Just enter your deployment name directly in the text field. If your deployment name contains "model-router" or "model_router", LiteLLM will automatically format it as `azure_ai/model_router/`.
-#### Click Model Name Field
+**Example:**
+- Enter: `azure-model-router`
+- LiteLLM creates: `azure_ai/model_router/azure-model-router`
-
-
-#### Select Custom Model Name
-
-
-
-#### Enter LiteLLM Model Name
-
-
-
-#### Click Custom Model Name Field
-
-
-
-#### Type Model Prefix
-
-Type `azure_ai/` as the prefix.
-
-
-
-#### Copy Model Name from Azure Portal
+##### Copy Deployment Name from Azure Portal
Switch to Azure AI Foundry and copy your model router deployment name.
@@ -130,73 +151,79 @@ Switch to Azure AI Foundry and copy your model router deployment name.

-#### Paste Model Name
+##### Enter Deployment Name in LiteLLM
-Paste to get `azure_ai/azure-model-router`.
+Paste your deployment name (e.g., `azure-model-router`) directly into the text field.
-
+
-### Configure API Base and Key
+**What happens behind the scenes:**
+- You enter: `azure-model-router`
+- LiteLLM automatically detects this is a model router deployment
+- The full model path becomes: `azure_ai/model_router/azure-model-router`
+- When making API calls, only `azure-model-router` is sent to Azure
+
+#### Step 3: Configure API Base and Key
Copy the endpoint URL and API key from Azure portal.
-#### Copy API Base URL from Azure
+##### Copy API Base URL from Azure

-#### Enter API Base in LiteLLM
+##### Enter API Base in LiteLLM


-#### Copy API Key from Azure
+##### Copy API Key from Azure

-#### Enter API Key in LiteLLM
+##### Enter API Key in LiteLLM

-### Test and Add Model
+#### Step 4: Test and Add Model
Verify your configuration works and save the model.
-#### Test Connection
+##### Test Connection

-#### Close Test Dialog
+##### Close Test Dialog

-#### Add Model
+##### Add Model

-### Verify in Playground
+#### Step 5: Verify in Playground
Test your model and verify cost tracking is working.
-#### Open Playground
+##### Open Playground

-#### Select Model
+##### Select Model

-#### Send Test Message
+##### Send Test Message

-#### View Logs
+##### View Logs

-#### Verify Cost Tracking
+##### Verify Cost Tracking
-Cost is tracked based on the actual model used (e.g., `gpt-4.1-nano`).
+Cost is tracked based on the actual model used (e.g., `gpt-4.1-nano`), plus a flat infrastructure cost of $0.14 per million input tokens for using the Model Router.

@@ -205,28 +232,50 @@ Cost is tracked based on the actual model used (e.g., `gpt-4.1-nano`).
LiteLLM automatically handles cost tracking for Azure Model Router by:
1. **Detecting the actual model**: When Azure Model Router routes your request to a specific model (e.g., `gpt-4.1-nano-2025-04-14`), LiteLLM extracts this from the response
-2. **Calculating accurate costs**: Costs are calculated based on the actual model used, not the router endpoint name
+2. **Calculating accurate costs**: Costs are calculated based on:
+ - The actual model used (e.g., `gpt-4.1-nano` token costs)
+ - Plus a flat infrastructure cost of **$0.14 per million input tokens** for using the Model Router
3. **Streaming support**: Cost tracking works correctly for both streaming and non-streaming requests
+### Cost Breakdown
+
+When you use Azure Model Router, the total cost includes:
+
+- **Model Cost**: Based on the actual model that handled your request (e.g., `gpt-4.1-nano`)
+- **Router Flat Cost**: $0.14 per million input tokens (Azure AI Foundry infrastructure fee)
+
### Example Response with Cost
```python
import litellm
response = litellm.completion(
- model="azure_ai/azure-model-router",
+ model="azure_ai/model_router/azure-model-router",
messages=[{"role": "user", "content": "Hello!"}],
api_base="https://your-endpoint.cognitiveservices.azure.com/openai/v1/",
api_key="your-api-key",
)
# The response will show the actual model used
-print(f"Model used: {response.model}") # e.g., "gpt-4.1-nano-2025-04-14"
+print(f"Model used: {response.model}") # e.g., "azure_ai/gpt-4.1-nano-2025-04-14"
-# Get cost
+# Get cost (includes both model cost and router flat cost)
from litellm import completion_cost
cost = completion_cost(completion_response=response)
-print(f"Cost: ${cost}")
+print(f"Total cost: ${cost}")
+
+# Access detailed cost breakdown
+if hasattr(response, '_hidden_params') and 'response_cost' in response._hidden_params:
+ print(f"Response cost: ${response._hidden_params['response_cost']}")
```
+### Viewing Cost Breakdown in UI
+
+When viewing logs in the LiteLLM UI, you'll see:
+- **Model Cost**: The cost for the actual model used
+- **Azure Model Router Flat Cost**: The $0.14/M input tokens infrastructure fee
+- **Total Cost**: Sum of both costs
+
+This breakdown helps you understand exactly what you're paying for when using the Model Router.
+
diff --git a/docs/my-website/docs/providers/bedrock.md b/docs/my-website/docs/providers/bedrock.md
index 487212ad655..e546ed97656 100644
--- a/docs/my-website/docs/providers/bedrock.md
+++ b/docs/my-website/docs/providers/bedrock.md
@@ -9,7 +9,7 @@ ALL Bedrock models (Anthropic, Meta, Deepseek, Mistral, Amazon, etc.) are Suppor
| Description | Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs). |
| Provider Route on LiteLLM | `bedrock/`, [`bedrock/converse/`](#set-converse--invoke-route), [`bedrock/invoke/`](#set-invoke-route), [`bedrock/converse_like/`](#calling-via-internal-proxy), [`bedrock/llama/`](#deepseek-not-r1), [`bedrock/deepseek_r1/`](#deepseek-r1), [`bedrock/qwen3/`](#qwen3-imported-models), [`bedrock/qwen2/`](./bedrock_imported.md#qwen2-imported-models), [`bedrock/openai/`](./bedrock_imported.md#openai-compatible-imported-models-qwen-25-vl-etc), [`bedrock/moonshot`](./bedrock_imported.md#moonshot-kimi-k2-thinking) |
| Provider Doc | [Amazon Bedrock ↗](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) |
-| Supported OpenAI Endpoints | `/chat/completions`, `/completions`, `/embeddings`, `/images/generations` |
+| Supported OpenAI Endpoints | `/chat/completions`, `/completions`, `/embeddings`, `/images/generations`, `/v1/realtime`|
| Rerank Endpoint | `/rerank` |
| Pass-through Endpoint | [Supported](../pass_through/bedrock.md) |
diff --git a/docs/my-website/docs/providers/bedrock_realtime_with_audio.md b/docs/my-website/docs/providers/bedrock_realtime_with_audio.md
new file mode 100644
index 00000000000..a2d9813ffd9
--- /dev/null
+++ b/docs/my-website/docs/providers/bedrock_realtime_with_audio.md
@@ -0,0 +1,362 @@
+# Bedrock Realtime API
+
+## Overview
+
+Amazon Bedrock's Nova Sonic model supports real-time bidirectional audio streaming for voice conversations. This tutorial shows how to use it through LiteLLM Proxy.
+
+## Setup
+
+### 1. Configure LiteLLM Proxy
+
+Create a `config.yaml` file:
+
+```yaml
+model_list:
+ - model_name: "bedrock-sonic"
+ litellm_params:
+ model: bedrock/amazon.nova-sonic-v1:0
+ aws_region_name: us-east-1 # or your preferred region
+ model_info:
+ mode: realtime
+```
+
+### 2. Start LiteLLM Proxy
+
+```bash
+litellm --config config.yaml
+```
+
+## Basic Text Interaction
+
+```python
+import asyncio
+import websockets
+import json
+
+LITELLM_API_KEY = "sk-1234" # Your LiteLLM API key
+LITELLM_URL = 'ws://localhost:4000/v1/realtime?model=bedrock-sonic'
+
+async def test_text_conversation():
+ async with websockets.connect(
+ LITELLM_URL,
+ additional_headers={
+ "Authorization": f"Bearer {LITELLM_API_KEY}"
+ }
+ ) as ws:
+ # Wait for session.created
+ response = await ws.recv()
+ print(f"Connected: {json.loads(response)['type']}")
+
+ # Configure session
+ session_update = {
+ "type": "session.update",
+ "session": {
+ "instructions": "You are a helpful assistant.",
+ "modalities": ["text"],
+ "temperature": 0.8
+ }
+ }
+ await ws.send(json.dumps(session_update))
+
+ # Send a message
+ message = {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [{"type": "input_text", "text": "Hello!"}]
+ }
+ }
+ await ws.send(json.dumps(message))
+
+ # Trigger response
+ await ws.send(json.dumps({"type": "response.create"}))
+
+ # Listen for response
+ while True:
+ response = await ws.recv()
+ event = json.loads(response)
+
+ if event['type'] == 'response.text.delta':
+ print(event['delta'], end='', flush=True)
+ elif event['type'] == 'response.done':
+ print("\n✓ Complete")
+ break
+
+if __name__ == "__main__":
+ asyncio.run(test_text_conversation())
+```
+
+## Audio Streaming with Voice Conversation
+
+```python
+import asyncio
+import websockets
+import json
+import base64
+import pyaudio
+
+LITELLM_API_KEY = "sk-1234"
+LITELLM_URL = 'ws://localhost:4000/v1/realtime?model=bedrock-sonic'
+
+# Audio configuration
+INPUT_RATE = 16000 # Nova Sonic expects 16kHz input
+OUTPUT_RATE = 24000 # Nova Sonic outputs 24kHz
+CHUNK = 1024
+
+async def audio_conversation():
+ # Initialize PyAudio
+ p = pyaudio.PyAudio()
+
+ # Input stream (microphone)
+ input_stream = p.open(
+ format=pyaudio.paInt16,
+ channels=1,
+ rate=INPUT_RATE,
+ input=True,
+ frames_per_buffer=CHUNK
+ )
+
+ # Output stream (speakers)
+ output_stream = p.open(
+ format=pyaudio.paInt16,
+ channels=1,
+ rate=OUTPUT_RATE,
+ output=True,
+ frames_per_buffer=CHUNK
+ )
+
+ async with websockets.connect(
+ LITELLM_URL,
+ additional_headers={"Authorization": f"Bearer {LITELLM_API_KEY}"}
+ ) as ws:
+ # Wait for session.created
+ await ws.recv()
+ print("✓ Connected")
+
+ # Configure session with audio
+ session_update = {
+ "type": "session.update",
+ "session": {
+ "instructions": "You are a friendly voice assistant.",
+ "modalities": ["text", "audio"],
+ "voice": "matthew",
+ "input_audio_format": "pcm16",
+ "output_audio_format": "pcm16"
+ }
+ }
+ await ws.send(json.dumps(session_update))
+ print("🎤 Speak into your microphone...")
+
+ async def send_audio():
+ """Capture and send audio from microphone"""
+ while True:
+ audio_data = input_stream.read(CHUNK, exception_on_overflow=False)
+ audio_b64 = base64.b64encode(audio_data).decode('utf-8')
+ await ws.send(json.dumps({
+ "type": "input_audio_buffer.append",
+ "audio": audio_b64
+ }))
+ await asyncio.sleep(0.01)
+
+ async def receive_audio():
+ """Receive and play audio responses"""
+ while True:
+ response = await ws.recv()
+ event = json.loads(response)
+
+ if event['type'] == 'response.audio.delta':
+ audio_b64 = event.get('delta', '')
+ if audio_b64:
+ audio_bytes = base64.b64decode(audio_b64)
+ output_stream.write(audio_bytes)
+
+ elif event['type'] == 'response.text.delta':
+ print(event['delta'], end='', flush=True)
+
+ elif event['type'] == 'response.done':
+ print("\n✓ Response complete")
+
+ # Run both tasks concurrently
+ await asyncio.gather(send_audio(), receive_audio())
+
+if __name__ == "__main__":
+ try:
+ asyncio.run(audio_conversation())
+ except KeyboardInterrupt:
+ print("\n\nGoodbye!")
+```
+
+## Using Tools/Function Calling
+
+```python
+import asyncio
+import websockets
+import json
+from datetime import datetime
+
+LITELLM_API_KEY = "sk-1234"
+LITELLM_URL = 'ws://localhost:4000/v1/realtime?model=bedrock-sonic'
+
+# Define tools
+TOOLS = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get current weather for a location",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": "City name"
+ }
+ },
+ "required": ["location"]
+ }
+ }
+ }
+]
+
+def get_weather(location: str) -> dict:
+ """Simulated weather function"""
+ return {
+ "location": location,
+ "temperature": 72,
+ "conditions": "sunny"
+ }
+
+async def conversation_with_tools():
+ async with websockets.connect(
+ LITELLM_URL,
+ additional_headers={"Authorization": f"Bearer {LITELLM_API_KEY}"}
+ ) as ws:
+ # Wait for session.created
+ await ws.recv()
+
+ # Configure session with tools
+ session_update = {
+ "type": "session.update",
+ "session": {
+ "instructions": "You are a helpful assistant with access to tools.",
+ "modalities": ["text"],
+ "tools": TOOLS
+ }
+ }
+ await ws.send(json.dumps(session_update))
+
+ # Send a message that requires a tool
+ message = {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [{"type": "input_text", "text": "What's the weather in San Francisco?"}]
+ }
+ }
+ await ws.send(json.dumps(message))
+ await ws.send(json.dumps({"type": "response.create"}))
+
+ # Handle responses and tool calls
+ while True:
+ response = await ws.recv()
+ event = json.loads(response)
+
+ if event['type'] == 'response.text.delta':
+ print(event['delta'], end='', flush=True)
+
+ elif event['type'] == 'response.function_call_arguments.done':
+ # Execute the tool
+ function_name = event['name']
+ arguments = json.loads(event['arguments'])
+
+ print(f"\n🔧 Calling {function_name}({arguments})")
+ result = get_weather(**arguments)
+
+ # Send tool result back
+ tool_result = {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "function_call_output",
+ "call_id": event['call_id'],
+ "output": json.dumps(result)
+ }
+ }
+ await ws.send(json.dumps(tool_result))
+ await ws.send(json.dumps({"type": "response.create"}))
+
+ elif event['type'] == 'response.done':
+ print("\n✓ Complete")
+ break
+
+if __name__ == "__main__":
+ asyncio.run(conversation_with_tools())
+```
+
+## Configuration Options
+
+### Voice Options
+Available voices: `matthew`, `joanna`, `ruth`, `stephen`, `gregory`, `amy`
+
+### Audio Formats
+- **Input**: 16kHz PCM16 (mono)
+- **Output**: 24kHz PCM16 (mono)
+
+### Modalities
+- `["text"]` - Text only
+- `["audio"]` - Audio only
+- `["text", "audio"]` - Both text and audio
+
+## Example Test Scripts
+
+Complete working examples are available in the LiteLLM repository:
+
+- **Basic audio streaming**: `test_bedrock_realtime_client.py`
+- **Simple text test**: `test_bedrock_realtime_simple.py`
+- **Tool calling**: `test_bedrock_realtime_tools.py`
+
+## Requirements
+
+```bash
+pip install litellm websockets pyaudio
+```
+
+## AWS Configuration
+
+Ensure your AWS credentials are configured:
+
+```bash
+export AWS_ACCESS_KEY_ID=your_access_key
+export AWS_SECRET_ACCESS_KEY=your_secret_key
+export AWS_REGION_NAME=us-east-1
+```
+
+Or use AWS CLI configuration:
+
+```bash
+aws configure
+```
+
+## Troubleshooting
+
+### Connection Issues
+- Ensure LiteLLM proxy is running on the correct port
+- Verify AWS credentials are properly configured
+- Check that the Bedrock model is available in your region
+
+### Audio Issues
+- Verify PyAudio is properly installed
+- Check microphone/speaker permissions
+- Ensure correct sample rates (16kHz input, 24kHz output)
+
+### Tool Calling Issues
+- Ensure tools are properly defined in session.update
+- Verify tool results are sent back with correct call_id
+- Check that response.create is sent after tool result
+
+## Related Resources
+
+- [OpenAI Realtime API Documentation](https://platform.openai.com/docs/guides/realtime)
+- [Amazon Bedrock Nova Sonic Documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/nova-sonic.html)
+- [LiteLLM Realtime API Documentation](/docs/realtime)
diff --git a/docs/my-website/docs/providers/dashscope.md b/docs/my-website/docs/providers/dashscope.md
index 565776d6c4c..3df0fbab1ba 100644
--- a/docs/my-website/docs/providers/dashscope.md
+++ b/docs/my-website/docs/providers/dashscope.md
@@ -1,7 +1,7 @@
-# Dashscope (Qwen API)
+# Dashscope API (Qwen models)
https://dashscope.console.aliyun.com/
-**We support ALL Qwen models, just set `dashscope/` as a prefix when sending completion requests**
+**We support ALL Qwen models (from Alibaba Cloud), just set `dashscope/` as a prefix when sending completion requests**
## API Key
```python
@@ -9,6 +9,26 @@ https://dashscope.console.aliyun.com/
os.environ['DASHSCOPE_API_KEY']
```
+## API Base
+You can optionally specify the API base URL depending on your region:
+
+| Region | API Base |
+|--------|----------|
+| **International** | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1` |
+| **China/Beijing** | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
+
+```python
+# Set via environment variable
+os.environ['DASHSCOPE_API_BASE'] = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
+
+# Or pass directly in the completion call
+response = completion(
+ model="dashscope/qwen-turbo",
+ messages=[{"role": "user", "content": "hello"}],
+ api_base="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
+)
+```
+
## Sample Usage
```python
from litellm import completion
@@ -43,9 +63,7 @@ for chunk in response:
```
-## Supported Models - ALL Qwen Models Supported!
-We support ALL Qwen models, just set `dashscope/` as a prefix when sending completion requests
-
+## All supported Models
[DashScope Model List](https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope?spm=a2c4g.11186623.help-menu-2400256.d_2_8_0.1efd516e2tTXBn&scm=20140722.H_2833609._.OR_help-T_cn~zh-V_1#7f9c78ae99pwz)
diff --git a/docs/my-website/docs/providers/elevenlabs.md b/docs/my-website/docs/providers/elevenlabs.md
index 5cf62f51203..b4ed3d3346b 100644
--- a/docs/my-website/docs/providers/elevenlabs.md
+++ b/docs/my-website/docs/providers/elevenlabs.md
@@ -243,6 +243,13 @@ ElevenLabs provides high-quality text-to-speech capabilities through their TTS A
| Supported Operations | `/audio/speech` |
| Link to Provider Doc | [ElevenLabs TTS API ↗](https://elevenlabs.io/docs/api-reference/text-to-speech) |
+### Supported Models
+
+| Model | Route | Description |
+|-------|-------|-------------|
+| Eleven v3 | `elevenlabs/eleven_v3` | Most expressive model. 70+ languages, audio tags support for sound effects and pauses. |
+| Eleven Multilingual v2 | `elevenlabs/eleven_multilingual_v2` | Default TTS model. 29 languages, stable and production-ready. |
+
### Quick Start
#### LiteLLM Python SDK
@@ -265,6 +272,26 @@ with open("test_output.mp3", "wb") as f:
f.write(audio.read())
```
+#### Using Eleven v3 with Audio Tags
+
+Eleven v3 supports [audio tags](https://elevenlabs.io/docs/overview/capabilities/text-to-speech#audio-tags) for adding sound effects and pauses directly in the text:
+
+```python showLineNumbers title="Eleven v3 with audio tags"
+import litellm
+import os
+
+os.environ["ELEVENLABS_API_KEY"] = "your-elevenlabs-api-key"
+
+audio = litellm.speech(
+ model="elevenlabs/eleven_v3",
+ input='Welcome back. applause Today we have a special guest. Let me introduce them.',
+ voice="alloy",
+)
+
+with open("eleven_v3_output.mp3", "wb") as f:
+ f.write(audio.read())
+```
+
#### Advanced Usage: Overriding Parameters and ElevenLabs-Specific Features
```python showLineNumbers title="Advanced TTS with custom parameters"
diff --git a/docs/my-website/docs/providers/gemini.md b/docs/my-website/docs/providers/gemini.md
index 23a02f7365c..6de2263916c 100644
--- a/docs/my-website/docs/providers/gemini.md
+++ b/docs/my-website/docs/providers/gemini.md
@@ -1196,6 +1196,8 @@ When responding to Computer Use tool calls, include the URL and screenshot:
+
+
## Thought Signatures
Thought signatures are encrypted representations of the model's internal reasoning process for a given turn in a conversation. By passing thought signatures back to the model in subsequent requests, you provide it with the context of its previous thoughts, allowing it to build upon its reasoning and maintain a coherent line of inquiry.
@@ -1840,6 +1842,57 @@ content = response.get('choices', [{}])[0].get('message', {}).get('content')
print(content)
```
+## gemini-robotics-er-1.5-preview Usage
+
+```python
+from litellm import api_base
+from openai import OpenAI
+import os
+import base64
+
+client = OpenAI(base_url="http://0.0.0.0:4000", api_key="sk-12345")
+base64_image = base64.b64encode(open("closeup-object-on-table-many-260nw-1216144471.webp", "rb").read()).decode()
+
+import json
+import re
+tools = [{"codeExecution": {}}]
+response = client.chat.completions.create(
+ model="gemini/gemini-robotics-er-1.5-preview",
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "Point to no more than 10 items in the image. The label returned should be an identifying name for the object detected. The answer should follow the json format: [{\"point\": [y, x], \"label\": }, ...]. The points are in [y, x] format normalized to 0-1000."
+ },
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}
+ }
+ ]
+ }
+ ],
+ tools=tools
+)
+
+# Extract JSON from markdown code block if present
+content = response.choices[0].message.content
+# Look for triple-backtick JSON block
+match = re.search(r'```json\s*(.*?)\s*```', content, re.DOTALL)
+if match:
+ json_str = match.group(1)
+else:
+ json_str = content
+
+try:
+ data = json.loads(json_str)
+ print(json.dumps(data, indent=2))
+except Exception as e:
+ print("Error parsing response as JSON:", e)
+ print("Response content:", content)
+```
+
## Usage - PDF / Videos / etc. Files
### Inline Data (e.g. audio stream)
diff --git a/docs/my-website/docs/providers/github_copilot.md b/docs/my-website/docs/providers/github_copilot.md
index 306c9f949ec..e9fd3444f5f 100644
--- a/docs/my-website/docs/providers/github_copilot.md
+++ b/docs/my-website/docs/providers/github_copilot.md
@@ -35,11 +35,10 @@ from litellm import completion
response = completion(
model="github_copilot/gpt-4",
- messages=[{"role": "user", "content": "Write a Python function to calculate fibonacci numbers"}],
- extra_headers={
- "editor-version": "vscode/1.85.1",
- "Copilot-Integration-Id": "vscode-chat"
- }
+ messages=[
+ {"role": "system", "content": "You are a helpful coding assistant"},
+ {"role": "user", "content": "Write a Python function to calculate fibonacci numbers"}
+ ]
)
print(response)
```
@@ -50,11 +49,7 @@ from litellm import completion
stream = completion(
model="github_copilot/gpt-4",
messages=[{"role": "user", "content": "Explain async/await in Python"}],
- stream=True,
- extra_headers={
- "editor-version": "vscode/1.85.1",
- "Copilot-Integration-Id": "vscode-chat"
- }
+ stream=True
)
for chunk in stream:
@@ -134,11 +129,7 @@ client = OpenAI(
# Non-streaming response
response = client.chat.completions.create(
model="github_copilot/gpt-4",
- messages=[{"role": "user", "content": "How do I optimize this SQL query?"}],
- extra_headers={
- "editor-version": "vscode/1.85.1",
- "Copilot-Integration-Id": "vscode-chat"
- }
+ messages=[{"role": "user", "content": "How do I optimize this SQL query?"}]
)
print(response.choices[0].message.content)
@@ -156,11 +147,7 @@ response = litellm.completion(
model="litellm_proxy/github_copilot/gpt-4",
messages=[{"role": "user", "content": "Review this code for bugs"}],
api_base="http://localhost:4000",
- api_key="your-proxy-api-key",
- extra_headers={
- "editor-version": "vscode/1.85.1",
- "Copilot-Integration-Id": "vscode-chat"
- }
+ api_key="your-proxy-api-key"
)
print(response.choices[0].message.content)
@@ -174,8 +161,6 @@ print(response.choices[0].message.content)
curl http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-proxy-api-key" \
- -H "editor-version: vscode/1.85.1" \
- -H "Copilot-Integration-Id: vscode-chat" \
-d '{
"model": "github_copilot/gpt-4",
"messages": [{"role": "user", "content": "Explain this error message"}]
@@ -211,9 +196,11 @@ export GITHUB_COPILOT_API_KEY_FILE="api-key.json"
### Headers
-GitHub Copilot supports various editor-specific headers:
+LiteLLM automatically injects the required GitHub Copilot headers (simulating VSCode). You don't need to specify them manually.
-```python showLineNumbers title="Common Headers"
+If you want to override the defaults (e.g., to simulate a different editor), you can use `extra_headers`:
+
+```python showLineNumbers title="Custom Headers (Optional)"
extra_headers = {
"editor-version": "vscode/1.85.1", # Editor version
"editor-plugin-version": "copilot/1.155.0", # Plugin version
diff --git a/docs/my-website/docs/providers/litellm_proxy.md b/docs/my-website/docs/providers/litellm_proxy.md
index bfefc8a787c..918ac6755a5 100644
--- a/docs/my-website/docs/providers/litellm_proxy.md
+++ b/docs/my-website/docs/providers/litellm_proxy.md
@@ -227,6 +227,28 @@ response = litellm.completion(
)
```
+## OAuth2/JWT Authentication
+
+If your LiteLLM Proxy requires OAuth2/JWT authentication (e.g., Azure AD, Keycloak, Okta), the SDK can automatically obtain and refresh tokens for you.
+
+```python
+import litellm
+from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=AzureADCredential(),
+ scope="api://my-litellm-proxy/.default"
+)
+litellm.api_base = "https://my-proxy.example.com"
+
+response = litellm.completion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "Hello!"}]
+)
+```
+
+[Learn more about SDK Proxy Authentication (OAuth2/JWT Auto-Refresh) →](../proxy_auth)
+
## Sending `tags` to LiteLLM Proxy
Tags allow you to categorize and track your API requests for monitoring, debugging, and analytics purposes. You can send tags as a list of strings to the LiteLLM Proxy using the `extra_body` parameter.
diff --git a/docs/my-website/docs/providers/openai.md b/docs/my-website/docs/providers/openai.md
index 80645a51ac5..23940e1c54e 100644
--- a/docs/my-website/docs/providers/openai.md
+++ b/docs/my-website/docs/providers/openai.md
@@ -230,7 +230,70 @@ os.environ["OPENAI_BASE_URL"] = "https://your_host/v1" # OPTIONAL
These also support the `OPENAI_BASE_URL` environment variable, which can be used to specify a custom API endpoint.
-## OpenAI Vision Models
+### OpenAI Web Search Models
+
+OpenAI has two ways to use web search, depending on the endpoint:
+
+| Approach | Endpoint | Models | How to enable |
+|----------|----------|--------|---------------|
+| **Search Models** | `/chat/completions` | `gpt-5-search-api`, `gpt-4o-search-preview`, `gpt-4o-mini-search-preview` | Pass `web_search_options` parameter |
+| **Web Search Tool** | `/responses` | `gpt-5`, `gpt-4.1`, `gpt-4o`, and other regular models | Pass `web_search_preview` tool |
+
+
+
+
+```python showLineNumbers
+from litellm import completion
+
+response = completion(
+ model="openai/gpt-5-search-api",
+ messages=[{"role": "user", "content": "What is the capital of France?"}],
+ web_search_options={
+ "search_context_size": "medium" # Options: "low", "medium", "high"
+ }
+)
+```
+
+
+
+
+```python showLineNumbers
+from litellm import responses
+
+response = responses(
+ model="openai/gpt-5",
+ input="What is the capital of France?",
+ tools=[{
+ "type": "web_search_preview",
+ "search_context_size": "low"
+ }]
+)
+```
+
+
+
+
+```yaml
+model_list:
+ # Search model for /chat/completions
+ - model_name: gpt-5-search-api
+ litellm_params:
+ model: openai/gpt-5-search-api
+ api_key: os.environ/OPENAI_API_KEY
+
+ # Regular model for /responses with web_search_preview tool
+ - model_name: gpt-5
+ litellm_params:
+ model: openai/gpt-5
+ api_key: os.environ/OPENAI_API_KEY
+```
+
+
+
+
+For full details, see the [Web Search guide](../completion/web_search.md).
+
+## OpenAI Vision Models
| Model Name | Function Call |
|-----------------------|-----------------------------------------------------------------|
| gpt-4o | `response = completion(model="gpt-4o", messages=messages)` |
diff --git a/docs/my-website/docs/providers/openai/responses_api.md b/docs/my-website/docs/providers/openai/responses_api.md
index 75eab1afac5..7799c93ccf2 100644
--- a/docs/my-website/docs/providers/openai/responses_api.md
+++ b/docs/my-website/docs/providers/openai/responses_api.md
@@ -37,6 +37,24 @@ for event in response:
print(event)
```
+#### Web Search
+```python showLineNumbers title="OpenAI Responses with Web Search"
+import litellm
+
+response = litellm.responses(
+ model="openai/gpt-5",
+ input="What is the capital of France?",
+ tools=[{
+ "type": "web_search_preview",
+ "search_context_size": "medium" # Options: "low", "medium", "high"
+ }]
+)
+
+print(response)
+```
+
+For full details, see the [Web Search guide](../../completion/web_search.md).
+
#### Image Generation with Streaming
```python showLineNumbers title="OpenAI Streaming Image Generation"
import litellm
diff --git a/docs/my-website/docs/providers/perplexity.md b/docs/my-website/docs/providers/perplexity.md
index 2fcb49c60fa..e3991c63bff 100644
--- a/docs/my-website/docs/providers/perplexity.md
+++ b/docs/my-website/docs/providers/perplexity.md
@@ -120,6 +120,370 @@ All models listed here https://docs.perplexity.ai/docs/model-cards are supported
+## Agent API (Responses API)
+
+Requires v1.72.6+
+
+
+### Using Presets
+
+Presets provide optimized defaults for specific use cases. Start with a preset for quick setup:
+
+
+
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+# Using the pro-search preset
+response = responses(
+ model="perplexity/preset/pro-search",
+ input="What are the latest developments in AI?",
+ custom_llm_provider="perplexity",
+)
+
+print(response.output)
+```
+
+
+
+
+1. Setup config.yaml
+
+```yaml
+model_list:
+ - model_name: perplexity-pro-search
+ litellm_params:
+ model: perplexity/preset/pro-search
+ api_key: os.environ/PERPLEXITY_API_KEY
+```
+
+2. Start proxy
+
+```bash
+litellm --config /path/to/config.yaml
+```
+
+3. Test it!
+
+```bash
+curl http://0.0.0.0:4000/v1/responses \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer anything" \
+ -d '{
+ "model": "perplexity-pro-search",
+ "input": "What are the latest developments in AI?"
+ }'
+```
+
+
+
+
+### Using Third-Party Models
+
+Access models from OpenAI, Anthropic, Google, xAI, and other providers through Perplexity's unified API:
+
+
+
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/openai/gpt-5.2",
+ input="Explain quantum computing in simple terms",
+ custom_llm_provider="perplexity",
+ max_output_tokens=500,
+)
+
+print(response.output)
+```
+
+
+
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/anthropic/claude-sonnet-4-5",
+ input="Write a short story about a robot learning to paint",
+ custom_llm_provider="perplexity",
+ max_output_tokens=500,
+)
+
+print(response.output)
+```
+
+
+
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/google/gemini-2.5-flash",
+ input="Explain the concept of neural networks",
+ custom_llm_provider="perplexity",
+ max_output_tokens=500,
+)
+
+print(response.output)
+```
+
+
+
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/xai/grok-4-1-fast-non-reasoning",
+ input="What makes a good AI assistant?",
+ custom_llm_provider="perplexity",
+ max_output_tokens=500,
+)
+
+print(response.output)
+```
+
+
+
+
+### Web Search Tool
+
+Enable web search capabilities to access real-time information:
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/openai/gpt-5.2",
+ input="What's the weather in San Francisco today?",
+ custom_llm_provider="perplexity",
+ tools=[{"type": "web_search"}],
+ instructions="You have access to a web_search tool. Use it for questions about current events.",
+)
+
+print(response.output)
+```
+
+### Function Calling
+
+The Agent API supports custom function tools. Pass function tools through unchanged:
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/openai/gpt-5.2",
+ input="What's the weather in San Francisco?",
+ custom_llm_provider="perplexity",
+ tools=[
+ {"type": "web_search"},
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get the current weather for a location",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "location": {"type": "string"},
+ "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
+ },
+ },
+ },
+ },
+ ],
+ instructions="Use tools when appropriate.",
+)
+
+print(response.output)
+```
+
+### Structured Outputs
+
+Request JSON schema structured outputs via the `text` parameter:
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/preset/pro-search",
+ input="Extract key facts about the Eiffel Tower",
+ custom_llm_provider="perplexity",
+ text={
+ "format": {
+ "type": "json_schema",
+ "name": "facts",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "height_meters": {"type": "number"},
+ "year_built": {"type": "integer"},
+ },
+ "required": ["name", "height_meters", "year_built"],
+ },
+ "strict": True,
+ }
+ },
+)
+
+print(response.output)
+```
+
+
+### Reasoning Effort (Responses API)
+
+Control the reasoning effort level for reasoning-capable models:
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/openai/gpt-5.2",
+ input="Solve this complex problem step by step",
+ custom_llm_provider="perplexity",
+ reasoning={"effort": "high"}, # Options: low, medium, high
+ max_output_tokens=1000,
+)
+
+print(response.output)
+```
+
+### Multi-Turn Conversations
+
+Use message arrays for multi-turn conversations with context:
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/anthropic/claude-sonnet-4-5",
+ input=[
+ {"type": "message", "role": "system", "content": "You are a helpful assistant."},
+ {"type": "message", "role": "user", "content": "What are the latest AI developments?"},
+ ],
+ custom_llm_provider="perplexity",
+ instructions="Provide detailed, well-researched answers.",
+ max_output_tokens=800,
+)
+
+print(response.output)
+```
+
+### Streaming Responses
+
+Stream responses for real-time output:
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+response = responses(
+ model="perplexity/openai/gpt-5.2",
+ input="Tell me a story about space exploration",
+ custom_llm_provider="perplexity",
+ stream=True,
+ max_output_tokens=500,
+)
+
+for chunk in response:
+ if hasattr(chunk, 'type'):
+ if chunk.type == "response.output_text.delta":
+ print(chunk.delta, end="", flush=True)
+```
+
+### Supported Third-Party Models
+
+| Provider | Model Name | Function Call |
+|----------|------------|---------------|
+| OpenAI | gpt-5.2 | `responses(model="perplexity/openai/gpt-5.2", ...)` |
+| OpenAI | gpt-5.1 | `responses(model="perplexity/openai/gpt-5.1", ...)` |
+| OpenAI | gpt-5-mini | `responses(model="perplexity/openai/gpt-5-mini", ...)` |
+| Anthropic | claude-opus-4-6 | `responses(model="perplexity/anthropic/claude-opus-4-6", ...)` |
+| Anthropic | claude-opus-4-5 | `responses(model="perplexity/anthropic/claude-opus-4-5", ...)` |
+| Anthropic | claude-sonnet-4-5 | `responses(model="perplexity/anthropic/claude-sonnet-4-5", ...)` |
+| Anthropic | claude-haiku-4-5 | `responses(model="perplexity/anthropic/claude-haiku-4-5", ...)` |
+| Google | gemini-3-pro-preview | `responses(model="perplexity/google/gemini-3-pro-preview", ...)` |
+| Google | gemini-3-flash-preview | `responses(model="perplexity/google/gemini-3-flash-preview", ...)` |
+| Google | gemini-2.5-pro | `responses(model="perplexity/google/gemini-2.5-pro", ...)` |
+| Google | gemini-2.5-flash | `responses(model="perplexity/google/gemini-2.5-flash", ...)` |
+| xAI | grok-4-1-fast-non-reasoning | `responses(model="perplexity/xai/grok-4-1-fast-non-reasoning", ...)` |
+| Perplexity | sonar | `responses(model="perplexity/perplexity/sonar", ...)` |
+
+### Available Presets
+
+| Preset Name | Function Call |
+|-------------|---------------|
+| fast-search | `responses(model="perplexity/preset/fast-search", ...)` |
+| pro-search | `responses(model="perplexity/preset/pro-search", ...)` |
+| deep-research | `responses(model="perplexity/preset/deep-research", ...)` |
+| advanced-deep-research | `responses(model="perplexity/preset/advanced-deep-research", ...)` |
+
+### Complete Example
+
+```python
+from litellm import responses
+import os
+
+os.environ['PERPLEXITY_API_KEY'] = ""
+
+# Comprehensive example with multiple features
+response = responses(
+ model="perplexity/openai/gpt-5.2",
+ input="Research the latest developments in quantum computing and provide sources",
+ custom_llm_provider="perplexity",
+ tools=[
+ {"type": "web_search"},
+ {"type": "fetch_url"}
+ ],
+ instructions="Use web_search to find relevant information and fetch_url to retrieve detailed content from sources. Provide citations for all claims.",
+ max_output_tokens=1000,
+ temperature=0.7,
+)
+
+print(f"Response ID: {response.id}")
+print(f"Model: {response.model}")
+print(f"Status: {response.status}")
+print(f"Output: {response.output}")
+print(f"Usage: {response.usage}")
+```
+
:::info
For more information about passing provider-specific parameters, [go here](../completion/provider_specific_params.md)
diff --git a/docs/my-website/docs/providers/sarvam.md b/docs/my-website/docs/providers/sarvam.md
new file mode 100644
index 00000000000..6a292456781
--- /dev/null
+++ b/docs/my-website/docs/providers/sarvam.md
@@ -0,0 +1,92 @@
+# Sarvam.ai
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+LiteLLM supports all the text models from [Sarvam ai](https://docs.sarvam.ai/api-reference-docs/chat/chat-completions)
+
+## Usage
+
+```python
+import os
+from litellm import completion
+
+# Set your Sarvam API key
+os.environ["SARVAM_API_KEY"] = ""
+
+messages = [{"role": "user", "content": "Hello"}]
+
+response = completion(
+ model="sarvam/sarvam-m",
+ messages=messages,
+)
+print(response)
+```
+
+## Usage with LiteLLM Proxy Server
+
+Here's how to call a Sarvam.ai model with the LiteLLM Proxy Server
+
+1. **Modify the `config.yaml`:**
+
+ ```yaml
+ model_list:
+ - model_name: my-model
+ litellm_params:
+ model: sarvam/ # add sarvam/ prefix to route as Sarvam provider
+ api_key: api-key # api key to send your model
+ ```
+
+2. **Start the proxy:**
+
+ ```bash
+ $ litellm --config /path/to/config.yaml
+ ```
+
+3. **Send a request to LiteLLM Proxy Server:**
+
+
+
+
+
+ ```python
+ import openai
+
+ client = openai.OpenAI(
+ api_key="sk-1234", # pass litellm proxy key, if you're using virtual keys
+ base_url="http://0.0.0.0:4000" # litellm-proxy-base url
+ )
+
+ response = client.chat.completions.create(
+ model="my-model",
+ messages=[
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ],
+ )
+
+ print(response)
+ ```
+
+
+
+
+ ```shell
+ curl --location 'http://0.0.0.0:4000/chat/completions' \
+ --header 'Authorization: Bearer sk-1234' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "model": "my-model",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+ }'
+ ```
+
+
+
diff --git a/docs/my-website/docs/providers/scaleway.md b/docs/my-website/docs/providers/scaleway.md
new file mode 100644
index 00000000000..ea57c24db30
--- /dev/null
+++ b/docs/my-website/docs/providers/scaleway.md
@@ -0,0 +1,62 @@
+
+# Scaleway
+LiteLLM supports all [models available on Scaleway Generative APIs ↗](https://www.scaleway.com/en/docs/generative-apis/reference-content/supported-models/).
+
+## Usage with LiteLLM Python SDK
+
+```python
+import os
+from litellm import completion
+
+os.environ["SCW_SECRET_KEY"] = "your-scaleway-secret-key"
+
+messages = [{"role": "user", "content": "Write a short poem"}]
+response = completion(model="scaleway/qwen3-235b-a22b-instruct-2507", messages=messages)
+print(response)
+```
+
+## Usage with LiteLLM Proxy
+
+### 1. Set Scaleway models in config.yaml
+
+```yaml
+model_list:
+ - model_name: scaleway-model
+ litellm_params:
+ model: scaleway/qwen3-235b-a22b-instruct-2507
+ api_key: "os.environ/SCW_SECRET_KEY" # ensure you have `SCW_SECRET_KEY` in your .env
+```
+
+### 2. Start proxy
+
+```bash
+litellm --config config.yaml
+```
+
+### 3. Query proxy
+
+Assuming the proxy is running on [http://localhost:4000](http://localhost:4000):
+```bash
+curl http://localhost:4000/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer YOUR_LITELLM_MASTER_KEY" \
+ -d '{
+ "model": "scaleway-model",
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant."
+ },
+ {
+ "role": "user",
+ "content": "Write a short poem"
+ }
+ ]
+ }'
+```
+`-H "Authorization: Bearer YOUR_LITELLM_MASTER_KEY" ` is only required if you have set a LiteLLM master key
+
+
+## Supported features
+
+Scaleway provider supports all features in [Generative APIs reference documentation ↗](https://www.scaleway.com/en/developers/api/generative-apis/), such as streaming, structured outputs and tool calling.
diff --git a/docs/my-website/docs/providers/vertex_speech.md b/docs/my-website/docs/providers/vertex_speech.md
index d0acacb5aec..751782a323c 100644
--- a/docs/my-website/docs/providers/vertex_speech.md
+++ b/docs/my-website/docs/providers/vertex_speech.md
@@ -312,6 +312,7 @@ Gemini models with audio output capabilities using the chat completions API.
- Only supports `pcm16` audio format
- Streaming not yet supported
- Must set `modalities: ["audio"]`
+- When using via LiteLLM Proxy, must include `"allowed_openai_params": ["audio", "modalities"]` in the request body to enable audio parameters
:::
### Quick Start
@@ -372,7 +373,8 @@ curl http://0.0.0.0:4000/v1/chat/completions \
"model": "gemini-tts",
"messages": [{"role": "user", "content": "Say hello in a friendly voice"}],
"modalities": ["audio"],
- "audio": {"voice": "Kore", "format": "pcm16"}
+ "audio": {"voice": "Kore", "format": "pcm16"},
+ "allowed_openai_params": ["audio", "modalities"]
}'
```
@@ -389,6 +391,7 @@ response = client.chat.completions.create(
messages=[{"role": "user", "content": "Say hello in a friendly voice"}],
modalities=["audio"],
audio={"voice": "Kore", "format": "pcm16"},
+ extra_body={"allowed_openai_params": ["audio", "modalities"]}
)
print(response)
```
diff --git a/docs/my-website/docs/providers/watsonx/rerank.md b/docs/my-website/docs/providers/watsonx/rerank.md
new file mode 100644
index 00000000000..0900ce96781
--- /dev/null
+++ b/docs/my-website/docs/providers/watsonx/rerank.md
@@ -0,0 +1,52 @@
+# watsonx.ai Rerank
+
+## Overview
+
+| Property | Details |
+|----------|--------------------------------------------------------------------------|
+| Description | watsonx.ai rerank integration |
+| Provider Route on LiteLLM | `watsonx/` |
+| Supported Operations | `/ml/v1/text/rerank` |
+| Link to Provider Doc | [IBM WatsonX.ai ↗](https://cloud.ibm.com/apidocs/watsonx-ai#text-rerank) |
+
+## Quick Start
+
+### **LiteLLM SDK**
+
+```python
+import os
+from litellm import rerank
+
+os.environ["WATSONX_APIKEY"] = "YOUR_WATSONX_APIKEY"
+os.environ["WATSONX_API_BASE"] = "YOUR_WATSONX_API_BASE"
+os.environ["WATSONX_PROJECT_ID"] = "YOUR_WATSONX_PROJECT_ID"
+
+query="Best programming language for beginners?"
+documents=[
+ "Python is great for beginners due to simple syntax.",
+ "JavaScript runs in browsers and is versatile.",
+ "Rust has a steep learning curve but is very safe.",
+]
+
+response = rerank(
+ model="watsonx/cross-encoder/ms-marco-minilm-l-12-v2",
+ query=query,
+ documents=documents,
+ top_n=2,
+ return_documents=True,
+)
+
+print(response)
+```
+
+### **LiteLLM Proxy**
+
+```yaml
+model_list:
+ - model_name: cross-encoder/ms-marco-minilm-l-12-v2
+ litellm_params:
+ model: watsonx/cross-encoder/ms-marco-minilm-l-12-v2
+ api_key: os.environ/WATSONX_APIKEY
+ api_base: os.environ/WATSONX_API_BASE
+ project_id: os.environ/WATSONX_PROJECT_ID
+```
diff --git a/docs/my-website/docs/providers/xai_realtime.md b/docs/my-website/docs/providers/xai_realtime.md
new file mode 100644
index 00000000000..b36908c4686
--- /dev/null
+++ b/docs/my-website/docs/providers/xai_realtime.md
@@ -0,0 +1,308 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# xAI Voice Agent (Realtime API)
+
+xAI's Grok Voice Agent provides real-time voice conversation capabilities through WebSocket connections, enabling natural bidirectional audio interactions.
+
+| Feature | Description | Comments |
+| --- | --- | --- |
+| LiteLLM AI Gateway | ✅ | |
+| LiteLLM Python SDK | ✅ | Full support via `litellm.realtime()` |
+
+## Quick Start
+
+### Supported Model
+
+| Model | Context | Features |
+|-------|---------|----------|
+| `xai/grok-4-1-fast-non-reasoning` | 2M tokens | Voice conversation, Function calling, Vision, Audio, Web search, Caching |
+
+**Note:** xAI Realtime API uses the non-reasoning variant for optimal real-time performance.
+
+## Python SDK Usage
+
+### Basic Realtime Connection
+
+```python
+import asyncio
+from litellm import realtime
+
+async def test_xai_realtime():
+ """
+ Test xAI Grok Voice Agent via LiteLLM SDK
+ """
+ # Initialize realtime connection
+ ws = await realtime(
+ model="xai/grok-4-1-fast-non-reasoning",
+ api_key="your-xai-api-key", # or set XAI_API_KEY env var
+ )
+
+ # Connection established, xAI sends "conversation.created" event
+ print("Connected to xAI Grok Voice Agent")
+
+ # Send a message
+ await ws.send_text(json.dumps({
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [{
+ "type": "input_text",
+ "text": "Hello! How are you?"
+ }]
+ }
+ }))
+
+ # Request a response
+ await ws.send_text(json.dumps({
+ "type": "response.create"
+ }))
+
+ # Listen for responses
+ async for message in ws:
+ data = json.loads(message)
+ print(f"Received: {data['type']}")
+
+ if data['type'] == 'response.done':
+ break
+
+ await ws.close()
+
+# Run the async function
+asyncio.run(test_xai_realtime())
+```
+
+### With Audio Input/Output
+
+```python
+import asyncio
+import json
+from litellm import realtime
+
+async def xai_voice_conversation():
+ """
+ Voice conversation with xAI Grok Voice Agent
+ """
+ ws = await realtime(
+ model="xai/grok-4-1-fast-non-reasoning",
+ api_key="your-xai-api-key",
+ )
+
+ # Send audio data (base64 encoded PCM16 24kHz)
+ await ws.send_text(json.dumps({
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [{
+ "type": "input_audio",
+ "audio": "base64_encoded_audio_data_here"
+ }]
+ }
+ }))
+
+ # Request response with audio
+ await ws.send_text(json.dumps({
+ "type": "response.create",
+ "response": {
+ "modalities": ["text", "audio"],
+ "instructions": "Please respond in a friendly tone."
+ }
+ }))
+
+ # Process streaming audio response
+ async for message in ws:
+ data = json.loads(message)
+
+ if data['type'] == 'response.audio.delta':
+ # Handle audio chunks
+ audio_chunk = data['delta']
+ # Process audio_chunk (play it, save it, etc.)
+
+ elif data['type'] == 'response.done':
+ break
+
+ await ws.close()
+
+asyncio.run(xai_voice_conversation())
+```
+
+## LiteLLM Proxy (AI Gateway) Usage
+
+Load balance across multiple xAI deployments or combine with other providers.
+
+### 1. Add Model to Config
+
+```yaml
+model_list:
+ - model_name: grok-voice-agent
+ litellm_params:
+ model: xai/grok-4-1-fast-non-reasoning
+ api_key: os.environ/XAI_API_KEY
+ model_info:
+ mode: realtime
+
+ # Optional: Add fallback to OpenAI
+ - model_name: grok-voice-agent
+ litellm_params:
+ model: openai/gpt-4o-realtime-preview-2024-10-01
+ api_key: os.environ/OPENAI_API_KEY
+ model_info:
+ mode: realtime
+```
+
+### 2. Start Proxy
+
+```bash
+litellm --config /path/to/config.yaml
+
+# RUNNING on http://0.0.0.0:4000
+```
+
+### 3. Test Connection
+
+#### Python Client
+
+```python
+import asyncio
+import websockets
+import json
+
+async def test_proxy():
+ url = "ws://0.0.0.0:4000/v1/realtime?model=grok-voice-agent"
+
+ async with websockets.connect(
+ url,
+ extra_headers={
+ "Authorization": "Bearer sk-1234", # Your LiteLLM proxy key
+ "OpenAI-Beta": "realtime=v1"
+ }
+ ) as ws:
+ # Wait for conversation.created event from xAI
+ message = await ws.recv()
+ print(f"Connected: {message}")
+
+ # Send a message
+ await ws.send(json.dumps({
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [{
+ "type": "input_text",
+ "text": "Hello from LiteLLM proxy!"
+ }]
+ }
+ }))
+
+ # Request response
+ await ws.send(json.dumps({
+ "type": "response.create"
+ }))
+
+ # Listen for response
+ async for message in ws:
+ data = json.loads(message)
+ print(f"Event: {data['type']}")
+
+ if data['type'] == 'response.done':
+ break
+
+asyncio.run(test_proxy())
+```
+
+#### Node.js Client
+
+```javascript
+// test.js - Run with: node test.js
+const WebSocket = require("ws");
+
+const url = "ws://0.0.0.0:4000/v1/realtime?model=grok-voice-agent";
+
+const ws = new WebSocket(url, {
+ headers: {
+ "Authorization": "Bearer sk-1234",
+ "OpenAI-Beta": "realtime=v1",
+ },
+});
+
+ws.on("open", function open() {
+ console.log("Connected to xAI via LiteLLM proxy");
+
+ // Send a message
+ ws.send(JSON.stringify({
+ type: "conversation.item.create",
+ item: {
+ type: "message",
+ role: "user",
+ content: [{
+ type: "input_text",
+ text: "What's the weather like?"
+ }]
+ }
+ }));
+
+ // Request response
+ ws.send(JSON.stringify({
+ type: "response.create",
+ response: {
+ modalities: ["text"],
+ instructions: "Please assist the user."
+ }
+ }));
+});
+
+ws.on("message", function incoming(message) {
+ const data = JSON.parse(message.toString());
+ console.log(`Event: ${data.type}`);
+
+ if (data.type === 'response.done') {
+ ws.close();
+ }
+});
+
+ws.on("error", function handleError(error) {
+ console.error("Error: ", error);
+});
+```
+
+## Key Differences from OpenAI
+
+xAI's Grok Voice Agent has some differences from OpenAI's Realtime API:
+
+| Feature | xAI | OpenAI | LiteLLM Handling |
+|---------|-----|--------|------------------|
+| Initial Event | `conversation.created` | `session.created` | ⚠️ Passed through as-is |
+| WebSocket URL | `wss://api.x.ai/v1/realtime` | `wss://api.openai.com/v1/realtime` | ✅ Auto-configured |
+| Model | `grok-4-1-fast-non-reasoning` | `gpt-4o-realtime-preview` | ✅ Via model prefix |
+| Audio Format | PCM16 24kHz mono | PCM16 24kHz mono | ✅ Compatible |
+| Context Window | 2M tokens | 128K tokens | N/A |
+
+**What LiteLLM Handles:**
+- ✅ Automatic URL routing to correct provider
+- ✅ Authentication headers (no `OpenAI-Beta` header for xAI)
+- ✅ WebSocket connection management
+- ✅ All other event types are compatible
+
+**What You Need to Handle:**
+- ⚠️ Initial event type difference (`conversation.created` vs `session.created`)
+
+**Tip:** Make your client compatible with both event types:
+```python
+# Handle both providers
+if event['type'] in ['session.created', 'conversation.created']:
+ print("Connection established")
+```
+
+## Related Documentation
+
+- [xAI Chat/Text Models](/docs/providers/xai)
+- [LiteLLM Realtime API Overview](/docs/realtime)
+- [xAI Official Documentation](https://docs.x.ai/docs)
+
+## Support
+
+For issues or questions:
+- [LiteLLM GitHub Issues](https://github.com/BerriAI/litellm/issues)
+- [xAI Documentation](https://docs.x.ai/docs)
diff --git a/docs/my-website/docs/proxy/access_groups.md b/docs/my-website/docs/proxy/access_groups.md
new file mode 100644
index 00000000000..59904575da8
--- /dev/null
+++ b/docs/my-website/docs/proxy/access_groups.md
@@ -0,0 +1,122 @@
+import Image from '@theme/IdealImage';
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Access Groups
+
+Access Groups simplify how you define and manage resource access across your organization. Instead of configuring models, MCP servers, and agents separately on each key or team, you create one group that bundles the resources you want to grant, then attach that group to your keys or teams.
+
+## Overview
+
+**Access Groups** let you define a reusable set of allowed resources—models, MCP servers, and agents—in a single place. One group can grant access to all three resource types. Simply attach the group to a key or team, and they get access to everything defined in that group.
+
+- **Unified resource control** – One group controls access to models, MCP servers, and agents together
+- **Reusable** – Define once, attach to many keys or teams
+- **Easy to maintain** – Update the group (add or remove resources) and all attached keys and teams automatically reflect the change
+- **Clear visibility** – See exactly which resources each group grants and which keys/teams use it
+
+
+
+### How It Works
+
+**Key concept:** Define resources in a group → Attach group to key or team → Key/team gets access to all resources in the group
+
+| Resource Type | What the group controls |
+| --------------- | -------------------------------------------------------------------- |
+| **Models** | Which LLM models keys/teams can use (e.g., `gpt-4`, `claude-3-opus`) |
+| **MCP Servers** | Which MCP servers are available for tool calling |
+| **Agents** | Which agents can be invoked |
+
+## How to Create and Use Access Groups in the UI
+
+### 1. Navigate to Access Groups
+
+Go to the Admin UI (e.g. `http://localhost:4000/ui` or your `PROXY_BASE_URL/ui`) and click **Access Groups** in the sidebar.
+
+
+
+### 2. Create an Access Group
+
+Click **Create Access Group** and give your group a name.
+
+
+
+
+
+### 3. Define Resources in the Group
+
+Use the tabs to select which models, MCP servers, and agents this group grants access to:
+
+- **Models tab** – Select the LLM models
+- **MCP Servers tab** – Select MCP servers (for tool calling)
+- **Agents tab** – Select agents
+
+
+
+
+
+
+
+### 4. Attach the Access Group to a Key
+
+When creating or editing a virtual key, expand **Optional Settings** and select your Access Group. The key will inherit access to all models, MCP servers, and agents defined in that group.
+
+1. Go to **Virtual Keys** and click **+ Create New Key**
+2. Expand **Optional Settings**
+3. In the Access Group field, select the group you created
+4. Save the key
+
+
+
+
+
+
+
+
+
+
+
+### 5. Attach the Access Group to a Team
+
+You can also attach an Access Group to a team when creating or editing the team. All keys associated with that team will then have access to the resources defined in the group.
+
+## Use Cases
+
+### Team-based Access
+
+Create groups like "Engineering", "Data Science", or "Product" with the models, MCP servers, and agents each team needs. Attach the group to the team—no need to configure each resource on every key.
+
+### Environment Separation
+
+- **Production group** – Production models, approved MCP servers, and production agents
+- **Development group** – Cost-efficient models, experimental MCP tools, and dev agents
+
+Attach the appropriate group to keys or teams based on environment.
+
+### Simplified Onboarding
+
+New developers get a key with an Access Group instead of manually configuring models, MCP servers, and agents. Add them to the right team or give them a key with the correct group.
+
+### Centralized Updates
+
+When you add a new model or MCP server to a group, every key and team attached to that group automatically gains access. Remove a resource from the group and it’s revoked everywhere at once.
+
+## Access Group vs. Model Access Groups
+
+LiteLLM has two related concepts:
+
+| Feature | **Access Groups** (this page) | **Model Access Groups** |
+| ---------- | ----------------------------------------------------------------------- | ------------------------------------------------------- |
+| Definition | Define in the UI; one group can include models, MCP servers, and agents | Defined in config or via API; groups are model-centric |
+| Scope | Models + MCP servers + agents | Models only |
+| Attach to | Keys, teams | Keys, teams |
+| Use when | You want unified control over models, MCP, and agents from the UI | You need config-based or API-based model access control |
+
+For config-based model access with `access_groups` in `model_info`, see [Model Access Groups](./model_access_groups.md).
+
+## Related Documentation
+
+- [Virtual Keys](./virtual_keys.md) – Creating and managing API keys
+- [Role-based Access Controls](./access_control.md) – Organizations, teams, and user roles
+- [Model Access Groups](./model_access_groups.md) – Config-based model access groups
+- [MCP Control](../mcp_control.md) – MCP server setup and access control
diff --git a/docs/my-website/docs/proxy/admin_ui_sso.md b/docs/my-website/docs/proxy/admin_ui_sso.md
index 7b299429db7..f88d3480446 100644
--- a/docs/my-website/docs/proxy/admin_ui_sso.md
+++ b/docs/my-website/docs/proxy/admin_ui_sso.md
@@ -23,26 +23,75 @@ From v1.76.0, SSO is now Free for up to 5 users.
-1. Add Okta credentials to your .env
+#### Step 1: Create an OIDC Application in Okta
+
+In your Okta Admin Console, create a new **OIDC Web Application**. See [Okta's guide on creating OIDC app integrations](https://help.okta.com/en-us/content/topics/apps/apps_app_integration_wizard_oidc.htm) for detailed instructions.
+
+When configuring the application:
+- **Sign-in redirect URI**: `https:///sso/callback`
+- **Sign-out redirect URI** (optional): `https://`
+
+
+
+After creating the app, copy your **Client ID** and **Client Secret** from the application's General tab:
+
+
+
+#### Step 2: Assign Users to the Application
+
+Ensure users are assigned to the app in the **Assignments** tab. If Federation Broker Mode is enabled, you may need to disable it to assign users manually.
+
+#### Step 3: Configure Authorization Server Access Policy
+
+:::warning Important
+This step is required. Without an Access Policy for your app, users will get a `no_matching_policy` error when attempting to log in.
+:::
+
+1. Go to **Security** → **API**
+
+
+
+2. Select the **default** authorization server (or your custom one)
+
+
+
+3. Click on **Access Policies** tab, create a new policy assigned to your LiteLLM app
+4. Add a rule that allows the **Authorization Code** grant type
+
+
+
+See [Okta's Access Policy documentation](https://help.okta.com/en-us/content/topics/security/api-access-management/access-policies.htm) for more details.
+
+#### Step 4: Configure LiteLLM Environment Variables
```bash
-GENERIC_CLIENT_ID = ""
-GENERIC_CLIENT_SECRET = ""
-GENERIC_AUTHORIZATION_ENDPOINT = "/authorize" # https://dev-2kqkcd6lx6kdkuzt.us.auth0.com/authorize
-GENERIC_TOKEN_ENDPOINT = "/token" # https://dev-2kqkcd6lx6kdkuzt.us.auth0.com/oauth/token
-GENERIC_USERINFO_ENDPOINT = "/userinfo" # https://dev-2kqkcd6lx6kdkuzt.us.auth0.com/userinfo
-GENERIC_CLIENT_STATE = "random-string" # [OPTIONAL] REQUIRED BY OKTA, if not set random state value is generated
-GENERIC_SSO_HEADERS = "Content-Type=application/json, X-Custom-Header=custom-value" # [OPTIONAL] Comma-separated list of additional headers to add to the request - e.g. Content-Type=application/json, etc.
+GENERIC_CLIENT_ID=""
+GENERIC_CLIENT_SECRET=""
+GENERIC_AUTHORIZATION_ENDPOINT="https:///oauth2/default/v1/authorize"
+GENERIC_TOKEN_ENDPOINT="https:///oauth2/default/v1/token"
+GENERIC_USERINFO_ENDPOINT="https:///oauth2/default/v1/userinfo"
+GENERIC_CLIENT_STATE="random-string"
+PROXY_BASE_URL="https://"
```
-You can get your domain specific auth/token/userinfo endpoints at `/.well-known/openid-configuration`
+:::tip
+You can find all OAuth endpoints at `https:///.well-known/openid-configuration`
+:::
-2. Add proxy url as callback_url on Okta
+#### Step 5: Test the SSO Flow
-On Okta, add the 'callback_url' as `/sso/callback`
+1. Start your LiteLLM proxy
+2. Navigate to `https:///ui`
+3. Click the SSO login button
+4. Authenticate with Okta and verify you're redirected back to LiteLLM
+#### Troubleshooting
-
+| Error | Cause | Solution |
+|-------|-------|----------|
+| `redirect_uri` error | Redirect URI not configured | Add `/sso/callback` to Sign-in redirect URIs in Okta |
+| `access_denied` | User not assigned to app | Assign the user in the Assignments tab |
+| `no_matching_policy` | Missing Access Policy | Create an Access Policy in the Authorization Server (see Step 3) |
@@ -174,6 +223,7 @@ GENERIC_USER_FIRST_NAME_ATTRIBUTE = "first_name"
GENERIC_USER_LAST_NAME_ATTRIBUTE = "last_name"
GENERIC_USER_ROLE_ATTRIBUTE = "given_role"
GENERIC_USER_PROVIDER_ATTRIBUTE = "provider"
+GENERIC_USER_EXTRA_ATTRIBUTES = "department,employee_id,manager" # comma-separated list of additional fields to extract from SSO response
GENERIC_CLIENT_STATE = "some-state" # if the provider needs a state parameter
GENERIC_INCLUDE_CLIENT_ID = "false" # some providers enforce that the client_id is not in the body
GENERIC_SCOPE = "openid profile email" # default scope openid is sometimes not enough to retrieve basic user info like first_name and last_name located in profile scope
@@ -190,6 +240,40 @@ Use `GENERIC_USER_ROLE_ATTRIBUTE` to specify which attribute in the SSO token co
Nested attribute paths are supported (e.g., `claims.role` or `attributes.litellm_role`).
+**Capturing Additional SSO Fields**
+
+Use `GENERIC_USER_EXTRA_ATTRIBUTES` to extract additional fields from the SSO provider response beyond the standard user attributes (id, email, name, etc.). This is useful when you need to access custom organization-specific data (e.g., department, employee ID, groups) in your [custom SSO handler](./custom_sso.md).
+
+```shell
+# Comma-separated list of field names to extract
+GENERIC_USER_EXTRA_ATTRIBUTES="department,employee_id,manager,groups"
+```
+
+**Accessing Extra Fields in Custom SSO Handler:**
+
+```python
+from litellm.proxy.management_endpoints.types import CustomOpenID
+
+async def custom_sso_handler(userIDPInfo: CustomOpenID):
+ # Access the extra fields
+ extra_fields = getattr(userIDPInfo, 'extra_fields', None) or {}
+
+ user_department = extra_fields.get("department")
+ employee_id = extra_fields.get("employee_id")
+ user_groups = extra_fields.get("groups", [])
+
+ # Use these fields for custom logic (e.g., team assignment, access control)
+ # ...
+```
+
+**Nested Field Paths:**
+
+Dot notation is supported for nested fields:
+
+```shell
+GENERIC_USER_EXTRA_ATTRIBUTES="org_info.department,org_info.cost_center,metadata.employee_type"
+```
+
- Set Redirect URI, if your provider requires it
- Set a redirect url = `/sso/callback`
```shell
diff --git a/docs/my-website/docs/proxy/call_hooks.md b/docs/my-website/docs/proxy/call_hooks.md
index fe865f67e09..17354725fd5 100644
--- a/docs/my-website/docs/proxy/call_hooks.md
+++ b/docs/my-website/docs/proxy/call_hooks.md
@@ -19,6 +19,7 @@ import Image from '@theme/IdealImage';
| `async_post_call_success_hook` | Modify outgoing response (non-streaming) | After successful LLM API call, for non-streaming responses |
| `async_post_call_failure_hook` | Transform error responses sent to clients | After failed LLM API call |
| `async_post_call_streaming_hook` | Modify outgoing response (streaming) | After successful LLM API call, for streaming responses |
+| `async_post_call_response_headers_hook` | Inject custom HTTP response headers | After LLM API call (both success and failure) |
See a complete example with our [parallel request rate limiter](https://github.com/BerriAI/litellm/blob/main/litellm/proxy/hooks/parallel_request_limiter.py)
@@ -115,6 +116,18 @@ class MyCustomHandler(CustomLogger): # https://docs.litellm.ai/docs/observabilit
async for item in response:
yield item
+ async def async_post_call_response_headers_hook(
+ self,
+ data: dict,
+ user_api_key_dict: UserAPIKeyAuth,
+ response: Any,
+ request_headers: Optional[Dict[str, str]] = None,
+ ) -> Optional[Dict[str, str]]:
+ """
+ Inject custom headers into HTTP response (runs for both success and failure).
+ """
+ return {"x-custom-header": "custom-value"}
+
proxy_handler_instance = MyCustomHandler()
```
@@ -389,3 +402,31 @@ proxy_handler_instance = MyErrorTransformer()
```
**Result:** Clients receive `"Your prompt is too long..."` instead of `"ContextWindowExceededError: Prompt exceeds context window"`.
+
+## Advanced - Inject Custom HTTP Response Headers
+
+Use `async_post_call_response_headers_hook` to inject custom HTTP headers into responses. This hook runs for **both successful and failed** LLM API calls.
+
+```python
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.proxy.proxy_server import UserAPIKeyAuth
+from typing import Any, Dict, Optional
+
+class CustomHeaderLogger(CustomLogger):
+ def __init__(self):
+ super().__init__()
+
+ async def async_post_call_response_headers_hook(
+ self,
+ data: dict,
+ user_api_key_dict: UserAPIKeyAuth,
+ response: Any,
+ request_headers: Optional[Dict[str, str]] = None,
+ ) -> Optional[Dict[str, str]]:
+ """
+ Inject custom headers into all responses (success and failure).
+ """
+ return {"x-custom-header": "custom-value"}
+
+proxy_handler_instance = CustomHeaderLogger()
+```
diff --git a/docs/my-website/docs/proxy/cli.md b/docs/my-website/docs/proxy/cli.md
index 9244f75b756..d3624000a32 100644
--- a/docs/my-website/docs/proxy/cli.md
+++ b/docs/my-website/docs/proxy/cli.md
@@ -1,7 +1,10 @@
# CLI Arguments
-Cli arguments, --host, --port, --num_workers
-## --host
+This page documents all command-line interface (CLI) arguments available for the LiteLLM proxy server.
+
+## Server Configuration
+
+### --host
- **Default:** `'0.0.0.0'`
- The host for the server to listen on.
- **Usage:**
@@ -14,7 +17,7 @@ Cli arguments, --host, --port, --num_workers
litellm
```
-## --port
+### --port
- **Default:** `4000`
- The port to bind the server to.
- **Usage:**
@@ -27,9 +30,9 @@ Cli arguments, --host, --port, --num_workers
litellm
```
-## --num_workers
- - **Default:** `1`
- - The number of uvicorn workers to spin up.
+### --num_workers
+ - **Default:** Number of logical CPUs in the system, or `4` if that cannot be determined
+ - The number of uvicorn / gunicorn workers to spin up.
- **Usage:**
```shell
litellm --num_workers 4
@@ -40,55 +43,273 @@ Cli arguments, --host, --port, --num_workers
litellm
```
-## --api_base
+### --config
+ - **Short form:** `-c`
- **Default:** `None`
- - The API base for the model litellm should call.
+ - Path to the proxy configuration file (e.g., config.yaml).
+ - **Usage:**
+ ```shell
+ litellm --config path/to/config.yaml
+ ```
+
+### --log_config
+ - **Default:** `None`
+ - **Type:** `str`
+ - Path to the logging configuration file for uvicorn.
+ - **Usage:**
+ ```shell
+ litellm --log_config path/to/log_config.conf
+ ```
+
+### --keepalive_timeout
+ - **Default:** `None`
+ - **Type:** `int`
+ - Set the uvicorn keepalive timeout in seconds (uvicorn timeout_keep_alive parameter).
+ - **Usage:**
+ ```shell
+ litellm --keepalive_timeout 30
+ ```
+ - **Usage - set Environment Variable:** `KEEPALIVE_TIMEOUT`
+ ```shell
+ export KEEPALIVE_TIMEOUT=30
+ litellm
+ ```
+
+### --max_requests_before_restart
+ - **Default:** `None`
+ - **Type:** `int`
+ - Restart worker after this many requests. This is useful for mitigating memory growth over time.
+ - For uvicorn: maps to `limit_max_requests`
+ - For gunicorn: maps to `max_requests`
+ - **Usage:**
+ ```shell
+ litellm --max_requests_before_restart 10000
+ ```
+ - **Usage - set Environment Variable:** `MAX_REQUESTS_BEFORE_RESTART`
+ ```shell
+ export MAX_REQUESTS_BEFORE_RESTART=10000
+ litellm
+ ```
+
+## Server Backend Options
+
+### --run_gunicorn
+ - **Default:** `False`
+ - **Type:** `bool` (Flag)
+ - Starts proxy via gunicorn instead of uvicorn. Better for managing multiple workers in production.
+ - **Usage:**
+ ```shell
+ litellm --run_gunicorn
+ ```
+
+### --run_hypercorn
+ - **Default:** `False`
+ - **Type:** `bool` (Flag)
+ - Starts proxy via hypercorn instead of uvicorn. Supports HTTP/2.
+ - **Usage:**
+ ```shell
+ litellm --run_hypercorn
+ ```
+
+### --skip_server_startup
+ - **Default:** `False`
+ - **Type:** `bool` (Flag)
+ - Skip starting the server after setup (useful for database migrations only).
+ - **Usage:**
+ ```shell
+ litellm --skip_server_startup
+ ```
+
+## SSL/TLS Configuration
+
+### --ssl_keyfile_path
+ - **Default:** `None`
+ - **Type:** `str`
+ - Path to the SSL keyfile. Use this when you want to provide SSL certificate when starting proxy.
+ - **Usage:**
+ ```shell
+ litellm --ssl_keyfile_path /path/to/key.pem --ssl_certfile_path /path/to/cert.pem
+ ```
+ - **Usage - set Environment Variable:** `SSL_KEYFILE_PATH`
+ ```shell
+ export SSL_KEYFILE_PATH=/path/to/key.pem
+ litellm
+ ```
+
+### --ssl_certfile_path
+ - **Default:** `None`
+ - **Type:** `str`
+ - Path to the SSL certfile. Use this when you want to provide SSL certificate when starting proxy.
+ - **Usage:**
+ ```shell
+ litellm --ssl_certfile_path /path/to/cert.pem --ssl_keyfile_path /path/to/key.pem
+ ```
+ - **Usage - set Environment Variable:** `SSL_CERTFILE_PATH`
+ ```shell
+ export SSL_CERTFILE_PATH=/path/to/cert.pem
+ litellm
+ ```
+
+### --ciphers
+ - **Default:** `None`
+ - **Type:** `str`
+ - Ciphers to use for the SSL setup. Only used with `--run_hypercorn`.
+ - **Usage:**
+ ```shell
+ litellm --run_hypercorn --ssl_keyfile_path /path/to/key.pem --ssl_certfile_path /path/to/cert.pem --ciphers "ECDHE+AESGCM"
+ ```
+
+## Model Configuration
+
+### --model or -m
+ - **Default:** `None`
+ - The model name to pass to LiteLLM.
+ - **Usage:**
+ ```shell
+ litellm --model gpt-3.5-turbo
+ ```
+
+### --alias
+ - **Default:** `None`
+ - An alias for the model, for user-friendly reference. Use this to give a litellm model name (e.g., "huggingface/codellama/CodeLlama-7b-Instruct-hf") a more user-friendly name ("codellama").
+ - **Usage:**
+ ```shell
+ litellm --alias my-gpt-model
+ ```
+
+### --api_base
+ - **Default:** `None`
+ - The API base for the model LiteLLM should call.
- **Usage:**
```shell
litellm --model huggingface/tinyllama --api_base https://k58ory32yinf1ly0.us-east-1.aws.endpoints.huggingface.cloud
```
-## --api_version
- - **Default:** `None`
+### --api_version
+ - **Default:** `2024-07-01-preview`
- For Azure services, specify the API version.
- **Usage:**
```shell
litellm --model azure/gpt-deployment --api_version 2023-08-01 --api_base https://"
```
-## --model or -m
+### --headers
- **Default:** `None`
- - The model name to pass to Litellm.
+ - Headers for the API call (as JSON string).
- **Usage:**
```shell
- litellm --model gpt-3.5-turbo
+ litellm --model my-model --headers '{"Authorization": "Bearer token"}'
```
-## --test
- - **Type:** `bool` (Flag)
- - Proxy chat completions URL to make a test request.
- - **Usage:**
- ```shell
- litellm --test
- ```
-
-## --health
- - **Type:** `bool` (Flag)
- - Runs a health check on all models in config.yaml
- - **Usage:**
- ```shell
- litellm --health
- ```
-
-## --alias
+### --add_key
- **Default:** `None`
- - An alias for the model, for user-friendly reference.
+ - Add a key to the model configuration.
- **Usage:**
```shell
- litellm --alias my-gpt-model
+ litellm --add_key my-api-key
```
-## --debug
+### --save
+ - **Type:** `bool` (Flag)
+ - Save the model-specific config.
+ - **Usage:**
+ ```shell
+ litellm --model gpt-3.5-turbo --save
+ ```
+
+## Model Parameters
+
+### --temperature
+ - **Default:** `None`
+ - **Type:** `float`
+ - Set the temperature for the model.
+ - **Usage:**
+ ```shell
+ litellm --temperature 0.7
+ ```
+
+### --max_tokens
+ - **Default:** `None`
+ - **Type:** `int`
+ - Set the maximum number of tokens for the model output.
+ - **Usage:**
+ ```shell
+ litellm --max_tokens 50
+ ```
+
+### --request_timeout
+ - **Default:** `None`
+ - **Type:** `int`
+ - Set the timeout in seconds for completion calls.
+ - **Usage:**
+ ```shell
+ litellm --request_timeout 300
+ ```
+
+### --max_budget
+ - **Default:** `None`
+ - **Type:** `float`
+ - Set max budget for API calls. Works for hosted models like OpenAI, TogetherAI, Anthropic, etc.
+ - **Usage:**
+ ```shell
+ litellm --max_budget 100.0
+ ```
+
+### --drop_params
+ - **Type:** `bool` (Flag)
+ - Drop any unmapped params.
+ - **Usage:**
+ ```shell
+ litellm --drop_params
+ ```
+
+### --add_function_to_prompt
+ - **Type:** `bool` (Flag)
+ - If a function passed but unsupported, pass it as a part of the prompt.
+ - **Usage:**
+ ```shell
+ litellm --add_function_to_prompt
+ ```
+
+## Database Configuration
+
+### --iam_token_db_auth
+ - **Default:** `False`
+ - **Type:** `bool` (Flag)
+ - Connects to an RDS database using IAM token authentication instead of a password. This is useful for AWS RDS instances that are configured to use IAM database authentication.
+ - When enabled, LiteLLM will generate an IAM authentication token to connect to the database.
+ - **Required Environment Variables:**
+ - `DATABASE_HOST` - The RDS database host
+ - `DATABASE_PORT` - The database port
+ - `DATABASE_USER` - The database user
+ - `DATABASE_NAME` - The database name
+ - `DATABASE_SCHEMA` (optional) - The database schema
+ - **Usage:**
+ ```shell
+ litellm --iam_token_db_auth
+ ```
+ - **Usage - set Environment Variable:** `IAM_TOKEN_DB_AUTH`
+ ```shell
+ export IAM_TOKEN_DB_AUTH=True
+ export DATABASE_HOST=mydb.us-east-1.rds.amazonaws.com
+ export DATABASE_PORT=5432
+ export DATABASE_USER=mydbuser
+ export DATABASE_NAME=mydb
+ litellm
+ ```
+
+### --use_prisma_db_push
+ - **Default:** `False`
+ - **Type:** `bool` (Flag)
+ - Use `prisma db push` instead of `prisma migrate` for database schema updates. This is useful when you want to quickly sync your database schema without creating migration files.
+ - **Usage:**
+ ```shell
+ litellm --use_prisma_db_push
+ ```
+
+## Debugging
+
+### --debug
- **Default:** `False`
- **Type:** `bool` (Flag)
- Enable debugging mode for the input.
@@ -102,10 +323,10 @@ Cli arguments, --host, --port, --num_workers
litellm
```
-## --detailed_debug
+### --detailed_debug
- **Default:** `False`
- **Type:** `bool` (Flag)
- - Enable debugging mode for the input.
+ - Enable detailed debugging mode to view verbose debug logs.
- **Usage:**
```shell
litellm --detailed_debug
@@ -116,80 +337,76 @@ Cli arguments, --host, --port, --num_workers
litellm
```
-#### --temperature
- - **Default:** `None`
- - **Type:** `float`
- - Set the temperature for the model.
- - **Usage:**
- ```shell
- litellm --temperature 0.7
- ```
-
-## --max_tokens
- - **Default:** `None`
- - **Type:** `int`
- - Set the maximum number of tokens for the model output.
- - **Usage:**
- ```shell
- litellm --max_tokens 50
- ```
-
-## --request_timeout
- - **Default:** `6000`
- - **Type:** `int`
- - Set the timeout in seconds for completion calls.
- - **Usage:**
- ```shell
- litellm --request_timeout 300
- ```
-
-## --drop_params
+### --local
+ - **Default:** `False`
- **Type:** `bool` (Flag)
- - Drop any unmapped params.
+ - For local debugging purposes.
- **Usage:**
```shell
- litellm --drop_params
+ litellm --local
```
-## --add_function_to_prompt
+## Testing & Health Checks
+
+### --test
- **Type:** `bool` (Flag)
- - If a function passed but unsupported, pass it as a part of the prompt.
+ - Proxy chat completions URL to make a test request to.
- **Usage:**
```shell
- litellm --add_function_to_prompt
+ litellm --test
```
-## --config
- - Configure Litellm by providing a configuration file path.
+### --test_async
+ - **Default:** `False`
+ - **Type:** `bool` (Flag)
+ - Calls async endpoints `/queue/requests` and `/queue/response`.
- **Usage:**
```shell
- litellm --config path/to/config.yaml
+ litellm --test_async
```
-## --telemetry
+### --num_requests
+ - **Default:** `10`
+ - **Type:** `int`
+ - Number of requests to hit async endpoint with (used with `--test_async`).
+ - **Usage:**
+ ```shell
+ litellm --test_async --num_requests 100
+ ```
+
+### --health
+ - **Type:** `bool` (Flag)
+ - Runs a health check on all models in config.yaml.
+ - **Usage:**
+ ```shell
+ litellm --health
+ ```
+
+## Other Options
+
+### --version
+ - **Short form:** `-v`
+ - **Type:** `bool` (Flag)
+ - Print LiteLLM version and exit.
+ - **Usage:**
+ ```shell
+ litellm --version
+ ```
+
+### --telemetry
- **Default:** `True`
- **Type:** `bool`
- - Help track usage of this feature.
+ - Help track usage of this feature. Turn off for privacy.
- **Usage:**
```shell
litellm --telemetry False
```
-
-## --log_config
- - **Default:** `None`
- - **Type:** `str`
- - Specify a log configuration file for uvicorn.
- - **Usage:**
- ```shell
- litellm --log_config path/to/log_config.conf
- ```
-
-## --skip_server_startup
+### --use_queue
- **Default:** `False`
- **Type:** `bool` (Flag)
- - Skip starting the server after setup (useful for DB migrations only).
+ - To use celery workers for async endpoints.
- **Usage:**
```shell
- litellm --skip_server_startup
- ```
\ No newline at end of file
+ litellm --use_queue
+ ```
diff --git a/docs/my-website/docs/proxy/cli_sso.md b/docs/my-website/docs/proxy/cli_sso.md
index cde6bf266d4..ad0f033f802 100644
--- a/docs/my-website/docs/proxy/cli_sso.md
+++ b/docs/my-website/docs/proxy/cli_sso.md
@@ -28,6 +28,37 @@ EXPERIMENTAL_UI_LOGIN="True" litellm --config config.yaml
:::
+### Configuration
+
+#### JWT Token Expiration
+
+By default, CLI authentication tokens expire after **24 hours**. You can customize this expiration time by setting the `LITELLM_CLI_JWT_EXPIRATION_HOURS` environment variable when starting your LiteLLM Proxy:
+
+```bash
+# Set CLI JWT tokens to expire after 48 hours
+export LITELLM_CLI_JWT_EXPIRATION_HOURS=48
+export EXPERIMENTAL_UI_LOGIN="True"
+litellm --config config.yaml
+```
+
+Or in a single command:
+
+```bash
+LITELLM_CLI_JWT_EXPIRATION_HOURS=48 EXPERIMENTAL_UI_LOGIN="True" litellm --config config.yaml
+```
+
+**Examples:**
+- `LITELLM_CLI_JWT_EXPIRATION_HOURS=12` - Tokens expire after 12 hours
+- `LITELLM_CLI_JWT_EXPIRATION_HOURS=168` - Tokens expire after 7 days (168 hours)
+- `LITELLM_CLI_JWT_EXPIRATION_HOURS=720` - Tokens expire after 30 days (720 hours)
+
+:::tip
+You can check your current token's age and expiration status using:
+```bash
+litellm-proxy whoami
+```
+:::
+
### Steps
1. **Install the CLI**
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index 89e1e2910e4..9e3b5e90978 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -94,7 +94,7 @@ litellm_settings:
# /chat/completions, /completions, /embeddings, /audio/transcriptions
mode: default_off # if default_off, you need to opt in to caching on a per call basis
ttl: 600 # ttl for caching
- disable_copilot_system_to_assistant: False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior.
+ disable_copilot_system_to_assistant: False # DEPRECATED - GitHub Copilot API supports system prompts.
callback_settings:
otel:
@@ -197,7 +197,7 @@ router_settings:
| disable_add_transform_inline_image_block | boolean | For Fireworks AI models - if true, turns off the auto-add of `#transform=inline` to the url of the image_url, if the model is not a vision model. |
| disable_hf_tokenizer_download | boolean | If true, it defaults to using the openai tokenizer for all models (including huggingface models). |
| enable_json_schema_validation | boolean | If true, enables json schema validation for all requests. |
-| disable_copilot_system_to_assistant | boolean | If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior. Useful for tools (like Claude Code) that send system messages, which Copilot does not support. |
+| disable_copilot_system_to_assistant | boolean | **DEPRECATED** - GitHub Copilot API supports system prompts. |
### general_settings - Reference
@@ -321,6 +321,7 @@ router_settings:
| redis_host | string | The host address for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them** |
| redis_password | string | The password for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them** |
| redis_port | string | The port number for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them**|
+| redis_db | int | The database number for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them**|
| enable_pre_call_check | boolean | If true, checks if a call is within the model's context window before making the call. [More information here](reliability) |
| content_policy_fallbacks | array of objects | Specifies fallback models for content policy violations. [More information here](reliability) |
| fallbacks | array of objects | Specifies fallback models for all types of errors. [More information here](reliability) |
@@ -357,7 +358,8 @@ router_settings:
| redis_url | str | URL for Redis server. **Known performance issue with Redis URL.** |
| cache_responses | boolean | Flag to enable caching LLM Responses, if cache set under `router_settings`. If true, caches responses. Defaults to False. |
| router_general_settings | RouterGeneralSettings | [SDK-Only] Router general settings - contains optimizations like 'async_only_mode'. [Docs](../routing.md#router-general-settings) |
-| optional_pre_call_checks | List[str] | List of pre-call checks to add to the router. Currently supported: 'router_budget_limiting', 'prompt_caching' |
+| optional_pre_call_checks | List[str] | List of pre-call checks to add to the router. Supported: `router_budget_limiting`, `prompt_caching`, `responses_api_deployment_check`, `deployment_affinity`, `forward_client_headers_by_model_group` |
+| deployment_affinity_ttl_seconds | int | TTL (seconds) for user-key → deployment affinity mapping when `deployment_affinity` is enabled (configured at Router init / proxy startup). Defaults to `3600` (1 hour). |
| ignore_invalid_deployments | boolean | If true, ignores invalid deployments. Default for proxy is True - to prevent invalid models from blocking other models from being loaded. |
| search_tools | List[SearchToolTypedDict] | List of search tool configurations for Search API integration. Each tool specifies a search_tool_name and litellm_params with search_provider, api_key, api_base, etc. [Further Docs](../search.md) |
| guardrail_list | List[GuardrailTypedDict] | List of guardrail configurations for guardrail load balancing. Enables load balancing across multiple guardrail deployments with the same guardrail_name. [Further Docs](./guardrails/guardrail_load_balancing.md) |
@@ -394,7 +396,7 @@ router_settings:
| ATHINA_API_KEY | API key for Athina service
| ATHINA_BASE_URL | Base URL for Athina service (defaults to `https://log.athina.ai`)
| AUTH_STRATEGY | Strategy used for authentication (e.g., OAuth, API key)
-| AUTO_REDIRECT_UI_LOGIN_TO_SSO | Flag to enable automatic redirect of UI login page to SSO when SSO is configured. Default is **true**
+| AUTO_REDIRECT_UI_LOGIN_TO_SSO | Flag to enable automatic redirect of UI login page to SSO when SSO is configured. Default is **false**
| AUDIO_SPEECH_CHUNK_SIZE | Chunk size for audio speech processing. Default is 1024
| ANTHROPIC_API_KEY | API key for Anthropic service
| ANTHROPIC_API_BASE | Base URL for Anthropic API. Default is https://api.anthropic.com
@@ -449,9 +451,12 @@ router_settings:
| BATCH_STATUS_POLL_INTERVAL_SECONDS | Interval in seconds for polling batch status. Default is 3600 (1 hour)
| BATCH_STATUS_POLL_MAX_ATTEMPTS | Maximum number of attempts for polling batch status. Default is 24 (for 24 hours)
| BEDROCK_MAX_POLICY_SIZE | Maximum size for Bedrock policy. Default is 75
+| BEDROCK_MIN_THINKING_BUDGET_TOKENS | Minimum thinking budget in tokens for Bedrock reasoning models. Bedrock returns a 400 error if budget_tokens is below this value. Requests with lower values are clamped to this minimum. Default is 1024
| BERRISPEND_ACCOUNT_ID | Account ID for BerriSpend service
| BRAINTRUST_API_KEY | API key for Braintrust integration
| BRAINTRUST_API_BASE | Base URL for Braintrust API. Default is https://api.braintrustdata.com/v1
+| BRAINTRUST_MOCK | Enable mock mode for Braintrust integration testing. When set to true, intercepts Braintrust API calls and returns mock responses without making actual network calls. Default is false
+| BRAINTRUST_MOCK_LATENCY_MS | Mock latency in milliseconds for Braintrust API calls when mock mode is enabled. Simulates network round-trip time. Default is 100ms
| CACHED_STREAMING_CHUNK_DELAY | Delay in seconds for cached streaming chunks. Default is 0.02
| CHATGPT_API_BASE | Base URL for ChatGPT API. Default is https://chatgpt.com/backend-api/codex
| CHATGPT_AUTH_FILE | Filename for ChatGPT authentication data. Default is "auth.json"
@@ -462,6 +467,7 @@ router_settings:
| CHATGPT_USER_AGENT_SUFFIX | Suffix to append to the ChatGPT user agent string
| CIRCLE_OIDC_TOKEN | OpenID Connect token for CircleCI
| CIRCLE_OIDC_TOKEN_V2 | Version 2 of the OpenID Connect token for CircleCI
+| CLI_JWT_EXPIRATION_HOURS | Expiration time in hours for CLI-generated JWT tokens. Default is 24 hours. Can also be set via LITELLM_CLI_JWT_EXPIRATION_HOURS
| CLOUDZERO_API_KEY | CloudZero API key for authentication
| CLOUDZERO_CONNECTION_ID | CloudZero connection ID for data submission
| CLOUDZERO_EXPORT_INTERVAL_MINUTES | Interval in minutes for CloudZero data export operations
@@ -488,6 +494,7 @@ router_settings:
| DATABASE_USER | Username for database connection
| DATABASE_USERNAME | Alias for database user
| DATABRICKS_API_BASE | Base URL for Databricks API
+| DATABRICKS_API_KEY | API key (Personal Access Token) for Databricks API authentication
| DATABRICKS_CLIENT_ID | Client ID for Databricks OAuth M2M authentication (Service Principal application ID)
| DATABRICKS_CLIENT_SECRET | Client secret for Databricks OAuth M2M authentication
| DATABRICKS_USER_AGENT | Custom user agent string for Databricks API requests. Used for partner telemetry attribution
@@ -504,15 +511,19 @@ router_settings:
| DD_AGENT_HOST | Hostname or IP of DataDog agent (e.g., "localhost"). When set, logs are sent to agent instead of direct API
| DD_AGENT_PORT | Port of DataDog agent for log intake. Default is 10518
| DD_API_KEY | API key for Datadog integration
+| DD_APP_KEY | Application key for Datadog Cost Management integration. Required along with DD_API_KEY for cost metrics
| DD_SITE | Site URL for Datadog (e.g., datadoghq.com)
| DD_SOURCE | Source identifier for Datadog logs
| DD_TRACER_STREAMING_CHUNK_YIELD_RESOURCE | Resource name for Datadog tracing of streaming chunk yields. Default is "streaming.chunk.yield"
| DD_ENV | Environment identifier for Datadog logs. Only supported for `datadog_llm_observability` callback
| DD_SERVICE | Service identifier for Datadog logs. Defaults to "litellm-server"
| DD_VERSION | Version identifier for Datadog logs. Defaults to "unknown"
+| DATADOG_MOCK | Enable mock mode for Datadog integration testing. When set to true, intercepts Datadog API calls and returns mock responses without making actual network calls. Default is false
+| DATADOG_MOCK_LATENCY_MS | Mock latency in milliseconds for Datadog API calls when mock mode is enabled. Simulates network round-trip time. Default is 100ms
| DEBUG_OTEL | Enable debug mode for OpenTelemetry
| DEFAULT_ALLOWED_FAILS | Maximum failures allowed before cooling down a model. Default is 3
| DEFAULT_A2A_AGENT_TIMEOUT | Default timeout in seconds for A2A (Agent-to-Agent) protocol requests. Default is 6000
+| DEFAULT_ACCESS_GROUP_CACHE_TTL | Time-to-live in seconds for cached access group information. Default is 600 (10 minutes)
| DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS | Default maximum tokens for Anthropic chat completions. Default is 4096
| DEFAULT_BATCH_SIZE | Default batch size for operations. Default is 512
| DEFAULT_CHUNK_OVERLAP | Default chunk overlap for RAG text splitters. Default is 200
@@ -531,17 +542,25 @@ router_settings:
| DEFAULT_IMAGE_WIDTH | Default width for images. Default is 300
| DEFAULT_IN_MEMORY_TTL | Default time-to-live for in-memory cache in seconds. Default is 5
| DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL | Default time-to-live in seconds for management objects (User, Team, Key, Organization) in memory cache. Default is 60 seconds.
-| DEFAULT_MAX_LRU_CACHE_SIZE | Default maximum size for LRU cache. Default is 16
+| DEFAULT_MAX_LRU_CACHE_SIZE | Default maximum size for LRU cache. Default is 64
| DEFAULT_MAX_RECURSE_DEPTH | Default maximum recursion depth. Default is 100
| DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER | Default maximum recursion depth for sensitive data masker. Default is 10
| DEFAULT_MAX_RETRIES | Default maximum retry attempts. Default is 2
| DEFAULT_MAX_TOKENS | Default maximum tokens for LLM calls. Default is 4096
| DEFAULT_MAX_TOKENS_FOR_TRITON | Default maximum tokens for Triton models. Default is 2000
| DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE | Default maximum size for redis batch cache. Default is 1000
+| DEFAULT_MCP_SEMANTIC_FILTER_EMBEDDING_MODEL | Default embedding model for MCP semantic tool filtering. Default is "text-embedding-3-small"
+| DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD | Default similarity threshold for MCP semantic tool filtering. Default is 0.3
+| DEFAULT_MCP_SEMANTIC_FILTER_TOP_K | Default number of top results to return for MCP semantic tool filtering. Default is 10
+| MCP_NPM_CACHE_DIR | Directory for npm cache used by STDIO MCP servers. In containers the default (~/.npm) may not exist or be read-only. Default is `/tmp/.npm_mcp_cache`
+| MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL | Default TTL in seconds for MCP OAuth2 token cache. Default is 3600
+| MCP_OAUTH2_TOKEN_CACHE_MAX_SIZE | Maximum number of entries in MCP OAuth2 token cache. Default is 200
+| MCP_OAUTH2_TOKEN_CACHE_MIN_TTL | Minimum TTL in seconds for MCP OAuth2 token cache. Default is 10
+| MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS | Seconds to subtract from token expiry when computing cache TTL. Default is 60
| DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT | Default token count for mock response completions. Default is 20
| DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT | Default token count for mock response prompts. Default is 10
| DEFAULT_MODEL_CREATED_AT_TIME | Default creation timestamp for models. Default is 1677610602
-| DEFAULT_NUM_WORKERS_LITELLM_PROXY | Default number of workers for LiteLLM proxy. Default is 4. **We strongly recommend setting NUM Workers to Number of vCPUs available**
+| DEFAULT_NUM_WORKERS_LITELLM_PROXY | Default number of workers for LiteLLM proxy when `NUM_WORKERS` is not set. Default is 1. **We strongly recommend setting NUM_WORKERS to the number of vCPUs available** (e.g. `NUM_WORKERS=8` or `--num_workers 8`).
| DEFAULT_PROMPT_INJECTION_SIMILARITY_THRESHOLD | Default threshold for prompt injection similarity. Default is 0.7
| DEFAULT_POLLING_INTERVAL | Default polling interval for schedulers in seconds. Default is 0.03
| DEFAULT_REASONING_EFFORT_DISABLE_THINKING_BUDGET | Default reasoning effort disable thinking budget. Default is 0
@@ -586,7 +605,6 @@ router_settings:
| EMAIL_BUDGET_ALERT_TTL | Time-to-live for budget alert deduplication in seconds. Default is 86400 (24 hours)
| ENKRYPTAI_API_BASE | Base URL for EnkryptAI Guardrails API. **Default is https://api.enkryptai.com**
| ENKRYPTAI_API_KEY | API key for EnkryptAI Guardrails service
-| EXPERIMENTAL_MULTI_INSTANCE_RATE_LIMITING | Flag to enable new multi-instance rate limiting. **Default is False**
| FIREWORKS_AI_4_B | Size parameter for Fireworks AI 4B model. Default is 4
| FIREWORKS_AI_16_B | Size parameter for Fireworks AI 16B model. Default is 16
| FIREWORKS_AI_56_B_MOE | Size parameter for Fireworks AI 56B MOE model. Default is 56
@@ -611,6 +629,8 @@ router_settings:
| GALILEO_USERNAME | Username for Galileo authentication
| GOOGLE_SECRET_MANAGER_PROJECT_ID | Project ID for Google Secret Manager
| GCS_BUCKET_NAME | Name of the Google Cloud Storage bucket
+| GCS_MOCK | Enable mock mode for GCS integration testing. When set to true, intercepts GCS API calls and returns mock responses without making actual network calls. Default is false
+| GCS_MOCK_LATENCY_MS | Mock latency in milliseconds for GCS API calls when mock mode is enabled. Simulates network round-trip time. Default is 150ms
| GCS_PATH_SERVICE_ACCOUNT | Path to the Google Cloud service account JSON file
| GCS_FLUSH_INTERVAL | Flush interval for GCS logging (in seconds). Specify how often you want a log to be sent to GCS. **Default is 20 seconds**
| GCS_BATCH_SIZE | Batch size for GCS logging. Specify after how many logs you want to flush to GCS. If `BATCH_SIZE` is set to 10, logs are flushed every 10 logs. **Default is 2048**
@@ -628,6 +648,7 @@ router_settings:
| GENERIC_TOKEN_ENDPOINT | Token endpoint for generic OAuth providers
| GENERIC_USER_DISPLAY_NAME_ATTRIBUTE | Attribute for user's display name in generic auth
| GENERIC_USER_EMAIL_ATTRIBUTE | Attribute for user's email in generic auth
+| GENERIC_USER_EXTRA_ATTRIBUTES | Comma-separated list of additional fields to extract from generic SSO provider response (e.g., "department,employee_id,groups"). Accessible via `CustomOpenID.extra_fields` in custom SSO handlers. Supports dot notation for nested fields
| GENERIC_USER_FIRST_NAME_ATTRIBUTE | Attribute for user's first name in generic auth
| GENERIC_USER_ID_ATTRIBUTE | Attribute for user ID in generic auth
| GENERIC_USER_LAST_NAME_ATTRIBUTE | Attribute for user's last name in generic auth
@@ -636,6 +657,10 @@ router_settings:
| GENERIC_USERINFO_ENDPOINT | Endpoint to fetch user information in generic OAuth
| GENERIC_LOGGER_ENDPOINT | Endpoint URL for the Generic Logger callback to send logs to
| GENERIC_LOGGER_HEADERS | JSON string of headers to include in Generic Logger callback requests
+| GENERIC_ROLE_MAPPINGS_DEFAULT_ROLE | Default LiteLLM role to assign when no role mapping matches in generic SSO. Used with GENERIC_ROLE_MAPPINGS_ROLES
+| GENERIC_ROLE_MAPPINGS_GROUP_CLAIM | The claim/attribute name in the SSO token that contains the user's groups. Used for role mapping
+| GENERIC_ROLE_MAPPINGS_ROLES | Python dict string mapping LiteLLM roles to SSO group names. Example: `{"proxy_admin": ["admin-group"], "internal_user": ["users"]}`
+| GENERIC_USER_ROLE_MAPPINGS | Alternative to GENERIC_ROLE_MAPPINGS_ROLES for configuring user role mappings from SSO
| GEMINI_API_BASE | Base URL for Gemini API. Default is https://generativelanguage.googleapis.com
| GALILEO_BASE_URL | Base URL for Galileo platform
| GALILEO_PASSWORD | Password for Galileo authentication
@@ -672,6 +697,8 @@ router_settings:
| HCP_VAULT_CERT_ROLE | Role for [Hashicorp Vault Secret Manager Auth](../secret.md#hashicorp-vault)
| HELICONE_API_KEY | API key for Helicone service
| HELICONE_API_BASE | Base URL for Helicone service, defaults to `https://api.helicone.ai`
+| HELICONE_MOCK | Enable mock mode for Helicone integration testing. When set to true, intercepts Helicone API calls and returns mock responses without making actual network calls. Default is false
+| HELICONE_MOCK_LATENCY_MS | Mock latency in milliseconds for Helicone API calls when mock mode is enabled. Simulates network round-trip time. Default is 100ms
| HOSTNAME | Hostname for the server, this will be [emitted to `datadog` logs](https://docs.litellm.ai/docs/proxy/logging#datadog)
| HOURS_IN_A_DAY | Hours in a day for calculation purposes. Default is 24
| HIDDENLAYER_API_BASE | Base URL for HiddenLayer API. Defaults to `https://api.hiddenlayer.ai`
@@ -697,6 +724,8 @@ router_settings:
| LANGFUSE_FLUSH_INTERVAL | Interval for flushing Langfuse logs
| LANGFUSE_TRACING_ENVIRONMENT | Environment for Langfuse tracing
| LANGFUSE_HOST | Host URL for Langfuse service
+| LANGFUSE_MOCK | Enable mock mode for Langfuse integration testing. When set to true, intercepts Langfuse API calls and returns mock responses without making actual network calls. Default is false
+| LANGFUSE_MOCK_LATENCY_MS | Mock latency in milliseconds for Langfuse API calls when mock mode is enabled. Simulates network round-trip time. Default is 100ms
| LANGFUSE_PUBLIC_KEY | Public key for Langfuse authentication
| LANGFUSE_RELEASE | Release version of Langfuse integration
| LANGFUSE_SECRET_KEY | Secret key for Langfuse authentication
@@ -708,6 +737,8 @@ router_settings:
| LANGSMITH_PROJECT | Project name for Langsmith integration
| LANGSMITH_SAMPLING_RATE | Sampling rate for Langsmith logging
| LANGSMITH_TENANT_ID | Tenant ID for Langsmith multi-tenant deployments
+| LANGSMITH_MOCK | Enable mock mode for Langsmith integration testing. When set to true, intercepts Langsmith API calls and returns mock responses without making actual network calls. Default is false
+| LANGSMITH_MOCK_LATENCY_MS | Mock latency in milliseconds for Langsmith API calls when mock mode is enabled. Simulates network round-trip time. Default is 100ms
| LANGTRACE_API_KEY | API key for Langtrace service
| LASSO_API_BASE | Base URL for Lasso API
| LASSO_API_KEY | API key for Lasso service
@@ -718,9 +749,14 @@ router_settings:
| LITERAL_API_KEY | API key for Literal integration
| LITERAL_API_URL | API URL for Literal service
| LITERAL_BATCH_SIZE | Batch size for Literal operations
+| LITELLM_ANTHROPIC_BETA_HEADERS_URL | Custom URL for fetching Anthropic beta headers configuration. Default is the GitHub main branch URL
| LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX | Disable automatic URL suffix appending for Anthropic API base URLs. When set to `true`, prevents LiteLLM from automatically adding `/v1/messages` or `/v1/complete` to custom Anthropic API endpoints
+| LITELLM_ASSETS_PATH | Path to directory for UI assets and logos. Used when running with read-only filesystem (e.g., Kubernetes). Default is `/var/lib/litellm/assets` in Docker.
+| LITELLM_CLI_JWT_EXPIRATION_HOURS | Expiration time in hours for CLI-generated JWT tokens. Default is 24 hours
| LITELLM_DD_AGENT_HOST | Hostname or IP of DataDog agent for LiteLLM-specific logging. When set, logs are sent to agent instead of direct API
+| LITELLM_DEPLOYMENT_ENVIRONMENT | Environment name for the deployment (e.g., "production", "staging"). Used as a fallback when OTEL_ENVIRONMENT_NAME is not set. Sets the `environment` tag in telemetry data
| LITELLM_DD_AGENT_PORT | Port of DataDog agent for LiteLLM-specific log intake. Default is 10518
+| LITELLM_DD_LLM_OBS_PORT | Port for Datadog LLM Observability agent. Default is 8126
| LITELLM_DONT_SHOW_FEEDBACK_BOX | Flag to hide feedback box in LiteLLM UI
| LITELLM_DROP_PARAMS | Parameters to drop in LiteLLM requests
| LITELLM_MODIFY_PARAMS | Parameters to modify in LiteLLM requests
@@ -731,11 +767,15 @@ router_settings:
| LITELLM_MIGRATION_DIR | Custom migrations directory for prisma migrations, used for baselining db in read-only file systems.
| LITELLM_HOSTED_UI | URL of the hosted UI for LiteLLM
| LITELLM_UI_API_DOC_BASE_URL | Optional override for the API Reference base URL (used in sample code/docs) when the admin UI runs on a different host than the proxy. Defaults to `PROXY_BASE_URL` when unset.
+| LITELLM_UI_PATH | Path to directory for Admin UI files. Used when running with read-only filesystem (e.g., Kubernetes). Default is `/var/lib/litellm/ui` in Docker.
| LITELM_ENVIRONMENT | Environment of LiteLLM Instance, used by logging services. Currently only used by DeepEval.
| LITELLM_KEY_ROTATION_ENABLED | Enable auto-key rotation for LiteLLM (boolean). Default is false.
| LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS | Interval in seconds for how often to run job that auto-rotates keys. Default is 86400 (24 hours).
+| LITELLM_KEY_ROTATION_GRACE_PERIOD | Duration to keep old key valid after rotation (e.g. "24h", "2d"). Default is empty (immediate revoke). Used for scheduled rotations and as fallback when not specified in regenerate request.
| LITELLM_LICENSE | License key for LiteLLM usage
+| LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS | Set to `True` to use the local bundled Anthropic beta headers config only, disabling remote fetching. Default is `False`
| LITELLM_LOCAL_MODEL_COST_MAP | Local configuration for model cost mapping in LiteLLM
+| LITELLM_LOCAL_POLICY_TEMPLATES | When set to "true", uses local backup policy templates instead of fetching from GitHub. Policy templates are fetched from https://raw.githubusercontent.com/BerriAI/litellm/main/policy_templates.json by default, with automatic fallback to local backup on failure
| LITELLM_LOG | Enable detailed logging for LiteLLM
| LITELLM_MODEL_COST_MAP_URL | URL for fetching model cost map data. Default is https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json
| LITELLM_LOG_FILE | File path to write LiteLLM logs to. When set, logs will be written to both console and the specified file
@@ -743,6 +783,10 @@ router_settings:
| LITELLM_METER_NAME | Name for OTEL Meter
| LITELLM_OTEL_INTEGRATION_ENABLE_EVENTS | Optionally enable semantic logs for OTEL
| LITELLM_OTEL_INTEGRATION_ENABLE_METRICS | Optionally enable emantic metrics for OTEL
+| LITELLM_ENABLE_PYROSCOPE | If true, enables Pyroscope CPU profiling. Profiles are sent to PYROSCOPE_SERVER_ADDRESS. Off by default. See [Pyroscope profiling](/proxy/pyroscope_profiling).
+| PYROSCOPE_APP_NAME | Application name reported to Pyroscope. Required when LITELLM_ENABLE_PYROSCOPE is true. No default.
+| PYROSCOPE_SERVER_ADDRESS | Pyroscope server URL to send profiles to. Required when LITELLM_ENABLE_PYROSCOPE is true. No default.
+| PYROSCOPE_SAMPLE_RATE | Optional. Sample rate for Pyroscope profiling (integer). No default; when unset, the pyroscope-io library default is used.
| LITELLM_MASTER_KEY | Master key for proxy authentication
| LITELLM_MODE | Operating mode for LiteLLM (e.g., production, development)
| LITELLM_NON_ROOT | Flag to run LiteLLM in non-root mode for enhanced security in Docker containers
@@ -755,6 +799,7 @@ router_settings:
| LITELLM_USER_AGENT | Custom user agent string for LiteLLM API requests. Used for partner telemetry attribution
| LITELLM_PRINT_STANDARD_LOGGING_PAYLOAD | If true, prints the standard logging payload to the console - useful for debugging
| LITELM_ENVIRONMENT | Environment for LiteLLM Instance. This is currently only logged to DeepEval to determine the environment for DeepEval integration.
+| LITELLM_ASYNCIO_QUEUE_MAXSIZE | Maximum size for asyncio queues (e.g. log queues, spend update queues, and cookbook examples such as realtime audio in `nova_sonic_realtime.py`). Bounds in-memory growth to prevent OOM. Default is 1000.
| LOGFIRE_TOKEN | Token for Logfire logging service
| LOGFIRE_BASE_URL | Base URL for Logfire logging service (useful for self hosted deployments)
| LOGGING_WORKER_CONCURRENCY | Maximum number of concurrent coroutine slots for the logging worker on the asyncio event loop. Default is 100. Setting too high will flood the event loop with logging tasks which will lower the overall latency of the requests.
@@ -781,6 +826,8 @@ router_settings:
| MAXIMUM_TRACEBACK_LINES_TO_LOG | Maximum number of lines to log in traceback in LiteLLM Logs UI. Default is 100
| MAX_RETRY_DELAY | Maximum delay in seconds for retrying requests. Default is 8.0
| MAX_LANGFUSE_INITIALIZED_CLIENTS | Maximum number of Langfuse clients to initialize on proxy. Default is 50. This is set since langfuse initializes 1 thread everytime a client is initialized. We've had an incident in the past where we reached 100% cpu utilization because Langfuse was initialized several times.
+| MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH | Maximum header length for MCP semantic filter tools. Default is 150
+| MAX_POLICY_ESTIMATE_IMPACT_ROWS | Maximum number of rows returned when estimating the impact of a policy. Default is 1000
| MIN_NON_ZERO_TEMPERATURE | Minimum non-zero temperature value. Default is 0.0001
| MINIMUM_PROMPT_CACHE_TOKEN_COUNT | Minimum token count for caching a prompt. Default is 1024
| MISTRAL_API_BASE | Base URL for Mistral API. Default is https://api.mistral.ai
@@ -797,6 +844,8 @@ router_settings:
| MICROSOFT_USER_ID_ATTRIBUTE | Field name for user ID in Microsoft SSO response. Default is `id`
| MICROSOFT_USER_LAST_NAME_ATTRIBUTE | Field name for user last name in Microsoft SSO response. Default is `surname`
| MICROSOFT_USERINFO_ENDPOINT | Custom userinfo endpoint URL for Microsoft SSO (overrides default Microsoft Graph userinfo endpoint)
+| MODEL_COST_MAP_MAX_SHRINK_RATIO | Maximum allowed shrinkage ratio when validating a fetched model cost map against the local backup. Rejects the fetched map if it is smaller than this fraction of the backup. Default is 0.5
+| MODEL_COST_MAP_MIN_MODEL_COUNT | Minimum number of models a fetched cost map must contain to be considered valid. Default is 50
| NO_DOCS | Flag to disable Swagger UI documentation
| NO_REDOC | Flag to disable Redoc documentation
| NO_PROXY | List of addresses to bypass proxy
@@ -816,6 +865,7 @@ router_settings:
| OPENMETER_EVENT_TYPE | Type of events sent to OpenMeter
| ONYX_API_BASE | Base URL for Onyx Security AI Guard service (defaults to https://ai-guard.onyx.security)
| ONYX_API_KEY | API key for Onyx Security AI Guard service
+| ONYX_TIMEOUT | Timeout in seconds for Onyx Guard server requests. Default is 10
| OTEL_ENDPOINT | OpenTelemetry endpoint for traces
| OTEL_EXPORTER_OTLP_ENDPOINT | OpenTelemetry endpoint for traces
| OTEL_ENVIRONMENT_NAME | Environment name for OpenTelemetry
@@ -839,6 +889,8 @@ router_settings:
| POD_NAME | Pod name for the server, this will be [emitted to `datadog` logs](https://docs.litellm.ai/docs/proxy/logging#datadog) as `POD_NAME`
| POSTHOG_API_KEY | API key for PostHog analytics integration
| POSTHOG_API_URL | Base URL for PostHog API (defaults to https://us.i.posthog.com)
+| POSTHOG_MOCK | Enable mock mode for PostHog integration testing. When set to true, intercepts PostHog API calls and returns mock responses without making actual network calls. Default is false
+| POSTHOG_MOCK_LATENCY_MS | Mock latency in milliseconds for PostHog API calls when mock mode is enabled. Simulates network round-trip time. Default is 100ms
| PREDIBASE_API_BASE | Base URL for Predibase API
| PRESIDIO_ANALYZER_API_BASE | Base URL for Presidio Analyzer service
| PRESIDIO_ANONYMIZER_API_BASE | Base URL for Presidio Anonymizer service
@@ -876,6 +928,8 @@ router_settings:
| ROUTER_MAX_FALLBACKS | Maximum number of fallbacks for router. Default is 5
| RUNWAYML_DEFAULT_API_VERSION | Default API version for RunwayML service. Default is "2024-11-06"
| RUNWAYML_POLLING_TIMEOUT | Timeout in seconds for RunwayML image generation polling. Default is 600 (10 minutes)
+| S3_VECTORS_DEFAULT_DIMENSION | Default vector dimension for S3 Vectors RAG ingestion. Default is 1024
+| S3_VECTORS_DEFAULT_DISTANCE_METRIC | Default distance metric for S3 Vectors RAG ingestion. Options: "cosine", "euclidean". Default is "cosine"
| SECRET_MANAGER_REFRESH_INTERVAL | Refresh interval in seconds for secret manager. Default is 86400 (24 hours)
| SEPARATE_HEALTH_APP | If set to '1', runs health endpoints on a separate ASGI app and port. Default: '0'.
| SEPARATE_HEALTH_PORT | Port for the separate health endpoints app. Only used if SEPARATE_HEALTH_APP=1. Default: 4001.
diff --git a/docs/my-website/docs/proxy/configs.md b/docs/my-website/docs/proxy/configs.md
index a5674bf2bc5..56a8b9566db 100644
--- a/docs/my-website/docs/proxy/configs.md
+++ b/docs/my-website/docs/proxy/configs.md
@@ -469,6 +469,7 @@ credential_list:
api_version: "2023-05-15"
credential_info:
description: "Production credentials for EU region"
+ custom_llm_provider: "azure"
```
#### Key Parameters
diff --git a/docs/my-website/docs/proxy/custom_pricing.md b/docs/my-website/docs/proxy/custom_pricing.md
index 8f4a4c450f5..b61da85bb1d 100644
--- a/docs/my-website/docs/proxy/custom_pricing.md
+++ b/docs/my-website/docs/proxy/custom_pricing.md
@@ -9,6 +9,7 @@ LiteLLM provides flexible cost tracking and pricing customization for all LLM pr
- **Custom Pricing** - Override default model costs or set pricing for custom models
- **Cost Per Token** - Track costs based on input/output tokens (most common)
- **Cost Per Second** - Track costs based on runtime (e.g., Sagemaker)
+- **Zero-Cost Models** - Bypass budget checks for free/on-premises models by setting costs to 0
- **[Provider Discounts](./provider_discounts.md)** - Apply percentage-based discounts to specific providers
- **[Provider Margins](./provider_margins.md)** - Add fees/margins to LLM costs for internal billing
- **Base Model Mapping** - Ensure accurate cost tracking for Azure deployments
@@ -106,6 +107,51 @@ There are other keys you can use to specify costs for different scenarios and mo
These keys evolve based on how new models handle multimodality. The latest version can be found at [https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json).
+## Zero-Cost Models (Bypass Budget Checks)
+
+**Use Case**: You have on-premises or free models that should be accessible even when users exceed their budget limits.
+
+**Solution** ✅: Set both `input_cost_per_token` and `output_cost_per_token` to `0` (explicitly) to bypass all budget checks for that model.
+
+:::info
+
+When a model is configured with zero cost, LiteLLM will automatically skip ALL budget checks (user, team, team member, end-user, organization, and global proxy budget) for requests to that model.
+
+**Important**: Both costs must be **explicitly set to 0**. If costs are `null` or undefined, the model will be treated as having cost and budget checks will apply.
+
+:::
+
+### Configuration Example
+
+```yaml
+model_list:
+ # On-premises model - free to use
+ - model_name: on-prem-llama
+ litellm_params:
+ model: ollama/llama3
+ api_base: http://localhost:11434
+ model_info:
+ input_cost_per_token: 0 # 👈 Explicitly set to 0
+ output_cost_per_token: 0 # 👈 Explicitly set to 0
+
+ # Paid cloud model - budget checks apply
+ - model_name: gpt-4
+ litellm_params:
+ model: gpt-4
+ api_key: os.environ/OPENAI_API_KEY
+ # No model_info - uses default pricing from cost map
+```
+
+### Behavior
+
+With the above configuration:
+
+- **User over budget** → Can still use `on-prem-llama` ✅, but blocked from `gpt-4` ❌
+- **Team over budget** → Can still use `on-prem-llama` ✅, but blocked from `gpt-4` ❌
+- **End-user over budget** → Can still use `on-prem-llama` ✅, but blocked from `gpt-4` ❌
+
+This ensures your free/on-premises models remain accessible regardless of budget constraints, while paid models are still properly governed.
+
## Set 'base_model' for Cost Tracking (e.g. Azure deployments)
**Problem**: Azure returns `gpt-4` in the response when `azure/gpt-4-1106-preview` is used. This leads to inaccurate cost tracking
diff --git a/docs/my-website/docs/proxy/custom_sso.md b/docs/my-website/docs/proxy/custom_sso.md
index bbd7f41bee1..8b7adeb0c5a 100644
--- a/docs/my-website/docs/proxy/custom_sso.md
+++ b/docs/my-website/docs/proxy/custom_sso.md
@@ -142,6 +142,18 @@ async def custom_sso_handler(userIDPInfo: OpenID) -> SSOUserDefinedValues:
f"No ID found for user. userIDPInfo.id is None {userIDPInfo}"
)
+ #################################################
+ # Access extra fields from SSO provider (requires GENERIC_USER_EXTRA_ATTRIBUTES env var)
+ # Example: Set GENERIC_USER_EXTRA_ATTRIBUTES="department,employee_id,groups"
+ extra_fields = getattr(userIDPInfo, 'extra_fields', None) or {}
+ user_department = extra_fields.get("department")
+ employee_id = extra_fields.get("employee_id")
+ user_groups = extra_fields.get("groups", [])
+
+ print(f"User department: {user_department}") # noqa
+ print(f"Employee ID: {employee_id}") # noqa
+ print(f"User groups: {user_groups}") # noqa
+ #################################################
#################################################
# Run your custom code / logic here
diff --git a/docs/my-website/docs/proxy/deploy.md b/docs/my-website/docs/proxy/deploy.md
index 7393e73ba87..0761e0e9fa8 100644
--- a/docs/my-website/docs/proxy/deploy.md
+++ b/docs/my-website/docs/proxy/deploy.md
@@ -200,6 +200,7 @@ Example `requirements.txt`
```shell
litellm[proxy]==1.57.3 # Specify the litellm version you want to use
+litellm-enterprise
prometheus_client
langfuse
prisma
diff --git a/docs/my-website/docs/proxy/embedding.md b/docs/my-website/docs/proxy/embedding.md
index 2adaaa24735..0e7c2d55c44 100644
--- a/docs/my-website/docs/proxy/embedding.md
+++ b/docs/my-website/docs/proxy/embedding.md
@@ -6,6 +6,16 @@ import TabItem from '@theme/TabItem';
See supported Embedding Providers & Models [here](https://docs.litellm.ai/docs/embedding/supported_embedding)
+## Supported Input Formats
+
+The `/v1/embeddings` endpoint follows the [OpenAI embeddings API specification](https://platform.openai.com/docs/api-reference/embeddings/create). The following input formats are supported:
+
+| Format | Example |
+|--------|---------|
+| String | `"input": "Hello"` |
+| Array of strings | `"input": ["Hello", "World"]` |
+| Array of tokens (integers) | `"input": [1234, 5678, 9012]` |
+| Array of token arrays | `"input": [[1234, 5678], [9012, 3456]]` |
## Quick start
Here's how to route between GPT-J embedding (sagemaker endpoint), Amazon Titan embedding (Bedrock) and Azure OpenAI embedding on the proxy server:
diff --git a/docs/my-website/docs/proxy/forward_client_headers.md b/docs/my-website/docs/proxy/forward_client_headers.md
index 5477ffe87aa..2155a7517be 100644
--- a/docs/my-website/docs/proxy/forward_client_headers.md
+++ b/docs/my-website/docs/proxy/forward_client_headers.md
@@ -6,6 +6,52 @@ Control which model groups can forward client headers to the underlying LLM prov
By default, LiteLLM does not forward client headers to LLM provider APIs for security reasons. However, you can selectively enable header forwarding for specific model groups using the `forward_client_headers_to_llm_api` setting.
+## How it Works
+
+LiteLLM does **not** forward all client headers to the LLM provider. Instead, it uses an **allowlist** approach — only headers matching specific rules are forwarded. This ensures sensitive headers (like your LiteLLM API key) are never accidentally sent to upstream providers.
+
+```mermaid
+sequenceDiagram
+ participant Client as Client (SDK / curl)
+ participant Proxy as LiteLLM Proxy
+ participant Filter as Header Filter (Allowlist)
+ participant LLM as LLM Provider (OpenAI, Anthropic, etc.)
+
+ Client->>Proxy: Request with all headers (Authorization, x-trace-id, x-custom-header, anthropic-beta, etc.)
+
+ Proxy->>Filter: Check forward_client_headers_to_llm_api setting for this model group
+
+ Note over Filter: Allowlist rules: 1. Headers starting with "x-" ✅ 2. "anthropic-beta" ✅ 3. "x-stainless-*" ❌ (blocked) 4. All other headers ❌ (blocked)
+
+ Filter-->>Proxy: Return only allowed headers
+
+ Proxy->>LLM: Request with filtered headers (x-trace-id, x-custom-header, anthropic-beta)
+
+ LLM-->>Proxy: Response
+ Proxy-->>Client: Response
+```
+
+### Header Allowlist Rules
+
+The following rules determine which headers are forwarded (see [`_get_forwardable_headers`](https://github.com/litellm/litellm/blob/main/litellm/proxy/litellm_pre_call_utils.py) in `litellm/proxy/litellm_pre_call_utils.py`):
+
+| Rule | Example | Forwarded? |
+|---|---|---|
+| Headers starting with `x-` | `x-trace-id`, `x-custom-header`, `x-request-source` | ✅ Yes |
+| `anthropic-beta` header | `anthropic-beta: prompt-caching-2024-07-31` | ✅ Yes |
+| Headers starting with `x-stainless-*` | `x-stainless-lang`, `x-stainless-arch` | ❌ No (causes OpenAI SDK issues) |
+| Standard HTTP headers | `Authorization`, `Content-Type`, `Host` | ❌ No |
+| Other provider headers | `Accept`, `User-Agent` | ❌ No |
+
+### Additional Header Mechanisms
+
+| Mechanism | Description | Reference |
+|---|---|---|
+| **`x-pass-` prefix** | Headers prefixed with `x-pass-` are always forwarded with the prefix stripped, regardless of settings. E.g., `x-pass-anthropic-beta: value` → `anthropic-beta: value`. Works for all pass-through endpoints. | [Source code](https://github.com/litellm/litellm/blob/main/litellm/passthrough/utils.py) |
+| **`openai-organization`** | Forwarded only when `forward_openai_org_id: true` is set in `general_settings`. | [Forward OpenAI Org ID](#enable-globally) |
+| **User information headers** | When `add_user_information_to_llm_headers: true`, LiteLLM adds `x-litellm-user-id`, `x-litellm-org-id`, etc. | [User Information Headers](#user-information-headers-optional) |
+| **Vertex AI pass-through** | Uses a separate, stricter allowlist: only `anthropic-beta` and `content-type`. | [Source code](https://github.com/litellm/litellm/blob/main/litellm/constants.py) |
+
## Configuration
## Enable Globally
diff --git a/docs/my-website/docs/proxy/guardrails/custom_code_guardrail.md b/docs/my-website/docs/proxy/guardrails/custom_code_guardrail.md
new file mode 100644
index 00000000000..8cbc247ae5e
--- /dev/null
+++ b/docs/my-website/docs/proxy/guardrails/custom_code_guardrail.md
@@ -0,0 +1,332 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Custom Code Guardrail
+
+Write custom guardrail logic using Python-like code that runs in a sandboxed environment.
+
+## Quick Start
+
+### 1. Define the guardrail in config
+
+```yaml
+model_list:
+ - model_name: gpt-4
+ litellm_params:
+ model: gpt-4
+ api_key: os.environ/OPENAI_API_KEY
+
+guardrails:
+ - guardrail_name: block-ssn
+ litellm_params:
+ guardrail: custom_code
+ mode: pre_call
+ custom_code: |
+ def apply_guardrail(inputs, request_data, input_type):
+ for text in inputs["texts"]:
+ if regex_match(text, r"\d{3}-\d{2}-\d{4}"):
+ return block("SSN detected")
+ return allow()
+```
+
+### 2. Start proxy
+
+```bash
+litellm --config config.yaml
+```
+
+### 3. Test
+
+```bash
+curl -X POST http://localhost:4000/chat/completions \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "My SSN is 123-45-6789"}],
+ "guardrails": ["block-ssn"]
+ }'
+```
+
+## Configuration
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `guardrail` | string | ✅ | Must be `custom_code` |
+| `mode` | string | ✅ | When to run: `pre_call`, `post_call`, `during_call` |
+| `custom_code` | string | ✅ | Python-like code with `apply_guardrail` function |
+| `default_on` | bool | ❌ | Run on all requests (default: `false`) |
+
+## Writing Custom Code
+
+### Function Signature
+
+Your code must define an `apply_guardrail` function. It can be either sync or async:
+
+```python
+# Sync version
+def apply_guardrail(inputs, request_data, input_type):
+ # inputs: see table below
+ # request_data: {"model": "...", "user_id": "...", "team_id": "...", "metadata": {...}}
+ # input_type: "request" or "response"
+
+ return allow() # or block() or modify()
+
+# Async version (recommended when using HTTP primitives)
+async def apply_guardrail(inputs, request_data, input_type):
+ response = await http_post("https://api.example.com/check", body={"text": inputs["texts"][0]})
+ if response["success"] and response["body"].get("flagged"):
+ return block("Content flagged")
+ return allow()
+```
+
+### `inputs` Parameter
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `texts` | `List[str]` | Extracted text from the request/response |
+| `images` | `List[str]` | Extracted images (for image guardrails) |
+| `tools` | `List[dict]` | Tools sent to the LLM |
+| `tool_calls` | `List[dict]` | Tool calls returned from the LLM |
+| `structured_messages` | `List[dict]` | Full messages with role info (system/user/assistant) |
+| `model` | `str` | The model being used |
+
+### `request_data` Parameter
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `model` | `str` | Model name |
+| `user_id` | `str` | User ID from API key |
+| `team_id` | `str` | Team ID from API key |
+| `end_user_id` | `str` | End user ID |
+| `metadata` | `dict` | Request metadata |
+
+### Return Values
+
+| Function | Description |
+|----------|-------------|
+| `allow()` | Let request/response through |
+| `block(reason)` | Reject with message |
+| `modify(texts=[], images=[], tool_calls=[])` | Transform content |
+
+## Built-in Primitives
+
+### Regex
+
+| Function | Description |
+|----------|-------------|
+| `regex_match(text, pattern)` | Returns `True` if pattern found |
+| `regex_replace(text, pattern, replacement)` | Replace all matches |
+| `regex_find_all(text, pattern)` | Return list of matches |
+
+### JSON
+
+| Function | Description |
+|----------|-------------|
+| `json_parse(text)` | Parse JSON string, returns `None` on error |
+| `json_stringify(obj)` | Convert to JSON string |
+| `json_schema_valid(obj, schema)` | Validate against JSON schema |
+
+### URL
+
+| Function | Description |
+|----------|-------------|
+| `extract_urls(text)` | Extract all URLs from text |
+| `is_valid_url(url)` | Check if URL is valid |
+| `all_urls_valid(text)` | Check all URLs in text are valid |
+
+### Code Detection
+
+| Function | Description |
+|----------|-------------|
+| `detect_code(text)` | Returns `True` if code detected |
+| `detect_code_languages(text)` | Returns list of detected languages |
+| `contains_code_language(text, ["sql", "python"])` | Check for specific languages |
+
+### Text Utilities
+
+| Function | Description |
+|----------|-------------|
+| `contains(text, substring)` | Check if substring exists |
+| `contains_any(text, [substr1, substr2])` | Check if any substring exists |
+| `word_count(text)` | Count words |
+| `char_count(text)` | Count characters |
+| `lower(text)` / `upper(text)` / `trim(text)` | String transforms |
+
+### HTTP Requests (Async)
+
+Make async HTTP requests to external APIs for additional validation or content moderation.
+
+| Function | Description |
+|----------|-------------|
+| `await http_request(url, method, headers, body, timeout)` | General async HTTP request |
+| `await http_get(url, headers, timeout)` | Async GET request |
+| `await http_post(url, body, headers, timeout)` | Async POST request |
+
+**Response format:**
+```python
+{
+ "status_code": 200, # HTTP status code
+ "body": {...}, # Response body (parsed JSON or string)
+ "headers": {...}, # Response headers
+ "success": True, # True if status code is 2xx
+ "error": None # Error message if request failed
+}
+```
+
+**Note:** When using HTTP primitives, define your function as `async def apply_guardrail(...)` for non-blocking execution.
+
+## Examples
+
+### Block PII (SSN)
+
+```python
+def apply_guardrail(inputs, request_data, input_type):
+ for text in inputs["texts"]:
+ if regex_match(text, r"\d{3}-\d{2}-\d{4}"):
+ return block("SSN detected")
+ return allow()
+```
+
+### Redact Email Addresses
+
+```python
+def apply_guardrail(inputs, request_data, input_type):
+ pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
+ modified = []
+ for text in inputs["texts"]:
+ modified.append(regex_replace(text, pattern, "[EMAIL REDACTED]"))
+ return modify(texts=modified)
+```
+
+### Block SQL Injection
+
+```python
+def apply_guardrail(inputs, request_data, input_type):
+ if input_type != "request":
+ return allow()
+ for text in inputs["texts"]:
+ if contains_code_language(text, ["sql"]):
+ return block("SQL code not allowed")
+ return allow()
+```
+
+### Validate JSON Response
+
+```python
+def apply_guardrail(inputs, request_data, input_type):
+ if input_type != "response":
+ return allow()
+
+ schema = {
+ "type": "object",
+ "required": ["name", "value"]
+ }
+
+ for text in inputs["texts"]:
+ obj = json_parse(text)
+ if obj is None:
+ return block("Invalid JSON response")
+ if not json_schema_valid(obj, schema):
+ return block("Response missing required fields")
+ return allow()
+```
+
+### Check URLs in Response
+
+```python
+def apply_guardrail(inputs, request_data, input_type):
+ if input_type != "response":
+ return allow()
+ for text in inputs["texts"]:
+ if not all_urls_valid(text):
+ return block("Response contains invalid URLs")
+ return allow()
+```
+
+### Call External Moderation API (Async)
+
+```python
+async def apply_guardrail(inputs, request_data, input_type):
+ # Call an external moderation API
+ for text in inputs["texts"]:
+ response = await http_post(
+ "https://api.example.com/moderate",
+ body={"text": text, "user_id": request_data["user_id"]},
+ headers={"Authorization": "Bearer YOUR_API_KEY"},
+ timeout=10
+ )
+
+ if not response["success"]:
+ # API call failed - decide whether to allow or block
+ return allow()
+
+ if response["body"].get("flagged"):
+ return block(response["body"].get("reason", "Content flagged"))
+
+ return allow()
+```
+
+### Combine Multiple Checks
+
+```python
+def apply_guardrail(inputs, request_data, input_type):
+ modified = []
+
+ for text in inputs["texts"]:
+ # Redact SSN
+ text = regex_replace(text, r"\d{3}-\d{2}-\d{4}", "[SSN]")
+ # Redact credit cards
+ text = regex_replace(text, r"\d{16}", "[CARD]")
+ modified.append(text)
+
+ # Block SQL in requests
+ if input_type == "request":
+ for text in inputs["texts"]:
+ if contains_code_language(text, ["sql"]):
+ return block("SQL injection blocked")
+
+ return modify(texts=modified)
+```
+
+## Sandbox Restrictions
+
+Custom code runs in a restricted environment:
+
+- ❌ No `import` statements
+- ❌ No file I/O
+- ❌ No `exec()` or `eval()`
+- ✅ HTTP requests via built-in `http_request`, `http_get`, `http_post` primitives
+- ✅ Only LiteLLM-provided primitives available
+
+## Per-Request Usage
+
+Enable guardrail per request:
+
+```bash
+curl -X POST http://localhost:4000/chat/completions \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "Hello"}],
+ "guardrails": ["block-ssn"]
+ }'
+```
+
+## Default On
+
+Run guardrail on all requests:
+
+```yaml
+litellm_settings:
+ guardrails:
+ - guardrail_name: block-ssn
+ litellm_params:
+ guardrail: custom_code
+ mode: pre_call
+ default_on: true
+ custom_code: |
+ def apply_guardrail(inputs, request_data, input_type):
+ ...
+```
diff --git a/docs/my-website/docs/proxy/guardrails/grayswan.md b/docs/my-website/docs/proxy/guardrails/grayswan.md
index d6efaf15504..6c0ccbc293d 100644
--- a/docs/my-website/docs/proxy/guardrails/grayswan.md
+++ b/docs/my-website/docs/proxy/guardrails/grayswan.md
@@ -13,20 +13,26 @@ Cygnal returns a `violation` score between `0` and `1` (higher means more likely
### 1. Obtain Credentials
-1. Create a Gray Swan account and generate a Cygnal API key.
+1. Log in to our Gray Swan platform and generate a Cygnal API key.
+
+ For existing customers, you should already have access to our [platform](https://platform.grayswan.ai).
+
+ For new users, please register at this [page](https://hubs.ly/Q03-sX1J0) and we are more than happy to give you an onboarding!
+
+
2. Configure environment variables for the LiteLLM proxy host:
-```bash
-export GRAYSWAN_API_KEY="your-grayswan-key"
-export GRAYSWAN_API_BASE="https://api.grayswan.ai"
-```
+ ```bash
+ export GRAYSWAN_API_KEY="your-grayswan-key"
+ export GRAYSWAN_API_BASE="https://api.grayswan.ai"
+ ```
### 2. Configure `config.yaml`
-Add a guardrail entry that references the Gray Swan integration. Below is a balanced example that monitors both input and output but only blocks once the violation score reaches the configured threshold.
+Add a guardrail entry that references the Gray Swan integration. Below is our recommmended settings.
```yaml
-model_list:
+model_list: # this part is a standard litellm configuration for reference
- model_name: openai/gpt-4.1-mini
litellm_params:
model: openai/gpt-4.1-mini
@@ -40,13 +46,14 @@ guardrails:
api_key: os.environ/GRAYSWAN_API_KEY
api_base: os.environ/GRAYSWAN_API_BASE # optional
optional_params:
- on_flagged_action: monitor # or "block"
+ on_flagged_action: passthrough # or "block" or "monitor"
violation_threshold: 0.5 # score >= threshold is flagged
reasoning_mode: hybrid # off | hybrid | thinking
- categories:
- safety: "Detect jailbreaks and policy violations"
- policy_id: "your-cygnal-policy-id"
+ policy_id: "your-cygnal-policy-id" # Optional: Your Cygnal policy ID. Defaults to a content safety policy if empty.
+ streaming_end_of_stream_only: true # For streaming API, only send the assembled message to Cygnal (post_call only). Defaults to false.
default_on: true
+ guardrail_timeout: 30 # Defaults to 30 seconds. Change accordingly.
+ fail_open: true # Defaults to true; set to false to propagate guardrail errors.
general_settings:
master_key: "your-litellm-master-key"
@@ -65,13 +72,13 @@ litellm --config config.yaml --port 4000
## Choosing Guardrail Modes
-Gray Swan can run during `pre_call`, `during_call`, and `post_call` stages. Combine modes based on your latency and coverage requirements.
+Gray Swan can run during `pre_call`, `during_call`, and `post_call` stages. Combine modes based on your latency and coverage requirements.
| Mode | When it Runs | Protects | Typical Use Case |
|--------------|-------------------|-----------------------|------------------|
| `pre_call` | Before LLM call | User input only | Block prompt injection before it reaches the model |
| `during_call`| Parallel to call | User input only | Low-latency monitoring without blocking |
-| `post_call` | After response | Full conversation | Scan output for policy violations, leaked secrets, or IPI |
+| `post_call` | After response | Model Outputs | Scan output for policy violations, leaked secrets, or IPI |
When using `during_call` with `on_flagged_action: block` or `on_flagged_action: passthrough`:
@@ -81,87 +88,110 @@ When using `during_call` with `on_flagged_action: block` or `on_flagged_action:
- The guardrail exception prevents the response from reaching the user, but **does not cancel the running LLM task**
- This means you pay full LLM costs while returning an error/passthrough message to the user
-**Recommendation:** For cost-sensitive applications, use `pre_call` and `post_call` instead of `during_call` for blocking or passthrough modes. Reserve `during_call` for `monitor` mode where you want low-latency logging without impacting the user experience.
+**Recommendation:** Use `pre_call` and `post_call` instead of `during_call` for `passthrough` (or `block`) `on_flagged_action` (see our recommended configuration above). Reserve `during_call` for `monitor` mode ONLY when you want low-latency logging without impacting the user experience.
-
-
+---
-```yaml
-guardrails:
- - guardrail_name: "cygnal-monitor-only"
- litellm_params:
- guardrail: grayswan
- mode: "during_call"
- api_key: os.environ/GRAYSWAN_API_KEY
- optional_params:
- on_flagged_action: monitor
- violation_threshold: 0.6
- default_on: true
+## Work with Claude Code
+
+Follow the official litellm [guide](https://docs.litellm.ai/docs/tutorials/claude_responses_api) on setting up Claude Code with litellm, with the guardrail part mentioned above added to your litellm configuration. Cygnal natively supports coding agent policies defense. Define your own policy or use the provided coding policies on the platform. The example config we show above is also the recommended setup for Claude Code (with the `policy_id` replaced with an appropriate one).
+
+---
+
+## Per-request overrides via `extra_body`
+
+You can override parts of the Gray Swan guardrail configuration on a per-request basis by passing `litellm_metadata.guardrails[*].grayswan.extra_body`.
+
+`extra_body` is merged into the Cygnal request body and takes precedence over specific fields from `config.yaml`, which are `policy_id`, `violation_threshold`, and `reasoning_mode`.
+
+If you include a `metadata` field inside `extra_body`, it is forwarded to the Cygnal API as-is under the request body's `metadata` field.
+
+Example:
+
+```bash
+curl -X POST "http://0.0.0.0:4000/v1/messages?beta=true" \
+ -H "Authorization: Bearer token" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "openrouter/anthropic/claude-sonnet-4.5",
+ "messages": [{"role": "user", "content": "hello"}],
+ "litellm_metadata": {
+ "guardrails": [
+ {
+ "cygnal-monitor": {
+ "extra_body": {
+ "policy_id": "specific policy id you want to use",
+ "metadata": {
+ "user": "health-check"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }'
```
-Best for visibility without blocking. Alerts are logged via LiteLLM’s standard logging callbacks.
+OpenAI client:
-
-
+```python
+from openai import OpenAI
-```yaml
-guardrails:
- - guardrail_name: "cygnal-block-input"
- litellm_params:
- guardrail: grayswan
- mode: "pre_call"
- api_key: os.environ/GRAYSWAN_API_KEY
- optional_params:
- on_flagged_action: block
- violation_threshold: 0.4
- categories:
- pii: "Detect sensitive data"
- default_on: true
+client = OpenAI(api_key="anything", base_url="http://0.0.0.0:4000")
+
+resp = client.responses.create(
+ model="openrouter/anthropic/claude-sonnet-4.5",
+ input="hello",
+ extra_body={
+ "litellm_metadata": {
+ "guardrails": [
+ {
+ "cygnal-monitor": {
+ "extra_body": {
+ "policy_id": "69038214e5cdb6befc5e991e",
+ "metadata": {"trace_id": "trace-123"},
+ }
+ }
+ }
+ ]
+ }
+ },
+)
```
-Stops malicious or sensitive prompts before any tokens are generated.
+Anthropic client:
-
-
+```python
+from anthropic import Anthropic
-```yaml
-guardrails:
- - guardrail_name: "cygnal-full-coverage"
- litellm_params:
- guardrail: grayswan
- mode: [pre_call, post_call]
- api_key: os.environ/GRAYSWAN_API_KEY
- optional_params:
- on_flagged_action: block
- violation_threshold: 0.5
- reasoning_mode: thinking
- policy_id: "policy-id-from-grayswan"
- default_on: true
+client = Anthropic(api_key="anything", base_url="http://0.0.0.0:4000")
+
+resp = client.messages.create(
+ model="openrouter/anthropic/claude-sonnet-4.5",
+ max_tokens=256,
+ messages=[{"role": "user", "content": "hello"}],
+ extra_body={
+ "litellm_metadata": {
+ "guardrails": [
+ {
+ "cygnal-monitor": {
+ "extra_body": {
+ "policy_id": "69038214e5cdb6befc5e991e",
+ "metadata": {"trace_id": "trace-123"},
+ }
+ }
+ }
+ ]
+ }
+ },
+)
```
-Provides the strongest enforcement by inspecting both prompts and responses.
+Notes:
-
-
-
-```yaml
-guardrails:
- - guardrail_name: "cygnal-passthrough"
- litellm_params:
- guardrail: grayswan
- mode: [pre_call, post_call]
- api_key: os.environ/GRAYSWAN_API_KEY
- optional_params:
- on_flagged_action: passthrough
- violation_threshold: 0.5
- default_on: true
-```
-
-Allows requests to proceed without raising a 400 error when content is flagged. Instead of blocking, the model response content is replaced with a detailed violation message including violation score, violated rules, and detection flags (mutation, IPI). **Supported Response Formats:** OpenAI chat/text completions, Anthropic Messages API. Other response types (embeddings, images, etc.) will log a warning and return unchanged.
-
-
-
+- The guardrail name (for example, `cygnal-monitor`) must match the `guardrail_name` in `config.yaml`.
+- Per-request guardrail overrides may require a premium license, depending on your proxy settings.
---
@@ -170,9 +200,14 @@ Allows requests to proceed without raising a 400 error when content is flagged.
| Parameter | Type | Description |
|---------------------------------------|-----------------|-------------|
| `api_key` | string | Gray Swan Cygnal API key. Reads from `GRAYSWAN_API_KEY` if omitted. |
+| `api_base` | string | Override for the Gray Swan API base URL. Defaults to `https://api.grayswan.ai` or `GRAYSWAN_API_BASE`. |
| `mode` | string or list | Guardrail stages (`pre_call`, `during_call`, `post_call`). |
| `optional_params.on_flagged_action` | string | `monitor` (log only), `block` (raise `HTTPException`), or `passthrough` (replace response content with violation message, no 400 error). |
-| `.optional_params.violation_threshold`| number (0-1) | Scores at or above this value are considered violations. |
+| `optional_params.violation_threshold` | number (0-1) | Scores at or above this value are considered violations. |
| `optional_params.reasoning_mode` | string | `off`, `hybrid`, or `thinking`. Enables Cygnal's reasoning capabilities. |
| `optional_params.categories` | object | Map of custom category names to descriptions. |
| `optional_params.policy_id` | string | Gray Swan policy identifier. |
+| `guardrail_timeout` | number | Timeout in seconds for the Cygnal request. Defaults to 30. |
+| `fail_open` | boolean | If true, errors contacting Cygnal are logged and the request proceeds; if false, errors propagate. Defaults to treu. |
+| `streaming_end_of_stream_only` | boolean | For streaming `post_call`, only send the final assembled response to Cygnal. Defaults to false. |
+| `default_on` | boolean | Run the guardrail on every request by default. |
diff --git a/docs/my-website/docs/proxy/guardrails/guardrail_policies.md b/docs/my-website/docs/proxy/guardrails/guardrail_policies.md
new file mode 100644
index 00000000000..e2cb839203e
--- /dev/null
+++ b/docs/my-website/docs/proxy/guardrails/guardrail_policies.md
@@ -0,0 +1,396 @@
+import Image from '@theme/IdealImage';
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# [Beta] Guardrail Policies
+
+Use policies to group guardrails and control which ones run for specific teams, keys, or models.
+
+## Why use policies?
+
+- Enable/disable specific guardrails for teams, keys, or models
+- Group guardrails into a single policy
+- Inherit from existing policies and override what you need
+
+## Quick Start
+
+
+
+
+```yaml showLineNumbers title="config.yaml"
+model_list:
+ - model_name: gpt-4
+ litellm_params:
+ model: openai/gpt-4
+
+# 1. Define your guardrails
+guardrails:
+ - guardrail_name: pii_masking
+ litellm_params:
+ guardrail: presidio
+ mode: pre_call
+
+ - guardrail_name: prompt_injection
+ litellm_params:
+ guardrail: lakera
+ mode: pre_call
+ api_key: os.environ/LAKERA_API_KEY
+
+# 2. Create a policy
+policies:
+ my-policy:
+ guardrails:
+ add:
+ - pii_masking
+ - prompt_injection
+
+# 3. Attach the policy
+policy_attachments:
+ - policy: my-policy
+ scope: "*" # apply to all requests
+```
+
+
+
+
+**Step 1: Create a Policy**
+
+Go to **Policies** tab and click **+ Create New Policy**. Fill in the policy name, description, and select guardrails to add.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Response headers show what ran:
+
+```
+x-litellm-applied-policies: my-policy
+x-litellm-applied-guardrails: pii_masking,prompt_injection
+```
+
+## Add guardrails for a specific team
+
+:::info
+✨ Enterprise only feature for team/key-based policy attachments. [Get a free trial](https://www.litellm.ai/enterprise#trial)
+:::
+
+You have a global baseline, but want to add extra guardrails for a specific team.
+
+
+
+
+```yaml showLineNumbers title="config.yaml"
+policies:
+ global-baseline:
+ guardrails:
+ add:
+ - pii_masking
+
+ finance-team-policy:
+ inherit: global-baseline
+ guardrails:
+ add:
+ - strict_compliance_check
+ - audit_logger
+
+policy_attachments:
+ - policy: global-baseline
+ scope: "*"
+
+ - policy: finance-team-policy
+ teams:
+ - finance # team alias from /team/new
+```
+
+
+
+
+**Option 1: Create a team-scoped attachment**
+
+Go to **Policies** > **Attachments** tab and click **+ Create New Attachment**. Select the policy and the teams to scope it to.
+
+
+
+
+
+**Option 2: Attach from team settings**
+
+Go to **Teams** > click on a team > **Settings** tab > under **Policies**, select the policies to attach.
+
+
+
+
+
+
+
+
+
+
+Now the `finance` team gets `pii_masking` + `strict_compliance_check` + `audit_logger`, while everyone else just gets `pii_masking`.
+
+## Remove guardrails for a specific team
+
+:::info
+✨ Enterprise only feature for team/key-based policy attachments. [Get a free trial](https://www.litellm.ai/enterprise#trial)
+:::
+
+You have guardrails running globally, but want to disable some for a specific team (e.g., internal testing).
+
+```yaml showLineNumbers title="config.yaml"
+policies:
+ global-baseline:
+ guardrails:
+ add:
+ - pii_masking
+ - prompt_injection
+
+ internal-team-policy:
+ inherit: global-baseline
+ guardrails:
+ remove:
+ - pii_masking # don't need PII masking for internal testing
+
+policy_attachments:
+ - policy: global-baseline
+ scope: "*"
+
+ - policy: internal-team-policy
+ teams:
+ - internal-testing # team alias from /team/new
+```
+
+Now the `internal-testing` team only gets `prompt_injection`, while everyone else gets both guardrails.
+
+## Inheritance
+
+Start with a base policy and build on it:
+
+```yaml showLineNumbers title="config.yaml"
+policies:
+ base:
+ guardrails:
+ add:
+ - pii_masking
+ - toxicity_filter
+
+ strict:
+ inherit: base
+ guardrails:
+ add:
+ - prompt_injection
+
+ relaxed:
+ inherit: base
+ guardrails:
+ remove:
+ - toxicity_filter
+```
+
+What you get:
+- `base` → `[pii_masking, toxicity_filter]`
+- `strict` → `[pii_masking, toxicity_filter, prompt_injection]`
+- `relaxed` → `[pii_masking]`
+
+## Model Conditions
+
+Run guardrails only for specific models:
+
+```yaml showLineNumbers title="config.yaml"
+policies:
+ gpt4-safety:
+ guardrails:
+ add:
+ - strict_content_filter
+ condition:
+ model: "gpt-4.*" # regex - matches gpt-4, gpt-4-turbo, gpt-4o
+
+ bedrock-compliance:
+ guardrails:
+ add:
+ - audit_logger
+ condition:
+ model: # exact match list
+ - bedrock/claude-3
+ - bedrock/claude-2
+```
+
+## Attachments
+
+Policies don't do anything until you attach them. Attachments tell LiteLLM *where* to apply each policy.
+
+**Global** - runs on every request:
+
+```yaml showLineNumbers title="config.yaml"
+policy_attachments:
+ - policy: default
+ scope: "*"
+```
+
+**Team-specific** (uses team alias from `/team/new`):
+
+```yaml showLineNumbers title="config.yaml"
+policy_attachments:
+ - policy: hipaa-compliance
+ teams:
+ - healthcare-team # team alias
+ - medical-research # team alias
+```
+
+**Key-specific** (uses key alias from `/key/generate`, wildcards supported):
+
+```yaml showLineNumbers title="config.yaml"
+policy_attachments:
+ - policy: internal-testing
+ keys:
+ - "dev-*" # key alias pattern
+ - "test-*" # key alias pattern
+```
+
+**Tag-based** (matches keys/teams by metadata tags, wildcards supported):
+
+```yaml showLineNumbers title="config.yaml"
+policy_attachments:
+ - policy: hipaa-compliance
+ tags:
+ - "healthcare"
+ - "health-*" # wildcard - matches health-team, health-dev, etc.
+```
+
+Tags are read from key and team `metadata.tags`. For example, a key created with `metadata: {"tags": ["healthcare"]}` would match the attachment above.
+
+## Test Policy Matching
+
+Debug which policies and guardrails apply for a given context. Use this to verify your policy configuration before deploying.
+
+
+
+
+Go to **Policies** > **Test** tab. Enter a team alias, key alias, model, or tags and click **Test** to see which policies match and what guardrails would be applied.
+
+
+
+
+
+
+```bash
+curl -X POST "http://localhost:4000/policies/resolve" \
+ -H "Authorization: Bearer " \
+ -H "Content-Type: application/json" \
+ -d '{
+ "tags": ["healthcare"],
+ "model": "gpt-4"
+ }'
+```
+
+Response:
+
+```json
+{
+ "effective_guardrails": ["pii_masking"],
+ "matched_policies": [
+ {
+ "policy_name": "hipaa-compliance",
+ "matched_via": "tag:healthcare",
+ "guardrails_added": ["pii_masking"]
+ }
+ ]
+}
+```
+
+
+
+
+## Config Reference
+
+### `policies`
+
+```yaml
+policies:
+ :
+ description: ...
+ inherit: ...
+ guardrails:
+ add: [...]
+ remove: [...]
+ condition:
+ model: ...
+```
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `description` | `string` | Optional. What this policy does. |
+| `inherit` | `string` | Optional. Parent policy to inherit guardrails from. |
+| `guardrails.add` | `list[string]` | Guardrails to enable. |
+| `guardrails.remove` | `list[string]` | Guardrails to disable (useful with inheritance). |
+| `condition.model` | `string` or `list[string]` | Optional. Only apply when model matches. Supports regex. |
+
+### `policy_attachments`
+
+```yaml
+policy_attachments:
+ - policy: ...
+ scope: ...
+ teams: [...]
+ keys: [...]
+ models: [...]
+ tags: [...]
+```
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `policy` | `string` | **Required.** Name of the policy to attach. |
+| `scope` | `string` | Use `"*"` to apply globally. |
+| `teams` | `list[string]` | Team aliases (from `/team/new`). Supports `*` wildcard. |
+| `keys` | `list[string]` | Key aliases (from `/key/generate`). Supports `*` wildcard. |
+| `models` | `list[string]` | Model names. Supports `*` wildcard. |
+| `tags` | `list[string]` | Tag patterns (from key/team `metadata.tags`). Supports `*` wildcard. |
+
+### Response Headers
+
+| Header | Description |
+|--------|-------------|
+| `x-litellm-applied-policies` | Policies that matched this request |
+| `x-litellm-applied-guardrails` | Guardrails that actually ran |
+| `x-litellm-policy-sources` | Why each policy matched (e.g., `hipaa=tag:healthcare; baseline=scope:*`) |
+
+## How it works
+
+Example config:
+
+```yaml showLineNumbers title="config.yaml"
+policies:
+ base:
+ guardrails:
+ add: [pii_masking]
+
+ finance-policy:
+ inherit: base
+ guardrails:
+ add: [audit_logger]
+
+policy_attachments:
+ - policy: base
+ scope: "*"
+ - policy: finance-policy
+ teams: [finance]
+```
+
+```mermaid
+flowchart TD
+ A["Request with team_alias='finance'"] --> B["Matches policies: base, finance-policy"]
+ B --> C["Resolves guardrails: pii_masking, audit_logger"]
+```
+
+1. Request comes in with `team_alias='finance'`
+2. Matches `base` (via `scope: "*"`) and `finance-policy` (via `teams: [finance]`)
+3. Resolves guardrails: `base` adds `pii_masking`, `finance-policy` inherits and adds `audit_logger`
+4. Final guardrails: `pii_masking`, `audit_logger`
diff --git a/docs/my-website/docs/proxy/guardrails/onyx_security.md b/docs/my-website/docs/proxy/guardrails/onyx_security.md
index 85b0ba9f830..d240902eb52 100644
--- a/docs/my-website/docs/proxy/guardrails/onyx_security.md
+++ b/docs/my-website/docs/proxy/guardrails/onyx_security.md
@@ -128,6 +128,7 @@ guardrails:
mode: ["pre_call", "post_call", "during_call"] # Run at multiple stages
api_key: os.environ/ONYX_API_KEY
api_base: os.environ/ONYX_API_BASE
+ timeout: 10.0 # Optional, defaults to 10 seconds
```
### Required Parameters
@@ -137,6 +138,7 @@ guardrails:
### Optional Parameters
- **`api_base`**: Onyx API base URL (defaults to `https://ai-guard.onyx.security`)
+- **`timeout`**: Request timeout in seconds (defaults to `10.0`)
## Environment Variables
@@ -145,4 +147,5 @@ You can set these environment variables instead of hardcoding values in your con
```shell
export ONYX_API_KEY="your-api-key-here"
export ONYX_API_BASE="https://ai-guard.onyx.security" # Optional
+export ONYX_TIMEOUT=10 # Optional, timeout in seconds
```
diff --git a/docs/my-website/docs/proxy/guardrails/policy_tags.md b/docs/my-website/docs/proxy/guardrails/policy_tags.md
new file mode 100644
index 00000000000..11840116c31
--- /dev/null
+++ b/docs/my-website/docs/proxy/guardrails/policy_tags.md
@@ -0,0 +1,139 @@
+# Tag-Based Policy Attachments
+
+Apply guardrail policies automatically to any key or team that has a specific tag. Instead of attaching policies one-by-one, tag your keys and let the policy engine handle the rest.
+
+**Example:** Your security team requires all healthcare-related keys to run PII masking and PHI detection. Tag those keys with `health`, create a single tag-based attachment, and every matching key gets the guardrails automatically.
+
+## 1. Create a Policy with Guardrails
+
+Navigate to **Policies** in the left sidebar. You'll see a list of existing policies along with their guardrails.
+
+
+
+Click **+ Add New Policy**. In the modal, enter a name for your policy (e.g., `high-risk-policy2`). You can also type to search existing policy names if you want to reference them.
+
+
+
+Scroll down to **Guardrails to Add**. Click the dropdown to see all available guardrails configured on your proxy — select the ones this policy should enforce.
+
+
+
+After selecting your guardrails, they appear as chips in the input field. The **Resolved Guardrails** section below shows the final set that will be applied (including any inherited from a parent policy).
+
+
+
+Click **Create Policy** to save.
+
+
+
+## 2. Add a Tag Attachment for the Policy
+
+After creating the policy, switch to the **Attachments** tab. This is where you define *where* the policy applies.
+
+
+
+Click **+ Add New Attachment**. The Attachments page explains the available scopes: Global, Teams, Keys, Models, and **Tags**.
+
+
+
+In the **Create Policy Attachment** modal, first select the policy you just created from the dropdown.
+
+
+
+Choose **Specific (teams, keys, models, or tags)** as the scope type. This expands the form to show fields for Teams, Keys, Models, and Tags.
+
+
+
+Scroll down to the **Tags** field and type the tag to match — here we enter `health`. You can enter any string, or use a wildcard pattern like `health-*` to match all tags starting with `health-` (e.g., `health-team`, `health-dev`).
+
+
+
+## 3. Check the Impact of the Attachment
+
+Before creating the attachment, click **Estimate Impact** to preview how many keys and teams would be affected. This is your blast-radius check — make sure the scope is what you expect before applying.
+
+
+
+The **Impact Preview** appears inline, showing exactly how many keys and teams would be affected. In this example: "This attachment would affect **1 key** and **0 teams**", with the key alias `hi` listed.
+
+
+
+Once you're satisfied with the impact, click **Create Attachment** to save.
+
+
+
+The attachment now appears in the table with the policy name `high-risk-policy2` and tag `health` visible.
+
+
+
+## 4. Create a Key with the Tag
+
+Navigate to **Virtual Keys** in the left sidebar. Click **+ Create New Key**.
+
+
+
+Enter a key name and select a model. Then expand **Optional Settings** and scroll down to the **Tags** field.
+
+
+
+In the **Tags** field, type `health` and press Enter. This is the tag the policy engine will match against.
+
+
+
+The tag `health` now appears as a chip in the Tags field. Confirm your settings look correct.
+
+
+
+Click **Create Key** at the bottom of the form.
+
+
+
+A dialog appears with your new virtual key. Click **Copy Virtual Key** — you'll need this to test in the next step.
+
+
+
+## 5. Test the Key and Validate the Policy is Applied
+
+Navigate to **Playground** in the left sidebar to test the key interactively.
+
+
+
+Under **Virtual Key Source**, select "Virtual Key" and paste the key you just copied into the input field.
+
+
+
+Select a model from the **Select Model** dropdown.
+
+
+
+Type a message and press Enter. If a guardrail blocks the request, you'll see it in the response. In this example, the `testing-pl` guardrail detected an email pattern and returned a 403 error — confirming the policy is working.
+
+
+
+**Using curl:**
+
+You can also verify via the command line. The response headers confirm which policies and guardrails were applied:
+
+```bash
+curl -v http://localhost:4000/chat/completions \
+ -H "Authorization: Bearer " \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4o",
+ "messages": [{"role": "user", "content": "say hi"}]
+ }'
+```
+
+Check the response headers:
+
+```
+x-litellm-applied-policies: high-risk-policy2
+x-litellm-applied-guardrails: pii-pre-guard,phi-pre-guard,testing-pl
+x-litellm-policy-sources: high-risk-policy2=tag:health
+```
+
+| Header | What it tells you |
+|--------|-------------------|
+| `x-litellm-applied-policies` | Which policies matched this request |
+| `x-litellm-applied-guardrails` | Which guardrails actually ran |
+| `x-litellm-policy-sources` | **Why** each policy matched — `tag:health` confirms it was the tag |
diff --git a/docs/my-website/docs/proxy/guardrails/policy_templates.md b/docs/my-website/docs/proxy/guardrails/policy_templates.md
new file mode 100644
index 00000000000..f0c93ca44c7
--- /dev/null
+++ b/docs/my-website/docs/proxy/guardrails/policy_templates.md
@@ -0,0 +1,296 @@
+# Policy Templates
+
+Policy templates provide pre-configured guardrail policies that you can use as a starting point for your organization. Instead of manually creating policies and guardrails, you can select a template that matches your use case and deploy it with one click.
+
+## Using Policy Templates
+
+### In the UI
+
+1. Navigate to **Policies → Templates** tab in the LiteLLM Admin UI
+2. Browse available templates (e.g., "PII Protection", "Cost Control", "HR Compliance")
+3. Click **"Use Template"** on any template
+4. Review the guardrails that will be created:
+ - Existing guardrails are marked with a green checkmark
+ - New guardrails can be selected/deselected
+5. Click **"Create X Guardrails & Use Template"**
+6. Review and customize the pre-filled policy form
+7. Click **"Create Policy"** to save
+
+### Workflow
+
+```
+Select Template → Review Guardrails → Create Selected → Edit Policy → Save
+```
+
+The system automatically:
+- ✅ Detects which guardrails already exist
+- ✅ Creates only the missing guardrails you select
+- ✅ Pre-fills the policy form with template data
+- ✅ Lets you customize before saving
+
+## Available Templates
+
+Templates are fetched from [GitHub](https://raw.githubusercontent.com/BerriAI/litellm/main/policy_templates.json) with automatic fallback to local backup.
+
+### Current Templates
+
+#### 1. Advanced PII Protection (Australia)
+- **Complexity:** High
+- **Use Case:** Comprehensive PII detection for Australian organizations
+- **Guardrails:**
+ - Australian tax identifiers (TFN, ABN, Medicare)
+ - Australian passports
+ - International PII (SSN, passports, national IDs)
+ - Contact information (email, phone, address)
+ - Financial data (credit cards, IBAN)
+ - API credentials (AWS, GitHub, Slack) - **BLOCKS** requests
+ - Network infrastructure (IP addresses)
+ - Protected class information (gender, race, religion, disability, etc.)
+
+#### 2. Baseline PII Protection
+- **Complexity:** Low
+- **Use Case:** Basic protection for internal tools and testing
+- **Guardrails:**
+ - Australian tax identifiers
+ - API credentials
+ - Financial data
+
+## Creating Your Own Policy Templates
+
+You can contribute policy templates for the entire LiteLLM community to use.
+
+### Template Structure
+
+Templates are defined in JSON format with the following structure:
+
+```json
+{
+ "id": "unique-template-id",
+ "title": "Display Title",
+ "description": "Detailed description of what this template protects",
+ "icon": "ShieldCheckIcon",
+ "iconColor": "text-purple-500",
+ "iconBg": "bg-purple-50",
+ "guardrails": [
+ "guardrail-name-1",
+ "guardrail-name-2"
+ ],
+ "complexity": "Low|Medium|High",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "example-guardrail",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "email",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "What this guardrail does"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "policy-name",
+ "description": "Policy description",
+ "guardrails_add": ["guardrail-name-1", "guardrail-name-2"],
+ "guardrails_remove": []
+ }
+}
+```
+
+### Field Descriptions
+
+#### Display Fields
+- **id**: Unique identifier (lowercase with hyphens)
+- **title**: User-facing name shown in UI
+- **description**: Detailed explanation of what the template protects
+- **icon**: Icon name (must be available in UI icon map)
+- **iconColor**: Tailwind CSS text color class
+- **iconBg**: Tailwind CSS background color class
+- **guardrails**: Array of guardrail names (for display only)
+- **complexity**: Badge showing difficulty ("Low", "Medium", or "High")
+
+#### Guardrail Definitions
+- **guardrailDefinitions**: Array of complete guardrail configurations
+ - Each must be a valid guardrail object that can be sent to `/guardrails` POST endpoint
+ - If a guardrail already exists, it will be skipped
+ - Can be empty `[]` if template uses only existing guardrails
+
+#### Policy Configuration
+- **templateData**: Object that pre-fills the policy form
+ - **policy_name**: Suggested name (user can edit)
+ - **description**: Policy description
+ - **guardrails_add**: Array of guardrail names to include
+ - **guardrails_remove**: Array to remove (usually `[]` for templates)
+ - **inherit**: (Optional) Parent policy name for inheritance
+
+### Example Template
+
+Here's a complete example for a HIPAA compliance template:
+
+```json
+{
+ "id": "hipaa-compliance",
+ "title": "HIPAA Compliance Policy",
+ "description": "Healthcare compliance policy that masks PHI and enforces HIPAA regulations for healthcare applications.",
+ "icon": "ShieldCheckIcon",
+ "iconColor": "text-red-500",
+ "iconBg": "bg-red-50",
+ "guardrails": [
+ "phi-detector",
+ "medical-record-blocker",
+ "patient-id-masker"
+ ],
+ "complexity": "High",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "phi-detector",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "us_ssn",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "email",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "us_phone",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[PHI_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Detects and masks Protected Health Information (PHI)"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "hipaa-compliance-policy",
+ "description": "HIPAA compliance policy for healthcare applications",
+ "guardrails_add": [
+ "phi-detector",
+ "medical-record-blocker",
+ "patient-id-masker"
+ ],
+ "guardrails_remove": []
+ }
+}
+```
+
+## Contributing Templates
+
+To contribute a policy template for everyone to use:
+
+### Step 1: Create Your Template JSON
+
+1. Create a JSON file following the structure above
+2. Test it locally by adding it to your local `policy_templates.json`
+3. Verify all guardrails work correctly
+4. Ensure descriptions are clear and helpful
+
+### Step 2: Submit a Pull Request
+
+1. Fork the [LiteLLM repository](https://github.com/BerriAI/litellm)
+2. Add your template to `policy_templates.json` at the root
+3. Add your template to `litellm/policy_templates_backup.json` (keep both in sync)
+4. Create a pull request with:
+ - Clear description of what the template protects
+ - Use case examples
+ - Any relevant compliance frameworks (HIPAA, GDPR, SOC 2, etc.)
+
+### Guidelines
+
+**DO:**
+- ✅ Use clear, descriptive names
+- ✅ Include comprehensive descriptions
+- ✅ Test all guardrails thoroughly
+- ✅ Document pattern sources (e.g., "Based on NIST guidelines")
+- ✅ Group related guardrails logically
+- ✅ Consider different complexity levels
+
+**DON'T:**
+- ❌ Include credentials or secrets
+- ❌ Use overly broad patterns that may have false positives
+- ❌ Duplicate existing templates
+- ❌ Use custom code without thorough testing
+
+## Using Templates Offline
+
+For air-gapped or offline deployments, set the environment variable:
+
+```bash
+export LITELLM_LOCAL_POLICY_TEMPLATES=true
+```
+
+This forces the system to use the local backup (`litellm/policy_templates_backup.json`) instead of fetching from GitHub.
+
+## Template Sources
+
+- **GitHub (default):** https://raw.githubusercontent.com/BerriAI/litellm/main/policy_templates.json
+- **Local backup:** `litellm/policy_templates_backup.json`
+
+Templates are automatically fetched from GitHub on each request, with fallback to local backup on any failure.
+
+## Available Pattern Types
+
+When creating guardrails for templates, you can use these prebuilt patterns:
+
+### Identity Documents
+- `passport_australia`, `passport_us`, `passport_uk`, `passport_germany`, etc.
+- `us_ssn`, `us_ssn_no_dash`
+- `au_tfn`, `au_abn`, `au_medicare`
+- `nl_bsn_contextual`
+- `br_cpf`, `br_rg`, `br_cnpj`
+
+### Financial
+- `visa`, `mastercard`, `amex`, `discover`, `credit_card`
+- `iban`
+
+### Contact Information
+- `email`
+- `us_phone`, `br_phone_landline`, `br_phone_mobile`
+- `street_address`
+- `br_cep` (Brazilian postal code)
+
+### Credentials
+- `aws_access_key`, `aws_secret_key`
+- `github_token`
+- `slack_token`
+- `generic_api_key`
+
+### Network
+- `ipv4`, `ipv6`
+
+### Protected Class
+- `gender_sexual_orientation`
+- `race_ethnicity_national_origin`
+- `religion`
+- `age_discrimination`
+- `disability`
+- `marital_family_status`
+- `military_status`
+- `public_assistance`
+
+See the [full patterns list](https://github.com/BerriAI/litellm/blob/main/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/patterns.json) for all available patterns.
+
+## Related Docs
+
+- [Guardrail Policies](./guardrail_policies)
+- [Policy Tags](./policy_tags)
+- [Content Filter Patterns](../hooks/content_filter)
+- [Custom Code Guardrails](../hooks/custom_code)
diff --git a/docs/my-website/docs/proxy/guardrails/quick_start.md b/docs/my-website/docs/proxy/guardrails/quick_start.md
index 4a8dc4e6fe4..ddb215fcb66 100644
--- a/docs/my-website/docs/proxy/guardrails/quick_start.md
+++ b/docs/my-website/docs/proxy/guardrails/quick_start.md
@@ -203,8 +203,12 @@ Your response headers will include `x-litellm-applied-guardrails` with the guard
x-litellm-applied-guardrails: aporia-pre-guard
```
+### Guardrail Policies
-
+Need more control? Use [Guardrail Policies](./guardrail_policies.md) to:
+- Group guardrails into reusable policies
+- Enable/disable guardrails for specific teams, keys, or models
+- Inherit from existing policies and override specific guardrails
## **Using Guardrails Client Side**
@@ -401,14 +405,10 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \
## **Proxy Admin Controls**
-### ✨ Monitoring Guardrails
+### Monitoring Guardrails
Monitor which guardrails were executed and whether they passed or failed. e.g. guardrail going rogue and failing requests we don't intend to fail
-:::info
-
-✨ This is an Enterprise only feature [Get a free trial](https://www.litellm.ai/enterprise#trial)
-
:::
#### Setup
diff --git a/docs/my-website/docs/proxy/guardrails/zscaler_ai_guard.md b/docs/my-website/docs/proxy/guardrails/zscaler_ai_guard.md
index 94f31c3bfdf..2e626004238 100644
--- a/docs/my-website/docs/proxy/guardrails/zscaler_ai_guard.md
+++ b/docs/my-website/docs/proxy/guardrails/zscaler_ai_guard.md
@@ -100,7 +100,7 @@ In cases where encounter other errors when apply Zscaler AI Guard, return exampl
}
}
```
-## 6. Sending User Information to Zscaler AI Guard for Analysis (Optional)
+## 6. Sending User Information to Zscaler AI Guard (Optional)
If you need to send end-user information to Zscaler AI Guard for analysis, you can set the configuration in the environment variables to True and include the relevant information in custom_headers on Zscaler AI Guard.
- To send user_api_key_alias:
@@ -133,4 +133,30 @@ curl -i http://localhost:8165/v1/chat/completions \
"zguard_policy_id":
}
}'
+```
+
+## 8. Set Custom Zscaler AI Guard Policy on Litellm Team OR Key Metadata (Optional)
+In addition to setting `zguard_policy_id` in a request or the configuration file, you can also set it in the metadata for LiteLLM Team or Key. The `zguard_policy_id` is determined using the following order of precedence: request, Key, Team, config file. This logic is illustrated below:
+```
+user_api_key_metadata = metadata.get("user_api_key_metadata", {}) or {}
+team_metadata = metadata.get("team_metadata", {}) or {}
+policy_id = (
+ metadata.get("zguard_policy_id")
+ if "zguard_policy_id" in metadata
+ else (
+ user_api_key_metadata.get("zguard_policy_id")
+ if "zguard_policy_id" in user_api_key_metadata
+ else (
+ team_metadata.get("zguard_policy_id")
+ if "zguard_policy_id" in team_metadata
+ else self.policy_id
+ )
+ )
+ )
+```
+You can leverage this feature to apply multiple policies configured on the Zscaler AI Guard (ZGuard) to traffic from different applications. (Note: It is recommended to map policies using either Team or Key metadata, but not a mix of both.)
+
+Example set in Team/Key Metadata, you can set From UI:
+```
+{"zguard_policy_id": 100}
```
\ No newline at end of file
diff --git a/docs/my-website/docs/proxy/keys_teams_router_settings.md b/docs/my-website/docs/proxy/keys_teams_router_settings.md
new file mode 100644
index 00000000000..ec59e8f271b
--- /dev/null
+++ b/docs/my-website/docs/proxy/keys_teams_router_settings.md
@@ -0,0 +1,150 @@
+import Image from '@theme/IdealImage';
+
+# UI - Router Settings for Keys and Teams
+
+Configure router settings at the key and team level to achieve granular control over routing behavior, fallbacks, retries, and other router configurations. This enables you to customize routing behavior for specific keys or teams without affecting global settings.
+
+## Overview
+
+Router Settings for Keys and Teams allows you to configure router behavior at different levels of granularity. Previously, router settings could only be configured globally, applying the same routing strategy, fallbacks, timeouts, and retry policies to all requests across your entire proxy instance.
+
+With key-level and team-level router settings, you can now:
+
+- **Customize routing strategies** per key or team (e.g., use `least-busy` for high-priority keys, `latency-based-routing` for others)
+- **Configure different fallback chains** for different keys or teams
+- **Set key-specific or team-specific timeouts** and retry policies
+- **Apply different reliability settings** (cooldowns, allowed failures) per key or team
+- **Override global settings** when needed for specific use cases
+
+
+
+## Summary
+
+Router settings follow a **hierarchical resolution order**: **Keys > Teams > Global**. When a request is made:
+
+1. **Key-level settings** are checked first. If router settings are configured for the API key being used, those settings are applied.
+2. **Team-level settings** are checked next. If the key belongs to a team and that team has router settings configured, those settings are used (unless key-level settings exist).
+3. **Global settings** are used as the final fallback. If neither key nor team settings are found, the global router settings from your proxy configuration are applied.
+
+This hierarchical approach ensures that the most specific settings take precedence, allowing you to fine-tune routing behavior for individual keys or teams while maintaining sensible defaults at the global level.
+
+## How Router Settings Resolution Works
+
+Router settings are resolved in the following priority order:
+
+### Resolution Order: Key > Team > Global
+
+1. **Key-level router settings** (highest priority)
+ - Applied when router settings are configured directly on an API key
+ - Takes precedence over all other settings
+ - Useful for individual key customization
+
+2. **Team-level router settings** (medium priority)
+ - Applied when the API key belongs to a team with router settings configured
+ - Only used if no key-level settings exist
+ - Useful for applying consistent settings across multiple keys in a team
+
+3. **Global router settings** (lowest priority)
+ - Applied from your proxy configuration file or database
+ - Used as the default when no key or team settings are found
+ - Previously, this was the only option available
+
+## How to Configure Router Settings
+
+### Configuring Router Settings for Keys
+
+Follow these steps to configure router settings for an API key:
+
+1. Navigate to [http://localhost:4000/ui/?login=success](http://localhost:4000/ui/?login=success)
+
+
+
+2. Click "+ Create New Key" (or edit an existing key)
+
+
+
+3. Click "Optional Settings"
+
+
+
+4. Click "Router Settings"
+
+
+
+5. Configure your desired router settings. For example, click "Fallbacks" to configure fallback models:
+
+
+
+6. Click "Select a model to begin configuring fallbacks" and configure your fallback chain:
+
+
+
+### Configuring Router Settings for Teams
+
+Follow these steps to configure router settings for a team:
+
+1. Navigate to [http://localhost:4000/ui/?login=success](http://localhost:4000/ui/?login=success)
+
+
+
+2. Click "Teams"
+
+
+
+3. Click "+ Create New Team" (or edit an existing team)
+
+
+
+4. Click "Router Settings"
+
+
+
+5. Configure your desired router settings. For example, click "Fallbacks" to configure fallback models:
+
+
+
+6. Click "Select a model to begin configuring fallbacks" and configure your fallback chain:
+
+
+
+## Use Cases
+
+### Different Routing Strategies per Key
+
+Configure different routing strategies for different use cases:
+
+- **High-priority production keys**: Use `latency-based-routing` for optimal performance
+- **Development keys**: Use `simple-shuffle` for simplicity
+- **Cost-sensitive keys**: Use `cost-based-routing` to minimize expenses
+
+### Team-Level Consistency
+
+Apply consistent router settings across all keys in a team:
+
+- Set team-wide fallback chains for reliability
+- Configure team-specific timeout policies
+- Apply uniform retry policies across team members
+
+### Override Global Settings
+
+Override global settings for specific scenarios:
+
+- Production keys may need stricter timeout policies than development
+- Certain teams may require different fallback models
+- Individual keys may need custom retry policies for specific use cases
+
+### Gradual Rollout
+
+Test new router settings on specific keys or teams before applying globally:
+
+- Configure new routing strategies on a test key first
+- Validate fallback chains on a small team before global rollout
+- A/B test different timeout values across different keys
+
+## Related Features
+
+- [Router Settings Reference](./config_settings.md#router_settings---reference) - Complete reference of all router settings
+- [Load Balancing](./load_balancing.md) - Learn about routing strategies and load balancing
+- [Reliability](./reliability.md) - Configure fallbacks, retries, and error handling
+- [Keys](./keys.md) - Manage API keys and their settings
+- [Teams](./teams.md) - Organize keys into teams
diff --git a/docs/my-website/docs/proxy/litellm_managed_files.md b/docs/my-website/docs/proxy/litellm_managed_files.md
index 7aba173f35b..6272180bd40 100644
--- a/docs/my-website/docs/proxy/litellm_managed_files.md
+++ b/docs/my-website/docs/proxy/litellm_managed_files.md
@@ -11,7 +11,7 @@ import Image from '@theme/IdealImage';
This is a free LiteLLM Enterprise feature.
-Available via the `litellm[proxy]` package or any `litellm` docker image.
+Available via the `litellm` docker image. If you are using the pip package, you must install [`litellm-enterprise`](https://pypi.org/project/litellm-enterprise/).
:::
diff --git a/docs/my-website/docs/proxy/load_balancing.md b/docs/my-website/docs/proxy/load_balancing.md
index 42f6ef1aa51..186307d6498 100644
--- a/docs/my-website/docs/proxy/load_balancing.md
+++ b/docs/my-website/docs/proxy/load_balancing.md
@@ -69,6 +69,67 @@ router_settings:
redis_port: 1992
```
+## Enforce Model Rate Limits
+
+Strictly enforce RPM/TPM limits set on deployments. When limits are exceeded, requests are blocked **before** reaching the LLM provider with a `429 Too Many Requests` error.
+
+:::info
+By default, `rpm` and `tpm` values are only used for **routing decisions** (picking deployments with capacity). With `enforce_model_rate_limits`, they become **hard limits**.
+:::
+
+### Quick Start
+
+```yaml
+model_list:
+ - model_name: gpt-4
+ litellm_params:
+ model: openai/gpt-4
+ api_key: os.environ/OPENAI_API_KEY
+ rpm: 60 # 60 requests per minute
+ tpm: 90000 # 90k tokens per minute
+
+router_settings:
+ optional_pre_call_checks:
+ - enforce_model_rate_limits # 👈 Enables strict enforcement
+```
+
+### How It Works
+
+| Limit Type | Enforcement | Accuracy |
+|------------|-------------|----------|
+| **RPM** | Hard limit - blocked at exact threshold | 100% accurate |
+| **TPM** | Best-effort - may slightly exceed | Blocked when already over limit |
+
+**Why TPM is best-effort:** Token count is unknown until the LLM responds. TPM is checked before each request (blocks if already over), and tracked after (adds actual tokens used).
+
+### Error Response
+
+```json
+{
+ "error": {
+ "message": "Model rate limit exceeded. RPM limit=60, current usage=60",
+ "type": "rate_limit_error",
+ "code": 429
+ }
+}
+```
+
+Response includes `retry-after: 60` header.
+
+### Multi-Instance Deployment
+
+For multiple LiteLLM proxy instances, add Redis to share rate limit state:
+
+```yaml
+router_settings:
+ optional_pre_call_checks:
+ - enforce_model_rate_limits
+ redis_host: redis.example.com
+ redis_port: 6379
+ redis_password: your-password
+```
+
+
:::info
Detailed information about [routing strategies can be found here](../routing)
:::
diff --git a/docs/my-website/docs/proxy/logging.md b/docs/my-website/docs/proxy/logging.md
index 56fb420e6cf..1abb127dfda 100644
--- a/docs/my-website/docs/proxy/logging.md
+++ b/docs/my-website/docs/proxy/logging.md
@@ -1338,6 +1338,7 @@ litellm_settings:
s3_aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY # AWS Secret Access Key for S3
s3_path: my-test-path # [OPTIONAL] set path in bucket you want to write logs to
s3_endpoint_url: https://s3.amazonaws.com # [OPTIONAL] S3 endpoint URL, if you want to use Backblaze/cloudflare s3 buckets
+ s3_use_virtual_hosted_style: false # [OPTIONAL] use virtual-hosted-style URLs (bucket.endpoint/key) instead of path-style (endpoint/bucket/key). Useful for S3-compatible services like MinIO
s3_strip_base64_files: false # [OPTIONAL] remove base64 files before storing in s3
```
diff --git a/docs/my-website/docs/proxy/prod.md b/docs/my-website/docs/proxy/prod.md
index a42d91a7d5f..994788a3ad9 100644
--- a/docs/my-website/docs/proxy/prod.md
+++ b/docs/my-website/docs/proxy/prod.md
@@ -250,11 +250,133 @@ The migrate deploy command:
### Read-only File System
-If you see a `Permission denied` error, it means the LiteLLM pod is running with a read-only file system.
+Running LiteLLM with `readOnlyRootFilesystem: true` is a Kubernetes security best practice that prevents container processes from writing to the root filesystem. LiteLLM fully supports this configuration.
-To fix this, just set `LITELLM_MIGRATION_DIR="/path/to/writeable/directory"` in your environment.
+#### Quick Fix for Permission Errors
-LiteLLM will use this directory to write migration files.
+If you see a `Permission denied` error, it means the LiteLLM pod is running with a read-only file system. LiteLLM needs writable directories for:
+- **Database migrations**: Set `LITELLM_MIGRATION_DIR="/path/to/writable/directory"`
+- **Admin UI**: Set `LITELLM_UI_PATH="/path/to/writable/directory"`
+- **UI assets/logos**: Set `LITELLM_ASSETS_PATH="/path/to/writable/directory"`
+
+#### Complete Read-Only Filesystem Setup (Kubernetes)
+
+For production deployments with enhanced security, use this configuration:
+
+**Option 1: Using EmptyDir Volumes with InitContainer (Recommended)**
+
+This approach copies the pre-built UI from the Docker image to writable emptyDir volumes at pod startup.
+
+```yaml
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: litellm-proxy
+spec:
+ template:
+ spec:
+ initContainers:
+ - name: setup-ui
+ image: ghcr.io/berriai/litellm:main-stable
+ command:
+ - sh
+ - -c
+ - |
+ cp -r /var/lib/litellm/ui/* /app/var/litellm/ui/ && \
+ cp -r /var/lib/litellm/assets/* /app/var/litellm/assets/
+ volumeMounts:
+ - name: ui-volume
+ mountPath: /app/var/litellm/ui
+ - name: assets-volume
+ mountPath: /app/var/litellm/assets
+
+ containers:
+ - name: litellm
+ image: ghcr.io/berriai/litellm:main-stable
+ env:
+ - name: LITELLM_NON_ROOT
+ value: "true"
+ - name: LITELLM_UI_PATH
+ value: "/app/var/litellm/ui"
+ - name: LITELLM_ASSETS_PATH
+ value: "/app/var/litellm/assets"
+ - name: LITELLM_MIGRATION_DIR
+ value: "/app/migrations"
+ - name: PRISMA_BINARY_CACHE_DIR
+ value: "/app/cache/prisma-python/binaries"
+ - name: XDG_CACHE_HOME
+ value: "/app/cache"
+ securityContext:
+ readOnlyRootFilesystem: true
+ runAsNonRoot: true
+ runAsUser: 101
+ capabilities:
+ drop:
+ - ALL
+ volumeMounts:
+ - name: config
+ mountPath: /app/config.yaml
+ subPath: config.yaml
+ readOnly: true
+ - name: ui-volume
+ mountPath: /app/var/litellm/ui
+ - name: assets-volume
+ mountPath: /app/var/litellm/assets
+ - name: cache
+ mountPath: /app/cache
+ - name: migrations
+ mountPath: /app/migrations
+
+ volumes:
+ - name: config
+ configMap:
+ name: litellm-config
+ - name: ui-volume
+ emptyDir:
+ sizeLimit: 100Mi
+ - name: assets-volume
+ emptyDir:
+ sizeLimit: 10Mi
+ - name: cache
+ emptyDir:
+ sizeLimit: 500Mi
+ - name: migrations
+ emptyDir:
+ sizeLimit: 64Mi
+```
+
+**Option 2: Without UI (API-only deployment)**
+
+If you don't need the admin UI, you can run with minimal configuration:
+
+```yaml
+env:
+ - name: LITELLM_NON_ROOT
+ value: "true"
+ - name: LITELLM_MIGRATION_DIR
+ value: "/app/migrations"
+securityContext:
+ readOnlyRootFilesystem: true
+```
+
+The proxy will log a warning about the UI but API endpoints will work normally.
+
+#### Environment Variables for Read-Only Filesystems
+
+| Variable | Purpose | Default |
+|----------|---------|---------|
+| `LITELLM_UI_PATH` | Admin UI directory | `/var/lib/litellm/ui` (Docker) |
+| `LITELLM_ASSETS_PATH` | UI assets/logos | `/var/lib/litellm/assets` (Docker) |
+| `LITELLM_MIGRATION_DIR` | Database migrations | Package directory |
+| `PRISMA_BINARY_CACHE_DIR` | Prisma binary cache | System default |
+| `XDG_CACHE_HOME` | General cache directory | System default |
+
+#### Important Notes
+
+1. **Migrations**: Always set `LITELLM_MIGRATION_DIR` to a writable emptyDir path
+2. **Prisma Cache**: Set `PRISMA_BINARY_CACHE_DIR` and `XDG_CACHE_HOME` to writable paths
+3. **Server Root Path**: If using a custom `server_root_path`, you must pre-process UI files in your Dockerfile as the proxy cannot modify files at runtime with read-only filesystem
+4. **Automatic Detection**: The UI is automatically detected as pre-restructured if it contains a `.litellm_ui_ready` marker file (created by the official Docker images)
## 10. Use a Separate Health Check App
:::info
diff --git a/docs/my-website/docs/proxy/prometheus.md b/docs/my-website/docs/proxy/prometheus.md
index cd2b3b68f37..93a0675f097 100644
--- a/docs/my-website/docs/proxy/prometheus.md
+++ b/docs/my-website/docs/proxy/prometheus.md
@@ -121,8 +121,8 @@ Use this to track overall LiteLLM Proxy usage.
| Metric Name | Description |
|----------------------|--------------------------------------|
-| `litellm_proxy_failed_requests_metric` | Total number of failed responses from proxy - the client did not get a success response from litellm proxy. Labels: `"end_user", "hashed_api_key", "api_key_alias", "requested_model", "team", "team_alias", "user", "exception_status", "exception_class", "route"` |
-| `litellm_proxy_total_requests_metric` | Total number of requests made to the proxy server - track number of client side requests. Labels: `"end_user", "hashed_api_key", "api_key_alias", "requested_model", "team", "team_alias", "user", "status_code", "user_email", "route"` |
+| `litellm_proxy_failed_requests_metric` | Total number of failed responses from proxy - the client did not get a success response from litellm proxy. Labels: `"end_user", "hashed_api_key", "api_key_alias", "requested_model", "team", "team_alias", "user", "user_email", "exception_status", "exception_class", "route", "model_id"` |
+| `litellm_proxy_total_requests_metric` | Total number of requests made to the proxy server - track number of client side requests. Labels: `"end_user", "hashed_api_key", "api_key_alias", "requested_model", "team", "team_alias", "user", "status_code", "user_email", "route", "model_id"` |
### Callback Logging Metrics
@@ -130,7 +130,12 @@ Monitor failures while shipping logs to downstream callbacks like `s3_v3` cold s
| Metric Name | Description |
|----------------------|--------------------------------------|
-| `litellm_callback_logging_failures_metric` | Total number of failed attempts to emit logs to a configured callback. Labels: `"callback_name"`. Use this to alert on callback delivery issues such as repeated failures when writing to `s3_v3`. |
+| `litellm_callback_logging_failures_metric` | Total number of failed attempts to emit logs to a configured callback. Labels: `"callback_name"`. Use this to alert on callback delivery issues such as repeated failures when writing to `s3_v3`, `langfuse`, or `langfuse_otel` and other otel providers |
+
+**Supported Callbacks:**
+- `S3Logger` - S3 v2 cold storage failures
+- `langfuse` - Langfuse logging failures
+- `otel` - OpenTelemetry logging failures
## LLM Provider Metrics
@@ -191,10 +196,10 @@ Use this for LLM API Error monitoring and tracking remaining rate limits and tok
| Metric Name | Description |
|----------------------|--------------------------------------|
-| `litellm_request_total_latency_metric` | Total latency (seconds) for a request to LiteLLM Proxy Server - tracked for labels "end_user", "hashed_api_key", "api_key_alias", "requested_model", "team", "team_alias", "user", "model" |
+| `litellm_request_total_latency_metric` | Total latency (seconds) for a request to LiteLLM Proxy Server - tracked for labels "end_user", "hashed_api_key", "api_key_alias", "requested_model", "team", "team_alias", "user", "model", "model_id" |
| `litellm_overhead_latency_metric` | Latency overhead (seconds) added by LiteLLM processing - tracked for labels "model_group", "api_provider", "api_base", "litellm_model_name", "hashed_api_key", "api_key_alias" |
| `litellm_llm_api_latency_metric` | Latency (seconds) for just the LLM API call - tracked for labels "model", "hashed_api_key", "api_key_alias", "team", "team_alias", "requested_model", "end_user", "user" |
-| `litellm_llm_api_time_to_first_token_metric` | Time to first token for LLM API call - tracked for labels `model`, `hashed_api_key`, `api_key_alias`, `team`, `team_alias` [Note: only emitted for streaming requests] |
+| `litellm_llm_api_time_to_first_token_metric` | Time to first token for LLM API call - tracked for labels `model`, `hashed_api_key`, `api_key_alias`, `team`, `team_alias`, `requested_model`, `end_user`, `user`, `model_id` [Note: only emitted for streaming requests] |
## Tracking `end_user` on Prometheus
diff --git a/docs/my-website/docs/proxy/prompt_management.md b/docs/my-website/docs/proxy/prompt_management.md
index 0c7ff96f538..08307ba99ec 100644
--- a/docs/my-website/docs/proxy/prompt_management.md
+++ b/docs/my-website/docs/proxy/prompt_management.md
@@ -11,6 +11,7 @@ Run experiments or change the specific model (e.g. from gpt-4o to gpt4o-mini fin
| Native LiteLLM GitOps (.prompt files) | [Get Started](native_litellm_prompt) |
| Langfuse | [Get Started](https://langfuse.com/docs/prompts/get-started) |
| Humanloop | [Get Started](../observability/humanloop) |
+| Generic Prompt Management API | [Get Started](../adding_provider/generic_prompt_management_api) |
## Onboarding Prompts via config.yaml
@@ -34,7 +35,7 @@ prompts:
- prompt_id: "my_prompt_id"
litellm_params:
prompt_id: "my_prompt_id"
- prompt_integration: "dotprompt" # or langfuse, bitbucket, gitlab, custom
+ prompt_integration: "dotprompt" # or langfuse, bitbucket, gitlab, generic_prompt_management, custom
# integration-specific parameters below
```
@@ -46,6 +47,7 @@ The `prompt_integration` field determines where and how prompts are loaded:
- **`langfuse`**: Fetch prompts from Langfuse prompt management
- **`bitbucket`**: Load from BitBucket repository `.prompt` files (team-based access control)
- **`gitlab`**: Load from GitLab repository `.prompt` files (team-based access control)
+- **`generic_prompt_management`**: Integrate any prompt management system via a simple API endpoint (no PR required)
- **`custom`**: Use your own custom prompt management implementation
Each integration has its own configuration parameters and access control mechanisms.
@@ -207,6 +209,57 @@ System: You are a helpful assistant.
User: {{user_message}}
```
+
+
+
+
+```yaml
+prompts:
+ - prompt_id: "simple_prompt"
+ litellm_params:
+ prompt_integration: "generic_prompt_management"
+ provider_specific_query_params:
+ project_name: litellm
+ slug: hello-world-prompt-2bac
+ api_base: http://localhost:8080
+ api_key: os.environ/GENERIC_PROMPT_API_KEY
+ ignore_prompt_manager_model: true # optional
+ ignore_prompt_manager_optional_params: true # optional
+```
+
+**What you need to implement:**
+
+A GET endpoint at `/beta/litellm_prompt_management` that returns:
+
+```json
+{
+ "prompt_id": "simple_prompt",
+ "prompt_template": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant."
+ },
+ {
+ "role": "user",
+ "content": "Help me with {task}"
+ }
+ ],
+ "prompt_template_model": "gpt-4",
+ "prompt_template_optional_params": {
+ "temperature": 0.7,
+ "max_tokens": 500
+ }
+}
+```
+
+**Benefits:**
+- No PR required - integrate any prompt management system
+- Full control over your prompt storage and versioning
+- Support for variable substitution with `{variable}` syntax
+- Custom query parameters for filtering and access control
+
+**Learn more:** [Generic Prompt Management API Documentation](../adding_provider/generic_prompt_management_api)
+
diff --git a/docs/my-website/docs/proxy/pyroscope_profiling.md b/docs/my-website/docs/proxy/pyroscope_profiling.md
new file mode 100644
index 00000000000..fa3db3a8782
--- /dev/null
+++ b/docs/my-website/docs/proxy/pyroscope_profiling.md
@@ -0,0 +1,43 @@
+# Grafana Pyroscope CPU profiling
+
+LiteLLM proxy can send continuous CPU profiles to [Grafana Pyroscope](https://grafana.com/docs/pyroscope/latest/) when enabled via environment variables. This is optional and off by default.
+
+## Quick start
+
+1. **Install the optional dependency** (required only when enabling Pyroscope):
+
+ ```bash
+ pip install pyroscope-io
+ ```
+
+ Or install the proxy extra:
+
+ ```bash
+ pip install "litellm[proxy]"
+ ```
+
+2. **Set environment variables** before starting the proxy:
+
+ | Variable | Required | Description |
+ |----------|----------|-------------|
+ | `LITELLM_ENABLE_PYROSCOPE` | Yes (to enable) | Set to `true` to enable Pyroscope profiling. |
+ | `PYROSCOPE_APP_NAME` | Yes (when enabled) | Application name shown in the Pyroscope UI. |
+ | `PYROSCOPE_SERVER_ADDRESS` | Yes (when enabled) | Pyroscope server URL (e.g. `http://localhost:4040`). |
+ | `PYROSCOPE_SAMPLE_RATE` | No | Sample rate (integer). If unset, the pyroscope-io library default is used. |
+
+3. **Start the proxy**; profiling will begin automatically when the proxy starts.
+
+ ```bash
+ export LITELLM_ENABLE_PYROSCOPE=true
+ export PYROSCOPE_APP_NAME=litellm-proxy
+ export PYROSCOPE_SERVER_ADDRESS=http://localhost:4040
+ litellm --config config.yaml
+ ```
+
+4. **View profiles** in the Pyroscope (or Grafana) UI and select your `PYROSCOPE_APP_NAME`.
+
+## Notes
+
+- **Optional dependency**: `pyroscope-io` is an optional dependency. If it is not installed and `LITELLM_ENABLE_PYROSCOPE=true`, the proxy will log a warning and continue without profiling.
+- **Platform support**: The `pyroscope-io` package uses a native extension and is not available on all platforms (e.g. Windows is excluded by the package).
+- **Other settings**: See [Configuration settings](/proxy/config_settings) for all proxy environment variables.
diff --git a/docs/my-website/docs/proxy/release_cycle.md b/docs/my-website/docs/proxy/release_cycle.md
index 10dd6d8b3c5..b3e056b0243 100644
--- a/docs/my-website/docs/proxy/release_cycle.md
+++ b/docs/my-website/docs/proxy/release_cycle.md
@@ -22,4 +22,10 @@ Stable releases come out every week (typically Sunday)
- 'patch' bumps: extremely minor addition that doesn't affect any existing functionality or add any user-facing features. (e.g. a 'created_at' column in a database table)
- 'minor' bumps: add a new feature or a new database table that is backward compatible.
-- 'major' bumps: break backward compatibility.
\ No newline at end of file
+- 'major' bumps: break backward compatibility.
+
+### Enterprise Support
+
+
+- Stable releases come out every week. Once a new one is available, we no longer provide support for an older one.
+- If there is a MAJOR change (according to semvar conventions - e.g. 1.x.x -> 2.x.x), we can provide support for upto 90 days on the prior stable image.
diff --git a/docs/my-website/docs/proxy/request_tags.md b/docs/my-website/docs/proxy/request_tags.md
new file mode 100644
index 00000000000..c78c48229b4
--- /dev/null
+++ b/docs/my-website/docs/proxy/request_tags.md
@@ -0,0 +1,58 @@
+# Request Tags for Spend Tracking
+
+Add tags to model deployments to track spend by environment, AWS account, or any custom label.
+
+Tags appear in the `request_tags` field of LiteLLM spend logs.
+
+## Config Setup
+
+Set tags on model deployments in `config.yaml`:
+
+```yaml title="config.yaml"
+model_list:
+ - model_name: gpt-4
+ litellm_params:
+ model: azure/gpt-4-prod
+ api_key: os.environ/AZURE_PROD_API_KEY
+ api_base: https://prod.openai.azure.com/
+ tags: ["AWS_IAM_PROD"] # 👈 Tag for production
+
+ - model_name: gpt-4-dev
+ litellm_params:
+ model: azure/gpt-4-dev
+ api_key: os.environ/AZURE_DEV_API_KEY
+ api_base: https://dev.openai.azure.com/
+ tags: ["AWS_IAM_DEV"] # 👈 Tag for development
+```
+
+## Make Request
+
+Requests just specify the model - tags are automatically applied:
+
+```bash
+curl -X POST 'http://0.0.0.0:4000/chat/completions' \
+ -H 'Authorization: Bearer sk-1234' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "Hello"}]
+ }'
+```
+
+## Spend Logs
+
+The tag from the model config appears in `LiteLLM_SpendLogs`:
+
+```json
+{
+ "request_id": "chatcmpl-abc123",
+ "request_tags": ["AWS_IAM_PROD"],
+ "spend": 0.002,
+ "model": "gpt-4"
+}
+```
+
+## Related
+
+- [Spend Tracking Overview](cost_tracking.md)
+- [Tag Budgets](tag_budgets.md) - Set budget limits per tag
diff --git a/docs/my-website/docs/proxy/sync_anthropic_beta_headers.md b/docs/my-website/docs/proxy/sync_anthropic_beta_headers.md
new file mode 100644
index 00000000000..e1645082d97
--- /dev/null
+++ b/docs/my-website/docs/proxy/sync_anthropic_beta_headers.md
@@ -0,0 +1,128 @@
+# Auto Sync Anthropic Beta Headers
+
+Automatically keep your Anthropic beta headers configuration up to date without restarting your service. **This allows you to support new Anthropic beta features across all providers without restarting your service.**
+
+## Overview
+
+When Anthropic releases new beta features (e.g., new tool capabilities, extended context windows), you typically need to restart your LiteLLM service to get the latest beta header mappings for different providers (Anthropic, Bedrock, Vertex AI, Azure AI).
+
+With auto-sync, LiteLLM automatically pulls the latest configuration from GitHub's [`anthropic_beta_headers_config.json`](https://github.com/BerriAI/litellm/blob/main/litellm/anthropic_beta_headers_config.json) without requiring a restart. This means:
+
+- **Zero downtime** when new beta features are released
+- **Always up-to-date** provider support mappings
+- **Automatic updates** - set it once and forget it
+
+## Quick Start
+
+**Manual sync:**
+```bash
+curl -X POST "https://your-proxy-url/reload/anthropic_beta_headers" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
+ -H "Content-Type: application/json"
+```
+
+**Automatic sync every 24 hours:**
+```bash
+curl -X POST "https://your-proxy-url/schedule/anthropic_beta_headers_reload?hours=24" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
+ -H "Content-Type: application/json"
+```
+
+## API Endpoints
+
+| Endpoint | Method | Description |
+|----------|--------|-------------|
+| `/reload/anthropic_beta_headers` | POST | Manual sync |
+| `/schedule/anthropic_beta_headers_reload?hours={hours}` | POST | Schedule periodic sync |
+| `/schedule/anthropic_beta_headers_reload` | DELETE | Cancel scheduled sync |
+| `/schedule/anthropic_beta_headers_reload/status` | GET | Check sync status |
+
+**Authentication:** Requires admin role or master key
+
+## Python Example
+
+```python
+import requests
+
+def sync_anthropic_beta_headers(proxy_url, admin_token):
+ response = requests.post(
+ f"{proxy_url}/reload/anthropic_beta_headers",
+ headers={"Authorization": f"Bearer {admin_token}"}
+ )
+ return response.json()
+
+# Usage
+result = sync_anthropic_beta_headers("https://your-proxy-url", "your-admin-token")
+print(result['message'])
+```
+
+## Configuration
+
+**Custom beta headers config URL:**
+```bash
+export LITELLM_ANTHROPIC_BETA_HEADERS_URL="https://raw.githubusercontent.com/BerriAI/litellm/main/litellm/anthropic_beta_headers_config.json"
+```
+
+**Use local beta headers config:**
+```bash
+export LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS=True
+```
+
+## Scheduling Automatic Reloads
+
+Schedule automatic reloads to ensure your proxy always has the latest beta header mappings:
+
+```bash
+# Reload every 24 hours
+curl -X POST "https://your-proxy-url/schedule/anthropic_beta_headers_reload?hours=24" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+```
+
+**Check reload status:**
+```bash
+curl -X GET "https://your-proxy-url/schedule/anthropic_beta_headers_reload/status" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+```
+
+**Response:**
+```json
+{
+ "scheduled": true,
+ "interval_hours": 24,
+ "last_run": "2026-02-13T10:00:00",
+ "next_run": "2026-02-14T10:00:00"
+}
+```
+
+**Cancel scheduled reload:**
+```bash
+curl -X DELETE "https://your-proxy-url/schedule/anthropic_beta_headers_reload" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+```
+
+## Environment Variables
+
+| Variable | Description | Default |
+|----------|-------------|---------|
+| `LITELLM_ANTHROPIC_BETA_HEADERS_URL` | URL to fetch beta headers config from | GitHub main branch |
+| `LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS` | Set to `True` to use local config only | `False` |
+
+## How It Works
+
+1. **Initial Load:** On startup, LiteLLM loads the beta headers configuration from the remote URL (or local file if configured)
+2. **Caching:** The configuration is cached in memory to avoid repeated fetches on every request
+3. **Scheduled Reload:** If configured, the proxy checks every 10 seconds whether it's time to reload based on your schedule
+4. **Manual Reload:** You can trigger an immediate reload via the API endpoint
+5. **Multi-Pod Support:** In multi-pod deployments, the reload configuration is stored in the database so all pods stay in sync
+
+## Benefits
+
+- **No Restarts Required:** Add support for new Anthropic beta features without downtime
+- **Provider Compatibility:** Automatically get updated mappings for Bedrock, Vertex AI, Azure AI, etc.
+- **Performance:** Configuration is cached and only reloaded when needed
+- **Reliability:** Falls back to local configuration if remote fetch fails
+
+## Related
+
+- [Model Cost Map Sync](./sync_models_github.md) - Auto-sync model pricing data
+- [Anthropic Beta Headers](../completion/anthropic.md#beta-features) - Using Anthropic beta features
diff --git a/docs/my-website/docs/proxy/team_budgets.md b/docs/my-website/docs/proxy/team_budgets.md
index 03d18797133..01b07f23a33 100644
--- a/docs/my-website/docs/proxy/team_budgets.md
+++ b/docs/my-website/docs/proxy/team_budgets.md
@@ -8,7 +8,6 @@ import TabItem from '@theme/TabItem';
# Pre-Requisites
- You must set up a Postgres database (e.g. Supabase, Neon, etc.)
-- To enable team member rate limits, set the environment variable `EXPERIMENTAL_MULTI_INSTANCE_RATE_LIMITING=true` **before starting the proxy server**. Without this, team member rate limits will not be enforced.
## Default Budget for Auto-Generated JWT Teams
diff --git a/docs/my-website/docs/proxy/ui/page_visibility.md b/docs/my-website/docs/proxy/ui/page_visibility.md
new file mode 100644
index 00000000000..06b06f33219
--- /dev/null
+++ b/docs/my-website/docs/proxy/ui/page_visibility.md
@@ -0,0 +1,121 @@
+import Image from '@theme/IdealImage';
+
+# Control Page Visibility for Internal Users
+
+Configure which navigation tabs and pages are visible to internal users (non-admin developers) in the LiteLLM UI.
+
+Use this feature to simplify the UI and control which pages your internal users/developers can see when signing in.
+
+## Overview
+
+By default, all pages accessible to internal users are visible in the navigation sidebar. The page visibility control allows admins to restrict which pages internal users can see, creating a more focused and streamlined experience.
+
+
+## Configure Page Visibility
+
+### 1. Navigate to Settings
+
+Click the **Settings** icon in the sidebar.
+
+
+
+### 2. Go to Admin Settings
+
+Click **Admin Settings** from the settings menu.
+
+
+
+### 3. Select UI Settings
+
+Click **UI Settings** to access the page visibility controls.
+
+
+
+### 4. Open Page Visibility Configuration
+
+Click **Configure Page Visibility** to expand the configuration panel.
+
+
+
+### 5. Select Pages to Make Visible
+
+Check the boxes for the pages you want internal users to see. Pages are organized by category for easy navigation.
+
+
+
+**Available pages include:**
+- Virtual Keys
+- Playground
+- Models + Endpoints
+- Agents
+- MCP Servers
+- Search Tools
+- Vector Stores
+- Logs
+- Teams
+- Organizations
+- Usage
+- Budgets
+- And more...
+
+### 6. Save Your Configuration
+
+Click **Save Page Visibility Settings** to apply the changes.
+
+
+
+### 7. Verify Changes
+
+Internal users will now only see the selected pages in their navigation sidebar.
+
+
+
+## Reset to Default
+
+To restore all pages to internal users:
+
+1. Open the Page Visibility configuration
+2. Click **Reset to Default (All Pages)**
+3. Click **Save Page Visibility Settings**
+
+This will clear the restriction and show all accessible pages to internal users.
+
+## API Configuration
+
+You can also configure page visibility programmatically using the API:
+
+### Get Current Settings
+
+```bash
+curl -X GET 'http://localhost:4000/ui_settings/get' \
+ -H 'Authorization: Bearer '
+```
+
+### Update Page Visibility
+
+```bash
+curl -X PATCH 'http://localhost:4000/ui_settings/update' \
+ -H 'Authorization: Bearer ' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "enabled_ui_pages_internal_users": [
+ "api-keys",
+ "agents",
+ "mcp-servers",
+ "logs",
+ "teams"
+ ]
+ }'
+```
+
+### Clear Page Visibility Restrictions
+
+```bash
+curl -X PATCH 'http://localhost:4000/ui_settings/update' \
+ -H 'Authorization: Bearer ' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "enabled_ui_pages_internal_users": null
+ }'
+```
+
diff --git a/docs/my-website/docs/proxy/ui_logs.md b/docs/my-website/docs/proxy/ui_logs.md
index 61f328011c3..8cfe818ebfd 100644
--- a/docs/my-website/docs/proxy/ui_logs.md
+++ b/docs/my-website/docs/proxy/ui_logs.md
@@ -25,7 +25,10 @@ View Spend, Token Usage, Key, Team Name for Each Request to LiteLLM
## Tracking - Request / Response Content in Logs Page
-If you want to view request and response content on LiteLLM Logs, you need to opt in with this setting
+If you want to view request and response content on LiteLLM Logs, you can enable it in either place:
+
+- **From the UI (no restart):** Use [UI Spend Log Settings](./ui_spend_log_settings.md) — open Logs → Settings → enable "Store Prompts in Spend Logs" → Save. Takes effect immediately and overrides config.
+- **From config:** Add this to your `proxy_config.yaml` (requires restart):
```yaml
general_settings:
@@ -34,6 +37,40 @@ general_settings:
+## Tracing Tools
+
+View which tools were provided and called in your completion requests.
+
+
+
+**Example:** Make a completion request with tools:
+
+```bash
+curl -X POST 'http://localhost:4000/chat/completions' \
+ -H 'Authorization: Bearer sk-1234' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "What is the weather?"}],
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get the current weather",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "location": {"type": "string"}
+ }
+ }
+ }
+ }
+ ]
+ }'
+```
+
+Check the Logs page to see all tools provided and which ones were called.
## Stop storing Error Logs in DB
@@ -57,7 +94,10 @@ general_settings:
If you're storing spend logs, it might be a good idea to delete them regularly to keep the database fast.
-LiteLLM lets you configure this in your `proxy_config.yaml`:
+You can set the retention period in either place:
+
+- **From the UI (no restart):** [UI Spend Log Settings](./ui_spend_log_settings.md) — Logs → Settings → set Retention Period → Save.
+- **From config:** Add the following to your `proxy_config.yaml` (requires restart):
```yaml
general_settings:
diff --git a/docs/my-website/docs/proxy/ui_spend_log_settings.md b/docs/my-website/docs/proxy/ui_spend_log_settings.md
new file mode 100644
index 00000000000..5e04974e3a7
--- /dev/null
+++ b/docs/my-website/docs/proxy/ui_spend_log_settings.md
@@ -0,0 +1,92 @@
+import Image from '@theme/IdealImage';
+
+# UI Spend Log Settings
+
+Configure spend log behavior directly from the Admin UI—no config file edits or proxy restart required. This is especially useful for cloud deployments where updating the config is difficult or requires a long release process.
+
+## Overview
+
+Previously, spend log options (such as storing request/response content and retention period) had to be set in `proxy_config.yaml` under `general_settings`. Changing them required editing the config and restarting the proxy, which was a pain point for users-especially in cloud environments—who don't have easy access to the config or whose deployment process makes config updates slow.
+
+
+
+**UI Spend Log Settings** lets you:
+
+- **Store prompts in spend logs** – Enable or disable storing request and response content in the spend logs table (only affects logs created after you change the setting)
+- **Set retention period** – Configure how long spend logs are kept before automatic cleanup (e.g. `7d`, `30d`)
+- **Apply changes immediately** – No proxy restart needed; settings take effect for new requests as soon as you save
+
+:::warning UI overrides config
+Settings changed in the UI **override** the values in your config file. For example, if `store_prompts_in_spend_logs` is explicitly set to `false` in `general_settings`, turning it on in the UI will still enable storing prompts. Use the UI when you want runtime control without redeploying.
+:::
+
+## Settings You Can Configure
+
+| Setting | Description |
+| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Store Prompts in Spend Logs** | When enabled, request messages and response content are stored for **new** spend logs so you can view them in the Logs UI. Logs created before you enabled this will not have request/response content. When disabled, only metadata (e.g. tokens, cost, model) is stored for new logs. |
+| **Retention Period** | Maximum time to keep spend logs before they are automatically deleted (e.g. `7d`, `30d`). Optional; if not set, logs are retained according to your config or default behavior. |
+
+The same options can be set in config via [general_settings](./config_settings.md#general_settings---reference) (`store_prompts_in_spend_logs`, `maximum_spend_logs_retention_period`). Values set in the UI take precedence.
+
+## How to Configure Spend Log Settings in the UI
+
+### 1. Open the Logs page
+
+Navigate to the Admin UI (e.g. `http://localhost:4000/ui` or your `PROXY_BASE_URL/ui`) and click **Logs**.
+
+
+
+
+
+### 2. Open Logs settings
+
+Click the **Settings** (gear) icon on the Logs page to open the spend log settings panel.
+
+
+
+### 3. Enable Store Prompts in Spend Logs (optional)
+
+Turn on **Store Prompts in Spend Logs** if you want request and response content to be stored for new requests and visible when you open those log entries. This only affects logs created after you enable it; existing logs will not gain request/response content. Leave it off if you only need metadata (tokens, cost, model, etc.).
+
+
+
+### 4. Set the retention period (optional)
+
+Optionally set the **Retention Period** (e.g. `7d`, `30d`) to control how long spend logs are kept before automatic cleanup. Uses the same format as the config option `maximum_spend_logs_retention_period`.
+
+
+
+### 5. Save settings
+
+Click **Save Settings**. Changes take effect immediately for new requests; no proxy restart is required. Existing logs are not updated.
+
+
+
+### 6. Verify: view request and response in a log
+
+After enabling **Store Prompts in Spend Logs**, make a new request through the proxy, then open that log entry (or any other log created after you enabled the setting). The log details view will include the request and response content. Logs that existed before you turned the setting on will not have this content.
+
+
+
+
+
+## Use Cases
+
+### Cloud and managed deployments
+
+When the proxy runs in a managed or cloud environment, config may be in a separate repo, require a long release, or be controlled by another team. Using the UI lets you change spend log behavior (e.g. enable prompt storage for debugging or set retention) without going through that process.
+
+### Quick toggles for debugging
+
+Temporarily enable **Store Prompts in Spend Logs** to inspect request/response content on new requests when debugging, then turn it off again from the UI without editing config or restarting. Only logs created while the setting was on will contain the content.
+
+### Retention without redeploying
+
+Adjust how long spend logs are retained (e.g. shorten to reduce storage or extend for compliance) and have the new retention period and cleanup job take effect immediately.
+
+## Related Documentation
+
+- [Getting Started with UI Logs](./ui_logs.md) – Overview of what gets logged and config-based options
+- [Config Settings](./config_settings.md) – `store_prompts_in_spend_logs`, `disable_spend_logs`, `maximum_spend_logs_retention_period` in `general_settings`
+- [Spend Logs Deletion](./spend_logs_deletion.md) – How retention and cleanup work
diff --git a/docs/my-website/docs/proxy/ui_team_soft_budget_alerts.md b/docs/my-website/docs/proxy/ui_team_soft_budget_alerts.md
new file mode 100644
index 00000000000..17c42e57c9a
--- /dev/null
+++ b/docs/my-website/docs/proxy/ui_team_soft_budget_alerts.md
@@ -0,0 +1,130 @@
+import Image from '@theme/IdealImage';
+
+# Team Soft Budget Alerts
+
+Set a soft budget on a team and get email alerts when spending crosses the threshold — without blocking any requests.
+
+## Overview
+
+A **soft budget** is a spending threshold that triggers email notifications when exceeded, but **does not block requests**. This is different from a hard budget (`max_budget`), which rejects requests once the limit is reached.
+
+
+
+Team soft budget alerts let you:
+
+- **Get notified early** — receive email alerts when a team's spend crosses the soft budget threshold
+- **Keep requests flowing** — unlike hard budgets, soft budgets never block API calls
+- **Target specific recipients** — send alerts to specific email addresses (e.g. team leads, finance), not just the team members
+- **Work without global alerting** — team soft budget alerts are sent via email independently of Slack or other global alerting configuration
+
+:::warning Email integration required
+Team soft budget alerts are sent via email. You must have an active email integration (SendGrid, Resend, or SMTP) configured on your proxy for alerts to be delivered. See [Email Notifications](./email.md) for setup instructions.
+:::
+
+:::info Automatically active
+Team soft budget alerts are **automatically active** once you configure a soft budget and at least one alerting email on a team. No additional proxy configuration or restart is needed — alerts are checked on every request.
+:::
+
+## How It Works
+
+On every API request made with a key belonging to a team, the proxy checks:
+
+1. Does the team have a `soft_budget` set?
+2. Is the team's current `spend` >= the `soft_budget`?
+3. Are there any emails configured in `soft_budget_alerting_emails`?
+
+If all three conditions are met, an email alert is sent to the configured recipients. Alerts are **deduplicated** so the same alert is only sent once within a 24-hour window.
+
+## How to Set Up Team Soft Budget Alerts
+
+### 1. Navigate to the Admin UI
+
+Go to the Admin UI (e.g. `http://localhost:4000/ui` or your `PROXY_BASE_URL/ui`).
+
+
+
+### 2. Go to Teams
+
+Click **Teams** in the sidebar.
+
+
+
+### 3. Select a team
+
+Click on the team you want to configure soft budget alerts for.
+
+
+
+### 4. Open team Settings
+
+Click the **Settings** tab to view the team's configuration.
+
+
+
+### 5. Edit Settings
+
+Click **Edit Settings** to modify the team's budget configuration.
+
+
+
+### 6. Set the Soft Budget
+
+Click the **Soft Budget (USD)** field and enter your desired threshold. For example, enter `0.01` for testing or a higher value like `500` for production.
+
+
+
+### 7. Add alerting emails
+
+Click the **Soft Budget Alerting Emails** field and enter one or more comma-separated email addresses that should receive the alert.
+
+
+
+### 8. Save Changes
+
+Click **Save Changes**. The soft budget alert is now active — no proxy restart required.
+
+
+
+### 9. Verify: email alert received
+
+Once the team's spend crosses the soft budget, an email alert is sent to the configured recipients. Below is an example of the alert email:
+
+
+
+## Settings Reference
+
+| Setting | Description |
+| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Soft Budget (USD)** | The spending threshold that triggers an email alert. Requests are **not** blocked when this limit is exceeded. |
+| **Soft Budget Alerting Emails** | Comma-separated email addresses that receive the alert when the soft budget is crossed. At least one email is required for alerts to be sent. |
+
+:::tip Soft Budget vs. Max Budget
+
+- **Soft Budget**: Advisory threshold — sends email alerts but does **not** block requests.
+- **Max Budget**: Hard limit — blocks requests once the budget is exceeded.
+
+You can set both on the same team to get early warnings (soft) and a hard stop (max).
+:::
+
+## API Configuration
+
+You can also configure team soft budgets via the API when creating or updating a team:
+
+```bash
+curl -X POST 'http://localhost:4000/team/update' \
+ --header 'Authorization: Bearer sk-1234' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "team_id": "your-team-id",
+ "soft_budget": 500.00,
+ "metadata": {
+ "soft_budget_alerting_emails": ["lead@example.com", "finance@example.com"]
+ }
+ }'
+```
+
+## Related Documentation
+
+- [Email Notifications](./email.md) – Configure email integrations (Resend, SMTP) for LiteLLM Proxy
+- [Alerting](./alerting.md) – Set up Slack and other alerting channels
+- [Cost Tracking](./cost_tracking.md) – Track and manage spend across teams, keys, and users
diff --git a/docs/my-website/docs/proxy/users.md b/docs/my-website/docs/proxy/users.md
index a389f0bd443..8517db51a8f 100644
--- a/docs/my-website/docs/proxy/users.md
+++ b/docs/my-website/docs/proxy/users.md
@@ -68,13 +68,6 @@ You can:
**Step-by step tutorial on setting, resetting budgets on Teams here (API or using Admin UI)**
-> **Prerequisite:**
-> To enable team member rate limits, you must set the environment variable `EXPERIMENTAL_MULTI_INSTANCE_RATE_LIMITING=true` before starting the proxy server. Without this, team member rate limits will not be enforced.
-
-👉 [https://docs.litellm.ai/docs/proxy/team_budgets](https://docs.litellm.ai/docs/proxy/team_budgets)
-
-:::
-
#### **Add budgets to teams**
```shell
@@ -822,12 +815,10 @@ Expected Response:
}
```
-### [BETA] Multi-instance rate limiting
+### Multi-instance rate limiting
-Enable multi-instance rate limiting with the env var `EXPERIMENTAL_MULTI_INSTANCE_RATE_LIMITING="True"`
**Important Notes:**
-- Setting `EXPERIMENTAL_MULTI_INSTANCE_RATE_LIMITING="True"` is required for team member rate limits to function, not just for multi-instance scenarios.
- **Rate limits do not apply to proxy admin users.**
- When testing rate limits, use internal user roles (non-admin) to ensure limits are enforced as expected.
diff --git a/docs/my-website/docs/proxy/virtual_keys.md b/docs/my-website/docs/proxy/virtual_keys.md
index 38ff4ede280..c74aa75ff4a 100644
--- a/docs/my-website/docs/proxy/virtual_keys.md
+++ b/docs/my-website/docs/proxy/virtual_keys.md
@@ -549,11 +549,14 @@ curl 'http://localhost:4000/key/sk-1234/regenerate' \
"models": [
"gpt-4",
"gpt-3.5-turbo"
- ]
+ ],
+ "grace_period": "48h"
}'
```
+**Grace period (optional)**: Set `grace_period` (e.g. `"24h"`, `"2d"`, `"1w"`) to keep the old key valid for a transitional period. Both old and new keys work until the grace period elapses, enabling seamless cutover without production downtime. Omitted or empty = immediate revoke. Can also be set via `LITELLM_KEY_ROTATION_GRACE_PERIOD` env var for scheduled rotations.
+
**Read More**
- [Write rotated keys to secrets manager](https://docs.litellm.ai/docs/secret#aws-secret-manager)
@@ -640,11 +643,13 @@ Set these environment variables when starting the proxy:
|----------|-------------|---------|
| `LITELLM_KEY_ROTATION_ENABLED` | Enable the rotation worker | `false` |
| `LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS` | How often to scan for keys to rotate (in seconds) | `86400` (24 hours) |
+| `LITELLM_KEY_ROTATION_GRACE_PERIOD` | Duration to keep old key valid after rotation (e.g. `24h`, `2d`) | `""` (immediate revoke) |
**Example:**
```bash
export LITELLM_KEY_ROTATION_ENABLED=true
export LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS=3600 # Check every hour
+export LITELLM_KEY_ROTATION_GRACE_PERIOD=48h # Keep old key valid for 48h during cutover
litellm --config config.yaml
```
diff --git a/docs/my-website/docs/proxy_auth.md b/docs/my-website/docs/proxy_auth.md
new file mode 100644
index 00000000000..91084b34a37
--- /dev/null
+++ b/docs/my-website/docs/proxy_auth.md
@@ -0,0 +1,333 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# SDK Proxy Authentication (OAuth2/JWT Auto-Refresh)
+
+Automatically obtain and refresh OAuth2/JWT tokens when using the LiteLLM Python SDK with a LiteLLM Proxy that requires JWT authentication.
+
+## Overview
+
+When your LiteLLM Proxy is protected by an OAuth2/OIDC provider (Azure AD, Keycloak, Okta, Auth0, etc.), your SDK clients need valid JWT tokens for every request. Instead of manually managing token lifecycle, `litellm.proxy_auth` handles this automatically:
+
+- Obtains tokens from your identity provider
+- Caches tokens to avoid unnecessary requests
+- Refreshes tokens before they expire (60-second buffer)
+- Injects `Authorization: Bearer ` headers into every request
+
+## Quick Start
+
+### Azure AD
+
+
+
+
+Uses the [DefaultAzureCredential](https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.defaultazurecredential) chain (environment variables, managed identity, Azure CLI, etc.):
+
+```python
+import litellm
+from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
+
+# One-time setup
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=AzureADCredential(), # uses DefaultAzureCredential
+ scope="api://my-litellm-proxy/.default"
+)
+litellm.api_base = "https://my-proxy.example.com"
+
+# All requests now include Authorization headers automatically
+response = litellm.completion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "Hello!"}]
+)
+```
+
+
+
+
+Use a specific Azure AD app registration:
+
+```python
+import litellm
+from azure.identity import ClientSecretCredential
+from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
+
+azure_cred = ClientSecretCredential(
+ tenant_id="your-tenant-id",
+ client_id="your-client-id",
+ client_secret="your-client-secret"
+)
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=AzureADCredential(credential=azure_cred),
+ scope="api://my-litellm-proxy/.default"
+)
+litellm.api_base = "https://my-proxy.example.com"
+
+response = litellm.completion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "Hello!"}]
+)
+```
+
+
+
+
+**Required package:** `pip install azure-identity`
+
+### Generic OAuth2 (Okta, Auth0, Keycloak, etc.)
+
+Works with any OAuth2 provider that supports the `client_credentials` grant type:
+
+```python
+import litellm
+from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=GenericOAuth2Credential(
+ client_id="your-client-id",
+ client_secret="your-client-secret",
+ token_url="https://your-idp.example.com/oauth2/token"
+ ),
+ scope="litellm_proxy_api"
+)
+litellm.api_base = "https://my-proxy.example.com"
+
+response = litellm.completion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "Hello!"}]
+)
+```
+
+### Custom Credential Provider
+
+Implement the `TokenCredential` protocol to use any authentication mechanism:
+
+```python
+import time
+import litellm
+from litellm.proxy_auth import AccessToken, ProxyAuthHandler
+
+class MyCustomCredential:
+ """Any class with a get_token(scope) -> AccessToken method works."""
+
+ def get_token(self, scope: str) -> AccessToken:
+ # Your custom logic to obtain a token
+ token = my_auth_system.get_jwt(scope=scope)
+ return AccessToken(
+ token=token,
+ expires_on=int(time.time()) + 3600
+ )
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=MyCustomCredential(),
+ scope="my-scope"
+)
+```
+
+## Supported Endpoints
+
+Auth headers are automatically injected for:
+
+| Endpoint | Function |
+|----------|----------|
+| Chat Completions | `litellm.completion()` / `litellm.acompletion()` |
+| Embeddings | `litellm.embedding()` / `litellm.aembedding()` |
+
+## How It Works
+
+```
+┌──────────┐ ┌──────────────────┐ ┌──────────────┐ ┌──────────────┐
+│ Your │ │ ProxyAuthHandler │ │ Identity │ │ LiteLLM │
+│ Code │────▶│ (token cache) │────▶│ Provider │ │ Proxy │
+│ │ │ │◀────│ (Azure AD, │ │ │
+│ │ │ │ │ Okta, etc) │ │ │
+│ │ └────────┬─────────┘ └──────────────┘ │ │
+│ │ │ Authorization: Bearer │ │
+│ │──────────────┼───────────────────────────────────▶│ │
+│ │◀─────────────┼────────────────────────────────────│ │
+└──────────┘ │ └──────────────┘
+```
+
+1. You set `litellm.proxy_auth` once at startup
+2. On each SDK call (`completion()`, `embedding()`), the handler checks its cached token
+3. If the token is missing or expires within 60 seconds, it requests a new one from your identity provider
+4. The `Authorization: Bearer ` header is injected into the request
+5. If token retrieval fails, a warning is logged and the request proceeds without auth headers
+
+## API Reference
+
+### ProxyAuthHandler
+
+The main handler that manages the token lifecycle.
+
+```python
+from litellm.proxy_auth import ProxyAuthHandler
+
+handler = ProxyAuthHandler(
+ credential=, # required - credential provider
+ scope="" # required - OAuth2 scope to request
+)
+```
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `credential` | `TokenCredential` | Yes | A credential provider (AzureADCredential, GenericOAuth2Credential, or custom) |
+| `scope` | `str` | Yes | The OAuth2 scope to request tokens for |
+
+**Methods:**
+
+| Method | Returns | Description |
+|--------|---------|-------------|
+| `get_token()` | `AccessToken` | Get a valid token, refreshing if needed |
+| `get_auth_headers()` | `dict` | Get `{"Authorization": "Bearer "}` headers |
+
+### AzureADCredential
+
+Wraps any `azure-identity` credential with lazy initialization.
+
+```python
+from litellm.proxy_auth import AzureADCredential
+
+# Uses DefaultAzureCredential (recommended)
+cred = AzureADCredential()
+
+# Or wrap a specific azure-identity credential
+from azure.identity import ManagedIdentityCredential
+cred = AzureADCredential(credential=ManagedIdentityCredential())
+```
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `credential` | Azure `TokenCredential` | No | An azure-identity credential. If `None`, uses `DefaultAzureCredential` |
+
+### GenericOAuth2Credential
+
+Standard OAuth2 client credentials flow for any provider.
+
+```python
+from litellm.proxy_auth import GenericOAuth2Credential
+
+cred = GenericOAuth2Credential(
+ client_id="your-client-id",
+ client_secret="your-client-secret",
+ token_url="https://your-idp.com/oauth2/token"
+)
+```
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `client_id` | `str` | Yes | OAuth2 client ID |
+| `client_secret` | `str` | Yes | OAuth2 client secret |
+| `token_url` | `str` | Yes | Token endpoint URL |
+
+### AccessToken
+
+Dataclass representing an OAuth2 access token.
+
+```python
+from litellm.proxy_auth import AccessToken
+
+token = AccessToken(
+ token="eyJhbG...", # JWT string
+ expires_on=1234567890 # Unix timestamp
+)
+```
+
+### TokenCredential Protocol
+
+Any class implementing this protocol can be used as a credential provider:
+
+```python
+from litellm.proxy_auth import AccessToken
+
+class MyCredential:
+ def get_token(self, scope: str) -> AccessToken:
+ ...
+```
+
+## Provider-Specific Examples
+
+### Keycloak
+
+```python
+from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=GenericOAuth2Credential(
+ client_id="litellm-client",
+ client_secret="your-keycloak-client-secret",
+ token_url="https://keycloak.example.com/realms/your-realm/protocol/openid-connect/token"
+ ),
+ scope="openid"
+)
+```
+
+### Okta
+
+```python
+from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=GenericOAuth2Credential(
+ client_id="your-okta-client-id",
+ client_secret="your-okta-client-secret",
+ token_url="https://your-org.okta.com/oauth2/default/v1/token"
+ ),
+ scope="litellm_api"
+)
+```
+
+### Auth0
+
+```python
+from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=GenericOAuth2Credential(
+ client_id="your-auth0-client-id",
+ client_secret="your-auth0-client-secret",
+ token_url="https://your-tenant.auth0.com/oauth/token"
+ ),
+ scope="https://my-proxy.example.com/api"
+)
+```
+
+### Azure AD with Managed Identity
+
+```python
+from azure.identity import ManagedIdentityCredential
+from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
+
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=AzureADCredential(
+ credential=ManagedIdentityCredential()
+ ),
+ scope="api://my-litellm-proxy/.default"
+)
+```
+
+## Combining with `use_litellm_proxy`
+
+You can use `proxy_auth` together with [`use_litellm_proxy`](./providers/litellm_proxy#send-all-sdk-requests-to-litellm-proxy) to route all SDK requests through an authenticated proxy:
+
+```python
+import os
+import litellm
+from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
+
+# Route all requests through the proxy
+os.environ["LITELLM_PROXY_API_BASE"] = "https://my-proxy.example.com"
+litellm.use_litellm_proxy = True
+
+# Authenticate with OAuth2/JWT
+litellm.proxy_auth = ProxyAuthHandler(
+ credential=AzureADCredential(),
+ scope="api://my-litellm-proxy/.default"
+)
+
+# This request goes through the proxy with automatic JWT auth
+response = litellm.completion(
+ model="vertex_ai/gemini-2.0-flash-001",
+ messages=[{"role": "user", "content": "Hello!"}]
+)
+```
diff --git a/docs/my-website/docs/rag_ingest.md b/docs/my-website/docs/rag_ingest.md
index 1133b85f206..7adc2d70b5b 100644
--- a/docs/my-website/docs/rag_ingest.md
+++ b/docs/my-website/docs/rag_ingest.md
@@ -5,7 +5,7 @@ All-in-one document ingestion pipeline: **Upload → Chunk → Embed → Vector
| Feature | Supported |
|---------|-----------|
| Logging | Yes |
-| Supported Providers | `openai`, `bedrock`, `vertex_ai`, `gemini` |
+| Supported Providers | `openai`, `bedrock`, `vertex_ai`, `gemini`, `s3_vectors` |
:::tip
After ingesting documents, use [/rag/query](./rag_query.md) to search and generate responses with your ingested content.
@@ -75,6 +75,31 @@ curl -X POST "http://localhost:4000/v1/rag/ingest" \
}"
```
+### AWS S3 Vectors
+
+```bash showLineNumbers title="Ingest to S3 Vectors"
+curl -X POST "http://localhost:4000/v1/rag/ingest" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"file\": {
+ \"filename\": \"document.txt\",
+ \"content\": \"$(base64 -i document.txt)\",
+ \"content_type\": \"text/plain\"
+ },
+ \"ingest_options\": {
+ \"embedding\": {
+ \"model\": \"text-embedding-3-small\"
+ },
+ \"vector_store\": {
+ \"custom_llm_provider\": \"s3_vectors\",
+ \"vector_bucket_name\": \"my-embeddings\",
+ \"aws_region_name\": \"us-west-2\"
+ }
+ }
+ }"
+```
+
## Response
```json
@@ -265,6 +290,57 @@ When `vector_store_id` is omitted, LiteLLM automatically creates:
4. Install: `pip install 'google-cloud-aiplatform>=1.60.0'`
:::
+### vector_store (AWS S3 Vectors)
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `custom_llm_provider` | string | - | `"s3_vectors"` |
+| `vector_bucket_name` | string | **required** | S3 vector bucket name |
+| `index_name` | string | auto-create | Vector index name |
+| `dimension` | integer | auto-detect | Vector dimension (auto-detected from embedding model) |
+| `distance_metric` | string | `cosine` | Distance metric: `cosine` or `euclidean` |
+| `non_filterable_metadata_keys` | array | `["source_text"]` | Metadata keys excluded from filtering |
+| `aws_region_name` | string | `us-west-2` | AWS region |
+| `aws_access_key_id` | string | env | AWS access key |
+| `aws_secret_access_key` | string | env | AWS secret key |
+
+:::info S3 Vectors Auto-Creation
+When `index_name` is omitted, LiteLLM automatically creates:
+- S3 vector bucket (if it doesn't exist)
+- Vector index with auto-detected dimensions from your embedding model
+
+**Dimension Auto-Detection**: The vector dimension is automatically detected by making a test embedding request to your specified model. No need to manually specify dimensions!
+
+**Supported Embedding Models**: Works with any LiteLLM-supported embedding model (OpenAI, Cohere, Bedrock, Azure, etc.)
+:::
+
+**Example with auto-detection:**
+```json
+{
+ "embedding": {
+ "model": "text-embedding-3-small" // Dimension auto-detected as 1536
+ },
+ "vector_store": {
+ "custom_llm_provider": "s3_vectors",
+ "vector_bucket_name": "my-embeddings"
+ }
+}
+```
+
+**Example with custom embedding provider:**
+```json
+{
+ "embedding": {
+ "model": "cohere/embed-english-v3.0" // Dimension auto-detected as 1024
+ },
+ "vector_store": {
+ "custom_llm_provider": "s3_vectors",
+ "vector_bucket_name": "my-embeddings",
+ "distance_metric": "cosine"
+ }
+}
+```
+
## Input Examples
### File (Base64)
diff --git a/docs/my-website/docs/realtime.md b/docs/my-website/docs/realtime.md
index 0b3c823f5db..b191c82c670 100644
--- a/docs/my-website/docs/realtime.md
+++ b/docs/my-website/docs/realtime.md
@@ -3,13 +3,15 @@ import TabItem from '@theme/TabItem';
# /realtime
-Use this to loadbalance across Azure + OpenAI.
+Use this to loadbalance across Azure + OpenAI + xAI and more.
Supported Providers:
- OpenAI
- Azure
+- xAI ([see full docs](/docs/providers/xai_realtime))
- Google AI Studio (Gemini)
- Vertex AI
+- Bedrock
## Proxy Usage
@@ -45,6 +47,21 @@ model_list:
api_key: os.environ/OPENAI_API_KEY
```
+
+
+
+```yaml
+model_list:
+ - model_name: grok-voice-agent
+ litellm_params:
+ model: xai/grok-4-1-fast-non-reasoning
+ api_key: os.environ/XAI_API_KEY
+ model_info:
+ mode: realtime
+```
+
+**[See full xAI Realtime documentation →](/docs/providers/xai_realtime)**
+
diff --git a/docs/my-website/docs/rerank.md b/docs/my-website/docs/rerank.md
index 90f685d2bbd..9c76883d7fd 100644
--- a/docs/my-website/docs/rerank.md
+++ b/docs/my-website/docs/rerank.md
@@ -8,15 +8,15 @@ LiteLLM Follows the [cohere api request / response for the rerank api](https://c
## Overview
-| Feature | Supported | Notes |
-|---------|-----------|-------|
-| Cost Tracking | ✅ | Works with all supported models |
-| Logging | ✅ | Works across all integrations |
-| End-user Tracking | ✅ | |
-| Fallbacks | ✅ | Works between supported models |
-| Loadbalancing | ✅ | Works between supported models |
-| Guardrails | ✅ | Applies to input query only (not documents) |
-| Supported Providers | Cohere, Together AI, Azure AI, DeepInfra, Nvidia NIM, Infinity, Fireworks AI, Voyage AI | |
+| Feature | Supported | Notes |
+|---------|-----------------------------------------------------------------------------------------------------|-------|
+| Cost Tracking | ✅ | Works with all supported models |
+| Logging | ✅ | Works across all integrations |
+| End-user Tracking | ✅ | |
+| Fallbacks | ✅ | Works between supported models |
+| Loadbalancing | ✅ | Works between supported models |
+| Guardrails | ✅ | Applies to input query only (not documents) |
+| Supported Providers | Cohere, Together AI, Azure AI, DeepInfra, Nvidia NIM, Infinity, Fireworks AI, Voyage AI, watsonx.ai | |
## **LiteLLM Python SDK Usage**
### Quick Start
@@ -123,17 +123,18 @@ curl http://0.0.0.0:4000/rerank \
#### ⚡️See all supported models and providers at [models.litellm.ai](https://models.litellm.ai/)
-| Provider | Link to Usage |
-|-------------|--------------------|
-| Cohere (v1 + v2 clients) | [Usage](#quick-start) |
-| Together AI| [Usage](../docs/providers/togetherai) |
-| Azure AI| [Usage](../docs/providers/azure_ai#rerank-endpoint) |
-| Jina AI| [Usage](../docs/providers/jina_ai) |
-| AWS Bedrock| [Usage](../docs/providers/bedrock#rerank-api) |
-| HuggingFace| [Usage](../docs/providers/huggingface_rerank) |
-| Infinity| [Usage](../docs/providers/infinity) |
-| vLLM| [Usage](../docs/providers/vllm#rerank-endpoint) |
-| DeepInfra| [Usage](../docs/providers/deepinfra#rerank-endpoint) |
-| Vertex AI| [Usage](../docs/providers/vertex#rerank-api) |
-| Fireworks AI| [Usage](../docs/providers/fireworks_ai#rerank-endpoint) |
-| Voyage AI| [Usage](../docs/providers/voyage#rerank) |
\ No newline at end of file
+| Provider | Link to Usage |
+|--------------------------|------------------------------------------------------|
+| Cohere (v1 + v2 clients) | [Usage](#quick-start) |
+| Together AI | [Usage](../docs/providers/togetherai) |
+| Azure AI | [Usage](../docs/providers/azure_ai#rerank-endpoint) |
+| Jina AI | [Usage](../docs/providers/jina_ai) |
+| AWS Bedrock | [Usage](../docs/providers/bedrock#rerank-api) |
+| HuggingFace | [Usage](../docs/providers/huggingface_rerank) |
+| Infinity | [Usage](../docs/providers/infinity) |
+| vLLM | [Usage](../docs/providers/vllm#rerank-endpoint) |
+| DeepInfra | [Usage](../docs/providers/deepinfra#rerank-endpoint) |
+| Vertex AI | [Usage](../docs/providers/vertex#rerank-api) |
+| Fireworks AI | [Usage](../docs/providers/fireworks_ai#rerank-endpoint) |
+| Voyage AI | [Usage](../docs/providers/voyage#rerank) |
+| IBM watsonx.ai | [Usage](../docs/providers/watsonx/rerank) |
\ No newline at end of file
diff --git a/docs/my-website/docs/response_api.md b/docs/my-website/docs/response_api.md
index 140dfd4faf8..65b7ad7773a 100644
--- a/docs/my-website/docs/response_api.md
+++ b/docs/my-website/docs/response_api.md
@@ -884,7 +884,12 @@ router = litellm.Router(
},
},
],
- optional_pre_call_checks=["responses_api_deployment_check"],
+ # `responses_api_deployment_check` ensures Requests with `previous_response_id`
+ # are routed to the same deployment. `deployment_affinity` adds sticky sessions
+ # for requests without `previous_response_id` (useful for implicit caching).
+ optional_pre_call_checks=["responses_api_deployment_check", "deployment_affinity"],
+ # Optional (default is 3600 seconds / 1 hour)
+ deployment_affinity_ttl_seconds=3600,
)
# Initial request
@@ -911,7 +916,16 @@ follow_up = await router.aresponses(
#### 1. Setup session continuity on proxy config.yaml
-To enable session continuity for Responses API in your LiteLLM proxy, set `optional_pre_call_checks: ["responses_api_deployment_check"]` in your proxy config.yaml.
+To enable session continuity for Responses API in your LiteLLM proxy, set `optional_pre_call_checks` in your proxy config.yaml.
+
+- `responses_api_deployment_check`: high priority routing when `previous_response_id` is provided
+- `deployment_affinity`: sticky sessions based on user key (applies even without `previous_response_id`)
+
+Notes:
+- User-key affinity is keyed on `metadata.user_api_key_hash` (the API key hash). The OpenAI `user` request parameter is an end-user identifier and is intentionally not used for deployment affinity.
+- `user_api_key_hash` is already SHA-256, and is used as-is (no double hashing).
+- Affinity is scoped by a stable model identifier (the model-map key, e.g. `model_map_information.model_map_key`) so model aliases map to the same stickiness bucket.
+- The mapping TTL is controlled by `deployment_affinity_ttl_seconds` (configured on Router init / proxy startup).
```yaml showLineNumbers title="config.yaml with Session Continuity"
model_list:
@@ -929,7 +943,11 @@ model_list:
api_base: https://endpoint2.openai.azure.com
router_settings:
- optional_pre_call_checks: ["responses_api_deployment_check"]
+ optional_pre_call_checks:
+ - responses_api_deployment_check
+ - deployment_affinity
+ # Optional (default is 3600 seconds / 1 hour)
+ deployment_affinity_ttl_seconds: 3600
```
#### 2. Use the OpenAI Python SDK to make requests to LiteLLM Proxy
@@ -1023,6 +1041,134 @@ curl http://localhost:4000/v1/responses \
+## Server-side compaction
+
+For long-running conversations, you can enable **server-side compaction** so that when the rendered context size crosses a threshold, the server automatically runs compaction in-stream and emits a compaction item—no separate `POST /v1/responses/compact` call is required.
+
+Supported on the OpenAI Responses API when using the `openai` or `azure` provider. Pass `context_management` with a compaction entry and `compact_threshold` (token count; minimum 1000). When the context crosses the threshold, the server compacts in-stream and continues. Chain turns with `previous_response_id` or by appending output items to your next input array. See [OpenAI Compaction guide](https://developers.openai.com/api/docs/guides/compaction) for details.
+
+For explicit control over when compaction runs, use the standalone compact endpoint (`POST /v1/responses/compact`) instead.
+
+### Python SDK
+
+```python showLineNumbers title="Server-side compaction with LiteLLM Python SDK"
+import litellm
+
+# Non-streaming: enable compaction when context exceeds 200k tokens
+response = litellm.responses(
+ model="openai/gpt-4o",
+ input="Your conversation input...",
+ context_management=[{"type": "compaction", "compact_threshold": 200000}],
+ max_output_tokens=1024,
+)
+print(response)
+
+# Streaming: same context_management, compaction runs in-stream if threshold is crossed
+stream = litellm.responses(
+ model="openai/gpt-4o",
+ input="Your conversation input...",
+ context_management=[{"type": "compaction", "compact_threshold": 200000}],
+ stream=True,
+)
+for event in stream:
+ print(event)
+```
+
+### LiteLLM Proxy (AI Gateway)
+
+Use the OpenAI SDK with your proxy as `base_url`, or call the proxy with curl. The proxy forwards `context_management` to the provider.
+
+**OpenAI Python SDK (proxy as base_url):**
+
+```python showLineNumbers title="Server-side compaction via LiteLLM Proxy"
+from openai import OpenAI
+
+client = OpenAI(
+ base_url="http://localhost:4000", # LiteLLM Proxy (AI Gateway)
+ api_key="your-proxy-api-key",
+)
+
+response = client.responses.create(
+ model="openai/gpt-4o",
+ input="Your conversation input...",
+ context_management=[{"type": "compaction", "compact_threshold": 200000}],
+ max_output_tokens=1024,
+)
+print(response)
+```
+
+**curl (proxy):**
+
+```bash title="Server-side compaction via curl to LiteLLM Proxy"
+curl -X POST "http://localhost:4000/v1/responses" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer your-proxy-api-key" \
+ -d '{
+ "model": "openai/gpt-4o",
+ "input": "Your conversation input...",
+ "context_management": [{"type": "compaction", "compact_threshold": 200000}],
+ "max_output_tokens": 1024
+ }'
+```
+
+## Shell tool
+
+The **Shell tool** lets the model run commands in a hosted container or local runtime (OpenAI Responses API). You pass `tools=[{"type": "shell", "environment": {...}}]`; the `environment` object configures the runtime (e.g. `type: "container_auto"` for auto-provisioned containers). See [OpenAI Shell tool guide](https://developers.openai.com/api/docs/guides/tools-shell) for full options.
+
+Supported when using the `openai` or `azure` provider with a model that supports the Shell tool.
+
+### Python SDK
+
+```python showLineNumbers title="Shell tool with LiteLLM Python SDK"
+import litellm
+
+response = litellm.responses(
+ model="openai/gpt-5.2",
+ input="List files in /mnt/data and run python --version.",
+ tools=[{"type": "shell", "environment": {"type": "container_auto"}}],
+ tool_choice="auto",
+ max_output_tokens=1024,
+)
+```
+
+### LiteLLM Proxy (AI Gateway)
+
+Use the OpenAI SDK with your proxy as `base_url`, or call the proxy with curl. The proxy forwards `tools` (including `type: "shell"`) to the provider.
+
+**OpenAI Python SDK (proxy as base_url):**
+
+```python showLineNumbers title="Shell tool via LiteLLM Proxy"
+from openai import OpenAI
+
+client = OpenAI(
+ base_url="http://localhost:4000",
+ api_key="your-proxy-api-key",
+)
+
+response = client.responses.create(
+ model="openai/gpt-5.2",
+ input="List files in /mnt/data.",
+ tools=[{"type": "shell", "environment": {"type": "container_auto"}}],
+ tool_choice="auto",
+ max_output_tokens=1024,
+)
+```
+
+**curl:**
+
+```bash title="Shell tool via curl to LiteLLM Proxy"
+curl -X POST "http://localhost:4000/v1/responses" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer your-proxy-api-key" \
+ -d '{
+ "model": "openai/gpt-5.2",
+ "input": "List files in /mnt/data.",
+ "tools": [{"type": "shell", "environment": {"type": "container_auto"}}],
+ "tool_choice": "auto",
+ "max_output_tokens": 1024
+ }'
+```
+
## Session Management
LiteLLM Proxy supports session management for all supported models. This allows you to store and fetch conversation history (state) in LiteLLM Proxy.
@@ -1228,8 +1374,3 @@ Response:
-
-
-
-
-
diff --git a/docs/my-website/docs/routing.md b/docs/my-website/docs/routing.md
index 47967775e1e..67e7f681147 100644
--- a/docs/my-website/docs/routing.md
+++ b/docs/my-website/docs/routing.md
@@ -830,6 +830,12 @@ asyncio.run(router_acompletion())
+## Traffic Mirroring / Silent Experiments
+
+Traffic mirroring allows you to "mimic" production traffic to a secondary (silent) model for evaluation purposes. The silent model's response is gathered in the background and does not affect the latency or result of the primary request.
+
+[**See detailed guide on A/B Testing - Traffic Mirroring here**](./traffic_mirroring.md)
+
## Basic Reliability
### Deployment Ordering (Priority)
@@ -1582,11 +1588,13 @@ Get a slack webhook url from https://api.slack.com/messaging/webhooks
Initialize an `AlertingConfig` and pass it to `litellm.Router`. The following code will trigger an alert because `api_key=bad-key` which is invalid
```python
-from litellm.router import AlertingConfig
import litellm
+from litellm.router import Router
+from litellm.types.router import AlertingConfig
import os
+import asyncio
-router = litellm.Router(
+router = Router(
model_list=[
{
"model_name": "gpt-3.5-turbo",
@@ -1597,17 +1605,28 @@ router = litellm.Router(
}
],
alerting_config= AlertingConfig(
- alerting_threshold=10, # threshold for slow / hanging llm responses (in seconds). Defaults to 300 seconds
- webhook_url= os.getenv("SLACK_WEBHOOK_URL") # webhook you want to send alerts to
+ alerting_threshold=10,
+ webhook_url= "https:/..."
),
)
-try:
- await router.acompletion(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": "Hey, how's it going?"}],
- )
-except:
- pass
+
+async def main():
+ print(f"\n=== Configuration ===")
+ print(f"Slack logger exists: {router.slack_alerting_logger is not None}")
+
+ try:
+ await router.acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hey, how's it going?"}],
+ )
+ except Exception as e:
+ print(f"\n=== Exception caught ===")
+ print(f"Waiting 10 seconds for alerts to be sent via periodic flush...")
+ await asyncio.sleep(10)
+ print(f"\n=== After waiting ===")
+ print(f"Alert should have been sent to Slack!")
+
+asyncio.run(main())
```
## Track cost for Azure Deployments
diff --git a/docs/my-website/docs/search/index.md b/docs/my-website/docs/search/index.md
index 551a495261a..8a71edead06 100644
--- a/docs/my-website/docs/search/index.md
+++ b/docs/my-website/docs/search/index.md
@@ -276,6 +276,7 @@ The response follows Perplexity's search format with the following structure:
| Firecrawl | `FIRECRAWL_API_KEY` | `firecrawl` |
| SearXNG | `SEARXNG_API_BASE` (required) | `searxng` |
| Linkup | `LINKUP_API_KEY` | `linkup` |
+| DuckDuckGo | `DUCKDUCKGO_API_BASE` | `duckduckgo` |
See the individual provider documentation for detailed setup instructions and provider-specific parameters.
diff --git a/docs/my-website/docs/traffic_mirroring.md b/docs/my-website/docs/traffic_mirroring.md
new file mode 100644
index 00000000000..3bdcb0f1614
--- /dev/null
+++ b/docs/my-website/docs/traffic_mirroring.md
@@ -0,0 +1,83 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# A/B Testing - Traffic Mirroring
+
+Traffic mirroring allows you to "mimic" production traffic to a secondary (silent) model for evaluation purposes. The silent model's response is gathered in the background and does not affect the latency or result of the primary request.
+
+This is useful for:
+- Testing a new model's performance on production prompts before switching.
+- Comparing costs and latency between different providers.
+- Debugging issues by mirroring traffic to a more verbose model.
+
+## Quick Start
+
+To enable traffic mirroring, add `silent_model` to the `litellm_params` of a deployment.
+
+
+
+
+```python
+from litellm import Router
+
+model_list = [
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {
+ "model": "azure/chatgpt-v-2",
+ "api_key": "...",
+ "silent_model": "gpt-4" # 👈 Mirror traffic to gpt-4
+ },
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "openai/gpt-4",
+ "api_key": "..."
+ },
+ }
+]
+
+router = Router(model_list=model_list)
+
+# The request to "gpt-3.5-turbo" will trigger a background call to "gpt-4"
+response = await router.acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "How does traffic mirroring work?"}]
+)
+```
+
+
+
+
+Add `silent_model` to your `config.yaml`:
+
+```yaml
+model_list:
+ - model_name: primary-model
+ litellm_params:
+ model: azure/gpt-35-turbo
+ api_key: os.environ/AZURE_API_KEY
+ silent_model: evaluation-model # 👈 Mirror traffic here
+ - model_name: evaluation-model
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: os.environ/OPENAI_API_KEY
+```
+
+
+
+
+## How it works
+1. **Request Received**: A request is made to a model group (e.g. `primary-model`).
+2. **Deployment Picked**: LiteLLM picks a deployment from the group.
+3. **Primary Call**: LiteLLM makes the call to the primary deployment.
+4. **Mirroring**: If `silent_model` is present, LiteLLM triggers a background call to that model.
+ - For **Sync** calls: Uses a shared thread pool.
+ - For **Async** calls: Uses `asyncio.create_task`.
+5. **Isolation**: The background call uses a `deepcopy` of the original request parameters and sets `metadata["is_silent_experiment"] = True`. It also strips out logging IDs to prevent collisions in usage tracking.
+
+## Key Features
+- **Latency Isolation**: The primary request returns as soon as it's ready. The background (silent) call does not block.
+- **Unified Logging**: Background calls are processed via the Router, meaning they are automatically logged to your configured observability tools (Langfuse, S3, etc.).
+- **Evaluation**: Use the `is_silent_experiment: True` flag in your logs to filter and compare results between the primary and mirrored calls.
diff --git a/docs/my-website/docs/troubleshoot.md b/docs/my-website/docs/troubleshoot.md
index f9ed47972eb..1539e1959f7 100644
--- a/docs/my-website/docs/troubleshoot.md
+++ b/docs/my-website/docs/troubleshoot.md
@@ -1,45 +1,43 @@
-# Troubleshooting & Support
-
-## Information to Provide When Seeking Help
+# Issue Reporting
When reporting issues, please include as much of the following as possible. It's okay if you can't provide everything—especially in production scenarios where the trigger might be unknown. Sharing most of this information will help us assist you more effectively.
-### 1. LiteLLM Configuration File
+## 1. LiteLLM Configuration File
Your `config.yaml` file (redact sensitive info like API keys). Include number of workers if not in config.
-### 2. Initialization Command
+## 2. Initialization Command
The command used to start LiteLLM (e.g., `litellm --config config.yaml --num_workers 8 --detailed_debug`).
-### 3. LiteLLM Version
+## 3. LiteLLM Version
-- Current version
-- Version when the issue first appeared (if different)
+- Current version
+- Version when the issue first appeared (if different)
- If upgraded, the version changed from → to
-### 4. Environment Variables
+## 4. Environment Variables
Non-sensitive environment variables not in your config (e.g., `NUM_WORKERS`, `LITELLM_LOG`, `LITELLM_MODE`). Do not include passwords or API keys.
-### 5. Server Specifications
+## 5. Server Specifications
CPU cores, RAM, OS, number of instances/replicas, etc.
-### 6. Database and Redis Usage
+## 6. Database and Redis Usage
- **Database:** Using database? (`DATABASE_URL` set), database type and version
- **Redis:** Using Redis? Redis version, configuration type (Standalone/Cluster/Sentinel).
-### 7. Endpoints
+## 7. Endpoints
The endpoint(s) you're using that are experiencing issues (e.g., `/chat/completions`, `/embeddings`).
-### 8. Request Example
+## 8. Request Example
A realistic example of the request causing issues, including expected vs. actual response and any error messages.
-### 9. Error Logs, Stack Traces, and Metrics
+## 9. Error Logs, Stack Traces, and Metrics
Full error logs, stack traces, and any images from service metrics (CPU, memory, request rates, etc.) that might help diagnose the issue.
@@ -57,4 +55,3 @@ Our numbers 📞 +1 (770) 8783-106 / +1 (412) 618-6238
Our emails ✉️ ishaan@berri.ai / krrish@berri.ai
[](https://wa.link/huol9n) [](https://discord.gg/wuPM9dRgDw)
-
diff --git a/docs/my-website/docs/troubleshoot/max_callbacks.md b/docs/my-website/docs/troubleshoot/max_callbacks.md
new file mode 100644
index 00000000000..4b0f3e24b73
--- /dev/null
+++ b/docs/my-website/docs/troubleshoot/max_callbacks.md
@@ -0,0 +1,68 @@
+# MAX_CALLBACKS Limit
+
+## Error Message
+
+```
+Cannot add callback - would exceed MAX_CALLBACKS limit of 30. Current callbacks: 30
+```
+
+## What This Means
+
+LiteLLM limits the number of callbacks that can be registered to prevent performance degradation. Each callback runs on every LLM request, so having too many callbacks can cause exponential CPU usage and slow down your proxy.
+
+The default limit is **30 callbacks**.
+
+## When You Might Hit This Limit
+
+- **Large enterprise deployments** with many teams, each having their own guardrails
+- **Multiple logging integrations** combined with custom callbacks
+- **Per-team callback configurations** that add up across your organization
+
+## How to Override
+
+Set the `LITELLM_MAX_CALLBACKS` environment variable to increase the limit:
+
+```bash
+# Docker
+docker run -e LITELLM_MAX_CALLBACKS=100 ...
+
+# Docker Compose
+environment:
+ - LITELLM_MAX_CALLBACKS=100
+
+# Kubernetes
+env:
+ - name: LITELLM_MAX_CALLBACKS
+ value: "100"
+
+# Direct
+export LITELLM_MAX_CALLBACKS=100
+litellm --config config.yaml
+```
+
+## Recommendations
+
+1. **Start conservative** - Only increase as much as you need. If you have 60 teams with guardrails, try `LITELLM_MAX_CALLBACKS=75` to leave headroom.
+
+2. **Monitor performance** - More callbacks means more processing per request. Watch your CPU usage and response latency after increasing the limit.
+
+3. **Consolidate where possible** - If multiple teams use identical guardrails, consider using shared callback configurations rather than per-team duplicates.
+
+## Example: Large Enterprise Setup
+
+For an organization with 60+ teams, each with a guardrail callback:
+
+```yaml
+# config.yaml
+litellm_settings:
+ callbacks: ["prometheus", "langfuse"] # 2 global callbacks
+
+# Each team adds 1 guardrail callback = 60+ callbacks
+# Total: 62+ callbacks needed
+```
+
+Set the environment variable:
+
+```bash
+export LITELLM_MAX_CALLBACKS=100
+```
diff --git a/docs/my-website/docs/troubleshoot/prisma_migrations.md b/docs/my-website/docs/troubleshoot/prisma_migrations.md
new file mode 100644
index 00000000000..9d9cb585b2b
--- /dev/null
+++ b/docs/my-website/docs/troubleshoot/prisma_migrations.md
@@ -0,0 +1,113 @@
+# Troubleshooting Prisma Migration Errors
+
+Common Prisma migration issues encountered when upgrading or downgrading LiteLLM proxy versions, and how to fix them.
+
+## How Prisma Migrations Work in LiteLLM
+
+- LiteLLM uses [Prisma](https://www.prisma.io/) to manage its PostgreSQL database schema.
+- Migration history is tracked in the `_prisma_migrations` table in your database.
+- When LiteLLM starts, it runs `prisma migrate deploy` to apply any new migrations.
+- Upgrading LiteLLM applies all migrations added since your last applied version.
+
+## Common Errors
+
+### 1. `relation "X" does not exist`
+
+**Example error:**
+
+```
+ERROR: relation "LiteLLM_DeletedTeamTable" does not exist
+Migration: 20260116142756_update_deleted_keys_teams_table_routing_settings
+```
+
+**Cause:** This typically happens after a version rollback. The `_prisma_migrations` table still records migrations from the newer version as "applied," but the underlying database tables were modified, dropped, or never fully created.
+
+**How to fix:**
+
+#### Step 1 — Delete the failed migration entry and restart
+
+Remove the problematic migration from the history so it can be re-applied:
+
+```sql
+-- View recent migrations
+SELECT migration_name, finished_at, rolled_back_at, logs
+FROM "_prisma_migrations"
+ORDER BY started_at DESC
+LIMIT 10;
+
+-- Delete the failed migration entry
+DELETE FROM "_prisma_migrations"
+WHERE migration_name = '';
+```
+
+After deleting the entry, restart LiteLLM — it will re-apply the migration on startup.
+
+#### Step 2 — If that doesn't work, use `prisma db push`
+
+If deleting the migration entry and restarting doesn't resolve the issue, sync the schema directly:
+
+```bash
+DATABASE_URL="" prisma db push
+```
+
+This bypasses migration history and forces the database schema to match the Prisma schema.
+
+---
+
+### 2. `New migrations cannot be applied before the error is recovered from`
+
+**Cause:** A previous migration failed (recorded with an error in `_prisma_migrations`), and Prisma refuses to apply any new migrations until the failure is resolved.
+
+**How to fix:**
+
+1. Find the failed migration:
+
+```sql
+SELECT migration_name, finished_at, rolled_back_at, logs
+FROM "_prisma_migrations"
+WHERE finished_at IS NULL OR rolled_back_at IS NOT NULL
+ORDER BY started_at DESC;
+```
+
+2. Delete the failed entry and restart LiteLLM:
+
+```sql
+DELETE FROM "_prisma_migrations"
+WHERE migration_name = '';
+```
+
+3. If that doesn't work, use `prisma db push`:
+
+```bash
+DATABASE_URL="" prisma db push
+```
+
+---
+
+### 3. Migration state mismatch after version rollback
+
+**Cause:** You upgraded to version X (new migrations applied), rolled back to version Y, then upgraded again. The `_prisma_migrations` table has stale entries for migrations that were partially applied or correspond to a schema state that no longer exists.
+
+**Fix:**
+
+1. Inspect the migration table for problematic entries:
+
+```sql
+SELECT migration_name, started_at, finished_at, rolled_back_at, logs
+FROM "_prisma_migrations"
+ORDER BY started_at DESC
+LIMIT 20;
+```
+
+2. For each migration that shouldn't be there (i.e., from the version you rolled back from), delete the entry:
+ ```sql
+ DELETE FROM "_prisma_migrations" WHERE migration_name = '';
+ ```
+
+3. Restart LiteLLM to re-run migrations.
+
+4. If that doesn't work, use `prisma db push`:
+
+```bash
+DATABASE_URL="" prisma db push
+```
diff --git a/docs/my-website/docs/troubleshoot/spend_queue_warnings.md b/docs/my-website/docs/troubleshoot/spend_queue_warnings.md
new file mode 100644
index 00000000000..4be8b18f5cd
--- /dev/null
+++ b/docs/my-website/docs/troubleshoot/spend_queue_warnings.md
@@ -0,0 +1,46 @@
+# Spend Update Queue Full Warnings
+
+## Overview
+
+The "Spend update queue is full" warning occurs in high-volume LiteLLM proxy deployments when the internal spend tracking queue reaches capacity. This is a protective mechanism to prevent memory issues during traffic spikes.
+
+## Warning Message
+
+```
+WARNING:litellm.proxy.db.db_transaction_queue.spend_update_queue:Spend update queue is full. Aggregating entries to prevent memory issues.
+```
+
+## Root Cause
+
+The spend update queue has a default maximum size of 10,000 entries (`MAX_SIZE_IN_MEMORY_QUEUE=10000`). When this limit is reached:
+
+1. New spend tracking entries are aggregated instead of queued individually
+2. This prevents memory exhaustion but may slightly delay spend updates
+3. The warning indicates your deployment is processing requests faster than the database can handle spend updates
+
+## Solutions
+
+### 1. Increase Queue Size
+
+Set the `MAX_SIZE_IN_MEMORY_QUEUE` environment variable to a higher value:
+
+```bash
+MAX_SIZE_IN_MEMORY_QUEUE=50000
+```
+
+**Tradeoffs:**
+Higher queue sizes store more items in memory - provision at least 8GB RAM for large queues
+- Recommended for deployments with consistent high traffic
+
+### 2. Horizontal Scaling
+
+Deploy multiple proxy instances with load balancing. This distributes the spend tracking load across multiple queues, reducing the pressure on any single instance's spend update queue.
+
+
+
+## Related Configuration
+
+```yaml
+# Environment variables
+MAX_SIZE_IN_MEMORY_QUEUE: 10000 # Default queue size
+```
diff --git a/docs/my-website/docs/troubleshoot/ui_issues.md b/docs/my-website/docs/troubleshoot/ui_issues.md
new file mode 100644
index 00000000000..90912b1daeb
--- /dev/null
+++ b/docs/my-website/docs/troubleshoot/ui_issues.md
@@ -0,0 +1,49 @@
+# UI Troubleshooting
+
+If you're experiencing issues with the LiteLLM Admin UI, please include the following information when reporting.
+
+## 1. Steps to Reproduce
+
+A clear, step-by-step description of how to trigger the issue (e.g., "Navigate to Settings → Team, click 'Create Team', fill in fields, click submit → error appears").
+
+## 2. LiteLLM Version
+
+The current version of LiteLLM you're running. Check via `litellm --version` or the UI's settings page.
+
+## 3. Architecture & Deployment Setup
+
+Distributed environments are a known source of UI issues. Please describe:
+
+- **Number of LiteLLM instances/replicas** and how they are deployed (e.g., Kubernetes, Docker Compose, ECS)
+- **Load balancer** type and configuration (e.g., ALB, Nginx, Cloudflare Tunnel) — include whether sticky sessions are enabled
+- **How the UI is accessed** — directly via LiteLLM, through a reverse proxy, or behind an ingress controller
+- **Any CDN or caching layers** between the user and the LiteLLM server
+
+## 4. Network Tab Requests
+
+Open your browser's Developer Tools (F12 → Network tab), reproduce the issue, and share:
+
+- The **failing request(s)** — URL, method, status code, and response body
+- **Screenshots or HAR export** of the relevant network activity
+- Any **CORS or mixed-content errors** shown in the Console tab
+
+## 5. Environment Variables
+
+Non-sensitive environment variables related to the UI and proxy setup, such as:
+
+- `LITELLM_MASTER_KEY`
+- `PROXY_BASE_URL` / `LITELLM_PROXY_BASE_URL`
+- `UI_BASE_PATH`
+- Any SSO-related variables (e.g., `GOOGLE_CLIENT_ID`, `MICROSOFT_TENANT`)
+
+Do **not** include passwords, secrets, or API keys.
+
+## 6. Browser & Access Details
+
+- **Browser** and version (e.g., Chrome 120, Firefox 121)
+- **Access URL** used to reach the UI (redact sensitive parts)
+- Whether the issue occurs for **all users or specific roles** (Admin, Internal User, etc.)
+
+## 7. Screenshots or Screen Recordings
+
+A screenshot or short screen recording of the issue is extremely helpful. Include any visible error messages, toasts, or unexpected behavior.
diff --git a/docs/my-website/docs/tutorials/claude_agent_sdk.md b/docs/my-website/docs/tutorials/claude_agent_sdk.md
new file mode 100644
index 00000000000..c56784ba2df
--- /dev/null
+++ b/docs/my-website/docs/tutorials/claude_agent_sdk.md
@@ -0,0 +1,115 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Claude Agent SDK with LiteLLM
+
+Use Anthropic's Claude Agent SDK with any LLM provider through LiteLLM Proxy.
+
+The Claude Agent SDK provides a high-level interface for building AI agents. By pointing it to LiteLLM, you can use the same agent code with OpenAI, Bedrock, Azure, Vertex AI, or any other provider.
+
+## Quick Start
+
+### 1. Install Dependencies
+
+```bash
+pip install claude-agent-sdk
+```
+
+### 2. Start LiteLLM Proxy
+
+```yaml title="config.yaml" showLineNumbers
+model_list:
+ - model_name: bedrock-claude-sonnet-3.5
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-claude-sonnet-4
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-claude-sonnet-4.5
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-claude-opus-4.5
+ litellm_params:
+ model: "bedrock/us.anthropic.claude-opus-4-5-20251101-v1:0"
+ aws_region_name: "us-east-1"
+
+ - model_name: bedrock-nova-premier
+ litellm_params:
+ model: "bedrock/amazon.nova-premier-v1:0"
+ aws_region_name: "us-east-1"
+```
+
+```bash
+litellm --config config.yaml
+```
+
+### 3. Point Agent SDK to LiteLLM
+
+| Environment Variable | Value | Description |
+|---------------------|-------|-------------|
+| `ANTHROPIC_BASE_URL` | `http://localhost:4000` | LiteLLM proxy URL |
+| `ANTHROPIC_API_KEY` | `sk-1234` | Your LiteLLM API key (not Anthropic key) |
+
+```python title="agent.py" showLineNumbers
+import os
+from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
+
+# Point to LiteLLM proxy (not Anthropic)
+os.environ["ANTHROPIC_BASE_URL"] = "http://localhost:4000"
+os.environ["ANTHROPIC_API_KEY"] = "sk-1234" # Your LiteLLM key
+
+# Configure agent with any model from your config
+options = ClaudeAgentOptions(
+ system_prompt="You are a helpful AI assistant.",
+ model="bedrock-claude-sonnet-4", # Use any model from config.yaml
+ max_turns=20,
+)
+
+async with ClaudeSDKClient(options=options) as client:
+ await client.query("What is LiteLLM?")
+
+ async for msg in client.receive_response():
+ if hasattr(msg, 'content'):
+ for content_block in msg.content:
+ if hasattr(content_block, 'text'):
+ print(content_block.text, end='', flush=True)
+```
+
+
+
+## Why Use LiteLLM with Agent SDK?
+
+| Feature | Benefit |
+|---------|---------|
+| **Multi-Provider** | Use the same agent code with OpenAI, Bedrock, Azure, Vertex AI, etc. |
+| **Cost Tracking** | Track spending across all agent conversations |
+| **Rate Limiting** | Set budgets and limits on agent usage |
+| **Load Balancing** | Distribute requests across multiple API keys or regions |
+| **Fallbacks** | Automatically retry with different models if one fails |
+
+## Complete Example
+
+See our [cookbook example](https://github.com/BerriAI/litellm/tree/main/cookbook/anthropic_agent_sdk) for a complete interactive CLI agent that:
+- Streams responses in real-time
+- Switches between models dynamically
+- Fetches available models from the proxy
+
+```bash
+# Clone and run the example
+git clone https://github.com/BerriAI/litellm.git
+cd litellm/cookbook/anthropic_agent_sdk
+pip install -r requirements.txt
+python main.py
+```
+
+## Related Resources
+
+- [Claude Agent SDK Documentation](https://github.com/anthropics/anthropic-agent-sdk)
+- [LiteLLM Proxy Quick Start](../proxy/quick_start)
+- [Complete Cookbook Example](https://github.com/BerriAI/litellm/tree/main/cookbook/anthropic_agent_sdk)
diff --git a/docs/my-website/docs/tutorials/claude_code_beta_headers.md b/docs/my-website/docs/tutorials/claude_code_beta_headers.md
new file mode 100644
index 00000000000..fab90d15e88
--- /dev/null
+++ b/docs/my-website/docs/tutorials/claude_code_beta_headers.md
@@ -0,0 +1,279 @@
+import Image from '@theme/IdealImage';
+
+# Claude Code - Managing Anthropic Beta Headers
+
+When using Claude Code with LiteLLM and non-Anthropic providers (Bedrock, Azure AI, Vertex AI), you need to ensure that only supported beta headers are sent to each provider. This guide explains how to add support for new beta headers or fix invalid beta header errors.
+
+## What Are Beta Headers?
+
+Anthropic uses beta headers to enable experimental features in Claude. When you use Claude Code, it may send beta headers like:
+
+```
+anthropic-beta: prompt-caching-scope-2026-01-05,advanced-tool-use-2025-11-20
+```
+
+However, not all providers support all Anthropic beta features. LiteLLM uses `anthropic_beta_headers_config.json` to manage which beta headers are supported by each provider.
+
+## Common Error Message
+
+```bash
+Error: The model returned the following errors: invalid beta flag
+```
+
+## How LiteLLM Handles Beta Headers
+
+LiteLLM uses a strict validation approach with a configuration file:
+
+```
+litellm/litellm/anthropic_beta_headers_config.json
+```
+
+This JSON file contains a **mapping** of beta headers for each provider:
+- **Keys**: Input beta header names (from Anthropic)
+- **Values**: Provider-specific header names (or `null` if unsupported)
+- **Validation**: Only headers present in the mapping with non-null values are forwarded
+
+This enforces stricter validation than just filtering unsupported headers - headers must be explicitly defined to be allowed.
+
+## Adding Support for a New Beta Header
+
+When Anthropic releases a new beta feature, you need to add it to the configuration file for each provider.
+
+### Step 1: Locate the Config File
+
+Find the file in your LiteLLM installation:
+
+```bash
+# If installed via pip
+cd $(python -c "import litellm; import os; print(os.path.dirname(litellm.__file__))")
+
+# The config file is at:
+# litellm/anthropic_beta_headers_config.json
+```
+
+### Step 2: Add the New Beta Header
+
+Open `anthropic_beta_headers_config.json` and add the new header to each provider's mapping:
+
+```json title="anthropic_beta_headers_config.json"
+{
+ "description": "Mapping of Anthropic beta headers for each provider. Keys are input header names, values are provider-specific header names (or null if unsupported). Only headers present in mapping keys with non-null values can be forwarded.",
+ "anthropic": {
+ "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
+ "new-feature-2026-03-01": "new-feature-2026-03-01",
+ ...
+ },
+ "azure_ai": {
+ "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
+ "new-feature-2026-03-01": "new-feature-2026-03-01",
+ ...
+ },
+ "bedrock_converse": {
+ "advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
+ "new-feature-2026-03-01": null,
+ ...
+ },
+ "bedrock": {
+ "advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
+ "new-feature-2026-03-01": null,
+ ...
+ },
+ "vertex_ai": {
+ "advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
+ "new-feature-2026-03-01": null,
+ ...
+ }
+}
+```
+
+**Key Points:**
+- **Supported headers**: Set the value to the provider-specific header name (often the same as the key)
+- **Unsupported headers**: Set the value to `null`
+- **Header transformations**: Some providers use different header names (e.g., Bedrock maps `advanced-tool-use-2025-11-20` to `tool-search-tool-2025-10-19`)
+- **Alphabetical order**: Keep headers sorted alphabetically for maintainability
+
+### Step 3: Reload Configuration (No Restart Required!)
+
+**Option 1: Dynamic Reload Without Restart**
+
+Instead of restarting your application, you can dynamically reload the beta headers configuration using environment variables and API endpoints:
+
+```bash
+# Set environment variable to fetch from remote URL (Do this if you want to point it to some other URL)
+export LITELLM_ANTHROPIC_BETA_HEADERS_URL="https://raw.githubusercontent.com/BerriAI/litellm/main/litellm/anthropic_beta_headers_config.json"
+
+# Manually trigger reload via API (no restart needed!)
+curl -X POST "https://your-proxy-url/reload/anthropic_beta_headers" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+```
+
+**Option 2: Schedule Automatic Reloads**
+
+Set up automatic reloading to always stay up-to-date with the latest beta headers:
+
+```bash
+# Reload configuration every 24 hours
+curl -X POST "https://your-proxy-url/schedule/anthropic_beta_headers_reload?hours=24" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+```
+
+**Option 3: Traditional Restart**
+
+If you prefer the traditional approach, restart your LiteLLM proxy or application:
+
+```bash
+# If using LiteLLM proxy
+litellm --config config.yaml
+
+# If using Python SDK
+# Just restart your Python application
+```
+
+:::tip Zero-Downtime Updates
+With dynamic reloading, you can fix invalid beta header errors **without restarting your service**! This is especially useful in production environments where downtime is costly.
+
+See [Auto Sync Anthropic Beta Headers](../proxy/sync_anthropic_beta_headers.md) for complete documentation.
+:::
+
+## Fixing Invalid Beta Header Errors
+
+If you encounter an "invalid beta flag" error, it means a beta header is being sent that the provider doesn't support.
+
+### Step 1: Identify the Problematic Header
+
+Check your logs to see which header is causing the issue:
+
+```bash
+Error: The model returned the following errors: invalid beta flag: new-feature-2026-03-01
+```
+
+### Step 2: Update the Config
+
+Set the header value to `null` for that provider:
+
+```json title="anthropic_beta_headers_config.json"
+{
+ "bedrock_converse": {
+ "new-feature-2026-03-01": null
+ }
+}
+```
+
+### Step 3: Restart and Test
+
+Restart your application and verify the header is now filtered out.
+
+## Contributing a Fix to LiteLLM
+
+Help the community by contributing your fix!
+
+### What to Include in Your PR
+
+1. **Update the config file**: Add the new beta header to `litellm/anthropic_beta_headers_config.json`
+2. **Test your changes**: Verify the header is correctly filtered/mapped for each provider
+3. **Documentation**: Include provider documentation links showing which headers are supported
+
+### Example PR Description
+
+```markdown
+## Add support for new-feature-2026-03-01 beta header
+
+### Changes
+- Added `new-feature-2026-03-01` to anthropic_beta_headers_config.json
+- Set to `null` for bedrock_converse (unsupported)
+- Set to header name for anthropic, azure_ai (supported)
+
+### Testing
+Tested with:
+- ✅ Anthropic: Header passed through correctly
+- ✅ Azure AI: Header passed through correctly
+- ✅ Bedrock Converse: Header filtered out (returns error without fix)
+
+### References
+- Anthropic docs: [link]
+- AWS Bedrock docs: [link]
+```
+
+
+## How Beta Header Filtering Works
+
+When you make a request through LiteLLM:
+
+```mermaid
+sequenceDiagram
+ participant CC as Claude Code
+ participant LP as LiteLLM
+ participant Config as Beta Headers Config
+ participant Provider as Provider (Bedrock/Azure/etc)
+
+ CC->>LP: Request with beta headers
+ Note over CC,LP: anthropic-beta: header1,header2,header3
+
+ LP->>Config: Load header mapping for provider
+ Config-->>LP: Returns mapping (header→value or null)
+
+ Note over LP: Validate & Transform: 1. Check if header exists in mapping 2. Filter out null values 3. Map to provider-specific names
+
+ LP->>Provider: Request with filtered & mapped headers
+ Note over LP,Provider: anthropic-beta: mapped-header2 (header1, header3 filtered out)
+
+ Provider-->>LP: Success response
+ LP-->>CC: Response
+```
+
+### Filtering Rules
+
+1. **Header must exist in mapping**: Unknown headers are filtered out
+2. **Header must have non-null value**: Headers with `null` values are filtered out
+3. **Header transformation**: Headers are mapped to provider-specific names (e.g., `advanced-tool-use-2025-11-20` → `tool-search-tool-2025-10-19` for Bedrock)
+
+### Example
+
+Request with headers:
+```
+anthropic-beta: advanced-tool-use-2025-11-20,computer-use-2025-01-24,unknown-header
+```
+
+For Bedrock Converse:
+- ✅ `computer-use-2025-01-24` → `computer-use-2025-01-24` (supported, passed through)
+- ❌ `advanced-tool-use-2025-11-20` → filtered out (null value in config)
+- ❌ `unknown-header` → filtered out (not in config)
+
+Result sent to Bedrock:
+```
+anthropic-beta: computer-use-2025-01-24
+```
+
+## Dynamic Configuration Management (No Restart Required!)
+
+### Environment Variables
+
+Control how LiteLLM loads the beta headers configuration:
+
+| Variable | Description | Default |
+|----------|-------------|---------|
+| `LITELLM_ANTHROPIC_BETA_HEADERS_URL` | URL to fetch config from | GitHub main branch |
+| `LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS` | Set to `True` to use local config only | `False` |
+
+**Example: Use Custom Config URL**
+```bash
+export LITELLM_ANTHROPIC_BETA_HEADERS_URL="https://your-company.com/custom-beta-headers.json"
+```
+
+**Example: Use Local Config Only (No Remote Fetching)**
+```bash
+export LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS=True
+```
+## Provider-Specific Notes
+
+### Bedrock
+- Beta headers appear in both HTTP headers AND request body (`additionalModelRequestFields.anthropic_beta`)
+- Some headers are transformed (e.g., `advanced-tool-use` → `tool-search-tool`)
+
+### Azure AI
+- Uses same header names as Anthropic
+- Some features not yet supported (check config for null values)
+
+### Vertex AI
+- Some headers are transformed to match Vertex AI's implementation
+- Limited beta feature support compared to Anthropic
\ No newline at end of file
diff --git a/docs/my-website/docs/tutorials/claude_code_plugin_marketplace.md b/docs/my-website/docs/tutorials/claude_code_plugin_marketplace.md
index 946fb47d92a..9d93c717c4f 100644
--- a/docs/my-website/docs/tutorials/claude_code_plugin_marketplace.md
+++ b/docs/my-website/docs/tutorials/claude_code_plugin_marketplace.md
@@ -2,7 +2,7 @@ import Image from '@theme/IdealImage';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
-# Claude Code Plugin Marketplace
+# Claude Code Plugin Marketplace (Managed Skills)
LiteLLM AI Gateway acts as a central registry for Claude Code plugins. Admins can govern which plugins are available across the organization, and engineers can discover and install approved plugins from a single source.
@@ -252,7 +252,7 @@ curl -X POST http://localhost:4000/claude-code/plugins \
}'
```
-### 3. Share with Your Team
+### 3. Use in Claude Code
Send engineers the marketplace URL:
diff --git a/docs/my-website/docs/tutorials/claude_code_prompt_cache_routing.md b/docs/my-website/docs/tutorials/claude_code_prompt_cache_routing.md
new file mode 100644
index 00000000000..bbb29489856
--- /dev/null
+++ b/docs/my-website/docs/tutorials/claude_code_prompt_cache_routing.md
@@ -0,0 +1,43 @@
+# Claude Code - Prompt Cache Routing
+
+Claude's [Prompt Caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) feature helps to optimize API usage through attempting to cache prompts and re-use cached prompts during subsequent API calls. This feature is used by Claude Code.
+
+When LiteLLM [load balancing](../proxy/load_balancing.md) is enabled, to ensure this prompt caching feature still works with Claude Code, LiteLLM needs to be configured to use the `PromptCachingDeploymentCheck` pre-call check. This pre-call check will ensure that API calls that used prompt caching are remembered and that subsequent API calls that try to use that prompt caching are routed to the same model deployment where a cache write occurred.
+
+## Set Up
+
+1. Configure the router so that it uses the `PromptCachingDeploymentCheck` (via setting the `optional_pre_call_checks` property), and configure the models so that they can access multiple deployments of Claude; below, we show an example for multiple AWS accounts (referred to as `account-1` and `account-2`, using the `aws_profile_name` property):
+```yaml
+router_settings:
+ optional_pre_call_checks: ["prompt_caching"]
+
+model_list:
+- litellm_params:
+ model: us.anthropic.claude-sonnet-4-5-20250929-v1:0
+ aws_profile_name: account-1
+ aws_region_name: us-west-2
+ model_info:
+ litellm_provider: bedrock
+ model_name: us.anthropic.claude-sonnet-4-5-20250929-v1:0
+- litellm_params:
+ model: us.anthropic.claude-sonnet-4-5-20250929-v1:0
+ aws_profile_name: account-2
+ aws_region_name: us-west-2
+ model_info:
+ litellm_provider: bedrock
+ model_name: us.anthropic.claude-sonnet-4-5-20250929-v1:0
+```
+2. Utilize Claude Code:
+ 1. Launch Claude Code, which will do a warm-up API call that tries to cache its warm-up prompt and its system prompt.
+ 2. Wait a few seconds, then quit Claude Code and re-open it.
+ 3. You'll notice that the warm-up API call successfully gets a cache hit (if using Claude Code in an IDE like VS Code, ensure that you don't do anything between step 2.1 and 2.2 here, otherwise there may not be a cache hit):
+ 1. Go to the [LiteLLM Request Logs page](../proxy/ui_logs.md) in the Admin UI
+ 2. Click on the individual requests to see (a) the cache creation and cache read tokens; and (b) the Model ID. In particular, the API call from step 2.1 should show a cache write, and the API call from step 2.2 should show a cache read; in addition, the Model ID should be equal (meaning the API call is getting forwarded to the same AWS account).
+
+## Related
+
+- [Claude Code - Quickstart](./claude_responses_api.md)
+- [Claude Code - Customer Tracking](./claude_code_customer_tracking.md)
+- [Claude Code - Plugin Marketplace](./claude_code_plugin_marketplace.md)
+- [Claude Code - WebSearch](./claude_code_websearch.md)
+- [Proxy - Load Balancing](../proxy/load_balancing.md)
diff --git a/docs/my-website/docs/tutorials/claude_mcp.md b/docs/my-website/docs/tutorials/claude_mcp.md
index 07c3cead0be..ab27908c8db 100644
--- a/docs/my-website/docs/tutorials/claude_mcp.md
+++ b/docs/my-website/docs/tutorials/claude_mcp.md
@@ -9,7 +9,7 @@ Note: LiteLLM supports OAuth for MCP servers as well. [Learn more](https://docs.
## Connecting MCP Servers
-You can also connect MCP servers to Claude Code via LiteLLM Proxy.
+You can connect MCP servers to Claude Code via LiteLLM Proxy.
1. Add the MCP server to your `config.yaml`
@@ -23,6 +23,7 @@ In this example, we'll add the Github MCP server to our `config.yaml`
mcp_servers:
github_mcp:
url: "https://api.githubcopilot.com/mcp"
+ transport: "http"
auth_type: oauth2
client_id: os.environ/GITHUB_OAUTH_CLIENT_ID
client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET
@@ -34,31 +35,70 @@ mcp_servers:
In this example, we'll add the Atlassian MCP server to our `config.yaml`
```yaml title="config.yaml" showLineNumbers
-atlassian_mcp:
- server_id: atlassian_mcp_id
- url: "https://mcp.atlassian.com/v1/sse"
- transport: "sse"
- auth_type: oauth2
+mcp_servers:
+ atlassian_mcp:
+ url: "https://mcp.atlassian.com/v1/mcp"
+ transport: "http"
+ auth_type: oauth2
```
+:::important
+The server name under `mcp_servers:` (e.g. `atlassian_mcp`, `github_mcp`) **must match** the name used in the Claude Code URL path (`/mcp/`). A mismatch will cause a 404 error during OAuth.
+:::
+
2. Start LiteLLM Proxy
+Since Claude Code needs a publicly accessible URL for the OAuth callback, expose your proxy via ngrok or a similar tool.
+
```bash
litellm --config /path/to/config.yaml
# RUNNING on http://0.0.0.0:4000
```
-3. Use the MCP server in Claude Code
-
```bash
-claude mcp add --transport http litellm_proxy http://0.0.0.0:4000/github_mcp/mcp --header "Authorization: Bearer sk-LITELLM_VIRTUAL_KEY"
+# In a separate terminal — expose proxy for OAuth callbacks
+ngrok http 4000
```
-For MCP servers that require dynamic client registration (such as Atlassian), please set `x-litellm-api-key: Bearer sk-LITELLM_VIRTUAL_KEY` instead of using `Authorization: Bearer LITELLM_VIRTUAL_KEY`.
+3. Add the MCP server to Claude Code
+
+
+
+
+```bash
+claude mcp add --transport http litellm-github https://your-ngrok-url.ngrok-free.dev/mcp/github_mcp \
+ --header "x-litellm-api-key: Bearer sk-1234"
+```
+
+
+
+
+```bash
+claude mcp add --transport http litellm-atlassian https://your-ngrok-url.ngrok-free.dev/mcp/atlassian_mcp \
+ --header "x-litellm-api-key: Bearer sk-1234"
+```
+
+
+
+
+**Parameter breakdown:**
+
+| Parameter | Description |
+|-----------|-------------|
+| `--transport http` | Use HTTP transport for the MCP connection |
+| `litellm-atlassian` | The name for this MCP server **on Claude Code** — can be anything you choose |
+| `https://your-ngrok-url.ngrok-free.dev/mcp/atlassian_mcp` | The LiteLLM proxy URL. Format: `/mcp/`. The `atlassian_mcp` part **must match** the key under `mcp_servers:` in your LiteLLM proxy config |
+| `--header "x-litellm-api-key: Bearer sk-1234"` | Your LiteLLM virtual key for authentication to the proxy |
+
+You can also add the MCP server directly to your `~/.claude.json` file instead of using `claude mcp add`. [See Claude Code docs](https://docs.anthropic.com/en/docs/claude-code/mcp).
+
+:::note
+For MCP servers that require OAuth (such as Atlassian), use `x-litellm-api-key` instead of `Authorization` for the LiteLLM virtual key. The `Authorization` header is reserved for the OAuth flow.
+:::
4. Authenticate via Claude Code
@@ -68,24 +108,20 @@ a. Start Claude Code
claude
```
-b. Authenticate via Claude Code
+b. Open the MCP menu
```bash
/mcp
```
-c. Select the MCP server
+c. Select the MCP server (e.g. `litellm-atlassian`)
-```bash
-> litellm_proxy
-```
-
-d. Start Oauth flow via Claude Code
+d. Start the OAuth flow
```bash
> 1. Authenticate
2. Reconnect
- 3. Disable
+ 3. Disable
```
e. Once completed, you should see this success message:
diff --git a/docs/my-website/docs/tutorials/copilotkit_sdk.md b/docs/my-website/docs/tutorials/copilotkit_sdk.md
new file mode 100644
index 00000000000..fc4db8bfe3e
--- /dev/null
+++ b/docs/my-website/docs/tutorials/copilotkit_sdk.md
@@ -0,0 +1,99 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# CopilotKit SDK with LiteLLM
+
+Use CopilotKit SDK with any LLM provider through LiteLLM Proxy.
+
+> **Note:** CopilotKit SDK integration with LiteLLM Proxy works with LiteLLM v1.81.7-nightly or higher.
+
+
+## Quick Start
+
+### 1. Add Model to Config
+
+```yaml title="config.yaml"
+model_list:
+ - model_name: claude-sonnet-4-5
+ litellm_params:
+ model: "anthropic/claude-sonnet-4-5-20250514-v1:0"
+ api_key: "os.environ/ANTHROPIC_API_KEY"
+```
+
+### 2. Start LiteLLM Proxy
+
+```bash
+litellm --config config.yaml
+```
+
+### 3. Use CopilotKit SDK
+
+```typescript
+import OpenAI from "openai";
+import {
+ CopilotRuntime,
+ OpenAIAdapter,
+ copilotRuntimeNextJSAppRouterEndpoint,
+} from "@copilotkit/runtime";
+import { NextRequest } from "next/server";
+
+const model = "claude-sonnet-4-5";
+
+const openai = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY || "sk-12345",
+ baseURL: process.env.OPENAI_BASE_URL || "http://localhost:4000/v1",
+});
+
+const serviceAdapter = new OpenAIAdapter({ openai, model });
+const runtime = new CopilotRuntime();
+
+export const POST = async (req: NextRequest) => {
+ const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
+ runtime,
+ serviceAdapter,
+ endpoint: "/api/copilotkit",
+ });
+ return handleRequest(req);
+};
+```
+
+### 4. Test
+
+```bash
+curl -X POST http://localhost:3000/api/copilotkit \
+ -H "Content-Type: application/json" \
+ -d '{
+ "method": "agent/run",
+ "params": {
+ "agentId": "default"
+ },
+ "runId": "your_run_id",
+ "threadId": "your_thread_id",
+ "runId": ""your_run_id"",
+ "tools": [],
+ "context": [],
+ "forwardedProps": {},
+ "state": {},
+ "messages": [
+ {
+ "id": "166e573e-f7c6-4c0f-8685-04dbefec18be",
+ "content": "Hi",
+ "role": "user"
+ }
+ ]
+ }
+}'
+```
+
+## Environment Variables
+
+| Variable | Value | Description |
+|----------|-------|-------------|
+| `OPENAI_API_KEY` | `sk-12345` | Your LiteLLM API key |
+| `OPENAI_BASE_URL` | `http://localhost:4000/v1` | LiteLLM proxy URL |
+
+
+## Related Resources
+
+- [CopilotKit Documentation](https://docs.copilotkit.ai)
+- [LiteLLM Proxy Quick Start](../proxy/quick_start)
diff --git a/docs/my-website/docs/tutorials/livekit_xai_realtime.md b/docs/my-website/docs/tutorials/livekit_xai_realtime.md
new file mode 100644
index 00000000000..1d70186382f
--- /dev/null
+++ b/docs/my-website/docs/tutorials/livekit_xai_realtime.md
@@ -0,0 +1,190 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# LiveKit xAI Realtime Voice Agent
+
+Use LiveKit's xAI Grok Voice Agent plugin with LiteLLM Proxy to build low-latency voice AI agents.
+
+The LiveKit Agents framework provides tools for building real-time voice and video AI applications. By routing through LiteLLM Proxy, you get unified access to multiple realtime voice providers, cost tracking, rate limiting, and more.
+
+## Quick Start
+
+### 1. Install Dependencies
+
+```bash
+pip install livekit-agents[xai]
+```
+
+### 2. Start LiteLLM Proxy
+
+Create a config file with your xAI realtime model:
+
+```yaml title="config.yaml" showLineNumbers
+model_list:
+ - model_name: grok-voice-agent
+ litellm_params:
+ model: xai/grok-2-vision-1212
+ api_key: os.environ/XAI_API_KEY
+ model_info:
+ mode: realtime
+
+litellm_settings:
+ drop_params: True
+
+general_settings:
+ master_key: sk-1234 # Change this to a secure key
+```
+
+Start the proxy:
+
+```bash
+litellm --config config.yaml --port 4000
+```
+
+### 3. Configure LiveKit xAI Plugin
+
+Point LiveKit's xAI plugin to your LiteLLM proxy:
+
+```python
+from livekit.plugins import xai
+
+# Configure xAI to use LiteLLM proxy
+model = xai.realtime.RealtimeModel(
+ voice="ara", # Voice option
+ api_key="sk-1234", # Your LiteLLM proxy master key
+ base_url="http://localhost:4000", # LiteLLM proxy URL
+)
+```
+
+## Complete Example
+
+Here's a complete working example:
+
+
+
+
+```python
+#!/usr/bin/env python3
+"""
+Simple xAI realtime voice agent through LiteLLM proxy.
+"""
+import asyncio
+import json
+import websockets
+
+PROXY_URL = "ws://localhost:4000/v1/realtime"
+API_KEY = "sk-1234"
+MODEL = "grok-voice-agent"
+
+async def run_voice_agent():
+ """Connect to xAI realtime API through LiteLLM proxy"""
+ url = f"{PROXY_URL}?model={MODEL}"
+ headers = {"Authorization": f"Bearer {API_KEY}"}
+
+ async with websockets.connect(url, extra_headers=headers) as ws:
+ # Wait for initial connection event
+ initial = json.loads(await ws.recv())
+ print(f"✅ Connected: {initial['type']}")
+
+ # Send user message
+ await ws.send(json.dumps({
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [{
+ "type": "input_text",
+ "text": "Hello! Tell me a joke."
+ }]
+ }
+ }))
+
+ # Request response
+ await ws.send(json.dumps({
+ "type": "response.create",
+ "response": {"modalities": ["text", "audio"]}
+ }))
+
+ # Collect response
+ transcript = []
+ async for message in ws:
+ event = json.loads(message)
+
+ # Capture text response
+ if event['type'] == 'response.output_audio_transcript.delta':
+ transcript.append(event['delta'])
+ print(event['delta'], end='', flush=True)
+
+ # Done when response completes
+ elif event['type'] == 'response.done':
+ break
+
+ print(f"\n\n✅ Full response: {''.join(transcript)}")
+
+if __name__ == "__main__":
+ asyncio.run(run_voice_agent())
+```
+
+
+
+
+
+```python
+from livekit.agents import Agent, AgentSession, WorkerOptions, cli
+from livekit.plugins import xai
+
+class VoiceAgent(Agent):
+ def __init__(self):
+ super().__init__(
+ instructions="You are a helpful voice assistant.",
+ llm=xai.realtime.RealtimeModel(
+ voice="ara",
+ api_key="sk-1234",
+ base_url="http://localhost:4000",
+ ),
+ )
+
+if __name__ == "__main__":
+ cli.run_app(
+ WorkerOptions(
+ agent_factory=VoiceAgent,
+ )
+ )
+```
+
+
+
+
+## Running the Example
+
+1. **Start LiteLLM Proxy** (if not already running):
+ ```bash
+ litellm --config config.yaml --port 4000
+ ```
+
+2. **Run the example**:
+ ```bash
+ python your_script.py
+ ```
+
+## Expected Output
+
+```
+✅ Connected: conversation.created
+Hello! Here's a joke for you: Why don't scientists trust atoms?
+Because they make up everything!
+
+✅ Full response: Hello! Here's a joke for you: Why don't scientists trust atoms? Because they make up everything!
+```
+
+
+## Complete Working Example
+
+**[LiveKit Agent SDK Cookbook](https://github.com/BerriAI/litellm/tree/main/cookbook/livekit_agent_sdk)**
+
+
+## Learn More
+
+- [xAI Realtime API](/docs/providers/xai_realtime)
+- [LiveKit xAI Plugin](https://docs.livekit.io/agents/models/realtime/plugins/xai/)
+- [LiteLLM Realtime API](/docs/realtime)
diff --git a/docs/my-website/docs/tutorials/opencode_integration.md b/docs/my-website/docs/tutorials/opencode_integration.md
index 4c1e03f3dff..e55367833f2 100644
--- a/docs/my-website/docs/tutorials/opencode_integration.md
+++ b/docs/my-website/docs/tutorials/opencode_integration.md
@@ -270,9 +270,6 @@ model_list:
litellm_params:
model: deepseek/deepseek-chat
api_key: os.environ/DEEPSEEK_API_KEY
-
-litellm_settings:
- master_key: os.environ/LITELLM_MASTER_KEY
```
## Troubleshooting
diff --git a/docs/my-website/img/a2a_agent_spend.png b/docs/my-website/img/a2a_agent_spend.png
new file mode 100644
index 00000000000..15ec769392a
Binary files /dev/null and b/docs/my-website/img/a2a_agent_spend.png differ
diff --git a/docs/my-website/img/a2a_trace_grouping.png b/docs/my-website/img/a2a_trace_grouping.png
new file mode 100644
index 00000000000..05130420aae
Binary files /dev/null and b/docs/my-website/img/a2a_trace_grouping.png differ
diff --git a/docs/my-website/img/okta_access_policies.png b/docs/my-website/img/okta_access_policies.png
new file mode 100644
index 00000000000..e09adc2ce7f
Binary files /dev/null and b/docs/my-website/img/okta_access_policies.png differ
diff --git a/docs/my-website/img/okta_authorization_server.png b/docs/my-website/img/okta_authorization_server.png
new file mode 100644
index 00000000000..bddb3e07a4a
Binary files /dev/null and b/docs/my-website/img/okta_authorization_server.png differ
diff --git a/docs/my-website/img/okta_client_credentials.png b/docs/my-website/img/okta_client_credentials.png
new file mode 100644
index 00000000000..a00a9f4657e
Binary files /dev/null and b/docs/my-website/img/okta_client_credentials.png differ
diff --git a/docs/my-website/img/okta_redirect_uri.png b/docs/my-website/img/okta_redirect_uri.png
new file mode 100644
index 00000000000..a1e58560c72
Binary files /dev/null and b/docs/my-website/img/okta_redirect_uri.png differ
diff --git a/docs/my-website/img/okta_security_api.png b/docs/my-website/img/okta_security_api.png
new file mode 100644
index 00000000000..7f9e218074c
Binary files /dev/null and b/docs/my-website/img/okta_security_api.png differ
diff --git a/docs/my-website/img/policy_team_attach.png b/docs/my-website/img/policy_team_attach.png
new file mode 100644
index 00000000000..4e337931ed8
Binary files /dev/null and b/docs/my-website/img/policy_team_attach.png differ
diff --git a/docs/my-website/img/policy_test_matching.png b/docs/my-website/img/policy_test_matching.png
new file mode 100644
index 00000000000..5d024ae78b4
Binary files /dev/null and b/docs/my-website/img/policy_test_matching.png differ
diff --git a/docs/my-website/img/release_notes/guard_actions.png b/docs/my-website/img/release_notes/guard_actions.png
new file mode 100644
index 00000000000..ef705828188
Binary files /dev/null and b/docs/my-website/img/release_notes/guard_actions.png differ
diff --git a/docs/my-website/img/release_notes/mcp_internet.png b/docs/my-website/img/release_notes/mcp_internet.png
new file mode 100644
index 00000000000..d24d2a20870
Binary files /dev/null and b/docs/my-website/img/release_notes/mcp_internet.png differ
diff --git a/docs/my-website/img/ui_access_groups.png b/docs/my-website/img/ui_access_groups.png
new file mode 100644
index 00000000000..484f6c852fc
Binary files /dev/null and b/docs/my-website/img/ui_access_groups.png differ
diff --git a/docs/my-website/img/ui_granular_router_settings.png b/docs/my-website/img/ui_granular_router_settings.png
new file mode 100644
index 00000000000..6242679956c
Binary files /dev/null and b/docs/my-website/img/ui_granular_router_settings.png differ
diff --git a/docs/my-website/img/ui_spend_logs_settings.png b/docs/my-website/img/ui_spend_logs_settings.png
new file mode 100644
index 00000000000..334f5b1d93e
Binary files /dev/null and b/docs/my-website/img/ui_spend_logs_settings.png differ
diff --git a/docs/my-website/img/ui_team_soft_budget_alerts.png b/docs/my-website/img/ui_team_soft_budget_alerts.png
new file mode 100644
index 00000000000..9627b5f1daa
Binary files /dev/null and b/docs/my-website/img/ui_team_soft_budget_alerts.png differ
diff --git a/docs/my-website/img/ui_team_soft_budget_email_example.png b/docs/my-website/img/ui_team_soft_budget_email_example.png
new file mode 100644
index 00000000000..0cd83487112
Binary files /dev/null and b/docs/my-website/img/ui_team_soft_budget_email_example.png differ
diff --git a/docs/my-website/img/ui_tools.png b/docs/my-website/img/ui_tools.png
new file mode 100644
index 00000000000..6f4d0f87410
Binary files /dev/null and b/docs/my-website/img/ui_tools.png differ
diff --git a/docs/my-website/package-lock.json b/docs/my-website/package-lock.json
index 419211cca02..3ba42bc5023 100644
--- a/docs/my-website/package-lock.json
+++ b/docs/my-website/package-lock.json
@@ -20455,6 +20455,13 @@
"url": "https://opencollective.com/webpack"
}
},
+ "node_modules/search-insights": {
+ "version": "2.17.3",
+ "resolved": "https://registry.npmjs.org/search-insights/-/search-insights-2.17.3.tgz",
+ "integrity": "sha512-RQPdCYTa8A68uM2jwxoY842xDhvx3E5LFL1LxvxCNMev4o5mLuokczhzjAgGwUZBAmOKZknArSxLKmXtIi2AxQ==",
+ "license": "MIT",
+ "peer": true
+ },
"node_modules/section-matter": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz",
diff --git a/docs/my-website/package.json b/docs/my-website/package.json
index 4c3db680565..4af7a168f83 100644
--- a/docs/my-website/package.json
+++ b/docs/my-website/package.json
@@ -61,6 +61,8 @@
"mermaid": ">=11.10.0",
"gray-matter": "4.0.3",
"glob": ">=11.1.0",
+ "tar": ">=7.5.7",
+ "@isaacs/brace-expansion": ">=5.0.1",
"node-forge": ">=1.3.2",
"mdast-util-to-hast": ">=13.2.1",
"lodash-es": ">=4.17.23"
diff --git a/docs/my-website/release_notes/v1.81.0/index.md b/docs/my-website/release_notes/v1.81.0/index.md
index 88ac240c614..e61d7d2d593 100644
--- a/docs/my-website/release_notes/v1.81.0/index.md
+++ b/docs/my-website/release_notes/v1.81.0/index.md
@@ -1,5 +1,5 @@
---
-title: "v1.81.0 - Claude Code - Web Search Across All Providers"
+title: "v1.81.0-stable - Claude Code - Web Search Across All Providers"
slug: "v1-81-0"
date: 2026-01-18T10:00:00
authors:
@@ -27,7 +27,7 @@ import TabItem from '@theme/TabItem';
docker run \
-e STORE_MODEL_IN_DB=True \
-p 4000:4000 \
-docker.litellm.ai/berriai/litellm:v1.81.0.rc.1
+docker.litellm.ai/berriai/litellm:v1.81.0-stable
```
@@ -62,7 +62,7 @@ This means you can now use Claude Code's web search tool with any provider, not
Proxy Admins can configure web search interception in their LiteLLM proxy config to enable this capability for their teams using Claude Code with Bedrock, Azure, or any other supported provider.
-[**Learn more →**](../../docs/tutorials/claude_code_websearch.md)
+[**Learn more →**](https://docs.litellm.ai/docs/tutorials/claude_code_websearch)
---
diff --git a/docs/my-website/release_notes/v1.81.12.md b/docs/my-website/release_notes/v1.81.12.md
new file mode 100644
index 00000000000..c68b23488c0
--- /dev/null
+++ b/docs/my-website/release_notes/v1.81.12.md
@@ -0,0 +1,433 @@
+---
+title: "[Preview] v1.81.12 - Guardrail Policy Templates & Action Builder"
+slug: "v1-81-12"
+date: 2026-02-14T00:00:00
+authors:
+ - name: Krrish Dholakia
+ title: CEO, LiteLLM
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: CTO, LiteLLM
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+hide_table_of_contents: false
+---
+
+## Deploy this version
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import Image from '@theme/IdealImage';
+
+
+
+
+``` showLineNumbers title="docker run litellm"
+docker run \
+-e STORE_MODEL_IN_DB=True \
+-p 4000:4000 \
+ghcr.io/berriai/litellm:main-v1.81.12.rc.1
+```
+
+
+
+
+``` showLineNumbers title="pip install litellm"
+pip install litellm==1.81.12.rc1
+```
+
+
+
+
+## Key Highlights
+
+- **Policy Templates** - [Pre-configured guardrail policy templates for common safety and compliance use-cases (including NSFW, toxic content, and child safety)](../../docs/proxy/guardrails/policy_templates)
+- **Guardrail Action Builder** - [Build and customize guardrail policy flows with the new action-builder UI and conditional execution support](../../docs/proxy/guardrails/policy_templates)
+- **MCP OAuth2 M2M + Tracing** - [Add machine-to-machine OAuth2 support for MCP servers and OpenTelemetry tracing for MCP calls through AI Gateway](../../docs/mcp)
+- **Responses API `shell` Tool & `context_management` support** - [Server-side context management (compaction) and Shell tool support for the OpenAI Responses API](../../docs/response_api)
+- **Access Groups** - [Create access groups to manage model, MCP server, and agent access across teams and keys](../../docs/proxy/access_groups)
+- **50+ New Bedrock Regional Model Entries** - DeepSeek V3.2, MiniMax M2.1, Kimi K2.5, Qwen3 Coder Next, and NVIDIA Nemotron Nano across multiple regions
+- **Add Semgrep & fix OOMs** - [Static analysis rules and out-of-memory fixes](#add-semgrep--fix-ooms) - [PR #20912](https://github.com/BerriAI/litellm/pull/20912)
+
+---
+
+## Add Semgrep & fix OOMs
+
+This release fixes out-of-memory (OOM) risks from unbounded `asyncio.Queue()` usage. Log queues (e.g. GCS bucket) and DB spend-update queues were previously unbounded and could grow without limit under load. They now use a configurable max size (`LITELLM_ASYNCIO_QUEUE_MAXSIZE`, default 1000); when full, queues flush immediately to make room instead of growing memory. A Semgrep rule (`.semgrep/rules/python/unbounded-memory.yml`) was added to flag similar unbounded-memory patterns in future code. [PR #20912](https://github.com/BerriAI/litellm/pull/20912)
+
+---
+
+## Guardrail Action Builder
+
+This release adds a visual action builder for guardrail policies with conditional execution support. You can now chain guardrails into multi-step pipelines — if a simple guardrail fails, route to an advanced one instead of immediately blocking. Each step has configurable ON PASS and ON FAIL actions (Next Step, Block, or Allow), and you can test the full pipeline with a sample message before saving.
+
+
+
+### Access Groups
+
+Access Groups simplify defining resource access across your organization. One group can grant access to models, MCP servers, and agents—simply attach it to a key or team. Create groups in the Admin UI, define which resources each group includes, then assign the group when creating keys or teams. Updates to a group apply automatically to all attached keys and teams.
+
+
+
+## New Providers and Endpoints
+
+### New Providers (2 new providers)
+
+| Provider | Supported LiteLLM Endpoints | Description |
+| -------- | --------------------------- | ----------- |
+| [Scaleway](../../docs/providers/scaleway) | `/chat/completions` | Scaleway Generative APIs for chat completions |
+| [Sarvam AI](../../docs/providers/sarvam) | `/chat/completions`, `/audio/transcriptions`, `/audio/speech` | Sarvam AI STT and TTS support for Indian languages |
+
+---
+
+## New Models / Updated Models
+
+#### New Model Support (19 highlighted models)
+
+| Provider | Model | Context Window | Input ($/1M tokens) | Output ($/1M tokens) |
+| -------- | ----- | -------------- | ------------------- | -------------------- |
+| AWS Bedrock | `deepseek.v3.2` | 164K | $0.62 | $1.85 |
+| AWS Bedrock | `minimax.minimax-m2.1` | 196K | $0.30 | $1.20 |
+| AWS Bedrock | `moonshotai.kimi-k2.5` | 262K | $0.60 | $3.00 |
+| AWS Bedrock | `moonshotai.kimi-k2-thinking` | 262K | $0.73 | $3.03 |
+| AWS Bedrock | `qwen.qwen3-coder-next` | 262K | $0.50 | $1.20 |
+| AWS Bedrock | `nvidia.nemotron-nano-3-30b` | 262K | $0.06 | $0.24 |
+| Azure AI | `azure_ai/kimi-k2.5` | 262K | $0.60 | $3.00 |
+| Vertex AI | `vertex_ai/zai-org/glm-5-maas` | 200K | $1.00 | $3.20 |
+| MiniMax | `minimax/MiniMax-M2.5` | 1M | $0.30 | $1.20 |
+| MiniMax | `minimax/MiniMax-M2.5-lightning` | 1M | $0.30 | $2.40 |
+| Dashscope | `dashscope/qwen3-max` | 258K | Tiered pricing | Tiered pricing |
+| Perplexity | `perplexity/preset/pro-search` | - | Per-request | Per-request |
+| Perplexity | `perplexity/openai/gpt-4o` | - | Per-request | Per-request |
+| Perplexity | `perplexity/openai/gpt-5.2` | - | Per-request | Per-request |
+| Vercel AI Gateway | `vercel_ai_gateway/anthropic/claude-opus-4.6` | 200K | $5.00 | $25.00 |
+| Vercel AI Gateway | `vercel_ai_gateway/anthropic/claude-sonnet-4` | 200K | $3.00 | $15.00 |
+| Vercel AI Gateway | `vercel_ai_gateway/anthropic/claude-haiku-4.5` | 200K | $1.00 | $5.00 |
+| Sarvam AI | `sarvam/sarvam-m` | 8K | Free tier | Free tier |
+| Anthropic | `fast/claude-opus-4-6` | 1M | $30.00 | $150.00 |
+
+*Note: AWS Bedrock models are available across multiple regions (us-east-1, us-east-2, us-west-2, eu-central-1, eu-north-1, ap-northeast-1, ap-south-1, ap-southeast-3, sa-east-1). 54 regional model entries were added in total.*
+
+#### Features
+
+- **[Anthropic](../../docs/providers/anthropic)**
+ - Enable non-tool structured outputs on Claude Opus 4.5 and 4.6 using `output_format` param - [PR #20548](https://github.com/BerriAI/litellm/pull/20548)
+ - Add support for `anthropic_messages` call type in prompt caching - [PR #19233](https://github.com/BerriAI/litellm/pull/19233)
+ - Managing Anthropic Beta Headers with remote URL fetching - [PR #20935](https://github.com/BerriAI/litellm/pull/20935), [PR #21110](https://github.com/BerriAI/litellm/pull/21110)
+ - Remove `x-anthropic-billing` block - [PR #20951](https://github.com/BerriAI/litellm/pull/20951)
+ - Use Authorization Bearer for OAuth tokens instead of x-api-key - [PR #21039](https://github.com/BerriAI/litellm/pull/21039)
+ - Filter unsupported JSON schema constraints for structured outputs - [PR #20813](https://github.com/BerriAI/litellm/pull/20813)
+ - New Claude Opus 4.6 features for `/v1/messages` - [PR #20733](https://github.com/BerriAI/litellm/pull/20733)
+ - Fix `reasoning_effort=None` and `"none"` should return None for Opus 4.6 - [PR #20800](https://github.com/BerriAI/litellm/pull/20800)
+
+- **[AWS Bedrock](../../docs/providers/bedrock)**
+ - Extend model support with 4 new beta models - [PR #21035](https://github.com/BerriAI/litellm/pull/21035)
+ - Add Claude Opus 4.6 to `_supports_tool_search_on_bedrock` - [PR #21017](https://github.com/BerriAI/litellm/pull/21017)
+ - Correct Bedrock Claude Opus 4.6 model IDs (remove `:0` suffix) - [PR #20564](https://github.com/BerriAI/litellm/pull/20564), [PR #20671](https://github.com/BerriAI/litellm/pull/20671)
+ - Add `output_config` as supported param - [PR #20748](https://github.com/BerriAI/litellm/pull/20748)
+
+- **[Vertex AI](../../docs/providers/vertex)**
+ - Add Vertex GLM-5 model support - [PR #21053](https://github.com/BerriAI/litellm/pull/21053)
+ - Propagate `extra_headers` anthropic-beta to request body - [PR #20666](https://github.com/BerriAI/litellm/pull/20666)
+ - Preserve `usageMetadata` in `_hidden_params` - [PR #20559](https://github.com/BerriAI/litellm/pull/20559)
+ - Map `IMAGE_PROHIBITED_CONTENT` to `content_filter` - [PR #20524](https://github.com/BerriAI/litellm/pull/20524)
+ - Add RAG ingest for Vertex AI - [PR #21120](https://github.com/BerriAI/litellm/pull/21120)
+
+- **[OCI / Cohere](../../docs/providers/cohere)**
+ - OCI Cohere responseFormat/Pydantic support - [PR #20663](https://github.com/BerriAI/litellm/pull/20663)
+ - Fix OCI Cohere system messages by populating `preambleOverride` - [PR #20958](https://github.com/BerriAI/litellm/pull/20958)
+
+- **[Perplexity](../../docs/providers/perplexity)**
+ - Perplexity Research API support with preset search - [PR #20860](https://github.com/BerriAI/litellm/pull/20860)
+
+- **[MiniMax](../../docs/providers/minimax)**
+ - Add MiniMax-M2.5 and MiniMax-M2.5-lightning models - [PR #21054](https://github.com/BerriAI/litellm/pull/21054)
+
+- **[Kimi / Moonshot](../../docs/providers/moonshot)**
+ - Add Kimi model pricing by region - [PR #20855](https://github.com/BerriAI/litellm/pull/20855)
+ - Add `moonshotai.kimi-k2.5` - [PR #20863](https://github.com/BerriAI/litellm/pull/20863)
+
+- **[Dashscope](../../docs/providers/dashscope)**
+ - Add `dashscope/qwen3-max` model with tiered pricing - [PR #20919](https://github.com/BerriAI/litellm/pull/20919)
+
+- **[Vercel AI Gateway](../../docs/providers/vercel_ai_gateway)**
+ - Add new Vercel AI Anthropic models - [PR #20745](https://github.com/BerriAI/litellm/pull/20745)
+
+- **[Azure AI](../../docs/providers/azure_ai)**
+ - Add `azure_ai/kimi-k2.5` to Azure model DB - [PR #20896](https://github.com/BerriAI/litellm/pull/20896)
+ - Support Azure AD token auth for non-Claude azure_ai models - [PR #20981](https://github.com/BerriAI/litellm/pull/20981)
+ - Fix Azure batches issues - [PR #21092](https://github.com/BerriAI/litellm/pull/21092)
+
+- **[DeepSeek](../../docs/providers/deepseek)**
+ - Sync DeepSeek model metadata and add bare-name fallback - [PR #20938](https://github.com/BerriAI/litellm/pull/20938)
+
+- **[Gemini](../../docs/providers/gemini)**
+ - Handle image in assistant message for Gemini - [PR #20845](https://github.com/BerriAI/litellm/pull/20845)
+ - Add missing tpm/rpm for Gemini models - [PR #21175](https://github.com/BerriAI/litellm/pull/21175)
+
+- **General**
+ - Add 30 missing models to pricing JSON - [PR #20797](https://github.com/BerriAI/litellm/pull/20797)
+ - Cleanup 39 deprecated OpenRouter models - [PR #20786](https://github.com/BerriAI/litellm/pull/20786)
+ - Standardize endpoint `display_name` naming convention - [PR #20791](https://github.com/BerriAI/litellm/pull/20791)
+ - Fix and stabilize model cost map formatting - [PR #20895](https://github.com/BerriAI/litellm/pull/20895)
+ - Export `PermissionDeniedError` from `litellm.__init__` - [PR #20960](https://github.com/BerriAI/litellm/pull/20960)
+
+### Bug Fixes
+
+- **[Anthropic](../../docs/providers/anthropic)**
+ - Fix `get_supported_anthropic_messages_params` - [PR #20752](https://github.com/BerriAI/litellm/pull/20752)
+ - Fix `base_model` name for body and deployment name in URL - [PR #20747](https://github.com/BerriAI/litellm/pull/20747)
+
+- **[Azure](../../docs/providers/azure/azure)**
+ - Preserve `content_policy_violation` error details from Azure OpenAI - [PR #20883](https://github.com/BerriAI/litellm/pull/20883)
+
+- **[Vertex AI](../../docs/providers/vertex)**
+ - Fix Gemini multi-turn tool calling message formatting (added and reverted) - [PR #20569](https://github.com/BerriAI/litellm/pull/20569), [PR #21051](https://github.com/BerriAI/litellm/pull/21051)
+
+---
+
+## LLM API Endpoints
+
+#### Features
+
+- **[Responses API](../../docs/response_api)**
+ - Add server-side context management (compaction) support - [PR #21058](https://github.com/BerriAI/litellm/pull/21058)
+ - Add Shell tool support for OpenAI Responses API - [PR #21063](https://github.com/BerriAI/litellm/pull/21063)
+ - Preserve tool call argument deltas when streaming id is omitted - [PR #20712](https://github.com/BerriAI/litellm/pull/20712)
+ - Preserve interleaved thinking/redacted_thinking blocks during streaming - [PR #20702](https://github.com/BerriAI/litellm/pull/20702)
+
+- **[Chat Completions](../../docs/completion/input)**
+ - Add Web Search support using LiteLLM `/search` (web search interception hook) - [PR #20483](https://github.com/BerriAI/litellm/pull/20483)
+ - Preserved nullable object fields by carrying schema properties - [PR #19132](https://github.com/BerriAI/litellm/pull/19132)
+ - Support `prompt_cache_key` for OpenAI and Azure chat completions - [PR #20989](https://github.com/BerriAI/litellm/pull/20989)
+
+- **[Pass-Through Endpoints](../../docs/pass_through/bedrock)**
+ - Add support for `langchain_aws` via LiteLLM passthrough - [PR #20843](https://github.com/BerriAI/litellm/pull/20843)
+ - Add `custom_body` parameter to `endpoint_func` in `create_pass_through_route` - [PR #20849](https://github.com/BerriAI/litellm/pull/20849)
+
+- **[Vector Stores](../../docs/providers/openai)**
+ - Add `target_model_names` for vector store endpoints - [PR #21089](https://github.com/BerriAI/litellm/pull/21089)
+
+- **General**
+ - Add `output_config` as supported param - [PR #20748](https://github.com/BerriAI/litellm/pull/20748)
+ - Add managed error file support - [PR #20838](https://github.com/BerriAI/litellm/pull/20838)
+
+#### Bugs
+
+- **General**
+ - Stop leaking Python tracebacks in streaming SSE error responses - [PR #20850](https://github.com/BerriAI/litellm/pull/20850)
+ - Fix video list pagination cursors not encoded with provider metadata - [PR #20710](https://github.com/BerriAI/litellm/pull/20710)
+ - Handle `metadata=None` in SDK path retry/error logic - [PR #20873](https://github.com/BerriAI/litellm/pull/20873)
+ - Fix Spend logs pickle error with Pydantic models and redaction - [PR #20685](https://github.com/BerriAI/litellm/pull/20685)
+ - Remove duplicate `PerplexityResponsesConfig` from `LLM_CONFIG_NAMES` - [PR #21105](https://github.com/BerriAI/litellm/pull/21105)
+
+---
+
+## Management Endpoints / UI
+
+#### Features
+
+- **Access Groups**
+ - New Access Groups feature for managing model, MCP server, and agent access - [PR #21022](https://github.com/BerriAI/litellm/pull/21022)
+ - Access Groups table and details page UI - [PR #21165](https://github.com/BerriAI/litellm/pull/21165)
+ - Refactor `model_ids` to `model_names` for backwards compatibility - [PR #21166](https://github.com/BerriAI/litellm/pull/21166)
+
+- **Policies**
+ - Allow connecting Policies to Tags, simulating Policies, viewing key/team counts - [PR #20904](https://github.com/BerriAI/litellm/pull/20904)
+ - Guardrail pipeline support for conditional sequential execution - [PR #21177](https://github.com/BerriAI/litellm/pull/21177)
+ - Pipeline flow builder UI for guardrail policies - [PR #21188](https://github.com/BerriAI/litellm/pull/21188)
+
+- **SSO / Auth**
+ - New Login With SSO Button - [PR #20908](https://github.com/BerriAI/litellm/pull/20908)
+ - M2M OAuth2 UI Flow - [PR #20794](https://github.com/BerriAI/litellm/pull/20794)
+ - Allow Organization and Team Admins to call `/invitation/new` - [PR #20987](https://github.com/BerriAI/litellm/pull/20987)
+ - Invite User: Email Integration Alert - [PR #20790](https://github.com/BerriAI/litellm/pull/20790)
+ - Populate identity fields in proxy admin JWT early-return path - [PR #21169](https://github.com/BerriAI/litellm/pull/21169)
+
+- **Spend Logs**
+ - Show predefined error codes in filter with user definable fallback - [PR #20773](https://github.com/BerriAI/litellm/pull/20773)
+ - Paginated searchable model select - [PR #20892](https://github.com/BerriAI/litellm/pull/20892)
+ - Sorting columns support - [PR #21143](https://github.com/BerriAI/litellm/pull/21143)
+ - Allow sorting on `/spend/logs/ui` - [PR #20991](https://github.com/BerriAI/litellm/pull/20991)
+
+- **UI Improvements**
+ - Navbar: Option to hide Usage Popup - [PR #20910](https://github.com/BerriAI/litellm/pull/20910)
+ - Model Page: Improve Credentials Messaging - [PR #21076](https://github.com/BerriAI/litellm/pull/21076)
+ - Fallbacks: Default configurable to 10 models - [PR #21144](https://github.com/BerriAI/litellm/pull/21144)
+ - Fallback display with arrows and card structure - [PR #20922](https://github.com/BerriAI/litellm/pull/20922)
+ - Team Info: Migrate to AntD Tabs + Table - [PR #20785](https://github.com/BerriAI/litellm/pull/20785)
+ - AntD refactoring and 0 cost models fix - [PR #20687](https://github.com/BerriAI/litellm/pull/20687)
+ - Zscaler AI Guard UI - [PR #21077](https://github.com/BerriAI/litellm/pull/21077)
+ - Include Config Defined Pass Through Endpoints - [PR #20898](https://github.com/BerriAI/litellm/pull/20898)
+ - Rename "HTTP" to "Streamable HTTP (Recommended)" in MCP server page - [PR #21000](https://github.com/BerriAI/litellm/pull/21000)
+ - MCP server discovery UI - [PR #21079](https://github.com/BerriAI/litellm/pull/21079)
+
+- **Virtual Keys**
+ - Allow Management keys to access `user/daily/activity` and team - [PR #20124](https://github.com/BerriAI/litellm/pull/20124)
+ - Skip premium check for empty metadata fields on team/key update - [PR #20598](https://github.com/BerriAI/litellm/pull/20598)
+
+#### Bugs
+
+- Logs: Fix Input and Output Copying - [PR #20657](https://github.com/BerriAI/litellm/pull/20657)
+- Teams: Fix Available Teams - [PR #20682](https://github.com/BerriAI/litellm/pull/20682)
+- Spend Logs: Reset Filters Resets Custom Date Range - [PR #21149](https://github.com/BerriAI/litellm/pull/21149)
+- Usage: Request Chart stack variant fix - [PR #20894](https://github.com/BerriAI/litellm/pull/20894)
+- Add Auto Router: Description Text Input Focus - [PR #21004](https://github.com/BerriAI/litellm/pull/21004)
+- Guardrail Edit: LiteLLM Content Filter Categories - [PR #21002](https://github.com/BerriAI/litellm/pull/21002)
+- Add null guard for models in API keys table - [PR #20655](https://github.com/BerriAI/litellm/pull/20655)
+- Show error details instead of 'Data Not Available' for failed requests - [PR #20656](https://github.com/BerriAI/litellm/pull/20656)
+- Fix Spend Management Tests - [PR #21088](https://github.com/BerriAI/litellm/pull/21088)
+- Fix JWT email domain validation error message - [PR #21212](https://github.com/BerriAI/litellm/pull/21212)
+
+---
+
+## AI Integrations
+
+### Logging
+
+- **[PostHog](../../docs/observability/posthog_integration)**
+ - Fix JSON serialization error for non-serializable objects - [PR #20668](https://github.com/BerriAI/litellm/pull/20668)
+
+- **[Prometheus](../../docs/proxy/logging#prometheus)**
+ - Sanitize label values to prevent metric scrape failures - [PR #20600](https://github.com/BerriAI/litellm/pull/20600)
+
+- **[Langfuse](../../docs/proxy/logging#langfuse)**
+ - Prevent empty proxy request spans from being sent to Langfuse - [PR #19935](https://github.com/BerriAI/litellm/pull/19935)
+
+- **[OpenTelemetry](../../docs/proxy/logging#otel)**
+ - Auto-infer `otlp_http` exporter when endpoint is configured - [PR #20438](https://github.com/BerriAI/litellm/pull/20438)
+
+- **[CloudZero](../../docs/proxy/logging)**
+ - Update CBF field mappings per LIT-1907 - [PR #20906](https://github.com/BerriAI/litellm/pull/20906)
+
+- **General**
+ - Allow `MAX_CALLBACKS` override via env var - [PR #20781](https://github.com/BerriAI/litellm/pull/20781)
+ - Add `standard_logging_payload_excluded_fields` config option - [PR #20831](https://github.com/BerriAI/litellm/pull/20831)
+ - Enable `verbose_logger` when `LITELLM_LOG=DEBUG` - [PR #20496](https://github.com/BerriAI/litellm/pull/20496)
+ - Guard against None `litellm_metadata` in batch logging path - [PR #20832](https://github.com/BerriAI/litellm/pull/20832)
+ - Propagate model-level tags from config to SpendLogs - [PR #20769](https://github.com/BerriAI/litellm/pull/20769)
+
+### Guardrails
+
+- **Policy Templates**
+ - New Policy Templates: pre-configured guardrail combinations for specific use-cases - [PR #21025](https://github.com/BerriAI/litellm/pull/21025)
+ - Add NSFW policy template, toxic keywords in multiple languages, child safety content filter, JSON content viewer - [PR #21205](https://github.com/BerriAI/litellm/pull/21205)
+ - Add toxic/abusive content filter guardrails - [PR #20934](https://github.com/BerriAI/litellm/pull/20934)
+
+- **Pipeline Execution**
+ - Add guardrail pipeline support for conditional sequential execution - [PR #21177](https://github.com/BerriAI/litellm/pull/21177)
+ - Agent Guardrails on streaming output - [PR #21206](https://github.com/BerriAI/litellm/pull/21206)
+ - Pipeline flow builder UI - [PR #21188](https://github.com/BerriAI/litellm/pull/21188)
+
+- **[Zscaler AI Guard](../../docs/apply_guardrail)**
+ - Zscaler AI Guard bug fixes and support during post-call - [PR #20801](https://github.com/BerriAI/litellm/pull/20801)
+ - Zscaler AI Guard UI - [PR #21077](https://github.com/BerriAI/litellm/pull/21077)
+
+- **[ZGuard](../../docs/apply_guardrail)**
+ - Add team policy mapping for ZGuard - [PR #20608](https://github.com/BerriAI/litellm/pull/20608)
+
+- **General**
+ - Add logging to all unified guardrails + link to custom code guardrail templates - [PR #20900](https://github.com/BerriAI/litellm/pull/20900)
+ - Forward request headers + `litellm_version` to generic guardrails - [PR #20729](https://github.com/BerriAI/litellm/pull/20729)
+ - Empty `guardrails`/`policies` arrays should not trigger enterprise license check - [PR #20567](https://github.com/BerriAI/litellm/pull/20567)
+ - Fix OpenAI moderation guardrails - [PR #20718](https://github.com/BerriAI/litellm/pull/20718)
+ - Fix `/v2/guardrails/list` returning sensitive values - [PR #20796](https://github.com/BerriAI/litellm/pull/20796)
+ - Fix guardrail status error - [PR #20972](https://github.com/BerriAI/litellm/pull/20972)
+ - Reuse `get_instance_fn` in `initialize_custom_guardrail` - [PR #20917](https://github.com/BerriAI/litellm/pull/20917)
+
+---
+
+## Spend Tracking, Budgets and Rate Limiting
+
+- **Prevent shared backend model key from being polluted** by per-deployment custom pricing - [PR #20679](https://github.com/BerriAI/litellm/pull/20679)
+- **Avoid in-place mutation** in SpendUpdateQueue aggregation - [PR #20876](https://github.com/BerriAI/litellm/pull/20876)
+
+---
+
+## MCP Gateway (12 updates)
+
+- **MCP M2M OAuth2 Support** - Add support for machine-to-machine OAuth2 for MCP servers - [PR #20788](https://github.com/BerriAI/litellm/pull/20788)
+- **MCP Server Discovery UI** - Browse and discover available MCP servers from the UI - [PR #21079](https://github.com/BerriAI/litellm/pull/21079)
+- **MCP Tracing** - Add OpenTelemetry tracing for MCP calls running through AI Gateway - [PR #21018](https://github.com/BerriAI/litellm/pull/21018)
+- **MCP OAuth2 Debug Headers** - Client-side debug headers for OAuth2 troubleshooting - [PR #21151](https://github.com/BerriAI/litellm/pull/21151)
+- **Fix MCP "Session not found" errors** - Resolve session persistence issues - [PR #21040](https://github.com/BerriAI/litellm/pull/21040)
+- **Fix MCP OAuth2 root endpoints** returning "MCP server not found" - [PR #20784](https://github.com/BerriAI/litellm/pull/20784)
+- **Fix MCP OAuth2 query param merging** when `authorization_url` already contains params - [PR #20968](https://github.com/BerriAI/litellm/pull/20968)
+- **Fix MCP SCOPES on Atlassian** issue - [PR #21150](https://github.com/BerriAI/litellm/pull/21150)
+- **Fix MCP StreamableHTTP backend** - Use `anyio.fail_after` instead of `asyncio.wait_for` - [PR #20891](https://github.com/BerriAI/litellm/pull/20891)
+- **Inject `NPM_CONFIG_CACHE`** into STDIO MCP subprocess env - [PR #21069](https://github.com/BerriAI/litellm/pull/21069)
+- **Block spaces and hyphens** in MCP server names and aliases - [PR #21074](https://github.com/BerriAI/litellm/pull/21074)
+
+---
+
+## Performance / Loadbalancing / Reliability improvements (8 improvements)
+
+- **Remove orphan entries from queue** - Fix memory leak in scheduler queue - [PR #20866](https://github.com/BerriAI/litellm/pull/20866)
+- **Remove repeated provider parsing** in budget limiter hot path - [PR #21043](https://github.com/BerriAI/litellm/pull/21043)
+- **Use current retry exception** for retry backoff instead of stale exception - [PR #20725](https://github.com/BerriAI/litellm/pull/20725)
+- **Add Semgrep & fix OOMs** - Static analysis rules and out-of-memory fixes - [PR #20912](https://github.com/BerriAI/litellm/pull/20912)
+- **Add Pyroscope** for continuous profiling and observability - [PR #21167](https://github.com/BerriAI/litellm/pull/21167)
+- **Respect `ssl_verify`** with shared aiohttp sessions - [PR #20349](https://github.com/BerriAI/litellm/pull/20349)
+- **Fix shared health check serialization** - [PR #21119](https://github.com/BerriAI/litellm/pull/21119)
+- **Change model mismatch logs** from WARNING to DEBUG - [PR #20994](https://github.com/BerriAI/litellm/pull/20994)
+
+---
+
+## Database Changes
+
+### Schema Updates
+
+| Table | Change Type | Description | PR | Migration |
+| ----- | ----------- | ----------- | -- | --------- |
+| `LiteLLM_VerificationToken` | New Indexes | Added indexes on `user_id`+`team_id`, `team_id`, and `budget_reset_at`+`expires` | [PR #20736](https://github.com/BerriAI/litellm/pull/20736) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260209085821_add_verificationtoken_indexes/migration.sql) |
+| `LiteLLM_PolicyAttachmentTable` | New Column | Added `tags` text array for policy-to-tag connections | [PR #21061](https://github.com/BerriAI/litellm/pull/21061) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260212103349_adjust_tags_policy_table/migration.sql) |
+| `LiteLLM_AccessGroupTable` | New Table | Access groups for managing model, MCP server, and agent access | [PR #21022](https://github.com/BerriAI/litellm/pull/21022) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260212143306_add_access_group_table/migration.sql) |
+| `LiteLLM_AccessGroupTable` | Column Change | Renamed `access_model_ids` to `access_model_names` | [PR #21166](https://github.com/BerriAI/litellm/pull/21166) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260213170952_access_group_change_to_model_name/migration.sql) |
+| `LiteLLM_ManagedVectorStoreTable` | New Table | Managed vector store tracking with model mappings | - | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260213105436_add_managed_vector_store_table/migration.sql) |
+| `LiteLLM_TeamTable`, `LiteLLM_VerificationToken` | New Column | Added `access_group_ids` text array | [PR #21022](https://github.com/BerriAI/litellm/pull/21022) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260212143306_add_access_group_table/migration.sql) |
+| `LiteLLM_GuardrailsTable` | New Column | Added `team_id` text column | - | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260214094754_schema_sync/migration.sql) |
+
+---
+
+## Documentation Updates (14 updates)
+
+- LiteLLM Observatory section added to v1.81.9 release notes - [PR #20675](https://github.com/BerriAI/litellm/pull/20675)
+- Callback registration optimization added to release notes - [PR #20681](https://github.com/BerriAI/litellm/pull/20681)
+- Middleware performance blog post - [PR #20677](https://github.com/BerriAI/litellm/pull/20677)
+- UI Team Soft Budget documentation - [PR #20669](https://github.com/BerriAI/litellm/pull/20669)
+- UI Contributing and Troubleshooting guide - [PR #20674](https://github.com/BerriAI/litellm/pull/20674)
+- Reorganize Admin UI subsection - [PR #20676](https://github.com/BerriAI/litellm/pull/20676)
+- SDK proxy authentication (OAuth2/JWT auto-refresh) - [PR #20680](https://github.com/BerriAI/litellm/pull/20680)
+- Forward client headers to LLM API documentation fix - [PR #20768](https://github.com/BerriAI/litellm/pull/20768)
+- Add docs guide for using policies - [PR #20914](https://github.com/BerriAI/litellm/pull/20914)
+- Add native thinking param examples for Claude Opus 4.6 - [PR #20799](https://github.com/BerriAI/litellm/pull/20799)
+- Fix Claude Code MCP tutorial - [PR #21145](https://github.com/BerriAI/litellm/pull/21145)
+- Add API base URLs for Dashscope (International and China/Beijing) - [PR #21083](https://github.com/BerriAI/litellm/pull/21083)
+- Fix `DEFAULT_NUM_WORKERS_LITELLM_PROXY` default (1, not 4) - [PR #21127](https://github.com/BerriAI/litellm/pull/21127)
+- Correct ElevenLabs support status in README - [PR #20643](https://github.com/BerriAI/litellm/pull/20643)
+
+---
+
+## New Contributors
+* @iver56 made their first contribution in [PR #20643](https://github.com/BerriAI/litellm/pull/20643)
+* @eliasaronson made their first contribution in [PR #20666](https://github.com/BerriAI/litellm/pull/20666)
+* @NirantK made their first contribution in [PR #19656](https://github.com/BerriAI/litellm/pull/19656)
+* @looksgood made their first contribution in [PR #20919](https://github.com/BerriAI/litellm/pull/20919)
+* @kelvin-tran made their first contribution in [PR #20548](https://github.com/BerriAI/litellm/pull/20548)
+* @bluet made their first contribution in [PR #20873](https://github.com/BerriAI/litellm/pull/20873)
+* @itayov made their first contribution in [PR #20729](https://github.com/BerriAI/litellm/pull/20729)
+* @CSteigstra made their first contribution in [PR #20960](https://github.com/BerriAI/litellm/pull/20960)
+* @rahulrd25 made their first contribution in [PR #20569](https://github.com/BerriAI/litellm/pull/20569)
+* @muraliavarma made their first contribution in [PR #20598](https://github.com/BerriAI/litellm/pull/20598)
+* @joaokopernico made their first contribution in [PR #21039](https://github.com/BerriAI/litellm/pull/21039)
+* @datzscaler made their first contribution in [PR #21077](https://github.com/BerriAI/litellm/pull/21077)
+* @atapia27 made their first contribution in [PR #20922](https://github.com/BerriAI/litellm/pull/20922)
+* @fpagny made their first contribution in [PR #21121](https://github.com/BerriAI/litellm/pull/21121)
+* @aidankovacic-8451 made their first contribution in [PR #21119](https://github.com/BerriAI/litellm/pull/21119)
+* @luisgallego-aily made their first contribution in [PR #19935](https://github.com/BerriAI/litellm/pull/19935)
+
+---
+
+## Full Changelog
+[v1.81.9.rc.1...v1.81.12.rc.1](https://github.com/BerriAI/litellm/compare/v1.81.9.rc.1...v1.81.12.rc.1)
diff --git a/docs/my-website/release_notes/v1.81.3-stable/index.md b/docs/my-website/release_notes/v1.81.3-stable/index.md
new file mode 100644
index 00000000000..c4b9013590c
--- /dev/null
+++ b/docs/my-website/release_notes/v1.81.3-stable/index.md
@@ -0,0 +1,423 @@
+---
+title: "v1.81.3-stable - Performance - 25% CPU Usage Reduction"
+slug: "v1-81-3"
+date: 2026-01-26T10:00:00
+authors:
+ - name: Krrish Dholakia
+ title: CEO, LiteLLM
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: CTO, LiteLLM
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+hide_table_of_contents: false
+---
+
+import Image from '@theme/IdealImage';
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+## Deploy this version
+
+
+
+
+``` showLineNumbers title="docker run litellm"
+docker run \
+-e STORE_MODEL_IN_DB=True \
+-p 4000:4000 \
+docker.litellm.ai/berriai/litellm:v1.81.3-stable
+```
+
+
+
+
+
+``` showLineNumbers title="pip install litellm"
+pip install litellm==1.81.3.rc.2
+```
+
+
+
+
+---
+
+## New Models / Updated Models
+
+### New Model Support
+
+| Provider | Model | Context Window | Input ($/1M tokens) | Output ($/1M tokens) | Deprecation Date |
+| -------- | ----- | -------------- | ------------------- | -------------------- | ---------------- |
+| OpenAI | `gpt-audio`, `gpt-audio-2025-08-28` | 128K | $32/1M audio tokens, $2.5/1M text tokens | $64/1M audio tokens, $10/1M text tokens | - |
+| OpenAI | `gpt-audio-mini`, `gpt-audio-mini-2025-08-28` | 128K | $10/1M audio tokens, $0.6/1M text tokens | $20/1M audio tokens, $2.4/1M text tokens | - |
+| Deepinfra, Vertex AI, Google AI Studio, OpenRouter, Vercel AI Gateway | `gemini-2.0-flash-001`, `gemini-2.0-flash` | - | - | - | 2026-03-31 |
+| Groq | `openai/gpt-oss-120b` | 131K | 0.075/1M cache read | 0.6/1M output tokens | - |
+| Groq | `groq/openai/gpt-oss-20b` | 131K | 0.0375/1M cache read, $0.075/1M text tokens | 0.3/1M output tokens | - |
+| Vertex AI | `gemini-2.5-computer-use-preview-10-2025` | 128K | $1.25 | $10 | - |
+| Azure AI | `claude-haiku-4-5` | $1.25/1M cache read, $2/1M cache read above 1 hr, $0.1/1M text tokens | $5/1M output tokens | - |
+| Azure AI | `claude-sonnet-4-5` | $3.75/1M cache read, $6/1M cache read above 1 hr, $3/1M text tokens | $15/1M output tokens | - |
+| Azure AI | `claude-opus-4-5` | $6.25/1M cache read, $10/1M cache read above 1 hr, $0.5/1M text tokens | $25/1M output tokens | - |
+| Azure AI | `claude-opus-4-1` | $18.75/1M cache read, $30/1M cache read above 1 hr, $1.5/1M text tokens | $75/1M output tokens | - |
+
+### Features
+
+- **[OpenAI](../../docs/providers/openai)**
+ - Add gpt-audio and gpt-audio-mini models to pricing - [PR #19509](https://github.com/BerriAI/litellm/pull/19509)
+ - correct audio token costs for gpt-4o-audio-preview models - [PR #19500](https://github.com/BerriAI/litellm/pull/19500)
+ - Limit stop sequence as per openai spec (ensures JetBrains IDE compatibility) - [PR #19562](https://github.com/BerriAI/litellm/pull/19562)
+
+- **[VertexAI](../../docs/providers/vertex)**
+ - Docs - Google Workload Identity Federation (WIF) support - [PR #19320](https://github.com/BerriAI/litellm/pull/19320)
+
+- **[Agentcore](../../docs/providers/bedrock_agentcore)**
+ - Fixes streaming issues with AWS Bedrock AgentCore where responses would stop after the first chunk, particularly affecting OAuth-enabled agents - [PR #17141](https://github.com/BerriAI/litellm/pull/17141)
+
+- **[Chatgpt](../../docs/providers/chatgpt)**
+ - Adds support for calling chatgpt subscription via LiteLLM - [PR #19030](https://github.com/BerriAI/litellm/pull/19030)
+ - Adds responses API bridge support for chatgpt subscription provider - [PR #19030](https://github.com/BerriAI/litellm/pull/19030)
+
+- **[Bedrock](../../docs/providers/bedrock)**
+ - support for output format for bedrock invoke via v1/messages - [PR #19560](https://github.com/BerriAI/litellm/pull/19560)
+
+- **[Azure](../../docs/providers/azure/azure)**
+ - Add support for Azure OpenAI v1 API - [PR #19313](https://github.com/BerriAI/litellm/pull/19313)
+ - preserve content_policy_violation details for images (#19328) - [PR #19372](https://github.com/BerriAI/litellm/pull/19372)
+ - Support OpenAI-format nested tool definitions for Responses API - [PR #19526](https://github.com/BerriAI/litellm/pull/19526)
+
+- **Gemini([Vertex AI](../../docs/providers/vertex), [Google AI Studio](../../docs/providers/gemini))**
+ - use responseJsonSchema for Gemini 2.0+ models - [PR #19314](https://github.com/BerriAI/litellm/pull/19314)
+
+- **[Volcengine](../../docs/providers/volcano)**
+ - Support Volcengine responses api - [PR #18508](https://github.com/BerriAI/litellm/pull/18508)
+
+- **[Anthropic](../../docs/providers/anthropic)**
+ - Add Support for calling Claude Code Max subscriptions via LiteLLM - [PR #19453](https://github.com/BerriAI/litellm/pull/19453)
+ - Add Structured output for /v1/messages with Anthropic API, Azure Anthropic API, Bedrock Converse - [PR #19545](https://github.com/BerriAI/litellm/pull/19545)
+
+- **[Brave Search](../../docs/search/brave)**
+ - New Search provider - [PR #19433](https://github.com/BerriAI/litellm/pull/19433)
+
+- **Sarvam ai**
+ - Add support for new sarvam models - [PR #19479](https://github.com/BerriAI/litellm/pull/19479)
+
+- **[GMI](../../docs/providers/gmi)**
+ - add GMI Cloud provider support - [PR #19376](https://github.com/BerriAI/litellm/pull/19376)
+
+
+### Bug Fixes
+
+- **[Anthropic](../../docs/providers/anthropic)**
+ - Fix anthropic-beta sent client side being overridden instead of appended to - [PR #19343](https://github.com/BerriAI/litellm/pull/19343)
+ - Filter out unsupported fields from JSON schema for Anthropic's output_format API - [PR #19482](https://github.com/BerriAI/litellm/pull/19482)
+
+- **[Bedrock](../../docs/providers/bedrock)**
+ - Expose stability models via /image_edits endpoint and ensure proper request transformation - [PR #19323](https://github.com/BerriAI/litellm/pull/19323)
+ - Claude Code x Bedrock Invoke fails with advanced-tool-use-2025-11-20 - [PR #19373](https://github.com/BerriAI/litellm/pull/19373)
+ - deduplicate tool calls in assistant history - [PR #19324](https://github.com/BerriAI/litellm/pull/19324)
+ - fix: correct us.anthropic.claude-opus-4-5 In-region pricing - [PR #19310](https://github.com/BerriAI/litellm/pull/19310)
+ - Fix request validation errors when using Claude 4 via bedrock invoke - [PR #19381](https://github.com/BerriAI/litellm/pull/19381)
+ - Handle thinking with tool calls for Claude 4 models - [PR #19506](https://github.com/BerriAI/litellm/pull/19506)
+ - correct streaming choice index for tool calls - [PR #19506](https://github.com/BerriAI/litellm/pull/19506)
+
+- **[Ollama](../../docs/providers/ollama)**
+ - Fix tool call errors due with improved message extraction - [PR #19369](https://github.com/BerriAI/litellm/pull/19369)
+
+- **[VertexAI](../../docs/providers/vertex)**
+ - Removed optional vertex_count_tokens_location param before request is sent to vertex - [PR #19359](https://github.com/BerriAI/litellm/pull/19359)
+
+- **Gemini([Vertex AI](../../docs/providers/vertex), [Google AI Studio](../../docs/providers/gemini))**
+ - Supports setting media_resolution and fps parameters on each video file, when using Gemini video understanding - [PR #19273](https://github.com/BerriAI/litellm/pull/19273)
+ - handle reasoning_effort as dict from OpenAI Agents SDK - [PR #19419](https://github.com/BerriAI/litellm/pull/19419)
+ - add file content support in tool results - [PR #19416](https://github.com/BerriAI/litellm/pull/19416)
+
+- **[Azure](../../docs/providers/azure_ai)**
+ - Fix Azure AI costs for Anthropic models - [PR #19530](https://github.com/BerriAI/litellm/pull/19530)
+
+- **[Giga Chat](../../docs/providers/gigachat)**
+ - Add tool choice mapping - [PR #19645](https://github.com/BerriAI/litellm/pull/19645)
+---
+
+## AI API Endpoints (LLMs, MCP, Agents)
+
+### Features
+
+- **[Files API](../../docs/files_endpoints)**
+ - Add managed files support when load_balancing is True - [PR #19338](https://github.com/BerriAI/litellm/pull/19338)
+
+- **[Claude Plugin Marketplace](../../docs/tutorials/claude_code_plugin_marketplace)**
+ - Add self hosted Claude Code Plugin Marketplace - [PR #19378](https://github.com/BerriAI/litellm/pull/19378)
+
+- **[MCP](../../docs/mcp)**
+ - Add MCP Protocol version 2025-11-25 support - [PR #19379](https://github.com/BerriAI/litellm/pull/19379)
+ - Log MCP tool calls and list tools in the LiteLLM Spend Logs table for easier debugging - [PR #19469](https://github.com/BerriAI/litellm/pull/19469)
+
+- **[Vertex AI](../../docs/providers/vertex)**
+ - Ensure only anthropic betas are forwarded down to LLM API (by default) - [PR #19542](https://github.com/BerriAI/litellm/pull/19542)
+ - Allow overriding to support forwarding incoming headers are forwarded down to target - [PR #19524](https://github.com/BerriAI/litellm/pull/19524)
+
+- **[Chat/Completions](../../docs/completion/input)**
+ - Add MCP tools response to chat completions - [PR #19552](https://github.com/BerriAI/litellm/pull/19552)
+ - Add custom vertex ai finish reasons to the output - [PR #19558](https://github.com/BerriAI/litellm/pull/19558)
+ - Return MCP execution in /chat/completions before model output during streaming - [PR #19623](https://github.com/BerriAI/litellm/pull/19623)
+
+### Bugs
+
+- **[Responses API](../../docs/response_api)**
+ - Fix duplicate messages during MCP streaming tool execution - [PR #19317](https://github.com/BerriAI/litellm/pull/19317)
+ - Fix pickle error when using OpenAI's Responses API with stream=True and tool_choice of type allowed_tools (an OpenAI-native parameter) - [PR #17205](https://github.com/BerriAI/litellm/pull/17205)
+ - stream tool call events for non-openai models - [PR #19368](https://github.com/BerriAI/litellm/pull/19368)
+ - preserve tool output ordering for gemini in responses bridge - [PR #19360](https://github.com/BerriAI/litellm/pull/19360)
+ - Add ID caching to prevent ID mismatch text-start and text-delta - [PR #19390](https://github.com/BerriAI/litellm/pull/19390)
+ - Include output_item, reasoning_summary_Text_done and reasoning_summary_part_done events for non-openai models - [PR #19472](https://github.com/BerriAI/litellm/pull/19472)
+
+- **[Chat/Completions](../../docs/completion/input)**
+ - fix: drop_params not dropping prompt_cache_key for non-OpenAI providers - [PR #19346](https://github.com/BerriAI/litellm/pull/19346)
+
+- **[Realtime API](../../docs/realtime)**
+ - disable SSL for ws:// WebSocket connections - [PR #19345](https://github.com/BerriAI/litellm/pull/19345)
+
+- **[Generate Content](../../docs/generateContent)**
+ - Log actual user input when google genai/vertex endpoints are called client-side - [PR #19156](https://github.com/BerriAI/litellm/pull/19156)
+
+- **[/messages/count_tokens Anthropic Token Counting](../../docs/anthropic_count_tokens)**
+ - ensure it works for Anthropic, Azure AI Anthropic on AI Gateway - [PR #19432](https://github.com/BerriAI/litellm/pull/19432)
+
+- **[MCP](../../docs/mcp)**
+ - forward static_headers to MCP servers - [PR #19366](https://github.com/BerriAI/litellm/pull/19366)
+
+- **[Batch API](../../docs/batches)**
+ - Fix: generation config empty for batch - [PR #19556](https://github.com/BerriAI/litellm/pull/19556)
+
+- **[Pass Through Endpoints](../../docs/proxy/pass_through)**
+ - Always reupdate registry - [PR #19420](https://github.com/BerriAI/litellm/pull/19420)
+---
+
+## Management Endpoints / UI
+
+### Features
+
+- **Cost Estimator**
+ - Fix model dropdown - [PR #19529](https://github.com/BerriAI/litellm/pull/19529)
+
+- **Claude Code Plugins**
+ - Allow Adding Claude Code Plugins via UI - [PR #19387](https://github.com/BerriAI/litellm/pull/19387)
+
+- **Guardrails**
+ - New Policy management UI - [PR #19668](https://github.com/BerriAI/litellm/pull/19668)
+ - Allow adding policies on Keys/Teams + Viewing on Info panels - [PR #19688](https://github.com/BerriAI/litellm/pull/19688)
+
+- **General**
+ - respects custom authentication header override - [PR #19276](https://github.com/BerriAI/litellm/pull/19276)
+
+- **Playground**
+ - Button to Fill Custom API Base - [PR #19440](https://github.com/BerriAI/litellm/pull/19440)
+ - display mcp output on the play ground - [PR #19553](https://github.com/BerriAI/litellm/pull/19553)
+
+- **Models**
+ - Paginate /v2/models/info - [PR #19521](https://github.com/BerriAI/litellm/pull/19521)
+ - All Model Tab Pagination - [PR #19525](https://github.com/BerriAI/litellm/pull/19525)
+ - Adding Optional scope Param to /models - [PR #19539](https://github.com/BerriAI/litellm/pull/19539)
+ - Model Search - [PR #19622](https://github.com/BerriAI/litellm/pull/19622)
+ - Filter by Model ID and Team ID - [PR #19713](https://github.com/BerriAI/litellm/pull/19713)
+
+- **MCP Servers**
+ - MCP Tools Tab Resetting to Overview - [PR #19468](https://github.com/BerriAI/litellm/pull/19468)
+
+- **Organizations**
+ - Prevent org admin from creating a new user with proxy_admin permissions - [PR #19296](https://github.com/BerriAI/litellm/pull/19296)
+ - Edit Page: Reusable Model Select - [PR #19601](https://github.com/BerriAI/litellm/pull/19601)
+
+- **Teams**
+ - Reusable Model Select - [PR #19543](https://github.com/BerriAI/litellm/pull/19543)
+ - [Fix] Team Update with Organization having All Proxy Models - [PR #19604](https://github.com/BerriAI/litellm/pull/19604)
+
+- **Logs**
+ - Include tool arguments in spend logs table - [PR #19640](https://github.com/BerriAI/litellm/pull/19640)
+
+- **Fallbacks / Loadbalancing**
+ - New fallbacks modal - [PR #19673](https://github.com/BerriAI/litellm/pull/19673)
+ - Set fallbacks/loadbalancing by team/key - [PR #19686](https://github.com/BerriAI/litellm/pull/19686)
+
+### Bugs
+
+- **Playground**
+ - increase model selector width in playground Compare view - [PR #19423](https://github.com/BerriAI/litellm/pull/19423)
+
+- **Virtual Keys**
+ - Sorting Shows Incorrect Entries - [PR #19534](https://github.com/BerriAI/litellm/pull/19534)
+
+- **General**
+ - UI 404 error when SERVER_ROOT_PATH is set - [PR #19467](https://github.com/BerriAI/litellm/pull/19467)
+ - Redirect to ui/login on expired JWT - [PR #19687](https://github.com/BerriAI/litellm/pull/19687)
+
+- **SSO**
+ - Fix SSO user roles not updating for existing users - [PR #19621](https://github.com/BerriAI/litellm/pull/19621)
+
+- **Guardrails**
+ - ensure guardrail patterns persist on edit and mode toggle - [PR #19265](https://github.com/BerriAI/litellm/pull/19265)
+---
+
+## AI Integrations
+
+### Logging
+
+- **General Logging**
+ - prevent printing duplicate StandardLoggingPayload logs - [PR #19325](https://github.com/BerriAI/litellm/pull/19325)
+ - Fix: log duplication when json_logs is enabled - [PR #19705](https://github.com/BerriAI/litellm/pull/19705)
+- **Langfuse OTEL**
+ - ignore service logs and fix callback shadowing - [PR #19298](https://github.com/BerriAI/litellm/pull/19298)
+- **Langfuse**
+ - Send litellm_trace_id - [PR #19528](https://github.com/BerriAI/litellm/pull/19528)
+ - Add Langfuse mock mode for testing without API calls - [PR #19676](https://github.com/BerriAI/litellm/pull/19676)
+- **GCS Bucket**
+ - prevent unbounded queue growth due to slow API calls - [PR #19297](https://github.com/BerriAI/litellm/pull/19297)
+ - Add GCS mock mode for testing without API calls - [PR #19683](https://github.com/BerriAI/litellm/pull/19683)
+- **Responses API Logging**
+ - Fix pydantic serialization error - [PR #19486](https://github.com/BerriAI/litellm/pull/19486)
+- **Arize Phoenix**
+ - add openinference span kinds to arize phoenix - [PR #19267](https://github.com/BerriAI/litellm/pull/19267)
+- **Prometheus**
+ - Added new prometheus metrics for user count and team count - [PR #19520](https://github.com/BerriAI/litellm/pull/19520)
+
+### Guardrails
+
+- **Bedrock Guardrails**
+ - Ensure post_call guardrail checks input+output - [PR #19151](https://github.com/BerriAI/litellm/pull/19151)
+- **Prompt Security**
+ - fixing prompt-security's guardrail implementation - [PR #19374](https://github.com/BerriAI/litellm/pull/19374)
+- **Presidio**
+ - Fixes crash in Presidio Guardrail when running in background threads (logging_hook) - [PR #19714](https://github.com/BerriAI/litellm/pull/19714)
+- **Pillar Security**
+ - Migrate Pillar Security to Generic Guardrail API - [PR #19364](https://github.com/BerriAI/litellm/pull/19364)
+- **Policy Engine**
+ - New LiteLLM Policy engine - create policies to manage guardrails, conditions - permissions per Key, Team - [PR #19612](https://github.com/BerriAI/litellm/pull/19612)
+- **General**
+ - add case-insensitive support for guardrail mode and actions - [PR #19480](https://github.com/BerriAI/litellm/pull/19480)
+
+### Prompt Management
+
+- **General**
+ - fix prompt info lookup and delete using correct IDs - [PR #19358](https://github.com/BerriAI/litellm/pull/19358)
+
+### Secret Manager
+
+- **AWS Secret Manager**
+ - ensure auto-rotation updates existing AWS secret instead of creating new one - [PR #19455](https://github.com/BerriAI/litellm/pull/19455)
+- **Hashicorp Vault**
+ - Ensure key rotations work with Vault - [PR #19634](https://github.com/BerriAI/litellm/pull/19634)
+
+---
+
+## Spend Tracking, Budgets and Rate Limiting
+
+- **Pricing Updates**
+ - Add openai/dall-e base pricing entries - [PR #19133](https://github.com/BerriAI/litellm/pull/19133)
+ - Add `input_cost_per_video_per_second` in ModelInfoBase - [PR #19398](https://github.com/BerriAI/litellm/pull/19398)
+
+---
+
+## Performance / Loadbalancing / Reliability improvements
+
+
+- **General**
+ - Fix date overflow/division by zero in proxy utils - [PR #19527](https://github.com/BerriAI/litellm/pull/19527)
+ - Fix in-flight request termination on SIGTERM when health-check runs in a separate process - [PR #19427](https://github.com/BerriAI/litellm/pull/19427)
+ - Fix Pass through routes to work with server root path - [PR #19383](https://github.com/BerriAI/litellm/pull/19383)
+ - Fix logging error for stop iteration - [PR #19649](https://github.com/BerriAI/litellm/pull/19649)
+ - prevent retrying 4xx client errors - [PR #19275](https://github.com/BerriAI/litellm/pull/19275)
+ - add better error handling for misconfig on health check - [PR #19441](https://github.com/BerriAI/litellm/pull/19441)
+
+- **Router**
+ - Fix Azure RPM calculation formula - [PR #19513](https://github.com/BerriAI/litellm/pull/19513)
+ - Persist scheduler request queue to redis - [PR #19304](https://github.com/BerriAI/litellm/pull/19304)
+ - pass search_tools to Router during DB-triggered initialization - [PR #19388](https://github.com/BerriAI/litellm/pull/19388)
+ - Fixed PromptCachingCache to correctly handle messages where cache_control is a sibling key of string content - [PR #19266](https://github.com/BerriAI/litellm/pull/19266)
+
+- **Memory Leaks/OOM**
+ - prevent OOM with nested $defs in tool schemas - [PR #19112](https://github.com/BerriAI/litellm/pull/19112)
+ - fix: HTTP client memory leaks in Presidio, OpenAI, and Gemini - [PR #19190](https://github.com/BerriAI/litellm/pull/19190)
+
+- **Non root**
+ - fix logfile and pidfile of supervisor for non root environment - [PR #17267](https://github.com/BerriAI/litellm/pull/17267)
+ - resolve Read-only file system error in non-root images - [PR #19449](https://github.com/BerriAI/litellm/pull/19449)
+
+- **Dockerfile**
+ - Redis Semantic Caching - add missing redisvl dependency to requirements.txt - [PR #19417](https://github.com/BerriAI/litellm/pull/19417)
+ - Bump OTEL versions to support a2a dependency - resolves modulenotfounderror for Microsoft Agents by @Harshit28j in #18991
+
+- **DB**
+ - Handle PostgreSQL cached plan errors during rolling deployments - [PR #19424](https://github.com/BerriAI/litellm/pull/19424)
+
+- **Timeouts**
+ - Fix: total timeout is not respected - [PR #19389](https://github.com/BerriAI/litellm/pull/19389)
+
+- **SDK**
+ - Field-Existence Checks to Type Classes to Prevent Attribute Errors - [PR #18321](https://github.com/BerriAI/litellm/pull/18321)
+ - add google-cloud-aiplatform as optional dependency with clear error message - [PR #19437](https://github.com/BerriAI/litellm/pull/19437)
+ - Make grpc dependency optional - [PR #19447](https://github.com/BerriAI/litellm/pull/19447)
+ - Add support for retry policies - [PR #19645](https://github.com/BerriAI/litellm/pull/19645)
+
+- **Performance**
+ - Cut chat_completion latency by ~21% by reducing pre-call processing time - [PR #19535](https://github.com/BerriAI/litellm/pull/19535)
+ - Optimize strip_trailing_slash with O(1) index check - [PR #19679](https://github.com/BerriAI/litellm/pull/19679)
+ - Optimize use_custom_pricing_for_model with set intersection - [PR #19677](https://github.com/BerriAI/litellm/pull/19677)
+ - perf: skip pattern_router.route() for non-wildcard models - [PR #19664](https://github.com/BerriAI/litellm/pull/19664)
+ - perf: Add LRU caching to get_model_info for faster cost lookups - [PR #19606](https://github.com/BerriAI/litellm/pull/19606)
+
+---
+
+## General Proxy Improvements
+
+### Doc Improvements
+ - new tutorial for adding MCPs to Cursor via LiteLLM - [PR #19317](https://github.com/BerriAI/litellm/pull/19317)
+ - fix vertex_region to vertex_location in Vertex AI pass-through docs - [PR #19380](https://github.com/BerriAI/litellm/pull/19380)
+ - clarify Gemini and Vertex AI model prefix in json file - [PR #19443](https://github.com/BerriAI/litellm/pull/19443)
+ - update Claude Code integration guides - [PR #19415](https://github.com/BerriAI/litellm/pull/19415)
+ - adjust opencode tutorial - [PR #19605](https://github.com/BerriAI/litellm/pull/19605)
+ - add spend-queue-troubleshooting docs - [PR #19659](https://github.com/BerriAI/litellm/pull/19659)
+ - docs: add litellm-enterprise requirement for managed files - [PR #19689](https://github.com/BerriAI/litellm/pull/19689)
+
+### Helm
+ - Add support for keda in helm chart - [PR #19337](https://github.com/BerriAI/litellm/pull/19337)
+ - sync Helm chart version with LiteLLM release version - [PR #19438](https://github.com/BerriAI/litellm/pull/19438)
+ - Enable PreStop hook configuration in values.yaml - [PR #19613](https://github.com/BerriAI/litellm/pull/19613)
+
+### General
+ - Add health check scripts and parallel execution support - [PR #19295](https://github.com/BerriAI/litellm/pull/19295)
+
+
+---
+
+## New Contributors
+
+
+* @dushyantzz made their first contribution in [PR #19158](https://github.com/BerriAI/litellm/pull/19158)
+* @obod-mpw made their first contribution in [PR #19133](https://github.com/BerriAI/litellm/pull/19133)
+* @msexxeta made their first contribution in [PR #19030](https://github.com/BerriAI/litellm/pull/19030)
+* @rsicart made their first contribution in [PR #19337](https://github.com/BerriAI/litellm/pull/19337)
+* @cluebbehusen made their first contribution in [PR #19311](https://github.com/BerriAI/litellm/pull/19311)
+* @Lucky-Lodhi2004 made their first contribution in [PR #19315](https://github.com/BerriAI/litellm/pull/19315)
+* @binbandit made their first contribution in [PR #19324](https://github.com/BerriAI/litellm/pull/19324)
+* @flex-myeonghyeon made their first contribution in [PR #19381](https://github.com/BerriAI/litellm/pull/19381)
+* @Lrakotoson made their first contribution in [PR #18321](https://github.com/BerriAI/litellm/pull/18321)
+* @bensi94 made their first contribution in [PR #18787](https://github.com/BerriAI/litellm/pull/18787)
+* @victorigualada made their first contribution in [PR #19368](https://github.com/BerriAI/litellm/pull/19368)
+* @VedantMadane made their first contribution in #19266
+* @stiyyagura0901 made their first contribution in #19276
+* @kamilio made their first contribution in [PR #19447](https://github.com/BerriAI/litellm/pull/19447)
+* @jonathansampson made their first contribution in [PR #19433](https://github.com/BerriAI/litellm/pull/19433)
+* @rynecarbone made their first contribution in [PR #19416](https://github.com/BerriAI/litellm/pull/19416)
+* @jayy-77 made their first contribution in #19366
+* @davida-ps made their first contribution in [PR #19374](https://github.com/BerriAI/litellm/pull/19374)
+* @joaodinissf made their first contribution in [PR #19506](https://github.com/BerriAI/litellm/pull/19506)
+* @ecao310 made their first contribution in [PR #19520](https://github.com/BerriAI/litellm/pull/19520)
+* @mpcusack-altos made their first contribution in [PR #19577](https://github.com/BerriAI/litellm/pull/19577)
+* @milan-berri made their first contribution in [PR #19602](https://github.com/BerriAI/litellm/pull/19602)
+* @xqe2011 made their first contribution in #19621
+
+---
+
+## Full Changelog
+
+**[View complete changelog on GitHub](https://github.com/BerriAI/litellm/releases/tag/v1.81.3.rc)**
diff --git a/docs/my-website/release_notes/v1.81.6.md b/docs/my-website/release_notes/v1.81.6.md
new file mode 100644
index 00000000000..1e948aa37b7
--- /dev/null
+++ b/docs/my-website/release_notes/v1.81.6.md
@@ -0,0 +1,392 @@
+---
+title: "[Preview] v1.81.6 - Logs v2 with Tool Call Tracing"
+slug: "v1-81-6"
+date: 2026-01-31T00:00:00
+authors:
+ - name: Krrish Dholakia
+ title: CEO, LiteLLM
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: CTO, LiteLLM
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+hide_table_of_contents: false
+---
+
+:::danger Known Issue - CPU Usage
+
+This release had known issues with CPU usage. This has been fixed in [v1.81.9-stable](./v1-81-9).
+
+**We recommend using v1.81.9-stable instead.**
+
+:::
+
+## Deploy this version
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import Image from '@theme/IdealImage';
+
+
+
+
+```bash
+docker run \
+-e STORE_MODEL_IN_DB=True \
+-p 4000:4000 \
+docker.litellm.ai/berriai/litellm:main-v1.81.6
+```
+
+
+
+
+```bash
+pip install litellm==1.81.6
+```
+
+
+
+
+## Key Highlights
+
+Logs View v2 with Tool Call Tracing - Redesigned logs interface with side panel, structured tool visualization, and error message search for faster debugging.
+
+Let's dive in.
+
+### Logs View v2 with Tool Call Tracing
+
+This release introduces comprehensive tool call tracing through LiteLLM's redesigned Logs View v2, enabling developers to debug and monitor AI agent workflows in production environments seamlessly.
+
+This means you can now onboard use cases like tracing complex multi-step agent interactions, debugging tool execution failures, and monitoring MCP server calls while maintaining full visibility into request/response payloads with syntax highlighting.
+
+Developers can access the new Logs View through LiteLLM's UI to inspect tool calls in structured format, search logs by error messages or request patterns, and correlate agent activities across sessions with collapsible side panel views.
+
+{/* TODO: Add image from Slack (group_7219.png) - save as logs_v2_tool_tracing.png */}
+{/* */}
+
+[Get Started](../../docs/proxy/ui_logs)
+
+## New Models / Updated Models
+
+#### New Model Support
+
+| Provider | Model | Context Window | Input ($/1M tokens) | Output ($/1M tokens) | Features |
+| -------- | ----- | -------------- | ------------------- | -------------------- | -------- |
+| AWS Bedrock | `amazon.nova-2-pro-preview-20251202-v1:0` | 1M | $2.19 | $17.50 | Chat completions, vision, video, PDF, function calling, prompt caching, reasoning |
+| Google Vertex AI | `gemini-robotics-er-1.5-preview` | 1M | $0.30 | $2.50 | Chat completions, multimodal (text, image, video, audio), function calling, reasoning |
+| OpenRouter | `openrouter/xiaomi/mimo-v2-flash` | 262K | $0.09 | $0.29 | Chat completions, function calling, reasoning |
+| OpenRouter | `openrouter/moonshotai/kimi-k2.5` | - | - | - | Chat completions |
+| OpenRouter | `openrouter/z-ai/glm-4.7` | 202K | $0.40 | $1.50 | Chat completions, vision, function calling, reasoning |
+
+#### Features
+
+- **[AWS Bedrock](../../docs/providers/bedrock)**
+ - Messages API Bedrock Converse caching and PDF support - [PR #19785](https://github.com/BerriAI/litellm/pull/19785)
+ - Translate advanced-tool-use to Bedrock-specific headers for Claude Opus 4.5 - [PR #19841](https://github.com/BerriAI/litellm/pull/19841)
+ - Support tool search header translation for Sonnet 4.5 - [PR #19871](https://github.com/BerriAI/litellm/pull/19871)
+ - Filter unsupported beta headers for AWS Bedrock Invoke API - [PR #19877](https://github.com/BerriAI/litellm/pull/19877)
+ - Nova grounding improvements - [PR #19598](https://github.com/BerriAI/litellm/pull/19598), [PR #20159](https://github.com/BerriAI/litellm/pull/20159)
+
+- **[Anthropic](../../docs/providers/anthropic)**
+ - Remove explicit cache_control null in tool_result content - [PR #19919](https://github.com/BerriAI/litellm/pull/19919)
+ - Fix tool handling - [PR #19805](https://github.com/BerriAI/litellm/pull/19805)
+
+- **[Google Gemini / Vertex AI](../../docs/providers/gemini)**
+ - Add Gemini Robotics-ER 1.5 preview support - [PR #19845](https://github.com/BerriAI/litellm/pull/19845)
+ - Support file retrieval in GoogleAIStudioFilesHandle - [PR #20018](https://github.com/BerriAI/litellm/pull/20018)
+ - Add /delete endpoint support - [PR #20055](https://github.com/BerriAI/litellm/pull/20055)
+ - Add custom_llm_provider as gemini translation - [PR #19988](https://github.com/BerriAI/litellm/pull/19988)
+ - Subtract implicit cached tokens from text_tokens for correct cost calculation - [PR #19775](https://github.com/BerriAI/litellm/pull/19775)
+ - Remove unsupported prompt-caching-scope-2026-01-05 header for vertex ai - [PR #20058](https://github.com/BerriAI/litellm/pull/20058)
+ - Add disable flag for anthropic gemini cache translation - [PR #20052](https://github.com/BerriAI/litellm/pull/20052)
+ - Convert image URLs to base64 in tool messages for Anthropic on Vertex AI - [PR #19896](https://github.com/BerriAI/litellm/pull/19896)
+
+- **[xAI](../../docs/providers/xai)**
+ - Add grok reasoning content support - [PR #19850](https://github.com/BerriAI/litellm/pull/19850)
+ - Add websearch params support for Responses API - [PR #19915](https://github.com/BerriAI/litellm/pull/19915)
+ - Add routing of xai chat completions to responses when web search options is present - [PR #20051](https://github.com/BerriAI/litellm/pull/20051)
+ - Correct cached token cost calculation - [PR #19772](https://github.com/BerriAI/litellm/pull/19772)
+
+- **[Azure OpenAI](../../docs/providers/azure)**
+ - Use generic cost calculator for audio token pricing - [PR #19771](https://github.com/BerriAI/litellm/pull/19771)
+ - Allow tool_choice for Azure GPT-5 chat models - [PR #19813](https://github.com/BerriAI/litellm/pull/19813)
+ - Set gpt-5.2-codex mode to responses for Azure and OpenRouter - [PR #19770](https://github.com/BerriAI/litellm/pull/19770)
+
+- **[OpenAI](../../docs/providers/openai)**
+ - Fix max_input_tokens for gpt-5.2-codex - [PR #20009](https://github.com/BerriAI/litellm/pull/20009)
+ - Fix gpt-image-1.5 cost calculation not including output image tokens - [PR #19515](https://github.com/BerriAI/litellm/pull/19515)
+
+- **[Hosted VLLM](../../docs/providers/vllm)**
+ - Support thinking parameter in anthropic_messages() and .completion() - [PR #19787](https://github.com/BerriAI/litellm/pull/19787)
+ - Route through base_llm_http_handler to support ssl_verify - [PR #19893](https://github.com/BerriAI/litellm/pull/19893)
+ - Fix vllm embedding format - [PR #20056](https://github.com/BerriAI/litellm/pull/20056)
+
+- **[OCI GenAI](../../docs/providers/oci)**
+ - Serialize imageUrl as object for OCI GenAI API - [PR #19661](https://github.com/BerriAI/litellm/pull/19661)
+
+- **[Volcengine](../../docs/providers/volcano)**
+ - Add context for volcengine models (deepseek-v3-2, glm-4-7, kimi-k2-thinking) - [PR #19335](https://github.com/BerriAI/litellm/pull/19335)
+
+- **[Chinese Providers](../../docs/providers/)**
+ - Add prompt caching and reasoning support for MiniMax, GLM, Xiaomi - [PR #19924](https://github.com/BerriAI/litellm/pull/19924)
+
+- **[Vercel AI Gateway](../../docs/providers/vercel_ai_gateway)**
+ - Add embeddings support - [PR #19660](https://github.com/BerriAI/litellm/pull/19660)
+
+### Bug Fixes
+
+- **[Google](../../docs/providers/gemini)**
+ - Fix gemini-robotics-er-1.5-preview entry - [PR #19974](https://github.com/BerriAI/litellm/pull/19974)
+
+- **General**
+ - Fix output_tokens_details.reasoning_tokens None - [PR #19914](https://github.com/BerriAI/litellm/pull/19914)
+ - Fix stream_chunk_builder to preserve images from streaming chunks - [PR #19654](https://github.com/BerriAI/litellm/pull/19654)
+ - Fix aspectRatio mapping in image edit - [PR #20053](https://github.com/BerriAI/litellm/pull/20053)
+ - Handle unknown models in Azure AI cost calculator - [PR #20150](https://github.com/BerriAI/litellm/pull/20150)
+
+- **[GigaChat](../../docs/providers/gigachat)**
+ - Ensure function content is valid JSON - [PR #19232](https://github.com/BerriAI/litellm/pull/19232)
+
+## LLM API Endpoints
+
+#### Features
+
+- **[Messages API (/messages)](../../docs/mcp)**
+ - Add LiteLLM x Claude Agent SDK Integration - [PR #20035](https://github.com/BerriAI/litellm/pull/20035)
+
+- **[A2A / MCP Gateway API (/a2a, /mcp)](../../docs/mcp)**
+ - Add A2A agent header-based context propagation support - [PR #19504](https://github.com/BerriAI/litellm/pull/19504)
+ - Enable progress notifications for MCP tool calls - [PR #19809](https://github.com/BerriAI/litellm/pull/19809)
+ - Fix support for non-standard MCP URL patterns - [PR #19738](https://github.com/BerriAI/litellm/pull/19738)
+ - Add backward compatibility for legacy A2A card formats (/.well-known/agent.json) - [PR #19949](https://github.com/BerriAI/litellm/pull/19949)
+ - Add support for agent parameter in /interactions endpoint - [PR #19866](https://github.com/BerriAI/litellm/pull/19866)
+
+- **[Responses API (/responses)](../../docs/response_api)**
+ - Fix custom_llm_provider for provider-specific params - [PR #19798](https://github.com/BerriAI/litellm/pull/19798)
+ - Extract input tokens details as dict in ResponseAPILoggingUtils - [PR #20046](https://github.com/BerriAI/litellm/pull/20046)
+
+- **[Batch API (/batches)](../../docs/batches)**
+ - Fix /batches to return encoded ids (from managed objects table) - [PR #19040](https://github.com/BerriAI/litellm/pull/19040)
+ - Fix Batch and File user level permissions - [PR #19981](https://github.com/BerriAI/litellm/pull/19981)
+ - Add cost tracking and usage object in retrieve_batch call type - [PR #19986](https://github.com/BerriAI/litellm/pull/19986)
+
+- **[Embeddings API (/embeddings)](../../docs/embedding/supported_embedding)**
+ - Add supported input formats documentation - [PR #20073](https://github.com/BerriAI/litellm/pull/20073)
+
+- **[RAG API (/rag/ingest, /vector_store)](../../docs/rag_ingest)**
+ - Add UI for /rag/ingest API - Upload docs, pdfs etc to create vector stores - [PR #19822](https://github.com/BerriAI/litellm/pull/19822)
+ - Add support for using S3 Vectors as Vector Store Provider - [PR #19888](https://github.com/BerriAI/litellm/pull/19888)
+ - Add s3_vectors as provider on /vector_store/search API + UI for creating + PDF support - [PR #19895](https://github.com/BerriAI/litellm/pull/19895)
+ - Add permission management for users and teams on Vector Stores - [PR #19972](https://github.com/BerriAI/litellm/pull/19972)
+ - Enable router support for completions in RAG query pipeline - [PR #19550](https://github.com/BerriAI/litellm/pull/19550)
+
+- **[Search API (/search)](../../docs/search)**
+ - Add /list endpoint to list what search tools exist in router - [PR #19969](https://github.com/BerriAI/litellm/pull/19969)
+ - Fix router search tools v2 integration - [PR #19840](https://github.com/BerriAI/litellm/pull/19840)
+
+- **[Passthrough Endpoints (/\{provider\}_passthrough)](../../docs/pass_through/intro)**
+ - Add /openai_passthrough route for OpenAI passthrough requests - [PR #19989](https://github.com/BerriAI/litellm/pull/19989)
+ - Add support for configuring role_mappings via environment variables - [PR #19498](https://github.com/BerriAI/litellm/pull/19498)
+ - Add Vertex AI LLM credentials sensitive keyword "vertex_credentials" for masking - [PR #19551](https://github.com/BerriAI/litellm/pull/19551)
+ - Fix prevention of provider-prefixed model name leaks in responses - [PR #19943](https://github.com/BerriAI/litellm/pull/19943)
+ - Fix proxy support for slashes in Google Vertex generateContent model names - [PR #19737](https://github.com/BerriAI/litellm/pull/19737), [PR #19753](https://github.com/BerriAI/litellm/pull/19753)
+ - Support model names with slashes in Vertex AI passthrough URLs - [PR #19944](https://github.com/BerriAI/litellm/pull/19944)
+ - Fix regression in Vertex AI passthroughs for router models - [PR #19967](https://github.com/BerriAI/litellm/pull/19967)
+ - Add regression tests for Vertex AI passthrough model names - [PR #19855](https://github.com/BerriAI/litellm/pull/19855)
+
+#### Bugs
+
+- **General**
+ - Fix token calculations and refactor - [PR #19696](https://github.com/BerriAI/litellm/pull/19696)
+
+## Management Endpoints / UI
+
+#### Features
+
+- **Proxy CLI Auth**
+ - Add configurable CLI JWT expiration via environment variable - [PR #19780](https://github.com/BerriAI/litellm/pull/19780)
+ - Fix team cli auth flow - [PR #19666](https://github.com/BerriAI/litellm/pull/19666)
+
+- **Virtual Keys**
+ - UI: Auto Truncation of Table Values - [PR #19718](https://github.com/BerriAI/litellm/pull/19718)
+ - Fix Create Key: Expire Key Input Duration - [PR #19807](https://github.com/BerriAI/litellm/pull/19807)
+ - Bulk Update Keys Endpoint - [PR #19886](https://github.com/BerriAI/litellm/pull/19886)
+
+- **Logs View**
+ - **v2 Logs view with side panel and improved UX** - [PR #20091](https://github.com/BerriAI/litellm/pull/20091)
+ - New View to render "Tools" on Logs View - [PR #20093](https://github.com/BerriAI/litellm/pull/20093)
+ - Add Pretty print view of request/response - [PR #20096](https://github.com/BerriAI/litellm/pull/20096)
+ - Add error_message search in Spend Logs Endpoint - [PR #19960](https://github.com/BerriAI/litellm/pull/19960)
+ - UI: Adding Error message search to ui spend logs - [PR #19963](https://github.com/BerriAI/litellm/pull/19963)
+ - Spend Logs: Settings Modal - [PR #19918](https://github.com/BerriAI/litellm/pull/19918)
+ - Fix error_code in Spend Logs metadata - [PR #20015](https://github.com/BerriAI/litellm/pull/20015)
+ - Spend Logs: Show Current Store and Retention Status - [PR #20017](https://github.com/BerriAI/litellm/pull/20017)
+ - Allow Dynamic Setting of store_prompts_in_spend_logs - [PR #19913](https://github.com/BerriAI/litellm/pull/19913)
+ - [Docs: UI Spend Logs Settings](../../docs/proxy/ui_spend_log_settings) - [PR #20197](https://github.com/BerriAI/litellm/pull/20197)
+
+- **Models + Endpoints**
+ - Add sortBy and sortOrder params for /v2/model/info - [PR #19903](https://github.com/BerriAI/litellm/pull/19903)
+ - Fix Sorting for /v2/model/info - [PR #19971](https://github.com/BerriAI/litellm/pull/19971)
+ - UI: Model Page Server Sort - [PR #19908](https://github.com/BerriAI/litellm/pull/19908)
+
+- **Usage & Analytics**
+ - UI: Usage Export: Breakdown by Teams and Keys - [PR #19953](https://github.com/BerriAI/litellm/pull/19953)
+ - UI: Usage: Model Breakdown Per Key - [PR #20039](https://github.com/BerriAI/litellm/pull/20039)
+
+- **UI Improvements**
+ - UI: Allow Admins to control what pages are visible on LeftNav - [PR #19907](https://github.com/BerriAI/litellm/pull/19907)
+ - UI: Add Light/Dark Mode Switch for Development - [PR #19804](https://github.com/BerriAI/litellm/pull/19804)
+ - UI: Dark Mode: Delete Resource Modal - [PR #20098](https://github.com/BerriAI/litellm/pull/20098)
+ - UI: Tables: Reusable Table Sort Component - [PR #19970](https://github.com/BerriAI/litellm/pull/19970)
+ - UI: New Badge Dot Render - [PR #20024](https://github.com/BerriAI/litellm/pull/20024)
+ - UI: Feedback Prompts: Option To Hide Prompts - [PR #19831](https://github.com/BerriAI/litellm/pull/19831)
+ - UI: Navbar: Fixed Default Logo + Bound Logo Box - [PR #20092](https://github.com/BerriAI/litellm/pull/20092)
+ - UI: Navbar: User Dropdown - [PR #20095](https://github.com/BerriAI/litellm/pull/20095)
+ - Change default key type from 'Default' to 'LLM API' - [PR #19516](https://github.com/BerriAI/litellm/pull/19516)
+
+- **Team & User Management**
+ - Fix /team/member_add User Email and ID Verifications - [PR #19814](https://github.com/BerriAI/litellm/pull/19814)
+ - Fix SSO Email Case Sensitivity - [PR #19799](https://github.com/BerriAI/litellm/pull/19799)
+ - UI: Internal User: Bulk Add - [PR #19721](https://github.com/BerriAI/litellm/pull/19721)
+
+- **AI Gateway Features**
+ - Add support for making silent LLM calls without logging - [PR #19544](https://github.com/BerriAI/litellm/pull/19544)
+ - UI: Fix MCP tools instructions to display comma-separated strings - [PR #20101](https://github.com/BerriAI/litellm/pull/20101)
+
+#### Bugs
+
+- Fix Model Name During Fallback - [PR #20177](https://github.com/BerriAI/litellm/pull/20177)
+- Fix Health Endpoints when Callback Objects Defined - [PR #20182](https://github.com/BerriAI/litellm/pull/20182)
+- Fix Unable to reset user max budget to unlimited - [PR #19796](https://github.com/BerriAI/litellm/pull/19796)
+- Fix Password comparison with non-ASCII characters - [PR #19568](https://github.com/BerriAI/litellm/pull/19568)
+- Correct error message for DISABLE_ADMIN_ENDPOINTS - [PR #19861](https://github.com/BerriAI/litellm/pull/19861)
+- Prevent clearing content filter patterns when editing guardrail - [PR #19671](https://github.com/BerriAI/litellm/pull/19671)
+- Fix Prompt Studio history to load tools and system messages - [PR #19920](https://github.com/BerriAI/litellm/pull/19920)
+- Add WATSONX_ZENAPIKEY to WatsonX credentials - [PR #20086](https://github.com/BerriAI/litellm/pull/20086)
+- UI: Vector Store: Allow Config Defined Models to Be Selected - [PR #20031](https://github.com/BerriAI/litellm/pull/20031)
+
+## Logging / Guardrail / Prompt Management Integrations
+
+#### Features
+
+- **[DataDog](../../docs/proxy/logging#datadog)**
+ - Add agent support for LLM Observability - [PR #19574](https://github.com/BerriAI/litellm/pull/19574)
+ - Add datadog cost management support and fix startup callback issue - [PR #19584](https://github.com/BerriAI/litellm/pull/19584)
+ - Add datadog_llm_observability to /health/services allowed list - [PR #19952](https://github.com/BerriAI/litellm/pull/19952)
+ - Check for agent mode before requiring DD_API_KEY/DD_SITE - [PR #20156](https://github.com/BerriAI/litellm/pull/20156)
+
+- **[OpenTelemetry](../../docs/observability/opentelemetry_integration)**
+ - Propagate JWT auth metadata to OTEL spans - [PR #19627](https://github.com/BerriAI/litellm/pull/19627)
+ - Fix thread leak in dynamic header path - [PR #19946](https://github.com/BerriAI/litellm/pull/19946)
+
+- **[Prometheus](../../docs/proxy/logging#prometheus)**
+ - Add callbacks and labels - [PR #19708](https://github.com/BerriAI/litellm/pull/19708)
+ - Add clientip and user agent in metrics - [PR #19717](https://github.com/BerriAI/litellm/pull/19717)
+ - Add tpm-rpm limit metrics - [PR #19725](https://github.com/BerriAI/litellm/pull/19725)
+ - Add model_id label to metrics - [PR #19678](https://github.com/BerriAI/litellm/pull/19678)
+ - Safely handle None metadata in logging - [PR #19691](https://github.com/BerriAI/litellm/pull/19691)
+ - Resolve high CPU when router_settings in DB by avoiding REGISTRY.collect() - [PR #20087](https://github.com/BerriAI/litellm/pull/20087)
+
+- **[Langfuse](../../docs/proxy/logging#langfuse)**
+ - Add litellm_callback_logging_failures_metric for Langfuse, Langfuse Otel and other Otel providers - [PR #19636](https://github.com/BerriAI/litellm/pull/19636)
+
+- **General Logging**
+ - Use return value from CustomLogger.async_post_call_success_hook - [PR #19670](https://github.com/BerriAI/litellm/pull/19670)
+ - Add async_post_call_response_headers_hook to CustomLogger - [PR #20083](https://github.com/BerriAI/litellm/pull/20083)
+ - Add mock client factory pattern and mock support for PostHog, Helicone, and Braintrust integrations - [PR #19707](https://github.com/BerriAI/litellm/pull/19707)
+
+#### Guardrails
+
+- **[Presidio](../../docs/proxy/guardrails/pii_masking_v2)**
+ - Reuse HTTP connections to prevent performance degradation - [PR #19964](https://github.com/BerriAI/litellm/pull/19964)
+
+- **Onyx**
+ - Add timeout to onyx guardrail - [PR #19731](https://github.com/BerriAI/litellm/pull/19731)
+
+- **General**
+ - Add guardrail model argument feature - [PR #19619](https://github.com/BerriAI/litellm/pull/19619)
+ - Fix guardrails issues with streaming-response regex - [PR #19901](https://github.com/BerriAI/litellm/pull/19901)
+ - Remove enterprise requirement for guardrail monitoring (docs) - [PR #19833](https://github.com/BerriAI/litellm/pull/19833)
+
+## Spend Tracking, Budgets and Rate Limiting
+
+- Add event-driven coordination for global spend query to prevent cache stampede - [PR #20030](https://github.com/BerriAI/litellm/pull/20030)
+
+## Performance / Loadbalancing / Reliability improvements
+
+- **Resolve high CPU when router_settings in DB** - by avoiding REGISTRY.collect() in PrometheusServicesLogger - [PR #20087](https://github.com/BerriAI/litellm/pull/20087)
+- **Reuse HTTP connections in Presidio** - to prevent performance degradation - [PR #19964](https://github.com/BerriAI/litellm/pull/19964)
+- **Event-driven coordination for global spend query** - prevent cache stampede - [PR #20030](https://github.com/BerriAI/litellm/pull/20030)
+- Fix recursive Pydantic validation issue - [PR #19531](https://github.com/BerriAI/litellm/pull/19531)
+- Refactor argument handling into helper function to reduce code bloat - [PR #19720](https://github.com/BerriAI/litellm/pull/19720)
+- Optimize logo fetching and resolve MCP import blockers - [PR #19719](https://github.com/BerriAI/litellm/pull/19719)
+- Improve logo download performance using async HTTP client - [PR #20155](https://github.com/BerriAI/litellm/pull/20155)
+- Fix server root path configuration - [PR #19790](https://github.com/BerriAI/litellm/pull/19790)
+- Refactor: Extract transport context creation into separate method - [PR #19794](https://github.com/BerriAI/litellm/pull/19794)
+- Add native_background_mode configuration to override polling_via_cache for specific models - [PR #19899](https://github.com/BerriAI/litellm/pull/19899)
+- Initialize tiktoken environment at import time to enable offline usage - [PR #19882](https://github.com/BerriAI/litellm/pull/19882)
+- Improve tiktoken performance using local cache in lazy loading - [PR #19774](https://github.com/BerriAI/litellm/pull/19774)
+- Fix timeout errors in chat completion calls to be correctly reported in failure callbacks - [PR #19842](https://github.com/BerriAI/litellm/pull/19842)
+- Fix environment variable type handling for NUM_RETRIES - [PR #19507](https://github.com/BerriAI/litellm/pull/19507)
+- Use safe_deep_copy in silent experiment kwargs to prevent mutation - [PR #20170](https://github.com/BerriAI/litellm/pull/20170)
+- Improve error handling by inspecting BadRequestError after all other policy types - [PR #19878](https://github.com/BerriAI/litellm/pull/19878)
+
+## Database Changes
+
+### Schema Updates
+
+| Table | Change Type | Description | PR | Migration |
+| ----- | ----------- | ----------- | -- | --------- |
+| `LiteLLM_ManagedVectorStoresTable` | New Columns | Added `team_id` and `user_id` fields for permission management | [PR #19972](https://github.com/BerriAI/litellm/pull/19972) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260131150814_add_team_user_to_vector_stores/migration.sql) |
+
+### Migration Improvements
+
+- Fix Docker: Use correct schema path for Prisma generation - [PR #19631](https://github.com/BerriAI/litellm/pull/19631)
+- Resolve 'relation does not exist' migration errors in setup_database - [PR #19281](https://github.com/BerriAI/litellm/pull/19281)
+- Fix migration issue and improve Docker image stability - [PR #19843](https://github.com/BerriAI/litellm/pull/19843)
+- Run Prisma generate as nobody user in non-root Docker container for security - [PR #20000](https://github.com/BerriAI/litellm/pull/20000)
+- Bump litellm-proxy-extras version to 0.4.28 - [PR #20166](https://github.com/BerriAI/litellm/pull/20166)
+
+## Documentation Updates
+
+- **[Add Claude Agents SDK x LiteLLM Guide](../../docs/mcp)** - [PR #20036](https://github.com/BerriAI/litellm/pull/20036)
+- **[Add Cookbook: Using Claude Agent SDK + MCPs with LiteLLM](https://github.com/BerriAI/litellm/tree/main/cookbook)** - [PR #20081](https://github.com/BerriAI/litellm/pull/20081)
+- Fix A2A Python SDK URL in documentation - [PR #19832](https://github.com/BerriAI/litellm/pull/19832)
+- **[Add Sarvam usage documentation](../../docs/providers/sarvam)** - [PR #19844](https://github.com/BerriAI/litellm/pull/19844)
+- **[Add supported input formats for embeddings](../../docs/embedding/supported_embedding)** - [PR #20073](https://github.com/BerriAI/litellm/pull/20073)
+- **[UI Spend Logs Settings Docs](../../docs/proxy/ui_spend_log_settings)** - [PR #20197](https://github.com/BerriAI/litellm/pull/20197)
+- Add OpenAI Agents SDK to OSS Adopters list in README - [PR #19820](https://github.com/BerriAI/litellm/pull/19820)
+- Update docs: Remove enterprise requirement for guardrail monitoring - [PR #19833](https://github.com/BerriAI/litellm/pull/19833)
+- Add missing environment variable documentation - [PR #20138](https://github.com/BerriAI/litellm/pull/20138)
+- Improve documentation blog index page - [PR #20188](https://github.com/BerriAI/litellm/pull/20188)
+
+## Infrastructure / Testing Improvements
+
+- Add test coverage for Router.get_valid_args and improve code coverage reporting - [PR #19797](https://github.com/BerriAI/litellm/pull/19797)
+- Add validation of model cost map as CI job - [PR #19993](https://github.com/BerriAI/litellm/pull/19993)
+- Add Realtime API benchmarks - [PR #20074](https://github.com/BerriAI/litellm/pull/20074)
+- Add Init Containers support in community helm chart - [PR #19816](https://github.com/BerriAI/litellm/pull/19816)
+- Add libsndfile to main Dockerfile for ARM64 audio processing support - [PR #19776](https://github.com/BerriAI/litellm/pull/19776)
+
+## New Contributors
+
+* @ruanjf made their first contribution in https://github.com/BerriAI/litellm/pull/19551
+* @moh-dev-stack made their first contribution in https://github.com/BerriAI/litellm/pull/19507
+* @formorter made their first contribution in https://github.com/BerriAI/litellm/pull/19498
+* @priyam-that made their first contribution in https://github.com/BerriAI/litellm/pull/19516
+* @marcosgriselli made their first contribution in https://github.com/BerriAI/litellm/pull/19550
+* @natimofeev made their first contribution in https://github.com/BerriAI/litellm/pull/19232
+* @zifeo made their first contribution in https://github.com/BerriAI/litellm/pull/19805
+* @pragyasardana made their first contribution in https://github.com/BerriAI/litellm/pull/19816
+* @ryewilson made their first contribution in https://github.com/BerriAI/litellm/pull/19833
+* @lizhen921 made their first contribution in https://github.com/BerriAI/litellm/pull/19919
+* @boarder7395 made their first contribution in https://github.com/BerriAI/litellm/pull/19666
+* @rushilchugh01 made their first contribution in https://github.com/BerriAI/litellm/pull/19938
+* @cfchase made their first contribution in https://github.com/BerriAI/litellm/pull/19893
+* @ayim made their first contribution in https://github.com/BerriAI/litellm/pull/19872
+* @varunsripad123 made their first contribution in https://github.com/BerriAI/litellm/pull/20018
+* @nht1206 made their first contribution in https://github.com/BerriAI/litellm/pull/20046
+* @genga6 made their first contribution in https://github.com/BerriAI/litellm/pull/20009
+
+**Full Changelog**: https://github.com/BerriAI/litellm/compare/v1.81.3.rc...v1.81.6
diff --git a/docs/my-website/release_notes/v1.81.9.md b/docs/my-website/release_notes/v1.81.9.md
new file mode 100644
index 00000000000..c7659442c4c
--- /dev/null
+++ b/docs/my-website/release_notes/v1.81.9.md
@@ -0,0 +1,382 @@
+---
+title: "v1.81.9 - Control which MCP Servers are exposed on the Internet"
+slug: "v1-81-9"
+date: 2026-02-07T00:00:00
+authors:
+ - name: Krrish Dholakia
+ title: CEO, LiteLLM
+ url: https://www.linkedin.com/in/krish-d/
+ image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
+ - name: Ishaan Jaff
+ title: CTO, LiteLLM
+ url: https://www.linkedin.com/in/reffajnaahsi/
+ image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg
+hide_table_of_contents: false
+---
+
+:::info Stable Release Branch
+
+For each stable release, we now maintain a dedicated branch with the format `litellm_stable_release_branch_x_xx_xx` for the version.
+
+This allows easier patching for day 0 model launches.
+
+**Branch for v1.81.9:** [litellm_stable_release_branch_1_81_9](https://github.com/BerriAI/litellm/tree/litellm_stable_release_branch_1_81_9)
+
+:::
+
+## Deploy this version
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import Image from '@theme/IdealImage';
+
+
+
+
+``` showLineNumbers title="docker run litellm"
+docker run \
+-e STORE_MODEL_IN_DB=True \
+-p 4000:4000 \
+ghcr.io/berriai/litellm:main-v1.81.9-stable
+```
+
+
+
+
+``` showLineNumbers title="pip install litellm"
+pip install litellm==1.81.9
+```
+
+
+
+
+## Key Highlights
+
+- **Claude Opus 4.6** - [Full support across Anthropic, AWS Bedrock, Azure AI, and Vertex AI with adaptive thinking and 1M context window](../../blog/claude_opus_4_6)
+- **A2A Agent Gateway** - [Call A2A (Agent-to-Agent) registered agents through the standard `/chat/completions` API](../../docs/a2a_invoking_agents)
+- **Expose MCP servers on the public internet** - [Launch MCP servers with public/private visibility and IP-based access control for internet-facing deployments](../../docs/mcp_public_internet)
+- **UI Team Soft Budget Alerts** - [Set soft budgets on teams and receive email alerts when spending crosses the threshold — without blocking requests](../../docs/proxy/ui_team_soft_budget_alerts)
+- **Performance Optimizations** - Multiple performance improvements including ~40% Prometheus CPU reduction, LRU caching, and optimized logging paths
+- **LiteLLM Observatory** - [Automated 24-hour load tests](../../blog/litellm-observatory)
+- **30% Faster Request Processing for Callback-Heavy Deployments** - [Performance improvement for callback heavy deployments][PR #20354](https://github.com/BerriAI/litellm/pull/20354)
+
+---
+
+## 30% Faster Request Processing for Callback-Heavy Deployments
+
+ If you use logging callbacks like Langfuse, Datadog, or Prometheus, every request was paying an unnecessary cost: three loops that re-sorted your callbacks on every single request, even though the callback list hadn't changed. The more callbacks you had configured, the more time was wasted. We moved this work to happen once at startup instead of on every request. For deployments with the default callback set, this is a ~30% speedup in request setup. For deployments with many callbacks configured, the improvement is even larger.
+
+---
+
+## LiteLLM Observatory
+
+LiteLLM Observatory is a long-running release-validation system we built to catch regressions before they reach users. The system is built to be extensible—you can add new tests, configure models and failure thresholds, and queue runs against any deployment. Our goal is to achieve 100% coverage of LiteLLM functionality through these tests. We run 24-hour load tests against our production deployments before all releases, surfacing issues like resource lifecycle bugs, OOMs, and CPU regressions that only appear under sustained load.
+
+---
+
+## MCP Servers on the Public Internet
+
+This release makes it safe to expose MCP servers on the public internet by adding public/private visibility and IP-based access control. You can now run internet-facing MCP services while restricting access to trusted networks and keeping internal tools private.
+
+[Get started](../../docs/mcp_public_internet)
+
+
+
+## UI Team Soft Budget Alerts
+
+Set a soft budget on any team to receive email alerts when spending crosses the threshold — without blocking any requests. Configure the threshold and alerting emails directly from the Admin UI, with no proxy restart needed.
+
+[Get started](../../docs/proxy/ui_team_soft_budget_alerts)
+
+
+
+Let's dive in.
+
+---
+
+## New Models / Updated Models
+
+#### New Model Support (13 new models)
+
+| Provider | Model | Context Window | Input ($/1M tokens) | Output ($/1M tokens) |
+| -------- | ----- | -------------- | ------------------- | -------------------- |
+| Anthropic | `claude-opus-4-6` | 1M | $5.00 | $25.00 |
+| AWS Bedrock | `anthropic.claude-opus-4-6-v1` | 1M | $5.00 | $25.00 |
+| Azure AI | `azure_ai/claude-opus-4-6` | 200K | $5.00 | $25.00 |
+| Vertex AI | `vertex_ai/claude-opus-4-6` | 1M | $5.00 | $25.00 |
+| Google Gemini | `gemini/deep-research-pro-preview-12-2025` | 65K | $2.00 | $12.00 |
+| Vertex AI | `vertex_ai/deep-research-pro-preview-12-2025` | 65K | $2.00 | $12.00 |
+| Moonshot | `moonshot/kimi-k2.5` | 262K | $0.60 | $3.00 |
+| OpenRouter | `openrouter/qwen/qwen3-235b-a22b-2507` | 262K | $0.07 | $0.10 |
+| OpenRouter | `openrouter/qwen/qwen3-235b-a22b-thinking-2507` | 262K | $0.11 | $0.60 |
+| Together AI | `together_ai/zai-org/GLM-4.7` | 200K | $0.45 | $2.00 |
+| Together AI | `together_ai/moonshotai/Kimi-K2.5` | 256K | $0.50 | $2.80 |
+| ElevenLabs | `elevenlabs/eleven_v3` | - | $0.18/1K chars | - |
+| ElevenLabs | `elevenlabs/eleven_multilingual_v2` | - | $0.18/1K chars | - |
+
+#### Features
+
+- **[Anthropic](../../docs/providers/anthropic)**
+ - Full Claude Opus 4.6 support with adaptive thinking across all regions (us, eu, apac, au) - [PR #20506](https://github.com/BerriAI/litellm/pull/20506), [PR #20508](https://github.com/BerriAI/litellm/pull/20508), [PR #20514](https://github.com/BerriAI/litellm/pull/20514), [PR #20551](https://github.com/BerriAI/litellm/pull/20551)
+ - Map reasoning content to anthropic thinking block (streaming + non-streaming) - [PR #20254](https://github.com/BerriAI/litellm/pull/20254)
+
+- **[AWS Bedrock](../../docs/providers/bedrock)**
+ - Add 1hr tiered caching costs for long-context models - [PR #20214](https://github.com/BerriAI/litellm/pull/20214)
+ - Support TTL (1h) field in prompt caching for Bedrock Claude 4.5 models - [PR #20338](https://github.com/BerriAI/litellm/pull/20338)
+ - Add Nova Sonic speech-to-speech model support - [PR #20244](https://github.com/BerriAI/litellm/pull/20244)
+ - Fix empty assistant message for Converse API - [PR #20390](https://github.com/BerriAI/litellm/pull/20390)
+ - Fix content blocked handling - [PR #20606](https://github.com/BerriAI/litellm/pull/20606)
+
+- **[Google Gemini / Vertex AI](../../docs/providers/gemini)**
+ - Add Gemini Deep Research model support - [PR #20406](https://github.com/BerriAI/litellm/pull/20406)
+ - Fix Vertex AI Gemini streaming content_filter handling - [PR #20105](https://github.com/BerriAI/litellm/pull/20105)
+ - Allow using OpenAI-style tools for `web_search` with Vertex AI/Gemini models - [PR #20280](https://github.com/BerriAI/litellm/pull/20280)
+ - Fix `supports_native_streaming` for Gemini and Vertex AI models - [PR #20408](https://github.com/BerriAI/litellm/pull/20408)
+ - Add mapping for responses tools in file IDs - [PR #20402](https://github.com/BerriAI/litellm/pull/20402)
+
+- **[Cohere](../../docs/providers/cohere)**
+ - Support `dimensions` param for Cohere embed v4 - [PR #20235](https://github.com/BerriAI/litellm/pull/20235)
+
+- **[Cerebras](../../docs/providers/cerebras)**
+ - Add reasoning param support for GPT OSS Cerebras - [PR #20258](https://github.com/BerriAI/litellm/pull/20258)
+
+- **[Moonshot](../../docs/providers/moonshot)**
+ - Add Kimi K2.5 model entries - [PR #20273](https://github.com/BerriAI/litellm/pull/20273)
+
+- **[OpenRouter](../../docs/providers/openrouter)**
+ - Add Qwen3-235B models - [PR #20455](https://github.com/BerriAI/litellm/pull/20455)
+
+- **[Together AI](../../docs/providers/togetherai)**
+ - Add GLM-4.7 and Kimi-K2.5 models - [PR #20319](https://github.com/BerriAI/litellm/pull/20319)
+
+- **[ElevenLabs](../../docs/providers/elevenlabs)**
+ - Add `eleven_v3` and `eleven_multilingual_v2` TTS models - [PR #20522](https://github.com/BerriAI/litellm/pull/20522)
+
+- **[Vercel AI Gateway](../../docs/providers/vercel_ai_gateway)**
+ - Add missing capability flags to models - [PR #20276](https://github.com/BerriAI/litellm/pull/20276)
+
+- **[GitHub Copilot](../../docs/providers/github_copilot)**
+ - Fix system prompts being dropped and auto-add required Copilot headers - [PR #20113](https://github.com/BerriAI/litellm/pull/20113)
+
+- **[GigaChat](../../docs/providers/gigachat)**
+ - Fix incorrect merging of consecutive user messages for GigaChat provider - [PR #20341](https://github.com/BerriAI/litellm/pull/20341)
+
+- **[xAI](../../docs/providers/xai_realtime)**
+ - Add xAI `/realtime` API support - works with LiveKit SDK - [PR #20381](https://github.com/BerriAI/litellm/pull/20381)
+
+- **[OpenAI](../../docs/providers/openai)**
+ - Add `gpt-5-search-api` model and docs clarifications - [PR #20512](https://github.com/BerriAI/litellm/pull/20512)
+
+### Bug Fixes
+
+- **[Anthropic](../../docs/providers/anthropic)**
+ - Fix extra inputs not permitted error for `provider_specific_fields` - [PR #20334](https://github.com/BerriAI/litellm/pull/20334)
+
+- **[AWS Bedrock](../../docs/providers/bedrock)**
+ - Fix: Managed Batches inconsistent state management for list and cancel batches - [PR #20331](https://github.com/BerriAI/litellm/pull/20331)
+
+- **[OpenAI Embeddings](../../docs/providers/openai)**
+ - Fix `open_ai_embedding_models` to have `custom_llm_provider` None - [PR #20253](https://github.com/BerriAI/litellm/pull/20253)
+
+---
+
+## LLM API Endpoints
+
+#### Features
+
+- **[Messages API](../../docs/providers/anthropic)**
+ - Filter unsupported Claude Code beta headers for non-Anthropic providers - [PR #20578](https://github.com/BerriAI/litellm/pull/20578)
+ - Fix inconsistent response format in `anthropic.messages.acreate()` when using non-Anthropic providers - [PR #20442](https://github.com/BerriAI/litellm/pull/20442)
+ - Fix 404 on `/api/event_logging/batch` endpoint that caused Claude Code "route not found" errors - [PR #20504](https://github.com/BerriAI/litellm/pull/20504)
+
+- **[A2A Agent Gateway](../../docs/a2a)**
+ - Allow calling A2A agents through LiteLLM `/chat/completions` API - [PR #20358](https://github.com/BerriAI/litellm/pull/20358)
+ - Use A2A registered agents with `/chat/completions` - [PR #20362](https://github.com/BerriAI/litellm/pull/20362)
+ - Fix A2A agents deployed with localhost/internal URLs in their agent cards - [PR #20604](https://github.com/BerriAI/litellm/pull/20604)
+
+- **[Files API](../../docs/providers/gemini)**
+ - Add support for delete and GET via file_id for Gemini - [PR #20329](https://github.com/BerriAI/litellm/pull/20329)
+
+- **General**
+ - Add User-Agent customization support - [PR #19881](https://github.com/BerriAI/litellm/pull/19881)
+ - Fix search tools not found when using per-request routers - [PR #19818](https://github.com/BerriAI/litellm/pull/19818)
+ - Forward extra headers in chat - [PR #20386](https://github.com/BerriAI/litellm/pull/20386)
+
+---
+
+## Management Endpoints / UI
+
+#### Features
+
+- **SSO Configuration**
+ - SSO Config Team Mappings - [PR #20111](https://github.com/BerriAI/litellm/pull/20111)
+ - UI - SSO: Add Team Mappings - [PR #20299](https://github.com/BerriAI/litellm/pull/20299)
+ - Extract user roles from JWT access token for Keycloak compatibility - [PR #20591](https://github.com/BerriAI/litellm/pull/20591)
+
+- **Auth / SDK**
+ - Add `proxy_auth` for auto OAuth2/JWT token management in SDK - [PR #20238](https://github.com/BerriAI/litellm/pull/20238)
+
+- **Virtual Keys**
+ - Key `reset_spend` endpoint - [PR #20305](https://github.com/BerriAI/litellm/pull/20305)
+ - UI - Keys: Allowed Routes to Key Info and Edit Pages - [PR #20369](https://github.com/BerriAI/litellm/pull/20369)
+ - Add Key info endpoint object permission data - [PR #20407](https://github.com/BerriAI/litellm/pull/20407)
+ - Keys and Teams Router Setting + Allow Override of Router Settings - [PR #20205](https://github.com/BerriAI/litellm/pull/20205)
+
+- **Teams & Budgets**
+ - Add `soft_budget` to Team Table + Create/Update Endpoints - [PR #20530](https://github.com/BerriAI/litellm/pull/20530)
+ - Team Soft Budget Email Alerts - [PR #20553](https://github.com/BerriAI/litellm/pull/20553)
+ - UI - Team Settings: Soft Budget + Alerting Emails - [PR #20634](https://github.com/BerriAI/litellm/pull/20634)
+ - UI - User Budget Page: Unlimited Budget Checkbox - [PR #20380](https://github.com/BerriAI/litellm/pull/20380)
+ - `/user/update` allow for `max_budget` resets - [PR #20375](https://github.com/BerriAI/litellm/pull/20375)
+
+- **UI Improvements**
+ - Default Team Settings: Migrate to use Reusable Model Select - [PR #20310](https://github.com/BerriAI/litellm/pull/20310)
+ - Navbar: Option to Hide Community Engagement Buttons - [PR #20308](https://github.com/BerriAI/litellm/pull/20308)
+ - Show team alias on Models health page - [PR #20359](https://github.com/BerriAI/litellm/pull/20359)
+ - Admin Settings: Add option for Authentication for public AI Hub - [PR #20444](https://github.com/BerriAI/litellm/pull/20444)
+ - Adjust daily spend date filtering for user timezone - [PR #20472](https://github.com/BerriAI/litellm/pull/20472)
+
+- **SCIM**
+ - Add base `/scim/v2` endpoint for SCIM resource discovery - [PR #20301](https://github.com/BerriAI/litellm/pull/20301)
+
+- **Proxy CLI**
+ - CLI arguments for RDS IAM auth - [PR #20437](https://github.com/BerriAI/litellm/pull/20437)
+
+#### Bugs
+
+- Fix: Remove unnecessary key blocking on UI login that prevented access - [PR #20210](https://github.com/BerriAI/litellm/pull/20210)
+- UI - Team Settings: Disable Global Guardrail Persistence - [PR #20307](https://github.com/BerriAI/litellm/pull/20307)
+- UI - Model Info Page: Fix Input and Output Labels - [PR #20462](https://github.com/BerriAI/litellm/pull/20462)
+- UI - Model Page: Column Resizing on Smaller Screens - [PR #20599](https://github.com/BerriAI/litellm/pull/20599)
+- Fix `/key/list` `user_id` Empty String Edge Case - [PR #20623](https://github.com/BerriAI/litellm/pull/20623)
+- Add array type checks for model, agent, and MCP hub data to prevent UI crashes - [PR #20469](https://github.com/BerriAI/litellm/pull/20469)
+- Fix unique constraint on daily tables + logging when updates fail - [PR #20394](https://github.com/BerriAI/litellm/pull/20394)
+
+---
+
+## Logging / Guardrail / Prompt Management Integrations
+
+#### Bug Fixes (3 fixes)
+
+- **[Langfuse](../../docs/proxy/logging#langfuse)**
+ - Fix Langfuse OTEL trace export failing when spans contain null attributes - [PR #20382](https://github.com/BerriAI/litellm/pull/20382)
+
+- **[Prometheus](../../docs/proxy/logging#prometheus)**
+ - Fix incorrect failure metrics labels causing miscounted error rates - [PR #20152](https://github.com/BerriAI/litellm/pull/20152)
+
+- **[Slack Alerts](../../docs/proxy/alerting)**
+ - Fix Slack alert delivery failing for certain budget threshold configurations - [PR #20257](https://github.com/BerriAI/litellm/pull/20257)
+
+#### Guardrails (7 updates)
+
+- **Custom Code Guardrails**
+ - Add HTTP support to custom code guardrails + Unified guardrails for MCP + Agent guardrail support - [PR #20619](https://github.com/BerriAI/litellm/pull/20619)
+ - Custom Code Guardrails UI Playground - [PR #20377](https://github.com/BerriAI/litellm/pull/20377)
+
+- **Team-Based Guardrails**
+ - Implement team-based isolation guardrails management - [PR #20318](https://github.com/BerriAI/litellm/pull/20318)
+
+- **[OpenAI Moderations](../../docs/apply_guardrail)**
+ - Ensure OpenAI Moderations Guard works with OpenAI Embeddings - [PR #20523](https://github.com/BerriAI/litellm/pull/20523)
+
+- **[GraySwan / Cygnal](../../docs/apply_guardrail)**
+ - Fix fail-open for GraySwan and pass metadata to Cygnal API endpoint - [PR #19837](https://github.com/BerriAI/litellm/pull/19837)
+
+- **General**
+ - Check for `model_response_choices` before guardrail input - [PR #19784](https://github.com/BerriAI/litellm/pull/19784)
+ - Preserve streaming content on guardrail-sampled chunks - [PR #20027](https://github.com/BerriAI/litellm/pull/20027)
+
+---
+
+## Spend Tracking, Budgets and Rate Limiting
+
+- **Support 0 cost models** - Allow zero-cost model entries for internal/free-tier models - [PR #20249](https://github.com/BerriAI/litellm/pull/20249)
+
+---
+
+## MCP Gateway (9 updates)
+
+- **MCP Semantic Filtering** - Filter MCP tools using semantic similarity to reduce tool sprawl for LLM calls - [PR #20296](https://github.com/BerriAI/litellm/pull/20296), [PR #20316](https://github.com/BerriAI/litellm/pull/20316)
+- **UI - MCP Semantic Filtering** - Add support for MCP Semantic Filtering configuration on UI - [PR #20454](https://github.com/BerriAI/litellm/pull/20454)
+- **MCP IP-Based Access Control** - Set MCP servers as private/public available on internet with IP-based restrictions - [PR #20607](https://github.com/BerriAI/litellm/pull/20607), [PR #20620](https://github.com/BerriAI/litellm/pull/20620)
+- **Fix MCP "Session not found" error** on VSCode reconnect - [PR #20298](https://github.com/BerriAI/litellm/pull/20298)
+- **Fix OAuth2 'Capabilities: none' bug** for upstream MCP servers - [PR #20602](https://github.com/BerriAI/litellm/pull/20602)
+- **Include Config Defined Search Tools** in `/search_tools/list` - [PR #20371](https://github.com/BerriAI/litellm/pull/20371)
+- **UI - Search Tools**: Show Config Defined Search Tools - [PR #20436](https://github.com/BerriAI/litellm/pull/20436)
+- **Ensure MCP permissions are enforced** when using JWT Auth - [PR #20383](https://github.com/BerriAI/litellm/pull/20383)
+- **Fix `gcs_bucket_name` not being passed** correctly for MCP server storage configuration - [PR #20491](https://github.com/BerriAI/litellm/pull/20491)
+
+---
+
+## Performance / Loadbalancing / Reliability improvements (14 improvements)
+
+- **Prometheus ~40% CPU reduction** - Parallelize budget metrics, fix caching bug, reduce CPU usage - [PR #20544](https://github.com/BerriAI/litellm/pull/20544)
+- **Prevent closed client errors** by reverting httpx client caching - [PR #20025](https://github.com/BerriAI/litellm/pull/20025)
+- **Avoid unnecessary Router creation** when no models or search tools are configured - [PR #20661](https://github.com/BerriAI/litellm/pull/20661)
+- **Optimize `wrapper_async`** with `CallTypes` caching and reduced lookups - [PR #20204](https://github.com/BerriAI/litellm/pull/20204)
+- **Cache `_get_relevant_args_to_use_for_logging()`** at module level - [PR #20077](https://github.com/BerriAI/litellm/pull/20077)
+- **LRU cache for `normalize_request_route`** - [PR #19812](https://github.com/BerriAI/litellm/pull/19812)
+- **Optimize `get_standard_logging_metadata`** with set intersection - [PR #19685](https://github.com/BerriAI/litellm/pull/19685)
+- **Early-exit guards in `completion_cost`** for unused features - [PR #20020](https://github.com/BerriAI/litellm/pull/20020)
+- **Optimize `get_litellm_params`** with sparse kwargs extraction - [PR #19884](https://github.com/BerriAI/litellm/pull/19884)
+- **Guard debug log f-strings** and remove redundant dict copies - [PR #19961](https://github.com/BerriAI/litellm/pull/19961)
+- **Replace enum construction with frozenset lookup** - [PR #20302](https://github.com/BerriAI/litellm/pull/20302)
+- **Guard debug f-string in `update_environment_variables`** - [PR #20360](https://github.com/BerriAI/litellm/pull/20360)
+- **Warn when budget lookup fails** to surface silent caching misses - [PR #20545](https://github.com/BerriAI/litellm/pull/20545)
+- **Add INFO-level session reuse logging** per request for better observability - [PR #20597](https://github.com/BerriAI/litellm/pull/20597)
+
+---
+
+## Database Changes
+
+### Schema Updates
+
+| Table | Change Type | Description | PR | Migration |
+| ----- | ----------- | ----------- | -- | --------- |
+| `LiteLLM_TeamTable` | New Column | Added `allow_team_guardrail_config` boolean field for team-based guardrail isolation | [PR #20318](https://github.com/BerriAI/litellm/pull/20318) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205091235_allow_team_guardrail_config/migration.sql) |
+| `LiteLLM_DeletedTeamTable` | New Column | Added `allow_team_guardrail_config` boolean field | [PR #20318](https://github.com/BerriAI/litellm/pull/20318) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205091235_allow_team_guardrail_config/migration.sql) |
+| `LiteLLM_TeamTable` | New Column | Added `soft_budget` (double precision) for soft budget alerting | [PR #20530](https://github.com/BerriAI/litellm/pull/20530) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205144610_add_soft_budget_to_team_table/migration.sql) |
+| `LiteLLM_DeletedTeamTable` | New Column | Added `soft_budget` (double precision) | [PR #20653](https://github.com/BerriAI/litellm/pull/20653) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260207110613_add_soft_budget_to_deleted_teams_table/migration.sql) |
+| `LiteLLM_MCPServerTable` | New Column | Added `available_on_public_internet` boolean for MCP IP-based access control | [PR #20607](https://github.com/BerriAI/litellm/pull/20607) | [Migration](https://github.com/BerriAI/litellm/blob/main/litellm-proxy-extras/litellm_proxy_extras/migrations/20260207093506_add_available_on_public_internet_to_mcp_servers/migration.sql) |
+
+---
+
+## Documentation Updates (14 updates)
+
+- Add FAQ for setting up and verifying LITELLM_LICENSE - [PR #20284](https://github.com/BerriAI/litellm/pull/20284)
+- Model request tags documentation - [PR #20290](https://github.com/BerriAI/litellm/pull/20290)
+- Add Prisma migration troubleshooting guide - [PR #20300](https://github.com/BerriAI/litellm/pull/20300)
+- MCP Semantic Filtering documentation - [PR #20316](https://github.com/BerriAI/litellm/pull/20316)
+- Add CopilotKit SDK doc as supported agents SDK - [PR #20396](https://github.com/BerriAI/litellm/pull/20396)
+- Add documentation for Nova Sonic - [PR #20320](https://github.com/BerriAI/litellm/pull/20320)
+- Update Vertex AI Text to Speech doc to show use of audio - [PR #20255](https://github.com/BerriAI/litellm/pull/20255)
+- Improve Okta SSO setup guide with step-by-step instructions - [PR #20353](https://github.com/BerriAI/litellm/pull/20353)
+- Langfuse doc update - [PR #20443](https://github.com/BerriAI/litellm/pull/20443)
+- Expose MCPs on public internet documentation - [PR #20626](https://github.com/BerriAI/litellm/pull/20626)
+- Add blog post: Achieving Sub-Millisecond Proxy Overhead - [PR #20309](https://github.com/BerriAI/litellm/pull/20309)
+- Add blog post about litellm-observatory - [PR #20622](https://github.com/BerriAI/litellm/pull/20622)
+- Update Opus 4.6 blog with adaptive thinking - [PR #20637](https://github.com/BerriAI/litellm/pull/20637)
+- `gpt-5-search-api` docs clarifications - [PR #20512](https://github.com/BerriAI/litellm/pull/20512)
+
+---
+
+## New Contributors
+* @Quentin-M made their first contribution in [PR #19818](https://github.com/BerriAI/litellm/pull/19818)
+* @amirzaushnizer made their first contribution in [PR #20235](https://github.com/BerriAI/litellm/pull/20235)
+* @cscguochang made their first contribution in [PR #20214](https://github.com/BerriAI/litellm/pull/20214)
+* @krauckbot made their first contribution in [PR #20273](https://github.com/BerriAI/litellm/pull/20273)
+* @agrattan0820 made their first contribution in [PR #19784](https://github.com/BerriAI/litellm/pull/19784)
+* @nina-hu made their first contribution in [PR #20472](https://github.com/BerriAI/litellm/pull/20472)
+* @swayambhu94 made their first contribution in [PR #20469](https://github.com/BerriAI/litellm/pull/20469)
+* @ssadedin made their first contribution in [PR #20566](https://github.com/BerriAI/litellm/pull/20566)
+
+---
+
+## Full Changelog
+[v1.81.6-nightly...v1.81.9](https://github.com/BerriAI/litellm/compare/v1.81.6-nightly...v1.81.9)
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index 2db4fb33daa..3acfa3937a9 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -43,46 +43,62 @@ const sidebars = {
items: [
"proxy/guardrails/quick_start",
"proxy/guardrails/guardrail_load_balancing",
+ "proxy/guardrails/test_playground",
+ "proxy/guardrails/litellm_content_filter",
{
type: "category",
- "label": "Contributing to Guardrails",
+ label: "Providers",
+ items: [
+ ...[
+ "proxy/guardrails/qualifire",
+ "proxy/guardrails/aim_security",
+ "proxy/guardrails/onyx_security",
+ "proxy/guardrails/aporia_api",
+ "proxy/guardrails/azure_content_guardrail",
+ "proxy/guardrails/bedrock",
+ "proxy/guardrails/enkryptai",
+ "proxy/guardrails/ibm_guardrails",
+ "proxy/guardrails/grayswan",
+ "proxy/guardrails/hiddenlayer",
+ "proxy/guardrails/lasso_security",
+ "proxy/guardrails/guardrails_ai",
+ "proxy/guardrails/lakera_ai",
+ "proxy/guardrails/model_armor",
+ "proxy/guardrails/noma_security",
+ "proxy/guardrails/dynamoai",
+ "proxy/guardrails/openai_moderation",
+ "proxy/guardrails/pangea",
+ "proxy/guardrails/pillar_security",
+ "proxy/guardrails/pii_masking_v2",
+ "proxy/guardrails/panw_prisma_airs",
+ "proxy/guardrails/secret_detection",
+ "proxy/guardrails/custom_guardrail",
+ "proxy/guardrails/custom_code_guardrail",
+ "proxy/guardrails/prompt_injection",
+ "proxy/guardrails/tool_permission",
+ "proxy/guardrails/zscaler_ai_guard",
+ "proxy/guardrails/javelin"
+ ].sort(),
+ ],
+ },
+ {
+ type: "category",
+ label: "Contributing to Guardrails",
items: [
"adding_provider/generic_guardrail_api",
"adding_provider/simple_guardrail_tutorial",
"adding_provider/adding_guardrail_support",
]
},
- "proxy/guardrails/test_playground",
- "proxy/guardrails/litellm_content_filter",
- ...[
- "proxy/guardrails/qualifire",
- "proxy/guardrails/aim_security",
- "proxy/guardrails/onyx_security",
- "proxy/guardrails/aporia_api",
- "proxy/guardrails/azure_content_guardrail",
- "proxy/guardrails/bedrock",
- "proxy/guardrails/enkryptai",
- "proxy/guardrails/ibm_guardrails",
- "proxy/guardrails/grayswan",
- "proxy/guardrails/hiddenlayer",
- "proxy/guardrails/lasso_security",
- "proxy/guardrails/guardrails_ai",
- "proxy/guardrails/lakera_ai",
- "proxy/guardrails/model_armor",
- "proxy/guardrails/noma_security",
- "proxy/guardrails/dynamoai",
- "proxy/guardrails/openai_moderation",
- "proxy/guardrails/pangea",
- "proxy/guardrails/pillar_security",
- "proxy/guardrails/pii_masking_v2",
- "proxy/guardrails/panw_prisma_airs",
- "proxy/guardrails/secret_detection",
- "proxy/guardrails/custom_guardrail",
- "proxy/guardrails/prompt_injection",
- "proxy/guardrails/tool_permission",
- "proxy/guardrails/zscaler_ai_guard",
- "proxy/guardrails/javelin"
- ].sort(),
+ ],
+ },
+ {
+ type: "category",
+ label: "Policies",
+ items: [
+ "proxy/guardrails/guardrail_policies",
+ "proxy/guardrails/policy_templates",
+ "proxy/guardrails/policy_tags",
],
},
{
@@ -91,13 +107,26 @@ const sidebars = {
items: [
"proxy/alerting",
"proxy/pagerduty",
- "proxy/prometheus"
+ "proxy/prometheus",
+ "proxy/pyroscope_profiling"
]
},
+ {
+ type: "doc",
+ id: "integrations/websearch_interception",
+ label: "Web Search Integration"
+ },
{
type: "category",
label: "[Beta] Prompt Management",
items: [
+ {
+ type: "category",
+ label: "Contributing to Prompt Management",
+ items: [
+ "adding_provider/generic_prompt_management_api",
+ ]
+ },
"proxy/litellm_prompt_management",
"proxy/custom_prompt_management",
"proxy/native_litellm_prompt",
@@ -123,10 +152,12 @@ const sidebars = {
"tutorials/claude_responses_api",
"tutorials/claude_code_max_subscription",
"tutorials/claude_code_customer_tracking",
+ "tutorials/claude_code_prompt_cache_routing",
"tutorials/claude_code_websearch",
"tutorials/claude_mcp",
"tutorials/claude_non_anthropic_models",
"tutorials/claude_code_plugin_marketplace",
+ "tutorials/claude_code_beta_headers",
]
},
"tutorials/opencode_integration",
@@ -138,6 +169,23 @@ const sidebars = {
"tutorials/openai_codex"
]
},
+ {
+ type: "category",
+ label: "Agent SDKs",
+ link: {
+ type: "generated-index",
+ title: "Agent SDKs",
+ description: "Use LiteLLM with agent frameworks and SDKs",
+ slug: "/agent_sdks"
+ },
+ items: [
+ "tutorials/claude_agent_sdk",
+ "tutorials/copilotkit_sdk",
+ "tutorials/google_adk",
+ "tutorials/livekit_xai_realtime",
+ "projects/openai-agents"
+ ]
+ },
],
// But you can create a sidebar manually
@@ -204,6 +252,7 @@ const sidebars = {
label: "Configuration",
items: [
"set_keys",
+ "proxy_auth",
"caching/all_caches",
],
},
@@ -268,31 +317,52 @@ const sidebars = {
label: "Admin UI",
items: [
"proxy/ui",
- "proxy/admin_ui_sso",
- "proxy/custom_root_ui",
- "proxy/custom_sso",
- "proxy/ai_hub",
- "proxy/model_compare_ui",
- "proxy/public_teams",
- "proxy/self_serve",
- "proxy/ui/bulk_edit_users",
- "proxy/ui_credentials",
- "tutorials/scim_litellm",
{
type: "category",
- label: "UI Usage Tracking",
+ label: "Setup & SSO",
items: [
- "proxy/customer_usage",
- "proxy/endpoint_activity"
+ "proxy/admin_ui_sso",
+ "proxy/custom_sso",
+ "proxy/custom_root_ui",
+ "tutorials/scim_litellm",
]
},
{
type: "category",
- label: "UI Logs",
+ label: "Models",
+ items: [
+ "proxy/ui_credentials",
+ "proxy/ai_hub",
+ "proxy/model_compare_ui",
+ ]
+ },
+ {
+ type: "category",
+ label: "Teams & Organizations",
+ items: [
+ "proxy/access_control",
+ "proxy/self_serve",
+ "proxy/public_teams",
+ "proxy/ui/bulk_edit_users",
+ "proxy/ui/page_visibility",
+ ]
+ },
+ {
+ type: "category",
+ label: "Observability: Usage",
+ items: [
+ "proxy/customer_usage",
+ "proxy/endpoint_activity",
+ ]
+ },
+ {
+ type: "category",
+ label: "Logs",
items: [
"proxy/ui_logs",
+ "proxy/ui_spend_log_settings",
"proxy/ui_logs_sessions",
- "proxy/deleted_keys_teams"
+ "proxy/deleted_keys_teams",
]
}
],
@@ -340,6 +410,7 @@ const sidebars = {
items: [
"proxy/users",
"proxy/team_budgets",
+ "proxy/ui_team_soft_budget_alerts",
"proxy/tag_budgets",
"proxy/customers",
"proxy/dynamic_rate_limit",
@@ -348,6 +419,16 @@ const sidebars = {
],
},
"proxy/caching",
+ {
+ type: "link",
+ label: "Guardrails",
+ href: "https://docs.litellm.ai/docs/proxy/guardrails/quick_start",
+ },
+ {
+ type: "link",
+ label: "Policies",
+ href: "https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",
+ },
{
type: "category",
label: "Create Custom Plugins",
@@ -363,6 +444,7 @@ const sidebars = {
label: "Load Balancing, Routing, Fallbacks",
href: "https://docs.litellm.ai/docs/routing-load-balancing",
},
+ "traffic_mirroring",
{
type: "category",
label: "Logging, Alerting, Metrics",
@@ -393,6 +475,7 @@ const sidebars = {
"proxy/model_access_guide",
"proxy/model_access",
"proxy/model_access_groups",
+ "proxy/access_groups",
"proxy/team_model_add"
]
},
@@ -417,6 +500,7 @@ const sidebars = {
label: "Spend Tracking",
items: [
"proxy/cost_tracking",
+ "proxy/request_tags",
"proxy/custom_pricing",
"proxy/pricing_calculator",
"proxy/provider_margins",
@@ -443,6 +527,7 @@ const sidebars = {
label: "/a2a - A2A Agent Gateway",
items: [
"a2a",
+ "a2a_invoking_agents",
"a2a_cost_tracking",
"a2a_agent_permissions"
],
@@ -495,6 +580,7 @@ const sidebars = {
"proxy/managed_finetuning",
]
},
+ "evals_api",
"generateContent",
"apply_guardrail",
"bedrock_invoke",
@@ -512,6 +598,9 @@ const sidebars = {
items: [
"mcp",
"mcp_usage",
+ "mcp_oauth",
+ "mcp_public_internet",
+ "mcp_semantic_filter",
"mcp_control",
"mcp_cost",
"mcp_guardrail",
@@ -690,6 +779,7 @@ const sidebars = {
"providers/bedrock_agents",
"providers/bedrock_writer",
"providers/bedrock_batches",
+ "providers/bedrock_realtime_with_audio",
"providers/aws_polly",
"providers/bedrock_vector_store",
]
@@ -774,6 +864,7 @@ const sidebars = {
"providers/oci",
"providers/ollama",
"providers/openrouter",
+ "providers/sarvam",
"providers/ovhcloud",
"providers/perplexity",
"providers/petals",
@@ -794,6 +885,7 @@ const sidebars = {
},
"providers/sambanova",
"providers/sap",
+ "providers/scaleway",
"providers/stability",
"providers/synthetic",
"providers/snowflake",
@@ -821,7 +913,14 @@ const sidebars = {
"providers/watsonx/audio_transcription",
]
},
- "providers/xai",
+ {
+ type: "category",
+ label: "xAI",
+ items: [
+ "providers/xai",
+ "providers/xai_realtime",
+ ]
+ },
"providers/xiaomi_mimo",
"providers/xinference",
"providers/zai",
@@ -842,8 +941,10 @@ const sidebars = {
"completion/image_generation_chat",
"completion/json_mode",
"completion/knowledgebase",
+ "providers/anthropic_tool_search",
"guides/code_interpreter",
"completion/message_trimming",
+ "completion/message_sanitization",
"completion/model_alias",
"completion/mock_requests",
"completion/predict_outputs",
@@ -878,6 +979,7 @@ const sidebars = {
"scheduler",
"proxy/auto_routing",
"proxy/load_balancing",
+ "proxy/keys_teams_router_settings",
"proxy/provider_budget_routing",
"proxy/reliability",
"proxy/fallback_management",
@@ -914,11 +1016,11 @@ const sidebars = {
"tutorials/presidio_pii_masking",
"tutorials/elasticsearch_logging",
"tutorials/gemini_realtime_with_audio",
+ "tutorials/claude_code_beta_headers",
{
type: "category",
label: "LiteLLM Python SDK Tutorials",
items: [
- 'tutorials/google_adk',
'tutorials/azure_openai',
'tutorials/instructor',
"tutorials/gradio_integration",
@@ -1009,13 +1111,40 @@ const sidebars = {
"proxy_server",
],
},
- "troubleshoot",
{
type: "category",
- label: "Issue Reporting",
+ label: "Troubleshooting",
items: [
- "troubleshoot/cpu_issues",
- "troubleshoot/memory_issues",
+ "troubleshoot/ui_issues",
+ "mcp_troubleshoot",
+ {
+ type: "category",
+ label: "Performance / Latency",
+ items: [
+ "troubleshoot/cpu_issues",
+ "troubleshoot/memory_issues",
+ "troubleshoot/spend_queue_warnings",
+ "troubleshoot/max_callbacks",
+ "troubleshoot/prisma_migrations",
+ ],
+ },
+ "troubleshoot",
+ ],
+ },
+ {
+ type: "category",
+ label: "Blog",
+ items: [
+ {
+ type: "link",
+ label: "Day 0 Support: Claude Sonnet 4.6",
+ href: "/blog/claude_sonnet_4_6",
+ },
+ {
+ type: "link",
+ label: "Incident: Broken Model Cost Map",
+ href: "/blog/model-cost-map-incident",
+ },
],
},
],
diff --git a/docs/my-website/src/components/MiddlewareDiagrams/BaseHTTPMiddlewareAnimation.tsx b/docs/my-website/src/components/MiddlewareDiagrams/BaseHTTPMiddlewareAnimation.tsx
new file mode 100644
index 00000000000..0821cf353c6
--- /dev/null
+++ b/docs/my-website/src/components/MiddlewareDiagrams/BaseHTTPMiddlewareAnimation.tsx
@@ -0,0 +1,133 @@
+import React, { useState, useEffect, useCallback, useRef } from 'react';
+import styles from './styles.module.css';
+
+interface Stage {
+ label: string;
+ subtitle: string;
+ code: string;
+}
+
+const STAGES: Stage[] = [
+ {
+ label: 'Request Wrapping',
+ subtitle: '_CachedRequest',
+ code: 'request = _CachedRequest(scope, receive)',
+ },
+ {
+ label: 'Sync Event',
+ subtitle: 'anyio.Event()',
+ code: 'response_sent = anyio.Event()',
+ },
+ {
+ label: 'Memory Stream',
+ subtitle: 'create_memory_object_stream()',
+ code: 'send_stream, recv_stream = anyio.create_memory_object_stream()',
+ },
+ {
+ label: 'Task Group',
+ subtitle: 'create_task_group()',
+ code: 'async with anyio.create_task_group() as task_group:',
+ },
+ {
+ label: 'Background Task',
+ subtitle: 'task_group.start_soon(coro)',
+ code: 'task_group.start_soon(coro) # app runs in separate task',
+ },
+ {
+ label: 'Nested Task Group',
+ subtitle: 'receive_or_disconnect()',
+ code: 'async with anyio.create_task_group() as task_group: ...',
+ },
+ {
+ label: 'Response Wrapping',
+ subtitle: '_StreamingResponse',
+ code: 'response = _StreamingResponse(status_code=..., content=body_stream())',
+ },
+];
+
+const INTERVAL_MS = 1200;
+const PAUSE_MS = 600;
+
+export default function BaseHTTPMiddlewareAnimation() {
+ const [activeStage, setActiveStage] = useState(0);
+ const [paused, setPaused] = useState(false);
+ const [expandedStage, setExpandedStage] = useState(null);
+ const timerRef = useRef | null>(null);
+
+ const clearTimer = useCallback(() => {
+ if (timerRef.current !== null) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ }, []);
+
+ useEffect(() => {
+ if (paused) return;
+
+ const advance = () => {
+ setActiveStage((prev) => {
+ const next = (prev + 1) % STAGES.length;
+ // If wrapping around, add extra pause
+ if (next === 0) {
+ timerRef.current = setTimeout(() => {
+ timerRef.current = setTimeout(advance, INTERVAL_MS);
+ }, PAUSE_MS);
+ return next;
+ }
+ timerRef.current = setTimeout(advance, INTERVAL_MS);
+ return next;
+ });
+ };
+
+ timerRef.current = setTimeout(advance, INTERVAL_MS);
+ return clearTimer;
+ }, [paused, clearTimer]);
+
+ const handleStageClick = (index: number) => {
+ clearTimer();
+ setPaused(true);
+ setActiveStage(index);
+
+ if (expandedStage === index) {
+ // Close panel and resume
+ setExpandedStage(null);
+ setPaused(false);
+ } else {
+ setExpandedStage(index);
+ }
+ };
+
+ return (
+
+ ⚠️ Note: Your API requests will continue to work, but you should monitor your usage closely.
+ If you reach your maximum budget, requests will be rejected.
+
+
+ You can view your usage and manage your budget in the LiteLLM Dashboard.
+
+ If you have any questions, please send an email to {email_support_contact}
+
+ Best,
+ The LiteLLM team
+"""
+
MAX_BUDGET_ALERT_EMAIL_TEMPLATE = """
diff --git a/litellm/integrations/gcs_bucket/gcs_bucket.py b/litellm/integrations/gcs_bucket/gcs_bucket.py
index 3cb62905531..0f1ba4a4093 100644
--- a/litellm/integrations/gcs_bucket/gcs_bucket.py
+++ b/litellm/integrations/gcs_bucket/gcs_bucket.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from urllib.parse import quote
from litellm._logging import verbose_logger
+from litellm.constants import LITELLM_ASYNCIO_QUEUE_MAXSIZE
from litellm.integrations.additional_logging_utils import AdditionalLoggingUtils
from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase
from litellm.proxy._types import CommonProxyErrors
@@ -41,7 +42,9 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils):
batch_size=self.batch_size,
flush_interval=self.flush_interval,
)
- self.log_queue: asyncio.Queue[GCSLogQueueItem] = asyncio.Queue() # type: ignore[assignment]
+ self.log_queue: asyncio.Queue[GCSLogQueueItem] = asyncio.Queue( # type: ignore[assignment]
+ maxsize=LITELLM_ASYNCIO_QUEUE_MAXSIZE
+ )
asyncio.create_task(self.periodic_flush())
AdditionalLoggingUtils.__init__(self)
@@ -69,6 +72,9 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils):
)
if logging_payload is None:
raise ValueError("standard_logging_object not found in kwargs")
+ # When queue is at maxsize, flush immediately to make room (no blocking, no data dropped)
+ if self.log_queue.full():
+ await self.flush_queue()
await self.log_queue.put(
GCSLogQueueItem(
payload=logging_payload, kwargs=kwargs, response_obj=response_obj
@@ -91,9 +97,9 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils):
)
if logging_payload is None:
raise ValueError("standard_logging_object not found in kwargs")
- # Add to logging queue - this will be flushed periodically
- # Use asyncio.Queue.put() for thread-safe concurrent access
- # If queue is full, this will block until space is available (backpressure)
+ # When queue is at maxsize, flush immediately to make room (no blocking, no data dropped)
+ if self.log_queue.full():
+ await self.flush_queue()
await self.log_queue.put(
GCSLogQueueItem(
payload=logging_payload, kwargs=kwargs, response_obj=response_obj
diff --git a/litellm/integrations/gcs_bucket/gcs_bucket_base.py b/litellm/integrations/gcs_bucket/gcs_bucket_base.py
index 2612face050..b1db9ec9588 100644
--- a/litellm/integrations/gcs_bucket/gcs_bucket_base.py
+++ b/litellm/integrations/gcs_bucket/gcs_bucket_base.py
@@ -2,6 +2,13 @@ import json
import os
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
+from litellm.integrations.gcs_bucket.gcs_bucket_mock_client import (
+ should_use_gcs_mock,
+ create_mock_gcs_client,
+ mock_vertex_auth_methods,
+)
+
+
from litellm._logging import verbose_logger
from litellm.integrations.custom_batch_logger import CustomBatchLogger
from litellm.llms.custom_httpx.http_handler import (
@@ -20,6 +27,12 @@ IAM_AUTH_KEY = "IAM_AUTH"
class GCSBucketBase(CustomBatchLogger):
def __init__(self, bucket_name: Optional[str] = None, **kwargs) -> None:
+ self.is_mock_mode = should_use_gcs_mock()
+
+ if self.is_mock_mode:
+ mock_vertex_auth_methods()
+ create_mock_gcs_client()
+
self.async_httpx_client = get_async_httpx_client(
llm_provider=httpxSpecialProvider.LoggingCallback
)
diff --git a/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py b/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py
new file mode 100644
index 00000000000..2d14f5eb962
--- /dev/null
+++ b/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py
@@ -0,0 +1,192 @@
+"""
+Mock client for GCS Bucket integration testing.
+
+This module intercepts GCS API calls and Vertex AI auth calls, returning successful
+mock responses, allowing full code execution without making actual network calls.
+
+Usage:
+ Set GCS_MOCK=true in environment variables or config to enable mock mode.
+"""
+
+import asyncio
+
+from litellm._logging import verbose_logger
+from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory, MockResponse
+
+# Use factory for POST handler
+_config = MockClientConfig(
+ name="GCS",
+ env_var="GCS_MOCK",
+ default_latency_ms=150,
+ default_status_code=200,
+ default_json_data={"kind": "storage#object", "name": "mock-object"},
+ url_matchers=["storage.googleapis.com"],
+ patch_async_handler=True,
+ patch_sync_client=False,
+)
+
+_create_mock_gcs_post, should_use_gcs_mock = create_mock_client_factory(_config)
+
+# Store original methods for GET/DELETE (GCS-specific)
+_original_async_handler_get = None
+_original_async_handler_delete = None
+_mocks_initialized = False
+
+# Default mock latency in seconds (simulates network round-trip)
+# Typical GCS API calls take 100-300ms for uploads, 50-150ms for GET/DELETE
+_MOCK_LATENCY_SECONDS = float(__import__("os").getenv("GCS_MOCK_LATENCY_MS", "150")) / 1000.0
+
+
+async def _mock_async_handler_get(self, url, params=None, headers=None, follow_redirects=None):
+ """Monkey-patched AsyncHTTPHandler.get that intercepts GCS calls."""
+ # Only mock GCS API calls
+ if isinstance(url, str) and "storage.googleapis.com" in url:
+ verbose_logger.info(f"[GCS MOCK] GET to {url}")
+ await asyncio.sleep(_MOCK_LATENCY_SECONDS)
+ # Return a minimal but valid StandardLoggingPayload JSON string as bytes
+ # This matches what GCS returns when downloading with ?alt=media
+ mock_payload = {
+ "id": "mock-request-id",
+ "trace_id": "mock-trace-id",
+ "call_type": "completion",
+ "stream": False,
+ "response_cost": 0.0,
+ "status": "success",
+ "status_fields": {"llm_api_status": "success"},
+ "custom_llm_provider": "mock",
+ "total_tokens": 0,
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "startTime": 0.0,
+ "endTime": 0.0,
+ "completionStartTime": 0.0,
+ "response_time": 0.0,
+ "model_map_information": {"model": "mock-model"},
+ "model": "mock-model",
+ "model_id": None,
+ "model_group": None,
+ "api_base": "https://api.mock.com",
+ "metadata": {},
+ "cache_hit": None,
+ "cache_key": None,
+ "saved_cache_cost": 0.0,
+ "request_tags": [],
+ "end_user": None,
+ "requester_ip_address": None,
+ "messages": None,
+ "response": None,
+ "error_str": None,
+ "error_information": None,
+ "model_parameters": {},
+ "hidden_params": {},
+ "guardrail_information": None,
+ "standard_built_in_tools_params": None,
+ }
+ return MockResponse(
+ status_code=200,
+ json_data=mock_payload,
+ url=url,
+ elapsed_seconds=_MOCK_LATENCY_SECONDS
+ )
+ if _original_async_handler_get is not None:
+ return await _original_async_handler_get(self, url=url, params=params, headers=headers, follow_redirects=follow_redirects)
+ raise RuntimeError("Original AsyncHTTPHandler.get not available")
+
+
+async def _mock_async_handler_delete(self, url, data=None, json=None, params=None, headers=None, timeout=None, stream=False, content=None):
+ """Monkey-patched AsyncHTTPHandler.delete that intercepts GCS calls."""
+ # Only mock GCS API calls
+ if isinstance(url, str) and "storage.googleapis.com" in url:
+ verbose_logger.info(f"[GCS MOCK] DELETE to {url}")
+ await asyncio.sleep(_MOCK_LATENCY_SECONDS)
+ # DELETE returns 204 No Content with empty body (not JSON)
+ return MockResponse(
+ status_code=204,
+ json_data=None, # Empty body for DELETE
+ url=url,
+ elapsed_seconds=_MOCK_LATENCY_SECONDS
+ )
+ if _original_async_handler_delete is not None:
+ return await _original_async_handler_delete(self, url=url, data=data, json=json, params=params, headers=headers, timeout=timeout, stream=stream, content=content)
+ raise RuntimeError("Original AsyncHTTPHandler.delete not available")
+
+
+def create_mock_gcs_client():
+ """
+ Monkey-patch AsyncHTTPHandler methods to intercept GCS calls.
+
+ AsyncHTTPHandler is used by LiteLLM's get_async_httpx_client() which is what
+ GCSBucketBase uses for making API calls.
+
+ This function is idempotent - it only initializes mocks once, even if called multiple times.
+ """
+ global _original_async_handler_get, _original_async_handler_delete, _mocks_initialized
+
+ # Use factory for POST handler
+ _create_mock_gcs_post()
+
+ # If already initialized, skip GET/DELETE patching
+ if _mocks_initialized:
+ return
+
+ verbose_logger.debug("[GCS MOCK] Initializing GCS GET/DELETE handlers...")
+
+ # Patch GET and DELETE handlers (GCS-specific)
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ if _original_async_handler_get is None:
+ _original_async_handler_get = AsyncHTTPHandler.get
+ AsyncHTTPHandler.get = _mock_async_handler_get # type: ignore
+ verbose_logger.debug("[GCS MOCK] Patched AsyncHTTPHandler.get")
+
+ if _original_async_handler_delete is None:
+ _original_async_handler_delete = AsyncHTTPHandler.delete
+ AsyncHTTPHandler.delete = _mock_async_handler_delete # type: ignore
+ verbose_logger.debug("[GCS MOCK] Patched AsyncHTTPHandler.delete")
+
+ verbose_logger.debug(f"[GCS MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms")
+ verbose_logger.debug("[GCS MOCK] GCS mock client initialization complete")
+
+ _mocks_initialized = True
+
+
+def mock_vertex_auth_methods():
+ """
+ Monkey-patch Vertex AI auth methods to return fake tokens.
+ This prevents auth failures when GCS_MOCK is enabled.
+
+ This function is idempotent - it only patches once, even if called multiple times.
+ """
+ from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
+
+ # Store original methods if not already stored
+ if not hasattr(VertexBase, '_original_ensure_access_token_async'):
+ setattr(VertexBase, '_original_ensure_access_token_async', VertexBase._ensure_access_token_async)
+ setattr(VertexBase, '_original_ensure_access_token', VertexBase._ensure_access_token)
+ setattr(VertexBase, '_original_get_token_and_url', VertexBase._get_token_and_url)
+
+ async def _mock_ensure_access_token_async(self, credentials, project_id, custom_llm_provider):
+ """Mock async auth method - returns fake token."""
+ verbose_logger.debug("[GCS MOCK] Vertex AI auth: _ensure_access_token_async called")
+ return ("mock-gcs-token", "mock-project-id")
+
+ def _mock_ensure_access_token(self, credentials, project_id, custom_llm_provider):
+ """Mock sync auth method - returns fake token."""
+ verbose_logger.debug("[GCS MOCK] Vertex AI auth: _ensure_access_token called")
+ return ("mock-gcs-token", "mock-project-id")
+
+ def _mock_get_token_and_url(self, model, auth_header, vertex_credentials, vertex_project,
+ vertex_location, gemini_api_key, stream, custom_llm_provider, api_base):
+ """Mock get_token_and_url - returns fake token."""
+ verbose_logger.debug("[GCS MOCK] Vertex AI auth: _get_token_and_url called")
+ return ("mock-gcs-token", "https://storage.googleapis.com")
+
+ # Patch the methods
+ VertexBase._ensure_access_token_async = _mock_ensure_access_token_async # type: ignore
+ VertexBase._ensure_access_token = _mock_ensure_access_token # type: ignore
+ VertexBase._get_token_and_url = _mock_get_token_and_url # type: ignore
+
+ verbose_logger.debug("[GCS MOCK] Patched Vertex AI auth methods")
+
+
+# should_use_gcs_mock is already created by the factory
diff --git a/litellm/integrations/helicone.py b/litellm/integrations/helicone.py
index 198cbaf4058..b996813b4e7 100644
--- a/litellm/integrations/helicone.py
+++ b/litellm/integrations/helicone.py
@@ -4,6 +4,11 @@ import os
import traceback
import litellm
+from litellm._logging import verbose_logger
+from litellm.integrations.helicone_mock_client import (
+ should_use_helicone_mock,
+ create_mock_helicone_client,
+)
class HeliconeLogger:
@@ -22,6 +27,11 @@ class HeliconeLogger:
def __init__(self):
# Instance variables
+ self.is_mock_mode = should_use_helicone_mock()
+ if self.is_mock_mode:
+ create_mock_helicone_client()
+ verbose_logger.info("[HELICONE MOCK] Helicone logger initialized in mock mode")
+
self.provider_url = "https://api.openai.com/v1"
self.key = os.getenv("HELICONE_API_KEY")
self.api_base = os.getenv("HELICONE_API_BASE") or "https://api.hconeai.com"
@@ -185,7 +195,10 @@ class HeliconeLogger:
}
response = litellm.module_level_client.post(url, headers=headers, json=data)
if response.status_code == 200:
- print_verbose("Helicone Logging - Success!")
+ if self.is_mock_mode:
+ print_verbose("[HELICONE MOCK] Helicone Logging - Successfully mocked!")
+ else:
+ print_verbose("Helicone Logging - Success!")
else:
print_verbose(
f"Helicone Logging - Error Request was not successful. Status Code: {response.status_code}"
diff --git a/litellm/integrations/helicone_mock_client.py b/litellm/integrations/helicone_mock_client.py
new file mode 100644
index 00000000000..0f4670a1d2c
--- /dev/null
+++ b/litellm/integrations/helicone_mock_client.py
@@ -0,0 +1,32 @@
+"""
+Mock HTTP client for Helicone integration testing.
+
+This module intercepts Helicone API calls and returns successful mock responses,
+allowing full code execution without making actual network calls.
+
+Usage:
+ Set HELICONE_MOCK=true in environment variables or config to enable mock mode.
+"""
+
+from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory
+
+# Create mock client using factory
+# Helicone uses HTTPHandler which internally uses httpx.Client.send(), not httpx.Client.post()
+_config = MockClientConfig(
+ name="HELICONE",
+ env_var="HELICONE_MOCK",
+ default_latency_ms=100,
+ default_status_code=200,
+ default_json_data={"status": "success"},
+ url_matchers=[
+ ".hconeai.com",
+ "hconeai.com",
+ ".helicone.ai",
+ "helicone.ai",
+ ],
+ patch_async_handler=False,
+ patch_sync_client=False, # HTTPHandler uses self.client.send(), not self.client.post()
+ patch_http_handler=True, # Patch HTTPHandler.post directly
+)
+
+create_mock_helicone_client, should_use_helicone_mock = create_mock_client_factory(_config)
diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.py
index b64af66ce9b..7bf97665fd2 100644
--- a/litellm/integrations/langfuse/langfuse.py
+++ b/litellm/integrations/langfuse/langfuse.py
@@ -26,6 +26,10 @@ from litellm.litellm_core_utils.core_helpers import (
filter_exceptions_from_params,
)
from litellm.litellm_core_utils.redact_messages import redact_user_api_key_info
+from litellm.integrations.langfuse.langfuse_mock_client import (
+ create_mock_langfuse_client,
+ should_use_langfuse_mock,
+)
from litellm.llms.custom_httpx.http_handler import _get_httpx_client
from litellm.secret_managers.main import str_to_bool
from litellm.types.integrations.langfuse import *
@@ -119,8 +123,14 @@ class LangFuseLogger:
self.langfuse_flush_interval = LangFuseLogger._get_langfuse_flush_interval(
flush_interval
)
- http_client = _get_httpx_client()
- self.langfuse_client = http_client.client
+
+ if should_use_langfuse_mock():
+ self.langfuse_client = create_mock_langfuse_client()
+ self.is_mock_mode = True
+ else:
+ http_client = _get_httpx_client()
+ self.langfuse_client = http_client.client
+ self.is_mock_mode = False
parameters = {
"public_key": self.public_key,
@@ -139,11 +149,15 @@ class LangFuseLogger:
# set the current langfuse project id in the environ
# this is used by Alerting to link to the correct project
- try:
- project_id = self.Langfuse.client.projects.get().data[0].id
- os.environ["LANGFUSE_PROJECT_ID"] = project_id
- except Exception:
- project_id = None
+ if self.is_mock_mode:
+ os.environ["LANGFUSE_PROJECT_ID"] = "mock-project-id"
+ verbose_logger.debug("Langfuse Mock: Using mock project ID")
+ else:
+ try:
+ project_id = self.Langfuse.client.projects.get().data[0].id
+ os.environ["LANGFUSE_PROJECT_ID"] = project_id
+ except Exception:
+ project_id = None
if os.getenv("UPSTREAM_LANGFUSE_SECRET_KEY") is not None:
upstream_langfuse_debug = (
diff --git a/litellm/integrations/langfuse/langfuse_mock_client.py b/litellm/integrations/langfuse/langfuse_mock_client.py
new file mode 100644
index 00000000000..8ed6cff8d47
--- /dev/null
+++ b/litellm/integrations/langfuse/langfuse_mock_client.py
@@ -0,0 +1,35 @@
+"""
+Mock httpx client for Langfuse integration testing.
+
+This module intercepts Langfuse API calls and returns successful mock responses,
+allowing full code execution without making actual network calls.
+
+Usage:
+ Set LANGFUSE_MOCK=true in environment variables or config to enable mock mode.
+"""
+
+import httpx
+from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory
+
+# Create mock client using factory
+_config = MockClientConfig(
+ name="LANGFUSE",
+ env_var="LANGFUSE_MOCK",
+ default_latency_ms=100,
+ default_status_code=200,
+ default_json_data={"status": "success"},
+ url_matchers=[
+ ".langfuse.com",
+ "langfuse.com",
+ ],
+ patch_async_handler=False,
+ patch_sync_client=True,
+)
+
+_create_mock_langfuse_client_internal, should_use_langfuse_mock = create_mock_client_factory(_config)
+
+# Langfuse needs to return an httpx.Client instance
+def create_mock_langfuse_client():
+ """Create and return an httpx.Client instance - the monkey-patch intercepts all calls."""
+ _create_mock_langfuse_client_internal()
+ return httpx.Client()
diff --git a/litellm/integrations/langfuse/langfuse_otel.py b/litellm/integrations/langfuse/langfuse_otel.py
index 08493a0e8ec..b96ec72b04e 100644
--- a/litellm/integrations/langfuse/langfuse_otel.py
+++ b/litellm/integrations/langfuse/langfuse_otel.py
@@ -1,6 +1,7 @@
import base64
import json # <--- NEW
import os
+from datetime import datetime
from typing import TYPE_CHECKING, Any, Optional, Union
from litellm._logging import verbose_logger
@@ -8,9 +9,8 @@ from litellm.integrations.arize import _utils
from litellm.integrations.langfuse.langfuse_otel_attributes import (
LangfuseLLMObsOTELAttributes,
)
-from litellm.integrations.opentelemetry import OpenTelemetry
+from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig
from litellm.types.integrations.langfuse_otel import (
- LangfuseOtelConfig,
LangfuseSpanAttributes,
)
from litellm.types.utils import StandardCallbackDynamicParams
@@ -18,17 +18,8 @@ from litellm.types.utils import StandardCallbackDynamicParams
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- from litellm.integrations.opentelemetry import (
- OpenTelemetryConfig as _OpenTelemetryConfig,
- )
- from litellm.types.integrations.arize import Protocol as _Protocol
-
- Protocol = _Protocol
- OpenTelemetryConfig = _OpenTelemetryConfig
Span = Union[_Span, Any]
else:
- Protocol = Any
- OpenTelemetryConfig = Any
Span = Any
@@ -37,8 +28,12 @@ LANGFUSE_CLOUD_US_ENDPOINT = "https://us.cloud.langfuse.com/api/public/otel"
class LangfuseOtelLogger(OpenTelemetry):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
+ def __init__(self, config=None, *args, **kwargs):
+ # Prevent LangfuseOtelLogger from modifying global environment variables by constructing config manually
+ # and passing it to the parent OpenTelemetry class
+ if config is None:
+ config = self._create_open_telemetry_config_from_langfuse_env()
+ super().__init__(config=config, *args, **kwargs)
@staticmethod
def set_langfuse_otel_attributes(span: Span, kwargs, response_obj):
@@ -114,6 +109,10 @@ class LangfuseOtelLogger(OpenTelemetry):
for key, enum_attr in mapping.items():
if key in metadata and metadata[key] is not None:
value = metadata[key]
+ if key == "trace_id" and isinstance(value, str):
+ # trace_id must be 32 hex char no dashes for langfuse : Litellm sends uuid with dashes (might be breaking at some point)
+ value = value.replace("-", "")
+
if isinstance(value, (list, dict)):
try:
value = json.dumps(value)
@@ -265,8 +264,47 @@ class LangfuseOtelLogger(OpenTelemetry):
"""
return os.environ.get("LANGFUSE_OTEL_HOST") or os.environ.get("LANGFUSE_HOST")
+ def _create_open_telemetry_config_from_langfuse_env(self) -> OpenTelemetryConfig:
+ """
+ Creates OpenTelemetryConfig from Langfuse environment variables.
+ Does NOT modify global environment variables.
+ """
+ from litellm.integrations.opentelemetry import OpenTelemetryConfig
+
+ public_key = os.environ.get("LANGFUSE_PUBLIC_KEY", None)
+ secret_key = os.environ.get("LANGFUSE_SECRET_KEY", None)
+
+ if not public_key or not secret_key:
+ # If no keys, return default from env (likely logging to console or something else)
+ return OpenTelemetryConfig.from_env()
+
+ # Determine endpoint - default to US cloud
+ langfuse_host = LangfuseOtelLogger._get_langfuse_otel_host()
+
+ if langfuse_host:
+ # If LANGFUSE_HOST is provided, construct OTEL endpoint from it
+ if not langfuse_host.startswith("http"):
+ langfuse_host = "https://" + langfuse_host
+ endpoint = f"{langfuse_host.rstrip('/')}/api/public/otel"
+ verbose_logger.debug(f"Using Langfuse OTEL endpoint from host: {endpoint}")
+ else:
+ # Default to US cloud endpoint
+ endpoint = LANGFUSE_CLOUD_US_ENDPOINT
+ verbose_logger.debug(f"Using Langfuse US cloud endpoint: {endpoint}")
+
+ auth_header = LangfuseOtelLogger._get_langfuse_authorization_header(
+ public_key=public_key, secret_key=secret_key
+ )
+ otlp_auth_headers = f"Authorization={auth_header}"
+
+ return OpenTelemetryConfig(
+ exporter="otlp_http",
+ endpoint=endpoint,
+ headers=otlp_auth_headers,
+ )
+
@staticmethod
- def get_langfuse_otel_config() -> LangfuseOtelConfig:
+ def get_langfuse_otel_config() -> "OpenTelemetryConfig":
"""
Retrieves the Langfuse OpenTelemetry configuration based on environment variables.
@@ -276,7 +314,7 @@ class LangfuseOtelLogger(OpenTelemetry):
LANGFUSE_HOST: Optional. Custom Langfuse host URL. Defaults to US cloud.
Returns:
- LangfuseOtelConfig: A Pydantic model containing Langfuse OTEL configuration.
+ OpenTelemetryConfig: A Pydantic model containing Langfuse OTEL configuration.
Raises:
ValueError: If required keys are missing.
@@ -308,12 +346,14 @@ class LangfuseOtelLogger(OpenTelemetry):
)
otlp_auth_headers = f"Authorization={auth_header}"
- # Set standard OTEL environment variables
- os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = endpoint
- os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = otlp_auth_headers
+ # Prevent modification of global env vars which causes leakage
+ # os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = endpoint
+ # os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = otlp_auth_headers
- return LangfuseOtelConfig(
- otlp_auth_headers=otlp_auth_headers, protocol="otlp_http"
+ return OpenTelemetryConfig(
+ exporter="otlp_http",
+ endpoint=endpoint,
+ headers=otlp_auth_headers,
)
@staticmethod
@@ -353,6 +393,22 @@ class LangfuseOtelLogger(OpenTelemetry):
return dynamic_headers
+ def create_litellm_proxy_request_started_span(
+ self,
+ start_time: datetime,
+ headers: dict,
+ ) -> Optional[Span]:
+ """
+ Override to prevent creating empty proxy request spans.
+
+ Langfuse should only receive spans for actual LLM calls, not for
+ internal proxy operations (auth, postgres, proxy_pre_call, etc.).
+
+ By returning None, we prevent the parent span from being created,
+ which in turn prevents empty traces from being sent to Langfuse.
+ """
+ return None
+
async def async_service_success_hook(self, *args, **kwargs):
"""
Langfuse should not receive service success logs.
diff --git a/litellm/integrations/langfuse/langfuse_prompt_management.py b/litellm/integrations/langfuse/langfuse_prompt_management.py
index 8f73eabad44..3986fc6a6ef 100644
--- a/litellm/integrations/langfuse/langfuse_prompt_management.py
+++ b/litellm/integrations/langfuse/langfuse_prompt_management.py
@@ -300,43 +300,59 @@ class LangfusePromptManagement(LangFuseLogger, PromptManagementBase, CustomLogge
)
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
- standard_callback_dynamic_params = kwargs.get(
- "standard_callback_dynamic_params"
- )
- langfuse_logger_to_use = LangFuseHandler.get_langfuse_logger_for_request(
- globalLangfuseLogger=self,
- standard_callback_dynamic_params=standard_callback_dynamic_params,
- in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,
- )
- langfuse_logger_to_use.log_event_on_langfuse(
- kwargs=kwargs,
- response_obj=response_obj,
- start_time=start_time,
- end_time=end_time,
- user_id=kwargs.get("user", None),
- )
+ try:
+ standard_callback_dynamic_params = kwargs.get(
+ "standard_callback_dynamic_params"
+ )
+ langfuse_logger_to_use = LangFuseHandler.get_langfuse_logger_for_request(
+ globalLangfuseLogger=self,
+ standard_callback_dynamic_params=standard_callback_dynamic_params,
+ in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,
+ )
+ langfuse_logger_to_use.log_event_on_langfuse(
+ kwargs=kwargs,
+ response_obj=response_obj,
+ start_time=start_time,
+ end_time=end_time,
+ user_id=kwargs.get("user", None),
+ )
+ except Exception as e:
+ from litellm._logging import verbose_logger
+
+ verbose_logger.exception(
+ f"Langfuse Layer Error - Exception occurred while logging success event: {str(e)}"
+ )
+ self.handle_callback_failure(callback_name="langfuse")
async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
- standard_callback_dynamic_params = kwargs.get(
- "standard_callback_dynamic_params"
- )
- langfuse_logger_to_use = LangFuseHandler.get_langfuse_logger_for_request(
- globalLangfuseLogger=self,
- standard_callback_dynamic_params=standard_callback_dynamic_params,
- in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,
- )
- standard_logging_object = cast(
- Optional[StandardLoggingPayload],
- kwargs.get("standard_logging_object", None),
- )
- if standard_logging_object is None:
- return
- langfuse_logger_to_use.log_event_on_langfuse(
- start_time=start_time,
- end_time=end_time,
- response_obj=None,
- user_id=kwargs.get("user", None),
- status_message=standard_logging_object["error_str"],
- level="ERROR",
- kwargs=kwargs,
- )
+ try:
+ standard_callback_dynamic_params = kwargs.get(
+ "standard_callback_dynamic_params"
+ )
+ langfuse_logger_to_use = LangFuseHandler.get_langfuse_logger_for_request(
+ globalLangfuseLogger=self,
+ standard_callback_dynamic_params=standard_callback_dynamic_params,
+ in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,
+ )
+ standard_logging_object = cast(
+ Optional[StandardLoggingPayload],
+ kwargs.get("standard_logging_object", None),
+ )
+ if standard_logging_object is None:
+ return
+ langfuse_logger_to_use.log_event_on_langfuse(
+ start_time=start_time,
+ end_time=end_time,
+ response_obj=None,
+ user_id=kwargs.get("user", None),
+ status_message=standard_logging_object["error_str"],
+ level="ERROR",
+ kwargs=kwargs,
+ )
+ except Exception as e:
+ from litellm._logging import verbose_logger
+
+ verbose_logger.exception(
+ f"Langfuse Layer Error - Exception occurred while logging failure event: {str(e)}"
+ )
+ self.handle_callback_failure(callback_name="langfuse")
diff --git a/litellm/integrations/langsmith.py b/litellm/integrations/langsmith.py
index 5893f14105d..ebd005f8804 100644
--- a/litellm/integrations/langsmith.py
+++ b/litellm/integrations/langsmith.py
@@ -15,6 +15,10 @@ from pydantic import BaseModel # type: ignore
import litellm
from litellm._logging import verbose_logger
from litellm.integrations.custom_batch_logger import CustomBatchLogger
+from litellm.integrations.langsmith_mock_client import (
+ should_use_langsmith_mock,
+ create_mock_langsmith_client,
+)
from litellm.llms.custom_httpx.http_handler import (
get_async_httpx_client,
httpxSpecialProvider,
@@ -45,6 +49,12 @@ class LangsmithLogger(CustomBatchLogger):
):
self.flush_lock = asyncio.Lock()
super().__init__(**kwargs, flush_lock=self.flush_lock)
+ self.is_mock_mode = should_use_langsmith_mock()
+
+ if self.is_mock_mode:
+ create_mock_langsmith_client()
+ verbose_logger.debug("[LANGSMITH MOCK] LangSmith logger initialized in mock mode")
+
self.default_credentials = self.get_credentials_from_env(
langsmith_api_key=langsmith_api_key,
langsmith_project=langsmith_project,
@@ -388,6 +398,8 @@ class LangsmithLogger(CustomBatchLogger):
verbose_logger.debug(
"Sending batch of %s runs to Langsmith", len(elements_to_log)
)
+ if self.is_mock_mode:
+ verbose_logger.debug("[LANGSMITH MOCK] Mock mode enabled - API calls will be intercepted")
response = await self.async_httpx_client.post(
url=url,
json={"post": elements_to_log},
@@ -400,9 +412,14 @@ class LangsmithLogger(CustomBatchLogger):
f"Langsmith Error: {response.status_code} - {response.text}"
)
else:
- verbose_logger.debug(
- f"Batch of {len(self.log_queue)} runs successfully created"
- )
+ if self.is_mock_mode:
+ verbose_logger.debug(
+ f"[LANGSMITH MOCK] Batch of {len(elements_to_log)} runs successfully mocked"
+ )
+ else:
+ verbose_logger.debug(
+ f"Batch of {len(self.log_queue)} runs successfully created"
+ )
except httpx.HTTPStatusError as e:
verbose_logger.exception(
f"Langsmith HTTP Error: {e.response.status_code} - {e.response.text}"
diff --git a/litellm/integrations/langsmith_mock_client.py b/litellm/integrations/langsmith_mock_client.py
new file mode 100644
index 00000000000..ef602908231
--- /dev/null
+++ b/litellm/integrations/langsmith_mock_client.py
@@ -0,0 +1,29 @@
+"""
+Mock client for LangSmith integration testing.
+
+This module intercepts LangSmith API calls and returns successful mock responses,
+allowing full code execution without making actual network calls.
+
+Usage:
+ Set LANGSMITH_MOCK=true in environment variables or config to enable mock mode.
+"""
+
+from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory
+
+# Create mock client using factory
+_config = MockClientConfig(
+ name="LANGSMITH",
+ env_var="LANGSMITH_MOCK",
+ default_latency_ms=100,
+ default_status_code=200,
+ default_json_data={"status": "success", "ids": ["mock-run-id"]},
+ url_matchers=[
+ ".smith.langchain.com",
+ "api.smith.langchain.com",
+ "smith.langchain.com",
+ ],
+ patch_async_handler=True,
+ patch_sync_client=False,
+)
+
+create_mock_langsmith_client, should_use_langsmith_mock = create_mock_client_factory(_config)
diff --git a/litellm/integrations/mock_client_factory.py b/litellm/integrations/mock_client_factory.py
new file mode 100644
index 00000000000..2f04fae9f76
--- /dev/null
+++ b/litellm/integrations/mock_client_factory.py
@@ -0,0 +1,216 @@
+"""
+Factory for creating mock HTTP clients for integration testing.
+
+This module provides a simple factory pattern to create mock clients that intercept
+API calls and return successful mock responses, allowing full code execution without
+making actual network calls.
+"""
+
+import httpx
+import json
+import asyncio
+from datetime import timedelta
+from typing import Dict, Optional, List, cast
+from dataclasses import dataclass
+
+from litellm._logging import verbose_logger
+
+
+@dataclass
+class MockClientConfig:
+ """Configuration for creating a mock client."""
+ name: str # e.g., "GCS", "LANGFUSE", "LANGSMITH", "DATADOG"
+ env_var: str # e.g., "GCS_MOCK", "LANGFUSE_MOCK"
+ default_latency_ms: int = 100 # Default mock latency in milliseconds
+ default_status_code: int = 200 # Default HTTP status code
+ default_json_data: Optional[Dict] = None # Default JSON response data
+ url_matchers: Optional[List[str]] = None # List of strings to match in URLs (e.g., ["storage.googleapis.com"])
+ patch_async_handler: bool = True # Whether to patch AsyncHTTPHandler.post
+ patch_sync_client: bool = False # Whether to patch httpx.Client.post
+ patch_http_handler: bool = False # Whether to patch HTTPHandler.post (for sync calls that use HTTPHandler)
+
+ def __post_init__(self):
+ """Ensure url_matchers is a list."""
+ if self.url_matchers is None:
+ self.url_matchers = []
+
+
+class MockResponse:
+ """Generic mock httpx.Response that satisfies API requirements."""
+
+ def __init__(self, status_code: int = 200, json_data: Optional[Dict] = None, url: Optional[str] = None, elapsed_seconds: float = 0.0):
+ self.status_code = status_code
+ self._json_data = json_data or {"status": "success"}
+ self.headers = httpx.Headers({})
+ self.is_success = status_code < 400
+ self.is_error = status_code >= 400
+ self.is_redirect = 300 <= status_code < 400
+ self.url = httpx.URL(url) if url else httpx.URL("")
+ self.elapsed = timedelta(seconds=elapsed_seconds)
+ self._text = json.dumps(self._json_data) if json_data else ""
+ self._content = self._text.encode("utf-8")
+
+ @property
+ def text(self) -> str:
+ """Return response text."""
+ return self._text
+
+ @property
+ def content(self) -> bytes:
+ """Return response content."""
+ return self._content
+
+ def json(self) -> Dict:
+ """Return JSON response data."""
+ return self._json_data
+
+ def read(self) -> bytes:
+ """Read response content."""
+ return self._content
+
+ def raise_for_status(self):
+ """Raise exception for error status codes."""
+ if self.status_code >= 400:
+ raise Exception(f"HTTP {self.status_code}")
+
+
+def _is_url_match(url, matchers: List[str]) -> bool:
+ """Check if URL matches any of the provided matchers."""
+ try:
+ parsed_url = httpx.URL(url) if isinstance(url, str) else url
+ url_str = str(parsed_url).lower()
+ hostname = parsed_url.host or ""
+
+ for matcher in matchers:
+ if matcher.lower() in url_str or matcher.lower() in hostname.lower():
+ return True
+
+ # Also check for localhost with matcher in path
+ if hostname in ("localhost", "127.0.0.1"):
+ for matcher in matchers:
+ if matcher.lower() in url_str:
+ return True
+
+ return False
+ except Exception:
+ return False
+
+
+def create_mock_client_factory(config: MockClientConfig): # noqa: PLR0915
+ """
+ Factory function that creates mock client functions based on configuration.
+
+ Returns:
+ tuple: (create_mock_client_func, should_use_mock_func)
+ """
+ # Store original methods for restoration
+ _original_async_handler_post = None
+ _original_sync_client_post = None
+ _original_http_handler_post = None
+ _mocks_initialized = False
+
+ # Calculate mock latency
+ import os
+ latency_env = f"{config.name.upper()}_MOCK_LATENCY_MS"
+ _MOCK_LATENCY_SECONDS = float(os.getenv(latency_env, str(config.default_latency_ms))) / 1000.0
+
+ # Create URL matcher function
+ def _is_mock_url(url) -> bool:
+ # url_matchers is guaranteed to be a list after __post_init__
+ return _is_url_match(url, cast(List[str], config.url_matchers))
+
+ # Create async handler mock
+ async def _mock_async_handler_post(self, url, data=None, json=None, params=None, headers=None, timeout=None, stream=False, logging_obj=None, files=None, content=None):
+ """Monkey-patched AsyncHTTPHandler.post that intercepts API calls."""
+ if isinstance(url, str) and _is_mock_url(url):
+ verbose_logger.info(f"[{config.name} MOCK] POST to {url}")
+ await asyncio.sleep(_MOCK_LATENCY_SECONDS)
+ return MockResponse(
+ status_code=config.default_status_code,
+ json_data=config.default_json_data,
+ url=url,
+ elapsed_seconds=_MOCK_LATENCY_SECONDS
+ )
+ if _original_async_handler_post is not None:
+ return await _original_async_handler_post(self, url=url, data=data, json=json, params=params, headers=headers, timeout=timeout, stream=stream, logging_obj=logging_obj, files=files, content=content)
+ raise RuntimeError("Original AsyncHTTPHandler.post not available")
+
+ # Create sync client mock
+ def _mock_sync_client_post(self, url, **kwargs):
+ """Monkey-patched httpx.Client.post that intercepts API calls."""
+ if _is_mock_url(url):
+ verbose_logger.info(f"[{config.name} MOCK] POST to {url} (sync)")
+ return MockResponse(
+ status_code=config.default_status_code,
+ json_data=config.default_json_data,
+ url=url,
+ elapsed_seconds=_MOCK_LATENCY_SECONDS
+ )
+ if _original_sync_client_post is not None:
+ return _original_sync_client_post(self, url, **kwargs)
+
+ # Create HTTPHandler mock (for sync calls that use HTTPHandler.post)
+ def _mock_http_handler_post(self, url, data=None, json=None, params=None, headers=None, timeout=None, stream=False, files=None, content=None, logging_obj=None):
+ """Monkey-patched HTTPHandler.post that intercepts API calls."""
+ if isinstance(url, str) and _is_mock_url(url):
+ verbose_logger.info(f"[{config.name} MOCK] POST to {url}")
+ import time
+ time.sleep(_MOCK_LATENCY_SECONDS)
+ return MockResponse(
+ status_code=config.default_status_code,
+ json_data=config.default_json_data,
+ url=url,
+ elapsed_seconds=_MOCK_LATENCY_SECONDS
+ )
+ if _original_http_handler_post is not None:
+ return _original_http_handler_post(self, url=url, data=data, json=json, params=params, headers=headers, timeout=timeout, stream=stream, files=files, content=content, logging_obj=logging_obj)
+ raise RuntimeError("Original HTTPHandler.post not available")
+
+ # Create mock client initialization function
+ def create_mock_client():
+ """Initialize the mock client by patching HTTP handlers."""
+ nonlocal _original_async_handler_post, _original_sync_client_post, _original_http_handler_post, _mocks_initialized
+
+ if _mocks_initialized:
+ return
+
+ verbose_logger.debug(f"[{config.name} MOCK] Initializing {config.name} mock client...")
+
+ if config.patch_async_handler and _original_async_handler_post is None:
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+ _original_async_handler_post = AsyncHTTPHandler.post
+ AsyncHTTPHandler.post = _mock_async_handler_post # type: ignore
+ verbose_logger.debug(f"[{config.name} MOCK] Patched AsyncHTTPHandler.post")
+
+ if config.patch_sync_client and _original_sync_client_post is None:
+ _original_sync_client_post = httpx.Client.post
+ httpx.Client.post = _mock_sync_client_post # type: ignore
+ verbose_logger.debug(f"[{config.name} MOCK] Patched httpx.Client.post")
+
+ if config.patch_http_handler and _original_http_handler_post is None:
+ from litellm.llms.custom_httpx.http_handler import HTTPHandler
+ _original_http_handler_post = HTTPHandler.post
+ HTTPHandler.post = _mock_http_handler_post # type: ignore
+ verbose_logger.debug(f"[{config.name} MOCK] Patched HTTPHandler.post")
+
+ verbose_logger.debug(f"[{config.name} MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms")
+ verbose_logger.debug(f"[{config.name} MOCK] {config.name} mock client initialization complete")
+
+ _mocks_initialized = True
+
+ # Create should_use_mock function
+ def should_use_mock() -> bool:
+ """Determine if mock mode should be enabled."""
+ import os
+ from litellm.secret_managers.main import str_to_bool
+
+ mock_mode = os.getenv(config.env_var, "false")
+ result = str_to_bool(mock_mode)
+ result = bool(result) if result is not None else False
+
+ if result:
+ verbose_logger.info(f"{config.name} Mock Mode: ENABLED - API calls will be mocked")
+
+ return result
+
+ return create_mock_client, should_use_mock
diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.py
index 93d631eb0f2..35362a71ccd 100644
--- a/litellm/integrations/opentelemetry.py
+++ b/litellm/integrations/opentelemetry.py
@@ -5,6 +5,10 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast
import litellm
from litellm._logging import verbose_logger
+from litellm.integrations._types.open_inference import (
+ OpenInferenceSpanKindValues,
+ SpanAttributes,
+)
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.secret_managers.main import get_secret_bool
@@ -36,7 +40,9 @@ if TYPE_CHECKING:
Context = Union[_Context, Any]
SpanExporter = Union[_SpanExporter, Any]
UserAPIKeyAuth = Union[_UserAPIKeyAuth, Any]
- ManagementEndpointLoggingPayload = Union[_ManagementEndpointLoggingPayload, Any]
+ ManagementEndpointLoggingPayload = Union[
+ _ManagementEndpointLoggingPayload, Any
+ ]
else:
Span = Any
Tracer = Any
@@ -66,6 +72,13 @@ class OpenTelemetryConfig:
model_id: Optional[str] = None
def __post_init__(self) -> None:
+ # If endpoint is specified but exporter is still the default "console",
+ # automatically infer "otlp_http" to send traces to the endpoint.
+ # This fixes an issue where UI-configured OTEL settings would default
+ # to console output instead of sending traces to the configured endpoint.
+ if self.endpoint and isinstance(self.exporter, str) and self.exporter == "console":
+ self.exporter = "otlp_http"
+
if not self.service_name:
self.service_name = os.getenv("OTEL_SERVICE_NAME", "litellm")
if not self.deployment_environment:
@@ -91,12 +104,16 @@ class OpenTelemetryConfig:
exporter = os.getenv(
"OTEL_EXPORTER_OTLP_PROTOCOL", os.getenv("OTEL_EXPORTER", "console")
)
- endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", os.getenv("OTEL_ENDPOINT"))
+ endpoint = os.getenv(
+ "OTEL_EXPORTER_OTLP_ENDPOINT", os.getenv("OTEL_ENDPOINT")
+ )
headers = os.getenv(
"OTEL_EXPORTER_OTLP_HEADERS", os.getenv("OTEL_HEADERS")
) # example: OTEL_HEADERS=x-honeycomb-team=B85YgLm96***"
enable_metrics: bool = (
- os.getenv("LITELLM_OTEL_INTEGRATION_ENABLE_METRICS", "false").lower()
+ os.getenv(
+ "LITELLM_OTEL_INTEGRATION_ENABLE_METRICS", "false"
+ ).lower()
== "true"
)
enable_events: bool = (
@@ -104,7 +121,9 @@ class OpenTelemetryConfig:
== "true"
)
service_name = os.getenv("OTEL_SERVICE_NAME", "litellm")
- deployment_environment = os.getenv("OTEL_ENVIRONMENT_NAME", "production")
+ deployment_environment = os.getenv(
+ "OTEL_ENVIRONMENT_NAME", "production"
+ )
model_id = os.getenv("OTEL_MODEL_ID", service_name)
if exporter == "in_memory":
@@ -140,6 +159,7 @@ class OpenTelemetry(CustomLogger):
self.OTEL_EXPORTER = self.config.exporter
self.OTEL_ENDPOINT = self.config.endpoint
self.OTEL_HEADERS = self.config.headers
+ self._tracer_provider_cache: Dict[str, Any] = {}
self._init_tracing(tracer_provider)
_debug_otel = str(os.getenv("DEBUG_OTEL", "False")).lower()
@@ -152,7 +172,9 @@ class OpenTelemetry(CustomLogger):
logging.getLogger(__name__)
# Enable OpenTelemetry logging
- otel_exporter_logger = logging.getLogger("opentelemetry.sdk.trace.export")
+ otel_exporter_logger = logging.getLogger(
+ "opentelemetry.sdk.trace.export"
+ )
otel_exporter_logger.setLevel(logging.DEBUG)
# init CustomLogger params
@@ -248,7 +270,9 @@ class OpenTelemetry(CustomLogger):
# Don't call set_provider to preserve existing context
else:
# Default proxy provider or unknown type, create our own
- verbose_logger.debug("OpenTelemetry: Creating new %s", provider_name)
+ verbose_logger.debug(
+ "OpenTelemetry: Creating new %s", provider_name
+ )
provider = create_new_provider_fn()
set_provider_fn(provider)
except Exception as e:
@@ -269,7 +293,9 @@ class OpenTelemetry(CustomLogger):
from opentelemetry.trace import SpanKind
def create_tracer_provider():
- provider = TracerProvider(resource=self._get_litellm_resource(self.config))
+ provider = TracerProvider(
+ resource=self._get_litellm_resource(self.config)
+ )
provider.add_span_processor(self._get_span_processor())
return provider
@@ -383,10 +409,14 @@ class OpenTelemetry(CustomLogger):
def log_failure_event(self, kwargs, response_obj, start_time, end_time):
self._handle_failure(kwargs, response_obj, start_time, end_time)
- async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ async def async_log_success_event(
+ self, kwargs, response_obj, start_time, end_time
+ ):
self._handle_success(kwargs, response_obj, start_time, end_time)
- async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
+ async def async_log_failure_event(
+ self, kwargs, response_obj, start_time, end_time
+ ):
self._handle_failure(kwargs, response_obj, start_time, end_time)
async def async_service_success_hook(
@@ -583,7 +613,9 @@ class OpenTelemetry(CustomLogger):
if dynamic_headers is not None:
# Create spans using a temporary tracer with dynamic headers
- tracer_to_use = self._get_tracer_with_dynamic_headers(dynamic_headers)
+ tracer_to_use = self._get_tracer_with_dynamic_headers(
+ dynamic_headers
+ )
verbose_logger.debug(
"Using dynamic headers for this request: %s", dynamic_headers
)
@@ -594,9 +626,9 @@ class OpenTelemetry(CustomLogger):
def _get_dynamic_otel_headers_from_kwargs(self, kwargs) -> Optional[dict]:
"""Extract dynamic headers from kwargs if available."""
- standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = (
- kwargs.get("standard_callback_dynamic_params")
- )
+ standard_callback_dynamic_params: Optional[
+ StandardCallbackDynamicParams
+ ] = kwargs.get("standard_callback_dynamic_params")
if not standard_callback_dynamic_params:
return None
@@ -611,12 +643,24 @@ class OpenTelemetry(CustomLogger):
"""Create a temporary tracer with dynamic headers for this request only."""
from opentelemetry.sdk.trace import TracerProvider
+ # Prevents thread exhaustion by reusing providers for the same credential sets (e.g. per-team keys)
+ cache_key = str(sorted(dynamic_headers.items()))
+ if cache_key in self._tracer_provider_cache:
+ return self._tracer_provider_cache[cache_key].get_tracer(
+ LITELLM_TRACER_NAME
+ )
+
# Create a temporary tracer provider with dynamic headers
- temp_provider = TracerProvider(resource=self._get_litellm_resource(self.config))
+ temp_provider = TracerProvider(
+ resource=self._get_litellm_resource(self.config)
+ )
temp_provider.add_span_processor(
self._get_span_processor(dynamic_headers=dynamic_headers)
)
+ # Store in cache for reuse
+ self._tracer_provider_cache[cache_key] = temp_provider
+
return temp_provider.get_tracer(LITELLM_TRACER_NAME)
def construct_dynamic_otel_headers(
@@ -660,6 +704,12 @@ class OpenTelemetry(CustomLogger):
self._maybe_log_raw_request(
kwargs, response_obj, start_time, end_time, span
)
+ # Ensure proxy-request parent span is annotated with the actual operation kind
+ if (
+ parent_span is not None
+ and parent_span.name == LITELLM_PROXY_REQUEST_SPAN_NAME
+ ):
+ self.set_attributes(parent_span, kwargs, response_obj)
else:
# Do not create primary span (keep hierarchy shallow when parent exists)
from opentelemetry.trace import Status, StatusCode
@@ -734,7 +784,9 @@ class OpenTelemetry(CustomLogger):
metadata = litellm_params.get("metadata") or {}
generation_name = metadata.get("generation_name")
- raw_span_name = generation_name if generation_name else RAW_REQUEST_SPAN_NAME
+ raw_span_name = (
+ generation_name if generation_name else RAW_REQUEST_SPAN_NAME
+ )
otel_tracer: Tracer = self.get_tracer_to_use_for_request(kwargs)
raw_span = otel_tracer.start_span(
@@ -759,7 +811,9 @@ class OpenTelemetry(CustomLogger):
}
std_log = kwargs.get("standard_logging_object")
- md = getattr(std_log, "metadata", None) or (std_log or {}).get("metadata", {})
+ md = getattr(std_log, "metadata", None) or (std_log or {}).get(
+ "metadata", {}
+ )
for key in [
"user_api_key_hash",
"user_api_key_alias",
@@ -781,9 +835,9 @@ class OpenTelemetry(CustomLogger):
common_attrs[f"metadata.{key}"] = str(md[key])
# get hidden params
- hidden_params = getattr(std_log, "hidden_params", None) or (std_log or {}).get(
- "hidden_params", {}
- )
+ hidden_params = getattr(std_log, "hidden_params", None) or (
+ std_log or {}
+ ).get("hidden_params", {})
if hidden_params:
common_attrs["hidden_params"] = safe_dumps(hidden_params)
@@ -817,7 +871,9 @@ class OpenTelemetry(CustomLogger):
self._record_response_duration_metric(kwargs, end_time, common_attrs)
@staticmethod
- def _to_timestamp(val: Optional[Union[datetime, float, str]]) -> Optional[float]:
+ def _to_timestamp(
+ val: Optional[Union[datetime, float, str]],
+ ) -> Optional[float]:
"""Convert datetime/float/string to timestamp."""
if val is None:
return None
@@ -834,7 +890,9 @@ class OpenTelemetry(CustomLogger):
except ValueError:
return None
- def _record_time_to_first_token_metric(self, kwargs: dict, common_attrs: dict):
+ def _record_time_to_first_token_metric(
+ self, kwargs: dict, common_attrs: dict
+ ):
"""Record Time to First Token (TTFT) metric for streaming requests."""
optional_params = kwargs.get("optional_params", {})
is_streaming = optional_params.get("stream", False)
@@ -847,7 +905,10 @@ class OpenTelemetry(CustomLogger):
api_call_start_time = kwargs.get("api_call_start_time", None)
completion_start_time = kwargs.get("completion_start_time", None)
- if api_call_start_time is not None and completion_start_time is not None:
+ if (
+ api_call_start_time is not None
+ and completion_start_time is not None
+ ):
# Convert to timestamps if needed (handles datetime, float, and string)
api_call_start_ts = self._to_timestamp(api_call_start_time)
completion_start_ts = self._to_timestamp(completion_start_time)
@@ -855,7 +916,9 @@ class OpenTelemetry(CustomLogger):
if api_call_start_ts is None or completion_start_ts is None:
return # Skip recording if conversion failed
- time_to_first_token_seconds = completion_start_ts - api_call_start_ts
+ time_to_first_token_seconds = (
+ completion_start_ts - api_call_start_ts
+ )
self._time_to_first_token_histogram.record(
time_to_first_token_seconds, attributes=common_attrs
)
@@ -925,7 +988,9 @@ class OpenTelemetry(CustomLogger):
generation_time_seconds = duration_s
if generation_time_seconds > 0:
- time_per_output_token_seconds = generation_time_seconds / completion_tokens
+ time_per_output_token_seconds = (
+ generation_time_seconds / completion_tokens
+ )
self._time_per_output_token_histogram.record(
time_per_output_token_seconds, attributes=common_attrs
)
@@ -986,20 +1051,18 @@ class OpenTelemetry(CustomLogger):
# See: https://github.com/open-telemetry/opentelemetry-python/pull/4676
# TODO: Refactor to use the proper OTEL Logs API instead of directly creating SDK LogRecords
- from opentelemetry._logs import SeverityNumber, get_logger, get_logger_provider
+ from opentelemetry._logs import SeverityNumber, get_logger
try:
- from opentelemetry.sdk._logs import LogRecord as SdkLogRecord # type: ignore[attr-defined] # OTEL < 1.39.0
+ from opentelemetry.sdk._logs import ( # type: ignore[attr-defined] # OTEL < 1.39.0
+ LogRecord as SdkLogRecord,
+ )
except ImportError:
- from opentelemetry.sdk._logs._internal import LogRecord as SdkLogRecord # OTEL >= 1.39.0
+ from opentelemetry.sdk._logs._internal import (
+ LogRecord as SdkLogRecord, # type: ignore[attr-defined] # OTEL >= 1.39.0
+ )
otel_logger = get_logger(LITELLM_LOGGER_NAME)
- # Get the resource from the logger provider
- logger_provider = get_logger_provider()
- resource = getattr(
- logger_provider, "_resource", None
- ) or self._get_litellm_resource(self.config)
-
parent_ctx = span.get_span_context()
provider = (kwargs.get("litellm_params") or {}).get(
"custom_llm_provider", "Unknown"
@@ -1008,7 +1071,10 @@ class OpenTelemetry(CustomLogger):
# per-message events
for msg in kwargs.get("messages", []):
role = msg.get("role", "user")
- attrs = {"event_name": "gen_ai.content.prompt", "gen_ai.system": provider}
+ attrs = {
+ "event_name": "gen_ai.content.prompt",
+ "gen_ai.system": provider,
+ }
if role == "tool" and msg.get("id"):
attrs["id"] = msg["id"]
if self.message_logging and msg.get("content"):
@@ -1022,7 +1088,6 @@ class OpenTelemetry(CustomLogger):
severity_number=SeverityNumber.INFO,
severity_text="INFO",
body=msg.copy(),
- resource=resource,
attributes=attrs,
)
otel_logger.emit(log_record)
@@ -1054,7 +1119,6 @@ class OpenTelemetry(CustomLogger):
severity_number=SeverityNumber.INFO,
severity_text="INFO",
body=body,
- resource=resource,
attributes=attrs,
)
otel_logger.emit(log_record)
@@ -1106,6 +1170,12 @@ class OpenTelemetry(CustomLogger):
context=context,
)
+ self.safe_set_attribute(
+ span=guardrail_span,
+ key=SpanAttributes.OPENINFERENCE_SPAN_KIND,
+ value=OpenInferenceSpanKindValues.GUARDRAIL.value,
+ )
+
self.safe_set_attribute(
span=guardrail_span,
key="guardrail_name",
@@ -1118,7 +1188,9 @@ class OpenTelemetry(CustomLogger):
value=guardrail_information.get("guardrail_mode"),
)
- masked_entity_count = guardrail_information.get("masked_entity_count")
+ masked_entity_count = guardrail_information.get(
+ "masked_entity_count"
+ )
if masked_entity_count is not None:
guardrail_span.set_attribute(
"masked_entity_count", safe_dumps(masked_entity_count)
@@ -1145,8 +1217,9 @@ class OpenTelemetry(CustomLogger):
# Decide whether to create a primary span
# Always create if no parent span exists (backward compatibility)
# OR if USE_OTEL_LITELLM_REQUEST_SPAN is explicitly enabled
- should_create_primary_span = parent_otel_span is None or get_secret_bool(
- "USE_OTEL_LITELLM_REQUEST_SPAN"
+ should_create_primary_span = (
+ parent_otel_span is None
+ or get_secret_bool("USE_OTEL_LITELLM_REQUEST_SPAN")
)
if should_create_primary_span:
@@ -1172,7 +1245,9 @@ class OpenTelemetry(CustomLogger):
if parent_otel_span.is_recording():
parent_otel_span.set_status(Status(StatusCode.ERROR))
self.set_attributes(parent_otel_span, kwargs, response_obj)
- self._record_exception_on_span(span=parent_otel_span, kwargs=kwargs)
+ self._record_exception_on_span(
+ span=parent_otel_span, kwargs=kwargs
+ )
# Create span for guardrail information
self._create_guardrail_span(kwargs=kwargs, context=_parent_context)
@@ -1195,7 +1270,9 @@ class OpenTelemetry(CustomLogger):
2. Sets structured error attributes from StandardLoggingPayloadErrorInformation
"""
try:
- from litellm.integrations._types.open_inference import ErrorAttributes
+ from litellm.integrations._types.open_inference import (
+ ErrorAttributes,
+ )
# Get the exception object if available
exception = kwargs.get("exception")
@@ -1205,15 +1282,17 @@ class OpenTelemetry(CustomLogger):
span.record_exception(exception)
# Get StandardLoggingPayload for structured error information
- standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get(
- "standard_logging_object"
+ standard_logging_payload: Optional[StandardLoggingPayload] = (
+ kwargs.get("standard_logging_object")
)
if standard_logging_payload is None:
return
# Extract error_information from StandardLoggingPayload
- error_information = standard_logging_payload.get("error_information")
+ error_information = standard_logging_payload.get(
+ "error_information"
+ )
if error_information is None:
# Fallback to error_str if error_information is not available
@@ -1303,7 +1382,9 @@ class OpenTelemetry(CustomLogger):
)
pass
- def cast_as_primitive_value_type(self, value) -> Union[str, bool, int, float]:
+ def cast_as_primitive_value_type(
+ self, value
+ ) -> Union[str, bool, int, float]:
"""
Casts the value to a primitive OTEL type if it is not already a primitive type.
@@ -1373,8 +1454,8 @@ class OpenTelemetry(CustomLogger):
optional_params = kwargs.get("optional_params", {})
litellm_params = kwargs.get("litellm_params", {}) or {}
- standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get(
- "standard_logging_object"
+ standard_logging_payload: Optional[StandardLoggingPayload] = (
+ kwargs.get("standard_logging_object")
)
if standard_logging_payload is None:
raise ValueError("standard_logging_object not found in kwargs")
@@ -1396,11 +1477,13 @@ class OpenTelemetry(CustomLogger):
) or (standard_logging_payload or {}).get("hidden_params", {})
if hidden_params:
self.safe_set_attribute(
- span=span, key="hidden_params", value=safe_dumps(hidden_params)
+ span=span,
+ key="hidden_params",
+ value=safe_dumps(hidden_params),
)
# Cost breakdown tracking
- cost_breakdown: Optional[CostBreakdown] = standard_logging_payload.get(
- "cost_breakdown"
+ cost_breakdown: Optional[CostBreakdown] = (
+ standard_logging_payload.get("cost_breakdown")
)
if cost_breakdown:
for key, value in cost_breakdown.items():
@@ -1476,7 +1559,9 @@ class OpenTelemetry(CustomLogger):
# The unique identifier for the completion.
if response_obj and response_obj.get("id"):
self.safe_set_attribute(
- span=span, key="gen_ai.response.id", value=response_obj.get("id")
+ span=span,
+ key="gen_ai.response.id",
+ value=response_obj.get("id"),
)
# The model used to generate the response.
@@ -1592,7 +1677,6 @@ class OpenTelemetry(CustomLogger):
for idx, choice in enumerate(response_obj.get("choices")):
if choice.get("finish_reason"):
-
message = choice.get("message")
tool_calls = message.get("tool_calls")
if tool_calls:
@@ -1605,11 +1689,16 @@ class OpenTelemetry(CustomLogger):
)
except Exception as e:
+ self.handle_callback_failure(
+ callback_name=self.callback_name or "opentelemetry"
+ )
verbose_logger.exception(
"OpenTelemetry logging error in set_attributes %s", str(e)
)
- def _cast_as_primitive_value_type(self, value) -> Union[str, bool, int, float]:
+ def _cast_as_primitive_value_type(
+ self, value
+ ) -> Union[str, bool, int, float]:
"""
Casts the value to a primitive OTEL type if it is not already a primitive type.
@@ -1643,7 +1732,10 @@ class OpenTelemetry(CustomLogger):
if isinstance(messages, str):
# Handle system_instructions passed as a string
return [
- {"role": "system", "parts": [{"type": "text", "content": messages}]}
+ {
+ "role": "system",
+ "parts": [{"type": "text", "content": messages}],
+ }
]
transformed = []
@@ -1684,9 +1776,11 @@ class OpenTelemetry(CustomLogger):
message = choice.get("message") or {}
finish_reason = choice.get("finish_reason")
- transformed_msg = self._transform_messages_to_otel_semantic_conventions(
- [message]
- )[0]
+ transformed_msg = (
+ self._transform_messages_to_otel_semantic_conventions(
+ [message]
+ )[0]
+ )
if finish_reason:
transformed_msg["finish_reason"] = finish_reason
@@ -1695,9 +1789,12 @@ class OpenTelemetry(CustomLogger):
def set_raw_request_attributes(self, span: Span, kwargs, response_obj):
try:
+ self.set_attributes(span, kwargs, response_obj)
kwargs.get("optional_params", {})
litellm_params = kwargs.get("litellm_params", {}) or {}
- custom_llm_provider = litellm_params.get("custom_llm_provider", "Unknown")
+ custom_llm_provider = litellm_params.get(
+ "custom_llm_provider", "Unknown"
+ )
_raw_response = kwargs.get("original_response")
_additional_args = kwargs.get("additional_args", {}) or {}
@@ -1710,7 +1807,9 @@ class OpenTelemetry(CustomLogger):
if complete_input_dict and isinstance(complete_input_dict, dict):
for param, val in complete_input_dict.items():
self.safe_set_attribute(
- span=span, key=f"llm.{custom_llm_provider}.{param}", value=val
+ span=span,
+ key=f"llm.{custom_llm_provider}.{param}",
+ value=val,
)
#############################################
@@ -1742,7 +1841,8 @@ class OpenTelemetry(CustomLogger):
)
except Exception as e:
verbose_logger.exception(
- "OpenTelemetry logging error in set_raw_request_attributes %s", str(e)
+ "OpenTelemetry logging error in set_raw_request_attributes %s",
+ str(e),
)
def _to_ns(self, dt):
@@ -1782,7 +1882,9 @@ class OpenTelemetry(CustomLogger):
)
litellm_params = kwargs.get("litellm_params", {}) or {}
- proxy_server_request = litellm_params.get("proxy_server_request", {}) or {}
+ proxy_server_request = (
+ litellm_params.get("proxy_server_request", {}) or {}
+ )
headers = proxy_server_request.get("headers", {}) or {}
traceparent = headers.get("traceparent", None)
_metadata = litellm_params.get("metadata", {}) or {}
@@ -1801,7 +1903,10 @@ class OpenTelemetry(CustomLogger):
"OpenTelemetry: Using traceparent header for context propagation"
)
carrier = {"traceparent": traceparent}
- return TraceContextTextMapPropagator().extract(carrier=carrier), None
+ return (
+ TraceContextTextMapPropagator().extract(carrier=carrier),
+ None,
+ )
# Priority 3: Active span from global context (auto-detection)
try:
@@ -1929,10 +2034,14 @@ class OpenTelemetry(CustomLogger):
self.OTEL_HEADERS,
)
- _split_otel_headers = OpenTelemetry._get_headers_dictionary(self.OTEL_HEADERS)
+ _split_otel_headers = OpenTelemetry._get_headers_dictionary(
+ self.OTEL_HEADERS
+ )
# Normalize endpoint for logs - ensure it points to /v1/logs instead of /v1/traces
- normalized_endpoint = self._normalize_otel_endpoint(self.OTEL_ENDPOINT, "logs")
+ normalized_endpoint = self._normalize_otel_endpoint(
+ self.OTEL_ENDPOINT, "logs"
+ )
verbose_logger.debug(
"OpenTelemetry: Log endpoint normalized from %s to %s",
@@ -2020,14 +2129,18 @@ class OpenTelemetry(CustomLogger):
self.OTEL_HEADERS,
)
- _split_otel_headers = OpenTelemetry._get_headers_dictionary(self.OTEL_HEADERS)
+ _split_otel_headers = OpenTelemetry._get_headers_dictionary(
+ self.OTEL_HEADERS
+ )
normalized_endpoint = self._normalize_otel_endpoint(
self.OTEL_ENDPOINT, "metrics"
)
if self.OTEL_EXPORTER == "console":
exporter = ConsoleMetricExporter()
- return PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
+ return PeriodicExportingMetricReader(
+ exporter, export_interval_millis=5000
+ )
elif (
self.OTEL_EXPORTER == "otlp_http"
@@ -2043,7 +2156,9 @@ class OpenTelemetry(CustomLogger):
headers=_split_otel_headers,
preferred_temporality={Histogram: AggregationTemporality.DELTA},
)
- return PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
+ return PeriodicExportingMetricReader(
+ exporter, export_interval_millis=5000
+ )
elif self.OTEL_EXPORTER == "otlp_grpc" or self.OTEL_EXPORTER == "grpc":
try:
@@ -2061,7 +2176,9 @@ class OpenTelemetry(CustomLogger):
headers=_split_otel_headers,
preferred_temporality={Histogram: AggregationTemporality.DELTA},
)
- return PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
+ return PeriodicExportingMetricReader(
+ exporter, export_interval_millis=5000
+ )
else:
verbose_logger.warning(
@@ -2069,7 +2186,9 @@ class OpenTelemetry(CustomLogger):
self.OTEL_EXPORTER,
)
exporter = ConsoleMetricExporter()
- return PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
+ return PeriodicExportingMetricReader(
+ exporter, export_interval_millis=5000
+ )
def _normalize_otel_endpoint(
self, endpoint: Optional[str], signal_type: str
@@ -2140,7 +2259,9 @@ class OpenTelemetry(CustomLogger):
return endpoint
@staticmethod
- def _get_headers_dictionary(headers: Optional[Union[str, dict]]) -> Dict[str, str]:
+ def _get_headers_dictionary(
+ headers: Optional[Union[str, dict]],
+ ) -> Dict[str, str]:
"""
Convert a string or dictionary of headers into a dictionary of headers.
"""
diff --git a/litellm/integrations/posthog.py b/litellm/integrations/posthog.py
index 468b1a441fb..c4b6e843d60 100644
--- a/litellm/integrations/posthog.py
+++ b/litellm/integrations/posthog.py
@@ -17,6 +17,11 @@ from typing import Any, Dict, Optional, Tuple
from litellm._logging import verbose_logger
from litellm._uuid import uuid
from litellm.integrations.custom_batch_logger import CustomBatchLogger
+from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+from litellm.integrations.posthog_mock_client import (
+ should_use_posthog_mock,
+ create_mock_posthog_client,
+)
from litellm.llms.custom_httpx.http_handler import (
_get_httpx_client,
get_async_httpx_client,
@@ -40,6 +45,12 @@ class PostHogLogger(CustomBatchLogger):
"""
try:
verbose_logger.debug("PostHog: in init posthog logger")
+
+ self.is_mock_mode = should_use_posthog_mock()
+ if self.is_mock_mode:
+ create_mock_posthog_client()
+ verbose_logger.debug("[POSTHOG MOCK] PostHog logger initialized in mock mode")
+
if os.getenv("POSTHOG_API_KEY", None) is None:
raise Exception("POSTHOG_API_KEY is not set, set 'POSTHOG_API_KEY=<>'")
@@ -90,7 +101,7 @@ class PostHogLogger(CustomBatchLogger):
response = self.sync_client.post(
url=capture_url,
- json=payload,
+ content=safe_dumps(payload),
headers=headers,
)
response.raise_for_status()
@@ -100,7 +111,10 @@ class PostHogLogger(CustomBatchLogger):
f"Response from PostHog API status_code: {response.status_code}, text: {response.text}"
)
- verbose_logger.debug("PostHog: Sync event successfully sent")
+ if self.is_mock_mode:
+ verbose_logger.debug("[POSTHOG MOCK] Sync event successfully mocked")
+ else:
+ verbose_logger.debug("PostHog: Sync event successfully sent")
except Exception as e:
verbose_logger.exception(f"PostHog Sync Layer Error - {str(e)}")
@@ -320,6 +334,9 @@ class PostHogLogger(CustomBatchLogger):
verbose_logger.debug(
f"PostHog: Sending batch of {len(self.log_queue)} events"
)
+
+ if self.is_mock_mode:
+ verbose_logger.debug("[POSTHOG MOCK] Mock mode enabled - API calls will be intercepted")
# Group events by credentials for batch sending
batches_by_credentials: Dict[tuple[str, str], list] = {}
@@ -340,7 +357,7 @@ class PostHogLogger(CustomBatchLogger):
response = await self.async_client.post(
url=capture_url,
- json=payload,
+ content=safe_dumps(payload),
headers=headers,
)
response.raise_for_status()
@@ -350,9 +367,12 @@ class PostHogLogger(CustomBatchLogger):
f"Response from PostHog API status_code: {response.status_code}, text: {response.text}"
)
- verbose_logger.debug(
- f"PostHog: Batch of {len(self.log_queue)} events successfully sent"
- )
+ if self.is_mock_mode:
+ verbose_logger.debug(f"[POSTHOG MOCK] Batch of {len(self.log_queue)} events successfully mocked")
+ else:
+ verbose_logger.debug(
+ f"PostHog: Batch of {len(self.log_queue)} events successfully sent"
+ )
except Exception as e:
verbose_logger.exception(f"PostHog Error sending batch API - {str(e)}")
@@ -419,7 +439,7 @@ class PostHogLogger(CustomBatchLogger):
response = self.sync_client.post(
url=capture_url,
- json=payload,
+ content=safe_dumps(payload),
headers=headers,
)
response.raise_for_status()
@@ -429,9 +449,14 @@ class PostHogLogger(CustomBatchLogger):
f"PostHog: Failed to flush on exit - status {response.status_code}"
)
- verbose_logger.debug(
- f"PostHog: Successfully flushed {len(self.log_queue)} events on exit"
- )
+ if self.is_mock_mode:
+ verbose_logger.debug(
+ f"[POSTHOG MOCK] Successfully flushed {len(self.log_queue)} events on exit"
+ )
+ else:
+ verbose_logger.debug(
+ f"PostHog: Successfully flushed {len(self.log_queue)} events on exit"
+ )
self.log_queue.clear()
except Exception as e:
diff --git a/litellm/integrations/posthog_mock_client.py b/litellm/integrations/posthog_mock_client.py
new file mode 100644
index 00000000000..b713587ed6f
--- /dev/null
+++ b/litellm/integrations/posthog_mock_client.py
@@ -0,0 +1,30 @@
+"""
+Mock httpx client for PostHog integration testing.
+
+This module intercepts PostHog API calls and returns successful mock responses,
+allowing full code execution without making actual network calls.
+
+Usage:
+ Set POSTHOG_MOCK=true in environment variables or config to enable mock mode.
+"""
+
+from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory
+
+# Create mock client using factory
+_config = MockClientConfig(
+ name="POSTHOG",
+ env_var="POSTHOG_MOCK",
+ default_latency_ms=100,
+ default_status_code=200,
+ default_json_data={"status": "success"},
+ url_matchers=[
+ ".posthog.com",
+ "posthog.com",
+ "us.i.posthog.com",
+ "app.posthog.com",
+ ],
+ patch_async_handler=True,
+ patch_sync_client=True,
+)
+
+create_mock_posthog_client, should_use_posthog_mock = create_mock_client_factory(_config)
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index bafb0d88c82..4c7afd5a57c 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -1,6 +1,7 @@
# used for /metrics endpoint on LiteLLM Proxy
#### What this does ####
# On success, log events to Prometheus
+import asyncio
import os
import sys
from datetime import datetime, timedelta
@@ -21,6 +22,10 @@ from typing import (
import litellm
from litellm._logging import print_verbose, verbose_logger
from litellm.integrations.custom_logger import CustomLogger
+from litellm.litellm_core_utils.core_helpers import (
+ get_litellm_metadata_from_kwargs,
+ get_metadata_variable_name_from_kwargs,
+)
from litellm.proxy._types import (
LiteLLM_DeletedVerificationToken,
LiteLLM_TeamTable,
@@ -28,7 +33,10 @@ from litellm.proxy._types import (
UserAPIKeyAuth,
)
from litellm.types.integrations.prometheus import *
-from litellm.types.integrations.prometheus import _sanitize_prometheus_label_name
+from litellm.types.integrations.prometheus import (
+ _sanitize_prometheus_label_name,
+ _sanitize_prometheus_label_value,
+)
from litellm.types.utils import StandardLoggingPayload
if TYPE_CHECKING:
@@ -229,14 +237,18 @@ class PrometheusLogger(CustomLogger):
self.litellm_remaining_api_key_requests_for_model = self._gauge_factory(
"litellm_remaining_api_key_requests_for_model",
"Remaining Requests API Key can make for model (model based rpm limit on key)",
- labelnames=["hashed_api_key", "api_key_alias", "model"],
+ labelnames=self.get_labels_for_metric(
+ "litellm_remaining_api_key_requests_for_model"
+ ),
)
# Remaining MODEL TPM limit for API Key
self.litellm_remaining_api_key_tokens_for_model = self._gauge_factory(
"litellm_remaining_api_key_tokens_for_model",
"Remaining Tokens API Key can make for model (model based tpm limit on key)",
- labelnames=["hashed_api_key", "api_key_alias", "model"],
+ labelnames=self.get_labels_for_metric(
+ "litellm_remaining_api_key_tokens_for_model"
+ ),
)
########################################
@@ -312,6 +324,18 @@ class PrometheusLogger(CustomLogger):
labelnames=self.get_labels_for_metric("litellm_deployment_state"),
)
+ self.litellm_deployment_tpm_limit = self._gauge_factory(
+ "litellm_deployment_tpm_limit",
+ "Deployment TPM limit found in config",
+ labelnames=self.get_labels_for_metric("litellm_deployment_tpm_limit"),
+ )
+
+ self.litellm_deployment_rpm_limit = self._gauge_factory(
+ "litellm_deployment_rpm_limit",
+ "Deployment RPM limit found in config",
+ labelnames=self.get_labels_for_metric("litellm_deployment_rpm_limit"),
+ )
+
self.litellm_deployment_cooled_down = self._counter_factory(
"litellm_deployment_cooled_down",
"LLM Deployment Analytics - Number of times a deployment has been cooled down by LiteLLM load balancing logic. exception_status is the status of the exception that caused the deployment to be cooled down",
@@ -373,15 +397,9 @@ class PrometheusLogger(CustomLogger):
self.litellm_llm_api_failed_requests_metric = self._counter_factory(
name="litellm_llm_api_failed_requests_metric",
documentation="deprecated - use litellm_proxy_failed_requests_metric",
- labelnames=[
- "end_user",
- "hashed_api_key",
- "api_key_alias",
- "model",
- "team",
- "team_alias",
- "user",
- ],
+ labelnames=self.get_labels_for_metric(
+ "litellm_llm_api_failed_requests_metric"
+ ),
)
self.litellm_requests_metric = self._counter_factory(
@@ -891,7 +909,7 @@ class PrometheusLogger(CustomLogger):
model = kwargs.get("model", "")
litellm_params = kwargs.get("litellm_params", {}) or {}
- _metadata = litellm_params.get("metadata", {})
+ _metadata = litellm_params.get("metadata") or {}
get_end_user_id_for_cost_tracking = _get_cached_end_user_id_for_cost_tracking()
end_user_id = get_end_user_id_for_cost_tracking(
@@ -954,6 +972,8 @@ class PrometheusLogger(CustomLogger):
route=standard_logging_payload["metadata"].get(
"user_api_key_request_route"
),
+ client_ip=standard_logging_payload["metadata"].get("requester_ip_address"),
+ user_agent=standard_logging_payload["metadata"].get("user_agent"),
)
if (
@@ -1011,6 +1031,7 @@ class PrometheusLogger(CustomLogger):
user_api_key_alias=user_api_key_alias,
kwargs=kwargs,
metadata=_metadata,
+ model_id=enum_values.model_id,
)
# set latency metrics
@@ -1038,16 +1059,16 @@ class PrometheusLogger(CustomLogger):
enum_values=enum_values,
)
- if (
- standard_logging_payload["stream"] is True
- ): # log successful streaming requests from logging event hook.
- _labels = prometheus_label_factory(
- supported_enum_labels=self.get_labels_for_metric(
- metric_name="litellm_proxy_total_requests_metric"
- ),
- enum_values=enum_values,
- )
- self.litellm_proxy_total_requests_metric.labels(**_labels).inc()
+ # increment litellm_proxy_total_requests_metric for all successful requests
+ # (both streaming and non-streaming) in this single location to prevent
+ # double-counting that occurs when async_post_call_success_hook also increments
+ _labels = prometheus_label_factory(
+ supported_enum_labels=self.get_labels_for_metric(
+ metric_name="litellm_proxy_total_requests_metric"
+ ),
+ enum_values=enum_values,
+ )
+ self.litellm_proxy_total_requests_metric.labels(**_labels).inc()
def _increment_token_metrics(
self,
@@ -1069,13 +1090,6 @@ class PrometheusLogger(CustomLogger):
):
_tags = standard_logging_payload["request_tags"]
- _labels = prometheus_label_factory(
- supported_enum_labels=self.get_labels_for_metric(
- metric_name="litellm_proxy_total_requests_metric"
- ),
- enum_values=enum_values,
- )
-
_labels = prometheus_label_factory(
supported_enum_labels=self.get_labels_for_metric(
metric_name="litellm_total_tokens_metric"
@@ -1165,49 +1179,44 @@ class PrometheusLogger(CustomLogger):
response_cost: float,
user_id: Optional[str] = None,
):
- _team_spend = litellm_params.get("metadata", {}).get(
- "user_api_key_team_spend", None
- )
- _team_max_budget = litellm_params.get("metadata", {}).get(
- "user_api_key_team_max_budget", None
- )
+ _metadata = litellm_params.get("metadata") or {}
+ _team_spend = _metadata.get("user_api_key_team_spend", None)
+ _team_max_budget = _metadata.get("user_api_key_team_max_budget", None)
- _api_key_spend = litellm_params.get("metadata", {}).get(
- "user_api_key_spend", None
- )
- _api_key_max_budget = litellm_params.get("metadata", {}).get(
- "user_api_key_max_budget", None
- )
+ _api_key_spend = _metadata.get("user_api_key_spend", None)
+ _api_key_max_budget = _metadata.get("user_api_key_max_budget", None)
- _user_spend = litellm_params.get("metadata", {}).get(
- "user_api_key_user_spend", None
- )
- _user_max_budget = litellm_params.get("metadata", {}).get(
- "user_api_key_user_max_budget", None
- )
+ _user_spend = _metadata.get("user_api_key_user_spend", None)
+ _user_max_budget = _metadata.get("user_api_key_user_max_budget", None)
- await self._set_api_key_budget_metrics_after_api_request(
- user_api_key=user_api_key,
- user_api_key_alias=user_api_key_alias,
- response_cost=response_cost,
- key_max_budget=_api_key_max_budget,
- key_spend=_api_key_spend,
- )
-
- await self._set_team_budget_metrics_after_api_request(
- user_api_team=user_api_team,
- user_api_team_alias=user_api_team_alias,
- team_spend=_team_spend,
- team_max_budget=_team_max_budget,
- response_cost=response_cost,
- )
-
- await self._set_user_budget_metrics_after_api_request(
- user_id=user_id,
- user_spend=_user_spend,
- user_max_budget=_user_max_budget,
- response_cost=response_cost,
+ results = await asyncio.gather(
+ self._set_api_key_budget_metrics_after_api_request(
+ user_api_key=user_api_key,
+ user_api_key_alias=user_api_key_alias,
+ response_cost=response_cost,
+ key_max_budget=_api_key_max_budget,
+ key_spend=_api_key_spend,
+ ),
+ self._set_team_budget_metrics_after_api_request(
+ user_api_team=user_api_team,
+ user_api_team_alias=user_api_team_alias,
+ team_spend=_team_spend,
+ team_max_budget=_team_max_budget,
+ response_cost=response_cost,
+ ),
+ self._set_user_budget_metrics_after_api_request(
+ user_id=user_id,
+ user_spend=_user_spend,
+ user_max_budget=_user_max_budget,
+ response_cost=response_cost,
+ ),
+ return_exceptions=True,
)
+ for i, r in enumerate(results):
+ if isinstance(r, Exception):
+ verbose_logger.debug(
+ f"[Non-Blocking] Prometheus: Budget metric lookup {['key', 'team', 'user'][i]} failed: {r}"
+ )
def _increment_top_level_request_and_spend_metrics(
self,
@@ -1245,6 +1254,7 @@ class PrometheusLogger(CustomLogger):
user_api_key_alias: Optional[str],
kwargs: dict,
metadata: dict,
+ model_id: Optional[str] = None,
):
from litellm.proxy.common_utils.callback_utils import (
get_model_group_from_litellm_kwargs,
@@ -1266,11 +1276,17 @@ class PrometheusLogger(CustomLogger):
)
self.litellm_remaining_api_key_requests_for_model.labels(
- user_api_key, user_api_key_alias, model_group
+ _sanitize_prometheus_label_value(user_api_key),
+ _sanitize_prometheus_label_value(user_api_key_alias),
+ _sanitize_prometheus_label_value(model_group),
+ _sanitize_prometheus_label_value(model_id),
).set(remaining_requests)
self.litellm_remaining_api_key_tokens_for_model.labels(
- user_api_key, user_api_key_alias, model_group
+ _sanitize_prometheus_label_value(user_api_key),
+ _sanitize_prometheus_label_value(user_api_key_alias),
+ _sanitize_prometheus_label_value(model_group),
+ _sanitize_prometheus_label_value(model_id),
).set(remaining_tokens)
def _set_latency_metrics(
@@ -1296,12 +1312,14 @@ class PrometheusLogger(CustomLogger):
time_to_first_token_seconds is not None
and kwargs.get("stream", False) is True # only emit for streaming requests
):
+ _ttft_labels = prometheus_label_factory(
+ supported_enum_labels=self.get_labels_for_metric(
+ metric_name="litellm_llm_api_time_to_first_token_metric"
+ ),
+ enum_values=enum_values,
+ )
self.litellm_llm_api_time_to_first_token_metric.labels(
- model,
- user_api_key,
- user_api_key_alias,
- user_api_team,
- user_api_team_alias,
+ **_ttft_labels
).observe(time_to_first_token_seconds)
else:
verbose_logger.debug(
@@ -1341,7 +1359,7 @@ class PrometheusLogger(CustomLogger):
# request queue time (time from arrival to processing start)
_litellm_params = kwargs.get("litellm_params", {}) or {}
- queue_time_seconds = _litellm_params.get("metadata", {}).get(
+ queue_time_seconds = (_litellm_params.get("metadata") or {}).get(
"queue_time_seconds"
)
if queue_time_seconds is not None and queue_time_seconds >= 0:
@@ -1365,14 +1383,14 @@ class PrometheusLogger(CustomLogger):
standard_logging_payload: StandardLoggingPayload = kwargs.get(
"standard_logging_object", {}
)
-
+
if self._should_skip_metrics_for_invalid_key(
kwargs=kwargs, standard_logging_payload=standard_logging_payload
):
return
-
+
model = kwargs.get("model", "")
-
+
litellm_params = kwargs.get("litellm_params", {}) or {}
get_end_user_id_for_cost_tracking = _get_cached_end_user_id_for_cost_tracking()
@@ -1389,13 +1407,14 @@ class PrometheusLogger(CustomLogger):
try:
self.litellm_llm_api_failed_requests_metric.labels(
- end_user_id,
- user_api_key,
- user_api_key_alias,
- model,
- user_api_team,
- user_api_team_alias,
- user_id,
+ _sanitize_prometheus_label_value(end_user_id),
+ _sanitize_prometheus_label_value(user_api_key),
+ _sanitize_prometheus_label_value(user_api_key_alias),
+ _sanitize_prometheus_label_value(model),
+ _sanitize_prometheus_label_value(user_api_team),
+ _sanitize_prometheus_label_value(user_api_team_alias),
+ _sanitize_prometheus_label_value(user_id),
+ _sanitize_prometheus_label_value(standard_logging_payload.get("model_id", "")),
).inc()
self.set_llm_deployment_failure_metrics(kwargs)
except Exception as e:
@@ -1413,49 +1432,57 @@ class PrometheusLogger(CustomLogger):
) -> Optional[int]:
"""
Extract HTTP status code from various input formats for validation.
-
+
This is a centralized helper to extract status code from different
callback function signatures. Handles both ProxyException (uses 'code')
and standard exceptions (uses 'status_code').
-
+
Args:
kwargs: Dictionary potentially containing 'exception' key
enum_values: Object with 'status_code' attribute
exception: Exception object to extract status code from directly
-
+
Returns:
Status code as integer if found, None otherwise
"""
status_code = None
-
+
# Try from enum_values first (most common in our callbacks)
- if enum_values and hasattr(enum_values, "status_code") and enum_values.status_code:
+ if (
+ enum_values
+ and hasattr(enum_values, "status_code")
+ and enum_values.status_code
+ ):
try:
status_code = int(enum_values.status_code)
except (ValueError, TypeError):
pass
-
+
if not status_code and exception:
# ProxyException uses 'code' attribute, other exceptions may use 'status_code'
- status_code = getattr(exception, "status_code", None) or getattr(exception, "code", None)
+ status_code = getattr(exception, "status_code", None) or getattr(
+ exception, "code", None
+ )
if status_code is not None:
try:
status_code = int(status_code)
except (ValueError, TypeError):
status_code = None
-
+
if not status_code and kwargs:
exception_in_kwargs = kwargs.get("exception")
if exception_in_kwargs:
- status_code = getattr(exception_in_kwargs, "status_code", None) or getattr(exception_in_kwargs, "code", None)
+ status_code = getattr(
+ exception_in_kwargs, "status_code", None
+ ) or getattr(exception_in_kwargs, "code", None)
if status_code is not None:
try:
status_code = int(status_code)
except (ValueError, TypeError):
status_code = None
-
+
return status_code
-
+
def _is_invalid_api_key_request(
self,
status_code: Optional[int],
@@ -1463,23 +1490,23 @@ class PrometheusLogger(CustomLogger):
) -> bool:
"""
Determine if a request has an invalid API key based on status code and exception.
-
+
This method prevents invalid authentication attempts from being recorded in
Prometheus metrics. A 401 status code is the definitive indicator of authentication
failure. Additionally, we check exception messages for authentication error patterns
to catch cases where the exception hasn't been converted to a ProxyException yet.
-
+
Args:
status_code: HTTP status code (401 indicates authentication error)
exception: Exception object to check for auth-related error messages
-
+
Returns:
True if the request has an invalid API key and metrics should be skipped,
False otherwise
"""
if status_code == 401:
return True
-
+
# Handle cases where AssertionError is raised before conversion to ProxyException
if exception is not None:
exception_str = str(exception).lower()
@@ -1492,9 +1519,9 @@ class PrometheusLogger(CustomLogger):
]
if any(pattern in exception_str for pattern in auth_error_patterns):
return True
-
+
return False
-
+
def _should_skip_metrics_for_invalid_key(
self,
kwargs: Optional[dict] = None,
@@ -1505,18 +1532,18 @@ class PrometheusLogger(CustomLogger):
) -> bool:
"""
Determine if Prometheus metrics should be skipped for invalid API key requests.
-
+
This is a centralized validation method that extracts status code and exception
information from various callback function signatures and determines if the request
represents an invalid API key attempt that should be filtered from metrics.
-
+
Args:
kwargs: Dictionary potentially containing exception and other data
user_api_key_dict: User API key authentication object (currently unused)
enum_values: Object with status_code attribute
standard_logging_payload: Standard logging payload dictionary
exception: Exception object to check directly
-
+
Returns:
True if metrics should be skipped (invalid key detected), False otherwise
"""
@@ -1525,17 +1552,17 @@ class PrometheusLogger(CustomLogger):
enum_values=enum_values,
exception=exception,
)
-
+
if exception is None and kwargs:
exception = kwargs.get("exception")
-
+
if self._is_invalid_api_key_request(status_code, exception=exception):
verbose_logger.debug(
"Skipping Prometheus metrics for invalid API key request: "
f"status_code={status_code}, exception={type(exception).__name__ if exception else None}"
)
return True
-
+
return False
async def async_post_call_failure_hook(
@@ -1576,6 +1603,10 @@ class PrometheusLogger(CustomLogger):
litellm_params=request_data,
proxy_server_request=request_data.get("proxy_server_request", {}),
)
+ _metadata = request_data.get("metadata", {}) or {}
+ model_id = _metadata.get("model_info", {}).get("id") or request_data.get(
+ "model_info", {}
+ ).get("id")
enum_values = UserAPIKeyLabelValues(
end_user=user_api_key_dict.end_user_id,
user=user_api_key_dict.user_id,
@@ -1590,6 +1621,9 @@ class PrometheusLogger(CustomLogger):
exception_class=self._get_exception_class_name(original_exception),
tags=_tags,
route=user_api_key_dict.request_route,
+ client_ip=_metadata.get("requester_ip_address"),
+ user_agent=_metadata.get("user_agent"),
+ model_id=model_id,
)
_labels = prometheus_label_factory(
supported_enum_labels=self.get_labels_for_metric(
@@ -1618,46 +1652,114 @@ class PrometheusLogger(CustomLogger):
):
"""
Proxy level tracking - triggered when the proxy responds with a success response to the client
+
+ Note: litellm_proxy_total_requests_metric is NOT incremented here to avoid
+ double-counting. It is incremented in async_log_success_event which fires
+ for all successful requests (both streaming and non-streaming).
"""
- try:
- from litellm.litellm_core_utils.litellm_logging import (
- StandardLoggingPayloadSetup,
- )
+ pass
- if self._should_skip_metrics_for_invalid_key(
- user_api_key_dict=user_api_key_dict
- ):
- return
+ def _safe_get(self, obj: Any, key: str, default: Any = None) -> Any:
+ """Get value from dict or Pydantic model."""
+ if obj is None:
+ return default
+ if isinstance(obj, dict):
+ return obj.get(key, default)
+ return getattr(obj, key, default)
- enum_values = UserAPIKeyLabelValues(
- end_user=user_api_key_dict.end_user_id,
- hashed_api_key=user_api_key_dict.api_key,
- api_key_alias=user_api_key_dict.key_alias,
- requested_model=data.get("model", ""),
- team=user_api_key_dict.team_id,
- team_alias=user_api_key_dict.team_alias,
- user=user_api_key_dict.user_id,
- user_email=user_api_key_dict.user_email,
- status_code="200",
- route=user_api_key_dict.request_route,
- tags=StandardLoggingPayloadSetup._get_request_tags(
- litellm_params=data,
- proxy_server_request=data.get("proxy_server_request", {}),
+ def _extract_deployment_failure_label_values(
+ self, request_kwargs: dict
+ ) -> Dict[str, Optional[str]]:
+ """
+ Extract label values for deployment failure metrics from all available
+ sources in request_kwargs. Falls back to litellm_params metadata and
+ user_api_key_auth when standard_logging_payload has None values.
+ """
+ standard_logging_payload = (
+ request_kwargs.get("standard_logging_object", {}) or {}
+ )
+ _litellm_params = request_kwargs.get("litellm_params", {}) or {}
+ _metadata_raw = self._safe_get(standard_logging_payload, "metadata") or {}
+ if isinstance(_metadata_raw, dict):
+ _metadata = _metadata_raw
+ else:
+ _metadata = {
+ "user_api_key_alias": getattr(
+ _metadata_raw, "user_api_key_alias", None
),
- )
- _labels = prometheus_label_factory(
- supported_enum_labels=self.get_labels_for_metric(
- metric_name="litellm_proxy_total_requests_metric"
+ "user_api_key_team_id": getattr(
+ _metadata_raw, "user_api_key_team_id", None
),
- enum_values=enum_values,
- )
- self.litellm_proxy_total_requests_metric.labels(**_labels).inc()
+ "user_api_key_team_alias": getattr(
+ _metadata_raw, "user_api_key_team_alias", None
+ ),
+ "user_api_key_hash": getattr(_metadata_raw, "user_api_key_hash", None),
+ "requester_ip_address": getattr(
+ _metadata_raw, "requester_ip_address", None
+ ),
+ "user_agent": getattr(_metadata_raw, "user_agent", None),
+ }
+ _litellm_params_metadata = _litellm_params.get("metadata", {}) or {}
- except Exception as e:
- verbose_logger.exception(
- "prometheus Layer Error(): Exception occured - {}".format(str(e))
- )
- pass
+ # Extract user_api_key_auth if present (proxy injects this, skipped in merge)
+ user_api_key_auth = _litellm_params_metadata.get("user_api_key_auth")
+
+ def _get_api_key_alias() -> Optional[str]:
+ val = _metadata.get("user_api_key_alias")
+ if val is not None:
+ return val
+ val = _litellm_params_metadata.get("user_api_key_alias")
+ if val is not None:
+ return val
+ if user_api_key_auth is not None:
+ return getattr(user_api_key_auth, "key_alias", None)
+ return None
+
+ def _get_team_id() -> Optional[str]:
+ val = _metadata.get("user_api_key_team_id")
+ if val is not None:
+ return val
+ val = _litellm_params_metadata.get("user_api_key_team_id")
+ if val is not None:
+ return val
+ if user_api_key_auth is not None:
+ return getattr(user_api_key_auth, "team_id", None)
+ return None
+
+ def _get_team_alias() -> Optional[str]:
+ val = _metadata.get("user_api_key_team_alias")
+ if val is not None:
+ return val
+ val = _litellm_params_metadata.get("user_api_key_team_alias")
+ if val is not None:
+ return val
+ if user_api_key_auth is not None:
+ return getattr(user_api_key_auth, "team_alias", None)
+ return None
+
+ def _get_hashed_api_key() -> Optional[str]:
+ val = _metadata.get("user_api_key_hash")
+ if val is not None:
+ return val
+ val = _litellm_params_metadata.get("user_api_key_hash")
+ if val is not None:
+ return val
+ if user_api_key_auth is not None:
+ return getattr(user_api_key_auth, "api_key", None) or getattr(
+ user_api_key_auth, "api_key_hash", None
+ )
+ return None
+
+ return {
+ "api_key_alias": _get_api_key_alias(),
+ "team": _get_team_id(),
+ "team_alias": _get_team_alias(),
+ "hashed_api_key": _get_hashed_api_key(),
+ "client_ip": _metadata.get("requester_ip_address")
+ or _litellm_params_metadata.get("requester_ip_address"),
+ "user_agent": _metadata.get("user_agent")
+ or _litellm_params_metadata.get("user_agent"),
+ }
def set_llm_deployment_failure_metrics(self, request_kwargs: dict):
"""
@@ -1683,16 +1785,59 @@ class PrometheusLogger(CustomLogger):
model_id = standard_logging_payload.get("model_id", None)
exception = request_kwargs.get("exception", None)
+ # Fallback: model_id from litellm_metadata.model_info
+ if model_id is None:
+ _model_info = (
+ (_litellm_params.get("litellm_metadata") or {}).get("model_info")
+ or (_litellm_params.get("metadata") or {}).get("model_info")
+ or {}
+ )
+ model_id = _model_info.get("id")
+
+ # Fallback: model_group from litellm_metadata
+ if model_group is None:
+ model_group = (_litellm_params.get("litellm_metadata") or {}).get(
+ "model_group"
+ ) or (_litellm_params.get("metadata") or {}).get("model_group")
+
llm_provider = _litellm_params.get("custom_llm_provider", None)
-
+
if self._should_skip_metrics_for_invalid_key(
kwargs=request_kwargs,
standard_logging_payload=standard_logging_payload,
):
return
- hashed_api_key = standard_logging_payload.get("metadata", {}).get(
+
+ # Extract context labels from all available sources (fix for None labels)
+ fallback_values = self._extract_deployment_failure_label_values(
+ request_kwargs
+ )
+ _metadata = standard_logging_payload.get("metadata", {}) or {}
+ hashed_api_key = fallback_values.get("hashed_api_key") or _metadata.get(
"user_api_key_hash"
)
+ api_key_alias = fallback_values.get("api_key_alias") or _metadata.get(
+ "user_api_key_alias"
+ )
+ team = fallback_values.get("team") or _metadata.get("user_api_key_team_id")
+ team_alias = fallback_values.get("team_alias") or _metadata.get(
+ "user_api_key_team_alias"
+ )
+ client_ip = fallback_values.get("client_ip") or _metadata.get(
+ "requester_ip_address"
+ )
+ user_agent = fallback_values.get("user_agent") or _metadata.get(
+ "user_agent"
+ )
+
+ # exception_status: prefer status_code, fallback to exception class for known types
+ exception_status = None
+ if exception is not None:
+ exception_status = str(getattr(exception, "status_code", None))
+ if exception_status == "None" or not exception_status:
+ code = getattr(exception, "code", None)
+ if code is not None:
+ exception_status = str(code)
# Create enum_values for the label factory (always create for use in different metrics)
enum_values = UserAPIKeyLabelValues(
@@ -1700,22 +1845,18 @@ class PrometheusLogger(CustomLogger):
model_id=model_id,
api_base=api_base,
api_provider=llm_provider,
- exception_status=(
- str(getattr(exception, "status_code", None)) if exception else None
- ),
+ exception_status=exception_status,
exception_class=(
self._get_exception_class_name(exception) if exception else None
),
- requested_model=model_group,
+ requested_model=model_group or litellm_model_name,
hashed_api_key=hashed_api_key,
- api_key_alias=standard_logging_payload["metadata"][
- "user_api_key_alias"
- ],
- team=standard_logging_payload["metadata"]["user_api_key_team_id"],
- team_alias=standard_logging_payload["metadata"][
- "user_api_key_team_alias"
- ],
+ api_key_alias=api_key_alias,
+ team=team,
+ team_alias=team_alias,
tags=standard_logging_payload.get("request_tags", []),
+ client_ip=client_ip,
+ user_agent=user_agent,
)
"""
@@ -1753,6 +1894,49 @@ class PrometheusLogger(CustomLogger):
)
)
+ def _set_deployment_tpm_rpm_limit_metrics(
+ self,
+ model_info: dict,
+ litellm_params: dict,
+ litellm_model_name: Optional[str],
+ model_id: Optional[str],
+ api_base: Optional[str],
+ llm_provider: Optional[str],
+ ):
+ """
+ Set the deployment TPM and RPM limits metrics
+ """
+ tpm = model_info.get("tpm") or litellm_params.get("tpm")
+ rpm = model_info.get("rpm") or litellm_params.get("rpm")
+
+ if tpm is not None:
+ _labels = prometheus_label_factory(
+ supported_enum_labels=self.get_labels_for_metric(
+ metric_name="litellm_deployment_tpm_limit"
+ ),
+ enum_values=UserAPIKeyLabelValues(
+ litellm_model_name=litellm_model_name,
+ model_id=model_id,
+ api_base=api_base,
+ api_provider=llm_provider,
+ ),
+ )
+ self.litellm_deployment_tpm_limit.labels(**_labels).set(tpm)
+
+ if rpm is not None:
+ _labels = prometheus_label_factory(
+ supported_enum_labels=self.get_labels_for_metric(
+ metric_name="litellm_deployment_rpm_limit"
+ ),
+ enum_values=UserAPIKeyLabelValues(
+ litellm_model_name=litellm_model_name,
+ model_id=model_id,
+ api_base=api_base,
+ api_provider=llm_provider,
+ ),
+ )
+ self.litellm_deployment_rpm_limit.labels(**_labels).set(rpm)
+
def set_llm_deployment_success_metrics(
self,
request_kwargs: dict,
@@ -1780,12 +1964,22 @@ class PrometheusLogger(CustomLogger):
api_base = standard_logging_payload["api_base"]
_litellm_params = request_kwargs.get("litellm_params", {}) or {}
- _metadata = _litellm_params.get("metadata", {})
+ _metadata = get_litellm_metadata_from_kwargs(request_kwargs)
litellm_model_name = request_kwargs.get("model", None)
llm_provider = _litellm_params.get("custom_llm_provider", None)
_model_info = _metadata.get("model_info") or {}
model_id = _model_info.get("id", None)
+ if _model_info or _litellm_params:
+ self._set_deployment_tpm_rpm_limit_metrics(
+ model_info=_model_info,
+ litellm_params=_litellm_params,
+ litellm_model_name=litellm_model_name,
+ model_id=model_id,
+ api_base=api_base,
+ llm_provider=llm_provider,
+ )
+
remaining_requests: Optional[int] = None
remaining_tokens: Optional[int] = None
if additional_headers := standard_logging_payload["hidden_params"][
@@ -1986,7 +2180,8 @@ class PrometheusLogger(CustomLogger):
original_model_group,
kwargs,
)
- _metadata = kwargs.get("metadata", {})
+ _metadata_key = get_metadata_variable_name_from_kwargs(kwargs)
+ _metadata = kwargs.get(_metadata_key) or {}
standard_metadata: StandardLoggingMetadata = (
StandardLoggingPayloadSetup.get_standard_logging_metadata(
metadata=_metadata
@@ -2031,7 +2226,8 @@ class PrometheusLogger(CustomLogger):
kwargs,
)
_new_model = kwargs.get("model")
- _metadata = kwargs.get("metadata", {})
+ _metadata_key = get_metadata_variable_name_from_kwargs(kwargs)
+ _metadata = kwargs.get(_metadata_key) or {}
_tags = cast(List[str], kwargs.get("tags") or [])
standard_metadata: StandardLoggingMetadata = (
StandardLoggingPayloadSetup.get_standard_logging_metadata(
@@ -2129,7 +2325,11 @@ class PrometheusLogger(CustomLogger):
increment metric when litellm.Router / load balancing logic places a deployment in cool down
"""
self.litellm_deployment_cooled_down.labels(
- litellm_model_name, model_id, api_base, api_provider, exception_status
+ _sanitize_prometheus_label_value(litellm_model_name),
+ _sanitize_prometheus_label_value(model_id),
+ _sanitize_prometheus_label_value(api_base),
+ _sanitize_prometheus_label_value(api_provider),
+ _sanitize_prometheus_label_value(exception_status),
).inc()
def increment_callback_logging_failure(
@@ -2263,7 +2463,10 @@ class PrometheusLogger(CustomLogger):
async def fetch_keys(
page_size: int, page: int
- ) -> Tuple[List[Union[str, UserAPIKeyAuth, LiteLLM_DeletedVerificationToken]], Optional[int]]:
+ ) -> Tuple[
+ List[Union[str, UserAPIKeyAuth, LiteLLM_DeletedVerificationToken]],
+ Optional[int],
+ ]:
key_list_response = await _list_key_helper(
prisma_client=prisma_client,
page=page,
@@ -2379,12 +2582,16 @@ class PrometheusLogger(CustomLogger):
# Get total user count
total_users = await prisma_client.db.litellm_usertable.count()
self.litellm_total_users_metric.set(total_users)
- verbose_logger.debug(f"Prometheus: set litellm_total_users to {total_users}")
+ verbose_logger.debug(
+ f"Prometheus: set litellm_total_users to {total_users}"
+ )
# Get total team count
total_teams = await prisma_client.db.litellm_teamtable.count()
self.litellm_teams_count_metric.set(total_teams)
- verbose_logger.debug(f"Prometheus: set litellm_teams_count to {total_teams}")
+ verbose_logger.debug(
+ f"Prometheus: set litellm_teams_count to {total_teams}"
+ )
except Exception as e:
verbose_logger.exception(
f"Error initializing user/team count metrics: {str(e)}"
@@ -2412,8 +2619,8 @@ class PrometheusLogger(CustomLogger):
self,
user_api_team: Optional[str],
user_api_team_alias: Optional[str],
- team_spend: float,
- team_max_budget: float,
+ team_spend: Optional[float],
+ team_max_budget: Optional[float],
response_cost: float,
):
"""
@@ -2575,7 +2782,7 @@ class PrometheusLogger(CustomLogger):
user_api_key: Optional[str],
user_api_key_alias: Optional[str],
response_cost: float,
- key_max_budget: float,
+ key_max_budget: Optional[float],
key_spend: Optional[float],
):
if user_api_key:
@@ -2592,7 +2799,7 @@ class PrometheusLogger(CustomLogger):
self,
user_api_key: str,
user_api_key_alias: str,
- key_max_budget: float,
+ key_max_budget: Optional[float],
key_spend: Optional[float],
response_cost: float,
) -> UserAPIKeyAuth:
@@ -2673,12 +2880,14 @@ class PrometheusLogger(CustomLogger):
max_budget=max_budget,
)
try:
+ # Note: Setting check_db_only=True bypasses cache and hits DB on every request,
+ # causing huge latency increase and CPU spikes. Keep check_db_only=False.
user_info = await get_user_object(
user_id=user_id,
prisma_client=prisma_client,
user_api_key_cache=user_api_key_cache,
user_id_upsert=False,
- check_db_only=True,
+ check_db_only=False,
)
except Exception as e:
verbose_logger.debug(
@@ -2840,9 +3049,10 @@ def prometheus_label_factory(
# Extract dictionary from Pydantic object
enum_dict = enum_values.model_dump()
- # Filter supported labels
+ # Filter supported labels and sanitize values to prevent breaking
+ # the Prometheus text format (e.g. U+2028 Line Separator in label values)
filtered_labels = {
- label: value
+ label: _sanitize_prometheus_label_value(value)
for label, value in enum_dict.items()
if label in supported_enum_labels
}
@@ -2860,14 +3070,14 @@ def prometheus_label_factory(
# check sanitized key
sanitized_key = _sanitize_prometheus_label_name(key)
if sanitized_key in supported_enum_labels:
- filtered_labels[sanitized_key] = value
+ filtered_labels[sanitized_key] = _sanitize_prometheus_label_value(value)
# Add custom tags if configured
if enum_values.tags is not None:
custom_tag_labels = get_custom_labels_from_tags(enum_values.tags)
for key, value in custom_tag_labels.items():
if key in supported_enum_labels:
- filtered_labels[key] = value
+ filtered_labels[key] = _sanitize_prometheus_label_value(value)
for label in supported_enum_labels:
if label not in filtered_labels:
diff --git a/litellm/integrations/prometheus_services.py b/litellm/integrations/prometheus_services.py
index a5f2f0b5c72..55ce758ece6 100644
--- a/litellm/integrations/prometheus_services.py
+++ b/litellm/integrations/prometheus_services.py
@@ -105,6 +105,11 @@ class PrometheusServicesLogger:
return metrics
def is_metric_registered(self, metric_name) -> bool:
+ # Use _names_to_collectors (O(1)) instead of REGISTRY.collect() (O(n)) to avoid
+ # perf regression when a new Router is created per request (e.g. router_settings in DB).
+ names_to_collectors = getattr(self.REGISTRY, "_names_to_collectors", None)
+ if names_to_collectors is not None:
+ return metric_name in names_to_collectors
for metric in self.REGISTRY.collect():
if metric_name == metric.name:
return True
diff --git a/litellm/integrations/s3_v2.py b/litellm/integrations/s3_v2.py
index 534b85e4752..eddc80dbc1f 100644
--- a/litellm/integrations/s3_v2.py
+++ b/litellm/integrations/s3_v2.py
@@ -51,6 +51,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
s3_use_team_prefix: bool = False,
s3_strip_base64_files: bool = False,
s3_use_key_prefix: bool = False,
+ s3_use_virtual_hosted_style: bool = False,
**kwargs,
):
try:
@@ -78,7 +79,8 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
s3_path=s3_path,
s3_use_team_prefix=s3_use_team_prefix,
s3_strip_base64_files=s3_strip_base64_files,
- s3_use_key_prefix=s3_use_key_prefix
+ s3_use_key_prefix=s3_use_key_prefix,
+ s3_use_virtual_hosted_style=s3_use_virtual_hosted_style
)
verbose_logger.debug(f"s3 logger using endpoint url {s3_endpoint_url}")
@@ -135,6 +137,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
s3_use_team_prefix: bool = False,
s3_strip_base64_files: bool = False,
s3_use_key_prefix: bool = False,
+ s3_use_virtual_hosted_style: bool = False,
):
"""
Initialize the s3 params for this logging callback
@@ -217,6 +220,11 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
or s3_strip_base64_files
)
+ self.s3_use_virtual_hosted_style = (
+ bool(litellm.s3_callback_params.get("s3_use_virtual_hosted_style", False))
+ or s3_use_virtual_hosted_style
+ )
+
return
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
@@ -247,8 +255,14 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
standard_logging_payload=kwargs.get("standard_logging_object", None),
)
+ # afile_delete and other non-model call types never produce a standard_logging_object,
+ # so s3_batch_logging_element is None. Skip gracefully instead of raising ValueError.
if s3_batch_logging_element is None:
- raise ValueError("s3_batch_logging_element is None")
+ verbose_logger.debug(
+ "s3 Logging - skipping event, no standard_logging_object for call_type=%s",
+ kwargs.get("call_type", "unknown"),
+ )
+ return
verbose_logger.debug(
"\ns3 Logger - Logging payload = %s", s3_batch_logging_element
@@ -302,13 +316,20 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
url = f"https://{self.s3_bucket_name}.s3.{self.s3_region_name}.amazonaws.com/{batch_logging_element.s3_object_key}"
if self.s3_endpoint_url and self.s3_bucket_name:
- url = (
- self.s3_endpoint_url
- + "/"
- + self.s3_bucket_name
- + "/"
- + batch_logging_element.s3_object_key
- )
+ if self.s3_use_virtual_hosted_style:
+ # Virtual-hosted-style: bucket.endpoint/key
+ endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "")
+ protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://"
+ url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{batch_logging_element.s3_object_key}"
+ else:
+ # Path-style: endpoint/bucket/key
+ url = (
+ self.s3_endpoint_url
+ + "/"
+ + self.s3_bucket_name
+ + "/"
+ + batch_logging_element.s3_object_key
+ )
# Convert JSON to string
json_string = safe_dumps(batch_logging_element.payload)
@@ -456,13 +477,20 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
url = f"https://{self.s3_bucket_name}.s3.{self.s3_region_name}.amazonaws.com/{batch_logging_element.s3_object_key}"
if self.s3_endpoint_url and self.s3_bucket_name:
- url = (
- self.s3_endpoint_url
- + "/"
- + self.s3_bucket_name
- + "/"
- + batch_logging_element.s3_object_key
- )
+ if self.s3_use_virtual_hosted_style:
+ # Virtual-hosted-style: bucket.endpoint/key
+ endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "")
+ protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://"
+ url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{batch_logging_element.s3_object_key}"
+ else:
+ # Path-style: endpoint/bucket/key
+ url = (
+ self.s3_endpoint_url
+ + "/"
+ + self.s3_bucket_name
+ + "/"
+ + batch_logging_element.s3_object_key
+ )
# Convert JSON to string
json_string = safe_dumps(batch_logging_element.payload)
@@ -550,13 +578,20 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
url = f"https://{self.s3_bucket_name}.s3.{self.s3_region_name}.amazonaws.com/{s3_object_key}"
if self.s3_endpoint_url and self.s3_bucket_name:
- url = (
- self.s3_endpoint_url
- + "/"
- + self.s3_bucket_name
- + "/"
- + s3_object_key
- )
+ if self.s3_use_virtual_hosted_style:
+ # Virtual-hosted-style: bucket.endpoint/key
+ endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "")
+ protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://"
+ url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{s3_object_key}"
+ else:
+ # Path-style: endpoint/bucket/key
+ url = (
+ self.s3_endpoint_url
+ + "/"
+ + self.s3_bucket_name
+ + "/"
+ + s3_object_key
+ )
# Prepare the request for GET operation
# For GET requests, we need x-amz-content-sha256 with hash of empty string
@@ -618,4 +653,4 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
verbose_logger.exception(
f"Error retrieving object {object_key} from cold storage: {str(e)}"
)
- return None
+ return None
\ No newline at end of file
diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py
index 5d36b760afb..1277cac51d7 100644
--- a/litellm/integrations/websearch_interception/handler.py
+++ b/litellm/integrations/websearch_interception/handler.py
@@ -17,6 +17,7 @@ from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.websearch_interception.tools import (
get_litellm_web_search_tool,
is_web_search_tool,
+ is_web_search_tool_chat_completion,
)
from litellm.integrations.websearch_interception.transformation import (
WebSearchTransformation,
@@ -48,7 +49,8 @@ class WebSearchInterceptionLogger(CustomLogger):
Args:
enabled_providers: List of LLM providers to enable interception for.
Use LlmProviders enum values (e.g., [LlmProviders.BEDROCK])
- Default: [LlmProviders.BEDROCK]
+ If None or empty list, enables for ALL providers.
+ Default: None (all providers enabled)
search_tool_name: Name of search tool configured in router's search_tools.
If None, will attempt to use first available search tool.
"""
@@ -183,10 +185,10 @@ class WebSearchInterceptionLogger(CustomLogger):
verbose_logger.debug(
f"WebSearchInterception: Pre-request hook called"
f" - custom_llm_provider={custom_llm_provider}"
- f" - enabled_providers={self.enabled_providers}"
+ f" - enabled_providers={self.enabled_providers or 'ALL'}"
)
- if custom_llm_provider not in self.enabled_providers:
+ if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers:
verbose_logger.debug(
f"WebSearchInterception: Skipping - provider {custom_llm_provider} not in {self.enabled_providers}"
)
@@ -245,7 +247,12 @@ class WebSearchInterceptionLogger(CustomLogger):
custom_llm_provider: str,
kwargs: Dict,
) -> Tuple[bool, Dict]:
- """Check if WebSearch tool interception is needed"""
+ """
+ Check if WebSearch tool interception is needed for Anthropic Messages API.
+
+ This is the legacy method for Anthropic-style responses.
+ For chat completions, use async_should_run_chat_completion_agentic_loop instead.
+ """
verbose_logger.debug(f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}")
verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}")
@@ -253,7 +260,7 @@ class WebSearchInterceptionLogger(CustomLogger):
# Check if provider should be intercepted
# Note: custom_llm_provider is already normalized by get_llm_provider()
# (e.g., "bedrock/invoke/..." -> "bedrock")
- if custom_llm_provider not in self.enabled_providers:
+ if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers:
verbose_logger.debug(
f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})"
)
@@ -267,10 +274,11 @@ class WebSearchInterceptionLogger(CustomLogger):
)
return False, {}
- # Detect WebSearch tool_use in response
+ # Detect WebSearch tool_use in response (Anthropic format)
should_intercept, tool_calls = WebSearchTransformation.transform_request(
response=response,
stream=stream,
+ response_format="anthropic",
)
if not should_intercept:
@@ -288,6 +296,67 @@ class WebSearchInterceptionLogger(CustomLogger):
"tool_calls": tool_calls,
"tool_type": "websearch",
"provider": custom_llm_provider,
+ "response_format": "anthropic",
+ }
+ return True, tools_dict
+
+ async def async_should_run_chat_completion_agentic_loop(
+ self,
+ response: Any,
+ model: str,
+ messages: List[Dict],
+ tools: Optional[List[Dict]],
+ stream: bool,
+ custom_llm_provider: str,
+ kwargs: Dict,
+ ) -> Tuple[bool, Dict]:
+ """
+ Check if WebSearch tool interception is needed for Chat Completions API.
+
+ Similar to async_should_run_agentic_loop but for OpenAI-style chat completions.
+ """
+
+ verbose_logger.debug(f"WebSearchInterception: Chat completion hook called! provider={custom_llm_provider}, stream={stream}")
+ verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}")
+
+ # Check if provider should be intercepted
+ if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers:
+ verbose_logger.debug(
+ f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})"
+ )
+ return False, {}
+
+ # Check if tools include any web search tool (strict check for chat completions)
+ has_websearch_tool = any(is_web_search_tool_chat_completion(t) for t in (tools or []))
+ if not has_websearch_tool:
+ verbose_logger.debug(
+ "WebSearchInterception: No litellm_web_search tool in request"
+ )
+ return False, {}
+
+ # Detect WebSearch tool_calls in response (OpenAI format)
+ should_intercept, tool_calls = WebSearchTransformation.transform_request(
+ response=response,
+ stream=stream,
+ response_format="openai",
+ )
+
+ if not should_intercept:
+ verbose_logger.debug(
+ "WebSearchInterception: No WebSearch tool_calls detected in response"
+ )
+ return False, {}
+
+ verbose_logger.debug(
+ f"WebSearchInterception: Detected {len(tool_calls)} WebSearch tool call(s), executing agentic loop"
+ )
+
+ # Return tools dict with tool calls
+ tools_dict = {
+ "tool_calls": tool_calls,
+ "tool_type": "websearch",
+ "provider": custom_llm_provider,
+ "response_format": "openai",
}
return True, tools_dict
@@ -303,7 +372,11 @@ class WebSearchInterceptionLogger(CustomLogger):
stream: bool,
kwargs: Dict,
) -> Any:
- """Execute agentic loop with WebSearch execution"""
+ """
+ Execute agentic loop with WebSearch execution for Anthropic Messages API.
+
+ This is the legacy method for Anthropic-style responses.
+ """
tool_calls = tools["tool_calls"]
@@ -321,6 +394,41 @@ class WebSearchInterceptionLogger(CustomLogger):
kwargs=kwargs,
)
+ async def async_run_chat_completion_agentic_loop(
+ self,
+ tools: Dict,
+ model: str,
+ messages: List[Dict],
+ response: Any,
+ optional_params: Dict,
+ logging_obj: Any,
+ stream: bool,
+ kwargs: Dict,
+ ) -> Any:
+ """
+ Execute agentic loop with WebSearch execution for Chat Completions API.
+
+ Similar to async_run_agentic_loop but for OpenAI-style chat completions.
+ """
+
+ tool_calls = tools["tool_calls"]
+ response_format = tools.get("response_format", "openai")
+
+ verbose_logger.debug(
+ f"WebSearchInterception: Executing chat completion agentic loop for {len(tool_calls)} search(es)"
+ )
+
+ return await self._execute_chat_completion_agentic_loop(
+ model=model,
+ messages=messages,
+ tool_calls=tool_calls,
+ optional_params=optional_params,
+ logging_obj=logging_obj,
+ stream=stream,
+ kwargs=kwargs,
+ response_format=response_format,
+ )
+
async def _execute_agentic_loop(
self,
model: str,
@@ -382,7 +490,8 @@ class WebSearchInterceptionLogger(CustomLogger):
)
# Make follow-up request with search results
- follow_up_messages = messages + [assistant_message, user_message]
+ # Type cast: user_message is a Dict for Anthropic format (default response_format)
+ follow_up_messages = messages + [assistant_message, cast(Dict, user_message)]
verbose_logger.debug(
"WebSearchInterception: Making follow-up request with search results"
@@ -521,6 +630,150 @@ class WebSearchInterceptionLogger(CustomLogger):
)
raise
+ async def _execute_chat_completion_agentic_loop( # noqa: PLR0915
+ self,
+ model: str,
+ messages: List[Dict],
+ tool_calls: List[Dict],
+ optional_params: Dict,
+ logging_obj: Any,
+ stream: bool,
+ kwargs: Dict,
+ response_format: str = "openai",
+ ) -> Any:
+ """Execute litellm.search() and make follow-up chat completion request"""
+
+ # Extract search queries from tool_calls
+ search_tasks = []
+ for tool_call in tool_calls:
+ # Handle both Anthropic-style input and OpenAI-style function.arguments
+ query = None
+ if "input" in tool_call and isinstance(tool_call["input"], dict):
+ query = tool_call["input"].get("query")
+ elif "function" in tool_call:
+ func = tool_call["function"]
+ if isinstance(func, dict):
+ args = func.get("arguments", {})
+ if isinstance(args, dict):
+ query = args.get("query")
+
+ if query:
+ verbose_logger.debug(
+ f"WebSearchInterception: Queuing search for query='{query}'"
+ )
+ search_tasks.append(self._execute_search(query))
+ else:
+ verbose_logger.warning(
+ f"WebSearchInterception: Tool call {tool_call.get('id')} has no query"
+ )
+ # Add empty result for tools without query
+ search_tasks.append(self._create_empty_search_result())
+
+ # Execute searches in parallel
+ verbose_logger.debug(
+ f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel"
+ )
+ search_results = await asyncio.gather(*search_tasks, return_exceptions=True)
+
+ # Handle any exceptions in search results
+ final_search_results: List[str] = []
+ for i, result in enumerate(search_results):
+ if isinstance(result, Exception):
+ verbose_logger.error(
+ f"WebSearchInterception: Search {i} failed with error: {str(result)}"
+ )
+ final_search_results.append(
+ f"Search failed: {str(result)}"
+ )
+ elif isinstance(result, str):
+ final_search_results.append(cast(str, result))
+ else:
+ verbose_logger.warning(
+ f"WebSearchInterception: Unexpected result type {type(result)} at index {i}"
+ )
+ final_search_results.append(str(result))
+
+ # Build assistant and tool messages using transformation
+ assistant_message, tool_messages_or_user = WebSearchTransformation.transform_response(
+ tool_calls=tool_calls,
+ search_results=final_search_results,
+ response_format=response_format,
+ )
+
+ # Make follow-up request with search results
+ # For OpenAI format, tool_messages_or_user is a list of tool messages
+ if response_format == "openai":
+ follow_up_messages = messages + [assistant_message] + cast(List[Dict], tool_messages_or_user)
+ else:
+ # For Anthropic format (shouldn't happen in this method, but handle it)
+ follow_up_messages = messages + [assistant_message, cast(Dict, tool_messages_or_user)]
+
+ verbose_logger.debug(
+ "WebSearchInterception: Making follow-up chat completion request with search results"
+ )
+ verbose_logger.debug(
+ f"WebSearchInterception: Follow-up messages count: {len(follow_up_messages)}"
+ )
+
+ # Use litellm.acompletion for follow-up request
+ try:
+ # Remove internal parameters that shouldn't be passed to follow-up request
+ internal_params = {
+ '_websearch_interception',
+ 'acompletion',
+ 'litellm_logging_obj',
+ 'custom_llm_provider',
+ 'model_alias_map',
+ 'stream_response',
+ 'custom_prompt_dict',
+ }
+ kwargs_for_followup = {
+ k: v for k, v in kwargs.items()
+ if not k.startswith('_websearch_interception') and k not in internal_params
+ }
+
+ # Get full model name from kwargs
+ full_model_name = model
+ if "custom_llm_provider" in kwargs:
+ custom_llm_provider = kwargs["custom_llm_provider"]
+ # Reconstruct full model name with provider prefix if needed
+ if not model.startswith(custom_llm_provider):
+ # Check if model already has a provider prefix
+ if "/" not in model:
+ full_model_name = f"{custom_llm_provider}/{model}"
+
+ verbose_logger.debug(
+ f"WebSearchInterception: Using model name: {full_model_name}"
+ )
+
+ # Prepare tools for follow-up request (same as original)
+ tools_param = optional_params.get("tools")
+
+ # Remove tools and extra_body from optional_params to avoid issues
+ # extra_body often contains internal LiteLLM params that shouldn't be forwarded
+ optional_params_clean = {
+ k: v for k, v in optional_params.items()
+ if k not in {"tools", "extra_body", "model_alias_map","stream_response", "custom_prompt_dict" }
+ }
+
+ final_response = await litellm.acompletion(
+ model=full_model_name,
+ messages=follow_up_messages,
+ tools=tools_param,
+ **optional_params_clean,
+ **kwargs_for_followup,
+ )
+
+ verbose_logger.debug(
+ f"WebSearchInterception: Follow-up request completed, response type: {type(final_response)}"
+ )
+ return final_response
+ except Exception as e:
+ verbose_logger.exception(
+ f"WebSearchInterception: Follow-up request failed: {str(e)}"
+ )
+ raise
+
async def _create_empty_search_result(self) -> str:
"""Create an empty search result for tool calls without queries"""
return "No search query provided"
diff --git a/litellm/integrations/websearch_interception/tools.py b/litellm/integrations/websearch_interception/tools.py
index 4f8b7372fe3..c39d150fb19 100644
--- a/litellm/integrations/websearch_interception/tools.py
+++ b/litellm/integrations/websearch_interception/tools.py
@@ -49,12 +49,57 @@ def get_litellm_web_search_tool() -> Dict[str, Any]:
}
+def is_web_search_tool_chat_completion(tool: Dict[str, Any]) -> bool:
+ """
+ Check if a tool is a web search tool for Chat Completions API (strict check).
+
+ This is a stricter version that ONLY checks for the exact LiteLLM web search tool name.
+ Use this for Chat Completions API to avoid false positives with user-defined tools.
+
+ Detects ONLY:
+ - LiteLLM standard: name == "litellm_web_search" (Anthropic format)
+ - OpenAI format: type == "function" with function.name == "litellm_web_search"
+
+ Args:
+ tool: Tool dictionary to check
+
+ Returns:
+ True if tool is exactly the LiteLLM web search tool
+
+ Example:
+ >>> is_web_search_tool_chat_completion({"name": "litellm_web_search"})
+ True
+ >>> is_web_search_tool_chat_completion({"type": "function", "function": {"name": "litellm_web_search"}})
+ True
+ >>> is_web_search_tool_chat_completion({"name": "web_search"})
+ False
+ >>> is_web_search_tool_chat_completion({"name": "WebSearch"})
+ False
+ """
+ tool_name = tool.get("name", "")
+ tool_type = tool.get("type", "")
+
+ # Check for OpenAI format: {"type": "function", "function": {"name": "litellm_web_search"}}
+ if tool_type == "function" and "function" in tool:
+ function_def = tool.get("function", {})
+ function_name = function_def.get("name", "")
+ if function_name == LITELLM_WEB_SEARCH_TOOL_NAME:
+ return True
+
+ # Check for LiteLLM standard tool (Anthropic format)
+ if tool_name == LITELLM_WEB_SEARCH_TOOL_NAME:
+ return True
+
+ return False
+
+
def is_web_search_tool(tool: Dict[str, Any]) -> bool:
"""
Check if a tool is a web search tool (native or LiteLLM standard).
Detects:
- LiteLLM standard: name == "litellm_web_search"
+ - OpenAI format: type == "function" with function.name == "litellm_web_search"
- Anthropic native: type starts with "web_search_" (e.g., "web_search_20250305")
- Claude Code: name == "web_search" with a type field
- Custom: name == "WebSearch" (legacy format)
@@ -68,6 +113,8 @@ def is_web_search_tool(tool: Dict[str, Any]) -> bool:
Example:
>>> is_web_search_tool({"name": "litellm_web_search"})
True
+ >>> is_web_search_tool({"type": "function", "function": {"name": "litellm_web_search"}})
+ True
>>> is_web_search_tool({"type": "web_search_20250305", "name": "web_search"})
True
>>> is_web_search_tool({"name": "calculator"})
@@ -75,8 +122,15 @@ def is_web_search_tool(tool: Dict[str, Any]) -> bool:
"""
tool_name = tool.get("name", "")
tool_type = tool.get("type", "")
+
+ # Check for OpenAI format: {"type": "function", "function": {"name": "..."}}
+ if tool_type == "function" and "function" in tool:
+ function_def = tool.get("function", {})
+ function_name = function_def.get("name", "")
+ if function_name == LITELLM_WEB_SEARCH_TOOL_NAME:
+ return True
- # Check for LiteLLM standard tool
+ # Check for LiteLLM standard tool (Anthropic format)
if tool_name == LITELLM_WEB_SEARCH_TOOL_NAME:
return True
diff --git a/litellm/integrations/websearch_interception/transformation.py b/litellm/integrations/websearch_interception/transformation.py
index 313358822a5..e44ec35c3a2 100644
--- a/litellm/integrations/websearch_interception/transformation.py
+++ b/litellm/integrations/websearch_interception/transformation.py
@@ -1,10 +1,10 @@
"""
WebSearch Tool Transformation
-Transforms between Anthropic tool_use format and LiteLLM search format.
+Transforms between Anthropic/OpenAI tool_use format and LiteLLM search format.
"""
-
-from typing import Any, Dict, List, Tuple
+import json
+from typing import Any, Dict, List, Tuple, Union
from litellm._logging import verbose_logger
from litellm.constants import LITELLM_WEB_SEARCH_TOOL_NAME
@@ -17,28 +17,31 @@ class WebSearchTransformation:
Handles transformation between:
- Anthropic tool_use format → LiteLLM search requests
- - LiteLLM SearchResponse → Anthropic tool_result format
+ - OpenAI tool_calls format → LiteLLM search requests
+ - LiteLLM SearchResponse → Anthropic/OpenAI tool_result format
"""
@staticmethod
def transform_request(
response: Any,
stream: bool,
+ response_format: str = "anthropic",
) -> Tuple[bool, List[Dict]]:
"""
- Transform Anthropic response to extract WebSearch tool calls.
+ Transform model response to extract WebSearch tool calls.
- Detects if response contains WebSearch tool_use blocks and extracts
+ Detects if response contains WebSearch tool_use/tool_calls blocks and extracts
the search queries for execution.
Args:
- response: Model response (dict or AnthropicMessagesResponse)
+ response: Model response (dict, AnthropicMessagesResponse, or ModelResponse)
stream: Whether response is streaming
+ response_format: Response format - "anthropic" or "openai" (default: "anthropic")
Returns:
(has_websearch, tool_calls):
has_websearch: True if WebSearch tool_use found
- tool_calls: List of tool_use dicts with id, name, input
+ tool_calls: List of tool_use/tool_calls dicts with id, name, input/function
Note:
Streaming requests are handled by converting stream=True to stream=False
@@ -54,8 +57,11 @@ class WebSearchTransformation:
)
return False, []
- # Parse non-streaming response
- return WebSearchTransformation._detect_from_non_streaming_response(response)
+ # Parse non-streaming response based on format
+ if response_format == "openai":
+ return WebSearchTransformation._detect_from_openai_response(response)
+ else:
+ return WebSearchTransformation._detect_from_non_streaming_response(response)
@staticmethod
def _detect_from_non_streaming_response(
@@ -114,26 +120,142 @@ class WebSearchTransformation:
return len(tool_calls) > 0, tool_calls
+ @staticmethod
+ def _detect_from_openai_response(
+ response: Any,
+ ) -> Tuple[bool, List[Dict]]:
+ """Parse OpenAI-style response for WebSearch tool_calls"""
+
+ # Handle both dict and ModelResponse objects
+ if isinstance(response, dict):
+ choices = response.get("choices", [])
+ else:
+ if not hasattr(response, "choices"):
+ verbose_logger.debug(
+ "WebSearchInterception: Response has no choices attribute"
+ )
+ return False, []
+ choices = response.choices or []
+
+ if not choices:
+ verbose_logger.debug(
+ "WebSearchInterception: Response has empty choices"
+ )
+ return False, []
+
+ # Get first choice's message
+ first_choice = choices[0]
+ if isinstance(first_choice, dict):
+ message = first_choice.get("message", {})
+ else:
+ message = getattr(first_choice, "message", None)
+
+ if not message:
+ verbose_logger.debug(
+ "WebSearchInterception: First choice has no message"
+ )
+ return False, []
+
+ # Get tool_calls from message
+ if isinstance(message, dict):
+ openai_tool_calls = message.get("tool_calls", [])
+ else:
+ openai_tool_calls = getattr(message, "tool_calls", None) or []
+
+ if not openai_tool_calls:
+ verbose_logger.debug(
+ "WebSearchInterception: Message has no tool_calls"
+ )
+ return False, []
+
+ # Find all WebSearch tool calls
+ tool_calls = []
+ for tool_call in openai_tool_calls:
+ # Handle both dict and object tool calls
+ if isinstance(tool_call, dict):
+ tool_id = tool_call.get("id")
+ tool_type = tool_call.get("type")
+ function = tool_call.get("function", {})
+ function_name = function.get("name") if isinstance(function, dict) else getattr(function, "name", None)
+ function_arguments = function.get("arguments") if isinstance(function, dict) else getattr(function, "arguments", None)
+ else:
+ tool_id = getattr(tool_call, "id", None)
+ tool_type = getattr(tool_call, "type", None)
+ function = getattr(tool_call, "function", None)
+ function_name = getattr(function, "name", None) if function else None
+ function_arguments = getattr(function, "arguments", None) if function else None
+
+ # Check for LiteLLM standard or legacy web search tools
+ if tool_type == "function" and function_name in (
+ LITELLM_WEB_SEARCH_TOOL_NAME, "WebSearch", "web_search"
+ ):
+ # Parse arguments (might be JSON string)
+ if isinstance(function_arguments, str):
+ try:
+ arguments = json.loads(function_arguments)
+ except json.JSONDecodeError:
+ verbose_logger.warning(
+ f"WebSearchInterception: Failed to parse function arguments: {function_arguments}"
+ )
+ arguments = {}
+ else:
+ arguments = function_arguments or {}
+
+ # Convert to internal format (similar to Anthropic)
+ tool_call_dict = {
+ "id": tool_id,
+ "type": "function",
+ "name": function_name,
+ "function": {
+ "name": function_name,
+ "arguments": arguments,
+ },
+ "input": arguments, # For compatibility with Anthropic format
+ }
+ tool_calls.append(tool_call_dict)
+ verbose_logger.debug(
+ f"WebSearchInterception: Found {function_name} tool_call with id={tool_id}"
+ )
+
+ return len(tool_calls) > 0, tool_calls
+
@staticmethod
def transform_response(
tool_calls: List[Dict],
search_results: List[str],
- ) -> Tuple[Dict, Dict]:
+ response_format: str = "anthropic",
+ ) -> Tuple[Dict, Union[Dict, List[Dict]]]:
"""
- Transform LiteLLM search results to Anthropic tool_result format.
+ Transform LiteLLM search results to Anthropic/OpenAI tool_result format.
- Builds the assistant and user messages needed for the agentic loop
+ Builds the assistant and user/tool messages needed for the agentic loop
follow-up request.
Args:
- tool_calls: List of tool_use dicts from transform_request
+ tool_calls: List of tool_use/tool_calls dicts from transform_request
search_results: List of search result strings (one per tool_call)
+ response_format: Response format - "anthropic" or "openai" (default: "anthropic")
Returns:
- (assistant_message, user_message):
- assistant_message: Message with tool_use blocks
- user_message: Message with tool_result blocks
+ (assistant_message, user_or_tool_messages):
+ For Anthropic: assistant_message with tool_use blocks, user_message with tool_result blocks
+ For OpenAI: assistant_message with tool_calls, tool_messages list with tool results
"""
+ if response_format == "openai":
+ return WebSearchTransformation._transform_response_openai(
+ tool_calls, search_results
+ )
+ else:
+ return WebSearchTransformation._transform_response_anthropic(
+ tool_calls, search_results
+ )
+
+ @staticmethod
+ def _transform_response_anthropic(
+ tool_calls: List[Dict],
+ search_results: List[str],
+ ) -> Tuple[Dict, Dict]:
+ """Transform to Anthropic format (single user message with tool_result blocks)"""
# Build assistant message with tool_use blocks
assistant_message = {
"role": "assistant",
@@ -163,6 +285,40 @@ class WebSearchTransformation:
return assistant_message, user_message
+ @staticmethod
+ def _transform_response_openai(
+ tool_calls: List[Dict],
+ search_results: List[str],
+ ) -> Tuple[Dict, List[Dict]]:
+ """Transform to OpenAI format (assistant with tool_calls, separate tool messages)"""
+ # Build assistant message with tool_calls
+ assistant_message = {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": tc["id"],
+ "type": "function",
+ "function": {
+ "name": tc["name"],
+ "arguments": json.dumps(tc["input"]) if isinstance(tc["input"], dict) else str(tc["input"]),
+ },
+ }
+ for tc in tool_calls
+ ],
+ }
+
+ # Build separate tool messages (one per tool call)
+ tool_messages = [
+ {
+ "role": "tool",
+ "tool_call_id": tool_calls[i]["id"],
+ "content": search_results[i],
+ }
+ for i in range(len(tool_calls))
+ ]
+
+ return assistant_message, tool_messages
+
@staticmethod
def format_search_response(result: SearchResponse) -> str:
"""
diff --git a/litellm/litellm_core_utils/api_route_to_call_types.py b/litellm/litellm_core_utils/api_route_to_call_types.py
index 4146ff6d6a6..2ae9986ce94 100644
--- a/litellm/litellm_core_utils/api_route_to_call_types.py
+++ b/litellm/litellm_core_utils/api_route_to_call_types.py
@@ -3,6 +3,9 @@ Dictionary mapping API routes to their corresponding CallTypes in LiteLLM.
This dictionary maps each API endpoint to the CallTypes that can be used for that route.
Each route can have both async (prefixed with 'a') and sync call types.
+
+Route patterns may contain placeholders like {agent_id}, {model}, {batch_id}; these
+match a single path segment when resolving call types for a concrete path.
"""
from typing import List, Optional
@@ -10,17 +13,43 @@ from typing import List, Optional
from litellm.types.utils import API_ROUTE_TO_CALL_TYPES, CallTypes
+def _route_matches_pattern(route: str, pattern: str) -> bool:
+ """
+ Return True if the concrete route matches the pattern.
+ Pattern segments like {param} match any single path segment.
+ """
+ route_parts = route.strip("/").split("/")
+ pattern_parts = pattern.strip("/").split("/")
+ if len(route_parts) != len(pattern_parts):
+ return False
+ for r, p in zip(route_parts, pattern_parts):
+ if p.startswith("{") and p.endswith("}"):
+ continue
+ if r != p:
+ return False
+ return True
+
+
def get_call_types_for_route(route: str) -> Optional[List[CallTypes]]:
"""
Get the list of CallTypes for a given API route.
+ Supports both exact keys and dynamic patterns (e.g. /a2a/my-agent/message/send
+ matches /a2a/{agent_id}/message/send).
+
Args:
- route: API route path (e.g., "/chat/completions")
+ route: API route path (e.g., "/chat/completions" or "/a2a/my-pydantic-agent/message/send")
Returns:
List of CallTypes for that route, or None if route not found
"""
- return API_ROUTE_TO_CALL_TYPES.get(route, None)
+ exact = API_ROUTE_TO_CALL_TYPES.get(route, None)
+ if exact is not None:
+ return exact
+ for pattern, call_types in API_ROUTE_TO_CALL_TYPES.items():
+ if _route_matches_pattern(route, pattern):
+ return call_types
+ return None
def get_routes_for_call_type(call_type: CallTypes) -> list:
diff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.py
index 9cb0a00d9fc..7c8e2ebeaff 100644
--- a/litellm/litellm_core_utils/core_helpers.py
+++ b/litellm/litellm_core_utils/core_helpers.py
@@ -94,8 +94,8 @@ def map_finish_reason(
return "length"
elif finish_reason == "tool_use": # anthropic
return "tool_calls"
- elif finish_reason == "content_filtered":
- return "content_filter"
+ elif finish_reason == "compaction":
+ return "length"
return finish_reason
@@ -351,9 +351,9 @@ def filter_exceptions_from_params(data: Any, max_depth: int = 20) -> Any:
# Skip callable objects (functions, methods, lambdas) but not classes (type objects)
if callable(data) and not isinstance(data, type):
return None
- # Skip known non-serializable object types (Logging, etc.)
+ # Skip known non-serializable object types (Logging, Router, etc.)
obj_type_name = type(data).__name__
- if obj_type_name in ["Logging", "LiteLLMLoggingObj"]:
+ if obj_type_name in ["Logging", "LiteLLMLoggingObj", "Router"]:
return None
if isinstance(data, dict):
diff --git a/litellm/litellm_core_utils/env_utils.py b/litellm/litellm_core_utils/env_utils.py
new file mode 100644
index 00000000000..34c65275331
--- /dev/null
+++ b/litellm/litellm_core_utils/env_utils.py
@@ -0,0 +1,21 @@
+"""
+Utility helpers for reading and parsing environment variables.
+"""
+
+import os
+
+
+def get_env_int(env_var: str, default: int) -> int:
+ """Parse an environment variable as an integer, falling back to default on invalid values.
+
+ Handles empty strings, whitespace, and non-numeric values gracefully
+ so that misconfiguration doesn't crash the process at import time.
+ """
+ raw = os.getenv(env_var)
+ if raw is None:
+ return default
+ raw = raw.strip()
+ try:
+ return int(raw)
+ except (ValueError, TypeError):
+ return default
diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py
index 3ddcae69315..dde44cced36 100644
--- a/litellm/litellm_core_utils/exception_mapping_utils.py
+++ b/litellm/litellm_core_utils/exception_mapping_utils.py
@@ -70,6 +70,11 @@ class ExceptionCheckers:
Check if an error string indicates a context window exceeded error.
"""
_error_str_lowercase = error_str.lower()
+ # Exclude param validation errors (e.g. OpenAI "user" param max 64 chars)
+ if "string_above_max_length" in _error_str_lowercase:
+ return False
+ if "invalid 'user'" in _error_str_lowercase and "string too long" in _error_str_lowercase:
+ return False
known_exception_substrings = [
"exceed context limit",
"this model's maximum context length is",
@@ -98,16 +103,18 @@ class ExceptionCheckers:
"""
Check if an error string indicates a content policy violation error.
"""
+ _lower = error_str.lower()
known_exception_substrings = [
- "invalid_request_error",
"content_policy_violation",
+ "responsibleaipolicyviolation",
"the response was filtered due to the prompt triggering azure openai's content management",
"your task failed as a result of our safety system",
"the model produced invalid content",
"content_filter_policy",
+ "your request was rejected as a result of our safety system",
]
for substring in known_exception_substrings:
- if substring in error_str.lower():
+ if substring in _lower:
return True
return False
@@ -2060,6 +2067,19 @@ def exception_type( # type: ignore # noqa: PLR0915
if isinstance(body_dict, dict):
if isinstance(body_dict.get("error"), dict):
azure_error_code = body_dict["error"].get("code") # type: ignore[index]
+ # Also check inner_error for
+ # ResponsibleAIPolicyViolation which indicates a
+ # content policy violation even when the top-level
+ # code is generic (e.g. "invalid_request_error").
+ if azure_error_code != "content_policy_violation":
+ _inner = (
+ body_dict["error"].get("inner_error") # type: ignore[index]
+ or body_dict["error"].get("innererror") # type: ignore[index]
+ )
+ if isinstance(_inner, dict) and _inner.get(
+ "code"
+ ) == "ResponsibleAIPolicyViolation":
+ azure_error_code = "content_policy_violation"
else:
azure_error_code = body_dict.get("code")
except Exception:
diff --git a/litellm/litellm_core_utils/get_litellm_params.py b/litellm/litellm_core_utils/get_litellm_params.py
index e290101f8bf..36a8dfdb5a6 100644
--- a/litellm/litellm_core_utils/get_litellm_params.py
+++ b/litellm/litellm_core_utils/get_litellm_params.py
@@ -1,19 +1,48 @@
from typing import Optional
+# Pre-define optional kwargs keys as frozenset for O(1) lookups
+# These are extracted from kwargs only if present, avoiding unnecessary .get() calls
+_OPTIONAL_KWARGS_KEYS = frozenset({
+ "azure_ad_token",
+ "tenant_id",
+ "client_id",
+ "client_secret",
+ "azure_username",
+ "azure_password",
+ "azure_scope",
+ "timeout",
+ "bucket_name",
+ "vertex_credentials",
+ "vertex_project",
+ "vertex_location",
+ "vertex_ai_project",
+ "vertex_ai_location",
+ "vertex_ai_credentials",
+ "aws_region_name",
+ "aws_access_key_id",
+ "aws_secret_access_key",
+ "aws_session_token",
+ "aws_session_name",
+ "aws_profile_name",
+ "aws_role_name",
+ "aws_web_identity_token",
+ "aws_sts_endpoint",
+ "aws_external_id",
+ "aws_bedrock_runtime_endpoint",
+ "tpm",
+ "rpm",
+})
+
+
def _get_base_model_from_litellm_call_metadata(
metadata: Optional[dict],
) -> Optional[str]:
if metadata is None:
return None
-
- if metadata is not None:
- model_info = metadata.get("model_info", {})
-
- if model_info is not None:
- base_model = model_info.get("base_model", None)
- if base_model is not None:
- return base_model
+ model_info = metadata.get("model_info")
+ if model_info:
+ return model_info.get("base_model")
return None
@@ -66,6 +95,7 @@ def get_litellm_params(
litellm_request_debug: Optional[bool] = None,
**kwargs,
) -> dict:
+ # Build base dict with explicit parameters (always included)
litellm_params = {
"acompletion": acompletion,
"api_key": api_key,
@@ -93,8 +123,11 @@ def get_litellm_params(
"text_completion": text_completion,
"azure_ad_token_provider": azure_ad_token_provider,
"user_continue_message": user_continue_message,
- "base_model": base_model or (
- _get_base_model_from_litellm_call_metadata(metadata=metadata) if metadata else None
+ "base_model": base_model
+ or (
+ _get_base_model_from_litellm_call_metadata(metadata=metadata)
+ if metadata
+ else None
),
"litellm_trace_id": litellm_trace_id,
"litellm_session_id": litellm_session_id,
@@ -109,35 +142,15 @@ def get_litellm_params(
"ssl_verify": ssl_verify,
"merge_reasoning_content_in_choices": merge_reasoning_content_in_choices,
"api_version": api_version,
- "azure_ad_token": kwargs.get("azure_ad_token"),
- "tenant_id": kwargs.get("tenant_id"),
- "client_id": kwargs.get("client_id"),
- "client_secret": kwargs.get("client_secret"),
- "azure_username": kwargs.get("azure_username"),
- "azure_password": kwargs.get("azure_password"),
- "azure_scope": kwargs.get("azure_scope"),
"max_retries": max_retries,
- "timeout": kwargs.get("timeout"),
- "bucket_name": kwargs.get("bucket_name"),
- "vertex_credentials": kwargs.get("vertex_credentials"),
- "vertex_project": kwargs.get("vertex_project"),
- "vertex_location": kwargs.get("vertex_location"),
- "vertex_ai_project": kwargs.get("vertex_ai_project"),
- "vertex_ai_location": kwargs.get("vertex_ai_location"),
- "vertex_ai_credentials": kwargs.get("vertex_ai_credentials"),
"use_litellm_proxy": use_litellm_proxy,
"litellm_request_debug": litellm_request_debug,
- "aws_region_name": kwargs.get("aws_region_name"),
- # AWS credentials for Bedrock/Sagemaker
- "aws_access_key_id": kwargs.get("aws_access_key_id"),
- "aws_secret_access_key": kwargs.get("aws_secret_access_key"),
- "aws_session_token": kwargs.get("aws_session_token"),
- "aws_session_name": kwargs.get("aws_session_name"),
- "aws_profile_name": kwargs.get("aws_profile_name"),
- "aws_role_name": kwargs.get("aws_role_name"),
- "aws_web_identity_token": kwargs.get("aws_web_identity_token"),
- "aws_sts_endpoint": kwargs.get("aws_sts_endpoint"),
- "aws_external_id": kwargs.get("aws_external_id"),
- "aws_bedrock_runtime_endpoint": kwargs.get("aws_bedrock_runtime_endpoint"),
}
+
+ # Sparse extraction: only add kwargs keys that are actually present
+ if kwargs:
+ for key in _OPTIONAL_KWARGS_KEYS:
+ if key in kwargs:
+ litellm_params[key] = kwargs[key]
+
return litellm_params
diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py
index 718773a1b16..8ab4ec15b07 100644
--- a/litellm/litellm_core_utils/get_llm_provider_logic.py
+++ b/litellm/litellm_core_utils/get_llm_provider_logic.py
@@ -51,7 +51,7 @@ def handle_cohere_chat_model_custom_llm_provider(
if custom_llm_provider == "cohere" and model in litellm.cohere_chat_models:
return model, "cohere_chat"
- if "/" in model:
+ if model and "/" in model:
_custom_llm_provider, _model = model.split("/", 1)
if (
_custom_llm_provider
@@ -84,7 +84,7 @@ def handle_anthropic_text_model_custom_llm_provider(
):
return model, "anthropic_text"
- if "/" in model:
+ if model and "/" in model:
_custom_llm_provider, _model = model.split("/", 1)
if (
_custom_llm_provider
@@ -113,6 +113,12 @@ def get_llm_provider( # noqa: PLR0915
Return model, custom_llm_provider, dynamic_api_key, api_base
"""
try:
+ # Early validation - model is required
+ if model is None:
+ raise ValueError(
+ "model parameter is required but was None. Please provide a valid model name."
+ )
+
if litellm.LiteLLMProxyChatConfig._should_use_litellm_proxy_by_default(
litellm_params=litellm_params
):
diff --git a/litellm/litellm_core_utils/get_model_cost_map.py b/litellm/litellm_core_utils/get_model_cost_map.py
index 9b86f4ca2f0..e622a317454 100644
--- a/litellm/litellm_core_utils/get_model_cost_map.py
+++ b/litellm/litellm_core_utils/get_model_cost_map.py
@@ -8,40 +8,187 @@ export LITELLM_LOCAL_MODEL_COST_MAP=True
```
"""
+import json
import os
+from importlib.resources import files
import httpx
+from litellm import verbose_logger
+from litellm.constants import (
+ MODEL_COST_MAP_MAX_SHRINK_RATIO,
+ MODEL_COST_MAP_MIN_MODEL_COUNT,
+)
+
+
+class GetModelCostMap:
+ """
+ Handles fetching, validating, and loading the model cost map.
+
+ Only the backup model *count* is cached (a single int). The full
+ backup dict is never held in memory — it is only parsed when it
+ needs to be *returned* as a fallback.
+ """
+
+ _backup_model_count: int = -1 # -1 = not yet loaded
+
+ @staticmethod
+ def load_local_model_cost_map() -> dict:
+ """Load the local backup model cost map bundled with the package."""
+ content = json.loads(
+ files("litellm")
+ .joinpath("model_prices_and_context_window_backup.json")
+ .read_text(encoding="utf-8")
+ )
+ return content
+
+ @classmethod
+ def _get_backup_model_count(cls) -> int:
+ """Return the number of models in the local backup (cached int)."""
+ if cls._backup_model_count < 0:
+ backup = cls.load_local_model_cost_map()
+ cls._backup_model_count = len(backup)
+ return cls._backup_model_count
+
+ @staticmethod
+ def _check_is_valid_dict(fetched_map: dict) -> bool:
+ """Check 1: fetched map is a non-empty dict."""
+ if not isinstance(fetched_map, dict):
+ verbose_logger.warning(
+ "LiteLLM: Fetched model cost map is not a dict (type=%s). "
+ "Falling back to local backup.",
+ type(fetched_map).__name__,
+ )
+ return False
+
+ if len(fetched_map) == 0:
+ verbose_logger.warning(
+ "LiteLLM: Fetched model cost map is empty. "
+ "Falling back to local backup.",
+ )
+ return False
+
+ return True
+
+ @classmethod
+ def _check_model_count_not_reduced(
+ cls,
+ fetched_map: dict,
+ backup_model_count: int,
+ min_model_count: int = MODEL_COST_MAP_MIN_MODEL_COUNT,
+ max_shrink_ratio: float = MODEL_COST_MAP_MAX_SHRINK_RATIO,
+ ) -> bool:
+ """Check 2: model count has not reduced significantly vs backup."""
+ fetched_count = len(fetched_map)
+
+ if fetched_count < min_model_count:
+ verbose_logger.warning(
+ "LiteLLM: Fetched model cost map has only %d models (minimum=%d). "
+ "This may indicate a corrupted upstream file. "
+ "Falling back to local backup.",
+ fetched_count,
+ min_model_count,
+ )
+ return False
+
+ if backup_model_count > 0 and fetched_count < backup_model_count * max_shrink_ratio:
+ verbose_logger.warning(
+ "LiteLLM: Fetched model cost map shrank significantly "
+ "(fetched=%d, backup=%d, threshold=%.0f%%). "
+ "This may indicate a corrupted upstream file. "
+ "Falling back to local backup.",
+ fetched_count,
+ backup_model_count,
+ max_shrink_ratio * 100,
+ )
+ return False
+
+ return True
+
+ @classmethod
+ def validate_model_cost_map(
+ cls,
+ fetched_map: dict,
+ backup_model_count: int,
+ min_model_count: int = MODEL_COST_MAP_MIN_MODEL_COUNT,
+ max_shrink_ratio: float = MODEL_COST_MAP_MAX_SHRINK_RATIO,
+ ) -> bool:
+ """
+ Validate the integrity of a fetched model cost map.
+
+ Runs each check in order and returns False on the first failure.
+
+ Checks:
+ 1. ``_check_is_valid_dict`` -- fetched map is a non-empty dict.
+ 2. ``_check_model_count_not_reduced`` -- model count meets minimum
+ and has not shrunk >``max_shrink_ratio`` vs backup.
+
+ Returns True if all checks pass, False otherwise.
+ """
+ if not cls._check_is_valid_dict(fetched_map):
+ return False
+
+ if not cls._check_model_count_not_reduced(
+ fetched_map=fetched_map,
+ backup_model_count=backup_model_count,
+ min_model_count=min_model_count,
+ max_shrink_ratio=max_shrink_ratio,
+ ):
+ return False
+
+ return True
+
+ @staticmethod
+ def fetch_remote_model_cost_map(url: str, timeout: int = 5) -> dict:
+ """
+ Fetch the model cost map from a remote URL.
+
+ Returns the parsed JSON dict. Raises on network/parse errors
+ (caller is expected to handle).
+ """
+ response = httpx.get(url, timeout=timeout)
+ response.raise_for_status()
+ return response.json()
+
def get_model_cost_map(url: str) -> dict:
- if (
- os.getenv("LITELLM_LOCAL_MODEL_COST_MAP", False)
- or os.getenv("LITELLM_LOCAL_MODEL_COST_MAP", False) == "True"
- ):
- from importlib.resources import files
- import json
+ """
+ Public entry point — returns the model cost map dict.
- content = json.loads(
- files("litellm")
- .joinpath("model_prices_and_context_window_backup.json")
- .read_text(encoding="utf-8")
- )
- return content
+ 1. If ``LITELLM_LOCAL_MODEL_COST_MAP`` is set, uses the local backup only.
+ 2. Otherwise fetches from ``url``, validates integrity, and falls back
+ to the local backup on any failure.
+
+ Only the backup model count is cached (a single int) for validation.
+ The full backup dict is only parsed when it must be *returned* as a
+ fallback — it is never held in memory long-term.
+ """
+ # Note: can't use get_secret_bool here — this runs during litellm.__init__
+ # before litellm._key_management_settings is set.
+ if os.getenv("LITELLM_LOCAL_MODEL_COST_MAP", "").lower() == "true":
+ return GetModelCostMap.load_local_model_cost_map()
try:
- response = httpx.get(
- url, timeout=5
- ) # set a 5 second timeout for the get request
- response.raise_for_status() # Raise an exception if the request is unsuccessful
- content = response.json()
- return content
- except Exception:
- from importlib.resources import files
- import json
-
- content = json.loads(
- files("litellm")
- .joinpath("model_prices_and_context_window_backup.json")
- .read_text(encoding="utf-8")
+ content = GetModelCostMap.fetch_remote_model_cost_map(url)
+ except Exception as e:
+ verbose_logger.warning(
+ "LiteLLM: Failed to fetch remote model cost map from %s: %s. "
+ "Falling back to local backup.",
+ url,
+ str(e),
)
- return content
+ return GetModelCostMap.load_local_model_cost_map()
+
+ # Validate using cached count (cheap int comparison, no file I/O)
+ if not GetModelCostMap.validate_model_cost_map(
+ fetched_map=content,
+ backup_model_count=GetModelCostMap._get_backup_model_count(),
+ ):
+ verbose_logger.warning(
+ "LiteLLM: Fetched model cost map failed integrity check. "
+ "Using local backup instead. url=%s",
+ url,
+ )
+ return GetModelCostMap.load_local_model_cost_map()
+
+ return content
diff --git a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py
index c425319b4d4..ff521d47804 100644
--- a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py
+++ b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py
@@ -1,8 +1,35 @@
from typing import Dict, Optional
-
from litellm.secret_managers.main import get_secret_str
from litellm.types.utils import StandardCallbackDynamicParams
+# Hardcoded list of supported callback params to avoid runtime inspection issues with TypedDict
+_supported_callback_params = [
+ "langfuse_public_key",
+ "langfuse_secret",
+ "langfuse_secret_key",
+ "langfuse_host",
+ "langfuse_prompt_version",
+ "gcs_bucket_name",
+ "gcs_path_service_account",
+ "langsmith_api_key",
+ "langsmith_project",
+ "langsmith_base_url",
+ "langsmith_sampling_rate",
+ "langsmith_tenant_id",
+ "humanloop_api_key",
+ "arize_api_key",
+ "arize_space_key",
+ "arize_space_id",
+ "posthog_api_key",
+ "posthog_host",
+ "braintrust_api_key",
+ "braintrust_project",
+ "braintrust_host",
+ "slack_webhook_url",
+ "lunary_public_key",
+ "turn_off_message_logging",
+]
+
def initialize_standard_callback_dynamic_params(
kwargs: Optional[Dict] = None,
@@ -15,13 +42,10 @@ def initialize_standard_callback_dynamic_params(
standard_callback_dynamic_params = StandardCallbackDynamicParams()
if kwargs:
- _supported_callback_params = (
- StandardCallbackDynamicParams.__annotations__.keys()
- )
-
+ # 1. Check top-level kwargs
for param in _supported_callback_params:
if param in kwargs:
- _param_value = kwargs.pop(param)
+ _param_value = kwargs.get(param)
if (
_param_value is not None
and isinstance(_param_value, str)
@@ -30,4 +54,22 @@ def initialize_standard_callback_dynamic_params(
_param_value = get_secret_str(secret_name=_param_value)
standard_callback_dynamic_params[param] = _param_value # type: ignore
+ # 2. Fallback: check "metadata" or "litellm_params" -> "metadata"
+ metadata = (kwargs.get("metadata") or {}).copy()
+ litellm_params = kwargs.get("litellm_params") or {}
+ if isinstance(litellm_params, dict):
+ metadata.update(litellm_params.get("metadata") or {})
+
+ if isinstance(metadata, dict):
+ for param in _supported_callback_params:
+ if param not in standard_callback_dynamic_params and param in metadata:
+ _param_value = metadata.get(param)
+ if (
+ _param_value is not None
+ and isinstance(_param_value, str)
+ and "os.environ/" in _param_value
+ ):
+ _param_value = get_secret_str(secret_name=_param_value)
+ standard_callback_dynamic_params[param] = _param_value # type: ignore
+
return standard_callback_dynamic_params
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index d512893465c..6a14e42c485 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -203,8 +203,17 @@ except Exception as e:
EnterpriseStandardLoggingPayloadSetupVAR = None
_in_memory_loggers: List[Any] = []
+_STANDARD_LOGGING_METADATA_KEYS: frozenset = frozenset(
+ StandardLoggingMetadata.__annotations__.keys()
+)
+
### GLOBAL VARIABLES ###
+# Cache custom pricing keys as frozenset for O(1) lookups instead of looping through 49 keys
+_CUSTOM_PRICING_KEYS: frozenset = frozenset(
+ CustomPricingLiteLLMParams.model_fields.keys()
+)
+
sentry_sdk_instance = None
capture_exception = None
add_breadcrumb = None
@@ -330,7 +339,9 @@ class Logging(LiteLLMLoggingBaseClass):
self.start_time = start_time # log the call start time
self.call_type = call_type
self.litellm_call_id = litellm_call_id
- self.litellm_trace_id: str = litellm_trace_id if litellm_trace_id else str(uuid.uuid4())
+ self.litellm_trace_id: str = (
+ litellm_trace_id if litellm_trace_id else str(uuid.uuid4())
+ )
self.function_id = function_id
self.streaming_chunks: List[Any] = [] # for generating complete stream response
self.sync_streaming_chunks: List[
@@ -515,7 +526,8 @@ class Logging(LiteLLMLoggingBaseClass):
}
self.litellm_request_debug = litellm_params.get("litellm_request_debug", False)
self.logger_fn = litellm_params.get("logger_fn", None)
- verbose_logger.debug(f"self.optional_params: {self.optional_params}")
+ if _is_debugging_on() or self.litellm_request_debug:
+ verbose_logger.debug(f"self.optional_params: {self.optional_params}")
self.model_call_details.update(
{
@@ -539,10 +551,11 @@ class Logging(LiteLLMLoggingBaseClass):
if "stream_options" in additional_params:
self.stream_options = additional_params["stream_options"]
## check if custom pricing set ##
- custom_pricing_keys = CustomPricingLiteLLMParams.model_fields.keys()
- for key in custom_pricing_keys:
- if litellm_params.get(key) is not None:
- self.custom_pricing = True
+ if any(
+ litellm_params.get(key) is not None
+ for key in _CUSTOM_PRICING_KEYS & litellm_params.keys()
+ ):
+ self.custom_pricing = True
if "custom_llm_provider" in self.model_call_details:
self.custom_llm_provider = self.model_call_details["custom_llm_provider"]
@@ -1289,6 +1302,7 @@ class Logging(LiteLLMLoggingBaseClass):
output_cost: float,
total_cost: float,
cost_for_built_in_tools_cost_usd_dollar: float,
+ additional_costs: Optional[dict] = None,
original_cost: Optional[float] = None,
discount_percent: Optional[float] = None,
discount_amount: Optional[float] = None,
@@ -1304,6 +1318,7 @@ class Logging(LiteLLMLoggingBaseClass):
output_cost: Cost of output/completion tokens
cost_for_built_in_tools_cost_usd_dollar: Cost of built-in tools
total_cost: Total cost of request
+ additional_costs: Free-form additional costs dict (e.g., {"azure_model_router_flat_cost": 0.00014})
original_cost: Cost before discount
discount_percent: Discount percentage (0.05 = 5%)
discount_amount: Discount amount in USD
@@ -1319,6 +1334,14 @@ class Logging(LiteLLMLoggingBaseClass):
tool_usage_cost=cost_for_built_in_tools_cost_usd_dollar,
)
+ # Store additional costs if provided (free-form dict for extensibility)
+ if (
+ additional_costs
+ and isinstance(additional_costs, dict)
+ and len(additional_costs) > 0
+ ):
+ self.cost_breakdown["additional_costs"] = additional_costs
+
# Store discount information if provided
if original_cost is not None:
self.cost_breakdown["original_cost"] = original_cost
@@ -1630,11 +1653,19 @@ class Logging(LiteLLMLoggingBaseClass):
"standard_logging_object"
)
) is not None:
- standard_logging_payload["response"] = (
+ response_dict = (
result.model_dump()
if hasattr(result, "model_dump")
else dict(result)
)
+ # Ensure usage is properly included with transformed chat format
+ if transformed_usage is not None:
+ response_dict["usage"] = (
+ transformed_usage.model_dump()
+ if hasattr(transformed_usage, "model_dump")
+ else dict(transformed_usage)
+ )
+ standard_logging_payload["response"] = response_dict
elif isinstance(result, TranscriptionResponse):
from litellm.litellm_core_utils.llm_cost_calc.usage_object_transformation import (
TranscriptionUsageObjectTransformation,
@@ -2304,7 +2335,7 @@ class Logging(LiteLLMLoggingBaseClass):
result, LiteLLMBatch
):
litellm_params = self.litellm_params or {}
- litellm_metadata = litellm_params.get("litellm_metadata", {})
+ litellm_metadata = litellm_params.get("litellm_metadata") or {}
if (
litellm_metadata.get("batch_ignore_default_logging", False) is True
): # polling job will query these frequently, don't spam db logs
@@ -2320,18 +2351,29 @@ class Logging(LiteLLMLoggingBaseClass):
batch_cost = kwargs.get("batch_cost", None)
batch_usage = kwargs.get("batch_usage", None)
batch_models = kwargs.get("batch_models", None)
- if all([batch_cost, batch_usage, batch_models]) is not None:
+ has_explicit_batch_data = all(
+ x is not None for x in (batch_cost, batch_usage, batch_models)
+ )
+
+ should_compute_batch_data = (
+ not is_base64_unified_file_id
+ or not has_explicit_batch_data
+ and result.status == "completed"
+ )
+ if has_explicit_batch_data:
result._hidden_params["response_cost"] = batch_cost
result._hidden_params["batch_models"] = batch_models
result.usage = batch_usage
- elif not is_base64_unified_file_id: # only run for non-unified file ids
+ elif should_compute_batch_data:
(
response_cost,
batch_usage,
batch_models,
) = await _handle_completed_batch(
- batch=result, custom_llm_provider=self.custom_llm_provider
+ batch=result,
+ custom_llm_provider=self.custom_llm_provider,
+ litellm_params=self.litellm_params,
)
result._hidden_params["response_cost"] = response_cost
@@ -2403,6 +2445,36 @@ class Logging(LiteLLMLoggingBaseClass):
standard_built_in_tools_params=self.standard_built_in_tools_params,
)
+ # print standard logging payload
+ if (
+ standard_logging_payload := self.model_call_details.get(
+ "standard_logging_object"
+ )
+ ) is not None:
+ emit_standard_logging_payload(standard_logging_payload)
+ elif self.call_type == "pass_through_endpoint":
+ print_verbose(
+ "Async success callbacks: Got a pass-through endpoint response"
+ )
+
+ self.model_call_details["async_complete_streaming_response"] = result
+
+ # cost calculation not possible for pass-through
+ self.model_call_details["response_cost"] = None
+
+ ## STANDARDIZED LOGGING PAYLOAD
+ self.model_call_details[
+ "standard_logging_object"
+ ] = get_standard_logging_object_payload(
+ kwargs=self.model_call_details,
+ init_response_obj=result,
+ start_time=start_time,
+ end_time=end_time,
+ logging_obj=self,
+ status="success",
+ standard_built_in_tools_params=self.standard_built_in_tools_params,
+ )
+
# print standard logging payload
if (
standard_logging_payload := self.model_call_details.get(
@@ -3060,7 +3132,7 @@ class Logging(LiteLLMLoggingBaseClass):
self, dynamic_success_callbacks: Optional[List], global_callbacks: List
) -> List:
if dynamic_success_callbacks is None:
- return global_callbacks
+ return list(global_callbacks)
return list(set(dynamic_success_callbacks + global_callbacks))
def _remove_internal_litellm_callbacks(self, callbacks: List) -> List:
@@ -3697,7 +3769,7 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
from litellm.integrations.opentelemetry import OpenTelemetry
for callback in _in_memory_loggers:
- if isinstance(callback, OpenTelemetry):
+ if type(callback) is OpenTelemetry:
return callback # type: ignore
otel_logger = OpenTelemetry(
**_get_custom_logger_settings_from_proxy_server(
@@ -3855,18 +3927,6 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
return langfuse_logger # type: ignore
elif logging_integration == "langfuse_otel":
from litellm.integrations.langfuse.langfuse_otel import LangfuseOtelLogger
- from litellm.integrations.opentelemetry import (
- OpenTelemetry,
- OpenTelemetryConfig,
- )
-
- langfuse_otel_config = LangfuseOtelLogger.get_langfuse_otel_config()
-
- # The endpoint and headers are now set as environment variables by get_langfuse_otel_config()
- otel_config = OpenTelemetryConfig(
- exporter=langfuse_otel_config.protocol,
- headers=langfuse_otel_config.otlp_auth_headers,
- )
for callback in _in_memory_loggers:
if (
@@ -3874,8 +3934,10 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
and callback.callback_name == "langfuse_otel"
):
return callback # type: ignore
+ # Allow LangfuseOtelLogger to initialize its own config safely
+ # This prevents startup crashes if LANGFUSE keys are not in env (e.g. for dynamic usage)
_otel_logger = LangfuseOtelLogger(
- config=otel_config, callback_name="langfuse_otel"
+ config=None, callback_name="langfuse_otel"
)
_in_memory_loggers.append(_otel_logger)
return _otel_logger # type: ignore
@@ -4249,15 +4311,21 @@ def use_custom_pricing_for_model(litellm_params: Optional[dict]) -> bool:
if litellm_params is None:
return False
+ # Check litellm_params using set intersection (only check keys that exist in both)
+ matching_keys = _CUSTOM_PRICING_KEYS & litellm_params.keys()
+ for key in matching_keys:
+ if litellm_params.get(key) is not None:
+ return True
+
+ # Check model_info
metadata: dict = litellm_params.get("metadata", {}) or {}
model_info: dict = metadata.get("model_info", {}) or {}
- custom_pricing_keys = CustomPricingLiteLLMParams.model_fields.keys()
- for key in custom_pricing_keys:
- if litellm_params.get(key, None) is not None:
- return True
- elif model_info.get(key, None) is not None:
- return True
+ if model_info:
+ matching_keys = _CUSTOM_PRICING_KEYS & model_info.keys()
+ for key in matching_keys:
+ if model_info.get(key) is not None:
+ return True
return False
@@ -4445,6 +4513,7 @@ class StandardLoggingPayloadSetup:
user_api_key_request_route=None,
spend_logs_metadata=None,
requester_ip_address=None,
+ user_agent=None,
requester_metadata=None,
prompt_management_metadata=prompt_management_metadata,
applied_guardrails=applied_guardrails,
@@ -4454,19 +4523,20 @@ class StandardLoggingPayloadSetup:
requester_custom_headers=None,
cold_storage_object_key=None,
user_api_key_auth_metadata=None,
+ team_alias=None,
+ team_id=None,
)
if isinstance(metadata, dict):
- # Filter the metadata dictionary to include only the specified keys
- supported_keys = StandardLoggingMetadata.__annotations__.keys()
- for key in supported_keys:
- if key in metadata:
- clean_metadata[key] = metadata[key] # type: ignore
+ for key in metadata.keys() & _STANDARD_LOGGING_METADATA_KEYS:
+ clean_metadata[key] = metadata[key] # type: ignore
- if metadata.get("user_api_key") is not None:
- if is_valid_sha256_hash(str(metadata.get("user_api_key"))):
- clean_metadata["user_api_key_hash"] = metadata.get(
- "user_api_key"
- ) # this is the hash
+ user_api_key = metadata.get("user_api_key")
+ if (
+ user_api_key
+ and isinstance(user_api_key, str)
+ and is_valid_sha256_hash(user_api_key)
+ ):
+ clean_metadata["user_api_key_hash"] = user_api_key
_potential_requester_metadata = metadata.get(
"metadata", None
) # check if user passed metadata in the sdk request - e.g. metadata for langsmith logging - https://docs.litellm.ai/docs/observability/langsmith_integration#set-langsmith-fields
@@ -4525,6 +4595,10 @@ class StandardLoggingPayloadSetup:
)
elif isinstance(usage, Usage):
return usage
+ elif isinstance(usage, ResponseAPIUsage):
+ return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(
+ usage
+ )
elif isinstance(usage, dict):
if ResponseAPILoggingUtils._is_response_api_usage(usage):
return (
@@ -4653,7 +4727,10 @@ class StandardLoggingPayloadSetup:
@staticmethod
def strip_trailing_slash(api_base: Optional[str]) -> Optional[str]:
if api_base:
- return api_base.rstrip("/")
+ if api_base.endswith("//"):
+ return api_base.rstrip("/")
+ if api_base[-1] == "/":
+ return api_base[:-1]
return api_base
@staticmethod
@@ -4722,7 +4799,14 @@ class StandardLoggingPayloadSetup:
) -> StandardLoggingPayloadErrorInformation:
from litellm.constants import MAXIMUM_TRACEBACK_LINES_TO_LOG
- error_status: str = str(getattr(original_exception, "status_code", ""))
+ # Check for 'code' first (used by ProxyException), then fall back to 'status_code' (used by LiteLLM exceptions)
+ # Ensure error_code is always a string for Prisma Python JSON field compatibility
+ error_code_attr = getattr(original_exception, "code", None)
+ if error_code_attr is not None and str(error_code_attr) not in ("", "None"):
+ error_status: str = str(error_code_attr)
+ else:
+ status_code_attr = getattr(original_exception, "status_code", None)
+ error_status = str(status_code_attr) if status_code_attr is not None else ""
error_class: str = (
str(original_exception.__class__.__name__) if original_exception else ""
)
@@ -5127,6 +5211,7 @@ def get_standard_logging_object_payload(
model_group=_model_group,
model_id=_model_id,
requester_ip_address=clean_metadata.get("requester_ip_address", None),
+ user_agent=clean_metadata.get("user_agent", None),
messages=StandardLoggingPayloadSetup.append_system_prompt_messages(
kwargs=kwargs, messages=kwargs.get("messages")
),
@@ -5192,6 +5277,7 @@ def get_standard_logging_metadata(
user_api_key_team_alias=None,
spend_logs_metadata=None,
requester_ip_address=None,
+ user_agent=None,
requester_metadata=None,
user_api_key_end_user_id=None,
prompt_management_metadata=None,
@@ -5203,6 +5289,8 @@ def get_standard_logging_metadata(
user_api_key_request_route=None,
cold_storage_object_key=None,
user_api_key_auth_metadata=None,
+ team_alias=None,
+ team_id=None,
)
if isinstance(metadata, dict):
# Update the clean_metadata with values from input metadata that match StandardLoggingMetadata fields
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py
index 785976ed319..2308dc7beca 100644
--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py
+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py
@@ -23,6 +23,15 @@ def _is_above_128k(tokens: float) -> bool:
return False
+def get_billable_input_tokens(usage: Usage) -> int:
+ """
+ Returns the number of billable input tokens.
+ Subtracts cached tokens from prompt tokens if applicable.
+ """
+ details = _parse_prompt_tokens_details(usage)
+ return usage.prompt_tokens - details["cache_hit_tokens"]
+
+
def select_cost_metric_for_model(
model_info: ModelInfo,
) -> Literal["cost_per_character", "cost_per_token"]:
@@ -190,7 +199,6 @@ def _get_token_base_cost(
1000 if "k" in threshold_str else 1
)
if usage.prompt_tokens > threshold:
-
prompt_base_cost = cast(
float, _get_cost_per_unit(model_info, key, prompt_base_cost)
)
@@ -207,6 +215,9 @@ def _get_token_base_cost(
cache_creation_tiered_key = (
f"cache_creation_input_token_cost_above_{threshold_str}_tokens"
)
+ cache_creation_1hr_tiered_key = (
+ f"cache_creation_input_token_cost_above_1hr_above_{threshold_str}_tokens"
+ )
cache_read_tiered_key = (
f"cache_read_input_token_cost_above_{threshold_str}_tokens"
)
@@ -221,6 +232,16 @@ def _get_token_base_cost(
),
)
+ if cache_creation_1hr_tiered_key in model_info:
+ cache_creation_cost_above_1hr = cast(
+ float,
+ _get_cost_per_unit(
+ model_info,
+ cache_creation_1hr_tiered_key,
+ cache_creation_cost_above_1hr,
+ ),
+ )
+
if cache_read_tiered_key in model_info:
cache_read_cost = cast(
float,
@@ -566,14 +587,28 @@ def generic_cost_per_token( # noqa: PLR0915
if usage.prompt_tokens_details:
prompt_tokens_details = _parse_prompt_tokens_details(usage)
- ## EDGE CASE - text tokens not set inside PromptTokensDetails
+ ## EDGE CASE - text tokens not set or includes cached tokens (double-counting)
+ ## Some providers (like xAI) report text_tokens = prompt_tokens (including cached)
+ ## We detect this when: text_tokens + cached_tokens + other > prompt_tokens
+ ## Ref: https://github.com/BerriAI/litellm/issues/19680, #14874, #14875
- if prompt_tokens_details["text_tokens"] == 0:
+ cache_hit = prompt_tokens_details["cache_hit_tokens"]
+ text_tokens = prompt_tokens_details["text_tokens"]
+ audio_tokens = prompt_tokens_details["audio_tokens"]
+ cache_creation = prompt_tokens_details["cache_creation_tokens"]
+ image_tokens = prompt_tokens_details["image_tokens"]
+
+ # Check for double-counting: sum of details > prompt_tokens means overlap
+ total_details = text_tokens + cache_hit + audio_tokens + cache_creation + image_tokens
+ has_double_counting = cache_hit > 0 and total_details > usage.prompt_tokens
+
+ if text_tokens == 0 or has_double_counting:
text_tokens = (
usage.prompt_tokens
- - prompt_tokens_details["cache_hit_tokens"]
- - prompt_tokens_details["audio_tokens"]
- - prompt_tokens_details["cache_creation_tokens"]
+ - cache_hit
+ - audio_tokens
+ - cache_creation
+ - image_tokens
)
prompt_tokens_details["text_tokens"] = text_tokens
@@ -619,7 +654,11 @@ def generic_cost_per_token( # noqa: PLR0915
# Calculate text tokens as remainder when we have a breakdown
# This handles cases like OpenAI's reasoning models where text_tokens isn't provided
text_tokens = max(
- 0, usage.completion_tokens - reasoning_tokens - audio_tokens - image_tokens
+ 0,
+ usage.completion_tokens
+ - reasoning_tokens
+ - audio_tokens
+ - image_tokens,
)
else:
# No breakdown at all, all tokens are text tokens
diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
index 25ad0a570cb..a6e502a32b3 100644
--- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
+++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
@@ -546,7 +546,11 @@ def convert_to_model_response_object( # noqa: PLR0915
message = litellm.Message(content=json_mode_content_str)
finish_reason = "stop"
if message is None:
- provider_specific_fields = {}
+ # Preserve provider_specific_fields if already present
+ # in the response (e.g. from proxy passthrough)
+ provider_specific_fields = dict(
+ choice["message"].get("provider_specific_fields", None) or {}
+ )
message_keys = Message.model_fields.keys()
for field in choice["message"].keys():
if field not in message_keys:
diff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.py
index 4f76a5bad03..34d25817378 100644
--- a/litellm/litellm_core_utils/logging_callback_manager.py
+++ b/litellm/litellm_core_utils/logging_callback_manager.py
@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Set, Type, Uni
import litellm
from litellm._logging import verbose_logger
+from litellm.constants import MAX_CALLBACKS
from litellm.integrations.additional_logging_utils import AdditionalLoggingUtils
from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.generic_api.generic_api_callback import GenericAPILogger
@@ -24,9 +25,6 @@ class LoggingCallbackManager:
- Keep a reasonable MAX_CALLBACKS limit (this ensures callbacks don't exponentially grow and consume CPU Resources)
"""
- # healthy maximum number of callbacks - unlikely someone needs more than 20
- MAX_CALLBACKS = 30
-
def add_litellm_input_callback(self, callback: Union[CustomLogger, str]):
"""
Add a input callback to litellm.input_callback
@@ -114,6 +112,27 @@ class LoggingCallbackManager:
for c in remove_list:
callback_list.remove(c)
+ def remove_callbacks_by_type(self, callback_list, callback_type):
+ """
+ Remove all callbacks of a specific type from a callback list.
+
+ Args:
+ callback_list: The list to remove callbacks from (e.g., litellm.callbacks)
+ callback_type: The class type to match (e.g., SemanticToolFilterHook)
+
+ Example:
+ litellm.logging_callback_manager.remove_callbacks_by_type(
+ litellm.callbacks, SemanticToolFilterHook
+ )
+ """
+ if not isinstance(callback_list, list):
+ return
+
+ remove_list = [c for c in callback_list if isinstance(c, callback_type)]
+
+ for c in remove_list:
+ callback_list.remove(c)
+
def _add_string_callback_to_list(
self, callback: str, parent_list: List[Union[CustomLogger, Callable, str]]
):
@@ -134,9 +153,9 @@ class LoggingCallbackManager:
Check if adding another callback would exceed MAX_CALLBACKS
Returns True if safe to add, False if would exceed limit
"""
- if len(parent_list) >= self.MAX_CALLBACKS:
+ if len(parent_list) >= MAX_CALLBACKS:
verbose_logger.warning(
- f"Cannot add callback - would exceed MAX_CALLBACKS limit of {self.MAX_CALLBACKS}. Current callbacks: {len(parent_list)}"
+ f"Cannot add callback - would exceed MAX_CALLBACKS limit of {MAX_CALLBACKS}. Current callbacks: {len(parent_list)}"
)
return False
return True
diff --git a/litellm/litellm_core_utils/logging_utils.py b/litellm/litellm_core_utils/logging_utils.py
index bf43519afc6..8cde8ccef1c 100644
--- a/litellm/litellm_core_utils/logging_utils.py
+++ b/litellm/litellm_core_utils/logging_utils.py
@@ -1,5 +1,6 @@
import asyncio
import functools
+import inspect
import time
from datetime import datetime
from typing import TYPE_CHECKING, Any, List, Optional, Union
@@ -270,7 +271,7 @@ def track_llm_api_timing():
verbose_logger.debug(f"Error in service logging: {str(e)}")
# Check if the function is async or sync
- if asyncio.iscoroutinefunction(func):
+ if inspect.iscoroutinefunction(func):
return async_wrapper
return sync_wrapper
diff --git a/litellm/litellm_core_utils/logging_worker.py b/litellm/litellm_core_utils/logging_worker.py
index 13a83956edd..d5eca9eeb55 100644
--- a/litellm/litellm_core_utils/logging_worker.py
+++ b/litellm/litellm_core_utils/logging_worker.py
@@ -415,6 +415,28 @@ class LoggingWorker:
"""
Safely log a message during shutdown, suppressing errors if logging is closed.
"""
+ # Check if logger has valid handlers before attempting to log
+ # During shutdown, handlers may be closed, causing ValueError when writing
+ if not hasattr(verbose_logger, 'handlers') or not verbose_logger.handlers:
+ return
+
+ # Check if any handler has a valid stream
+ has_valid_handler = False
+ for handler in verbose_logger.handlers:
+ try:
+ if hasattr(handler, 'stream') and handler.stream and not handler.stream.closed:
+ has_valid_handler = True
+ break
+ elif not hasattr(handler, 'stream'):
+ # Non-stream handlers (like NullHandler) are always valid
+ has_valid_handler = True
+ break
+ except (AttributeError, ValueError):
+ continue
+
+ if not has_valid_handler:
+ return
+
try:
if level == "debug":
verbose_logger.debug(message)
diff --git a/litellm/litellm_core_utils/model_param_helper.py b/litellm/litellm_core_utils/model_param_helper.py
index 91f2f1341cf..4d45c47c224 100644
--- a/litellm/litellm_core_utils/model_param_helper.py
+++ b/litellm/litellm_core_utils/model_param_helper.py
@@ -17,15 +17,16 @@ from litellm.types.rerank import RerankRequest
class ModelParamHelper:
+ # Cached at class level — deterministic set built from static OpenAI type annotations
+ _relevant_logging_args: frozenset = frozenset()
+
@staticmethod
def get_standard_logging_model_parameters(
model_parameters: dict,
) -> dict:
""" """
standard_logging_model_parameters: dict = {}
- supported_model_parameters = (
- ModelParamHelper._get_relevant_args_to_use_for_logging()
- )
+ supported_model_parameters = ModelParamHelper._relevant_logging_args
for key, value in model_parameters.items():
if key in supported_model_parameters:
@@ -172,3 +173,8 @@ class ModelParamHelper:
Get the kwargs to exclude from the cache key
"""
return set(["metadata"])
+
+
+ModelParamHelper._relevant_logging_args = frozenset(
+ ModelParamHelper._get_relevant_args_to_use_for_logging()
+)
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index 7790fb83361..cdddee4e54e 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -443,13 +443,21 @@ def update_messages_with_model_file_ids(
def update_responses_input_with_model_file_ids(
input: Any,
+ model_id: Optional[str] = None,
+ model_file_id_mapping: Optional[Dict[str, Dict[str, str]]] = None,
) -> Union[str, List[Dict[str, Any]]]:
"""
Updates responses API input with provider-specific file IDs.
File IDs are always inside the content array, not as direct input_file items.
- For managed files (unified file IDs), decodes the base64-encoded unified file ID
- and extracts the llm_output_file_id directly.
+ For managed files (unified file IDs), uses model_file_id_mapping if provided,
+ otherwise decodes the base64-encoded unified file ID and extracts the llm_output_file_id directly.
+
+ Args:
+ input: The responses API input parameter
+ model_id: The model ID to use for looking up provider-specific file IDs
+ model_file_id_mapping: Dictionary mapping litellm file IDs to provider file IDs
+ Format: {"litellm_file_id": {"model_id": "provider_file_id"}}
"""
from litellm.proxy.openai_files_endpoints.common_utils import (
_is_base64_encoded_unified_file_id,
@@ -479,22 +487,35 @@ def update_responses_input_with_model_file_ids(
):
file_id = content_item.get("file_id")
if file_id:
- # Check if this is a managed file ID (base64-encoded unified file ID)
- is_unified_file_id = _is_base64_encoded_unified_file_id(file_id)
- if is_unified_file_id:
- unified_file_id = convert_b64_uid_to_unified_uid(file_id)
- if "llm_output_file_id," in unified_file_id:
- provider_file_id = unified_file_id.split(
- "llm_output_file_id,"
- )[1].split(";")[0]
- else:
- # Fallback: keep original if we can't extract
- provider_file_id = file_id
+ provider_file_id = file_id # Default to original
+
+ # Check if we have a mapping for this file ID
+ if model_file_id_mapping and model_id and file_id in model_file_id_mapping:
+ # Use the model-specific file ID from mapping
+ provider_file_id = (
+ model_file_id_mapping.get(file_id, {}).get(model_id)
+ or file_id
+ )
updated_content_item = content_item.copy()
updated_content_item["file_id"] = provider_file_id
updated_content.append(updated_content_item)
else:
- updated_content.append(content_item)
+ # Check if this is a base64-encoded unified file ID without mapping
+ is_unified_file_id = _is_base64_encoded_unified_file_id(file_id)
+ if is_unified_file_id:
+ # Fallback: decode unified file ID
+ unified_file_id = convert_b64_uid_to_unified_uid(file_id)
+ if "llm_output_file_id," in unified_file_id:
+ provider_file_id = unified_file_id.split(
+ "llm_output_file_id,"
+ )[1].split(";")[0]
+
+ updated_content_item = content_item.copy()
+ updated_content_item["file_id"] = provider_file_id
+ updated_content.append(updated_content_item)
+ else:
+ # Not a managed file, keep as-is
+ updated_content.append(content_item)
else:
updated_content.append(content_item)
else:
@@ -506,6 +527,68 @@ def update_responses_input_with_model_file_ids(
return updated_input
+def update_responses_tools_with_model_file_ids(
+ tools: Optional[List[Dict[str, Any]]],
+ model_id: Optional[str] = None,
+ model_file_id_mapping: Optional[Dict[str, Dict[str, str]]] = None,
+) -> Optional[List[Dict[str, Any]]]:
+ """
+ Updates responses API tools with provider-specific file IDs.
+
+ Handles code_interpreter tools with container.file_ids.
+
+ Args:
+ tools: The responses API tools parameter
+ model_id: The model ID to use for looking up provider-specific file IDs
+ model_file_id_mapping: Dictionary mapping litellm file IDs to provider file IDs
+ Format: {"litellm_file_id": {"model_id": "provider_file_id"}}
+ """
+ if not tools or not isinstance(tools, list):
+ return tools
+
+ if not model_file_id_mapping or not model_id:
+ return tools
+
+ updated_tools = []
+ for tool in tools:
+ if not isinstance(tool, dict):
+ updated_tools.append(tool)
+ continue
+
+ updated_tool = tool.copy()
+
+ # Handle code_interpreter with container file_ids
+ if tool.get("type") == "code_interpreter":
+ container = tool.get("container")
+ if isinstance(container, dict):
+ container_file_ids = container.get("file_ids")
+ if isinstance(container_file_ids, list):
+ updated_file_ids = []
+ for file_id in container_file_ids:
+ if isinstance(file_id, str):
+ # Check if we have a mapping for this file ID
+ if file_id in model_file_id_mapping:
+ # Map to provider-specific file ID
+ provider_file_id = (
+ model_file_id_mapping.get(file_id, {}).get(model_id)
+ or file_id
+ )
+ updated_file_ids.append(provider_file_id)
+ else:
+ updated_file_ids.append(file_id)
+ else:
+ updated_file_ids.append(file_id)
+
+ # Update the tool with new file IDs
+ updated_container = container.copy()
+ updated_container["file_ids"] = updated_file_ids
+ updated_tool["container"] = updated_container
+
+ updated_tools.append(updated_tool)
+
+ return updated_tools
+
+
def extract_file_data(file_data: FileTypes) -> ExtractedFileData:
"""
Extracts and processes file data from various input formats.
@@ -1189,3 +1272,59 @@ def parse_tool_call_arguments(
)
raise ValueError(error_message) from e
+
+
+def split_concatenated_json_objects(raw: str) -> List[Dict[str, Any]]:
+ """
+ Split a string that contains one or more concatenated JSON objects into
+ a list of parsed dicts.
+
+ LLM providers (notably Bedrock Claude Sonnet 4.5) sometimes return
+ multiple tool-call argument objects concatenated in a single
+ ``arguments`` string, e.g.::
+
+ '{"command":["curl",...]}{"command":["curl",...]}{"command":["curl",...]}'
+
+ ``json.loads()`` fails on this with ``JSONDecodeError: Extra data``.
+ This helper uses ``json.JSONDecoder.raw_decode()`` to walk the string
+ and extract each JSON object individually.
+
+ Returns
+ -------
+ list[dict]
+ A list of parsed dicts – one per JSON object found. If *raw* is
+ empty or whitespace-only, an empty list is returned.
+
+ Raises
+ ------
+ json.JSONDecodeError
+ If the string contains text that cannot be parsed as JSON at all.
+ """
+ import json
+
+ raw = raw.strip()
+ if not raw:
+ return []
+
+ decoder = json.JSONDecoder()
+ results: List[Dict[str, Any]] = []
+ idx = 0
+ length = len(raw)
+
+ while idx < length:
+ # Skip whitespace between objects
+ while idx < length and raw[idx] in " \t\n\r":
+ idx += 1
+ if idx >= length:
+ break
+
+ obj, end_idx = decoder.raw_decode(raw, idx)
+ if isinstance(obj, dict):
+ results.append(obj)
+ else:
+ # Non-dict JSON value – wrap in empty dict (Bedrock requires
+ # toolUse.input to be an object).
+ results.append({})
+ idx = end_idx
+
+ return results
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index 1d1e38c09da..7b485501f61 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -1632,6 +1632,7 @@ def _sanitize_anthropic_tool_use_id(tool_use_id: str) -> str:
def convert_to_anthropic_tool_result(
message: Union[ChatCompletionToolMessage, ChatCompletionFunctionMessage],
+ force_base64: bool = False,
) -> AnthropicMessagesToolResultParam:
"""
OpenAI message with a tool result looks like:
@@ -1677,13 +1678,16 @@ def convert_to_anthropic_tool_result(
] = []
for content in content_list:
if content["type"] == "text":
- anthropic_content_list.append(
- AnthropicMessagesToolResultContent(
- type="text",
- text=content["text"],
- cache_control=content.get("cache_control", None),
- )
- )
+ # Only include cache_control if explicitly set and not None
+ # to avoid sending "cache_control": null which breaks some API channels
+ text_content: AnthropicMessagesToolResultContent = {
+ "type": "text",
+ "text": content["text"],
+ }
+ cache_control_value = content.get("cache_control")
+ if cache_control_value is not None:
+ text_content["cache_control"] = cache_control_value
+ anthropic_content_list.append(text_content)
elif content["type"] == "image_url":
format = (
content["image_url"].get("format")
@@ -1691,7 +1695,7 @@ def convert_to_anthropic_tool_result(
else None
)
_anthropic_image_param = create_anthropic_image_param(
- content["image_url"], format=format
+ content["image_url"], format=format, is_bedrock_invoke=force_base64
)
_anthropic_image_param = add_cache_control_to_content(
anthropic_content_element=_anthropic_image_param,
@@ -2014,6 +2018,235 @@ def anthropic_process_openai_file_message(
)
+def _sanitize_empty_text_content(
+ message: AllMessageValues,
+) -> AllMessageValues:
+ """
+ Case C: Sanitize empty text content
+ - Replace empty or whitespace-only text content with a placeholder message.
+
+ Returns:
+ The message with sanitized content if needed, otherwise the original message
+ """
+ if message.get("role") in ["user", "assistant"]:
+ content = message.get("content")
+ if isinstance(content, str):
+ if not content or not content.strip():
+ message = cast(AllMessageValues, dict(message)) # Make a copy
+ message["content"] = "[System: Empty message content sanitised to satisfy protocol]"
+ verbose_logger.debug(
+ f"_sanitize_empty_text_content: Replaced empty text content in {message.get('role')} message"
+ )
+ return message
+
+
+def _add_missing_tool_results( # noqa: PLR0915
+ current_message: AllMessageValues,
+ messages: List[AllMessageValues],
+ current_index: int,
+) -> Tuple[List[AllMessageValues], int]:
+ """
+ Case A: Missing tool_result for tool_use (orphaned tool calls)
+ - If an assistant message has tool_calls but no corresponding tool result follows,
+ add a dummy tool result message indicating the user did not provide the result.
+
+ Returns:
+ A tuple of:
+ - List containing the assistant message, followed by existing tool results,
+ followed by any dummy tool results needed
+ - Number of original messages consumed (to adjust iteration index)
+ """
+ result_messages: List[AllMessageValues] = []
+ tool_calls = current_message.get("tool_calls")
+
+ if not tool_calls or len(cast(list, tool_calls)) == 0:
+ return ([current_message], 0)
+
+ # Collect all tool_call_ids from this assistant message
+ expected_tool_call_ids = set()
+ for tool_call in cast(list, tool_calls):
+ tool_call_id = None
+ if isinstance(tool_call, dict):
+ tool_call_id = tool_call.get("id")
+ else:
+ tool_call_id = getattr(tool_call, "id", None)
+ if tool_call_id:
+ expected_tool_call_ids.add(tool_call_id)
+
+ # Collect actual tool result messages that follow this assistant message
+ found_tool_call_ids = set()
+ actual_tool_results: List[AllMessageValues] = []
+ j = current_index + 1
+
+ while j < len(messages):
+ next_msg = messages[j]
+ next_role = next_msg.get("role")
+
+ if next_role == "assistant":
+ break
+
+ if next_role in ["tool", "function"]:
+ tool_call_id = next_msg.get("tool_call_id")
+ if tool_call_id and tool_call_id in expected_tool_call_ids:
+ found_tool_call_ids.add(tool_call_id)
+ actual_tool_results.append(next_msg)
+
+ j += 1
+
+ # Find missing tool results
+ missing_tool_call_ids = expected_tool_call_ids - found_tool_call_ids
+
+ if missing_tool_call_ids:
+ verbose_logger.debug(
+ f"_add_missing_tool_results: Found {len(missing_tool_call_ids)} orphaned tool calls. Adding dummy tool results."
+ )
+
+ result_messages.append(current_message)
+
+ # Add existing tool results FIRST
+ result_messages.extend(actual_tool_results)
+
+ # Then add dummy tool results for missing ones
+ for tool_call_id in missing_tool_call_ids:
+ tool_name = "unknown_tool"
+ for tool_call in cast(list, tool_calls):
+ tc_id = None
+ if isinstance(tool_call, dict):
+ tc_id = tool_call.get("id")
+ else:
+ tc_id = getattr(tool_call, "id", None)
+
+ if tc_id == tool_call_id:
+ if isinstance(tool_call, dict):
+ function = tool_call.get("function", {})
+ if isinstance(function, dict):
+ tool_name = function.get("name", "unknown_tool")
+ else:
+ tool_name = getattr(function, "name", "unknown_tool")
+ else:
+ function = getattr(tool_call, "function", None)
+ if function:
+ tool_name = getattr(function, "name", "unknown_tool")
+ break
+
+ dummy_tool_result: ChatCompletionToolMessage = {
+ "role": "tool",
+ "tool_call_id": tool_call_id,
+ "content": f"[System: Tool execution skipped/interrupted by user. No result provided for tool '{tool_name}'.]",
+ }
+ result_messages.append(dummy_tool_result)
+
+ # Return the messages and the number of original messages to skip
+ return (result_messages, len(actual_tool_results))
+
+ return ([current_message], 0)
+
+
+def _is_orphaned_tool_result(
+ current_message: AllMessageValues,
+ sanitized_messages: List[AllMessageValues],
+) -> bool:
+ """
+ Case B: Orphaned tool_result (unexpected result)
+ - Check if a tool message references a tool_call_id that doesn't exist in the previous
+ assistant message.
+
+ Returns:
+ True if this is an orphaned tool result that should be removed, False otherwise
+ """
+ if current_message.get("role") not in ["tool", "function"]:
+ return False
+
+ tool_call_id = current_message.get("tool_call_id")
+
+ if not tool_call_id:
+ return False
+
+ # Look back to find the most recent assistant message with tool_calls
+ found_matching_tool_call = False
+
+ for j in range(len(sanitized_messages) - 1, -1, -1):
+ prev_msg = sanitized_messages[j]
+ if prev_msg.get("role") == "assistant":
+ tool_calls = prev_msg.get("tool_calls")
+ if tool_calls:
+ for tool_call in cast(list, tool_calls):
+ tc_id = None
+ if isinstance(tool_call, dict):
+ tc_id = tool_call.get("id")
+ else:
+ tc_id = getattr(tool_call, "id", None)
+
+ if tc_id == tool_call_id:
+ found_matching_tool_call = True
+ break
+
+ break
+
+ if not found_matching_tool_call:
+ verbose_logger.debug(
+ "_is_orphaned_tool_result: Found orphaned tool result with redacted tool_call_id"
+ )
+ return True
+
+ return False
+
+
+def sanitize_messages_for_tool_calling(
+ messages: List[AllMessageValues],
+) -> List[AllMessageValues]:
+ """
+ Sanitize messages for tool calling to handle common issues when modify_params=True:
+
+ Case A: Missing tool_result for tool_use (orphaned tool calls)
+ - If an assistant message has tool_calls but no corresponding tool result follows,
+ add a dummy tool result message indicating the user did not provide the result.
+
+ Case B: Orphaned tool_result (unexpected result)
+ - If a tool message references a tool_call_id that doesn't exist in the previous
+ assistant message, remove that tool message.
+
+ Case C: Empty text content
+ - Replace empty or whitespace-only text content with a placeholder message.
+
+ This function operates on OpenAI format messages before they are converted to
+ provider-specific formats.
+ """
+ if not litellm.modify_params:
+ return messages
+
+ sanitized_messages: List[AllMessageValues] = []
+ i = 0
+
+ while i < len(messages):
+ current_message = messages[i]
+
+ # Case C: Sanitize empty text content
+ current_message = _sanitize_empty_text_content(current_message)
+
+ # Case A: Check if assistant message has tool_calls without following tool results
+ if current_message.get("role") == "assistant":
+ result_messages, messages_consumed = _add_missing_tool_results(current_message, messages, i)
+
+ # If dummy tool results were added, extend sanitized_messages and skip consumed messages
+ if len(result_messages) > 1:
+ sanitized_messages.extend(result_messages)
+ # Skip the assistant message and any actual tool results that were included
+ i += 1 + messages_consumed
+ continue
+
+ # Case B: Check for orphaned tool results
+ if _is_orphaned_tool_result(current_message, sanitized_messages):
+ i += 1
+ continue # Skip this orphaned tool result
+
+ # Add the message to sanitized list
+ sanitized_messages.append(current_message)
+ i += 1
+
+ return sanitized_messages
+
+
def anthropic_messages_pt( # noqa: PLR0915
messages: List[AllMessageValues],
model: str,
@@ -2033,6 +2266,9 @@ def anthropic_messages_pt( # noqa: PLR0915
5. System messages are a separate param to the Messages API
6. Ensure we only accept role, content. (message.name is not supported)
"""
+ # Sanitize messages for tool calling issues when modify_params=True
+ messages = sanitize_messages_for_tool_calling(messages)
+
# add role=tool support to allow function call result/error submission
user_message_types = {"user", "tool", "function"}
# reformat messages to ensure user/assistant are alternating, if there's either 2 consecutive 'user' messages or 2 consecutive 'assistant' message, merge them.
@@ -2053,6 +2289,12 @@ def anthropic_messages_pt( # noqa: PLR0915
else:
messages.append(DEFAULT_USER_CONTINUE_MESSAGE_TYPED)
+ # Bedrock invoke models have format: invoke/...
+ # Vertex AI Anthropic also doesn't support URL sources for images
+ is_bedrock_invoke = model.lower().startswith("invoke/")
+ is_vertex_ai = llm_provider.startswith("vertex_ai") if llm_provider else False
+ force_base64 = is_bedrock_invoke or is_vertex_ai
+
msg_i = 0
while msg_i < len(messages):
user_content: List[AnthropicMessagesUserMessageValues] = []
@@ -2162,7 +2404,9 @@ def anthropic_messages_pt( # noqa: PLR0915
):
# OpenAI's tool message content will always be a string
user_content.append(
- convert_to_anthropic_tool_result(user_message_types_block)
+ convert_to_anthropic_tool_result(
+ user_message_types_block, force_base64=force_base64
+ )
)
msg_i += 1
@@ -2178,6 +2422,16 @@ def anthropic_messages_pt( # noqa: PLR0915
while msg_i < len(messages) and messages[msg_i]["role"] == "assistant":
assistant_content_block: ChatCompletionAssistantMessage = messages[msg_i] # type: ignore
+ # Extract compaction_blocks from provider_specific_fields and add them first
+ _provider_specific_fields_raw = assistant_content_block.get(
+ "provider_specific_fields"
+ )
+ if isinstance(_provider_specific_fields_raw, dict):
+ _compaction_blocks = _provider_specific_fields_raw.get("compaction_blocks")
+ if _compaction_blocks and isinstance(_compaction_blocks, list):
+ # Add compaction blocks at the beginning of assistant content : https://platform.claude.com/docs/en/build-with-claude/compaction
+ assistant_content.extend(_compaction_blocks) # type: ignore
+
thinking_blocks = assistant_content_block.get("thinking_blocks", None)
if (
thinking_blocks is not None
@@ -3265,25 +3519,68 @@ def _convert_to_bedrock_tool_call_invoke(
- extract name
- extract id
"""
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ split_concatenated_json_objects,
+ )
try:
_parts_list: List[BedrockContentBlock] = []
for tool in tool_calls:
if "function" in tool:
- id = tool["id"]
+ tool_id = tool["id"]
name = tool["function"].get("name", "")
arguments = tool["function"].get("arguments", "")
- arguments_dict = json.loads(arguments) if arguments else {}
- # Ensure arguments_dict is always a dict (Bedrock requires toolUse.input to be an object)
- # When some providers return arguments: '""' (JSON-encoded empty string), json.loads returns ""
- if not isinstance(arguments_dict, dict):
- arguments_dict = {}
+
if not arguments or not arguments.strip():
arguments_dict = {}
else:
- arguments_dict = json.loads(arguments)
+ try:
+ arguments_dict = json.loads(arguments)
+ # Ensure arguments_dict is always a dict
+ # (Bedrock requires toolUse.input to be an object).
+ # Some providers return arguments: '""' which
+ # json.loads decodes to a bare string.
+ if not isinstance(arguments_dict, dict):
+ arguments_dict = {}
+ except json.JSONDecodeError:
+ # The model may return multiple JSON objects
+ # concatenated in a single arguments string, e.g.
+ # '{"cmd":"a"}{"cmd":"b"}{"cmd":"c"}'
+ # Split them and emit one toolUse block per object.
+ # Fixes: https://github.com/BerriAI/litellm/issues/20543
+ parsed_objects = split_concatenated_json_objects(
+ arguments
+ )
+ if parsed_objects:
+ # First object keeps the original tool id.
+ for obj_idx, obj in enumerate(parsed_objects):
+ block_id = (
+ tool_id
+ if obj_idx == 0
+ else f"{tool_id}_{obj_idx}"
+ )
+ bedrock_tool = BedrockToolUseBlock(
+ input=obj, name=name, toolUseId=block_id
+ )
+ _parts_list.append(
+ BedrockContentBlock(toolUse=bedrock_tool)
+ )
+ # cache_control applies to the whole original
+ # tool call; attach after the last split block.
+ if tool.get("cache_control", None) is not None:
+ _parts_list.append(
+ BedrockContentBlock(
+ cachePoint=CachePointBlock(
+ type="default"
+ )
+ )
+ )
+ continue
+ # Fallback: no objects extracted — use empty dict.
+ arguments_dict = {}
+
bedrock_tool = BedrockToolUseBlock(
- input=arguments_dict, name=name, toolUseId=id
+ input=arguments_dict, name=name, toolUseId=tool_id
)
bedrock_content_block = BedrockContentBlock(toolUse=bedrock_tool)
_parts_list.append(bedrock_content_block)
@@ -3387,6 +3684,59 @@ def _convert_to_bedrock_tool_call_result(
return content_block
+def _deduplicate_bedrock_content_blocks(
+ blocks: List[BedrockContentBlock],
+ block_key: str,
+ id_key: str = "toolUseId",
+) -> List[BedrockContentBlock]:
+ """
+ Remove duplicate content blocks that share the same ID under ``block_key``.
+
+ Bedrock requires all toolResult and toolUse IDs within a single message to
+ be unique. When merging consecutive messages, duplicates can occur if the
+ same tool_call_id appears multiple times in conversation history.
+
+ When duplicates exist, the first occurrence is retained and subsequent ones
+ are discarded. A warning is logged for every dropped block so that
+ upstream duplication bugs remain visible.
+
+ Blocks that do not contain ``block_key`` (e.g., cachePoint, text) are
+ always preserved.
+
+ Args:
+ blocks: The list of Bedrock content blocks to deduplicate.
+ block_key: The dict key to inspect (e.g. ``"toolResult"`` or ``"toolUse"``).
+ id_key: The nested key that holds the unique ID (default ``"toolUseId"``).
+ """
+ seen_ids: Set[str] = set()
+ deduplicated: List[BedrockContentBlock] = []
+ for block in blocks:
+ keyed = block.get(block_key)
+ if keyed is not None and isinstance(keyed, dict):
+ block_id = keyed.get(id_key)
+ if block_id:
+ if block_id in seen_ids:
+ verbose_logger.warning(
+ "Bedrock Converse: dropping duplicate %s block with "
+ "%s=%s. This may indicate duplicate tool messages in "
+ "conversation history.",
+ block_key,
+ id_key,
+ block_id,
+ )
+ continue
+ seen_ids.add(block_id)
+ deduplicated.append(block)
+ return deduplicated
+
+
+def _deduplicate_bedrock_tool_content(
+ tool_content: List[BedrockContentBlock],
+) -> List[BedrockContentBlock]:
+ """Convenience wrapper: deduplicate ``toolResult`` blocks by ``toolUseId``."""
+ return _deduplicate_bedrock_content_blocks(tool_content, "toolResult")
+
+
def _insert_assistant_continue_message(
messages: List[BedrockMessageBlock],
assistant_continue_message: Optional[
@@ -3855,6 +4205,8 @@ class BedrockConverseMessagesProcessor:
tool_content.append(cache_point_block)
msg_i += 1
+ # Deduplicate toolResult blocks with the same toolUseId
+ tool_content = _deduplicate_bedrock_tool_content(tool_content)
if tool_content:
# if last message was a 'user' message, then add a blank assistant message (bedrock requires alternating roles)
if len(contents) > 0 and contents[-1]["role"] == "user":
@@ -3920,10 +4272,12 @@ class BedrockConverseMessagesProcessor:
assistant_parts=assistants_parts,
)
elif element["type"] == "text":
- assistants_part = BedrockContentBlock(
- text=element["text"]
- )
- assistants_parts.append(assistants_part)
+ # Skip completely empty strings to avoid blank content blocks
+ if element.get("text", "").strip():
+ assistants_part = BedrockContentBlock(
+ text=element["text"]
+ )
+ assistants_parts.append(assistants_part)
elif element["type"] == "image_url":
if isinstance(element["image_url"], dict):
image_url = element["image_url"]["url"]
@@ -3948,9 +4302,12 @@ class BedrockConverseMessagesProcessor:
elif _assistant_content is not None and isinstance(
_assistant_content, str
):
- assistant_content.append(
- BedrockContentBlock(text=_assistant_content)
- )
+ # Skip completely empty strings to avoid blank content blocks
+ if _assistant_content.strip():
+ assistant_content.append(
+ BedrockContentBlock(text=_assistant_content)
+ )
+ # If content is empty/whitespace, skip it (don't add a placeholder)
# Add cache point block for assistant string content
_cache_point_block = (
litellm.AmazonConverseConfig()._get_cache_point_block(
@@ -3968,6 +4325,8 @@ class BedrockConverseMessagesProcessor:
msg_i += 1
+ assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse")
+
if assistant_content:
contents.append(
BedrockMessageBlock(role="assistant", content=assistant_content)
@@ -4218,6 +4577,8 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915
tool_content.append(cache_point_block)
msg_i += 1
+ # Deduplicate toolResult blocks with the same toolUseId
+ tool_content = _deduplicate_bedrock_tool_content(tool_content)
if tool_content:
# if last message was a 'user' message, then add a blank assistant message (bedrock requires alternating roles)
if len(contents) > 0 and contents[-1]["role"] == "user":
@@ -4277,12 +4638,11 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915
assistant_parts=assistants_parts,
)
elif element["type"] == "text":
- # AWS Bedrock doesn't allow empty or whitespace-only text content, so use placeholder for empty strings
- text_content = (
- element["text"] if element["text"].strip() else "."
- )
- assistants_part = BedrockContentBlock(text=text_content)
- assistants_parts.append(assistants_part)
+ # AWS Bedrock doesn't allow empty or whitespace-only text content
+ # Skip completely empty strings to avoid blank content blocks
+ if element.get("text", "").strip():
+ assistants_part = BedrockContentBlock(text=element["text"])
+ assistants_parts.append(assistants_part)
elif element["type"] == "image_url":
if isinstance(element["image_url"], dict):
image_url = element["image_url"]["url"]
@@ -4305,9 +4665,9 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915
assistants_parts.append(_cache_point_block)
assistant_content.extend(assistants_parts)
elif _assistant_content is not None and isinstance(_assistant_content, str):
- # AWS Bedrock doesn't allow empty or whitespace-only text content, so use placeholder for empty strings
- text_content = _assistant_content if _assistant_content.strip() else "."
- assistant_content.append(BedrockContentBlock(text=text_content))
+ # Skip completely empty strings to avoid blank content blocks
+ if _assistant_content.strip():
+ assistant_content.append(BedrockContentBlock(text=_assistant_content))
# Add cache point block for assistant string content
_cache_point_block = (
litellm.AmazonConverseConfig()._get_cache_point_block(
@@ -4324,6 +4684,8 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915
msg_i += 1
+ assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse")
+
if assistant_content:
contents.append(
BedrockMessageBlock(role="assistant", content=assistant_content)
@@ -4383,6 +4745,32 @@ def add_cache_point_tool_block(tool: dict) -> Optional[BedrockToolBlock]:
return None
+def _is_bedrock_tool_block(tool: dict) -> bool:
+ """
+ Check if a tool is already a BedrockToolBlock.
+
+ BedrockToolBlock has one of: systemTool, toolSpec, or cachePoint.
+ This is used to detect tools that are already in Bedrock format
+ (e.g., systemTool for Nova grounding) vs OpenAI-style function tools
+ that need transformation.
+
+ Args:
+ tool: The tool dict to check
+
+ Returns:
+ True if the tool is already a BedrockToolBlock, False otherwise
+
+ Examples:
+ >>> _is_bedrock_tool_block({"systemTool": {"name": "nova_grounding"}})
+ True
+ >>> _is_bedrock_tool_block({"type": "function", "function": {...}})
+ False
+ """
+ return isinstance(tool, dict) and (
+ "systemTool" in tool or "toolSpec" in tool or "cachePoint" in tool
+ )
+
+
def _bedrock_tools_pt(tools: List) -> List[BedrockToolBlock]:
"""
OpenAI tools looks like:
@@ -4436,7 +4824,13 @@ def _bedrock_tools_pt(tools: List) -> List[BedrockToolBlock]:
tool_block_list: List[BedrockToolBlock] = []
for tool in tools:
- # Handle regular function tools
+ # Check if tool is already a BedrockToolBlock (e.g., systemTool for Nova grounding)
+ if _is_bedrock_tool_block(tool):
+ # Already a BedrockToolBlock, pass it through
+ tool_block_list.append(tool) # type: ignore
+ continue
+
+ # Handle regular OpenAI-style function tools
parameters = tool.get("function", {}).get(
"parameters", {"type": "object", "properties": {}}
)
diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.py
index 5d0bedb776d..7137a4e4222 100644
--- a/litellm/litellm_core_utils/prompt_templates/image_handling.py
+++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py
@@ -31,15 +31,19 @@ def _process_image_response(response: Response, url: str) -> str:
f"Error: Image size ({size_mb:.2f}MB) exceeds maximum allowed size ({MAX_IMAGE_URL_DOWNLOAD_SIZE_MB}MB). url={url}"
)
- image_bytes = response.content
+ # Stream download with size checking to prevent downloading huge files
+ max_bytes = int(MAX_IMAGE_URL_DOWNLOAD_SIZE_MB * 1024 * 1024)
+ image_bytes = bytearray()
+ bytes_downloaded = 0
- # Check actual size after download if Content-Length was not available
- if content_length is None:
- size_mb = len(image_bytes) / (1024 * 1024)
- if size_mb > MAX_IMAGE_URL_DOWNLOAD_SIZE_MB:
+ for chunk in response.iter_bytes(chunk_size=8192):
+ bytes_downloaded += len(chunk)
+ if bytes_downloaded > max_bytes:
+ size_mb = bytes_downloaded / (1024 * 1024)
raise litellm.ImageFetchError(
f"Error: Image size ({size_mb:.2f}MB) exceeds maximum allowed size ({MAX_IMAGE_URL_DOWNLOAD_SIZE_MB}MB). url={url}"
)
+ image_bytes.extend(chunk)
base64_image = base64.b64encode(image_bytes).decode("utf-8")
diff --git a/litellm/litellm_core_utils/redact_messages.py b/litellm/litellm_core_utils/redact_messages.py
index 0effed3db70..ad68f3851a8 100644
--- a/litellm/litellm_core_utils/redact_messages.py
+++ b/litellm/litellm_core_utils/redact_messages.py
@@ -9,6 +9,7 @@
import asyncio
import copy
+import inspect
from typing import TYPE_CHECKING, Any, Optional
import litellm
@@ -101,8 +102,8 @@ def perform_redaction(model_call_details: dict, result):
# Redact result
if result is not None:
# Check if result is a coroutine, async generator, or other async object - these cannot be deepcopied
- if (asyncio.iscoroutine(result) or
- asyncio.iscoroutinefunction(result) or
+ if (asyncio.iscoroutine(result) or
+ inspect.iscoroutinefunction(result) or
hasattr(result, '__aiter__') or # async generator
hasattr(result, '__anext__')): # async iterator
# For async objects, return a simple redacted response without deepcopy
@@ -130,45 +131,55 @@ def perform_redaction(model_call_details: dict, result):
def should_redact_message_logging(model_call_details: dict) -> bool:
"""
Determine if message logging should be redacted.
+
+ Priority order:
+ 1. Dynamic parameter (turn_off_message_logging in request)
+ 2. Headers (litellm-disable-message-redaction / litellm-enable-message-redaction)
+ 3. Global setting (litellm.turn_off_message_logging)
"""
litellm_params = model_call_details.get("litellm_params", {})
metadata_field = get_metadata_variable_name_from_kwargs(litellm_params)
metadata = litellm_params.get(metadata_field, {})
-
- # Get headers from the metadata
- request_headers = metadata.get("headers", {}) if isinstance(metadata, dict) else {}
+ if not isinstance(metadata, dict):
+ # Fall back: litellm_metadata was None, try metadata
+ metadata = litellm_params.get("metadata", {})
+ if not isinstance(metadata, dict):
+ metadata = {}
- possible_request_headers = [
+ # Get headers from the metadata
+ request_headers = metadata.get("headers", {})
+
+ # Check for headers that explicitly control redaction
+ if request_headers and bool(
+ request_headers.get("litellm-disable-message-redaction", False)
+ ):
+ # User explicitly disabled redaction via header
+ return False
+
+ possible_enable_headers = [
"litellm-enable-message-redaction", # old header. maintain backwards compatibility
"x-litellm-enable-message-redaction", # new header
]
is_redaction_enabled_via_header = False
- for header in possible_request_headers:
+ for header in possible_enable_headers:
if bool(request_headers.get(header, False)):
is_redaction_enabled_via_header = True
break
- # check if user opted out of logging message/response to callbacks
- if (
- litellm.turn_off_message_logging is not True
- and is_redaction_enabled_via_header is not True
- and _get_turn_off_message_logging_from_dynamic_params(model_call_details)
- is not True
- ):
- return False
-
- if request_headers and bool(
- request_headers.get("litellm-disable-message-redaction", False)
- ):
- return False
-
- # user has OPTED OUT of message redaction
- if _get_turn_off_message_logging_from_dynamic_params(model_call_details) is False:
- return False
-
- return True
+ # Priority 1: Check dynamic parameter first (if explicitly set)
+ dynamic_turn_off = _get_turn_off_message_logging_from_dynamic_params(model_call_details)
+ if dynamic_turn_off is not None:
+ # Dynamic parameter is explicitly set, use it
+ return dynamic_turn_off
+
+ # Priority 2: Check if header explicitly enables redaction
+ if is_redaction_enabled_via_header:
+ return True
+
+ # Priority 3: Fall back to global setting
+ return litellm.turn_off_message_logging is True
def redact_message_input_output_from_logging(
diff --git a/litellm/litellm_core_utils/safe_json_dumps.py b/litellm/litellm_core_utils/safe_json_dumps.py
index 8b50e41a795..051aa2f27a5 100644
--- a/litellm/litellm_core_utils/safe_json_dumps.py
+++ b/litellm/litellm_core_utils/safe_json_dumps.py
@@ -1,6 +1,8 @@
import json
from typing import Any, Union
+from pydantic import BaseModel
+
from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH
@@ -41,6 +43,11 @@ def safe_dumps(data: Any, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> str:
result = sorted([_serialize(item, seen, depth + 1) for item in obj])
seen.remove(id(obj))
return result
+ elif isinstance(obj, BaseModel):
+ dumped = obj.model_dump()
+ result = _serialize(dumped, seen, depth + 1)
+ seen.remove(id(obj))
+ return result
else:
# Fall back to string conversion for non-serializable objects.
try:
@@ -49,4 +56,4 @@ def safe_dumps(data: Any, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> str:
return "Unserializable Object"
safe_data = _serialize(data, set(), 0)
- return json.dumps(safe_data, default=str)
\ No newline at end of file
+ return json.dumps(safe_data, default=str)
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index 53252df0a28..76c7246b87e 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -1,6 +1,6 @@
import base64
import time
-from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast
from litellm.types.llms.openai import (
ChatCompletionAssistantContentValue,
@@ -326,10 +326,22 @@ class ChunkProcessor:
thinking_blocks: List[
Union["ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"]
] = []
- combined_thinking_text: Optional[str] = None
- data: Optional[str] = None
- signature: Optional[str] = None
- type: Literal["thinking", "redacted_thinking"] = "thinking"
+ current_thinking_text_parts: List[str] = []
+ current_signature: Optional[str] = None
+
+ def _flush_thinking_block() -> None:
+ nonlocal current_thinking_text_parts, current_signature
+ if len(current_thinking_text_parts) > 0 and current_signature:
+ thinking_blocks.append(
+ ChatCompletionThinkingBlock(
+ type="thinking",
+ thinking="".join(current_thinking_text_parts),
+ signature=current_signature,
+ )
+ )
+ current_thinking_text_parts = []
+ current_signature = None
+
for chunk in chunks:
choices = chunk["choices"]
for choice in choices:
@@ -339,33 +351,25 @@ class ChunkProcessor:
for thinking_block in thinking:
thinking_type = thinking_block.get("type", None)
if thinking_type and thinking_type == "redacted_thinking":
- type = "redacted_thinking"
- data = thinking_block.get("data", None)
+ _flush_thinking_block()
+ redacted_data = thinking_block.get("data", None)
+ if redacted_data:
+ thinking_blocks.append(
+ ChatCompletionRedactedThinkingBlock(
+ type="redacted_thinking",
+ data=redacted_data,
+ )
+ )
else:
- type = "thinking"
thinking_text = thinking_block.get("thinking", None)
if thinking_text:
- if combined_thinking_text is None:
- combined_thinking_text = ""
-
- combined_thinking_text += thinking_text
+ current_thinking_text_parts.append(thinking_text)
signature = thinking_block.get("signature", None)
+ if signature:
+ current_signature = signature
+ _flush_thinking_block()
- if combined_thinking_text and type == "thinking" and signature:
- thinking_blocks.append(
- ChatCompletionThinkingBlock(
- type=type,
- thinking=combined_thinking_text,
- signature=signature,
- )
- )
- elif data and type == "redacted_thinking":
- thinking_blocks.append(
- ChatCompletionRedactedThinkingBlock(
- type=type,
- data=data,
- )
- )
+ _flush_thinking_block()
if len(thinking_blocks) > 0:
return thinking_blocks
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index 3304759f749..46e95304cb7 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -2,6 +2,7 @@ import asyncio
import collections.abc
import datetime
import json
+import logging
import threading
import time
import traceback
@@ -435,7 +436,7 @@ class CustomStreamWrapper:
def handle_openai_chat_completion_chunk(self, chunk):
try:
- print_verbose(f"\nRaw OpenAI Chunk\n{chunk}\n")
+
str_line = chunk
text = ""
is_finished = False
@@ -485,7 +486,7 @@ class CustomStreamWrapper:
def handle_azure_text_completion_chunk(self, chunk):
try:
- print_verbose(f"\nRaw OpenAI Chunk\n{chunk}\n")
+
text = ""
is_finished = False
finish_reason = None
@@ -506,7 +507,7 @@ class CustomStreamWrapper:
def handle_openai_text_completion_chunk(self, chunk):
try:
- print_verbose(f"\nRaw OpenAI Chunk\n{chunk}\n")
+
text = ""
is_finished = False
finish_reason = None
@@ -870,9 +871,6 @@ class CustomStreamWrapper:
preserve_upstream_non_openai_attributes,
)
- print_verbose(
- f"completion_obj: {completion_obj}, model_response.choices[0]: {model_response.choices[0]}, response_obj: {response_obj}"
- )
is_chunk_non_empty = self.is_chunk_non_empty(
completion_obj, model_response, response_obj
)
@@ -899,11 +897,9 @@ class CustomStreamWrapper:
choice_json.pop(
"finish_reason", None
) # for mistral etc. which return a value in their last chunk (not-openai compatible).
- print_verbose(f"choice_json: {choice_json}")
choices.append(StreamingChoices(**choice_json))
except Exception:
choices.append(StreamingChoices())
- print_verbose(f"choices in streaming: {choices}")
setattr(model_response, "choices", choices)
else:
return
@@ -921,9 +917,11 @@ class CustomStreamWrapper:
)
model_response = self.strip_role_from_delta(model_response)
- verbose_logger.debug(
- f"model_response.choices[0].delta inside is_chunk_non_empty: {model_response.choices[0].delta}"
- )
+ if verbose_logger.isEnabledFor(logging.DEBUG):
+ verbose_logger.debug(
+ "model_response.choices[0].delta: %s",
+ model_response.choices[0].delta,
+ )
else:
## else
completion_obj["content"] = model_response_str
@@ -1370,9 +1368,6 @@ class CustomStreamWrapper:
)
model_response.model = self.model
- print_verbose(
- f"model_response finish reason 3: {self.received_finish_reason}; response_obj={response_obj}"
- )
## FUNCTION CALL PARSING
original_chunk = (
response_obj.get("original_chunk") if response_obj is not None else None
@@ -1432,7 +1427,6 @@ class CustomStreamWrapper:
):
t.function.arguments = ""
_json_delta = delta.model_dump()
- print_verbose(f"_json_delta: {_json_delta}")
if "role" not in _json_delta or _json_delta["role"] is None:
_json_delta[
"role"
@@ -1466,11 +1460,7 @@ class CustomStreamWrapper:
if original_chunk.choices[0].delta is None
else dict(original_chunk.choices[0].delta)
)
- print_verbose(f"original delta: {delta}")
model_response.choices[0].delta = Delta(**delta)
- print_verbose(
- f"new delta: {model_response.choices[0].delta}"
- )
except Exception:
model_response.choices[0].delta = Delta()
else:
@@ -1480,11 +1470,6 @@ class CustomStreamWrapper:
):
return model_response
return
- print_verbose(
- f"model_response.choices[0].delta: {model_response.choices[0].delta}; completion_obj: {completion_obj}"
- )
- print_verbose(f"self.sent_first_chunk: {self.sent_first_chunk}")
-
## CHECK FOR TOOL USE
if "tool_calls" in completion_obj and len(completion_obj["tool_calls"]) > 0:
@@ -1571,6 +1556,50 @@ class CustomStreamWrapper:
)
return chunk
+ def _add_mcp_list_tools_to_first_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream:
+ """
+ Add mcp_list_tools from _hidden_params to the first chunk's delta.provider_specific_fields.
+
+ This method checks if MCP metadata with mcp_list_tools is stored in _hidden_params
+ and adds it to the first chunk's delta.provider_specific_fields.
+ """
+ try:
+ # Check if MCP metadata should be added to first chunk
+ if not hasattr(self, "_hidden_params") or not self._hidden_params:
+ return chunk
+
+ mcp_metadata = self._hidden_params.get("mcp_metadata")
+ if not mcp_metadata or not isinstance(mcp_metadata, dict):
+ return chunk
+
+ # Only add mcp_list_tools to first chunk (not tool_calls or tool_results)
+ mcp_list_tools = mcp_metadata.get("mcp_list_tools")
+ if not mcp_list_tools:
+ return chunk
+
+ # Add mcp_list_tools to delta.provider_specific_fields
+ if hasattr(chunk, "choices") and chunk.choices:
+ for choice in chunk.choices:
+ if isinstance(choice, StreamingChoices) and hasattr(choice, "delta") and choice.delta:
+ # Get existing provider_specific_fields or create new dict
+ provider_fields = (
+ getattr(choice.delta, "provider_specific_fields", None) or {}
+ )
+
+ # Add only mcp_list_tools to first chunk
+ provider_fields["mcp_list_tools"] = mcp_list_tools
+
+ # Set the provider_specific_fields
+ setattr(choice.delta, "provider_specific_fields", provider_fields)
+
+ except Exception as e:
+ from litellm._logging import verbose_logger
+ verbose_logger.exception(
+ f"Error adding MCP list tools to first chunk: {str(e)}"
+ )
+
+ return chunk
+
def _add_mcp_metadata_to_final_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream:
"""
Add MCP metadata from _hidden_params to the final chunk's delta.provider_specific_fields.
@@ -1727,6 +1756,12 @@ class CustomStreamWrapper:
)
# HANDLE STREAM OPTIONS
self.chunks.append(response)
+
+ # Add mcp_list_tools to first chunk if present
+ if not self.sent_first_chunk:
+ response = self._add_mcp_list_tools_to_first_chunk(response)
+ self.sent_first_chunk = True
+
if hasattr(
response, "usage"
): # remove usage from chunk, only send on final chunk
@@ -1865,18 +1900,9 @@ class CustomStreamWrapper:
and len(chunk.parts) == 0
):
continue
- # chunk_creator() does logging/stream chunk building. We need to let it know its being called in_async_func, so we don't double add chunks.
- # __anext__ also calls async_success_handler, which does logging
- verbose_logger.debug(
- f"PROCESSED ASYNC CHUNK PRE CHUNK CREATOR: {chunk}"
- )
-
processed_chunk: Optional[ModelResponseStream] = self.chunk_creator(
chunk=chunk
)
- verbose_logger.debug(
- f"PROCESSED ASYNC CHUNK POST CHUNK CREATOR: {processed_chunk}"
- )
if processed_chunk is None:
continue
@@ -1893,26 +1919,28 @@ class CustomStreamWrapper:
self.rules.post_call_rules(
input=self.response_uptil_now, model=self.model
)
- self.chunks.append(processed_chunk)
- if hasattr(
- processed_chunk, "usage"
- ): # remove usage from chunk, only send on final chunk
- # Convert the object to a dictionary
- obj_dict = processed_chunk.model_dump()
+ # Store a shallow copy so usage stripping below
+ # does not mutate the stored chunk.
+ self.chunks.append(processed_chunk.model_copy())
- # Remove an attribute (e.g., 'attr2')
- if "usage" in obj_dict:
- del obj_dict["usage"]
-
- # Create a new object without the removed attribute
- processed_chunk = self.model_response_creator(chunk=obj_dict)
+ # Add mcp_list_tools to first chunk if present
+ if not self.sent_first_chunk:
+ processed_chunk = self._add_mcp_list_tools_to_first_chunk(processed_chunk)
+ self.sent_first_chunk = True
+ if (
+ hasattr(processed_chunk, "usage")
+ and getattr(processed_chunk, "usage", None) is not None
+ ):
+ # Strip usage from the outgoing chunk so
+ # model_dump_json(exclude_none=True) drops it.
+ # The copy in self.chunks retains usage for
+ # calculate_total_usage().
+ processed_chunk.usage = None # type: ignore
is_empty = is_model_response_stream_empty(
model_response=cast(ModelResponseStream, processed_chunk)
)
-
if is_empty:
continue
- print_verbose(f"final returned processed chunk: {processed_chunk}")
# add usage as hidden param
if self.sent_last_chunk is True and self.stream_options is None:
@@ -1927,7 +1955,7 @@ class CustomStreamWrapper:
)
)
# Add MCP metadata to final chunk if present (after hooks)
- processed_chunk = self._add_mcp_metadata_to_final_chunk(processed_chunk)
+ processed_chunk = self._add_mcp_metadata_to_final_chunk(processed_chunk) # type: ignore[reportArgumentType]
return processed_chunk
raise StopAsyncIteration
@@ -1941,13 +1969,9 @@ class CustomStreamWrapper:
else:
chunk = next(self.completion_stream)
if chunk is not None and chunk != b"":
- print_verbose(f"PROCESSED CHUNK PRE CHUNK CREATOR: {chunk}")
processed_chunk: Optional[
ModelResponseStream
] = self.chunk_creator(chunk=chunk)
- print_verbose(
- f"PROCESSED CHUNK POST CHUNK CREATOR: {processed_chunk}"
- )
if processed_chunk is None:
continue
@@ -2138,7 +2162,7 @@ def calculate_total_usage(chunks: List[ModelResponse]) -> Usage:
prompt_tokens: int = 0
completion_tokens: int = 0
for chunk in chunks:
- if "usage" in chunk:
+ if "usage" in chunk and chunk["usage"] is not None:
if "prompt_tokens" in chunk["usage"]:
prompt_tokens = chunk["usage"].get("prompt_tokens", 0) or 0
if "completion_tokens" in chunk["usage"]:
diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py
index a99bd1cd0f3..6b9e51034c0 100644
--- a/litellm/litellm_core_utils/token_counter.py
+++ b/litellm/litellm_core_utils/token_counter.py
@@ -706,7 +706,7 @@ def _count_content_list(
if isinstance(c, str):
num_tokens += count_function(c)
elif c["type"] == "text":
- num_tokens += count_function(c.get("text", ""))
+ num_tokens += count_function(str(c.get("text", "")))
elif c["type"] == "image_url":
image_url = c.get("image_url")
num_tokens += _count_image_tokens(
@@ -722,7 +722,7 @@ def _count_content_list(
elif c["type"] == "thinking":
# Claude extended thinking content block
# Count the thinking text and skip signature (opaque signature blob)
- thinking_text = c.get("thinking", "")
+ thinking_text = str(c.get("thinking", ""))
if thinking_text:
num_tokens += count_function(thinking_text)
else:
diff --git a/litellm/llms/a2a/__init__.py b/litellm/llms/a2a/__init__.py
new file mode 100644
index 00000000000..043efa5e8bf
--- /dev/null
+++ b/litellm/llms/a2a/__init__.py
@@ -0,0 +1,6 @@
+"""
+A2A (Agent-to-Agent) Protocol Provider for LiteLLM
+"""
+from .chat.transformation import A2AConfig
+
+__all__ = ["A2AConfig"]
diff --git a/litellm/llms/a2a/chat/__init__.py b/litellm/llms/a2a/chat/__init__.py
new file mode 100644
index 00000000000..76bf4dd71d9
--- /dev/null
+++ b/litellm/llms/a2a/chat/__init__.py
@@ -0,0 +1,6 @@
+"""
+A2A Chat Completion Implementation
+"""
+from .transformation import A2AConfig
+
+__all__ = ["A2AConfig"]
diff --git a/litellm/llms/a2a/chat/guardrail_translation/README.md b/litellm/llms/a2a/chat/guardrail_translation/README.md
new file mode 100644
index 00000000000..1e18f5cda3a
--- /dev/null
+++ b/litellm/llms/a2a/chat/guardrail_translation/README.md
@@ -0,0 +1,155 @@
+# A2A Protocol Guardrail Translation Handler
+
+Handler for processing A2A (Agent-to-Agent) Protocol messages with guardrails.
+
+## Overview
+
+This handler processes A2A JSON-RPC 2.0 input/output by:
+1. Extracting text from message parts (`kind: "text"`)
+2. Applying guardrails to text content
+3. Mapping guardrailed text back to original structure
+
+## A2A Protocol Format
+
+### Input Format (JSON-RPC 2.0)
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": "request-id",
+ "method": "message/send",
+ "params": {
+ "message": {
+ "kind": "message",
+ "messageId": "...",
+ "role": "user",
+ "parts": [
+ {"kind": "text", "text": "Hello, my SSN is 123-45-6789"}
+ ]
+ },
+ "metadata": {
+ "guardrails": ["block-ssn"]
+ }
+ }
+}
+```
+
+### Output Formats
+
+The handler supports multiple A2A response formats:
+
+**Direct message:**
+```json
+{
+ "result": {
+ "kind": "message",
+ "parts": [{"kind": "text", "text": "Response text"}]
+ }
+}
+```
+
+**Nested message:**
+```json
+{
+ "result": {
+ "message": {
+ "parts": [{"kind": "text", "text": "Response text"}]
+ }
+ }
+}
+```
+
+**Task with artifacts:**
+```json
+{
+ "result": {
+ "kind": "task",
+ "artifacts": [
+ {"parts": [{"kind": "text", "text": "Artifact text"}]}
+ ]
+ }
+}
+```
+
+**Task with status message:**
+```json
+{
+ "result": {
+ "kind": "task",
+ "status": {
+ "message": {
+ "parts": [{"kind": "text", "text": "Status message"}]
+ }
+ }
+ }
+}
+```
+
+**Streaming artifact-update:**
+```json
+{
+ "result": {
+ "kind": "artifact-update",
+ "artifact": {
+ "parts": [{"kind": "text", "text": "Streaming text"}]
+ }
+ }
+}
+```
+
+## Usage
+
+The handler is automatically discovered and applied when guardrails are used with A2A endpoints.
+
+### Via LiteLLM Proxy
+
+```bash
+curl -X POST 'http://localhost:4000/a2a/my-agent' \
+-H 'Content-Type: application/json' \
+-H 'Authorization: Bearer your-api-key' \
+-d '{
+ "jsonrpc": "2.0",
+ "id": "1",
+ "method": "message/send",
+ "params": {
+ "message": {
+ "kind": "message",
+ "messageId": "msg-1",
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Hello, my SSN is 123-45-6789"}]
+ },
+ "metadata": {
+ "guardrails": ["block-ssn"]
+ }
+ }
+}'
+```
+
+### Specifying Guardrails
+
+Guardrails can be specified in the A2A request via the `metadata.guardrails` field:
+
+```json
+{
+ "params": {
+ "message": {...},
+ "metadata": {
+ "guardrails": ["block-ssn", "pii-filter"]
+ }
+ }
+}
+```
+
+## Extension
+
+Override these methods to customize behavior:
+
+- `_extract_texts_from_result()`: Custom text extraction from A2A responses
+- `_extract_texts_from_parts()`: Custom text extraction from message parts
+- `_apply_text_to_path()`: Custom application of guardrailed text
+
+## Call Types
+
+This handler is registered for:
+- `CallTypes.send_message`: Synchronous A2A message sending
+- `CallTypes.asend_message`: Asynchronous A2A message sending
diff --git a/litellm/llms/a2a/chat/guardrail_translation/__init__.py b/litellm/llms/a2a/chat/guardrail_translation/__init__.py
new file mode 100644
index 00000000000..13c20677485
--- /dev/null
+++ b/litellm/llms/a2a/chat/guardrail_translation/__init__.py
@@ -0,0 +1,11 @@
+"""A2A Protocol handler for Unified Guardrails."""
+
+from litellm.llms.a2a.chat.guardrail_translation.handler import A2AGuardrailHandler
+from litellm.types.utils import CallTypes
+
+guardrail_translation_mappings = {
+ CallTypes.send_message: A2AGuardrailHandler,
+ CallTypes.asend_message: A2AGuardrailHandler,
+}
+
+__all__ = ["guardrail_translation_mappings"]
diff --git a/litellm/llms/a2a/chat/guardrail_translation/handler.py b/litellm/llms/a2a/chat/guardrail_translation/handler.py
new file mode 100644
index 00000000000..fbd1da749c2
--- /dev/null
+++ b/litellm/llms/a2a/chat/guardrail_translation/handler.py
@@ -0,0 +1,428 @@
+"""
+A2A Protocol Handler for Unified Guardrails
+
+This module provides guardrail translation support for A2A (Agent-to-Agent) Protocol.
+It handles both JSON-RPC 2.0 input requests and output responses, extracting text
+from message parts and applying guardrails.
+
+A2A Protocol Format:
+- Input: JSON-RPC 2.0 with params.message.parts containing text parts
+- Output: JSON-RPC 2.0 with result containing message/artifact parts
+"""
+
+import json
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+
+from litellm._logging import verbose_proxy_logger
+from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.utils import GenericGuardrailAPIInputs
+
+if TYPE_CHECKING:
+ from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.proxy._types import UserAPIKeyAuth
+
+
+class A2AGuardrailHandler(BaseTranslation):
+ """
+ Handler for processing A2A Protocol messages with guardrails.
+
+ This class provides methods to:
+ 1. Process input messages (pre-call hook) - extracts text from A2A message parts
+ 2. Process output responses (post-call hook) - extracts text from A2A response parts
+
+ A2A Message Format:
+ - Input: params.message.parts[].text (where kind == "text")
+ - Output: result.message.parts[].text or result.artifacts[].parts[].text
+ """
+
+ async def process_input_messages(
+ self,
+ data: dict,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ ) -> Any:
+ """
+ Process A2A input messages by applying guardrails to text content.
+
+ Extracts text from A2A message parts and applies guardrails.
+
+ Args:
+ data: The A2A JSON-RPC 2.0 request data
+ guardrail_to_apply: The guardrail instance to apply
+ litellm_logging_obj: Optional logging object
+
+ Returns:
+ Modified data with guardrails applied to text content
+ """
+ # A2A request format: { "params": { "message": { "parts": [...] } } }
+ params = data.get("params", {})
+ message = params.get("message", {})
+ parts = message.get("parts", [])
+
+ if not parts:
+ verbose_proxy_logger.debug("A2A: No parts in message, skipping guardrail")
+ return data
+
+ texts_to_check: List[str] = []
+ text_part_indices: List[int] = [] # Track which parts contain text
+
+ # Step 1: Extract text from all text parts
+ for part_idx, part in enumerate(parts):
+ if part.get("kind") == "text":
+ text = part.get("text", "")
+ if text:
+ texts_to_check.append(text)
+ text_part_indices.append(part_idx)
+
+ # Step 2: Apply guardrail to all texts in batch
+ if texts_to_check:
+ inputs = GenericGuardrailAPIInputs(texts=texts_to_check)
+
+ # Pass the structured A2A message to guardrails
+ inputs["structured_messages"] = [message]
+
+ # Include agent model info if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
+
+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data=data,
+ input_type="request",
+ logging_obj=litellm_logging_obj,
+ )
+
+ guardrailed_texts = guardrailed_inputs.get("texts", [])
+
+ # Step 3: Apply guardrailed text back to original parts
+ if guardrailed_texts and len(guardrailed_texts) == len(text_part_indices):
+ for task_idx, part_idx in enumerate(text_part_indices):
+ parts[part_idx]["text"] = guardrailed_texts[task_idx]
+
+ verbose_proxy_logger.debug("A2A: Processed input message: %s", message)
+
+ return data
+
+ async def process_output_response(
+ self,
+ response: Any,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ user_api_key_dict: Optional["UserAPIKeyAuth"] = None,
+ ) -> Any:
+ """
+ Process A2A output response by applying guardrails to text content.
+
+ Handles multiple A2A response formats:
+ - Direct message: {"result": {"kind": "message", "parts": [...]}}
+ - Nested message: {"result": {"message": {"parts": [...]}}}
+ - Task with artifacts: {"result": {"kind": "task", "artifacts": [{"parts": [...]}]}}
+ - Task with status message: {"result": {"kind": "task", "status": {"message": {"parts": [...]}}}}
+
+ Args:
+ response: A2A JSON-RPC 2.0 response dict or object
+ guardrail_to_apply: The guardrail instance to apply
+ litellm_logging_obj: Optional logging object
+ user_api_key_dict: User API key metadata
+
+ Returns:
+ Modified response with guardrails applied to text content
+ """
+ # Handle both dict and Pydantic model responses
+ if hasattr(response, "model_dump"):
+ response_dict = response.model_dump()
+ is_pydantic = True
+ elif isinstance(response, dict):
+ response_dict = response
+ is_pydantic = False
+ else:
+ verbose_proxy_logger.warning(
+ "A2A: Unknown response type %s, skipping guardrail", type(response)
+ )
+ return response
+
+ result = response_dict.get("result", {})
+ if not result or not isinstance(result, dict):
+ verbose_proxy_logger.debug("A2A: No result in response, skipping guardrail")
+ return response
+
+ # Find all text-containing parts in the response
+ texts_to_check: List[str] = []
+ # Each mapping is (path_to_parts_list, part_index)
+ # path_to_parts_list is a tuple of keys to navigate to the parts list
+ task_mappings: List[Tuple[Tuple[str, ...], int]] = []
+
+ # Extract texts from all possible locations
+ self._extract_texts_from_result(
+ result=result,
+ texts_to_check=texts_to_check,
+ task_mappings=task_mappings,
+ )
+
+ if not texts_to_check:
+ verbose_proxy_logger.debug("A2A: No text content in response")
+ return response
+
+ # Step 2: Apply guardrail to all texts in batch
+ # Create a request_data dict with response info and user API key metadata
+ request_data: dict = {"response": response_dict}
+
+ # Add user API key metadata with prefixed keys
+ user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)
+ if user_metadata:
+ request_data["litellm_metadata"] = user_metadata
+
+ inputs = GenericGuardrailAPIInputs(texts=texts_to_check)
+
+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data=request_data,
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+
+ guardrailed_texts = guardrailed_inputs.get("texts", [])
+
+ # Step 3: Apply guardrailed text back to original response
+ if guardrailed_texts and len(guardrailed_texts) == len(task_mappings):
+ for task_idx, (path, part_idx) in enumerate(task_mappings):
+ self._apply_text_to_path(
+ result=result,
+ path=path,
+ part_idx=part_idx,
+ text=guardrailed_texts[task_idx],
+ )
+
+ verbose_proxy_logger.debug("A2A: Processed output response")
+
+ # Update the original response
+ if is_pydantic:
+ # For Pydantic models, we need to update the underlying dict
+ # and the model will reflect the changes
+ response_dict["result"] = result
+ return response
+ else:
+ response["result"] = result
+ return response
+
+ async def process_output_streaming_response(
+ self,
+ responses_so_far: List[Any],
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ user_api_key_dict: Optional["UserAPIKeyAuth"] = None,
+ ) -> List[Any]:
+ """
+ Process A2A streaming output by applying guardrails to accumulated text.
+
+ responses_so_far can be a list of JSON-RPC 2.0 objects (dict or NDJSON str), e.g.:
+ - task with history, status-update, artifact-update (with result.artifact.parts),
+ - then status-update (final). Text is extracted from result.artifact.parts,
+ result.message.parts, result.parts, etc., concatenated in order, guardrailed once,
+ then the combined guardrailed text is written into the first chunk that had text
+ and all other text parts in other chunks are cleared (in-place).
+ """
+ from litellm.llms.a2a.common_utils import extract_text_from_a2a_response
+
+ # Parse each item; keep alignment with responses_so_far (None where unparseable)
+ parsed: List[Optional[Dict[str, Any]]] = [None] * len(responses_so_far)
+ for i, item in enumerate(responses_so_far):
+ if isinstance(item, dict):
+ obj = item
+ elif isinstance(item, str):
+ try:
+ obj = json.loads(item.strip())
+ except (json.JSONDecodeError, TypeError):
+ continue
+ else:
+ continue
+ if isinstance(obj.get("result"), dict):
+ parsed[i] = obj
+
+ valid_parsed = [(i, obj) for i, obj in enumerate(parsed) if obj is not None]
+ if not valid_parsed:
+ return responses_so_far
+
+ # Collect text from each chunk in order (by original index in responses_so_far)
+ text_parts: List[str] = []
+ chunk_indices_with_text: List[int] = [] # indices into valid_parsed
+ for idx, (orig_i, obj) in enumerate(valid_parsed):
+ t = extract_text_from_a2a_response(obj)
+ if t:
+ text_parts.append(t)
+ chunk_indices_with_text.append(orig_i)
+
+ combined_text = "".join(text_parts)
+ if not combined_text:
+ return responses_so_far
+
+ request_data: dict = {"responses_so_far": responses_so_far}
+ user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)
+ if user_metadata:
+ request_data["litellm_metadata"] = user_metadata
+
+ inputs = GenericGuardrailAPIInputs(texts=[combined_text])
+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data=request_data,
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ guardrailed_texts = guardrailed_inputs.get("texts", [])
+ if not guardrailed_texts:
+ return responses_so_far
+ guardrailed_text = guardrailed_texts[0]
+
+ # Find first chunk (by original index) that has text; put full guardrailed text there and clear rest
+ first_chunk_with_text: Optional[int] = (
+ chunk_indices_with_text[0] if chunk_indices_with_text else None
+ )
+
+ for orig_i, obj in valid_parsed:
+ result = obj.get("result", {})
+ if not isinstance(result, dict):
+ continue
+ texts_in_chunk: List[str] = []
+ mappings: List[Tuple[Tuple[str, ...], int]] = []
+ self._extract_texts_from_result(
+ result=result,
+ texts_to_check=texts_in_chunk,
+ task_mappings=mappings,
+ )
+ if not mappings:
+ continue
+ if orig_i == first_chunk_with_text:
+ # Put full guardrailed text in first text part; clear others
+ for task_idx, (path, part_idx) in enumerate(mappings):
+ text = guardrailed_text if task_idx == 0 else ""
+ self._apply_text_to_path(
+ result=result,
+ path=path,
+ part_idx=part_idx,
+ text=text,
+ )
+ else:
+ for path, part_idx in mappings:
+ self._apply_text_to_path(
+ result=result,
+ path=path,
+ part_idx=part_idx,
+ text="",
+ )
+
+ # Write back to responses_so_far where we had NDJSON strings
+ for i, item in enumerate(responses_so_far):
+ if isinstance(item, str) and parsed[i] is not None:
+ responses_so_far[i] = json.dumps(parsed[i]) + "\n"
+
+ return responses_so_far
+
+ def _extract_texts_from_result(
+ self,
+ result: Dict[str, Any],
+ texts_to_check: List[str],
+ task_mappings: List[Tuple[Tuple[str, ...], int]],
+ ) -> None:
+ """
+ Extract text from all possible locations in an A2A result.
+
+ Handles multiple response formats:
+ 1. Direct message with parts: {"parts": [...]}
+ 2. Nested message: {"message": {"parts": [...]}}
+ 3. Task with artifacts: {"artifacts": [{"parts": [...]}]}
+ 4. Task with status message: {"status": {"message": {"parts": [...]}}}
+ 5. Streaming artifact-update: {"artifact": {"parts": [...]}}
+ """
+ # Case 1: Direct parts in result (direct message)
+ if "parts" in result:
+ self._extract_texts_from_parts(
+ parts=result["parts"],
+ path=("parts",),
+ texts_to_check=texts_to_check,
+ task_mappings=task_mappings,
+ )
+
+ # Case 2: Nested message
+ message = result.get("message")
+ if message and isinstance(message, dict) and "parts" in message:
+ self._extract_texts_from_parts(
+ parts=message["parts"],
+ path=("message", "parts"),
+ texts_to_check=texts_to_check,
+ task_mappings=task_mappings,
+ )
+
+ # Case 3: Streaming artifact-update (singular artifact)
+ artifact = result.get("artifact")
+ if artifact and isinstance(artifact, dict) and "parts" in artifact:
+ self._extract_texts_from_parts(
+ parts=artifact["parts"],
+ path=("artifact", "parts"),
+ texts_to_check=texts_to_check,
+ task_mappings=task_mappings,
+ )
+
+ # Case 4: Task with status message
+ status = result.get("status", {})
+ if isinstance(status, dict):
+ status_message = status.get("message")
+ if (
+ status_message
+ and isinstance(status_message, dict)
+ and "parts" in status_message
+ ):
+ self._extract_texts_from_parts(
+ parts=status_message["parts"],
+ path=("status", "message", "parts"),
+ texts_to_check=texts_to_check,
+ task_mappings=task_mappings,
+ )
+
+ # Case 5: Task with artifacts (plural, array)
+ artifacts = result.get("artifacts", [])
+ if artifacts and isinstance(artifacts, list):
+ for artifact_idx, art in enumerate(artifacts):
+ if isinstance(art, dict) and "parts" in art:
+ self._extract_texts_from_parts(
+ parts=art["parts"],
+ path=("artifacts", str(artifact_idx), "parts"),
+ texts_to_check=texts_to_check,
+ task_mappings=task_mappings,
+ )
+
+ def _extract_texts_from_parts(
+ self,
+ parts: List[Dict[str, Any]],
+ path: Tuple[str, ...],
+ texts_to_check: List[str],
+ task_mappings: List[Tuple[Tuple[str, ...], int]],
+ ) -> None:
+ """Extract text from message parts."""
+ for part_idx, part in enumerate(parts):
+ if part.get("kind") == "text":
+ text = part.get("text", "")
+ if text:
+ texts_to_check.append(text)
+ task_mappings.append((path, part_idx))
+
+ def _apply_text_to_path(
+ self,
+ result: Dict[Union[str, int], Any],
+ path: Tuple[str, ...],
+ part_idx: int,
+ text: str,
+ ) -> None:
+ """Apply guardrailed text back to the specified path in the result."""
+ # Navigate to the parts list
+ current = result
+ for key in path:
+ if key.isdigit():
+ # Array index
+ current = current[int(key)]
+ else:
+ current = current[key]
+
+ # Update the text in the part
+ current[part_idx]["text"] = text
diff --git a/litellm/llms/a2a/chat/streaming_iterator.py b/litellm/llms/a2a/chat/streaming_iterator.py
new file mode 100644
index 00000000000..4b689414ddd
--- /dev/null
+++ b/litellm/llms/a2a/chat/streaming_iterator.py
@@ -0,0 +1,103 @@
+"""
+A2A Streaming Response Iterator
+"""
+from typing import Optional, Union
+
+from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
+from litellm.types.utils import GenericStreamingChunk, ModelResponseStream
+
+from ..common_utils import extract_text_from_a2a_response
+
+
+class A2AModelResponseIterator(BaseModelResponseIterator):
+ """
+ Iterator for parsing A2A streaming responses.
+
+ Converts A2A JSON-RPC streaming chunks to OpenAI-compatible format.
+ """
+
+ def __init__(
+ self,
+ streaming_response,
+ sync_stream: bool,
+ json_mode: Optional[bool] = False,
+ model: str = "a2a/agent",
+ ):
+ super().__init__(
+ streaming_response=streaming_response,
+ sync_stream=sync_stream,
+ json_mode=json_mode,
+ )
+ self.model = model
+
+ def chunk_parser(self, chunk: dict) -> Union[GenericStreamingChunk, ModelResponseStream]:
+ """
+ Parse A2A streaming chunk to OpenAI format.
+
+ A2A chunk format:
+ {
+ "jsonrpc": "2.0",
+ "id": "request-id",
+ "result": {
+ "message": {
+ "parts": [{"kind": "text", "text": "content"}]
+ }
+ }
+ }
+
+ Or for tasks:
+ {
+ "jsonrpc": "2.0",
+ "result": {
+ "kind": "task",
+ "status": {"state": "running"},
+ "artifacts": [{"parts": [{"kind": "text", "text": "content"}]}]
+ }
+ }
+ """
+ try:
+ # Extract text from A2A response
+ text = extract_text_from_a2a_response(chunk)
+
+ # Determine finish reason
+ finish_reason = self._get_finish_reason(chunk)
+
+ # Return generic streaming chunk
+ return GenericStreamingChunk(
+ text=text,
+ is_finished=bool(finish_reason),
+ finish_reason=finish_reason or "",
+ usage=None,
+ index=0,
+ tool_use=None,
+ )
+ except Exception:
+ # Return empty chunk on parse error
+ return GenericStreamingChunk(
+ text="",
+ is_finished=False,
+ finish_reason="",
+ usage=None,
+ index=0,
+ tool_use=None,
+ )
+
+ def _get_finish_reason(self, chunk: dict) -> Optional[str]:
+ """Extract finish reason from A2A chunk"""
+ result = chunk.get("result", {})
+
+ # Check for task completion
+ if isinstance(result, dict):
+ status = result.get("status", {})
+ if isinstance(status, dict):
+ state = status.get("state")
+ if state == "completed":
+ return "stop"
+ elif state == "failed":
+ return "stop" # Map failed state to 'stop' (valid finish_reason)
+
+ # Check for [DONE] marker
+ if chunk.get("done") is True:
+ return "stop"
+
+ return None
diff --git a/litellm/llms/a2a/chat/transformation.py b/litellm/llms/a2a/chat/transformation.py
new file mode 100644
index 00000000000..163cd5ab22e
--- /dev/null
+++ b/litellm/llms/a2a/chat/transformation.py
@@ -0,0 +1,370 @@
+"""
+A2A Protocol Transformation for LiteLLM
+"""
+import uuid
+from typing import Any, Dict, Iterator, List, Optional, Union
+
+import httpx
+
+from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
+from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException
+from litellm.types.llms.openai import AllMessageValues
+from litellm.types.utils import Choices, Message, ModelResponse
+
+from ..common_utils import (
+ A2AError,
+ convert_messages_to_prompt,
+ extract_text_from_a2a_response,
+)
+from .streaming_iterator import A2AModelResponseIterator
+
+
+class A2AConfig(BaseConfig):
+ """
+ Configuration for A2A (Agent-to-Agent) Protocol.
+
+ Handles transformation between OpenAI and A2A JSON-RPC 2.0 formats.
+ """
+
+ @staticmethod
+ def resolve_agent_config_from_registry(
+ model: str,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ headers: Optional[Dict[str, Any]],
+ optional_params: Dict[str, Any],
+ ) -> tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]:
+ """
+ Resolve agent configuration from registry if model format is "a2a/".
+
+ Extracts agent name from model string and looks up configuration in the
+ agent registry (if available in proxy context).
+
+ Args:
+ model: Model string (e.g., "a2a/my-agent")
+ api_base: Explicit api_base (takes precedence over registry)
+ api_key: Explicit api_key (takes precedence over registry)
+ headers: Explicit headers (takes precedence over registry)
+ optional_params: Dict to merge additional litellm_params into
+
+ Returns:
+ Tuple of (api_base, api_key, headers) with registry values filled in
+ """
+ # Extract agent name from model (e.g., "a2a/my-agent" -> "my-agent")
+ agent_name = model.split("/", 1)[1] if "/" in model else None
+
+ # Only lookup if agent name exists and some config is missing
+ if not agent_name or (api_base is not None and api_key is not None and headers is not None):
+ return api_base, api_key, headers
+
+ # Try registry lookup (only available in proxy context)
+ try:
+ from litellm.proxy.agent_endpoints.agent_registry import (
+ global_agent_registry,
+ )
+
+ agent = global_agent_registry.get_agent_by_name(agent_name)
+ if agent:
+ # Get api_base from agent card URL
+ if api_base is None and agent.agent_card_params:
+ api_base = agent.agent_card_params.get("url")
+
+ # Get api_key, headers, and other params from litellm_params
+ if agent.litellm_params:
+ if api_key is None:
+ api_key = agent.litellm_params.get("api_key")
+
+ if headers is None:
+ agent_headers = agent.litellm_params.get("headers")
+ if agent_headers:
+ headers = agent_headers
+
+ # Merge other litellm_params (timeout, max_retries, etc.)
+ for key, value in agent.litellm_params.items():
+ if key not in ["api_key", "api_base", "headers", "model"] and key not in optional_params:
+ optional_params[key] = value
+ except ImportError:
+ pass # Registry not available (not running in proxy context)
+
+ return api_base, api_key, headers
+
+ def get_supported_openai_params(self, model: str) -> List[str]:
+ """Return list of supported OpenAI parameters"""
+ return [
+ "stream",
+ "temperature",
+ "max_tokens",
+ "top_p",
+ ]
+
+ def map_openai_params(
+ self,
+ non_default_params: dict,
+ optional_params: dict,
+ model: str,
+ drop_params: bool,
+ ) -> dict:
+ """
+ Map OpenAI parameters to A2A parameters.
+
+ For A2A protocol, we need to map the stream parameter so
+ transform_request can determine which JSON-RPC method to use.
+ """
+ # Map stream parameter
+ for param, value in non_default_params.items():
+ if param == "stream" and value is True:
+ optional_params["stream"] = value
+
+ return optional_params
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ """
+ Validate environment and set headers for A2A requests.
+
+ Args:
+ headers: Request headers dict
+ model: Model name
+ messages: Messages list
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters
+ api_key: API key (optional for A2A)
+ api_base: API base URL
+
+ Returns:
+ Updated headers dict
+ """
+ # Ensure Content-Type is set to application/json for JSON-RPC 2.0
+ if "content-type" not in headers and "Content-Type" not in headers:
+ headers["Content-Type"] = "application/json"
+
+ # Add Authorization header if API key is provided
+ if api_key is not None:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ return headers
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ model: str,
+ optional_params: dict,
+ litellm_params: dict,
+ stream: Optional[bool] = None,
+ ) -> str:
+ """
+ Get the complete A2A agent endpoint URL.
+
+ A2A agents use JSON-RPC 2.0 at the base URL, not specific paths.
+ The method (message/send or message/stream) is specified in the
+ JSON-RPC request body, not in the URL.
+
+ Args:
+ api_base: Base URL of the A2A agent (e.g., "http://0.0.0.0:9999")
+ api_key: API key (not used for URL construction)
+ model: Model name (not used for A2A, agent determined by api_base)
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters
+ stream: Whether this is a streaming request (affects JSON-RPC method)
+
+ Returns:
+ Complete URL for the A2A endpoint (base URL)
+ """
+ if api_base is None:
+ raise ValueError("api_base is required for A2A provider")
+
+ # A2A uses JSON-RPC 2.0 at the base URL
+ # Remove trailing slash for consistency
+ return api_base.rstrip("/")
+
+ def transform_request(
+ self,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ headers: dict,
+ ) -> dict:
+ """
+ Transform OpenAI request to A2A JSON-RPC 2.0 format.
+
+ Args:
+ model: Model name
+ messages: List of OpenAI messages
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ A2A JSON-RPC 2.0 request dict
+ """
+ # Generate request ID
+ request_id = str(uuid.uuid4())
+
+ if not messages:
+ raise ValueError("At least one message is required for A2A completion")
+
+ # Convert all messages to maintain conversation history
+ # Use helper to format conversation with role prefixes
+ full_context = convert_messages_to_prompt(messages)
+
+ # Create single A2A message with full conversation context
+ a2a_message = {
+ "role": "user",
+ "parts": [{"kind": "text", "text": full_context}],
+ "messageId": str(uuid.uuid4()),
+ }
+
+ # Build JSON-RPC 2.0 request
+ # For A2A protocol, the method is "message/send" for non-streaming
+ # and "message/stream" for streaming
+ stream = optional_params.get("stream", False)
+ method = "message/stream" if stream else "message/send"
+
+ request_data = {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "method": method,
+ "params": {
+ "message": a2a_message
+ }
+ }
+
+ return request_data
+
+ def transform_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: ModelResponse,
+ logging_obj: Any,
+ request_data: dict,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ encoding: Any,
+ api_key: Optional[str] = None,
+ json_mode: Optional[bool] = None,
+ ) -> ModelResponse:
+ """
+ Transform A2A JSON-RPC 2.0 response to OpenAI format.
+
+ Args:
+ model: Model name
+ raw_response: HTTP response from A2A agent
+ model_response: Model response object to populate
+ logging_obj: Logging object
+ request_data: Original request data
+ messages: Original messages
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters
+ encoding: Encoding object
+ api_key: API key
+ json_mode: JSON mode flag
+
+ Returns:
+ Populated ModelResponse object
+ """
+ try:
+ response_json = raw_response.json()
+ except Exception as e:
+ raise A2AError(
+ status_code=raw_response.status_code,
+ message=f"Failed to parse A2A response: {str(e)}",
+ headers=dict(raw_response.headers),
+ )
+
+ # Check for JSON-RPC error
+ if "error" in response_json:
+ error = response_json["error"]
+ raise A2AError(
+ status_code=raw_response.status_code,
+ message=f"A2A error: {error.get('message', 'Unknown error')}",
+ headers=dict(raw_response.headers),
+ )
+
+ # Extract text from A2A response
+ text = extract_text_from_a2a_response(response_json)
+
+ # Populate model response
+ model_response.choices = [
+ Choices(
+ finish_reason="stop",
+ index=0,
+ message=Message(
+ content=text,
+ role="assistant",
+ ),
+ )
+ ]
+
+ # Set model
+ model_response.model = model
+
+ # Set ID from response
+ model_response.id = response_json.get("id", str(uuid.uuid4()))
+
+ return model_response
+
+ def get_model_response_iterator(
+ self,
+ streaming_response: Union[Iterator, Any],
+ sync_stream: bool,
+ json_mode: Optional[bool] = False,
+ ) -> BaseModelResponseIterator:
+ """
+ Get streaming iterator for A2A responses.
+
+ Args:
+ streaming_response: Streaming response iterator
+ sync_stream: Whether this is a sync stream
+ json_mode: JSON mode flag
+
+ Returns:
+ A2A streaming iterator
+ """
+ return A2AModelResponseIterator(
+ streaming_response=streaming_response,
+ sync_stream=sync_stream,
+ json_mode=json_mode,
+ )
+
+ def _openai_message_to_a2a_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Convert OpenAI message to A2A message format.
+
+ Args:
+ message: OpenAI message dict
+
+ Returns:
+ A2A message dict
+ """
+ content = message.get("content", "")
+ role = message.get("role", "user")
+
+ return {
+ "role": role,
+ "parts": [{"kind": "text", "text": str(content)}],
+ "messageId": str(uuid.uuid4()),
+ }
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]
+ ) -> BaseLLMException:
+ """Return appropriate error class for A2A errors"""
+ # Convert headers to dict if needed
+ headers_dict = dict(headers) if isinstance(headers, httpx.Headers) else headers
+ return A2AError(
+ status_code=status_code,
+ message=error_message,
+ headers=headers_dict,
+ )
diff --git a/litellm/llms/a2a/common_utils.py b/litellm/llms/a2a/common_utils.py
new file mode 100644
index 00000000000..116e1205409
--- /dev/null
+++ b/litellm/llms/a2a/common_utils.py
@@ -0,0 +1,152 @@
+"""
+Common utilities for A2A (Agent-to-Agent) Protocol
+"""
+from typing import Any, Dict, List
+
+from pydantic import BaseModel
+
+from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ convert_content_list_to_str,
+)
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.types.llms.openai import AllMessageValues
+
+
+class A2AError(BaseLLMException):
+ """Base exception for A2A protocol errors"""
+
+ def __init__(
+ self,
+ status_code: int,
+ message: str,
+ headers: Dict[str, Any] = {},
+ ):
+ super().__init__(
+ status_code=status_code,
+ message=message,
+ headers=headers,
+ )
+
+
+def convert_messages_to_prompt(messages: List[AllMessageValues]) -> str:
+ """
+ Convert OpenAI messages to a single prompt string for A2A agent.
+
+ Formats each message as "{role}: {content}" and joins with newlines
+ to preserve conversation history. Handles both string and list content.
+
+ Args:
+ messages: List of OpenAI-format messages
+
+ Returns:
+ Formatted prompt string with full conversation context
+ """
+ conversation_parts = []
+ for msg in messages:
+ # Use LiteLLM's helper to extract text from content (handles both str and list)
+ content_text = convert_content_list_to_str(message=msg)
+
+ # Get role
+ if isinstance(msg, BaseModel):
+ role = msg.model_dump().get("role", "user")
+ elif isinstance(msg, dict):
+ role = msg.get("role", "user")
+ else:
+ role = dict(msg).get("role", "user") # type: ignore
+
+ if content_text:
+ conversation_parts.append(f"{role}: {content_text}")
+
+ return "\n".join(conversation_parts)
+
+
+def extract_text_from_a2a_message(
+ message: Dict[str, Any], depth: int = 0, max_depth: int = 10
+) -> str:
+ """
+ Extract text content from A2A message parts.
+
+ Args:
+ message: A2A message dict with 'parts' containing text parts
+ depth: Current recursion depth (internal use)
+ max_depth: Maximum recursion depth to prevent infinite loops
+
+ Returns:
+ Concatenated text from all text parts
+ """
+ if message is None or depth >= max_depth:
+ return ""
+
+ parts = message.get("parts", [])
+ text_parts: List[str] = []
+
+ for part in parts:
+ if part.get("kind") == "text":
+ text_parts.append(part.get("text", ""))
+ # Handle nested parts if they exist
+ elif "parts" in part:
+ nested_text = extract_text_from_a2a_message(part, depth + 1, max_depth)
+ if nested_text:
+ text_parts.append(nested_text)
+
+ return " ".join(text_parts)
+
+
+def extract_text_from_a2a_response(
+ response_dict: Dict[str, Any], max_depth: int = 10
+) -> str:
+ """
+ Extract text content from A2A response result.
+
+ Args:
+ response_dict: A2A response dict with 'result' containing message
+ max_depth: Maximum recursion depth to prevent infinite loops
+
+ Returns:
+ Text from response message parts
+ """
+ result = response_dict.get("result", {})
+ if not isinstance(result, dict):
+ return ""
+
+ # A2A response can have different formats:
+ # 1. Direct message: {"result": {"kind": "message", "parts": [...]}}
+ # 2. Nested message: {"result": {"message": {"parts": [...]}}}
+ # 3. Task with artifacts: {"result": {"kind": "task", "artifacts": [{"parts": [...]}]}}
+ # 4. Task with status message: {"result": {"kind": "task", "status": {"message": {"parts": [...]}}}}
+ # 5. Streaming artifact-update: {"result": {"kind": "artifact-update", "artifact": {"parts": [...]}}}
+
+ # Check if result itself has parts (direct message)
+ if "parts" in result:
+ return extract_text_from_a2a_message(result, depth=0, max_depth=max_depth)
+
+ # Check for nested message
+ message = result.get("message")
+ if message:
+ return extract_text_from_a2a_message(message, depth=0, max_depth=max_depth)
+
+ # Check for streaming artifact-update (singular artifact)
+ artifact = result.get("artifact")
+ if artifact and isinstance(artifact, dict):
+ return extract_text_from_a2a_message(
+ artifact, depth=0, max_depth=max_depth
+ )
+
+ # Check for task status message (common in Gemini A2A agents)
+ status = result.get("status", {})
+ if isinstance(status, dict):
+ status_message = status.get("message")
+ if status_message:
+ return extract_text_from_a2a_message(
+ status_message, depth=0, max_depth=max_depth
+ )
+
+ # Handle task result with artifacts (plural, array)
+ artifacts = result.get("artifacts", [])
+ if artifacts and len(artifacts) > 0:
+ first_artifact = artifacts[0]
+ return extract_text_from_a2a_message(
+ first_artifact, depth=0, max_depth=max_depth
+ )
+
+ return ""
diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 9d50cc4d92d..a14e7d118e8 100644
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@ -34,6 +34,7 @@ from litellm.types.llms.openai import (
)
from litellm.types.utils import (
ChatCompletionMessageToolCall,
+ Choices,
GenericGuardrailAPIInputs,
ModelResponse,
)
@@ -74,9 +75,10 @@ class AnthropicMessagesHandler(BaseTranslation):
if messages is None:
return data
- chat_completion_compatible_request = (
+ chat_completion_compatible_request, tool_name_mapping = (
LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai(
- anthropic_message_request=cast(AnthropicMessagesRequest, data)
+ # Use a shallow copy to avoid mutating request data (pop on litellm_metadata).
+ anthropic_message_request=cast(AnthropicMessagesRequest, data.copy())
)
)
@@ -84,9 +86,9 @@ class AnthropicMessagesHandler(BaseTranslation):
texts_to_check: List[str] = []
images_to_check: List[str] = []
- tools_to_check: List[ChatCompletionToolParam] = (
- chat_completion_compatible_request.get("tools", [])
- )
+ tools_to_check: List[
+ ChatCompletionToolParam
+ ] = chat_completion_compatible_request.get("tools", [])
task_mappings: List[Tuple[int, Optional[int]]] = []
# Track (message_index, content_index) for each text
# content_index is None for string content, int for list content
@@ -110,6 +112,10 @@ class AnthropicMessagesHandler(BaseTranslation):
inputs["tools"] = tools_to_check
if structured_messages:
inputs["structured_messages"] = structured_messages
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
request_data=data,
@@ -278,7 +284,10 @@ class AnthropicMessagesHandler(BaseTranslation):
if hasattr(content_block, "model_dump"):
block_dict = content_block.model_dump()
else:
- block_dict = {"type": block_type, "text": getattr(content_block, "text", None)}
+ block_dict = {
+ "type": block_type,
+ "text": getattr(content_block, "text", None),
+ }
else:
continue
@@ -309,6 +318,14 @@ class AnthropicMessagesHandler(BaseTranslation):
inputs["images"] = images_to_check
if tool_calls_to_check:
inputs["tool_calls"] = tool_calls_to_check
+ # Include model information from the response if available
+ response_model = None
+ if isinstance(response, dict):
+ response_model = response.get("model")
+ elif hasattr(response, "model"):
+ response_model = getattr(response, "model", None)
+ if response_model:
+ inputs["model"] = response_model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
@@ -346,30 +363,40 @@ class AnthropicMessagesHandler(BaseTranslation):
"""
has_ended = self._check_streaming_has_ended(responses_so_far)
if has_ended:
-
# build the model response from the responses_so_far
- model_response = cast(
- ModelResponse,
- AnthropicPassthroughLoggingHandler._build_complete_streaming_response(
- all_chunks=responses_so_far,
- litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj),
- model="",
- ),
+ built_response = AnthropicPassthroughLoggingHandler._build_complete_streaming_response(
+ all_chunks=responses_so_far,
+ litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj),
+ model="",
)
- tool_calls_list = cast(Optional[List[ChatCompletionMessageToolCall]], model_response.choices[0].message.tool_calls) # type: ignore
- string_so_far = model_response.choices[0].message.content # type: ignore
- guardrail_inputs = GenericGuardrailAPIInputs()
- if string_so_far:
- guardrail_inputs["texts"] = [string_so_far]
- if tool_calls_list:
- guardrail_inputs["tool_calls"] = tool_calls_list
- _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid
- inputs=guardrail_inputs,
- request_data={},
- input_type="response",
- logging_obj=litellm_logging_obj,
- )
+ # Check if model_response is valid and has choices before accessing
+ if (
+ built_response is not None
+ and hasattr(built_response, "choices")
+ and built_response.choices
+ ):
+ model_response = cast(ModelResponse, built_response)
+ first_choice = cast(Choices, model_response.choices[0])
+ tool_calls_list = cast(
+ Optional[List[ChatCompletionMessageToolCall]],
+ first_choice.message.tool_calls,
+ )
+ string_so_far = first_choice.message.content
+ guardrail_inputs = GenericGuardrailAPIInputs()
+ if string_so_far:
+ guardrail_inputs["texts"] = [string_so_far]
+ if tool_calls_list:
+ guardrail_inputs["tool_calls"] = tool_calls_list
+
+ _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid
+ inputs=guardrail_inputs,
+ request_data={},
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ else:
+ verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices")
return responses_so_far
string_so_far = self.get_streaming_string_so_far(responses_so_far)
@@ -552,7 +579,7 @@ class AnthropicMessagesHandler(BaseTranslation):
response_content = response.get("content", [])
else:
response_content = getattr(response, "content", None) or []
-
+
if not response_content:
return False
for content_block in response_content:
@@ -636,7 +663,10 @@ class AnthropicMessagesHandler(BaseTranslation):
if isinstance(content_block, dict):
if content_block.get("type") == "text":
cast(Dict[str, Any], content_block)["text"] = guardrail_response
- elif hasattr(content_block, "type") and getattr(content_block, "type", None) == "text":
+ elif (
+ hasattr(content_block, "type")
+ and getattr(content_block, "type", None) == "text"
+ ):
# Update Pydantic object's text attribute
if hasattr(content_block, "text"):
content_block.text = guardrail_response
diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py
index 6a9aafd076b..f51adf96102 100644
--- a/litellm/llms/anthropic/chat/handler.py
+++ b/litellm/llms/anthropic/chat/handler.py
@@ -58,6 +58,9 @@ from litellm.types.utils import (
from ...base import BaseLLM
from ..common_utils import AnthropicError, process_anthropic_headers
+from litellm.anthropic_beta_headers_manager import (
+ update_headers_with_filtered_beta,
+)
from .transformation import AnthropicConfig
if TYPE_CHECKING:
@@ -75,6 +78,7 @@ async def make_call(
logging_obj,
timeout: Optional[Union[float, httpx.Timeout]],
json_mode: bool,
+ speed: Optional[str] = None,
) -> Tuple[Any, httpx.Headers]:
if client is None:
client = litellm.module_level_aclient
@@ -103,6 +107,7 @@ async def make_call(
streaming_response=response.aiter_lines(),
sync_stream=False,
json_mode=json_mode,
+ speed=speed,
)
# LOGGING
@@ -126,6 +131,7 @@ def make_sync_call(
logging_obj,
timeout: Optional[Union[float, httpx.Timeout]],
json_mode: bool,
+ speed: Optional[str] = None,
) -> Tuple[Any, httpx.Headers]:
if client is None:
client = litellm.module_level_client # re-use a module level client
@@ -159,7 +165,7 @@ def make_sync_call(
)
completion_stream = ModelResponseIterator(
- streaming_response=response.iter_lines(), sync_stream=True, json_mode=json_mode
+ streaming_response=response.iter_lines(), sync_stream=True, json_mode=json_mode, speed=speed
)
# LOGGING
@@ -213,6 +219,7 @@ class AnthropicChatCompletion(BaseLLM):
logging_obj=logging_obj,
timeout=timeout,
json_mode=json_mode,
+ speed=optional_params.get("speed") if optional_params else None,
)
streamwrapper = CustomStreamWrapper(
completion_stream=completion_stream,
@@ -329,6 +336,10 @@ class AnthropicChatCompletion(BaseLLM):
litellm_params=litellm_params,
)
+ headers = update_headers_with_filtered_beta(
+ headers=headers, provider=custom_llm_provider
+ )
+
config = ProviderConfigManager.get_provider_chat_config(
model=model,
provider=LlmProviders(custom_llm_provider),
@@ -427,6 +438,7 @@ class AnthropicChatCompletion(BaseLLM):
logging_obj=logging_obj,
timeout=timeout,
json_mode=json_mode,
+ speed=optional_params.get("speed") if optional_params else None,
)
return CustomStreamWrapper(
completion_stream=completion_stream,
@@ -485,13 +497,14 @@ class AnthropicChatCompletion(BaseLLM):
class ModelResponseIterator:
def __init__(
- self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False
+ self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False, speed: Optional[str] = None
):
self.streaming_response = streaming_response
self.response_iterator = self.streaming_response
self.content_blocks: List[ContentBlockDelta] = []
self.tool_index = -1
self.json_mode = json_mode
+ self.speed = speed
# Generate response ID once per stream to match OpenAI-compatible behavior
self.response_id = _generate_id()
@@ -512,6 +525,9 @@ class ModelResponseIterator:
# Accumulate web_search_tool_result blocks for multi-turn reconstruction
# See: https://github.com/BerriAI/litellm/issues/17737
self.web_search_results: List[Dict[str, Any]] = []
+
+ # Accumulate compaction blocks for multi-turn reconstruction
+ self.compaction_blocks: List[Dict[str, Any]] = []
def check_empty_tool_call_args(self) -> bool:
"""
@@ -538,7 +554,7 @@ class ModelResponseIterator:
def _handle_usage(self, anthropic_usage_chunk: Union[dict, UsageDelta]) -> Usage:
return AnthropicConfig().calculate_usage(
- usage_object=cast(dict, anthropic_usage_chunk), reasoning_content=None
+ usage_object=cast(dict, anthropic_usage_chunk), reasoning_content=None, speed=self.speed
)
def _content_block_delta_helper(self, chunk: dict) -> Tuple[
@@ -592,6 +608,12 @@ class ModelResponseIterator:
)
]
provider_specific_fields["thinking_blocks"] = thinking_blocks
+ elif "content" in content_block["delta"] and content_block["delta"].get("type") == "compaction_delta":
+ # Handle compaction delta
+ provider_specific_fields["compaction_delta"] = {
+ "type": "compaction_delta",
+ "content": content_block["delta"]["content"]
+ }
return text, tool_use, thinking_blocks, provider_specific_fields
@@ -721,6 +743,20 @@ class ModelResponseIterator:
provider_specific_fields=provider_specific_fields,
)
+ elif content_block_start["content_block"]["type"] == "compaction":
+ # Handle compaction blocks
+ # The full content comes in content_block_start
+ self.compaction_blocks.append(
+ content_block_start["content_block"]
+ )
+ provider_specific_fields["compaction_blocks"] = (
+ self.compaction_blocks
+ )
+ provider_specific_fields["compaction_start"] = {
+ "type": "compaction",
+ "content": content_block_start["content_block"].get("content", "")
+ }
+
elif content_block_start["content_block"]["type"].endswith("_tool_result"):
# Handle all tool result types (web_search, bash_code_execution, text_editor, etc.)
content_type = content_block_start["content_block"]["type"]
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py
index 82eccee596d..a5f8fe22a2c 100644
--- a/litellm/llms/anthropic/chat/transformation.py
+++ b/litellm/llms/anthropic/chat/transformation.py
@@ -170,9 +170,10 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
tool_call["caller"] = cast(Dict[str, Any], anthropic_tool_content["caller"]) # type: ignore[typeddict-item]
return tool_call
- def _is_claude_opus_4_5(self, model: str) -> bool:
- """Check if the model is Claude Opus 4.5."""
- return "opus-4-5" in model.lower() or "opus_4_5" in model.lower()
+ @staticmethod
+ def _is_claude_opus_4_6(model: str) -> bool:
+ """Check if the model is Claude Opus 4.5 or Sonnet 4.6."""
+ return "opus-4-6" in model.lower() or "opus_4_6" in model.lower() or "sonnet-4-6" in model.lower() or "sonnet_4_6" in model.lower() or "sonnet-4.6" in model.lower()
def get_supported_openai_params(self, model: str):
params = [
@@ -189,6 +190,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
"response_format",
"user",
"web_search_options",
+ "speed",
]
if "claude-3-7-sonnet" in model or supports_reasoning(
@@ -206,29 +208,73 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
Filter out unsupported fields from JSON schema for Anthropic's output_format API.
Anthropic's output_format doesn't support certain JSON schema properties:
- - maxItems: Not supported for array types
- - minItems: Not supported for array types
+ - maxItems/minItems: Not supported for array types
+ - minimum/maximum: Not supported for numeric types
+ - minLength/maxLength: Not supported for string types
- This function recursively removes these unsupported fields while preserving
- all other valid schema properties.
+ This mirrors the transformation done by the Anthropic Python SDK.
+ See: https://platform.claude.com/docs/en/build-with-claude/structured-outputs#how-sdk-transformation-works
+
+ The SDK approach:
+ 1. Remove unsupported constraints from schema
+ 2. Add constraint info to description (e.g., "Must be at least 100")
+ 3. Validate responses against original schema
Args:
schema: The JSON schema dictionary to filter
Returns:
- A new dictionary with unsupported fields removed
+ A new dictionary with unsupported fields removed and descriptions updated
- Related issue: https://github.com/BerriAI/litellm/issues/19444
+ Related issues:
+ - https://github.com/BerriAI/litellm/issues/19444
"""
if not isinstance(schema, dict):
return schema
- unsupported_fields = {"maxItems", "minItems"}
+ # All numeric/string/array constraints not supported by Anthropic
+ unsupported_fields = {
+ "maxItems", "minItems", # array constraints
+ "minimum", "maximum", # numeric constraints
+ "exclusiveMinimum", "exclusiveMaximum", # numeric constraints
+ "minLength", "maxLength", # string constraints
+ }
+
+ # Build description additions from removed constraints
+ constraint_descriptions: list = []
+ constraint_labels = {
+ "minItems": "minimum number of items: {}",
+ "maxItems": "maximum number of items: {}",
+ "minimum": "minimum value: {}",
+ "maximum": "maximum value: {}",
+ "exclusiveMinimum": "exclusive minimum value: {}",
+ "exclusiveMaximum": "exclusive maximum value: {}",
+ "minLength": "minimum length: {}",
+ "maxLength": "maximum length: {}",
+ }
+ for field in unsupported_fields:
+ if field in schema:
+ constraint_descriptions.append(
+ constraint_labels[field].format(schema[field])
+ )
result: Dict[str, Any] = {}
+
+ # Update description with removed constraint info
+ if constraint_descriptions:
+ existing_desc = schema.get("description", "")
+ constraint_note = "Note: " + ", ".join(constraint_descriptions) + "."
+ if existing_desc:
+ result["description"] = existing_desc + " " + constraint_note
+ else:
+ result["description"] = constraint_note
+
for key, value in schema.items():
if key in unsupported_fields:
continue
+ if key == "description" and "description" in result:
+ # Already handled above
+ continue
if key == "properties" and isinstance(value, dict):
result[key] = {
@@ -290,10 +336,19 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
elif tool_choice == "none":
_tool_choice = AnthropicMessagesToolChoice(type="none")
elif isinstance(tool_choice, dict):
- _tool_name = tool_choice.get("function", {}).get("name")
- _tool_choice = AnthropicMessagesToolChoice(type="tool")
- if _tool_name is not None:
- _tool_choice["name"] = _tool_name
+ if "type" in tool_choice and "function" not in tool_choice:
+ tool_type = tool_choice.get("type")
+ if tool_type == "auto":
+ _tool_choice = AnthropicMessagesToolChoice(type="auto")
+ elif tool_type == "required" or tool_type == "any":
+ _tool_choice = AnthropicMessagesToolChoice(type="any")
+ elif tool_type == "none":
+ _tool_choice = AnthropicMessagesToolChoice(type="none")
+ else:
+ _tool_name = tool_choice.get("function", {}).get("name")
+ if _tool_name is not None:
+ _tool_choice = AnthropicMessagesToolChoice(type="tool")
+ _tool_choice["name"] = _tool_name
if parallel_tool_use is not None:
# Anthropic uses 'disable_parallel_tool_use' flag to determine if parallel tool use is allowed
@@ -650,10 +705,15 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
@staticmethod
def _map_reasoning_effort(
- reasoning_effort: Optional[Union[REASONING_EFFORT, str]],
+ reasoning_effort: Optional[Union[REASONING_EFFORT, str]],
+ model: str,
) -> Optional[AnthropicThinkingParam]:
- if reasoning_effort is None:
+ if reasoning_effort is None or reasoning_effort == "none":
return None
+ if AnthropicConfig._is_claude_opus_4_6(model):
+ return AnthropicThinkingParam(
+ type="adaptive",
+ )
elif reasoning_effort == "low":
return AnthropicThinkingParam(
type="enabled",
@@ -817,6 +877,14 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
"sonnet-4-5",
"opus-4.1",
"opus-4-1",
+ "opus-4.5",
+ "opus-4-5",
+ "opus-4.6",
+ "opus-4-6",
+ "sonnet-4.6",
+ "sonnet-4-6",
+ "sonnet_4.6",
+ "sonnet_4_6",
}
):
_output_format = (
@@ -851,13 +919,8 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
if param == "thinking":
optional_params["thinking"] = value
elif param == "reasoning_effort" and isinstance(value, str):
- # For Claude Opus 4.5, map reasoning_effort to output_config
- if self._is_claude_opus_4_5(model):
- optional_params["output_config"] = {"effort": value}
-
- # For other models, map to thinking parameter
optional_params["thinking"] = AnthropicConfig._map_reasoning_effort(
- value
+ reasoning_effort=value, model=model
)
elif param == "web_search_options" and isinstance(value, dict):
hosted_web_search_tool = self.map_web_search_tool(
@@ -868,6 +931,12 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
)
elif param == "extra_headers":
optional_params["extra_headers"] = value
+ elif param == "context_management" and isinstance(value, dict):
+ # Pass through Anthropic-specific context_management parameter
+ optional_params["context_management"] = value
+ elif param == "speed" and isinstance(value, str):
+ # Pass through Anthropic-specific speed parameter for fast mode
+ optional_params["speed"] = value
## handle thinking tokens
self.update_optional_params_with_thinking_tokens(
@@ -913,6 +982,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
Translate system message to anthropic format.
Removes system message from the original list and returns a new list of anthropic system message content.
+ Filters out system messages containing x-anthropic-billing-header metadata.
"""
system_prompt_indices = []
anthropic_system_message_list: List[AnthropicSystemMessageContent] = []
@@ -924,6 +994,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
# Skip empty text blocks - Anthropic API raises errors for empty text
if not system_message_block["content"]:
continue
+ # Skip system messages containing x-anthropic-billing-header metadata
+ if system_message_block["content"].startswith("x-anthropic-billing-header:"):
+ continue
anthropic_system_message_content = AnthropicSystemMessageContent(
type="text",
text=system_message_block["content"],
@@ -942,6 +1015,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
text_value = _content.get("text")
if _content.get("type") == "text" and not text_value:
continue
+ # Skip system messages containing x-anthropic-billing-header metadata
+ if _content.get("type") == "text" and text_value and text_value.startswith("x-anthropic-billing-header:"):
+ continue
anthropic_system_message_content = (
AnthropicSystemMessageContent(
type=_content.get("type"),
@@ -1017,9 +1093,37 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
if beta_value not in existing_values:
headers["anthropic-beta"] = f"{existing_beta}, {beta_value}"
- def _ensure_context_management_beta_header(self, headers: dict) -> None:
- beta_value = ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value
- self._ensure_beta_header(headers, beta_value)
+ def _ensure_context_management_beta_header(
+ self, headers: dict, context_management: dict
+ ) -> None:
+ """
+ Add appropriate beta headers based on context_management edits.
+ - If any edit has type "compact_20260112", add compact-2026-01-12 header
+ - For all other edits, add context-management-2025-06-27 header
+ """
+ edits = context_management.get("edits", [])
+
+ has_compact = False
+ has_other = False
+
+ for edit in edits:
+ edit_type = edit.get("type", "")
+ if edit_type == "compact_20260112":
+ has_compact = True
+ else:
+ has_other = True
+
+ # Add compact header if any compact edits exist
+ if has_compact:
+ self._ensure_beta_header(
+ headers, ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value
+ )
+
+ # Add context management header if any other edits exist
+ if has_other:
+ self._ensure_beta_header(
+ headers, ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value
+ )
def update_headers_with_optional_anthropic_beta(
self, headers: dict, optional_params: dict
@@ -1047,11 +1151,17 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
headers, ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value
)
if optional_params.get("context_management") is not None:
- self._ensure_context_management_beta_header(headers)
+ self._ensure_context_management_beta_header(
+ headers, optional_params["context_management"]
+ )
if optional_params.get("output_format") is not None:
self._ensure_beta_header(
headers, ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value
)
+ if optional_params.get("speed") == "fast":
+ self._ensure_beta_header(
+ headers, ANTHROPIC_BETA_HEADER_VALUES.FAST_MODE_2026_02_01.value
+ )
return headers
def transform_request(
@@ -1176,9 +1286,13 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
output_config = optional_params.get("output_config")
if output_config and isinstance(output_config, dict):
effort = output_config.get("effort")
- if effort and effort not in ["high", "medium", "low"]:
+ if effort and effort not in ["high", "medium", "low", "max"]:
raise ValueError(
- f"Invalid effort value: {effort}. Must be one of: 'high', 'medium', 'low'"
+ f"Invalid effort value: {effort}. Must be one of: 'high', 'medium', 'low', 'max'"
+ )
+ if effort == "max" and not self._is_claude_opus_4_6(model):
+ raise ValueError(
+ f"effort='max' is only supported by Claude Opus 4.6. Got model: {model}"
)
data["output_config"] = output_config
@@ -1216,6 +1330,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
List[ChatCompletionToolCallChunk],
Optional[List[Any]],
Optional[List[Any]],
+ Optional[List[Any]],
]:
text_content = ""
citations: Optional[List[Any]] = None
@@ -1228,6 +1343,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
tool_calls: List[ChatCompletionToolCallChunk] = []
web_search_results: Optional[List[Any]] = None
tool_results: Optional[List[Any]] = None
+ compaction_blocks: Optional[List[Any]] = None
for idx, content in enumerate(completion_response["content"]):
if content["type"] == "text":
text_content += content["text"]
@@ -1269,6 +1385,12 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
thinking_blocks.append(
cast(ChatCompletionRedactedThinkingBlock, content)
)
+
+ ## COMPACTION
+ elif content["type"] == "compaction":
+ if compaction_blocks is None:
+ compaction_blocks = []
+ compaction_blocks.append(content)
## CITATIONS
if content.get("citations") is not None:
@@ -1290,13 +1412,14 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
if thinking_content is not None:
reasoning_content += thinking_content
- return text_content, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results
+ return text_content, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks
def calculate_usage(
self,
usage_object: dict,
reasoning_content: Optional[str],
completion_response: Optional[dict] = None,
+ speed: Optional[str] = None,
) -> Usage:
# NOTE: Sometimes the usage object has None set explicitly for token counts, meaning .get() & key access returns None, and we need to account for this
prompt_tokens = usage_object.get("input_tokens", 0) or 0
@@ -1307,6 +1430,10 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
cache_creation_token_details: Optional[CacheCreationTokenDetails] = None
web_search_requests: Optional[int] = None
tool_search_requests: Optional[int] = None
+ inference_geo: Optional[str] = None
+ if "inference_geo" in _usage and _usage["inference_geo"] is not None:
+ inference_geo = _usage["inference_geo"]
+
if (
"cache_creation_input_tokens" in _usage
and _usage["cache_creation_input_tokens"] is not None
@@ -1369,7 +1496,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
else 0
)
completion_token_details = CompletionTokensDetailsWrapper(
- reasoning_tokens=reasoning_tokens if reasoning_tokens > 0 else None,
+ reasoning_tokens=reasoning_tokens if reasoning_tokens > 0 else 0,
text_tokens=completion_tokens - reasoning_tokens if reasoning_tokens > 0 else completion_tokens,
)
total_tokens = prompt_tokens + completion_tokens
@@ -1390,6 +1517,8 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
if (web_search_requests is not None or tool_search_requests is not None)
else None
),
+ inference_geo=inference_geo,
+ speed=speed,
)
return usage
@@ -1400,6 +1529,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
model_response: ModelResponse,
json_mode: Optional[bool] = None,
prefix_prompt: Optional[str] = None,
+ speed: Optional[str] = None,
):
_hidden_params: Dict = {}
_hidden_params["additional_headers"] = process_anthropic_headers(
@@ -1433,6 +1563,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
tool_calls,
web_search_results,
tool_results,
+ compaction_blocks,
) = self.extract_response_content(completion_response=completion_response)
if (
@@ -1460,6 +1591,8 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
provider_specific_fields["tool_results"] = tool_results
if container is not None:
provider_specific_fields["container"] = container
+ if compaction_blocks is not None:
+ provider_specific_fields["compaction_blocks"] = compaction_blocks
_message = litellm.Message(
tool_calls=tool_calls,
@@ -1468,6 +1601,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
thinking_blocks=thinking_blocks,
reasoning_content=reasoning_content,
)
+ _message.provider_specific_fields = provider_specific_fields
## HANDLE JSON MODE - anthropic returns single function call
json_mode_message = self._transform_response_for_json_mode(
@@ -1492,24 +1626,14 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
usage_object=completion_response["usage"],
reasoning_content=reasoning_content,
completion_response=completion_response,
+ speed=speed,
)
setattr(model_response, "usage", usage) # type: ignore
model_response.created = int(time.time())
model_response.model = completion_response["model"]
- context_management_response = completion_response.get("context_management")
- if context_management_response is not None:
- _hidden_params["context_management"] = context_management_response
- try:
- model_response.__dict__["context_management"] = (
- context_management_response
- )
- except Exception:
- pass
-
model_response._hidden_params = _hidden_params
-
return model_response
def get_prefix_prompt(self, messages: List[AllMessageValues]) -> Optional[str]:
@@ -1571,6 +1695,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
)
prefix_prompt = self.get_prefix_prompt(messages=messages)
+ speed = optional_params.get("speed")
model_response = self.transform_parsed_response(
completion_response=completion_response,
@@ -1578,6 +1703,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
model_response=model_response,
json_mode=json_mode,
prefix_prompt=prefix_prompt,
+ speed=speed,
)
return model_response
diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py
index cb23d21fbc9..0cceddd9acf 100644
--- a/litellm/llms/anthropic/common_utils.py
+++ b/litellm/llms/anthropic/common_utils.py
@@ -22,6 +22,15 @@ from litellm.types.llms.anthropic import (
from litellm.types.llms.openai import AllMessageValues
+def is_anthropic_oauth_key(value: Optional[str]) -> bool:
+ """Check if a value contains an Anthropic OAuth token (sk-ant-oat*)."""
+ if value is None:
+ return False
+ # Handle both raw token and "Bearer " format
+ if value.startswith("Bearer "):
+ value = value[7:]
+ return value.startswith(ANTHROPIC_OAUTH_TOKEN_PREFIX)
+
def optionally_handle_anthropic_oauth(
headers: dict, api_key: Optional[str]
) -> tuple[dict, Optional[str]]:
@@ -38,9 +47,18 @@ def optionally_handle_anthropic_oauth(
Returns:
Tuple of (updated headers, api_key)
"""
+ # Check Authorization header (passthrough / forwarded requests)
auth_header = headers.get("authorization", "")
if auth_header and auth_header.startswith(f"Bearer {ANTHROPIC_OAUTH_TOKEN_PREFIX}"):
api_key = auth_header.replace("Bearer ", "")
+ headers.pop("x-api-key", None)
+ headers["anthropic-beta"] = ANTHROPIC_OAUTH_BETA_HEADER
+ headers["anthropic-dangerous-direct-browser-access"] = "true"
+ return headers, api_key
+ # Check api_key directly (standard chat/completion flow)
+ if api_key and api_key.startswith(ANTHROPIC_OAUTH_TOKEN_PREFIX):
+ headers.pop("x-api-key", None)
+ headers["authorization"] = f"Bearer {api_key}"
headers["anthropic-beta"] = ANTHROPIC_OAUTH_BETA_HEADER
headers["anthropic-dangerous-direct-browser-access"] = "true"
return headers, api_key
@@ -108,7 +126,9 @@ class AnthropicModelInfo(BaseLLMModelInfo):
if tools is None:
return False
for tool in tools:
- if "type" in tool and tool["type"].startswith(ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value):
+ if "type" in tool and tool["type"].startswith(
+ ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value
+ ):
return True
return False
@@ -134,111 +154,126 @@ class AnthropicModelInfo(BaseLLMModelInfo):
"""
if not tools:
return False
-
+
for tool in tools:
tool_type = tool.get("type", "")
- if tool_type in ["tool_search_tool_regex_20251119", "tool_search_tool_bm25_20251119"]:
+ if tool_type in [
+ "tool_search_tool_regex_20251119",
+ "tool_search_tool_bm25_20251119",
+ ]:
return True
return False
-
+
def is_programmatic_tool_calling_used(self, tools: Optional[List]) -> bool:
"""
Check if programmatic tool calling is being used (tools with allowed_callers field).
-
+
Returns True if any tool has allowed_callers containing 'code_execution_20250825'.
"""
if not tools:
return False
-
+
for tool in tools:
# Check top-level allowed_callers
allowed_callers = tool.get("allowed_callers", None)
if allowed_callers and isinstance(allowed_callers, list):
if "code_execution_20250825" in allowed_callers:
return True
-
+
# Check function.allowed_callers for OpenAI format tools
function = tool.get("function", {})
if isinstance(function, dict):
function_allowed_callers = function.get("allowed_callers", None)
- if function_allowed_callers and isinstance(function_allowed_callers, list):
+ if function_allowed_callers and isinstance(
+ function_allowed_callers, list
+ ):
if "code_execution_20250825" in function_allowed_callers:
return True
-
+
return False
-
+
def is_input_examples_used(self, tools: Optional[List]) -> bool:
"""
Check if input_examples is being used in any tools.
-
+
Returns True if any tool has input_examples field.
"""
if not tools:
return False
-
+
for tool in tools:
# Check top-level input_examples
input_examples = tool.get("input_examples", None)
- if input_examples and isinstance(input_examples, list) and len(input_examples) > 0:
+ if (
+ input_examples
+ and isinstance(input_examples, list)
+ and len(input_examples) > 0
+ ):
return True
-
+
# Check function.input_examples for OpenAI format tools
function = tool.get("function", {})
if isinstance(function, dict):
function_input_examples = function.get("input_examples", None)
- if function_input_examples and isinstance(function_input_examples, list) and len(function_input_examples) > 0:
+ if (
+ function_input_examples
+ and isinstance(function_input_examples, list)
+ and len(function_input_examples) > 0
+ ):
return True
-
+
return False
-
- def is_effort_used(self, optional_params: Optional[dict], model: Optional[str] = None) -> bool:
+
+ def is_effort_used(
+ self, optional_params: Optional[dict], model: Optional[str] = None
+ ) -> bool:
"""
Check if effort parameter is being used.
-
+
Returns True if effort-related parameters are present.
"""
if not optional_params:
return False
-
+
# Check if reasoning_effort is provided for Claude Opus 4.5
if model and ("opus-4-5" in model.lower() or "opus_4_5" in model.lower()):
reasoning_effort = optional_params.get("reasoning_effort")
if reasoning_effort and isinstance(reasoning_effort, str):
return True
-
+
# Check if output_config is directly provided
output_config = optional_params.get("output_config")
if output_config and isinstance(output_config, dict):
effort = output_config.get("effort")
if effort and isinstance(effort, str):
return True
-
+
return False
def is_code_execution_tool_used(self, tools: Optional[List]) -> bool:
"""
Check if code execution tool is being used.
-
+
Returns True if any tool has type "code_execution_20250825".
"""
if not tools:
return False
-
+
for tool in tools:
tool_type = tool.get("type", "")
if tool_type == "code_execution_20250825":
return True
return False
-
+
def is_container_with_skills_used(self, optional_params: Optional[dict]) -> bool:
"""
Check if container with skills is being used.
-
+
Returns True if optional_params contains container with skills.
"""
if not optional_params:
return False
-
+
container = optional_params.get("container")
if container and isinstance(container, dict):
skills = container.get("skills")
@@ -256,10 +291,10 @@ class AnthropicModelInfo(BaseLLMModelInfo):
def get_computer_tool_beta_header(self, computer_tool_version: str) -> str:
"""
Get the appropriate beta header for a given computer tool version.
-
+
Args:
computer_tool_version: The computer tool version (e.g., 'computer_20250124', 'computer_20241022')
-
+
Returns:
The corresponding beta header string
"""
@@ -282,37 +317,37 @@ class AnthropicModelInfo(BaseLLMModelInfo):
) -> List[str]:
"""
Get list of common beta headers based on the features that are active.
-
+
Returns:
List of beta header strings
"""
from litellm.types.llms.anthropic import (
ANTHROPIC_EFFORT_BETA_HEADER,
)
-
+
betas = []
-
+
# Detect features
effort_used = self.is_effort_used(optional_params, model)
-
+
if effort_used:
betas.append(ANTHROPIC_EFFORT_BETA_HEADER) # effort-2025-11-24
-
+
if computer_tool_used:
beta_header = self.get_computer_tool_beta_header(computer_tool_used)
betas.append(beta_header)
-
+
# Anthropic no longer requires the prompt-caching beta header
# Prompt caching now works automatically when cache_control is used in messages
# Reference: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
-
+
if file_id_used:
betas.append("files-api-2025-04-14")
betas.append("code-execution-2025-05-22")
-
+
if mcp_server_used:
betas.append("mcp-client-2025-04-04")
-
+
return list(set(betas))
def get_anthropic_headers(
@@ -351,27 +386,35 @@ class AnthropicModelInfo(BaseLLMModelInfo):
# Tool search, programmatic tool calling, and input_examples all use the same beta header
if tool_search_used or programmatic_tool_calling_used or input_examples_used:
from litellm.types.llms.anthropic import ANTHROPIC_TOOL_SEARCH_BETA_HEADER
+
betas.add(ANTHROPIC_TOOL_SEARCH_BETA_HEADER)
-
+
# Effort parameter uses a separate beta header
if effort_used:
from litellm.types.llms.anthropic import ANTHROPIC_EFFORT_BETA_HEADER
+
betas.add(ANTHROPIC_EFFORT_BETA_HEADER)
-
+
# Code execution tool uses a separate beta header
if code_execution_tool_used:
betas.add("code-execution-2025-08-25")
-
+
# Container with skills uses a separate beta header
if container_with_skills_used:
betas.add("skills-2025-10-02")
+ _is_oauth = api_key and api_key.startswith(ANTHROPIC_OAUTH_TOKEN_PREFIX)
headers = {
"anthropic-version": anthropic_version or "2023-06-01",
- "x-api-key": api_key,
"accept": "application/json",
"content-type": "application/json",
}
+ if _is_oauth:
+ headers["authorization"] = f"Bearer {api_key}"
+ headers["anthropic-dangerous-direct-browser-access"] = "true"
+ betas.add(ANTHROPIC_OAUTH_BETA_HEADER)
+ else:
+ headers["x-api-key"] = api_key
if user_anthropic_beta_headers is not None:
betas.update(user_anthropic_beta_headers)
@@ -381,7 +424,10 @@ class AnthropicModelInfo(BaseLLMModelInfo):
# Vertex AI requires web search beta header for web search to work
if web_search_tool_used:
from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES
- headers["anthropic-beta"] = ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value
+
+ headers[
+ "anthropic-beta"
+ ] = ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value
elif len(betas) > 0:
headers["anthropic-beta"] = ",".join(betas)
@@ -398,7 +444,9 @@ class AnthropicModelInfo(BaseLLMModelInfo):
api_base: Optional[str] = None,
) -> Dict:
# Check for Anthropic OAuth token in headers
- headers, api_key = optionally_handle_anthropic_oauth(headers=headers, api_key=api_key)
+ headers, api_key = optionally_handle_anthropic_oauth(
+ headers=headers, api_key=api_key
+ )
if api_key is None:
raise litellm.AuthenticationError(
message="Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params. Please set `ANTHROPIC_API_KEY` in your environment vars",
@@ -416,11 +464,15 @@ class AnthropicModelInfo(BaseLLMModelInfo):
file_id_used = self.is_file_id_used(messages=messages)
web_search_tool_used = self.is_web_search_tool_used(tools=tools)
tool_search_used = self.is_tool_search_used(tools=tools)
- programmatic_tool_calling_used = self.is_programmatic_tool_calling_used(tools=tools)
+ programmatic_tool_calling_used = self.is_programmatic_tool_calling_used(
+ tools=tools
+ )
input_examples_used = self.is_input_examples_used(tools=tools)
effort_used = self.is_effort_used(optional_params=optional_params, model=model)
code_execution_tool_used = self.is_code_execution_tool_used(tools=tools)
- container_with_skills_used = self.is_container_with_skills_used(optional_params=optional_params)
+ container_with_skills_used = self.is_container_with_skills_used(
+ optional_params=optional_params
+ )
user_anthropic_beta_headers = self._get_user_anthropic_beta_headers(
anthropic_beta_header=headers.get("anthropic-beta")
)
@@ -499,7 +551,7 @@ class AnthropicModelInfo(BaseLLMModelInfo):
def get_token_counter(self) -> Optional[BaseTokenCounter]:
"""
Factory method to create an Anthropic token counter.
-
+
Returns:
AnthropicTokenCounter instance for this provider.
"""
diff --git a/litellm/llms/anthropic/cost_calculation.py b/litellm/llms/anthropic/cost_calculation.py
index 8f34eb00ce5..271406f2f7d 100644
--- a/litellm/llms/anthropic/cost_calculation.py
+++ b/litellm/llms/anthropic/cost_calculation.py
@@ -22,10 +22,22 @@ def cost_per_token(model: str, usage: "Usage") -> Tuple[float, float]:
Returns:
Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd
"""
- return generic_cost_per_token(
- model=model, usage=usage, custom_llm_provider="anthropic"
+ model_with_prefix = model
+
+ # First, prepend inference_geo if present
+ if hasattr(usage, "inference_geo") and usage.inference_geo and usage.inference_geo.lower() not in ["global", "not_available"]:
+ model_with_prefix = f"{usage.inference_geo}/{model_with_prefix}"
+
+ # Then, prepend speed if it's "fast"
+ if hasattr(usage, "speed") and usage.speed == "fast":
+ model_with_prefix = f"fast/{model_with_prefix}"
+
+ prompt_cost, completion_cost = generic_cost_per_token(
+ model=model_with_prefix, usage=usage, custom_llm_provider="anthropic"
)
+ return prompt_cost, completion_cost
+
def get_cost_for_anthropic_web_search(
model_info: Optional["ModelInfo"] = None,
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
index 8fa7bb7e65e..73e74c228ba 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
@@ -6,6 +6,7 @@ from typing import (
Dict,
List,
Optional,
+ Tuple,
Union,
cast,
)
@@ -18,6 +19,7 @@ from litellm.types.llms.anthropic_messages.anthropic_response import (
AnthropicMessagesResponse,
)
from litellm.types.utils import ModelResponse
+from litellm.utils import get_model_info
if TYPE_CHECKING:
pass
@@ -29,6 +31,66 @@ ANTHROPIC_ADAPTER = AnthropicAdapter()
class LiteLLMMessagesToCompletionTransformationHandler:
+ @staticmethod
+ def _route_openai_thinking_to_responses_api_if_needed(
+ completion_kwargs: Dict[str, Any],
+ *,
+ thinking: Optional[Dict[str, Any]],
+ ) -> None:
+ """
+ When users call `litellm.anthropic.messages.*` with a non-Anthropic model and
+ `thinking={"type": "enabled", ...}`, LiteLLM converts this into OpenAI
+ `reasoning_effort`.
+
+ For OpenAI models, Chat Completions typically does not return reasoning text
+ (only token accounting). To return a thinking-like content block in the
+ Anthropic response format, we route the request through OpenAI's Responses API
+ and request a reasoning summary.
+ """
+ custom_llm_provider = completion_kwargs.get("custom_llm_provider")
+ if custom_llm_provider is None:
+ try:
+ _, inferred_provider, _, _ = litellm.utils.get_llm_provider(
+ model=cast(str, completion_kwargs.get("model"))
+ )
+ custom_llm_provider = inferred_provider
+ except Exception:
+ custom_llm_provider = None
+
+ if custom_llm_provider != "openai":
+ return
+
+ if not isinstance(thinking, dict) or thinking.get("type") != "enabled":
+ return
+
+ model = completion_kwargs.get("model")
+ try:
+ model_info = get_model_info(model=cast(str, model), custom_llm_provider=custom_llm_provider)
+ if model_info and model_info.get("supports_reasoning") is False:
+ # Model doesn't support reasoning/responses API, don't route
+ return
+ except Exception:
+ pass
+
+ if isinstance(model, str) and model and not model.startswith("responses/"):
+ # Prefix model with "responses/" to route to OpenAI Responses API
+ completion_kwargs["model"] = f"responses/{model}"
+
+ reasoning_effort = completion_kwargs.get("reasoning_effort")
+ if isinstance(reasoning_effort, str) and reasoning_effort:
+ completion_kwargs["reasoning_effort"] = {
+ "effort": reasoning_effort,
+ "summary": "detailed",
+ }
+ elif isinstance(reasoning_effort, dict):
+ if (
+ "summary" not in reasoning_effort
+ and "generate_summary" not in reasoning_effort
+ ):
+ updated_reasoning_effort = dict(reasoning_effort)
+ updated_reasoning_effort["summary"] = "detailed"
+ completion_kwargs["reasoning_effort"] = updated_reasoning_effort
+
@staticmethod
def _prepare_completion_kwargs(
*,
@@ -47,8 +109,14 @@ class LiteLLMMessagesToCompletionTransformationHandler:
top_p: Optional[float] = None,
output_format: Optional[Dict] = None,
extra_kwargs: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """Prepare kwargs for litellm.completion/acompletion"""
+ ) -> Tuple[Dict[str, Any], Dict[str, str]]:
+ """Prepare kwargs for litellm.completion/acompletion.
+
+ Returns:
+ Tuple of (completion_kwargs, tool_name_mapping)
+ - tool_name_mapping maps truncated tool names back to original names
+ for tools that exceeded OpenAI's 64-char limit
+ """
from litellm.litellm_core_utils.litellm_logging import (
Logging as LiteLLMLoggingObject,
)
@@ -80,7 +148,7 @@ class LiteLLMMessagesToCompletionTransformationHandler:
if output_format:
request_data["output_format"] = output_format
- openai_request = ANTHROPIC_ADAPTER.translate_completion_input_params(
+ openai_request, tool_name_mapping = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping(
request_data
)
@@ -116,7 +184,12 @@ class LiteLLMMessagesToCompletionTransformationHandler:
):
completion_kwargs[key] = value
- return completion_kwargs
+ LiteLLMMessagesToCompletionTransformationHandler._route_openai_thinking_to_responses_api_if_needed(
+ completion_kwargs,
+ thinking=thinking,
+ )
+
+ return completion_kwargs, tool_name_mapping
@staticmethod
async def async_anthropic_messages_handler(
@@ -137,7 +210,7 @@ class LiteLLMMessagesToCompletionTransformationHandler:
**kwargs,
) -> Union[AnthropicMessagesResponse, AsyncIterator]:
"""Handle non-Anthropic models asynchronously using the adapter"""
- completion_kwargs = (
+ completion_kwargs, tool_name_mapping = (
LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs(
max_tokens=max_tokens,
messages=messages,
@@ -164,6 +237,7 @@ class LiteLLMMessagesToCompletionTransformationHandler:
ANTHROPIC_ADAPTER.translate_completion_output_params_streaming(
completion_response,
model=model,
+ tool_name_mapping=tool_name_mapping,
)
)
if transformed_stream is not None:
@@ -172,7 +246,8 @@ class LiteLLMMessagesToCompletionTransformationHandler:
else:
anthropic_response = (
ANTHROPIC_ADAPTER.translate_completion_output_params(
- cast(ModelResponse, completion_response)
+ cast(ModelResponse, completion_response),
+ tool_name_mapping=tool_name_mapping,
)
)
if anthropic_response is not None:
@@ -222,7 +297,7 @@ class LiteLLMMessagesToCompletionTransformationHandler:
**kwargs,
)
- completion_kwargs = (
+ completion_kwargs, tool_name_mapping = (
LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs(
max_tokens=max_tokens,
messages=messages,
@@ -249,6 +324,7 @@ class LiteLLMMessagesToCompletionTransformationHandler:
ANTHROPIC_ADAPTER.translate_completion_output_params_streaming(
completion_response,
model=model,
+ tool_name_mapping=tool_name_mapping,
)
)
if transformed_stream is not None:
@@ -257,7 +333,8 @@ class LiteLLMMessagesToCompletionTransformationHandler:
else:
anthropic_response = (
ANTHROPIC_ADAPTER.translate_completion_output_params(
- cast(ModelResponse, completion_response)
+ cast(ModelResponse, completion_response),
+ tool_name_mapping=tool_name_mapping,
)
)
if anthropic_response is not None:
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
index 24524233ddf..de634ff9ecf 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
@@ -3,7 +3,7 @@
import json
import traceback
from collections import deque
-from typing import TYPE_CHECKING, Any, AsyncIterator, Iterator, Literal, Optional
+from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, Literal, Optional
from litellm import verbose_logger
from litellm._uuid import uuid
@@ -44,9 +44,16 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
pending_new_content_block: bool = False
chunk_queue: deque = deque() # Queue for buffering multiple chunks
- def __init__(self, completion_stream: Any, model: str):
+ def __init__(
+ self,
+ completion_stream: Any,
+ model: str,
+ tool_name_mapping: Optional[Dict[str, str]] = None,
+ ):
super().__init__(completion_stream)
self.model = model
+ # Mapping of truncated tool names to original names (for OpenAI's 64-char limit)
+ self.tool_name_mapping = tool_name_mapping or {}
def _create_initial_usage_delta(self) -> UsageDelta:
"""
@@ -232,8 +239,13 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
merged_chunk["delta"] = {}
# Add usage to the held chunk
+ uncached_input_tokens = chunk.usage.prompt_tokens or 0
+ if hasattr(chunk.usage, "prompt_tokens_details") and chunk.usage.prompt_tokens_details:
+ cached_tokens = getattr(chunk.usage.prompt_tokens_details, "cached_tokens", 0) or 0
+ uncached_input_tokens -= cached_tokens
+
usage_dict: UsageDelta = {
- "input_tokens": chunk.usage.prompt_tokens or 0,
+ "input_tokens": uncached_input_tokens,
"output_tokens": chunk.usage.completion_tokens or 0,
}
# Add cache tokens if available (for prompt caching support)
@@ -401,6 +413,20 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
choices=chunk.choices # type: ignore
)
+ # Restore original tool name if it was truncated for OpenAI's 64-char limit
+ if block_type == "tool_use":
+ # Type narrowing: content_block_start is ToolUseBlock when block_type is "tool_use"
+ from typing import cast
+
+ from litellm.types.llms.anthropic import ToolUseBlock
+
+ tool_block = cast(ToolUseBlock, content_block_start)
+
+ if tool_block.get("name"):
+ truncated_name = tool_block["name"]
+ original_name = self.tool_name_mapping.get(truncated_name, truncated_name)
+ tool_block["name"] = original_name
+
if block_type != self.current_content_block_type:
self.current_content_block_type = block_type
self.current_content_block_start = content_block_start
@@ -408,9 +434,15 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
# For parallel tool calls, we'll necessarily have a new content block
# if we get a function name since it signals a new tool call
- if block_type == "tool_use" and content_block_start.get("name"):
- self.current_content_block_type = block_type
- self.current_content_block_start = content_block_start
- return True
+ if block_type == "tool_use":
+ from typing import cast
+
+ from litellm.types.llms.anthropic import ToolUseBlock
+
+ tool_block = cast(ToolUseBlock, content_block_start)
+ if tool_block.get("name"):
+ self.current_content_block_type = block_type
+ self.current_content_block_start = content_block_start
+ return True
return False
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index 1706f045f14..8b21569546e 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@ -1,3 +1,4 @@
+import hashlib
import json
from typing import (
TYPE_CHECKING,
@@ -12,6 +13,54 @@ from typing import (
cast,
)
+# OpenAI has a 64-character limit for function/tool names
+# Anthropic does not have this limit, so we need to truncate long names
+OPENAI_MAX_TOOL_NAME_LENGTH = 64
+TOOL_NAME_HASH_LENGTH = 8
+TOOL_NAME_PREFIX_LENGTH = OPENAI_MAX_TOOL_NAME_LENGTH - TOOL_NAME_HASH_LENGTH - 1 # 55
+
+
+def truncate_tool_name(name: str) -> str:
+ """
+ Truncate tool names that exceed OpenAI's 64-character limit.
+
+ Uses format: {55-char-prefix}_{8-char-hash} to avoid collisions
+ when multiple tools have similar long names.
+
+ Args:
+ name: The original tool name
+
+ Returns:
+ The original name if <= 64 chars, otherwise truncated with hash
+ """
+ if len(name) <= OPENAI_MAX_TOOL_NAME_LENGTH:
+ return name
+
+ # Create deterministic hash from full name to avoid collisions
+ name_hash = hashlib.sha256(name.encode()).hexdigest()[:TOOL_NAME_HASH_LENGTH]
+ return f"{name[:TOOL_NAME_PREFIX_LENGTH]}_{name_hash}"
+
+
+def create_tool_name_mapping(
+ tools: List[Dict[str, Any]],
+) -> Dict[str, str]:
+ """
+ Create a mapping of truncated tool names to original names.
+
+ Args:
+ tools: List of tool definitions with 'name' field
+
+ Returns:
+ Dict mapping truncated names to original names (only for truncated tools)
+ """
+ mapping: Dict[str, str] = {}
+ for tool in tools:
+ original_name = tool.get("name", "")
+ truncated_name = truncate_tool_name(original_name)
+ if truncated_name != original_name:
+ mapping[truncated_name] = original_name
+ return mapping
+
from openai.types.chat.chat_completion_chunk import Choice as OpenAIStreamingChoice
from litellm.litellm_core_utils.prompt_templates.common_utils import (
@@ -77,8 +126,29 @@ class AnthropicAdapter:
self, kwargs
) -> Optional[ChatCompletionRequest]:
"""
+ Translate Anthropic request params to OpenAI format.
+
- translate params, where needed
- pass rest, as is
+
+ Note: Use translate_completion_input_params_with_tool_mapping() if you need
+ the tool name mapping for restoring original names in responses.
+ """
+ result, _ = self.translate_completion_input_params_with_tool_mapping(kwargs)
+ return result
+
+ def translate_completion_input_params_with_tool_mapping(
+ self, kwargs
+ ) -> Tuple[Optional[ChatCompletionRequest], Dict[str, str]]:
+ """
+ Translate Anthropic request params to OpenAI format, returning tool name mapping.
+
+ This method handles truncation of tool names that exceed OpenAI's 64-character
+ limit. The mapping allows restoring original names when translating responses.
+
+ Returns:
+ Tuple of (openai_request, tool_name_mapping)
+ - tool_name_mapping maps truncated tool names back to original names
"""
#########################################################
@@ -102,26 +172,51 @@ class AnthropicAdapter:
model=model, messages=messages, **kwargs
)
- translated_body = (
+ translated_body, tool_name_mapping = (
LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai(
anthropic_message_request=request_body
)
)
- return translated_body
+ return translated_body, tool_name_mapping
def translate_completion_output_params(
- self, response: ModelResponse
+ self,
+ response: ModelResponse,
+ tool_name_mapping: Optional[Dict[str, str]] = None,
) -> Optional[AnthropicMessagesResponse]:
+ """
+ Translate OpenAI response to Anthropic format.
+
+ Args:
+ response: The OpenAI ModelResponse
+ tool_name_mapping: Optional mapping of truncated tool names to original names.
+ Used to restore original names for tools that exceeded
+ OpenAI's 64-char limit.
+ """
return LiteLLMAnthropicMessagesAdapter().translate_openai_response_to_anthropic(
- response=response
+ response=response,
+ tool_name_mapping=tool_name_mapping,
)
def translate_completion_output_params_streaming(
- self, completion_stream: Any, model: str
+ self,
+ completion_stream: Any,
+ model: str,
+ tool_name_mapping: Optional[Dict[str, str]] = None,
) -> Union[AsyncIterator[bytes], None]:
+ """
+ Translate OpenAI streaming response to Anthropic format.
+
+ Args:
+ completion_stream: The OpenAI streaming response
+ model: The model name
+ tool_name_mapping: Optional mapping of truncated tool names to original names.
+ """
anthropic_wrapper = AnthropicStreamWrapper(
- completion_stream=completion_stream, model=model
+ completion_stream=completion_stream,
+ model=model,
+ tool_name_mapping=tool_name_mapping,
)
# Return the SSE-wrapped version for proper event formatting
return anthropic_wrapper.async_anthropic_sse_wrapper()
@@ -168,12 +263,62 @@ class LiteLLMAnthropicMessagesAdapter:
return provider_specific_fields.get("signature")
return None
+ def _add_cache_control_if_applicable(
+ self,
+ source: Any,
+ target: Any,
+ model: Optional[str],
+ ) -> None:
+ """
+ Extract cache_control from source and add to target if it should be preserved.
+
+ This method accepts Any type to support both regular dicts and TypedDict objects.
+ TypedDict objects (like ChatCompletionTextObject, ChatCompletionImageObject, etc.)
+ are dicts at runtime but have specific types at type-check time. Using Any allows
+ this method to work with both while maintaining runtime correctness.
+
+ Args:
+ source: Dict or TypedDict containing potential cache_control field
+ target: Dict or TypedDict to add cache_control to
+ model: Model name to check if cache_control should be preserved
+ """
+ # TypedDict objects are dicts at runtime, so .get() works
+ cache_control = source.get("cache_control") if isinstance(source, dict) else getattr(source, "cache_control", None)
+ if cache_control and model and self.is_anthropic_claude_model(model):
+ # TypedDict objects support dict operations at runtime
+ # Use type ignore consistent with codebase pattern (see anthropic/chat/transformation.py:432)
+ if isinstance(target, dict):
+ target["cache_control"] = cache_control # type: ignore[typeddict-item]
+ else:
+ # Fallback for non-dict objects (shouldn't happen in practice)
+ cast(Dict[str, Any], target)["cache_control"] = cache_control
+
def translatable_anthropic_params(self) -> List:
"""
Which anthropic params, we need to translate to the openai format.
"""
return ["messages", "metadata", "system", "tool_choice", "tools", "thinking", "output_format"]
+ def _is_web_search_tool(self, tool: Dict[str, Any]) -> bool:
+ """
+ Check if a tool is an Anthropic web search tool.
+
+ Anthropic web search tools have:
+ - type starting with "web_search" (e.g., "web_search_20260209")
+ - name = "web_search"
+
+ Args:
+ tool: Tool definition dict
+
+ Returns:
+ True if this is a web search tool
+ """
+ tool_type = tool.get("type", "")
+ tool_name = tool.get("name", "")
+ return (
+ isinstance(tool_type, str) and tool_type.startswith("web_search")
+ ) or tool_name == "web_search"
+
def translate_anthropic_messages_to_openai( # noqa: PLR0915
self,
messages: List[
@@ -205,12 +350,8 @@ class LiteLLMAnthropicMessagesAdapter:
text_obj = ChatCompletionTextObject(
type="text", text=content.get("text", "")
)
- # Preserve cache_control if present (for prompt caching)
- # Only for Anthropic models that support prompt caching
- cache_control = content.get("cache_control")
- if cache_control and model and self.is_anthropic_claude_model(model):
- text_obj["cache_control"] = cache_control # type: ignore
- new_user_content_list.append(text_obj)
+ self._add_cache_control_if_applicable(content, text_obj, model)
+ new_user_content_list.append(text_obj) # type: ignore
elif content.get("type") == "image":
# Convert Anthropic image format to OpenAI format
source = content.get("source", {})
@@ -225,7 +366,24 @@ class LiteLLMAnthropicMessagesAdapter:
image_obj = ChatCompletionImageObject(
type="image_url", image_url=image_url_obj
)
- new_user_content_list.append(image_obj)
+ self._add_cache_control_if_applicable(content, image_obj, model)
+ new_user_content_list.append(image_obj) # type: ignore
+ elif content.get("type") == "document":
+ # Convert Anthropic document format (PDF, etc.) to OpenAI format
+ source = content.get("source", {})
+ openai_image_url = (
+ self._translate_anthropic_image_to_openai(cast(dict, source))
+ )
+
+ if openai_image_url:
+ image_url_obj = ChatCompletionImageUrlObject(
+ url=openai_image_url
+ )
+ doc_obj = ChatCompletionImageObject(
+ type="image_url", image_url=image_url_obj
+ )
+ self._add_cache_control_if_applicable(content, doc_obj, model)
+ new_user_content_list.append(doc_obj) # type: ignore
elif content.get("type") == "tool_result":
if "content" not in content:
tool_result = ChatCompletionToolMessage(
@@ -233,14 +391,16 @@ class LiteLLMAnthropicMessagesAdapter:
tool_call_id=content.get("tool_use_id", ""),
content="",
)
- tool_message_list.append(tool_result)
+ self._add_cache_control_if_applicable(content, tool_result, model)
+ tool_message_list.append(tool_result) # type: ignore[arg-type]
elif isinstance(content.get("content"), str):
tool_result = ChatCompletionToolMessage(
role="tool",
tool_call_id=content.get("tool_use_id", ""),
content=str(content.get("content", "")),
)
- tool_message_list.append(tool_result)
+ self._add_cache_control_if_applicable(content, tool_result, model)
+ tool_message_list.append(tool_result) # type: ignore[arg-type]
elif isinstance(content.get("content"), list):
# Combine all content items into a single tool message
# to avoid creating multiple tool_result blocks with the same ID
@@ -256,7 +416,8 @@ class LiteLLMAnthropicMessagesAdapter:
tool_call_id=content.get("tool_use_id", ""),
content=c,
)
- tool_message_list.append(tool_result)
+ self._add_cache_control_if_applicable(content, tool_result, model)
+ tool_message_list.append(tool_result) # type: ignore[arg-type]
elif isinstance(c, dict):
if c.get("type") == "text":
tool_result = ChatCompletionToolMessage(
@@ -266,7 +427,8 @@ class LiteLLMAnthropicMessagesAdapter:
),
content=c.get("text", ""),
)
- tool_message_list.append(tool_result)
+ self._add_cache_control_if_applicable(content, tool_result, model)
+ tool_message_list.append(tool_result) # type: ignore[arg-type]
elif c.get("type") == "image":
source = c.get("source", {})
openai_image_url = (
@@ -282,7 +444,8 @@ class LiteLLMAnthropicMessagesAdapter:
),
content=openai_image_url,
)
- tool_message_list.append(tool_result)
+ self._add_cache_control_if_applicable(content, tool_result, model)
+ tool_message_list.append(tool_result) # type: ignore[arg-type]
else:
# For multiple content items, combine into a single tool message
# with list content to preserve all items while having one tool_use_id
@@ -331,7 +494,8 @@ class LiteLLMAnthropicMessagesAdapter:
tool_call_id=content.get("tool_use_id", ""),
content=combined_content_parts, # type: ignore
)
- tool_message_list.append(tool_result)
+ self._add_cache_control_if_applicable(content, tool_result, model)
+ tool_message_list.append(tool_result) # type: ignore[arg-type]
if len(tool_message_list) > 0:
new_messages.extend(tool_message_list)
@@ -344,6 +508,8 @@ class LiteLLMAnthropicMessagesAdapter:
## ASSISTANT MESSAGE ##
assistant_message_str: Optional[str] = None
+ assistant_content_list: List[Dict[str, Any]] = [] # For content blocks with cache_control
+ has_cache_control_in_text = False
tool_calls: List[ChatCompletionAssistantToolCall] = []
thinking_blocks: List[
Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]
@@ -357,13 +523,19 @@ class LiteLLMAnthropicMessagesAdapter:
assistant_message_str = str(content)
elif isinstance(content, dict):
if content.get("type") == "text":
- if assistant_message_str is None:
- assistant_message_str = content.get("text", "")
- else:
- assistant_message_str += content.get("text", "")
+ text_block: Dict[str, Any] = {
+ "type": "text",
+ "text": content.get("text", ""),
+ }
+ self._add_cache_control_if_applicable(content, text_block, model)
+ if "cache_control" in text_block:
+ has_cache_control_in_text = True
+ assistant_content_list.append(text_block)
elif content.get("type") == "tool_use":
+ # Truncate tool name for OpenAI's 64-char limit
+ tool_name = truncate_tool_name(content.get("name", ""))
function_chunk: ChatCompletionToolCallFunctionChunk = {
- "name": content.get("name", ""),
+ "name": tool_name,
"arguments": json.dumps(content.get("input", {})),
}
signature = (
@@ -384,13 +556,13 @@ class LiteLLMAnthropicMessagesAdapter:
provider_specific_fields
)
- tool_calls.append(
- ChatCompletionAssistantToolCall(
- id=content.get("id", ""),
- type="function",
- function=function_chunk,
- )
+ tool_call = ChatCompletionAssistantToolCall(
+ id=content.get("id", ""),
+ type="function",
+ function=function_chunk,
)
+ self._add_cache_control_if_applicable(content, tool_call, model)
+ tool_calls.append(tool_call)
elif content.get("type") == "thinking":
thinking_block = ChatCompletionThinkingBlock(
type="thinking",
@@ -411,18 +583,30 @@ class LiteLLMAnthropicMessagesAdapter:
if (
assistant_message_str is not None
+ or len(assistant_content_list) > 0
or len(tool_calls) > 0
or len(thinking_blocks) > 0
):
+ # Use list format if any text block has cache_control, otherwise use string
+ if has_cache_control_in_text and len(assistant_content_list) > 0:
+ assistant_content: Any = assistant_content_list
+ elif len(assistant_content_list) > 0 and not has_cache_control_in_text:
+ # Concatenate text blocks into string when no cache_control
+ assistant_content = "".join(
+ block.get("text", "") for block in assistant_content_list
+ )
+ else:
+ assistant_content = assistant_message_str
+
assistant_message = ChatCompletionAssistantMessage(
role="assistant",
- content=assistant_message_str,
+ content=assistant_content,
thinking_blocks=(
thinking_blocks if len(thinking_blocks) > 0 else None
),
)
if len(tool_calls) > 0:
- assistant_message["tool_calls"] = tool_calls
+ assistant_message["tool_calls"] = tool_calls # type: ignore
if len(thinking_blocks) > 0:
assistant_message["thinking_blocks"] = thinking_blocks # type: ignore
new_messages.append(assistant_message)
@@ -520,8 +704,11 @@ class LiteLLMAnthropicMessagesAdapter:
elif tool_choice["type"] == "auto":
return "auto"
elif tool_choice["type"] == "tool":
+ # Truncate tool name if it exceeds OpenAI's 64-char limit
+ original_name = tool_choice.get("name", "")
+ truncated_name = truncate_tool_name(original_name)
tc_function_param = ChatCompletionToolChoiceFunctionParam(
- name=tool_choice.get("name", "")
+ name=truncated_name
)
return ChatCompletionToolChoiceObjectParam(
type="function", function=tc_function_param
@@ -532,13 +719,29 @@ class LiteLLMAnthropicMessagesAdapter:
)
def translate_anthropic_tools_to_openai(
- self, tools: List[AllAnthropicToolsValues]
- ) -> List[ChatCompletionToolParam]:
+ self, tools: List[AllAnthropicToolsValues], model: Optional[str] = None
+ ) -> Tuple[List[ChatCompletionToolParam], Dict[str, str]]:
+ """
+ Translate Anthropic tools to OpenAI format.
+
+ Returns:
+ Tuple of (translated_tools, tool_name_mapping)
+ - tool_name_mapping maps truncated names back to original names
+ for tools that exceeded OpenAI's 64-char limit
+ """
new_tools: List[ChatCompletionToolParam] = []
- mapped_tool_params = ["name", "input_schema", "description"]
+ tool_name_mapping: Dict[str, str] = {}
+ mapped_tool_params = ["name", "input_schema", "description", "cache_control"]
for tool in tools:
+ original_name = tool["name"]
+ truncated_name = truncate_tool_name(original_name)
+
+ # Store mapping if name was truncated
+ if truncated_name != original_name:
+ tool_name_mapping[truncated_name] = original_name
+
function_chunk = ChatCompletionToolParamFunctionChunk(
- name=tool["name"],
+ name=truncated_name,
)
if "input_schema" in tool:
function_chunk["parameters"] = tool["input_schema"] # type: ignore
@@ -548,11 +751,11 @@ class LiteLLMAnthropicMessagesAdapter:
for k, v in tool.items():
if k not in mapped_tool_params: # pass additional computer kwargs
function_chunk.setdefault("parameters", {}).update({k: v})
- new_tools.append(
- ChatCompletionToolParam(type="function", function=function_chunk)
- )
+ tool_param = ChatCompletionToolParam(type="function", function=function_chunk)
+ self._add_cache_control_if_applicable(tool, tool_param, model)
+ new_tools.append(tool_param) # type: ignore[arg-type]
- return new_tools
+ return new_tools, tool_name_mapping # type: ignore[return-value]
def translate_anthropic_output_format_to_openai(
self, output_format: Any
@@ -590,14 +793,55 @@ class LiteLLMAnthropicMessagesAdapter:
},
}
+ def _add_system_message_to_messages(
+ self,
+ new_messages: List[AllMessageValues],
+ anthropic_message_request: AnthropicMessagesRequest,
+ ) -> None:
+ """Add system message to messages list if present in request."""
+ if "system" not in anthropic_message_request:
+ return
+ system_content = anthropic_message_request["system"]
+ if not system_content:
+ return
+ # Handle system as string or array of content blocks
+ if isinstance(system_content, str):
+ new_messages.insert(
+ 0,
+ ChatCompletionSystemMessage(role="system", content=system_content),
+ )
+ elif isinstance(system_content, list):
+ # Convert Anthropic system content blocks to OpenAI format
+ openai_system_content: List[Dict[str, Any]] = []
+ model_name = anthropic_message_request.get("model", "")
+ for block in system_content:
+ if isinstance(block, dict) and block.get("type") == "text":
+ text_block: Dict[str, Any] = {
+ "type": "text",
+ "text": block.get("text", ""),
+ }
+ self._add_cache_control_if_applicable(block, text_block, model_name)
+ openai_system_content.append(text_block)
+ if openai_system_content:
+ new_messages.insert(
+ 0,
+ ChatCompletionSystemMessage(role="system", content=openai_system_content), # type: ignore
+ )
+
def translate_anthropic_to_openai(
self, anthropic_message_request: AnthropicMessagesRequest
- ) -> ChatCompletionRequest:
+ ) -> Tuple[ChatCompletionRequest, Dict[str, str]]:
"""
This is used by the beta Anthropic Adapter, for translating anthropic `/v1/messages` requests to the openai format.
+
+ Returns:
+ Tuple of (openai_request, tool_name_mapping)
+ - tool_name_mapping maps truncated tool names back to original names
+ for tools that exceeded OpenAI's 64-char limit
"""
# Debug: Processing Anthropic message request
new_messages: List[AllMessageValues] = []
+ tool_name_mapping: Dict[str, str] = {}
## CONVERT ANTHROPIC MESSAGES TO OPENAI
messages_list: List[
@@ -618,13 +862,7 @@ class LiteLLMAnthropicMessagesAdapter:
model=anthropic_message_request.get("model"),
)
## ADD SYSTEM MESSAGE TO MESSAGES
- if "system" in anthropic_message_request:
- system_content = anthropic_message_request["system"]
- if system_content:
- new_messages.insert(
- 0,
- ChatCompletionSystemMessage(role="system", content=system_content),
- )
+ self._add_system_message_to_messages(new_messages, anthropic_message_request)
new_kwargs: ChatCompletionRequest = {
"model": anthropic_message_request["model"],
@@ -654,9 +892,25 @@ class LiteLLMAnthropicMessagesAdapter:
if "tools" in anthropic_message_request:
tools = anthropic_message_request["tools"]
if tools:
- new_kwargs["tools"] = self.translate_anthropic_tools_to_openai(
- tools=cast(List[AllAnthropicToolsValues], tools)
- )
+ # Separate web search tools from regular tools
+ web_search_tools = []
+ regular_tools = []
+ for tool in tools:
+ if self._is_web_search_tool(cast(Dict[str, Any], tool)):
+ web_search_tools.append(tool)
+ else:
+ regular_tools.append(tool)
+
+ # If web search tools are present, add web_search_options parameter
+ if web_search_tools:
+ new_kwargs["web_search_options"] = {} # type: ignore
+
+ # Only translate regular tools (non-web-search)
+ if regular_tools:
+ new_kwargs["tools"], tool_name_mapping = self.translate_anthropic_tools_to_openai(
+ tools=cast(List[AllAnthropicToolsValues], regular_tools),
+ model=new_kwargs.get("model"),
+ )
## CONVERT THINKING
if "thinking" in anthropic_message_request:
@@ -687,7 +941,7 @@ class LiteLLMAnthropicMessagesAdapter:
if k not in translatable_params: # pass remaining params as is
new_kwargs[k] = v # type: ignore
- return new_kwargs
+ return new_kwargs, tool_name_mapping
def _translate_anthropic_image_to_openai(self, image_source: dict) -> Optional[str]:
"""
@@ -716,22 +970,12 @@ class LiteLLMAnthropicMessagesAdapter:
return None
- def _translate_openai_content_to_anthropic(self, choices: List[Choices]) -> List[
- Union[
- AnthropicResponseContentBlockText,
- AnthropicResponseContentBlockToolUse,
- AnthropicResponseContentBlockThinking,
- AnthropicResponseContentBlockRedactedThinking,
- ]
- ]:
- new_content: List[
- Union[
- AnthropicResponseContentBlockText,
- AnthropicResponseContentBlockToolUse,
- AnthropicResponseContentBlockThinking,
- AnthropicResponseContentBlockRedactedThinking,
- ]
- ] = []
+ def _translate_openai_content_to_anthropic(
+ self,
+ choices: List[Choices],
+ tool_name_mapping: Optional[Dict[str, str]] = None,
+ ) -> List[Dict[str, Any]]:
+ new_content: List[Dict[str, Any]] = []
for choice in choices:
# Handle thinking blocks first
if (
@@ -755,7 +999,7 @@ class LiteLLMAnthropicMessagesAdapter:
if signature_value is not None
else None
),
- )
+ ).model_dump()
)
elif thinking_block.get("type") == "redacted_thinking":
data_value = thinking_block.get("data", "")
@@ -763,15 +1007,27 @@ class LiteLLMAnthropicMessagesAdapter:
AnthropicResponseContentBlockRedactedThinking(
type="redacted_thinking",
data=str(data_value) if data_value is not None else "",
- )
+ ).model_dump()
)
+ # Handle reasoning_content when thinking_blocks is not present
+ elif (
+ hasattr(choice.message, "reasoning_content")
+ and choice.message.reasoning_content
+ ):
+ new_content.append(
+ AnthropicResponseContentBlockThinking(
+ type="thinking",
+ thinking=str(choice.message.reasoning_content),
+ signature=None,
+ ).model_dump()
+ )
# Handle text content
if choice.message.content is not None:
new_content.append(
AnthropicResponseContentBlockText(
type="text", text=choice.message.content
- )
+ ).model_dump()
)
# Handle tool calls (in parallel to text content)
if (
@@ -786,13 +1042,21 @@ class LiteLLMAnthropicMessagesAdapter:
if signature:
provider_specific_fields["signature"] = signature
+ # Restore original tool name if it was truncated
+ truncated_name = tool_call.function.name or ""
+ original_name = (
+ tool_name_mapping.get(truncated_name, truncated_name)
+ if tool_name_mapping
+ else truncated_name
+ )
+
tool_use_block = AnthropicResponseContentBlockToolUse(
type="tool_use",
id=tool_call.id,
- name=tool_call.function.name or "",
+ name=original_name,
input=parse_tool_call_arguments(
tool_call.function.arguments,
- tool_name=tool_call.function.name,
+ tool_name=original_name,
context="Anthropic pass-through adapter",
),
)
@@ -801,7 +1065,7 @@ class LiteLLMAnthropicMessagesAdapter:
tool_use_block.provider_specific_fields = (
provider_specific_fields
)
- new_content.append(tool_use_block)
+ new_content.append(tool_use_block.model_dump())
return new_content
@@ -817,18 +1081,37 @@ class LiteLLMAnthropicMessagesAdapter:
return "end_turn"
def translate_openai_response_to_anthropic(
- self, response: ModelResponse
+ self,
+ response: ModelResponse,
+ tool_name_mapping: Optional[Dict[str, str]] = None,
) -> AnthropicMessagesResponse:
+ """
+ Translate OpenAI response to Anthropic format.
+
+ Args:
+ response: The OpenAI ModelResponse
+ tool_name_mapping: Optional mapping of truncated tool names to original names.
+ Used to restore original names for tools that exceeded
+ OpenAI's 64-char limit.
+ """
## translate content block
- anthropic_content = self._translate_openai_content_to_anthropic(choices=response.choices) # type: ignore
+ anthropic_content = self._translate_openai_content_to_anthropic(
+ choices=response.choices, # type: ignore
+ tool_name_mapping=tool_name_mapping,
+ )
## extract finish reason
anthropic_finish_reason = self._translate_openai_finish_reason_to_anthropic(
openai_finish_reason=response.choices[0].finish_reason # type: ignore
)
# extract usage
usage: Usage = getattr(response, "usage")
+ uncached_input_tokens = usage.prompt_tokens or 0
+ if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details:
+ cached_tokens = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0
+ uncached_input_tokens -= cached_tokens
+
anthropic_usage = AnthropicUsage(
- input_tokens=usage.prompt_tokens or 0,
+ input_tokens=uncached_input_tokens,
output_tokens=usage.completion_tokens or 0,
)
# Add cache tokens if available (for prompt caching support)
@@ -843,7 +1126,7 @@ class LiteLLMAnthropicMessagesAdapter:
role="assistant",
model=response.model or "unknown-model",
stop_sequence=None,
- usage=anthropic_usage,
+ usage=anthropic_usage, # type: ignore
content=anthropic_content, # type: ignore
stop_reason=anthropic_finish_reason,
)
@@ -939,6 +1222,13 @@ class LiteLLMAnthropicMessagesAdapter:
reasoning_content += thinking
reasoning_signature += signature
+ # Handle reasoning_content when thinking_blocks is not present
+ # This handles providers like OpenRouter that return reasoning_content
+ elif isinstance(choice, StreamingChoices) and hasattr(
+ choice.delta, "reasoning_content"
+ ):
+ if choice.delta.reasoning_content is not None:
+ reasoning_content += choice.delta.reasoning_content
if reasoning_content and reasoning_signature:
raise ValueError(
@@ -980,8 +1270,13 @@ class LiteLLMAnthropicMessagesAdapter:
else:
litellm_usage_chunk = None
if litellm_usage_chunk is not None:
+ uncached_input_tokens = litellm_usage_chunk.prompt_tokens or 0
+ if hasattr(litellm_usage_chunk, "prompt_tokens_details") and litellm_usage_chunk.prompt_tokens_details:
+ cached_tokens = getattr(litellm_usage_chunk.prompt_tokens_details, "cached_tokens", 0) or 0
+ uncached_input_tokens -= cached_tokens
+
usage_delta = UsageDelta(
- input_tokens=litellm_usage_chunk.prompt_tokens or 0,
+ input_tokens=uncached_input_tokens,
output_tokens=litellm_usage_chunk.completion_tokens or 0,
)
# Add cache tokens if available (for prompt caching support)
@@ -992,7 +1287,7 @@ class LiteLLMAnthropicMessagesAdapter:
else:
usage_delta = UsageDelta(input_tokens=0, output_tokens=0)
return MessageBlockDelta(
- type="message_delta", delta=delta, usage=usage_delta
+ type="message_delta", delta=delta, usage=usage_delta # type: ignore
)
(
type_of_content,
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
index 308bf367d06..8275ba2b3e1 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
@@ -43,10 +43,49 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):
"thinking",
"context_management",
"output_format",
+ "inference_geo",
+ "speed",
+ "output_config",
# TODO: Add Anthropic `metadata` support
# "metadata",
]
+ @staticmethod
+ def _filter_billing_headers_from_system(system_param):
+ """
+ Filter out x-anthropic-billing-header metadata from system parameter.
+
+ Args:
+ system_param: Can be a string or a list of system message content blocks
+
+ Returns:
+ Filtered system parameter (string or list), or None if all content was filtered
+ """
+ if isinstance(system_param, str):
+ # If it's a string and starts with billing header, filter it out
+ if system_param.startswith("x-anthropic-billing-header:"):
+ return None
+ return system_param
+ elif isinstance(system_param, list):
+ # Filter list of system content blocks
+ filtered_list = []
+ for content_block in system_param:
+ if isinstance(content_block, dict):
+ text = content_block.get("text", "")
+ content_type = content_block.get("type", "")
+ # Skip text blocks that start with billing header
+ if content_type == "text" and text.startswith(
+ "x-anthropic-billing-header:"
+ ):
+ continue
+ filtered_list.append(content_block)
+ else:
+ # Keep non-dict items as-is
+ filtered_list.append(content_block)
+ return filtered_list if len(filtered_list) > 0 else None
+ else:
+ return system_param
+
def get_complete_url(
self,
api_base: Optional[str],
@@ -74,11 +113,13 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):
import os
# Check for Anthropic OAuth token in Authorization header
- headers, api_key = optionally_handle_anthropic_oauth(headers=headers, api_key=api_key)
+ headers, api_key = optionally_handle_anthropic_oauth(
+ headers=headers, api_key=api_key
+ )
if api_key is None:
api_key = os.getenv("ANTHROPIC_API_KEY")
- if "x-api-key" not in headers and api_key:
+ if "x-api-key" not in headers and "authorization" not in headers and api_key:
headers["x-api-key"] = api_key
if "anthropic-version" not in headers:
headers["anthropic-version"] = DEFAULT_ANTHROPIC_API_VERSION
@@ -112,6 +153,17 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):
message="max_tokens is required for Anthropic /v1/messages API",
status_code=400,
)
+
+ # Filter out x-anthropic-billing-header from system messages
+ system_param = anthropic_messages_optional_request_params.get("system")
+ if system_param is not None:
+ filtered_system = self._filter_billing_headers_from_system(system_param)
+ if filtered_system is not None and len(filtered_system) > 0:
+ anthropic_messages_optional_request_params["system"] = filtered_system
+ else:
+ # Remove system parameter if all content was filtered out
+ anthropic_messages_optional_request_params.pop("system", None)
+
####### get required params for all anthropic messages requests ######
verbose_logger.debug(f"TRANSFORMATION DEBUG - Messages: {messages}")
anthropic_messages_request: AnthropicMessagesRequest = AnthropicMessagesRequest(
@@ -175,10 +227,11 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):
- context_management: adds 'context-management-2025-06-27'
- tool_search: adds provider-specific tool search header
- output_format: adds 'structured-outputs-2025-11-13'
+ - speed: adds 'fast-mode-2026-02-01'
Args:
headers: Request headers dict
- optional_params: Optional parameters including tools, context_management, output_format
+ optional_params: Optional parameters including tools, context_management, output_format, speed
custom_llm_provider: Provider name for looking up correct tool search header
"""
beta_values: set = set()
@@ -189,12 +242,39 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):
beta_values.update(b.strip() for b in existing_beta.split(","))
# Check for context management
- if optional_params.get("context_management") is not None:
- beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value)
+ context_management_param = optional_params.get("context_management")
+ if context_management_param is not None:
+ # Check edits array for compact_20260112 type
+ edits = context_management_param.get("edits", [])
+ has_compact = False
+ has_other = False
+
+ for edit in edits:
+ edit_type = edit.get("type", "")
+ if edit_type == "compact_20260112":
+ has_compact = True
+ else:
+ has_other = True
+
+ # Add compact header if any compact edits exist
+ if has_compact:
+ beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value)
+
+ # Add context management header if any other edits exist
+ if has_other:
+ beta_values.add(
+ ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value
+ )
# Check for structured outputs
if optional_params.get("output_format") is not None:
- beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value)
+ beta_values.add(
+ ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value
+ )
+
+ # Check for fast mode
+ if optional_params.get("speed") == "fast":
+ beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.FAST_MODE_2026_02_01.value)
# Check for tool search tools
tools = optional_params.get("tools")
diff --git a/litellm/llms/azure/azure.py b/litellm/llms/azure/azure.py
index cb9fe0aeb30..44ee51d14ab 100644
--- a/litellm/llms/azure/azure.py
+++ b/litellm/llms/azure/azure.py
@@ -901,7 +901,20 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM):
if response.json()["status"] == "failed":
error_data = response.json()
- raise AzureOpenAIError(status_code=400, message=json.dumps(error_data))
+ # Preserve Azure error details (e.g. content_policy_violation,
+ # inner_error, content_filter_results) as structured body so
+ # exception_type() can route them correctly.
+ _error_body = error_data.get("error", error_data)
+ _error_msg = (
+ _error_body.get("message", "Image generation failed")
+ if isinstance(_error_body, dict)
+ else json.dumps(error_data)
+ )
+ raise AzureOpenAIError(
+ status_code=400,
+ message=_error_msg,
+ body=error_data,
+ )
result = response.json()["result"]
return httpx.Response(
@@ -999,7 +1012,20 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM):
if response.json()["status"] == "failed":
error_data = response.json()
- raise AzureOpenAIError(status_code=400, message=json.dumps(error_data))
+ # Preserve Azure error details (e.g. content_policy_violation,
+ # inner_error, content_filter_results) as structured body so
+ # exception_type() can route them correctly.
+ _error_body = error_data.get("error", error_data)
+ _error_msg = (
+ _error_body.get("message", "Image generation failed")
+ if isinstance(_error_body, dict)
+ else json.dumps(error_data)
+ )
+ raise AzureOpenAIError(
+ status_code=400,
+ message=_error_msg,
+ body=error_data,
+ )
result = response.json()["result"]
return httpx.Response(
@@ -1060,6 +1086,7 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM):
headers: dict,
client=None,
timeout=None,
+ model: Optional[str] = None,
) -> ImageResponse:
response: Optional[dict] = None
@@ -1071,8 +1098,9 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM):
if api_base.endswith("/"):
api_base = api_base.rstrip("/")
api_version: str = azure_client_params.get("api_version", "")
+ # Use the deployment name (model) for URL construction, not the base_model from data
img_gen_api_base = self.create_azure_base_url(
- azure_client_params=azure_client_params, model=data.get("model", "")
+ azure_client_params=azure_client_params, model=model or data.get("model", "")
)
## LOGGING
@@ -1159,21 +1187,20 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM):
model = model
else:
model = None
-
## BASE MODEL CHECK
if (
model_response is not None
- and optional_params.get("base_model", None) is not None
+ and litellm_params is not None
+ and litellm_params.get("base_model", None) is not None
):
- model_response._hidden_params["model"] = optional_params.pop(
- "base_model"
- )
+ model_response._hidden_params["model"] = litellm_params.get("base_model", None)
# Azure image generation API doesn't support extra_body parameter
extra_body = optional_params.pop("extra_body", {})
flattened_params = {**optional_params, **extra_body}
- data = {"model": model, "prompt": prompt, **flattened_params}
+ base_model = litellm_params.get("base_model", None) if litellm_params else None
+ data = {"model": base_model or model, "prompt": prompt, **flattened_params}
max_retries = data.pop("max_retries", 2)
if not isinstance(max_retries, int):
raise AzureOpenAIError(
@@ -1196,10 +1223,11 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM):
is_async=False,
)
if aimg_generation is True:
- return self.aimage_generation(data=data, input=input, logging_obj=logging_obj, model_response=model_response, api_key=api_key, client=client, azure_client_params=azure_client_params, timeout=timeout, headers=headers) # type: ignore
+ return self.aimage_generation(data=data, input=input, logging_obj=logging_obj, model_response=model_response, api_key=api_key, client=client, azure_client_params=azure_client_params, timeout=timeout, headers=headers, model=model) # type: ignore
+ # Use the deployment name (model) for URL construction, not the base_model from data
img_gen_api_base = self.create_azure_base_url(
- azure_client_params=azure_client_params, model=data.get("model", "")
+ azure_client_params=azure_client_params, model=model
)
## LOGGING
diff --git a/litellm/llms/azure/batches/handler.py b/litellm/llms/azure/batches/handler.py
index 3996cb808e4..aaefe801687 100644
--- a/litellm/llms/azure/batches/handler.py
+++ b/litellm/llms/azure/batches/handler.py
@@ -5,12 +5,10 @@ Azure Batches API Handler
from typing import Any, Coroutine, Optional, Union, cast
import httpx
-
from openai import AsyncOpenAI, OpenAI
from litellm.llms.azure.azure import AsyncAzureOpenAI, AzureOpenAI
from litellm.types.llms.openai import (
- Batch,
CancelBatchRequest,
CreateBatchRequest,
RetrieveBatchRequest,
@@ -130,9 +128,9 @@ class AzureBatchesAPI(BaseAzureLLM):
self,
cancel_batch_data: CancelBatchRequest,
client: Union[AsyncAzureOpenAI, AsyncOpenAI],
- ) -> Batch:
+ ) -> LiteLLMBatch:
response = await client.batches.cancel(**cancel_batch_data)
- return response
+ return LiteLLMBatch(**response.model_dump())
def cancel_batch(
self,
@@ -160,8 +158,23 @@ class AzureBatchesAPI(BaseAzureLLM):
raise ValueError(
"OpenAI client is not initialized. Make sure api_key is passed or OPENAI_API_KEY is set in the environment."
)
+
+ if _is_async is True:
+ if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)):
+ raise ValueError(
+ "Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI. Make sure you passed an async client."
+ )
+ return self.acancel_batch( # type: ignore
+ cancel_batch_data=cancel_batch_data, client=azure_client
+ )
+
+ # At this point, azure_client is guaranteed to be a sync client
+ if not isinstance(azure_client, (AzureOpenAI, OpenAI)):
+ raise ValueError(
+ "Azure client is not an instance of AzureOpenAI or OpenAI. Make sure you passed a sync client."
+ )
response = azure_client.batches.cancel(**cancel_batch_data)
- return response
+ return LiteLLMBatch(**response.model_dump())
async def alist_batches(
self,
diff --git a/litellm/llms/azure/chat/gpt_5_transformation.py b/litellm/llms/azure/chat/gpt_5_transformation.py
index 506b7fdfe5e..eeb55911ecf 100644
--- a/litellm/llms/azure/chat/gpt_5_transformation.py
+++ b/litellm/llms/azure/chat/gpt_5_transformation.py
@@ -22,7 +22,8 @@ class AzureOpenAIGPT5Config(AzureOpenAIConfig, OpenAIGPT5Config):
Accepts both explicit gpt-5 model names and the ``gpt5_series/`` prefix
used for manual routing.
"""
- return "gpt-5" in model or "gpt5_series" in model
+ # gpt-5-chat* is a chat model and shouldn't go through GPT-5 reasoning restrictions.
+ return ("gpt-5" in model and "gpt-5-chat" not in model) or "gpt5_series" in model
def get_supported_openai_params(self, model: str) -> List[str]:
"""Get supported parameters for Azure OpenAI GPT-5 models.
@@ -37,6 +38,11 @@ class AzureOpenAIGPT5Config(AzureOpenAIConfig, OpenAIGPT5Config):
"""
params = OpenAIGPT5Config.get_supported_openai_params(self, model=model)
+ # Azure supports tool_choice for GPT-5 deployments, but the base GPT-5 config
+ # can drop it when the deployment name isn't in the OpenAI model registry.
+ if "tool_choice" not in params:
+ params.append("tool_choice")
+
# Only gpt-5.2 has been verified to support logprobs on Azure
if self.is_model_gpt_5_2_model(model):
azure_supported_params = ["logprobs", "top_logprobs"]
diff --git a/litellm/llms/azure/chat/gpt_transformation.py b/litellm/llms/azure/chat/gpt_transformation.py
index 0ae6fad7300..18dad503a59 100644
--- a/litellm/llms/azure/chat/gpt_transformation.py
+++ b/litellm/llms/azure/chat/gpt_transformation.py
@@ -105,6 +105,7 @@ class AzureOpenAIConfig(BaseConfig):
"modalities",
"audio",
"web_search_options",
+ "prompt_cache_key",
]
def _is_response_format_supported_model(self, model: str) -> bool:
diff --git a/litellm/llms/azure/cost_calculation.py b/litellm/llms/azure/cost_calculation.py
index 96c58d95ff2..5b411095ea1 100644
--- a/litellm/llms/azure/cost_calculation.py
+++ b/litellm/llms/azure/cost_calculation.py
@@ -1,11 +1,12 @@
"""
Helper util for handling azure openai-specific cost calculation
-- e.g.: prompt caching
+- e.g.: prompt caching, audio tokens
"""
from typing import Optional, Tuple
from litellm._logging import verbose_logger
+from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token
from litellm.types.utils import Usage
from litellm.utils import get_model_info
@@ -18,34 +19,15 @@ def cost_per_token(
Input:
- model: str, the model name without provider prefix
- - usage: LiteLLM Usage block, containing anthropic caching information
+ - usage: LiteLLM Usage block, containing caching and audio token information
Returns:
Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd
"""
## GET MODEL INFO
model_info = get_model_info(model=model, custom_llm_provider="azure")
- cached_tokens: Optional[int] = None
- ## CALCULATE INPUT COST
- non_cached_text_tokens = usage.prompt_tokens
- if usage.prompt_tokens_details and usage.prompt_tokens_details.cached_tokens:
- cached_tokens = usage.prompt_tokens_details.cached_tokens
- non_cached_text_tokens = non_cached_text_tokens - cached_tokens
- prompt_cost: float = non_cached_text_tokens * model_info["input_cost_per_token"]
- ## CALCULATE OUTPUT COST
- completion_cost: float = (
- usage["completion_tokens"] * model_info["output_cost_per_token"]
- )
-
- ## Prompt Caching cost calculation
- if model_info.get("cache_read_input_token_cost") is not None and cached_tokens:
- # Note: We read ._cache_read_input_tokens from the Usage - since cost_calculator.py standardizes the cache read tokens on usage._cache_read_input_tokens
- prompt_cost += cached_tokens * (
- model_info.get("cache_read_input_token_cost", 0) or 0
- )
-
- ## Speech / Audio cost calculation
+ ## Speech / Audio cost calculation (cost per second for TTS models)
if (
"output_cost_per_second" in model_info
and model_info["output_cost_per_second"] is not None
@@ -55,7 +37,14 @@ def cost_per_token(
f"For model={model} - output_cost_per_second: {model_info.get('output_cost_per_second')}; response time: {response_time_ms}"
)
## COST PER SECOND ##
- prompt_cost = 0
+ prompt_cost = 0.0
completion_cost = model_info["output_cost_per_second"] * response_time_ms / 1000
+ return prompt_cost, completion_cost
- return prompt_cost, completion_cost
+ ## Use generic cost calculator for all other cases
+ ## This properly handles: text tokens, audio tokens, cached tokens, reasoning tokens, etc.
+ return generic_cost_per_token(
+ model=model,
+ usage=usage,
+ custom_llm_provider="azure",
+ )
diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.py
index d621cb209d7..78631d38005 100644
--- a/litellm/llms/azure/responses/transformation.py
+++ b/litellm/llms/azure/responses/transformation.py
@@ -1,3 +1,4 @@
+from copy import deepcopy
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union
import httpx
@@ -20,10 +21,25 @@ else:
class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
+
+ # Parameters not supported by Azure Responses API
+ AZURE_UNSUPPORTED_PARAMS = ["context_management"]
+
@property
def custom_llm_provider(self) -> LlmProviders:
return LlmProviders.AZURE
+ def get_supported_openai_params(self, model: str) -> list:
+ """
+ Azure Responses API does not support context_management (compaction).
+ """
+ base_supported_params = super().get_supported_openai_params(model)
+ return [
+ param
+ for param in base_supported_params
+ if param not in self.AZURE_UNSUPPORTED_PARAMS
+ ]
+
def validate_environment(
self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]
) -> dict:
@@ -43,7 +59,7 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
"""
Handle reasoning items to filter out the status field.
Issue: https://github.com/BerriAI/litellm/issues/13484
-
+
Azure OpenAI API does not accept 'status' field in reasoning input items.
"""
if item.get("type") == "reasoning":
@@ -78,7 +94,7 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
}
return filtered_item
return item
-
+
def _validate_input_param(
self, input: Union[str, ResponseInputParam]
) -> Union[str, ResponseInputParam]:
@@ -90,7 +106,7 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
# First call parent's validation
validated_input = super()._validate_input_param(input)
-
+
# Then filter out status from message items
if isinstance(validated_input, list):
filtered_input: List[Any] = []
@@ -102,7 +118,7 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
else:
filtered_input.append(item)
return cast(ResponseInputParam, filtered_input)
-
+
return validated_input
def transform_responses_api_request(
@@ -116,6 +132,21 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
"""No transform applied since inputs are in OpenAI spec already"""
stripped_model_name = self.get_stripped_model_name(model)
+ # Azure Responses API requires flattened tools (params at top level, not nested in 'function')
+ if "tools" in response_api_optional_request_params and isinstance(
+ response_api_optional_request_params["tools"], list
+ ):
+ new_tools: List[Dict[str, Any]] = []
+ for tool in response_api_optional_request_params["tools"]:
+ if isinstance(tool, dict) and "function" in tool:
+ new_tool: Dict[str, Any] = deepcopy(tool)
+ function_data = new_tool.pop("function")
+ new_tool.update(function_data)
+ new_tools.append(new_tool)
+ else:
+ new_tools.append(tool)
+ response_api_optional_request_params["tools"] = new_tools
+
return super().transform_responses_api_request(
model=stripped_model_name,
input=input,
diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py
index e284595cc8a..09b83b7c971 100644
--- a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py
+++ b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py
@@ -30,30 +30,32 @@ class AzureAIAnthropicCountTokensConfig(AnthropicCountTokensConfig):
"""
Get the required headers for the Azure AI Anthropic CountTokens API.
- Uses Azure authentication (api-key header) instead of Anthropic's x-api-key.
+ Azure AI Anthropic uses Anthropic's native API format, which requires the
+ x-api-key header for authentication (in addition to Azure's api-key header).
Args:
api_key: The Azure AI API key
litellm_params: Optional LiteLLM parameters for additional auth config
Returns:
- Dictionary of required headers with Azure authentication
+ Dictionary of required headers with both x-api-key and Azure authentication
"""
- # Start with base headers
+ # Start with base headers including x-api-key for Anthropic API compatibility
headers = {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"anthropic-beta": ANTHROPIC_TOKEN_COUNTING_BETA_VERSION,
+ "x-api-key": api_key, # Azure AI Anthropic requires this header
}
- # Use Azure authentication
+ # Also set up Azure auth headers for flexibility
litellm_params = litellm_params or {}
if "api_key" not in litellm_params:
litellm_params["api_key"] = api_key
litellm_params_obj = GenericLiteLLMParams(**litellm_params)
- # Get Azure auth headers
+ # Get Azure auth headers (api-key or Authorization)
azure_headers = BaseAzureLLM._base_validate_azure_environment(
headers={}, litellm_params=litellm_params_obj
)
@@ -68,7 +70,7 @@ class AzureAIAnthropicCountTokensConfig(AnthropicCountTokensConfig):
Get the Azure AI Anthropic CountTokens API endpoint.
Args:
- api_base: The Azure AI API base URL
+ api_base: The Azure AI API base URL
(e.g., https://my-resource.services.ai.azure.com or
https://my-resource.services.ai.azure.com/anthropic)
diff --git a/litellm/llms/azure_ai/anthropic/messages_transformation.py b/litellm/llms/azure_ai/anthropic/messages_transformation.py
index 0d00c907031..a4dc88f9c68 100644
--- a/litellm/llms/azure_ai/anthropic/messages_transformation.py
+++ b/litellm/llms/azure_ai/anthropic/messages_transformation.py
@@ -62,7 +62,6 @@ class AzureAnthropicMessagesConfig(AnthropicMessagesConfig):
if "content-type" not in headers:
headers["content-type"] = "application/json"
- # Update headers with anthropic beta features (context management, tool search, etc.)
headers = self._update_headers_with_anthropic_beta(
headers=headers,
optional_params=optional_params,
diff --git a/litellm/llms/azure_ai/anthropic/transformation.py b/litellm/llms/azure_ai/anthropic/transformation.py
index 2d8d3b987c7..c5510db68b1 100644
--- a/litellm/llms/azure_ai/anthropic/transformation.py
+++ b/litellm/llms/azure_ai/anthropic/transformation.py
@@ -2,7 +2,6 @@
Azure Anthropic transformation config - extends AnthropicConfig with Azure authentication
"""
from typing import TYPE_CHECKING, Dict, List, Optional, Union
-
from litellm.llms.anthropic.chat.transformation import AnthropicConfig
from litellm.llms.azure.common_utils import BaseAzureLLM
from litellm.types.llms.openai import AllMessageValues
@@ -87,6 +86,7 @@ class AzureAnthropicConfig(AnthropicConfig):
if "anthropic-version" not in headers:
headers["anthropic-version"] = "2023-06-01"
+
return headers
def transform_request(
diff --git a/litellm/llms/azure_ai/azure_model_router/__init__.py b/litellm/llms/azure_ai/azure_model_router/__init__.py
new file mode 100644
index 00000000000..0165d60b643
--- /dev/null
+++ b/litellm/llms/azure_ai/azure_model_router/__init__.py
@@ -0,0 +1,4 @@
+"""Azure AI Foundry Model Router support."""
+from .transformation import AzureModelRouterConfig
+
+__all__ = ["AzureModelRouterConfig"]
diff --git a/litellm/llms/azure_ai/azure_model_router/transformation.py b/litellm/llms/azure_ai/azure_model_router/transformation.py
new file mode 100644
index 00000000000..3d6dc53c515
--- /dev/null
+++ b/litellm/llms/azure_ai/azure_model_router/transformation.py
@@ -0,0 +1,125 @@
+"""
+Transformation for Azure AI Foundry Model Router.
+
+The Model Router is a special Azure AI deployment that automatically routes requests
+to the best available model. It has specific cost tracking requirements.
+"""
+from typing import Any, List, Optional
+
+from httpx import Response
+
+from litellm.llms.azure_ai.chat.transformation import AzureAIStudioConfig
+from litellm.llms.base_llm.chat.transformation import LiteLLMLoggingObj
+from litellm.types.llms.openai import AllMessageValues
+from litellm.types.utils import ModelResponse
+
+
+class AzureModelRouterConfig(AzureAIStudioConfig):
+ """
+ Configuration for Azure AI Foundry Model Router.
+
+ Handles:
+ - Stripping model_router prefix before sending to Azure API
+ - Preserving full model path in responses for cost tracking
+ - Calculating flat infrastructure costs for Model Router
+ """
+
+ def transform_request(
+ self,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ headers: dict,
+ ) -> dict:
+ """
+ Transform request for Model Router.
+
+ Strips the model_router/ prefix so only the deployment name is sent to Azure.
+ Example: model_router/azure-model-router -> azure-model-router
+ """
+ from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo
+
+ # Get base model name (strips routing prefixes like model_router/)
+ base_model: str = AzureFoundryModelInfo.get_base_model(model)
+
+ return super().transform_request(
+ base_model, messages, optional_params, litellm_params, headers
+ )
+
+ def transform_response(
+ self,
+ model: str,
+ raw_response: Response,
+ model_response: ModelResponse,
+ logging_obj: LiteLLMLoggingObj,
+ request_data: dict,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ encoding: Any,
+ api_key: Optional[str] = None,
+ json_mode: Optional[bool] = None,
+ ) -> ModelResponse:
+ """
+ Transform response for Model Router.
+
+ Preserves the original model path (including model_router/ prefix) in the response
+ for proper cost tracking and logging.
+ """
+ from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo
+
+ # Preserve the original model from litellm_params (includes routing prefixes like model_router/)
+ # This ensures cost tracking and logging use the full model path
+ original_model: str = litellm_params.get("model") or model
+ if not original_model.startswith("azure_ai/"):
+ # Add provider prefix if not already present
+ model_response.model = f"azure_ai/{original_model}"
+ else:
+ model_response.model = original_model
+
+ # Get base model for the parent call (strips routing prefixes for API compatibility)
+ base_model: str = AzureFoundryModelInfo.get_base_model(model)
+
+ return super().transform_response(
+ model=base_model,
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=logging_obj,
+ request_data=request_data,
+ messages=messages,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ encoding=encoding,
+ api_key=api_key,
+ json_mode=json_mode,
+ )
+
+ def calculate_additional_costs(
+ self, model: str, prompt_tokens: int, completion_tokens: int
+ ) -> Optional[dict]:
+ """
+ Calculate additional costs for Azure Model Router.
+
+ Adds a flat infrastructure cost of $0.14 per M input tokens for using the Model Router.
+
+ Args:
+ model: The model name (should be a model router model)
+ prompt_tokens: Number of prompt tokens
+ completion_tokens: Number of completion tokens
+
+ Returns:
+ Dictionary with additional costs, or None if not applicable.
+ """
+ from litellm.llms.azure_ai.cost_calculator import (
+ calculate_azure_model_router_flat_cost,
+ )
+
+ flat_cost = calculate_azure_model_router_flat_cost(
+ model=model, prompt_tokens=prompt_tokens
+ )
+
+ if flat_cost > 0:
+ return {"Azure Model Router Flat Cost": flat_cost}
+
+ return None
diff --git a/litellm/llms/azure_ai/chat/transformation.py b/litellm/llms/azure_ai/chat/transformation.py
index 04d2b3a2769..585efd3307d 100644
--- a/litellm/llms/azure_ai/chat/transformation.py
+++ b/litellm/llms/azure_ai/chat/transformation.py
@@ -11,12 +11,14 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import (
_audio_or_image_in_message_content,
convert_content_list_to_str,
)
+from litellm.llms.azure.common_utils import BaseAzureLLM
from litellm.llms.base_llm.chat.transformation import LiteLLMLoggingObj
from litellm.llms.openai.common_utils import drop_params_from_unprocessable_entity_error
from litellm.llms.openai.openai import OpenAIConfig
from litellm.llms.xai.chat.transformation import XAIChatConfig
from litellm.secret_managers.main import get_secret_str
from litellm.types.llms.openai import AllMessageValues
+from litellm.types.router import GenericLiteLLMParams
from litellm.types.utils import ModelResponse, ProviderField
from litellm.utils import _add_path_to_api_base, supports_tool_choice
@@ -64,12 +66,21 @@ class AzureAIStudioConfig(OpenAIConfig):
api_key: Optional[str] = None,
api_base: Optional[str] = None,
) -> dict:
- if api_base and self._should_use_api_key_header(api_base):
- headers["api-key"] = api_key
+ if api_key:
+ if api_base and self._should_use_api_key_header(api_base):
+ headers["api-key"] = api_key
+ else:
+ headers["Authorization"] = f"Bearer {api_key}"
else:
- headers["Authorization"] = f"Bearer {api_key}"
+ # No api_key provided — fall back to Azure AD token-based auth
+ litellm_params_obj = GenericLiteLLMParams(
+ **(litellm_params if isinstance(litellm_params, dict) else {})
+ )
+ headers = BaseAzureLLM._base_validate_azure_environment(
+ headers=headers, litellm_params=litellm_params_obj
+ )
- headers["Content-Type"] = "application/json" # tell Azure AI Studio to expect JSON
+ headers["Content-Type"] = "application/json"
return headers
diff --git a/litellm/llms/azure_ai/common_utils.py b/litellm/llms/azure_ai/common_utils.py
index 01a3f5766c6..47d397d6e98 100644
--- a/litellm/llms/azure_ai/common_utils.py
+++ b/litellm/llms/azure_ai/common_utils.py
@@ -13,14 +13,28 @@ class AzureFoundryModelInfo(BaseLLMModelInfo):
self._model = model
@staticmethod
- def get_azure_ai_route(model: str) -> Literal["agents", "default"]:
+ def get_azure_ai_route(model: str) -> Literal["agents", "model_router", "default"]:
"""
Get the Azure AI route for the given model.
Similar to BedrockModelInfo.get_bedrock_route().
+
+ Supported routes:
+ - agents: azure_ai/agents/
+ - model_router: azure_ai/model_router/ or models with "model-router"/"model_router" in name
+ - default: standard models
"""
if "agents/" in model:
return "agents"
+ # Detect model router by prefix (model_router/) or by name containing "model-router"/"model_router"
+ model_lower = model.lower()
+ if (
+ "model_router/" in model_lower
+ or "model-router/" in model_lower
+ or "model-router" in model_lower
+ or "model_router" in model_lower
+ ):
+ return "model_router"
return "default"
@staticmethod
@@ -75,8 +89,73 @@ class AzureFoundryModelInfo(BaseLLMModelInfo):
#########################################################
@staticmethod
- def get_base_model(model: str) -> Optional[str]:
- raise NotImplementedError("Azure Foundry does not support base model")
+ def strip_model_router_prefix(model: str) -> str:
+ """
+ Strip the model_router prefix from model name.
+
+ Examples:
+ - "model_router/gpt-4o" -> "gpt-4o"
+ - "model-router/gpt-4o" -> "gpt-4o"
+ - "gpt-4o" -> "gpt-4o"
+
+ Args:
+ model: Model name potentially with model_router prefix
+
+ Returns:
+ Model name without the prefix
+ """
+ if "model_router/" in model:
+ return model.split("model_router/", 1)[1]
+ if "model-router/" in model:
+ return model.split("model-router/", 1)[1]
+ return model
+
+ @staticmethod
+ def get_base_model(model: str) -> str:
+ """
+ Get the base model name, stripping any Azure AI routing prefixes.
+
+ Args:
+ model: Model name potentially with routing prefixes
+
+ Returns:
+ Base model name
+ """
+ # Strip model_router prefix if present
+ model = AzureFoundryModelInfo.strip_model_router_prefix(model)
+ return model
+
+ @staticmethod
+ def get_azure_ai_config_for_model(model: str):
+ """
+ Get the appropriate Azure AI config class for the given model.
+
+ Routes to specialized configs based on model type:
+ - Model Router: AzureModelRouterConfig
+ - Claude models: AzureAnthropicConfig
+ - Default: AzureAIStudioConfig
+
+ Args:
+ model: The model name
+
+ Returns:
+ The appropriate config instance
+ """
+ azure_ai_route = AzureFoundryModelInfo.get_azure_ai_route(model)
+
+ if azure_ai_route == "model_router":
+ from litellm.llms.azure_ai.azure_model_router.transformation import (
+ AzureModelRouterConfig,
+ )
+ return AzureModelRouterConfig()
+ elif "claude" in model.lower():
+ from litellm.llms.azure_ai.anthropic.transformation import (
+ AzureAnthropicConfig,
+ )
+ return AzureAnthropicConfig()
+ else:
+ from litellm.llms.azure_ai.chat.transformation import AzureAIStudioConfig
+ return AzureAIStudioConfig()
def validate_environment(
self,
diff --git a/litellm/llms/azure_ai/cost_calculator.py b/litellm/llms/azure_ai/cost_calculator.py
new file mode 100644
index 00000000000..999f94da182
--- /dev/null
+++ b/litellm/llms/azure_ai/cost_calculator.py
@@ -0,0 +1,121 @@
+"""
+Azure AI cost calculation helper.
+Handles Azure AI Foundry Model Router flat cost and other Azure AI specific pricing.
+"""
+
+from typing import Optional, Tuple
+
+from litellm._logging import verbose_logger
+from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token
+from litellm.types.utils import Usage
+from litellm.utils import get_model_info
+
+
+def _is_azure_model_router(model: str) -> bool:
+ """
+ Check if the model is Azure AI Foundry Model Router.
+
+ Detects patterns like:
+ - "azure-model-router"
+ - "model-router"
+ - "model_router/"
+ - "model-router/"
+
+ Args:
+ model: The model name
+
+ Returns:
+ bool: True if this is a model router model
+ """
+ model_lower = model.lower()
+ return (
+ "model-router" in model_lower
+ or "model_router" in model_lower
+ or model_lower == "azure-model-router"
+ )
+
+
+def calculate_azure_model_router_flat_cost(model: str, prompt_tokens: int) -> float:
+ """
+ Calculate the flat cost for Azure AI Foundry Model Router.
+
+ Args:
+ model: The model name (should be a model router model)
+ prompt_tokens: Number of prompt tokens
+
+ Returns:
+ float: The flat cost in USD, or 0.0 if not applicable
+ """
+ if not _is_azure_model_router(model):
+ return 0.0
+
+ # Get the model router pricing from model_prices_and_context_window.json
+ # Use "model_router" as the key (without actual model name suffix)
+ model_info = get_model_info(model="model_router", custom_llm_provider="azure_ai")
+ router_flat_cost_per_token = model_info.get("input_cost_per_token", 0)
+
+ if router_flat_cost_per_token > 0:
+ return prompt_tokens * router_flat_cost_per_token
+
+ return 0.0
+
+
+def cost_per_token(
+ model: str, usage: Usage, response_time_ms: Optional[float] = 0.0
+) -> Tuple[float, float]:
+ """
+ Calculate the cost per token for Azure AI models.
+
+ For Azure AI Foundry Model Router:
+ - Adds a flat cost of $0.14 per million input tokens (from model_prices_and_context_window.json)
+ - Plus the cost of the actual model used (handled by generic_cost_per_token)
+
+ Args:
+ model: str, the model name without provider prefix
+ usage: LiteLLM Usage block
+ response_time_ms: Optional response time in milliseconds
+
+ Returns:
+ Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd
+
+ Raises:
+ ValueError: If the model is not found in the cost map and cost cannot be calculated
+ (except for Model Router models where we return just the routing flat cost)
+ """
+ prompt_cost = 0.0
+ completion_cost = 0.0
+
+ # Calculate base cost using generic cost calculator
+ # This may raise an exception if the model is not in the cost map
+ try:
+ prompt_cost, completion_cost = generic_cost_per_token(
+ model=model,
+ usage=usage,
+ custom_llm_provider="azure_ai",
+ )
+ except Exception as e:
+ # For Model Router, the model name (e.g., "azure-model-router") may not be in the cost map
+ # because it's a routing service, not an actual model. In this case, we continue
+ # to calculate just the routing flat cost.
+ if not _is_azure_model_router(model):
+ # Re-raise for non-router models - they should have pricing defined
+ raise
+ verbose_logger.debug(
+ f"Azure AI Model Router: model '{model}' not in cost map, calculating routing flat cost only. Error: {e}"
+ )
+
+ # Add flat cost for Azure Model Router
+ # The flat cost is defined in model_prices_and_context_window.json for azure_ai/model_router
+ if _is_azure_model_router(model):
+ router_flat_cost = calculate_azure_model_router_flat_cost(model, usage.prompt_tokens)
+
+ if router_flat_cost > 0:
+ verbose_logger.debug(
+ f"Azure AI Model Router flat cost: ${router_flat_cost:.6f} "
+ f"({usage.prompt_tokens} tokens × ${router_flat_cost / usage.prompt_tokens:.9f}/token)"
+ )
+
+ # Add flat cost to prompt cost
+ prompt_cost += router_flat_cost
+
+ return prompt_cost, completion_cost
diff --git a/litellm/llms/azure_ai/rerank/transformation.py b/litellm/llms/azure_ai/rerank/transformation.py
index a47b6082c37..f577a42ed58 100644
--- a/litellm/llms/azure_ai/rerank/transformation.py
+++ b/litellm/llms/azure_ai/rerank/transformation.py
@@ -11,6 +11,7 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
from litellm.llms.cohere.rerank.transformation import CohereRerankConfig
from litellm.secret_managers.main import get_secret_str
from litellm.types.utils import RerankResponse
+from litellm.utils import _add_path_to_api_base
class AzureAIRerankConfig(CohereRerankConfig):
@@ -28,9 +29,34 @@ class AzureAIRerankConfig(CohereRerankConfig):
raise ValueError(
"Azure AI API Base is required. api_base=None. Set in call or via `AZURE_AI_API_BASE` env var."
)
- if not api_base.endswith("/v1/rerank"):
- api_base = f"{api_base}/v1/rerank"
- return api_base
+ original_url = httpx.URL(api_base)
+ if not original_url.is_absolute_url:
+ raise ValueError(
+ "Azure AI API Base must be an absolute URL including scheme (e.g. "
+ "'https://.services.ai.azure.com'). "
+ f"Got api_base={api_base!r}."
+ )
+ normalized_path = original_url.path.rstrip("/")
+
+ # Allow callers to pass either full v1/v2 rerank endpoints:
+ # - https://.services.ai.azure.com/v1/rerank
+ # - https://.services.ai.azure.com/providers/cohere/v2/rerank
+ if normalized_path.endswith("/v1/rerank") or normalized_path.endswith("/v2/rerank"):
+ return str(original_url.copy_with(path=normalized_path or "/"))
+
+ # If callers pass just the version path (e.g. ".../v2" or ".../providers/cohere/v2"), append "/rerank"
+ if (
+ normalized_path.endswith("/v1")
+ or normalized_path.endswith("/v2")
+ or normalized_path.endswith("/providers/cohere/v2")
+ ):
+ return _add_path_to_api_base(
+ api_base=str(original_url.copy_with(path=normalized_path or "/")),
+ ending_path="/rerank",
+ )
+
+ # Backwards compatible default: Azure AI rerank was originally exposed under /v1/rerank
+ return _add_path_to_api_base(api_base=api_base, ending_path="/v1/rerank")
def validate_environment(
self,
diff --git a/litellm/llms/base_llm/chat/transformation.py b/litellm/llms/base_llm/chat/transformation.py
index 41a1797cebe..ac209904e6e 100644
--- a/litellm/llms/base_llm/chat/transformation.py
+++ b/litellm/llms/base_llm/chat/transformation.py
@@ -437,3 +437,23 @@ class BaseConfig(ABC):
By default, this is true for almost all providers.
"""
return True
+
+ def calculate_additional_costs(
+ self, model: str, prompt_tokens: int, completion_tokens: int
+ ) -> Optional[dict]:
+ """
+ Calculate any additional costs beyond standard token costs.
+
+ This is used for provider-specific infrastructure costs, routing fees, etc.
+
+ Args:
+ model: The model name
+ prompt_tokens: Number of prompt tokens
+ completion_tokens: Number of completion tokens
+
+ Returns:
+ Optional dictionary with cost names and amounts, e.g.:
+ {"Infrastructure Fee": 0.001, "Routing Cost": 0.0005}
+ Returns None if no additional costs apply.
+ """
+ return None
diff --git a/litellm/llms/base_llm/evals/__init__.py b/litellm/llms/base_llm/evals/__init__.py
new file mode 100644
index 00000000000..948ed5364ea
--- /dev/null
+++ b/litellm/llms/base_llm/evals/__init__.py
@@ -0,0 +1,7 @@
+"""
+Base configuration for Evals API
+"""
+
+from .transformation import BaseEvalsAPIConfig
+
+__all__ = ["BaseEvalsAPIConfig"]
diff --git a/litellm/llms/base_llm/evals/transformation.py b/litellm/llms/base_llm/evals/transformation.py
new file mode 100644
index 00000000000..54dc2f7aae9
--- /dev/null
+++ b/litellm/llms/base_llm/evals/transformation.py
@@ -0,0 +1,542 @@
+"""
+Base configuration class for Evals API
+"""
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
+
+import httpx
+
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.types.llms.openai_evals import (
+ CancelEvalResponse,
+ CancelRunResponse,
+ CreateEvalRequest,
+ CreateRunRequest,
+ DeleteEvalResponse,
+ Eval,
+ ListEvalsParams,
+ ListEvalsResponse,
+ ListRunsParams,
+ ListRunsResponse,
+ Run,
+ RunDeleteResponse,
+ UpdateEvalRequest,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import LlmProviders
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+
+
+class BaseEvalsAPIConfig(ABC):
+ """Base configuration for Evals API providers"""
+
+ def __init__(self):
+ pass
+
+ @property
+ @abstractmethod
+ def custom_llm_provider(self) -> LlmProviders:
+ pass
+
+ @abstractmethod
+ def validate_environment(
+ self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]
+ ) -> dict:
+ """
+ Validate and update headers with provider-specific requirements
+
+ Args:
+ headers: Base headers dictionary
+ litellm_params: LiteLLM parameters
+
+ Returns:
+ Updated headers dictionary
+ """
+ return headers
+
+ @abstractmethod
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ endpoint: str,
+ eval_id: Optional[str] = None,
+ ) -> str:
+ """
+ Get the complete URL for the API request
+
+ Args:
+ api_base: Base API URL
+ endpoint: API endpoint (e.g., 'evals', 'evals/{id}')
+ eval_id: Optional eval ID for specific eval operations
+
+ Returns:
+ Complete URL
+ """
+ if api_base is None:
+ raise ValueError("api_base is required")
+ return f"{api_base}/v1/{endpoint}"
+
+ @abstractmethod
+ def transform_create_eval_request(
+ self,
+ create_request: CreateEvalRequest,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ """
+ Transform create eval request to provider-specific format
+
+ Args:
+ create_request: Eval creation parameters
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Provider-specific request body
+ """
+ pass
+
+ @abstractmethod
+ def transform_create_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Eval:
+ """
+ Transform provider response to Eval object
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ Eval object
+ """
+ pass
+
+ @abstractmethod
+ def transform_list_evals_request(
+ self,
+ list_params: ListEvalsParams,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform list evals request parameters
+
+ Args:
+ list_params: List parameters (pagination, filters)
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, query_params)
+ """
+ pass
+
+ @abstractmethod
+ def transform_list_evals_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> ListEvalsResponse:
+ """
+ Transform provider response to ListEvalsResponse
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ ListEvalsResponse object
+ """
+ pass
+
+ @abstractmethod
+ def transform_get_eval_request(
+ self,
+ eval_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform get eval request
+
+ Args:
+ eval_id: Eval ID
+ api_base: Base API URL
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, headers)
+ """
+ pass
+
+ @abstractmethod
+ def transform_get_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Eval:
+ """
+ Transform provider response to Eval object
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ Eval object
+ """
+ pass
+
+ @abstractmethod
+ def transform_update_eval_request(
+ self,
+ eval_id: str,
+ update_request: UpdateEvalRequest,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """
+ Transform update eval request
+
+ Args:
+ eval_id: Eval ID
+ update_request: Update parameters
+ api_base: Base API URL
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, headers, body)
+ """
+ pass
+
+ @abstractmethod
+ def transform_update_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Eval:
+ """
+ Transform provider response to Eval object
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ Eval object
+ """
+ pass
+
+ @abstractmethod
+ def transform_delete_eval_request(
+ self,
+ eval_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform delete eval request
+
+ Args:
+ eval_id: Eval ID
+ api_base: Base API URL
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, headers)
+ """
+ pass
+
+ @abstractmethod
+ def transform_delete_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> DeleteEvalResponse:
+ """
+ Transform provider response to DeleteEvalResponse
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ DeleteEvalResponse object
+ """
+ pass
+
+ @abstractmethod
+ def transform_cancel_eval_request(
+ self,
+ eval_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """
+ Transform cancel eval request
+
+ Args:
+ eval_id: Eval ID
+ api_base: Base API URL
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, headers, body)
+ """
+ pass
+
+ @abstractmethod
+ def transform_cancel_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> CancelEvalResponse:
+ """
+ Transform provider response to CancelEvalResponse
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ CancelEvalResponse object
+ """
+ pass
+
+ # Run API Transformations
+ @abstractmethod
+ def transform_create_run_request(
+ self,
+ eval_id: str,
+ create_request: CreateRunRequest,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform create run request to provider-specific format
+
+ Args:
+ eval_id: Eval ID
+ create_request: Run creation parameters
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, request_body)
+ """
+ pass
+
+ @abstractmethod
+ def transform_create_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Run:
+ """
+ Transform provider response to Run object
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ Run object
+ """
+ pass
+
+ @abstractmethod
+ def transform_list_runs_request(
+ self,
+ eval_id: str,
+ list_params: ListRunsParams,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform list runs request parameters
+
+ Args:
+ eval_id: Eval ID
+ list_params: List parameters (pagination, filters)
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, query_params)
+ """
+ pass
+
+ @abstractmethod
+ def transform_list_runs_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> ListRunsResponse:
+ """
+ Transform provider response to ListRunsResponse
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ ListRunsResponse object
+ """
+ pass
+
+ @abstractmethod
+ def transform_get_run_request(
+ self,
+ eval_id: str,
+ run_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform get run request
+
+ Args:
+ eval_id: Eval ID
+ run_id: Run ID
+ api_base: Base API URL
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, headers)
+ """
+ pass
+
+ @abstractmethod
+ def transform_get_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Run:
+ """
+ Transform provider response to Run object
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ Run object
+ """
+ pass
+
+ @abstractmethod
+ def transform_cancel_run_request(
+ self,
+ eval_id: str,
+ run_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """
+ Transform cancel run request
+
+ Args:
+ eval_id: Eval ID
+ run_id: Run ID
+ api_base: Base API URL
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, headers, body)
+ """
+ pass
+
+ @abstractmethod
+ def transform_cancel_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> CancelRunResponse:
+ """
+ Transform provider response to CancelRunResponse
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ CancelRunResponse object
+ """
+ pass
+
+ @abstractmethod
+ def transform_delete_run_request(
+ self,
+ eval_id: str,
+ run_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """
+ Transform delete run request
+
+ Args:
+ eval_id: Eval ID
+ run_id: Run ID
+ api_base: Base API URL
+ litellm_params: LiteLLM parameters
+ headers: Request headers
+
+ Returns:
+ Tuple of (url, headers, body)
+ """
+ pass
+
+ @abstractmethod
+ def transform_delete_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> "RunDeleteResponse":
+ """
+ Transform provider response to RunDeleteResponse
+
+ Args:
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+
+ Returns:
+ RunDeleteResponse object
+ """
+ pass
+
+ def get_error_class(
+ self,
+ error_message: str,
+ status_code: int,
+ headers: dict,
+ ) -> Exception:
+ """Get appropriate error class for the provider."""
+ return BaseLLMException(
+ status_code=status_code,
+ message=error_message,
+ headers=headers,
+ )
diff --git a/litellm/llms/base_llm/managed_resources/__init__.py b/litellm/llms/base_llm/managed_resources/__init__.py
new file mode 100644
index 00000000000..5eb9b46f89f
--- /dev/null
+++ b/litellm/llms/base_llm/managed_resources/__init__.py
@@ -0,0 +1,41 @@
+"""
+Managed Resources Module
+
+This module provides base classes and utilities for managing resources
+(files, vector stores, etc.) with target_model_names support.
+
+The BaseManagedResource class provides common functionality for:
+- Storing unified resource IDs with model mappings
+- Retrieving resources by unified ID
+- Deleting resources across multiple models
+- Creating resources for multiple models
+- Filtering deployments based on model mappings
+"""
+
+from .base_managed_resource import BaseManagedResource
+from .utils import (
+ decode_unified_id,
+ encode_unified_id,
+ extract_model_id_from_unified_id,
+ extract_provider_resource_id_from_unified_id,
+ extract_resource_type_from_unified_id,
+ extract_target_model_names_from_unified_id,
+ extract_unified_uuid_from_unified_id,
+ generate_unified_id_string,
+ is_base64_encoded_unified_id,
+ parse_unified_id,
+)
+
+__all__ = [
+ "BaseManagedResource",
+ "is_base64_encoded_unified_id",
+ "extract_target_model_names_from_unified_id",
+ "extract_resource_type_from_unified_id",
+ "extract_unified_uuid_from_unified_id",
+ "extract_model_id_from_unified_id",
+ "extract_provider_resource_id_from_unified_id",
+ "generate_unified_id_string",
+ "encode_unified_id",
+ "decode_unified_id",
+ "parse_unified_id",
+]
diff --git a/litellm/llms/base_llm/managed_resources/base_managed_resource.py b/litellm/llms/base_llm/managed_resources/base_managed_resource.py
new file mode 100644
index 00000000000..3c8ce748ade
--- /dev/null
+++ b/litellm/llms/base_llm/managed_resources/base_managed_resource.py
@@ -0,0 +1,605 @@
+# What is this?
+## Base class for managing resources (files, vector stores, etc.) with target_model_names support
+## This provides common functionality for creating, retrieving, and managing resources across multiple models
+
+import base64
+import json
+from abc import ABC, abstractmethod
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Generic,
+ List,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+)
+
+from litellm import verbose_logger
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.types.utils import SpecialEnums
+
+if TYPE_CHECKING:
+ from opentelemetry.trace import Span as _Span
+
+ from litellm.proxy.utils import InternalUsageCache as _InternalUsageCache
+ from litellm.proxy.utils import PrismaClient as _PrismaClient
+ from litellm.router import Router as _Router
+
+ Span = Union[_Span, Any]
+ InternalUsageCache = _InternalUsageCache
+ PrismaClient = _PrismaClient
+ Router = _Router
+else:
+ Span = Any
+ InternalUsageCache = Any
+ PrismaClient = Any
+ Router = Any
+
+# Generic type for resource objects
+ResourceObjectType = TypeVar('ResourceObjectType')
+
+
+class BaseManagedResource(ABC, Generic[ResourceObjectType]):
+ """
+ Base class for managing resources with target_model_names support.
+
+ This class provides common functionality for:
+ - Storing unified resource IDs with model mappings
+ - Retrieving resources by unified ID
+ - Deleting resources across multiple models
+ - Creating resources for multiple models
+ - Filtering deployments based on model mappings
+
+ Subclasses should implement:
+ - resource_type: str property
+ - table_name: str property
+ - create_resource_for_model: method to create resource on a specific model
+ - get_unified_resource_id_format: method to generate unified ID format
+ """
+
+ def __init__(
+ self,
+ internal_usage_cache: InternalUsageCache,
+ prisma_client: PrismaClient,
+ ):
+ self.internal_usage_cache = internal_usage_cache
+ self.prisma_client = prisma_client
+
+ # ============================================================================
+ # ABSTRACT METHODS
+ # ============================================================================
+
+ @property
+ @abstractmethod
+ def resource_type(self) -> str:
+ """
+ Return the resource type identifier (e.g., 'file', 'vector_store', 'vector_store_file').
+ Used for logging and unified ID generation.
+ """
+ pass
+
+ @property
+ @abstractmethod
+ def table_name(self) -> str:
+ """
+ Return the database table name for this resource type.
+ Example: 'litellm_managedfiletable', 'litellm_managedvectorstoretable'
+ """
+ pass
+
+ @abstractmethod
+ def get_unified_resource_id_format(
+ self,
+ resource_object: ResourceObjectType,
+ target_model_names_list: List[str],
+ ) -> str:
+ """
+ Generate the format string for the unified resource ID.
+
+ This should return a string that will be base64 encoded.
+ Example for files:
+ "litellm_proxy:application/json;unified_id,{uuid};target_model_names,{models};..."
+
+ Args:
+ resource_object: The resource object returned from the provider
+ target_model_names_list: List of target model names
+
+ Returns:
+ Format string to be base64 encoded
+ """
+ pass
+
+ @abstractmethod
+ async def create_resource_for_model(
+ self,
+ llm_router: Router,
+ model: str,
+ request_data: Dict[str, Any],
+ litellm_parent_otel_span: Span,
+ ) -> ResourceObjectType:
+ """
+ Create a resource for a specific model.
+
+ Args:
+ llm_router: LiteLLM router instance
+ model: Model name to create resource for
+ request_data: Request data for resource creation
+ litellm_parent_otel_span: OpenTelemetry span for tracing
+
+ Returns:
+ Resource object from the provider
+ """
+ pass
+
+ # ============================================================================
+ # COMMON STORAGE OPERATIONS
+ # ============================================================================
+
+ async def store_unified_resource_id(
+ self,
+ unified_resource_id: str,
+ resource_object: Optional[ResourceObjectType],
+ litellm_parent_otel_span: Optional[Span],
+ model_mappings: Dict[str, str],
+ user_api_key_dict: UserAPIKeyAuth,
+ additional_db_fields: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """
+ Store unified resource ID with model mappings in cache and database.
+
+ Args:
+ unified_resource_id: The unified resource ID (base64 encoded)
+ resource_object: The resource object to store (can be None)
+ litellm_parent_otel_span: OpenTelemetry span for tracing
+ model_mappings: Dictionary mapping model_id -> provider_resource_id
+ user_api_key_dict: User API key authentication details
+ additional_db_fields: Additional fields to store in database
+ """
+ verbose_logger.info(
+ f"Storing LiteLLM Managed {self.resource_type} with id={unified_resource_id} in cache"
+ )
+
+ # Prepare cache data
+ cache_data = {
+ "unified_resource_id": unified_resource_id,
+ "resource_object": resource_object,
+ "model_mappings": model_mappings,
+ "flat_model_resource_ids": list(model_mappings.values()),
+ "created_by": user_api_key_dict.user_id,
+ "updated_by": user_api_key_dict.user_id,
+ }
+
+ # Add additional fields if provided
+ if additional_db_fields:
+ cache_data.update(additional_db_fields)
+
+ # Store in cache
+ if resource_object is not None:
+ await self.internal_usage_cache.async_set_cache(
+ key=unified_resource_id,
+ value=cache_data,
+ litellm_parent_otel_span=litellm_parent_otel_span,
+ )
+
+ # Prepare database data
+ db_data = {
+ "unified_resource_id": unified_resource_id,
+ "model_mappings": json.dumps(model_mappings),
+ "flat_model_resource_ids": list(model_mappings.values()),
+ "created_by": user_api_key_dict.user_id,
+ "updated_by": user_api_key_dict.user_id,
+ }
+
+ # Add resource object if available
+ if resource_object is not None:
+ # Handle both dict and Pydantic models
+ if hasattr(resource_object, "model_dump_json"):
+ db_data["resource_object"] = resource_object.model_dump_json() # type: ignore
+ elif isinstance(resource_object, dict):
+ db_data["resource_object"] = json.dumps(resource_object)
+
+ # Extract storage metadata from hidden params if present
+ hidden_params = getattr(resource_object, "_hidden_params", {}) or {}
+ if "storage_backend" in hidden_params:
+ db_data["storage_backend"] = hidden_params["storage_backend"]
+ if "storage_url" in hidden_params:
+ db_data["storage_url"] = hidden_params["storage_url"]
+
+ # Add additional fields to database
+ if additional_db_fields:
+ db_data.update(additional_db_fields)
+
+ # Store in database
+ table = getattr(self.prisma_client.db, self.table_name)
+ result = await table.create(data=db_data)
+
+ verbose_logger.debug(
+ f"LiteLLM Managed {self.resource_type} with id={unified_resource_id} stored in db: {result}"
+ )
+
+ async def get_unified_resource_id(
+ self,
+ unified_resource_id: str,
+ litellm_parent_otel_span: Optional[Span] = None,
+ ) -> Optional[Dict[str, Any]]:
+ """
+ Retrieve unified resource by ID from cache or database.
+
+ Args:
+ unified_resource_id: The unified resource ID to retrieve
+ litellm_parent_otel_span: OpenTelemetry span for tracing
+
+ Returns:
+ Dictionary containing resource data or None if not found
+ """
+ # Check cache first
+ result = cast(
+ Optional[dict],
+ await self.internal_usage_cache.async_get_cache(
+ key=unified_resource_id,
+ litellm_parent_otel_span=litellm_parent_otel_span,
+ ),
+ )
+
+ if result:
+ return result
+
+ # Check database
+ table = getattr(self.prisma_client.db, self.table_name)
+ db_object = await table.find_first(
+ where={"unified_resource_id": unified_resource_id}
+ )
+
+ if db_object:
+ return db_object.model_dump()
+
+ return None
+
+ async def delete_unified_resource_id(
+ self,
+ unified_resource_id: str,
+ litellm_parent_otel_span: Optional[Span] = None,
+ ) -> Optional[ResourceObjectType]:
+ """
+ Delete unified resource from cache and database.
+
+ Args:
+ unified_resource_id: The unified resource ID to delete
+ litellm_parent_otel_span: OpenTelemetry span for tracing
+
+ Returns:
+ The deleted resource object or None if not found
+ """
+ # Get old value from database
+ table = getattr(self.prisma_client.db, self.table_name)
+ initial_value = await table.find_first(
+ where={"unified_resource_id": unified_resource_id}
+ )
+
+ if initial_value is None:
+ raise Exception(
+ f"LiteLLM Managed {self.resource_type} with id={unified_resource_id} not found"
+ )
+
+ # Delete from cache
+ await self.internal_usage_cache.async_set_cache(
+ key=unified_resource_id,
+ value=None,
+ litellm_parent_otel_span=litellm_parent_otel_span,
+ )
+
+ # Delete from database
+ await table.delete(where={"unified_resource_id": unified_resource_id})
+
+ return initial_value.resource_object
+
+ async def can_user_access_unified_resource_id(
+ self,
+ unified_resource_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ litellm_parent_otel_span: Optional[Span] = None,
+ ) -> bool:
+ """
+ Check if user has access to the unified resource ID.
+
+ Uses get_unified_resource_id() which checks cache first before hitting the database,
+ avoiding direct DB queries in the critical request path.
+
+ Args:
+ unified_resource_id: The unified resource ID to check
+ user_api_key_dict: User API key authentication details
+ litellm_parent_otel_span: OpenTelemetry span for tracing
+
+ Returns:
+ True if user has access, False otherwise
+ """
+ user_id = user_api_key_dict.user_id
+
+ # Use cached method instead of direct DB query
+ resource = await self.get_unified_resource_id(
+ unified_resource_id, litellm_parent_otel_span
+ )
+
+ if resource:
+ return resource.get("created_by") == user_id
+
+ return False
+
+ # ============================================================================
+ # MODEL MAPPING OPERATIONS
+ # ============================================================================
+
+ async def get_model_resource_id_mapping(
+ self,
+ resource_ids: List[str],
+ litellm_parent_otel_span: Span,
+ ) -> Dict[str, Dict[str, str]]:
+ """
+ Get model-specific resource IDs for a list of unified resource IDs.
+
+ Args:
+ resource_ids: List of unified resource IDs
+ litellm_parent_otel_span: OpenTelemetry span for tracing
+
+ Returns:
+ Dictionary mapping unified_resource_id -> model_id -> provider_resource_id
+
+ Example:
+ {
+ "unified_resource_id_1": {
+ "model_id_1": "provider_resource_id_1",
+ "model_id_2": "provider_resource_id_2"
+ }
+ }
+ """
+ resource_id_mapping: Dict[str, Dict[str, str]] = {}
+
+ for resource_id in resource_ids:
+ # Get unified resource from cache/db
+ unified_resource_object = await self.get_unified_resource_id(
+ resource_id, litellm_parent_otel_span
+ )
+
+ if unified_resource_object:
+ model_mappings = unified_resource_object.get("model_mappings", {})
+
+ # Handle both JSON string and dict
+ if isinstance(model_mappings, str):
+ model_mappings = json.loads(model_mappings)
+
+ resource_id_mapping[resource_id] = model_mappings
+
+ return resource_id_mapping
+
+ # ============================================================================
+ # RESOURCE CREATION OPERATIONS
+ # ============================================================================
+
+ async def create_resource_for_each_model(
+ self,
+ llm_router: Router,
+ request_data: Dict[str, Any],
+ target_model_names_list: List[str],
+ litellm_parent_otel_span: Span,
+ ) -> List[ResourceObjectType]:
+ """
+ Create a resource for each model in the target list.
+
+ Args:
+ llm_router: LiteLLM router instance
+ request_data: Request data for resource creation
+ target_model_names_list: List of target model names
+ litellm_parent_otel_span: OpenTelemetry span for tracing
+
+ Returns:
+ List of resource objects created for each model
+ """
+ if llm_router is None:
+ raise Exception("LLM Router not initialized. Ensure models added to proxy.")
+
+ responses = []
+ for model in target_model_names_list:
+ individual_response = await self.create_resource_for_model(
+ llm_router=llm_router,
+ model=model,
+ request_data=request_data,
+ litellm_parent_otel_span=litellm_parent_otel_span,
+ )
+ responses.append(individual_response)
+ return responses
+
+ def generate_unified_resource_id(
+ self,
+ resource_objects: List[ResourceObjectType],
+ target_model_names_list: List[str],
+ ) -> str:
+ """
+ Generate a unified resource ID from multiple resource objects.
+
+ Args:
+ resource_objects: List of resource objects from different models
+ target_model_names_list: List of target model names
+
+ Returns:
+ Base64 encoded unified resource ID
+ """
+ # Use the first resource object to generate the format
+ unified_id_format = self.get_unified_resource_id_format(
+ resource_object=resource_objects[0],
+ target_model_names_list=target_model_names_list,
+ )
+
+ # Convert to URL-safe base64 and strip padding
+ base64_unified_id = (
+ base64.urlsafe_b64encode(unified_id_format.encode()).decode().rstrip("=")
+ )
+
+ return base64_unified_id
+
+ def extract_model_mappings_from_responses(
+ self,
+ resource_objects: List[ResourceObjectType],
+ ) -> Dict[str, str]:
+ """
+ Extract model mappings from resource objects.
+
+ Args:
+ resource_objects: List of resource objects from different models
+
+ Returns:
+ Dictionary mapping model_id -> provider_resource_id
+ """
+ model_mappings: Dict[str, str] = {}
+
+ for resource_object in resource_objects:
+ # Get hidden params if available
+ hidden_params = getattr(resource_object, "_hidden_params", {}) or {}
+ model_resource_id_mapping = hidden_params.get("model_resource_id_mapping")
+
+ if model_resource_id_mapping and isinstance(model_resource_id_mapping, dict):
+ model_mappings.update(model_resource_id_mapping)
+
+ return model_mappings
+
+ # ============================================================================
+ # DEPLOYMENT FILTERING
+ # ============================================================================
+
+ async def async_filter_deployments(
+ self,
+ model: str,
+ healthy_deployments: List,
+ request_kwargs: Optional[Dict] = None,
+ parent_otel_span: Optional[Span] = None,
+ resource_id_key: str = "resource_id",
+ ) -> List[Dict]:
+ """
+ Filter deployments based on model mappings for a resource.
+
+ This is used by the router to select only deployments that have
+ the resource available.
+
+ Args:
+ model: Model name
+ healthy_deployments: List of healthy deployments
+ request_kwargs: Request kwargs containing resource_id and mappings
+ parent_otel_span: OpenTelemetry span for tracing
+ resource_id_key: Key to use for resource ID in request_kwargs
+
+ Returns:
+ Filtered list of deployments
+ """
+ if request_kwargs is None:
+ return healthy_deployments
+
+ resource_id = cast(Optional[str], request_kwargs.get(resource_id_key))
+ model_resource_id_mapping = cast(
+ Optional[Dict[str, Dict[str, str]]],
+ request_kwargs.get("model_resource_id_mapping"),
+ )
+
+ allowed_model_ids = []
+ if resource_id and model_resource_id_mapping:
+ model_id_dict = model_resource_id_mapping.get(resource_id, {})
+ allowed_model_ids = list(model_id_dict.keys())
+
+ if len(allowed_model_ids) == 0:
+ return healthy_deployments
+
+ return [
+ deployment
+ for deployment in healthy_deployments
+ if deployment.get("model_info", {}).get("id") in allowed_model_ids
+ ]
+
+ # ============================================================================
+ # UTILITY METHODS
+ # ============================================================================
+
+ def get_unified_id_prefix(self) -> str:
+ """
+ Get the prefix for unified IDs for this resource type.
+
+ Returns:
+ Prefix string (e.g., "litellm_proxy:")
+ """
+ return SpecialEnums.LITELM_MANAGED_FILE_ID_PREFIX.value
+
+ async def list_user_resources(
+ self,
+ user_api_key_dict: UserAPIKeyAuth,
+ limit: Optional[int] = None,
+ after: Optional[str] = None,
+ additional_filters: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """
+ List resources created by a user.
+
+ Args:
+ user_api_key_dict: User API key authentication details
+ limit: Maximum number of resources to return
+ after: Cursor for pagination
+ additional_filters: Additional filters to apply
+
+ Returns:
+ Dictionary with list of resources and pagination info
+ """
+ where_clause: Dict[str, Any] = {}
+
+ # Filter by user who created the resource
+ if user_api_key_dict.user_id:
+ where_clause["created_by"] = user_api_key_dict.user_id
+
+ if after:
+ where_clause["id"] = {"gt": after}
+
+ # Add additional filters
+ if additional_filters:
+ where_clause.update(additional_filters)
+
+ # Fetch resources
+ fetch_limit = limit or 20
+ table = getattr(self.prisma_client.db, self.table_name)
+ resources = await table.find_many(
+ where=where_clause,
+ take=fetch_limit,
+ order={"created_at": "desc"},
+ )
+
+ resource_objects: List[Any] = []
+ for resource in resources:
+ try:
+ # Stop once we have enough
+ if len(resource_objects) >= (limit or 20):
+ break
+
+ # Parse resource object
+ resource_data = resource.resource_object
+ if isinstance(resource_data, str):
+ resource_data = json.loads(resource_data)
+
+ # Set unified ID
+ if hasattr(resource_data, "id"):
+ resource_data.id = resource.unified_resource_id
+ elif isinstance(resource_data, dict):
+ resource_data["id"] = resource.unified_resource_id
+
+ resource_objects.append(resource_data)
+
+ except Exception as e:
+ verbose_logger.warning(
+ f"Failed to parse {self.resource_type} object "
+ f"{resource.unified_resource_id}: {e}"
+ )
+ continue
+
+ return {
+ "object": "list",
+ "data": resource_objects,
+ "first_id": resource_objects[0].id if resource_objects else None,
+ "last_id": resource_objects[-1].id if resource_objects else None,
+ "has_more": len(resource_objects) == (limit or 20),
+ }
diff --git a/litellm/llms/base_llm/managed_resources/utils.py b/litellm/llms/base_llm/managed_resources/utils.py
new file mode 100644
index 00000000000..0d843b6d128
--- /dev/null
+++ b/litellm/llms/base_llm/managed_resources/utils.py
@@ -0,0 +1,364 @@
+"""
+Utility functions for managed resources.
+
+This module provides common utility functions that can be used across
+different managed resource types (files, vector stores, etc.).
+"""
+
+import base64
+import re
+from typing import List, Optional, Union, Literal
+
+
+def is_base64_encoded_unified_id(
+ resource_id: str,
+ prefix: str = "litellm_proxy:",
+) -> Union[str, Literal[False]]:
+ """
+ Check if a resource ID is a base64 encoded unified ID.
+
+ Args:
+ resource_id: The resource ID to check
+ prefix: The expected prefix for unified IDs
+
+ Returns:
+ Decoded string if valid unified ID, False otherwise
+ """
+ # Ensure resource_id is a string
+ if not isinstance(resource_id, str):
+ return False
+
+ # Add padding back if needed
+ padded = resource_id + "=" * (-len(resource_id) % 4)
+
+ # Decode from base64
+ try:
+ decoded = base64.urlsafe_b64decode(padded).decode()
+ if decoded.startswith(prefix):
+ return decoded
+ else:
+ return False
+ except Exception:
+ return False
+
+
+def extract_target_model_names_from_unified_id(
+ unified_id: str,
+) -> List[str]:
+ """
+ Extract target model names from a unified resource ID.
+
+ Args:
+ unified_id: The unified resource ID (decoded or encoded)
+
+ Returns:
+ List of target model names
+
+ Example:
+ unified_id = "litellm_proxy:vector_store;unified_id,uuid;target_model_names,gpt-4,gemini-2.0"
+ returns: ["gpt-4", "gemini-2.0"]
+ """
+ try:
+ # Ensure unified_id is a string
+ if not isinstance(unified_id, str):
+ return []
+
+ # Decode if it's base64 encoded
+ decoded_id = is_base64_encoded_unified_id(unified_id)
+ if decoded_id:
+ unified_id = decoded_id
+
+ # Extract model names using regex
+ match = re.search(r"target_model_names,([^;]+)", unified_id)
+ if match:
+ # Split on comma and strip whitespace from each model name
+ return [model.strip() for model in match.group(1).split(",")]
+
+ return []
+ except Exception:
+ return []
+
+
+def extract_resource_type_from_unified_id(
+ unified_id: str,
+) -> Optional[str]:
+ """
+ Extract resource type from a unified resource ID.
+
+ Args:
+ unified_id: The unified resource ID (decoded or encoded)
+
+ Returns:
+ Resource type string or None
+
+ Example:
+ unified_id = "litellm_proxy:vector_store;unified_id,uuid;..."
+ returns: "vector_store"
+ """
+ try:
+ # Ensure unified_id is a string
+ if not isinstance(unified_id, str):
+ return None
+
+ # Decode if it's base64 encoded
+ decoded_id = is_base64_encoded_unified_id(unified_id)
+ if decoded_id:
+ unified_id = decoded_id
+
+ # Extract resource type (comes after prefix and before first semicolon)
+ match = re.search(r"litellm_proxy:([^;]+)", unified_id)
+ if match:
+ return match.group(1).strip()
+
+ return None
+ except Exception:
+ return None
+
+
+def extract_unified_uuid_from_unified_id(
+ unified_id: str,
+) -> Optional[str]:
+ """
+ Extract the UUID from a unified resource ID.
+
+ Args:
+ unified_id: The unified resource ID (decoded or encoded)
+
+ Returns:
+ UUID string or None
+
+ Example:
+ unified_id = "litellm_proxy:vector_store;unified_id,abc-123;..."
+ returns: "abc-123"
+ """
+ try:
+ # Ensure unified_id is a string
+ if not isinstance(unified_id, str):
+ return None
+
+ # Decode if it's base64 encoded
+ decoded_id = is_base64_encoded_unified_id(unified_id)
+ if decoded_id:
+ unified_id = decoded_id
+
+ # Extract UUID
+ match = re.search(r"unified_id,([^;]+)", unified_id)
+ if match:
+ return match.group(1).strip()
+
+ return None
+ except Exception:
+ return None
+
+
+def extract_model_id_from_unified_id(
+ unified_id: str,
+) -> Optional[str]:
+ """
+ Extract model ID from a unified resource ID.
+
+ Args:
+ unified_id: The unified resource ID (decoded or encoded)
+
+ Returns:
+ Model ID string or None
+
+ Example:
+ unified_id = "litellm_proxy:vector_store;...;model_id,gpt-4-model-id;..."
+ returns: "gpt-4-model-id"
+ """
+ try:
+ # Ensure unified_id is a string
+ if not isinstance(unified_id, str):
+ return None
+
+ # Decode if it's base64 encoded
+ decoded_id = is_base64_encoded_unified_id(unified_id)
+ if decoded_id:
+ unified_id = decoded_id
+
+ # Extract model ID
+ match = re.search(r"model_id,([^;]+)", unified_id)
+ if match:
+ return match.group(1).strip()
+
+ return None
+ except Exception:
+ return None
+
+
+def extract_provider_resource_id_from_unified_id(
+ unified_id: str,
+) -> Optional[str]:
+ """
+ Extract provider resource ID from a unified resource ID.
+
+ Args:
+ unified_id: The unified resource ID (decoded or encoded)
+
+ Returns:
+ Provider resource ID string or None
+
+ Example:
+ unified_id = "litellm_proxy:vector_store;...;resource_id,vs_abc123;..."
+ returns: "vs_abc123"
+ """
+ try:
+ # Ensure unified_id is a string
+ if not isinstance(unified_id, str):
+ return None
+
+ # Decode if it's base64 encoded
+ decoded_id = is_base64_encoded_unified_id(unified_id)
+ if decoded_id:
+ unified_id = decoded_id
+
+ # Extract resource ID (try multiple patterns for different resource types)
+ patterns = [
+ r"resource_id,([^;]+)",
+ r"vector_store_id,([^;]+)",
+ r"file_id,([^;]+)",
+ ]
+
+ for pattern in patterns:
+ match = re.search(pattern, unified_id)
+ if match:
+ return match.group(1).strip()
+
+ return None
+ except Exception:
+ return None
+
+
+def generate_unified_id_string(
+ resource_type: str,
+ unified_uuid: str,
+ target_model_names: List[str],
+ provider_resource_id: str,
+ model_id: str,
+ additional_fields: Optional[dict] = None,
+) -> str:
+ """
+ Generate a unified ID string (before base64 encoding).
+
+ Args:
+ resource_type: Type of resource (e.g., "vector_store", "file")
+ unified_uuid: UUID for this unified resource
+ target_model_names: List of target model names
+ provider_resource_id: Resource ID from the provider
+ model_id: Model ID from the router
+ additional_fields: Additional fields to include in the ID
+
+ Returns:
+ Unified ID string (not yet base64 encoded)
+
+ Example:
+ generate_unified_id_string(
+ resource_type="vector_store",
+ unified_uuid="abc-123",
+ target_model_names=["gpt-4", "gemini"],
+ provider_resource_id="vs_xyz",
+ model_id="model-id-123",
+ )
+ returns: "litellm_proxy:vector_store;unified_id,abc-123;target_model_names,gpt-4,gemini;resource_id,vs_xyz;model_id,model-id-123"
+ """
+ # Build the unified ID string
+ parts = [
+ f"litellm_proxy:{resource_type}",
+ f"unified_id,{unified_uuid}",
+ f"target_model_names,{','.join(target_model_names)}",
+ f"resource_id,{provider_resource_id}",
+ f"model_id,{model_id}",
+ ]
+
+ # Add additional fields if provided
+ if additional_fields:
+ for key, value in additional_fields.items():
+ parts.append(f"{key},{value}")
+
+ return ";".join(parts)
+
+
+def encode_unified_id(unified_id_string: str) -> str:
+ """
+ Encode a unified ID string to base64.
+
+ Args:
+ unified_id_string: The unified ID string to encode
+
+ Returns:
+ Base64 encoded unified ID (URL-safe, padding stripped)
+ """
+ return (
+ base64.urlsafe_b64encode(unified_id_string.encode())
+ .decode()
+ .rstrip("=")
+ )
+
+
+def decode_unified_id(encoded_unified_id: str) -> Optional[str]:
+ """
+ Decode a base64 encoded unified ID.
+
+ Args:
+ encoded_unified_id: The base64 encoded unified ID
+
+ Returns:
+ Decoded unified ID string or None if invalid
+ """
+ try:
+ # Add padding back if needed
+ padded = encoded_unified_id + "=" * (-len(encoded_unified_id) % 4)
+
+ # Decode from base64
+ decoded = base64.urlsafe_b64decode(padded).decode()
+
+ # Verify it starts with the expected prefix
+ if decoded.startswith("litellm_proxy:"):
+ return decoded
+
+ return None
+ except Exception:
+ return None
+
+
+def parse_unified_id(
+ unified_id: str,
+) -> Optional[dict]:
+ """
+ Parse a unified ID into its components.
+
+ Args:
+ unified_id: The unified ID (encoded or decoded)
+
+ Returns:
+ Dictionary with parsed components or None if invalid
+
+ Example:
+ {
+ "resource_type": "vector_store",
+ "unified_uuid": "abc-123",
+ "target_model_names": ["gpt-4", "gemini"],
+ "provider_resource_id": "vs_xyz",
+ "model_id": "model-id-123"
+ }
+ """
+ try:
+ # Decode if needed
+ decoded_id = decode_unified_id(unified_id)
+ if not decoded_id:
+ # Maybe it's already decoded
+ if unified_id.startswith("litellm_proxy:"):
+ decoded_id = unified_id
+ else:
+ return None
+
+ return {
+ "resource_type": extract_resource_type_from_unified_id(decoded_id),
+ "unified_uuid": extract_unified_uuid_from_unified_id(decoded_id),
+ "target_model_names": extract_target_model_names_from_unified_id(decoded_id),
+ "provider_resource_id": extract_provider_resource_id_from_unified_id(decoded_id),
+ "model_id": extract_model_id_from_unified_id(decoded_id),
+ }
+ except Exception:
+ return None
diff --git a/litellm/llms/base_llm/vector_store/transformation.py b/litellm/llms/base_llm/vector_store/transformation.py
index 89f2094d5df..935fd53c199 100644
--- a/litellm/llms/base_llm/vector_store/transformation.py
+++ b/litellm/llms/base_llm/vector_store/transformation.py
@@ -5,8 +5,8 @@ import httpx
from litellm.types.router import GenericLiteLLMParams
from litellm.types.vector_stores import (
- BaseVectorStoreAuthCredentials,
VECTOR_STORE_OPENAI_PARAMS,
+ BaseVectorStoreAuthCredentials,
VectorStoreCreateOptionalRequestParams,
VectorStoreCreateResponse,
VectorStoreIndexEndpoints,
@@ -64,6 +64,30 @@ class BaseVectorStoreConfig:
pass
+ async def atransform_search_vector_store_request(
+ self,
+ vector_store_id: str,
+ query: Union[str, List[str]],
+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,
+ api_base: str,
+ litellm_logging_obj: LiteLLMLoggingObj,
+ litellm_params: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Optional async version of transform_search_vector_store_request.
+ If not implemented, the handler will fall back to the sync version.
+ Providers that need to make async calls (e.g., generating embeddings) should override this.
+ """
+ # Default implementation: call the sync version
+ return self.transform_search_vector_store_request(
+ vector_store_id=vector_store_id,
+ query=query,
+ vector_store_search_optional_params=vector_store_search_optional_params,
+ api_base=api_base,
+ litellm_logging_obj=litellm_logging_obj,
+ litellm_params=litellm_params,
+ )
+
@abstractmethod
def transform_search_vector_store_response(
self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj
diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.py
index 642d15fe3ed..dfaddb3c2b1 100644
--- a/litellm/llms/bedrock/base_aws_llm.py
+++ b/litellm/llms/bedrock/base_aws_llm.py
@@ -211,25 +211,13 @@ class BaseAWSLLM:
aws_external_id=aws_external_id,
)
elif aws_role_name is not None:
- # Check if we're in IRSA and trying to assume the same role we already have
- current_role_arn = os.getenv("AWS_ROLE_ARN")
- web_identity_token_file = os.getenv("AWS_WEB_IDENTITY_TOKEN_FILE")
-
- # In IRSA environments, we should skip role assumption if we're already running as the target role
- # This is true when:
- # 1. We have AWS_ROLE_ARN set (current role)
- # 2. We have AWS_WEB_IDENTITY_TOKEN_FILE set (IRSA environment)
- # 3. The current role matches the requested role
- if (
- current_role_arn
- and web_identity_token_file
- and current_role_arn == aws_role_name
- ):
+ # Check if we're already running as the target role and can skip assumption
+ # This handles IRSA (EKS), ECS task roles, and EC2 instance profiles
+ if self._is_already_running_as_role(aws_role_name, ssl_verify=ssl_verify):
verbose_logger.debug(
- "Using IRSA same-role optimization: calling _auth_with_env_vars"
+ "Already running as target role %s, using ambient credentials",
+ aws_role_name,
)
- # We're already running as this role via IRSA, no need to assume it again
- # Use the default boto3 credentials (which will use the IRSA credentials)
credentials, _cache_ttl = self._auth_with_env_vars()
else:
verbose_logger.debug(
@@ -396,6 +384,14 @@ class BaseAWSLLM:
model_id = BaseAWSLLM._get_model_id_from_model_with_spec(
model_id, spec="moonshot"
)
+ elif "nova-2/" in model_id:
+ model_id = BaseAWSLLM._get_model_id_from_model_with_spec(
+ model_id, spec="nova-2"
+ )
+ elif "nova/" in model_id:
+ model_id = BaseAWSLLM._get_model_id_from_model_with_spec(
+ model_id, spec="nova"
+ )
return model_id
@staticmethod
@@ -553,6 +549,107 @@ class BaseAWSLLM:
aws_region_name = "us-west-2"
return aws_region_name
+ @staticmethod
+ def _parse_arn_account_and_role_name(
+ arn: str,
+ ) -> Optional[Tuple[str, str, str]]:
+ """
+ Parse an ARN and return (partition, account_id, role_name).
+
+ Handles:
+ - arn:aws:iam::123456789012:role/MyRole
+ - arn:aws:iam::123456789012:role/path/to/MyRole
+ - arn:aws:sts::123456789012:assumed-role/MyRole/session-name
+
+ Returns None if the ARN cannot be parsed.
+ """
+ # ARN format: arn:PARTITION:SERVICE:REGION:ACCOUNT:RESOURCE
+ parts = arn.split(":")
+ if len(parts) < 6 or parts[0] != "arn":
+ return None
+
+ partition = parts[1] # e.g. "aws", "aws-cn", "aws-us-gov"
+ account_id = parts[4]
+ resource = ":".join(parts[5:]) # rejoin in case resource contains colons
+
+ if resource.startswith("role/"):
+ # arn:aws:iam::ACCOUNT:role/[path/]ROLE_NAME
+ role_name = resource.split("/")[-1]
+ elif resource.startswith("assumed-role/"):
+ # arn:aws:sts::ACCOUNT:assumed-role/ROLE_NAME/SESSION
+ role_parts = resource.split("/")
+ if len(role_parts) >= 2:
+ role_name = role_parts[1]
+ else:
+ return None
+ else:
+ return None
+
+ return partition, account_id, role_name
+
+ def _is_already_running_as_role(
+ self,
+ aws_role_name: str,
+ ssl_verify: Optional[Union[bool, str]] = None,
+ ) -> bool:
+ """
+ Check if the current environment is already running as the target IAM role.
+
+ This handles multiple AWS environments:
+ - IRSA (EKS): AWS_ROLE_ARN + AWS_WEB_IDENTITY_TOKEN_FILE are set
+ - ECS task roles: Uses sts:GetCallerIdentity to check current role ARN
+ - EC2 instance profiles: Uses sts:GetCallerIdentity to check current role ARN
+
+ Compares partition, account ID, and role name to avoid cross-account
+ false matches.
+
+ Returns True if the current identity matches the target role, meaning
+ we can skip sts:AssumeRole and use ambient credentials directly.
+ """
+ target_parsed = self._parse_arn_account_and_role_name(aws_role_name)
+ if target_parsed is None:
+ return False
+
+ target_partition, target_account, target_role = target_parsed
+
+ # Fast path: IRSA environment check (no API call needed)
+ current_role_arn = os.getenv("AWS_ROLE_ARN")
+ web_identity_token_file = os.getenv("AWS_WEB_IDENTITY_TOKEN_FILE")
+ if current_role_arn and web_identity_token_file:
+ return current_role_arn == aws_role_name
+
+ # For ECS/EC2: call sts:GetCallerIdentity to check if already running as the role
+ try:
+ import boto3
+
+ with tracer.trace("boto3.client(sts).get_caller_identity"):
+ sts_client = boto3.client(
+ "sts", verify=self._get_ssl_verify(ssl_verify)
+ )
+ identity = sts_client.get_caller_identity()
+ caller_arn = identity.get("Arn", "")
+
+ caller_parsed = self._parse_arn_account_and_role_name(caller_arn)
+ if caller_parsed is not None:
+ caller_partition, caller_account, caller_role = caller_parsed
+ if (
+ caller_partition == target_partition
+ and caller_account == target_account
+ and caller_role == target_role
+ ):
+ verbose_logger.debug(
+ "Current identity already matches target role: %s",
+ aws_role_name,
+ )
+ return True
+
+ except Exception as e:
+ verbose_logger.debug(
+ "Could not determine current role identity: %s", str(e)
+ )
+
+ return False
+
@tracer.wrap()
def _auth_with_web_identity_token(
self,
@@ -867,7 +964,35 @@ class BaseAWSLLM:
if aws_external_id is not None:
assume_role_params["ExternalId"] = aws_external_id
- sts_response = sts_client.assume_role(**assume_role_params)
+ try:
+ sts_response = sts_client.assume_role(**assume_role_params)
+ except Exception as e:
+ error_str = str(e)
+ if "AccessDenied" in error_str:
+ # Only fall back to ambient credentials if we can positively
+ # confirm the caller is already the target role (same account,
+ # partition, and role name). This avoids silently using the
+ # wrong identity when there is a genuine trust-policy or
+ # permission misconfiguration.
+ if self._is_already_running_as_role(
+ aws_role_name, ssl_verify=ssl_verify
+ ):
+ verbose_logger.warning(
+ "AssumeRole failed for %s (%s). "
+ "Caller is already running as this role; "
+ "falling back to ambient credentials.",
+ aws_role_name,
+ error_str,
+ )
+ return self._auth_with_env_vars()
+ # Genuine permission error — re-raise
+ verbose_logger.error(
+ "AssumeRole AccessDenied for %s and caller is NOT "
+ "the same role. Re-raising. Error: %s",
+ aws_role_name,
+ error_str,
+ )
+ raise
# Extract the credentials from the response and convert to Session Credentials
sts_credentials = sts_response["Credentials"]
@@ -1163,7 +1288,7 @@ class BaseAWSLLM:
def _sign_request(
self,
- service_name: Literal["bedrock", "sagemaker", "bedrock-agentcore"],
+ service_name: Literal["bedrock", "sagemaker", "bedrock-agentcore", "s3vectors"],
headers: dict,
optional_params: dict,
request_data: dict,
diff --git a/litellm/llms/bedrock/chat/converse_handler.py b/litellm/llms/bedrock/chat/converse_handler.py
index d5bd054118d..60a93b169c8 100644
--- a/litellm/llms/bedrock/chat/converse_handler.py
+++ b/litellm/llms/bedrock/chat/converse_handler.py
@@ -13,7 +13,9 @@ from litellm.llms.custom_httpx.http_handler import (
)
from litellm.types.utils import ModelResponse
from litellm.utils import CustomStreamWrapper
-
+from litellm.anthropic_beta_headers_manager import (
+ update_headers_with_filtered_beta,
+ )
from ..base_aws_llm import BaseAWSLLM, Credentials
from ..common_utils import BedrockError
from .invoke_handler import AWSEventStreamDecoder, MockResponseIterator, make_call
@@ -270,7 +272,18 @@ class BedrockConverseLLM(BaseAWSLLM):
if unencoded_model_id is not None:
modelId = self.encode_model_id(model_id=unencoded_model_id)
else:
- modelId = self.encode_model_id(model_id=model)
+ # Strip nova spec prefixes before encoding model ID for API URL
+ _model_for_id = model
+ _stripped = _model_for_id
+ for rp in ["bedrock/converse/", "bedrock/", "converse/"]:
+ if _stripped.startswith(rp):
+ _stripped = _stripped[len(rp):]
+ break
+ for _nova_prefix in ["nova-2/", "nova/"]:
+ if _stripped.startswith(_nova_prefix):
+ _model_for_id = _model_for_id.replace(_nova_prefix, "", 1)
+ break
+ modelId = self.encode_model_id(model_id=_model_for_id)
fake_stream = litellm.AmazonConverseConfig().should_fake_stream(
fake_stream=fake_stream,
@@ -337,7 +350,11 @@ class BedrockConverseLLM(BaseAWSLLM):
headers = {"Content-Type": "application/json"}
if extra_headers is not None:
headers = {"Content-Type": "application/json", **extra_headers}
-
+
+ # Filter beta headers in HTTP headers before making the request
+ headers = update_headers_with_filtered_beta(
+ headers=headers, provider="bedrock_converse"
+ )
### ROUTING (ASYNC, STREAMING, SYNC)
if acompletion:
if isinstance(client, HTTPHandler):
diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.py
index ec665142073..daac3e6a008 100644
--- a/litellm/llms/bedrock/chat/converse_transformation.py
+++ b/litellm/llms/bedrock/chat/converse_transformation.py
@@ -3,6 +3,7 @@ Translating between OpenAI's `/chat/completion` format and Amazon's `/converse`
"""
import copy
+import json
import time
import types
from typing import List, Literal, Optional, Tuple, Union, cast, overload
@@ -11,7 +12,10 @@ import httpx
import litellm
from litellm._logging import verbose_logger
-from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+from litellm.constants import (
+ BEDROCK_MIN_THINKING_BUDGET_TOKENS,
+ RESPONSE_FORMAT_TOOL_NAME,
+)
from litellm.litellm_core_utils.core_helpers import (
filter_exceptions_from_params,
filter_internal_params,
@@ -66,6 +70,7 @@ from ..common_utils import (
BedrockModelInfo,
get_anthropic_beta_from_headers,
get_bedrock_tool_name,
+ is_claude_4_5_on_bedrock,
)
# Computer use tool prefixes supported by Bedrock
@@ -76,6 +81,42 @@ BEDROCK_COMPUTER_USE_TOOLS = [
"text_editor_",
]
+# Beta header patterns that are not supported by Bedrock Converse API
+# These will be filtered out to prevent errors
+UNSUPPORTED_BEDROCK_CONVERSE_BETA_PATTERNS = [
+ "advanced-tool-use", # Bedrock Converse doesn't support advanced-tool-use beta headers
+ "prompt-caching", # Prompt caching not supported in Converse API
+ "compact-2026-01-12", # The compact beta feature is not currently supported on the Converse and ConverseStream APIs
+]
+
+# Models that support Bedrock's native structured outputs API (outputConfig.textFormat)
+# Uses substring matching against the Bedrock model ID
+# Ref: https://docs.aws.amazon.com/bedrock/latest/userguide/structured-output.html
+BEDROCK_NATIVE_STRUCTURED_OUTPUT_MODELS = {
+ # Anthropic Claude 4.5+
+ "claude-haiku-4-5",
+ "claude-sonnet-4-5",
+ "claude-opus-4-5",
+ "claude-opus-4-6",
+ # Qwen3
+ "qwen3",
+ # DeepSeek
+ "deepseek-v3.1",
+ # Gemma 3
+ "gemma-3",
+ # MiniMax
+ "minimax-m2",
+ # Mistral (magistral-small excluded: broken constrained decoding on Bedrock)
+ "ministral",
+ "mistral-large-3",
+ "voxtral",
+ # Moonshot
+ "kimi-k2",
+ # NVIDIA
+ "nemotron-nano",
+ # OpenAI (gpt-oss excluded: broken constrained decoding, works via tool-call fallback)
+}
+
class AmazonConverseConfig(BaseConfig):
"""
@@ -258,50 +299,59 @@ class AmazonConverseConfig(BaseConfig):
llm_provider="bedrock",
)
- def _is_nova_lite_2_model(self, model: str) -> bool:
+ def _is_nova_2_model(self, model: str) -> bool:
"""
- Check if the model is a Nova Lite 2 model that supports reasoningConfig.
+ Check if the model is a Nova 2 model that supports reasoningConfig.
- Nova Lite 2 models use a different reasoning configuration structure compared to
+ Nova 2 models use a different reasoning configuration structure compared to
Anthropic's thinking parameter and GPT-OSS's reasoning_effort parameter.
Supported models:
- amazon.nova-2-lite-v1:0
+ - amazon.nova-2-pro-preview-20251202-v1:0
- us.amazon.nova-2-lite-v1:0
- eu.amazon.nova-2-lite-v1:0
- apac.amazon.nova-2-lite-v1:0
+ - (and other regional variants)
Args:
model: The model identifier
Returns:
- True if the model is a Nova Lite 2 model, False otherwise
+ True if the model is a Nova 2 model, False otherwise
Examples:
>>> config = AmazonConverseConfig()
- >>> config._is_nova_lite_2_model("amazon.nova-2-lite-v1:0")
+ >>> config._is_nova_2_model("amazon.nova-2-lite-v1:0")
True
- >>> config._is_nova_lite_2_model("us.amazon.nova-2-lite-v1:0")
+ >>> config._is_nova_2_model("us.amazon.nova-2-lite-v1:0")
True
- >>> config._is_nova_lite_2_model("amazon.nova-pro-1-5-v1:0")
+ >>> config._is_nova_2_model("us.amazon.nova-2-pro-preview-20251202-v1:0")
+ True
+ >>> config._is_nova_2_model("amazon.nova-pro-1-5-v1:0")
False
- >>> config._is_nova_lite_2_model("amazon.nova-pro-v1:0")
+ >>> config._is_nova_2_model("amazon.nova-pro-v1:0")
False
"""
- # Remove regional prefix if present (us., eu., apac.)
+ # Remove provider routing prefix if present (bedrock/converse/, bedrock/, converse/)
model_without_region = model
- for prefix in ["us.", "eu.", "apac."]:
- if model.startswith(prefix):
- model_without_region = model[len(prefix) :]
+ for routing_prefix in ["bedrock/converse/", "bedrock/", "converse/"]:
+ if model_without_region.startswith(routing_prefix):
+ model_without_region = model_without_region[len(routing_prefix) :]
break
- # Check if the model is specifically Nova Lite 2
- return "nova-2-lite" in model_without_region
+ # Remove regional prefix if present (us., eu., apac.)
+ for prefix in ["us.", "eu.", "apac."]:
+ if model_without_region.startswith(prefix):
+ model_without_region = model_without_region[len(prefix) :]
+ break
+
+ # Check if the model is a Nova 2 model (matches nova-2-lite, nova-2-pro, etc.)
+ # Also check for nova-2/ spec prefix for imported models
+ return model_without_region.startswith("amazon.nova-2-") or model_without_region.startswith("nova-2/")
def _map_web_search_options(
- self,
- web_search_options: dict,
- model: str
+ self, web_search_options: dict, model: str
) -> Optional[BedrockToolBlock]:
"""
Map web_search_options to Nova grounding systemTool.
@@ -386,7 +436,7 @@ class AmazonConverseConfig(BaseConfig):
Different model families handle reasoning effort differently:
- GPT-OSS models: Keep reasoning_effort as-is (passed to additionalModelRequestFields)
- - Nova Lite 2 models: Transform to reasoningConfig structure
+ - Nova 2 models: Transform to reasoningConfig structure
- Other models (Anthropic, etc.): Convert to thinking parameter
Args:
@@ -415,8 +465,8 @@ class AmazonConverseConfig(BaseConfig):
# GPT-OSS models: keep reasoning_effort as-is
# It will be passed through to additionalModelRequestFields
optional_params["reasoning_effort"] = reasoning_effort
- elif self._is_nova_lite_2_model(model):
- # Nova Lite 2 models: transform to reasoningConfig
+ elif self._is_nova_2_model(model):
+ # Nova 2 models: transform to reasoningConfig
reasoning_config = self._transform_reasoning_effort_to_reasoning_config(
reasoning_effort
)
@@ -424,9 +474,28 @@ class AmazonConverseConfig(BaseConfig):
else:
# Anthropic and other models: convert to thinking parameter
optional_params["thinking"] = AnthropicConfig._map_reasoning_effort(
- reasoning_effort
+ reasoning_effort=reasoning_effort, model=model
)
+ @staticmethod
+ def _clamp_thinking_budget_tokens(optional_params: dict) -> None:
+ """
+ Clamp thinking.budget_tokens to the Bedrock minimum (1024).
+
+ Bedrock returns a 400 error if budget_tokens < 1024.
+ """
+ thinking = optional_params.get("thinking")
+ if isinstance(thinking, dict):
+ budget = thinking.get("budget_tokens")
+ if isinstance(budget, int) and budget < BEDROCK_MIN_THINKING_BUDGET_TOKENS:
+ verbose_logger.debug(
+ "Bedrock requires thinking.budget_tokens >= %d, got %d. "
+ "Clamping to minimum.",
+ BEDROCK_MIN_THINKING_BUDGET_TOKENS,
+ budget,
+ )
+ thinking["budget_tokens"] = BEDROCK_MIN_THINKING_BUDGET_TOKENS
+
def get_supported_openai_params(self, model: str) -> List[str]:
from litellm.utils import supports_function_calling
@@ -451,6 +520,9 @@ class AmazonConverseConfig(BaseConfig):
supported_params.append("tool_choice")
supported_params.append("thinking")
supported_params.append("reasoning_effort")
+ # For nova imported models, also add web_search_options
+ if "nova" in model.lower():
+ supported_params.append("web_search_options")
return supported_params
## Filter out 'cross-region' from model name
@@ -485,8 +557,8 @@ class AmazonConverseConfig(BaseConfig):
if "gpt-oss" in model:
supported_params.append("reasoning_effort")
- elif self._is_nova_lite_2_model(model):
- # Nova Lite 2 models support reasoning_effort (transformed to reasoningConfig)
+ elif self._is_nova_2_model(model):
+ # Nova 2 models support reasoning_effort (transformed to reasoningConfig)
# These models use a different reasoning structure than Anthropic's thinking parameter
supported_params.append("reasoning_effort")
elif (
@@ -685,6 +757,100 @@ class AmazonConverseConfig(BaseConfig):
)
return _tool
+ @staticmethod
+ def _supports_native_structured_outputs(model: str) -> bool:
+ """Check if the Bedrock model supports native structured outputs (outputConfig.textFormat)."""
+ return any(
+ substring in model
+ for substring in BEDROCK_NATIVE_STRUCTURED_OUTPUT_MODELS
+ )
+
+ @staticmethod
+ def _add_additional_properties_to_schema(schema: dict) -> dict:
+ """
+ Recursively ensure all object types in a JSON schema have
+ ``"additionalProperties": false``.
+
+ Bedrock's native structured-outputs API requires this field to be
+ explicitly set on every object node, otherwise it returns a
+ validation error.
+ """
+ if not isinstance(schema, dict):
+ return schema
+
+ result = dict(schema)
+
+ if result.get("type") == "object" and "additionalProperties" not in result:
+ result["additionalProperties"] = False
+
+ # Recurse into nested schemas
+ if "properties" in result and isinstance(result["properties"], dict):
+ result["properties"] = {
+ k: AmazonConverseConfig._add_additional_properties_to_schema(v)
+ for k, v in result["properties"].items()
+ }
+ if "items" in result and isinstance(result["items"], dict):
+ result["items"] = AmazonConverseConfig._add_additional_properties_to_schema(
+ result["items"]
+ )
+ for defs_key in ("$defs", "definitions"):
+ if defs_key in result and isinstance(result[defs_key], dict):
+ result[defs_key] = {
+ k: AmazonConverseConfig._add_additional_properties_to_schema(v)
+ for k, v in result[defs_key].items()
+ }
+ for key in ("anyOf", "allOf", "oneOf"):
+ if key in result and isinstance(result[key], list):
+ result[key] = [
+ AmazonConverseConfig._add_additional_properties_to_schema(item)
+ for item in result[key]
+ ]
+
+ return result
+
+ @staticmethod
+ def _create_output_config_for_response_format(
+ json_schema: Optional[dict] = None,
+ name: Optional[str] = None,
+ description: Optional[str] = None,
+ ) -> "OutputConfigBlock":
+ """
+ Build an outputConfig block for Bedrock's native structured outputs API.
+
+ The Converse API expects:
+ {
+ "outputConfig": {
+ "textFormat": {
+ "type": "json_schema",
+ "structure": {
+ "jsonSchema": {
+ "schema": "",
+ "name": "optional",
+ "description": "optional"
+ }
+ }
+ }
+ }
+ }
+ """
+ if json_schema is not None:
+ json_schema = AmazonConverseConfig._add_additional_properties_to_schema(
+ json_schema
+ )
+ schema_str = json.dumps(json_schema) if json_schema is not None else "{}"
+ json_schema_def: JsonSchemaDefinition = {"schema": schema_str}
+ if name is not None:
+ json_schema_def["name"] = name
+ if description is not None:
+ json_schema_def["description"] = description
+
+ return OutputConfigBlock(
+ textFormat=OutputFormat(
+ type="json_schema",
+ structure=OutputFormatStructure(jsonSchema=json_schema_def),
+ )
+ )
+
def _apply_tool_call_transformation(
self,
tools: List[OpenAIChatCompletionToolParam],
@@ -767,16 +933,18 @@ class AmazonConverseConfig(BaseConfig):
if bedrock_tier in ("default", "flex", "priority"):
optional_params["serviceTier"] = {"type": bedrock_tier}
- if param == "web_search_options" and value and isinstance(value, dict):
- grounding_tool = self._map_web_search_options(value, model)
- if grounding_tool is not None:
- optional_params = self._add_tools_to_optional_params(
- optional_params=optional_params, tools=[grounding_tool]
- )
+ if param == "web_search_options" and isinstance(value, dict):
+ # Note: we use `isinstance(value, dict)` instead of `value and isinstance(value, dict)`
+ # because empty dict {} is falsy but is a valid way to enable Nova grounding
+ grounding_tool = self._map_web_search_options(value, model)
+ if grounding_tool is not None:
+ optional_params = self._add_tools_to_optional_params(
+ optional_params=optional_params, tools=[grounding_tool]
+ )
# Only update thinking tokens for non-GPT-OSS models and non-Nova-Lite-2 models
- # Nova Lite 2 handles token budgeting differently through reasoningConfig
- if "gpt-oss" not in model and not self._is_nova_lite_2_model(model):
+ # Nova 2 handles token budgeting differently through reasoningConfig
+ if "gpt-oss" not in model and not self._is_nova_2_model(model):
self.update_optional_params_with_thinking_tokens(
non_default_params=non_default_params, optional_params=optional_params
)
@@ -812,45 +980,53 @@ class AmazonConverseConfig(BaseConfig):
return optional_params
json_schema: Optional[dict] = None
+ name: Optional[str] = None
description: Optional[str] = None
if "response_schema" in value:
json_schema = value["response_schema"]
elif "json_schema" in value:
json_schema = value["json_schema"]["schema"]
+ name = value["json_schema"].get("name")
description = value["json_schema"].get("description")
if "type" in value and value["type"] == "text":
return optional_params
- """
- Follow similar approach to anthropic - translate to a single tool call.
-
- When using tools in this way: - https://docs.anthropic.com/en/docs/build-with-claude/tool-use#json-mode
- - You usually want to provide a single tool
- - You should set tool_choice (see Forcing tool use) to instruct the model to explicitly use that tool
- - Remember that the model will pass the input to the tool, so the name of the tool and description should be from the model’s perspective.
- """
- _tool = self._create_json_tool_call_for_response_format(
- json_schema=json_schema,
- description=description,
- )
- optional_params = self._add_tools_to_optional_params(
- optional_params=optional_params, tools=[_tool]
- )
-
- if (
- litellm.utils.supports_tool_choice(
- model=model, custom_llm_provider=self.custom_llm_provider
+ if self._supports_native_structured_outputs(model) and json_schema is not None:
+ # Use Bedrock's native structured outputs API (outputConfig.textFormat)
+ # No synthetic tool injection, no fake_stream needed.
+ # Requires an explicit schema — json_object with no schema falls through
+ # to the tool-call path below.
+ output_config = self._create_output_config_for_response_format(
+ json_schema=json_schema,
+ name=name,
+ description=description,
)
- and not is_thinking_enabled
- ):
- optional_params["tool_choice"] = ToolChoiceValuesBlock(
- tool=SpecificToolChoiceBlock(name=RESPONSE_FORMAT_TOOL_NAME)
+ optional_params["outputConfig"] = output_config
+ else:
+ # Fallback: translate to a synthetic tool call
+ # https://docs.anthropic.com/en/docs/build-with-claude/tool-use#json-mode
+ _tool = self._create_json_tool_call_for_response_format(
+ json_schema=json_schema,
+ description=description,
)
+ optional_params = self._add_tools_to_optional_params(
+ optional_params=optional_params, tools=[_tool]
+ )
+
+ if (
+ litellm.utils.supports_tool_choice(
+ model=model, custom_llm_provider=self.custom_llm_provider
+ )
+ and not is_thinking_enabled
+ ):
+ optional_params["tool_choice"] = ToolChoiceValuesBlock(
+ tool=SpecificToolChoiceBlock(name=RESPONSE_FORMAT_TOOL_NAME)
+ )
+ if non_default_params.get("stream", False) is True:
+ optional_params["fake_stream"] = True
+
optional_params["json_mode"] = True
- if non_default_params.get("stream", False) is True:
- optional_params["fake_stream"] = True
-
return optional_params
def update_optional_params_with_thinking_tokens(
@@ -862,9 +1038,14 @@ class AmazonConverseConfig(BaseConfig):
Checks 'non_default_params' for 'thinking' and 'max_tokens'
if 'thinking' is enabled and 'max_tokens' is not specified, set 'max_tokens' to the thinking token budget + DEFAULT_MAX_TOKENS
+
+ Also clamps thinking.budget_tokens to the Bedrock minimum (1024) to
+ prevent 400 errors from the Bedrock API.
"""
from litellm.constants import DEFAULT_MAX_TOKENS
+ self._clamp_thinking_budget_tokens(optional_params)
+
is_thinking_enabled = self.is_thinking_enabled(optional_params)
is_max_tokens_in_request = self.is_max_tokens_in_request(non_default_params)
if is_thinking_enabled and not is_max_tokens_in_request:
@@ -886,6 +1067,7 @@ class AmazonConverseConfig(BaseConfig):
ChatCompletionAssistantMessage,
],
block_type: Literal["system"],
+ model: Optional[str] = None,
) -> Optional[SystemContentBlock]:
pass
@@ -899,6 +1081,7 @@ class AmazonConverseConfig(BaseConfig):
ChatCompletionAssistantMessage,
],
block_type: Literal["content_block"],
+ model: Optional[str] = None,
) -> Optional[ContentBlock]:
pass
@@ -911,16 +1094,26 @@ class AmazonConverseConfig(BaseConfig):
ChatCompletionAssistantMessage,
],
block_type: Literal["system", "content_block"],
+ model: Optional[str] = None,
) -> Optional[Union[SystemContentBlock, ContentBlock]]:
- if message_block.get("cache_control", None) is None:
+ cache_control = message_block.get("cache_control", None)
+ if cache_control is None:
return None
+
+ cache_point = CachePointBlock(type="default")
+ if isinstance(cache_control, dict) and "ttl" in cache_control:
+ ttl = cache_control["ttl"]
+ if ttl in ["5m", "1h"] and model is not None:
+ if is_claude_4_5_on_bedrock(model):
+ cache_point["ttl"] = ttl
+
if block_type == "system":
- return SystemContentBlock(cachePoint=CachePointBlock(type="default"))
+ return SystemContentBlock(cachePoint=cache_point)
else:
- return ContentBlock(cachePoint=CachePointBlock(type="default"))
+ return ContentBlock(cachePoint=cache_point)
def _transform_system_message(
- self, messages: List[AllMessageValues]
+ self, messages: List[AllMessageValues], model: Optional[str] = None
) -> Tuple[List[AllMessageValues], List[SystemContentBlock]]:
system_prompt_indices = []
system_content_blocks: List[SystemContentBlock] = []
@@ -932,7 +1125,7 @@ class AmazonConverseConfig(BaseConfig):
SystemContentBlock(text=message["content"])
)
cache_block = self._get_cache_point_block(
- message, block_type="system"
+ message, block_type="system", model=model
)
if cache_block:
system_content_blocks.append(cache_block)
@@ -943,7 +1136,7 @@ class AmazonConverseConfig(BaseConfig):
SystemContentBlock(text=m["text"])
)
cache_block = self._get_cache_point_block(
- m, block_type="system"
+ m, block_type="system", model=model
)
if cache_block:
system_content_blocks.append(cache_block)
@@ -976,7 +1169,7 @@ class AmazonConverseConfig(BaseConfig):
def _prepare_request_params(
self, optional_params: dict, model: str
- ) -> Tuple[dict, dict, dict]:
+ ) -> Tuple[dict, dict, dict, Optional[OutputConfigBlock]]:
"""Prepare and separate request parameters."""
# Filter out exception objects before deepcopy to prevent deepcopy failures
# Exceptions should not be stored in optional_params (this is a defensive fix)
@@ -999,6 +1192,8 @@ class AmazonConverseConfig(BaseConfig):
if request_metadata is not None:
self._validate_request_metadata(request_metadata)
+ output_config: Optional[OutputConfigBlock] = inference_params.pop("outputConfig", None)
+
# keep supported params in 'inference_params', and set all model-specific params in 'additional_request_params'
additional_request_params = {
k: v for k, v in inference_params.items() if k not in total_supported_params
@@ -1023,7 +1218,12 @@ class AmazonConverseConfig(BaseConfig):
additional_request_params
)
- return inference_params, additional_request_params, request_metadata
+ return (
+ inference_params,
+ additional_request_params,
+ request_metadata,
+ output_config,
+ )
def _process_tools_and_beta(
self,
@@ -1041,10 +1241,16 @@ class AmazonConverseConfig(BaseConfig):
user_betas = get_anthropic_beta_from_headers(headers)
anthropic_beta_list.extend(user_betas)
- # Filter out tool search tools - Bedrock Converse API doesn't support them
+ # Separate pre-formatted Bedrock tools (e.g. systemTool from web_search_options)
+ # from OpenAI-format tools that need transformation via _bedrock_tools_pt
filtered_tools = []
+ pre_formatted_tools: List[ToolBlock] = []
if original_tools:
for tool in original_tools:
+ # Already-formatted Bedrock tools (e.g. systemTool for Nova grounding)
+ if "systemTool" in tool:
+ pre_formatted_tools.append(tool)
+ continue
tool_type = tool.get("type", "")
if tool_type in (
"tool_search_tool_regex_20251119",
@@ -1066,7 +1272,50 @@ class AmazonConverseConfig(BaseConfig):
# Add computer use tools and anthropic_beta if needed (only when computer use tools are present)
if computer_use_tools:
- anthropic_beta_list.append("computer-use-2024-10-22")
+ # Determine the correct computer-use beta header based on model
+ # "computer-use-2025-11-24" for Claude Opus 4.6, Claude Opus 4.5
+ # "computer-use-2025-01-24" for Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7
+ # "computer-use-2024-10-22" for older models
+ model_lower = model.lower()
+ if "opus-4.6" in model_lower or "opus_4.6" in model_lower or "opus-4-6" in model_lower or "opus_4_6" in model_lower or "sonnet-4.6" in model_lower or "sonnet_4.6" in model_lower or "sonnet-4-6" in model_lower or "sonnet_4_6" in model_lower:
+ computer_use_header = "computer-use-2025-11-24"
+ elif (
+ "opus-4.5" in model_lower
+ or "opus_4.5" in model_lower
+ or "opus-4-5" in model_lower
+ or "opus_4_5" in model_lower
+ ):
+ computer_use_header = "computer-use-2025-11-24"
+ elif any(
+ pattern in model_lower
+ for pattern in [
+ "sonnet-4.5",
+ "sonnet_4.5",
+ "sonnet-4-5",
+ "sonnet_4_5",
+ "haiku-4.5",
+ "haiku_4.5",
+ "haiku-4-5",
+ "haiku_4_5",
+ "opus-4.1",
+ "opus_4.1",
+ "opus-4-1",
+ "opus_4_1",
+ "sonnet-4",
+ "sonnet_4",
+ "opus-4",
+ "opus_4",
+ "sonnet-3.7",
+ "sonnet_3.7",
+ "sonnet-3-7",
+ "sonnet_3_7",
+ ]
+ ):
+ computer_use_header = "computer-use-2025-01-24"
+ else:
+ computer_use_header = "computer-use-2024-10-22"
+
+ anthropic_beta_list.append(computer_use_header)
# Transform computer use tools to proper Bedrock format
transformed_computer_tools = self._transform_computer_use_tools(
computer_use_tools
@@ -1076,19 +1325,14 @@ class AmazonConverseConfig(BaseConfig):
# No computer use tools, process all tools as regular tools
bedrock_tools = _bedrock_tools_pt(filtered_tools)
+ # Append pre-formatted tools (systemTool etc.) after transformation
+ bedrock_tools.extend(pre_formatted_tools)
+
# Set anthropic_beta in additional_request_params if we have any beta features
# ONLY apply to Anthropic/Claude models - other models (e.g., Qwen, Llama) don't support this field
- # and will error with "unknown variant anthropic_beta" if included
base_model = BedrockModelInfo.get_base_model(model)
if anthropic_beta_list and base_model.startswith("anthropic"):
- # Remove duplicates while preserving order
- unique_betas = []
- seen = set()
- for beta in anthropic_beta_list:
- if beta not in seen:
- unique_betas.append(beta)
- seen.add(beta)
- additional_request_params["anthropic_beta"] = unique_betas
+ additional_request_params["anthropic_beta"] = anthropic_beta_list
return bedrock_tools, anthropic_beta_list
@@ -1140,9 +1384,12 @@ class AmazonConverseConfig(BaseConfig):
)
# Prepare and separate parameters
- inference_params, additional_request_params, request_metadata = self._prepare_request_params(
- optional_params, model
- )
+ (
+ inference_params,
+ additional_request_params,
+ request_metadata,
+ output_config,
+ ) = self._prepare_request_params(optional_params, model)
original_tools = inference_params.pop("tools", [])
@@ -1184,6 +1431,9 @@ class AmazonConverseConfig(BaseConfig):
if request_metadata is not None:
data["requestMetadata"] = request_metadata
+ if output_config is not None:
+ data["outputConfig"] = output_config
+
return data
async def _async_transform_request(
@@ -1194,7 +1444,9 @@ class AmazonConverseConfig(BaseConfig):
litellm_params: dict,
headers: Optional[dict] = None,
) -> RequestObject:
- messages, system_content_blocks = self._transform_system_message(messages)
+ messages, system_content_blocks = self._transform_system_message(
+ messages, model=model
+ )
# Convert last user message to guarded_text if guardrailConfig is present
messages = self._convert_consecutive_user_messages_to_guarded_text(
@@ -1250,7 +1502,9 @@ class AmazonConverseConfig(BaseConfig):
litellm_params: dict,
headers: Optional[dict] = None,
) -> RequestObject:
- messages, system_content_blocks = self._transform_system_message(messages)
+ messages, system_content_blocks = self._transform_system_message(
+ messages, model=model
+ )
# Convert last user message to guarded_text if guardrailConfig is present
messages = self._convert_consecutive_user_messages_to_guarded_text(
@@ -1501,7 +1755,7 @@ class AmazonConverseConfig(BaseConfig):
return content_str, tools, reasoningContentBlocks, citationsContentBlocks
- def _transform_response( # noqa: PLR0915
+ def _transform_response( # noqa: PLR0915
self,
model: str,
response: httpx.Response,
@@ -1595,7 +1849,9 @@ class AmazonConverseConfig(BaseConfig):
provider_specific_fields["citationsContent"] = citationsContentBlocks
if provider_specific_fields:
- chat_completion_message["provider_specific_fields"] = provider_specific_fields
+ chat_completion_message["provider_specific_fields"] = (
+ provider_specific_fields
+ )
if reasoningContentBlocks is not None:
chat_completion_message["reasoning_content"] = (
@@ -1616,8 +1872,6 @@ class AmazonConverseConfig(BaseConfig):
)
json_mode_content_str: Optional[str] = tools[0]["function"].get("arguments")
if json_mode_content_str is not None:
- import json
-
# Bedrock returns the response wrapped in a "properties" object
# We need to extract the actual content from this wrapper
try:
@@ -1636,7 +1890,7 @@ class AmazonConverseConfig(BaseConfig):
pass
chat_completion_message["content"] = json_mode_content_str
- else:
+ elif tools:
chat_completion_message["tool_calls"] = tools
## CALCULATING USAGE - bedrock returns usage in the headers
diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.py
index 77d2a3c0c22..1c58a11eebe 100644
--- a/litellm/llms/bedrock/chat/invoke_handler.py
+++ b/litellm/llms/bedrock/chat/invoke_handler.py
@@ -1532,7 +1532,7 @@ class AWSEventStreamDecoder:
]
] = None
- index = int(chunk_data.get("contentBlockIndex", 0))
+ content_block_index = int(chunk_data.get("contentBlockIndex", 0))
if "start" in chunk_data:
start_obj = ContentBlockStartEvent(**chunk_data["start"])
(
@@ -1548,11 +1548,11 @@ class AWSEventStreamDecoder:
provider_specific_fields,
reasoning_content,
thinking_blocks,
- ) = self._handle_converse_delta_event(delta_obj, index)
+ ) = self._handle_converse_delta_event(delta_obj, content_block_index)
elif (
"contentBlockIndex" in chunk_data
): # stop block, no 'start' or 'delta' object
- tool_use = self._handle_converse_stop_event(index)
+ tool_use = self._handle_converse_stop_event(content_block_index)
elif "stopReason" in chunk_data:
finish_reason = map_finish_reason(chunk_data.get("stopReason", "stop"))
elif "usage" in chunk_data:
@@ -1566,7 +1566,7 @@ class AWSEventStreamDecoder:
choices=[
StreamingChoices(
finish_reason=finish_reason,
- index=index,
+ index=0, # Always 0 - Bedrock never returns multiple choices
delta=Delta(
content=text,
role="assistant",
diff --git a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py
index 53e08229799..dfab81123fd 100644
--- a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py
+++ b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py
@@ -53,13 +53,26 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):
model: str,
drop_params: bool,
) -> dict:
- return AnthropicConfig.map_openai_params(
+ # Force tool-based structured outputs for Bedrock Invoke
+ # (similar to VertexAI fix in #19201)
+ # Bedrock Invoke doesn't support output_format parameter
+ original_model = model
+ if "response_format" in non_default_params:
+ # Use a model name that forces tool-based approach
+ model = "claude-3-sonnet-20240229"
+
+ optional_params = AnthropicConfig.map_openai_params(
self,
non_default_params,
optional_params,
model,
drop_params,
)
+
+ # Restore original model name
+ model = original_model
+
+ return optional_params
def transform_request(
@@ -90,6 +103,8 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):
_anthropic_request.pop("model", None)
_anthropic_request.pop("stream", None)
+ # Bedrock Invoke doesn't support output_format parameter
+ _anthropic_request.pop("output_format", None)
if "anthropic_version" not in _anthropic_request:
_anthropic_request["anthropic_version"] = self.anthropic_version
@@ -117,8 +132,10 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):
if "opus-4" in model.lower() or "opus_4" in model.lower():
beta_set.add("tool-search-tool-2025-10-19")
- if beta_set:
- _anthropic_request["anthropic_beta"] = list(beta_set)
+ # Filter out beta headers that Bedrock Invoke doesn't support
+ # Uses centralized configuration from anthropic_beta_headers_config.json
+ beta_list = list(beta_set)
+ _anthropic_request["anthropic_beta"] = beta_list
return _anthropic_request
diff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.py
index 89b42f5e947..b779c892c67 100644
--- a/litellm/llms/bedrock/common_utils.py
+++ b/litellm/llms/bedrock/common_utils.py
@@ -404,7 +404,7 @@ def extract_model_name_from_bedrock_arn(model: str) -> str:
def strip_bedrock_routing_prefix(model: str) -> str:
"""Strip LiteLLM routing prefixes from model name."""
- for prefix in ["bedrock/", "converse/", "invoke/", "openai/"]:
+ for prefix in ["bedrock/", "converse/", "invoke/", "openai/", "nova-2/", "nova/"]:
if model.startswith(prefix):
model = model.split("/", 1)[1]
return model
@@ -427,7 +427,20 @@ def get_bedrock_base_model(model: str) -> str:
- "us.meta.llama3-2-11b-instruct-v1:0" -> "meta.llama3-2-11b-instruct-v1"
- "bedrock/converse/model" -> "model"
- "anthropic.claude-3-5-sonnet-20241022-v2:0:51k" -> "anthropic.claude-3-5-sonnet-20241022-v2:0"
+ - "bedrock/nova-2/arn:aws:..." -> "amazon.nova-2-custom"
+ - "bedrock/nova/arn:aws:..." -> "amazon.nova-custom"
"""
+ # Detect nova spec prefixes before stripping them
+ stripped = model
+ for rp in ["bedrock/converse/", "bedrock/", "converse/"]:
+ if stripped.startswith(rp):
+ stripped = stripped[len(rp):]
+ break
+ if stripped.startswith("nova-2/"):
+ return "amazon.nova-2-custom"
+ elif stripped.startswith("nova/"):
+ return "amazon.nova-custom"
+
model = strip_bedrock_routing_prefix(model)
model = extract_model_name_from_bedrock_arn(model)
model = strip_bedrock_throughput_suffix(model)
@@ -446,6 +459,37 @@ def get_bedrock_base_model(model: str) -> str:
return model
+def is_claude_4_5_on_bedrock(model: str) -> bool:
+ """
+ Check if the model is a Claude 4.5 model on Bedrock.
+ Claude 4.5 models support prompt caching with '5m' and '1h' TTL on Bedrock.
+ """
+ model_lower = model.lower()
+ claude_4_5_patterns = [
+ "sonnet-4.5",
+ "sonnet_4.5",
+ "sonnet-4-5",
+ "sonnet_4_5",
+ "haiku-4.5",
+ "haiku_4.5",
+ "haiku-4-5",
+ "haiku_4_5",
+ "opus-4.5",
+ "opus_4.5",
+ "opus-4-5",
+ "opus_4_5",
+ "sonnet-4.6",
+ "sonnet_4.6",
+ "sonnet-4-6",
+ "sonnet_4_6",
+ "opus-4.6",
+ "opus_4.6",
+ "opus-4-6",
+ "opus_4_6",
+ ]
+ return any(pattern in model_lower for pattern in claude_4_5_patterns)
+
+
# Import after standalone functions to avoid circular imports
from litellm.llms.bedrock.count_tokens.bedrock_token_counter import BedrockTokenCounter
@@ -571,6 +615,11 @@ class BedrockModelInfo(BaseLLMModelInfo):
if prefix in model:
return route_type
+ # Check for nova spec prefixes (nova/ and nova-2/)
+ _model_after_bedrock = model.replace("bedrock/", "", 1)
+ if _model_after_bedrock.startswith("nova-2/") or _model_after_bedrock.startswith("nova/"):
+ return "converse"
+
base_model = BedrockModelInfo.get_base_model(model)
alt_model = BedrockModelInfo.get_non_litellm_routing_model_name(model=model)
if (
@@ -797,7 +846,7 @@ class BedrockEventStreamDecoderBase:
def get_anthropic_beta_from_headers(headers: dict) -> List[str]:
"""
Extract anthropic-beta header values and convert them to a list.
- Supports comma-separated values from user headers.
+ Supports both JSON array format and comma-separated values from user headers.
Used by both converse and invoke transformations for consistent handling
of anthropic-beta headers that should be passed to AWS Bedrock.
@@ -812,8 +861,27 @@ def get_anthropic_beta_from_headers(headers: dict) -> List[str]:
if not anthropic_beta_header:
return []
- # Split comma-separated values and strip whitespace
- return [beta.strip() for beta in anthropic_beta_header.split(",")]
+ # If it's already a list, return it
+ if isinstance(anthropic_beta_header, list):
+ return anthropic_beta_header
+
+ # Try to parse as JSON array first (e.g., '["interleaved-thinking-2025-05-14", "claude-code-20250219"]')
+ if isinstance(anthropic_beta_header, str):
+ anthropic_beta_header = anthropic_beta_header.strip()
+ if anthropic_beta_header.startswith("[") and anthropic_beta_header.endswith(
+ "]"
+ ):
+ try:
+ parsed = json.loads(anthropic_beta_header)
+ if isinstance(parsed, list):
+ return [str(beta).strip() for beta in parsed]
+ except json.JSONDecodeError:
+ pass # Fall through to comma-separated parsing
+
+ # Fall back to comma-separated values
+ return [beta.strip() for beta in anthropic_beta_header.split(",")]
+
+ return []
class CommonBatchFilesUtils:
diff --git a/litellm/llms/bedrock/cost_calculation.py b/litellm/llms/bedrock/cost_calculation.py
index b20350d7325..ac99d4e36e7 100644
--- a/litellm/llms/bedrock/cost_calculation.py
+++ b/litellm/llms/bedrock/cost_calculation.py
@@ -3,7 +3,7 @@ Helper util for handling bedrock-specific cost calculation
- e.g.: prompt caching
"""
-from typing import TYPE_CHECKING, Tuple
+from typing import TYPE_CHECKING, Optional, Tuple
from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token
@@ -11,12 +11,17 @@ if TYPE_CHECKING:
from litellm.types.utils import Usage
-def cost_per_token(model: str, usage: "Usage") -> Tuple[float, float]:
+def cost_per_token(
+ model: str, usage: "Usage", service_tier: Optional[str] = None
+) -> Tuple[float, float]:
"""
Calculates the cost per token for a given model, prompt tokens, and completion tokens.
Follows the same logic as Anthropic's cost per token calculation.
"""
return generic_cost_per_token(
- model=model, usage=usage, custom_llm_provider="bedrock"
- )
\ No newline at end of file
+ model=model,
+ usage=usage,
+ custom_llm_provider="bedrock",
+ service_tier=service_tier,
+ )
diff --git a/litellm/llms/bedrock/embed/cohere_transformation.py b/litellm/llms/bedrock/embed/cohere_transformation.py
index 490cd71b793..d00cb74aae0 100644
--- a/litellm/llms/bedrock/embed/cohere_transformation.py
+++ b/litellm/llms/bedrock/embed/cohere_transformation.py
@@ -15,7 +15,7 @@ class BedrockCohereEmbeddingConfig:
pass
def get_supported_openai_params(self) -> List[str]:
- return ["encoding_format"]
+ return ["encoding_format", "dimensions"]
def map_openai_params(
self, non_default_params: dict, optional_params: dict
@@ -23,6 +23,8 @@ class BedrockCohereEmbeddingConfig:
for k, v in non_default_params.items():
if k == "encoding_format":
optional_params["embedding_types"] = v
+ elif k == "dimensions":
+ optional_params["output_dimension"] = v
return optional_params
def _is_v3_model(self, model: str) -> bool:
diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
index a7065caece2..03885ff2080 100644
--- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
+++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
@@ -23,7 +23,10 @@ from litellm.llms.bedrock.chat.invoke_handler import AWSEventStreamDecoder
from litellm.llms.bedrock.chat.invoke_transformations.base_invoke_transformation import (
AmazonInvokeConfig,
)
-from litellm.llms.bedrock.common_utils import get_anthropic_beta_from_headers
+from litellm.llms.bedrock.common_utils import (
+ get_anthropic_beta_from_headers,
+ is_claude_4_5_on_bedrock,
+)
from litellm.types.llms.anthropic import ANTHROPIC_TOOL_SEARCH_BETA_HEADER
from litellm.types.llms.openai import AllMessageValues
from litellm.types.router import GenericLiteLLMParams
@@ -52,9 +55,6 @@ class AmazonAnthropicClaudeMessagesConfig(
# Beta header patterns that are not supported by Bedrock Invoke API
# These will be filtered out to prevent 400 "invalid beta flag" errors
- UNSUPPORTED_BEDROCK_INVOKE_BETA_PATTERNS = [
- "advanced-tool-use", # Bedrock Invoke doesn't support advanced-tool-use beta headers
- ]
def __init__(self, **kwargs):
BaseAnthropicMessagesConfig.__init__(self, **kwargs)
@@ -115,15 +115,22 @@ class AmazonAnthropicClaudeMessagesConfig(
)
def _remove_ttl_from_cache_control(
- self, anthropic_messages_request: Dict
+ self, anthropic_messages_request: Dict, model: Optional[str] = None
) -> None:
"""
Remove `ttl` field from cache_control in messages.
Bedrock doesn't support the ttl field in cache_control.
+ Update: Bedock supports `5m` and `1h` for Claude 4.5 models.
+
Args:
anthropic_messages_request: The request dictionary to modify in-place
+ model: The model name to check if it supports ttl
"""
+ is_claude_4_5 = False
+ if model:
+ is_claude_4_5 = self._is_claude_4_5_on_bedrock(model)
+
if "messages" in anthropic_messages_request:
for message in anthropic_messages_request["messages"]:
if isinstance(message, dict) and "content" in message:
@@ -132,7 +139,14 @@ class AmazonAnthropicClaudeMessagesConfig(
for item in content:
if isinstance(item, dict) and "cache_control" in item:
cache_control = item["cache_control"]
- if isinstance(cache_control, dict) and "ttl" in cache_control:
+ if (
+ isinstance(cache_control, dict)
+ and "ttl" in cache_control
+ ):
+ ttl = cache_control["ttl"]
+ if is_claude_4_5 and ttl in ["5m", "1h"]:
+ continue
+
cache_control.pop("ttl", None)
def _supports_extended_thinking_on_bedrock(self, model: str) -> bool:
@@ -154,55 +168,105 @@ class AmazonAnthropicClaudeMessagesConfig(
# Supported models on Bedrock for extended thinking
supported_patterns = [
- "opus-4.5", "opus_4.5", "opus-4-5", "opus_4_5", # Opus 4.5
- "opus-4.1", "opus_4.1", "opus-4-1", "opus_4_1", # Opus 4.1
- "opus-4", "opus_4", # Opus 4
- "sonnet-4", "sonnet_4", # Sonnet 4
+ "opus-4.5",
+ "opus_4.5",
+ "opus-4-5",
+ "opus_4_5", # Opus 4.5
+ "opus-4.1",
+ "opus_4.1",
+ "opus-4-1",
+ "opus_4_1", # Opus 4.1
+ "opus-4",
+ "opus_4", # Opus 4
+ "sonnet-4",
+ "sonnet_4", # Sonnet 4
+ "sonnet-4.6",
+ "sonnet_4.6",
+ "sonnet-4-6",
+ "sonnet_4_6",
+ "opus-4.6",
+ "opus_4.6",
+ "opus-4-6",
+ "opus_4_6",
]
return any(pattern in model_lower for pattern in supported_patterns)
- def _filter_unsupported_beta_headers_for_bedrock(
- self, model: str, beta_set: set
- ) -> None:
+ def _is_claude_opus_4_5(self, model: str) -> bool:
"""
- Remove beta headers that are not supported on Bedrock for the given model.
-
- Extended thinking beta headers are only supported on specific Claude 4+ models.
- Advanced tool use headers are not supported on Bedrock Invoke API.
- This prevents 400 "invalid beta flag" errors on Bedrock.
-
- Note: Bedrock Invoke API fails with a 400 error when unsupported beta headers
- are sent, returning: {"message":"invalid beta flag"}
+ Check if the model is Claude Opus 4.5.
Args:
model: The model name
- beta_set: The set of beta headers to filter in-place
+
+ Returns:
+ True if the model is Claude Opus 4.5
"""
- beta_headers_to_remove = set()
-
- # 1. Filter out beta headers that are universally unsupported on Bedrock Invoke
- for beta in beta_set:
- for unsupported_pattern in self.UNSUPPORTED_BEDROCK_INVOKE_BETA_PATTERNS:
- if unsupported_pattern in beta.lower():
- beta_headers_to_remove.add(beta)
- break
-
- # 2. Filter out extended thinking headers for models that don't support them
- extended_thinking_patterns = [
- "extended-thinking",
- "interleaved-thinking",
+ model_lower = model.lower()
+ opus_4_5_patterns = [
+ "opus-4.5",
+ "opus_4.5",
+ "opus-4-5",
+ "opus_4_5",
]
- if not self._supports_extended_thinking_on_bedrock(model):
- for beta in beta_set:
- for pattern in extended_thinking_patterns:
- if pattern in beta.lower():
- beta_headers_to_remove.add(beta)
- break
+ return any(pattern in model_lower for pattern in opus_4_5_patterns)
- # Remove all filtered headers
- for beta in beta_headers_to_remove:
- beta_set.discard(beta)
+ def _is_claude_4_5_on_bedrock(self, model: str) -> bool:
+ """
+ Check if the model is Claude 4.5 on Bedrock.
+
+ Claude Sonnet 4.5, Haiku 4.5, and Opus 4.5 support 1-hour prompt caching.
+
+ Args:
+ model: The model name
+
+ Returns:
+ True if the model is Claude 4.5
+ """
+ return is_claude_4_5_on_bedrock(model)
+
+ def _supports_tool_search_on_bedrock(self, model: str) -> bool:
+ """
+ Check if the model supports tool search on Bedrock.
+
+ On Amazon Bedrock, server-side tool search is supported on Claude Opus 4.5
+ and Claude Sonnet 4.5 with the tool-search-tool-2025-10-19 beta header.
+
+ Ref: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool
+
+ Args:
+ model: The model name
+
+ Returns:
+ True if the model supports tool search on Bedrock
+ """
+ model_lower = model.lower()
+
+ # Supported models for tool search on Bedrock
+ supported_patterns = [
+ # Opus 4.5
+ "opus-4.5",
+ "opus_4.5",
+ "opus-4-5",
+ "opus_4_5",
+ # Sonnet 4.5
+ "sonnet-4.5",
+ "sonnet_4.5",
+ "sonnet-4-5",
+ "sonnet_4_5",
+ # Opus 4.6
+ "opus-4.6",
+ "opus_4.6",
+ "opus-4-6",
+ "opus_4_6",
+ #sonnet 4.6
+ "sonnet-4.6",
+ "sonnet_4.6",
+ "sonnet-4-6",
+ "sonnet_4_6",
+ ]
+
+ return any(pattern in model_lower for pattern in supported_patterns)
def _get_tool_search_beta_header_for_bedrock(
self,
@@ -230,9 +294,11 @@ class AmazonAnthropicClaudeMessagesConfig(
input_examples_used: Whether input examples are used
beta_set: The set of beta headers to modify in-place
"""
- if tool_search_used and not (programmatic_tool_calling_used or input_examples_used):
+ if tool_search_used and not (
+ programmatic_tool_calling_used or input_examples_used
+ ):
beta_set.discard(ANTHROPIC_TOOL_SEARCH_BETA_HEADER)
- if "opus-4" in model.lower() or "opus_4" in model.lower():
+ if self._supports_tool_search_on_bedrock(model):
beta_set.add("tool-search-tool-2025-10-19")
def _convert_output_format_to_inline_schema(
@@ -242,13 +308,13 @@ class AmazonAnthropicClaudeMessagesConfig(
) -> None:
"""
Convert Anthropic output_format to inline schema in message content.
-
+
Bedrock Invoke doesn't support the output_format parameter, so we embed
the schema directly into the user message content as text instructions.
-
+
This approach adds the schema to the last user message, instructing the model
to respond in the specified JSON format.
-
+
Args:
output_format: The output_format dict with 'type' and 'schema'
anthropic_messages_request: The request dict to modify in-place
@@ -256,40 +322,37 @@ class AmazonAnthropicClaudeMessagesConfig(
Ref: https://aws.amazon.com/blogs/machine-learning/structured-data-response-with-amazon-bedrock-prompt-engineering-and-tool-use/
"""
import json
-
+
# Extract schema from output_format
schema = output_format.get("schema")
if not schema:
return
-
+
# Get messages from the request
messages = anthropic_messages_request.get("messages", [])
if not messages:
return
-
+
# Find the last user message
last_user_message_idx = None
for idx in range(len(messages) - 1, -1, -1):
if messages[idx].get("role") == "user":
last_user_message_idx = idx
break
-
+
if last_user_message_idx is None:
return
-
+
last_user_message = messages[last_user_message_idx]
content = last_user_message.get("content", [])
-
+
# Ensure content is a list
if isinstance(content, str):
content = [{"type": "text", "text": content}]
last_user_message["content"] = content
-
+
# Add schema as text content to the message
- schema_text = {
- "type": "text",
- "text": json.dumps(schema)
- }
+ schema_text = {"type": "text", "text": json.dumps(schema)}
content.append(schema_text)
def transform_anthropic_messages_request(
@@ -314,9 +377,9 @@ class AmazonAnthropicClaudeMessagesConfig(
# 1. anthropic_version is required for all claude models
if "anthropic_version" not in anthropic_messages_request:
- anthropic_messages_request["anthropic_version"] = (
- self.DEFAULT_BEDROCK_ANTHROPIC_API_VERSION
- )
+ anthropic_messages_request[
+ "anthropic_version"
+ ] = self.DEFAULT_BEDROCK_ANTHROPIC_API_VERSION
# 2. `stream` is not allowed in request body for bedrock invoke
if "stream" in anthropic_messages_request:
@@ -326,8 +389,10 @@ class AmazonAnthropicClaudeMessagesConfig(
if "model" in anthropic_messages_request:
anthropic_messages_request.pop("model", None)
- # 4. Remove `ttl` field from cache_control in messages (Bedrock doesn't support it)
- self._remove_ttl_from_cache_control(anthropic_messages_request)
+ # 4. Remove `ttl` field from cache_control in messages (Bedrock doesn't support it for older models)
+ self._remove_ttl_from_cache_control(
+ anthropic_messages_request=anthropic_messages_request, model=model
+ )
# 5. Convert `output_format` to inline schema (Bedrock invoke doesn't support output_format)
output_format = anthropic_messages_request.pop("output_format", None)
@@ -336,14 +401,14 @@ class AmazonAnthropicClaudeMessagesConfig(
output_format=output_format,
anthropic_messages_request=anthropic_messages_request,
)
-
+
# 6. AUTO-INJECT beta headers based on features used
anthropic_model_info = AnthropicModelInfo()
tools = anthropic_messages_optional_request_params.get("tools")
messages_typed = cast(List[AllMessageValues], messages)
tool_search_used = anthropic_model_info.is_tool_search_used(tools)
- programmatic_tool_calling_used = anthropic_model_info.is_programmatic_tool_calling_used(
- tools
+ programmatic_tool_calling_used = (
+ anthropic_model_info.is_programmatic_tool_calling_used(tools)
)
input_examples_used = anthropic_model_info.is_input_examples_used(tools)
@@ -368,16 +433,12 @@ class AmazonAnthropicClaudeMessagesConfig(
beta_set=beta_set,
)
- # Filter out unsupported beta headers for Bedrock (e.g., advanced-tool-use, extended-thinking on non-Opus/Sonnet 4 models)
- self._filter_unsupported_beta_headers_for_bedrock(
- model=model,
- beta_set=beta_set,
- )
-
+ if "tool-search-tool-2025-10-19" in beta_set:
+ beta_set.add("tool-examples-2025-10-29")
+
if beta_set:
anthropic_messages_request["anthropic_beta"] = list(beta_set)
-
-
+
return anthropic_messages_request
def get_async_streaming_response_iterator(
@@ -395,7 +456,7 @@ class AmazonAnthropicClaudeMessagesConfig(
)
# Convert decoded Bedrock events to Server-Sent Events expected by Anthropic clients.
return self.bedrock_sse_wrapper(
- completion_stream=completion_stream,
+ completion_stream=completion_stream,
litellm_logging_obj=litellm_logging_obj,
request_body=request_body,
)
@@ -414,14 +475,14 @@ class AmazonAnthropicClaudeMessagesConfig(
from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (
BaseAnthropicMessagesStreamingIterator,
)
+
handler = BaseAnthropicMessagesStreamingIterator(
litellm_logging_obj=litellm_logging_obj,
request_body=request_body,
)
-
+
async for chunk in handler.async_sse_wrapper(completion_stream):
yield chunk
-
class AmazonAnthropicClaudeMessagesStreamDecoder(AWSEventStreamDecoder):
diff --git a/litellm/llms/bedrock/realtime/handler.py b/litellm/llms/bedrock/realtime/handler.py
new file mode 100644
index 00000000000..9b6a80f4a2f
--- /dev/null
+++ b/litellm/llms/bedrock/realtime/handler.py
@@ -0,0 +1,307 @@
+"""
+This file contains the handler for AWS Bedrock Nova Sonic realtime API.
+
+This uses aws_sdk_bedrock_runtime for bidirectional streaming with Nova Sonic.
+"""
+
+import asyncio
+import json
+from typing import Any, Optional
+
+from litellm._logging import verbose_proxy_logger
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
+
+from ..base_aws_llm import BaseAWSLLM
+from .transformation import BedrockRealtimeConfig
+
+
+class BedrockRealtime(BaseAWSLLM):
+ """Handler for Bedrock Nova Sonic realtime speech-to-speech API."""
+
+ def __init__(self):
+ super().__init__()
+
+ async def async_realtime(
+ self,
+ model: str,
+ websocket: Any,
+ logging_obj: LiteLLMLogging,
+ api_base: Optional[str] = None,
+ api_key: Optional[str] = None,
+ timeout: Optional[float] = None,
+ aws_region_name: Optional[str] = None,
+ aws_access_key_id: Optional[str] = None,
+ aws_secret_access_key: Optional[str] = None,
+ aws_session_token: Optional[str] = None,
+ aws_role_name: Optional[str] = None,
+ aws_session_name: Optional[str] = None,
+ aws_profile_name: Optional[str] = None,
+ aws_web_identity_token: Optional[str] = None,
+ aws_sts_endpoint: Optional[str] = None,
+ aws_bedrock_runtime_endpoint: Optional[str] = None,
+ aws_external_id: Optional[str] = None,
+ **kwargs,
+ ):
+ """
+ Establish bidirectional streaming connection with Bedrock Nova Sonic.
+
+ Args:
+ model: Model ID (e.g., 'amazon.nova-sonic-v1:0')
+ websocket: Client WebSocket connection
+ logging_obj: LiteLLM logging object
+ aws_region_name: AWS region
+ Various AWS authentication parameters
+ """
+ try:
+ from aws_sdk_bedrock_runtime.client import (
+ BedrockRuntimeClient,
+ InvokeModelWithBidirectionalStreamOperationInput,
+ )
+ from aws_sdk_bedrock_runtime.config import Config
+ from smithy_aws_core.identity.environment import (
+ EnvironmentCredentialsResolver,
+ )
+ except ImportError:
+ raise ImportError(
+ "Missing aws_sdk_bedrock_runtime. Install with: pip install aws-sdk-bedrock-runtime"
+ )
+
+ # Get AWS region
+ if aws_region_name is None:
+ optional_params = {
+ "aws_region_name": aws_region_name,
+ }
+ aws_region_name = self._get_aws_region_name(optional_params, model)
+
+ # Get endpoint URL
+ if api_base is not None:
+ endpoint_uri = api_base
+ elif aws_bedrock_runtime_endpoint is not None:
+ endpoint_uri = aws_bedrock_runtime_endpoint
+ else:
+ endpoint_uri = f"https://bedrock-runtime.{aws_region_name}.amazonaws.com"
+
+ verbose_proxy_logger.debug(
+ f"Bedrock Realtime: Connecting to {endpoint_uri} with model {model}"
+ )
+
+ # Initialize Bedrock client with aws_sdk_bedrock_runtime
+ config = Config(
+ endpoint_uri=endpoint_uri,
+ region=aws_region_name,
+ aws_credentials_identity_resolver=EnvironmentCredentialsResolver(),
+ )
+ bedrock_client = BedrockRuntimeClient(config=config)
+
+ transformation_config = BedrockRealtimeConfig()
+
+ try:
+ # Initialize the bidirectional stream
+ bedrock_stream = await bedrock_client.invoke_model_with_bidirectional_stream(
+ InvokeModelWithBidirectionalStreamOperationInput(model_id=model)
+ )
+
+ verbose_proxy_logger.debug(
+ "Bedrock Realtime: Bidirectional stream established"
+ )
+
+ # Track state for transformation
+ session_state = {
+ "current_output_item_id": None,
+ "current_response_id": None,
+ "current_conversation_id": None,
+ "current_delta_chunks": None,
+ "current_item_chunks": None,
+ "current_delta_type": None,
+ "session_configuration_request": None,
+ }
+
+ # Create tasks for bidirectional forwarding
+ client_to_bedrock_task = asyncio.create_task(
+ self._forward_client_to_bedrock(
+ websocket,
+ bedrock_stream,
+ transformation_config,
+ model,
+ session_state,
+ )
+ )
+
+ bedrock_to_client_task = asyncio.create_task(
+ self._forward_bedrock_to_client(
+ bedrock_stream,
+ websocket,
+ transformation_config,
+ model,
+ logging_obj,
+ session_state,
+ )
+ )
+
+ # Wait for both tasks to complete
+ await asyncio.gather(
+ client_to_bedrock_task,
+ bedrock_to_client_task,
+ return_exceptions=True,
+ )
+
+ except Exception as e:
+ verbose_proxy_logger.exception(
+ f"Error in BedrockRealtime.async_realtime: {e}"
+ )
+ try:
+ await websocket.close(code=1011, reason=f"Internal error: {str(e)}")
+ except Exception:
+ pass
+ raise
+
+ async def _forward_client_to_bedrock(
+ self,
+ client_ws: Any,
+ bedrock_stream: Any,
+ transformation_config: BedrockRealtimeConfig,
+ model: str,
+ session_state: dict,
+ ):
+ """Forward messages from client WebSocket to Bedrock stream."""
+ try:
+ from aws_sdk_bedrock_runtime.models import (
+ BidirectionalInputPayloadPart,
+ InvokeModelWithBidirectionalStreamInputChunk,
+ )
+
+ while True:
+ # Receive message from client
+ message = await client_ws.receive_text()
+ verbose_proxy_logger.debug(
+ f"Bedrock Realtime: Received from client: {message[:200]}"
+ )
+
+ # Transform OpenAI format to Bedrock format
+ transformed_messages = transformation_config.transform_realtime_request(
+ message=message,
+ model=model,
+ session_configuration_request=session_state.get(
+ "session_configuration_request"
+ ),
+ )
+
+ # Send transformed messages to Bedrock
+ for bedrock_message in transformed_messages:
+ event = InvokeModelWithBidirectionalStreamInputChunk(
+ value=BidirectionalInputPayloadPart(
+ bytes_=bedrock_message.encode("utf-8")
+ )
+ )
+ await bedrock_stream.input_stream.send(event)
+ verbose_proxy_logger.debug(
+ f"Bedrock Realtime: Sent to Bedrock: {bedrock_message[:200]}"
+ )
+
+ except Exception as e:
+ verbose_proxy_logger.debug(
+ f"Client to Bedrock forwarding ended: {e}", exc_info=True
+ )
+ # Close the Bedrock stream input
+ try:
+ await bedrock_stream.input_stream.close()
+ except Exception:
+ pass
+
+ async def _forward_bedrock_to_client(
+ self,
+ bedrock_stream: Any,
+ client_ws: Any,
+ transformation_config: BedrockRealtimeConfig,
+ model: str,
+ logging_obj: LiteLLMLogging,
+ session_state: dict,
+ ):
+ """Forward messages from Bedrock stream to client WebSocket."""
+ try:
+ while True:
+ # Receive from Bedrock
+ output = await bedrock_stream.await_output()
+ result = await output[1].receive()
+
+ if result.value and result.value.bytes_:
+ bedrock_response = result.value.bytes_.decode("utf-8")
+ verbose_proxy_logger.debug(
+ f"Bedrock Realtime: Received from Bedrock: {bedrock_response[:200]}"
+ )
+
+ # Transform Bedrock format to OpenAI format
+ from litellm.types.realtime import RealtimeResponseTransformInput
+
+ realtime_response_transform_input: RealtimeResponseTransformInput = {
+ "current_output_item_id": session_state.get(
+ "current_output_item_id"
+ ),
+ "current_response_id": session_state.get("current_response_id"),
+ "current_conversation_id": session_state.get(
+ "current_conversation_id"
+ ),
+ "current_delta_chunks": session_state.get(
+ "current_delta_chunks"
+ ),
+ "current_item_chunks": session_state.get("current_item_chunks"),
+ "current_delta_type": session_state.get("current_delta_type"),
+ "session_configuration_request": session_state.get(
+ "session_configuration_request"
+ ),
+ }
+
+ transformed_response = (
+ transformation_config.transform_realtime_response(
+ message=bedrock_response,
+ model=model,
+ logging_obj=logging_obj,
+ realtime_response_transform_input=realtime_response_transform_input,
+ )
+ )
+
+ # Update session state
+ session_state.update(
+ {
+ "current_output_item_id": transformed_response.get(
+ "current_output_item_id"
+ ),
+ "current_response_id": transformed_response.get(
+ "current_response_id"
+ ),
+ "current_conversation_id": transformed_response.get(
+ "current_conversation_id"
+ ),
+ "current_delta_chunks": transformed_response.get(
+ "current_delta_chunks"
+ ),
+ "current_item_chunks": transformed_response.get(
+ "current_item_chunks"
+ ),
+ "current_delta_type": transformed_response.get(
+ "current_delta_type"
+ ),
+ "session_configuration_request": transformed_response.get(
+ "session_configuration_request"
+ ),
+ }
+ )
+
+ # Send transformed messages to client
+ openai_messages = transformed_response.get("response", [])
+ for openai_message in openai_messages:
+ message_json = json.dumps(openai_message)
+ await client_ws.send_text(message_json)
+ verbose_proxy_logger.debug(
+ f"Bedrock Realtime: Sent to client: {message_json[:200]}"
+ )
+
+ except Exception as e:
+ verbose_proxy_logger.debug(
+ f"Bedrock to client forwarding ended: {e}", exc_info=True
+ )
+ # Close the client WebSocket
+ try:
+ await client_ws.close()
+ except Exception:
+ pass
diff --git a/litellm/llms/bedrock/realtime/transformation.py b/litellm/llms/bedrock/realtime/transformation.py
new file mode 100644
index 00000000000..1dde1b47fe3
--- /dev/null
+++ b/litellm/llms/bedrock/realtime/transformation.py
@@ -0,0 +1,1156 @@
+"""
+This file contains the transformation logic for Bedrock Nova Sonic realtime API.
+
+Transforms between OpenAI Realtime API format and Bedrock Nova Sonic format.
+"""
+
+import json
+import uuid as uuid_lib
+from typing import Any, List, Optional, Union
+
+from litellm._logging import verbose_logger
+from litellm._uuid import uuid
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfig
+from litellm.types.llms.openai import (
+ OpenAIRealtimeContentPartDone,
+ OpenAIRealtimeDoneEvent,
+ OpenAIRealtimeEvents,
+ OpenAIRealtimeOutputItemDone,
+ OpenAIRealtimeResponseAudioDone,
+ OpenAIRealtimeResponseContentPartAdded,
+ OpenAIRealtimeResponseDelta,
+ OpenAIRealtimeResponseDoneObject,
+ OpenAIRealtimeResponseTextDone,
+ OpenAIRealtimeStreamResponseBaseObject,
+ OpenAIRealtimeStreamResponseOutputItemAdded,
+ OpenAIRealtimeStreamSession,
+ OpenAIRealtimeStreamSessionEvents,
+)
+from litellm.types.realtime import (
+ ALL_DELTA_TYPES,
+ RealtimeResponseTransformInput,
+ RealtimeResponseTypedDict,
+)
+from litellm.utils import get_empty_usage
+
+
+class BedrockRealtimeConfig(BaseRealtimeConfig):
+ """Configuration for Bedrock Nova Sonic realtime transformations."""
+
+ def __init__(self):
+ # Track session state
+ self.prompt_name = str(uuid_lib.uuid4())
+ self.content_name = str(uuid_lib.uuid4())
+ self.audio_content_name = str(uuid_lib.uuid4())
+
+ # Default configuration values
+ # Inference configuration
+ self.max_tokens = 1024
+ self.top_p = 0.9
+ self.temperature = 0.7
+
+ # Audio output configuration
+ self.output_sample_rate_hertz = 24000
+ self.output_sample_size_bits = 16
+ self.output_channel_count = 1
+ self.voice_id = "matthew"
+ self.output_encoding = "base64"
+ self.output_audio_type = "SPEECH"
+ self.output_media_type = "audio/lpcm"
+
+ # Audio input configuration
+ self.input_sample_rate_hertz = 16000
+ self.input_sample_size_bits = 16
+ self.input_channel_count = 1
+ self.input_encoding = "base64"
+ self.input_audio_type = "SPEECH"
+ self.input_media_type = "audio/lpcm"
+
+ # Text configuration
+ self.text_media_type = "text/plain"
+
+ def validate_environment(
+ self, headers: dict, model: str, api_key: Optional[str] = None
+ ) -> dict:
+ """Validate environment - no special validation needed for Bedrock."""
+ return headers
+
+ def get_complete_url(
+ self, api_base: Optional[str], model: str, api_key: Optional[str] = None
+ ) -> str:
+ """Get complete URL - handled by aws_sdk_bedrock_runtime."""
+ return api_base or ""
+
+ def requires_session_configuration(self) -> bool:
+ """Bedrock requires session configuration."""
+ return True
+
+ def session_configuration_request(self, model: str, tools: Optional[List[dict]] = None) -> str:
+ """
+ Create initial session configuration for Bedrock Nova Sonic.
+
+ Args:
+ model: Model ID
+ tools: Optional list of tool definitions
+
+ Returns JSON string with session start and prompt start events.
+ """
+ session_start = {
+ "event": {
+ "sessionStart": {
+ "inferenceConfiguration": {
+ "maxTokens": self.max_tokens,
+ "topP": self.top_p,
+ "temperature": self.temperature,
+ }
+ }
+ }
+ }
+
+ prompt_start_config = {
+ "promptName": self.prompt_name,
+ "textOutputConfiguration": {"mediaType": self.text_media_type},
+ "audioOutputConfiguration": {
+ "mediaType": self.output_media_type,
+ "sampleRateHertz": self.output_sample_rate_hertz,
+ "sampleSizeBits": self.output_sample_size_bits,
+ "channelCount": self.output_channel_count,
+ "voiceId": self.voice_id,
+ "encoding": self.output_encoding,
+ "audioType": self.output_audio_type,
+ },
+ }
+
+ # Add tool configuration if tools are provided
+ if tools:
+ prompt_start_config["toolUseOutputConfiguration"] = {
+ "mediaType": "application/json"
+ }
+ prompt_start_config["toolConfiguration"] = {
+ "tools": self._transform_tools_to_bedrock_format(tools)
+ }
+
+ prompt_start = {"event": {"promptStart": prompt_start_config}}
+
+ # Return as a marker that we've sent the configuration
+ return json.dumps(
+ {"session_start": session_start, "prompt_start": prompt_start}
+ )
+
+ def _transform_tools_to_bedrock_format(self, tools: List[dict]) -> List[dict]:
+ """
+ Transform OpenAI tool format to Bedrock tool format.
+
+ Args:
+ tools: List of OpenAI format tools
+
+ Returns:
+ List of Bedrock format tools
+ """
+ bedrock_tools = []
+ for tool in tools:
+ if tool.get("type") == "function":
+ function = tool.get("function", {})
+ bedrock_tool = {
+ "toolSpec": {
+ "name": function.get("name", ""),
+ "description": function.get("description", ""),
+ "inputSchema": {
+ "json": json.dumps(function.get("parameters", {}))
+ }
+ }
+ }
+ bedrock_tools.append(bedrock_tool)
+ return bedrock_tools
+
+ def _map_audio_format_to_sample_rate(self, audio_format: str, is_output: bool = True) -> int:
+ """
+ Map OpenAI audio format to sample rate.
+
+ Args:
+ audio_format: OpenAI audio format (pcm16, g711_ulaw, g711_alaw)
+ is_output: Whether this is for output (True) or input (False)
+
+ Returns:
+ Sample rate in Hz
+ """
+ # OpenAI uses 24kHz for output and can vary for input
+ # Bedrock Nova Sonic uses 24kHz for output and 16kHz for input by default
+ if audio_format == "pcm16":
+ return 24000 if is_output else 16000
+ elif audio_format in ["g711_ulaw", "g711_alaw"]:
+ return 8000 # G.711 typically uses 8kHz
+ return 24000 if is_output else 16000
+
+ def transform_session_update_event(self, json_message: dict) -> List[str]:
+ """
+ Transform session.update event to Bedrock session configuration.
+
+ Args:
+ json_message: OpenAI session.update message
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ verbose_logger.debug("Handling session.update")
+ messages: List[str] = []
+
+ session_config = json_message.get("session", {})
+
+ # Update inference configuration from session if provided
+ if "max_response_output_tokens" in session_config:
+ self.max_tokens = session_config["max_response_output_tokens"]
+ if "temperature" in session_config:
+ self.temperature = session_config["temperature"]
+
+ # Update audio output configuration from session if provided
+ if "voice" in session_config:
+ self.voice_id = session_config["voice"]
+ if "output_audio_format" in session_config:
+ output_format = session_config["output_audio_format"]
+ self.output_sample_rate_hertz = self._map_audio_format_to_sample_rate(
+ output_format, is_output=True
+ )
+
+ # Update audio input configuration from session if provided
+ if "input_audio_format" in session_config:
+ input_format = session_config["input_audio_format"]
+ self.input_sample_rate_hertz = self._map_audio_format_to_sample_rate(
+ input_format, is_output=False
+ )
+
+ # Allow direct override of sample rates if provided (custom extension)
+ if "output_sample_rate_hertz" in session_config:
+ self.output_sample_rate_hertz = session_config["output_sample_rate_hertz"]
+ if "input_sample_rate_hertz" in session_config:
+ self.input_sample_rate_hertz = session_config["input_sample_rate_hertz"]
+
+ # Send session start
+ session_start = {
+ "event": {
+ "sessionStart": {
+ "inferenceConfiguration": {
+ "maxTokens": self.max_tokens,
+ "topP": self.top_p,
+ "temperature": self.temperature,
+ }
+ }
+ }
+ }
+ messages.append(json.dumps(session_start))
+
+ # Send prompt start
+ prompt_start_config = {
+ "promptName": self.prompt_name,
+ "textOutputConfiguration": {"mediaType": self.text_media_type},
+ "audioOutputConfiguration": {
+ "mediaType": self.output_media_type,
+ "sampleRateHertz": self.output_sample_rate_hertz,
+ "sampleSizeBits": self.output_sample_size_bits,
+ "channelCount": self.output_channel_count,
+ "voiceId": self.voice_id,
+ "encoding": self.output_encoding,
+ "audioType": self.output_audio_type,
+ },
+ }
+
+ # Add tool configuration if tools are provided
+ tools = session_config.get("tools")
+ if tools:
+ prompt_start_config["toolUseOutputConfiguration"] = {
+ "mediaType": "application/json"
+ }
+ prompt_start_config["toolConfiguration"] = {
+ "tools": self._transform_tools_to_bedrock_format(tools)
+ }
+
+ prompt_start = {"event": {"promptStart": prompt_start_config}}
+ messages.append(json.dumps(prompt_start))
+
+ # Send system prompt if provided
+ instructions = session_config.get("instructions")
+ if instructions:
+ text_content_name = str(uuid_lib.uuid4())
+
+ # Content start
+ text_content_start = {
+ "event": {
+ "contentStart": {
+ "promptName": self.prompt_name,
+ "contentName": text_content_name,
+ "type": "TEXT",
+ "interactive": False,
+ "role": "SYSTEM",
+ "textInputConfiguration": {"mediaType": self.text_media_type},
+ }
+ }
+ }
+ messages.append(json.dumps(text_content_start))
+
+ # Text input
+ text_input = {
+ "event": {
+ "textInput": {
+ "promptName": self.prompt_name,
+ "contentName": text_content_name,
+ "content": instructions,
+ }
+ }
+ }
+ messages.append(json.dumps(text_input))
+
+ # Content end
+ text_content_end = {
+ "event": {
+ "contentEnd": {
+ "promptName": self.prompt_name,
+ "contentName": text_content_name,
+ }
+ }
+ }
+ messages.append(json.dumps(text_content_end))
+
+ return messages
+
+ def transform_input_audio_buffer_append_event(self, json_message: dict) -> List[str]:
+ """
+ Transform input_audio_buffer.append event to Bedrock audio input.
+
+ Args:
+ json_message: OpenAI input_audio_buffer.append message
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ verbose_logger.debug("Handling input_audio_buffer.append")
+ messages: List[str] = []
+
+ # Check if we need to start audio content
+ if not hasattr(self, "_audio_content_started"):
+ audio_content_start = {
+ "event": {
+ "contentStart": {
+ "promptName": self.prompt_name,
+ "contentName": self.audio_content_name,
+ "type": "AUDIO",
+ "interactive": True,
+ "role": "USER",
+ "audioInputConfiguration": {
+ "mediaType": self.input_media_type,
+ "sampleRateHertz": self.input_sample_rate_hertz,
+ "sampleSizeBits": self.input_sample_size_bits,
+ "channelCount": self.input_channel_count,
+ "audioType": self.input_audio_type,
+ "encoding": self.input_encoding,
+ },
+ }
+ }
+ }
+ messages.append(json.dumps(audio_content_start))
+ self._audio_content_started = True
+
+ # Send audio chunk
+ audio_data = json_message.get("audio", "")
+ audio_event = {
+ "event": {
+ "audioInput": {
+ "promptName": self.prompt_name,
+ "contentName": self.audio_content_name,
+ "content": audio_data,
+ }
+ }
+ }
+ messages.append(json.dumps(audio_event))
+
+ return messages
+
+ def transform_input_audio_buffer_commit_event(self, json_message: dict) -> List[str]:
+ """
+ Transform input_audio_buffer.commit event to Bedrock audio content end.
+
+ Args:
+ json_message: OpenAI input_audio_buffer.commit message
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ verbose_logger.debug("Handling input_audio_buffer.commit")
+ messages: List[str] = []
+
+ if hasattr(self, "_audio_content_started"):
+ audio_content_end = {
+ "event": {
+ "contentEnd": {
+ "promptName": self.prompt_name,
+ "contentName": self.audio_content_name,
+ }
+ }
+ }
+ messages.append(json.dumps(audio_content_end))
+ delattr(self, "_audio_content_started")
+
+ return messages
+
+ def transform_conversation_item_create_event(self, json_message: dict) -> List[str]:
+ """
+ Transform conversation.item.create event to Bedrock text input or tool result.
+
+ Args:
+ json_message: OpenAI conversation.item.create message
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ verbose_logger.debug("Handling conversation.item.create")
+ messages: List[str] = []
+
+ item = json_message.get("item", {})
+ item_type = item.get("type")
+
+ # Handle tool result
+ if item_type == "function_call_output":
+ return self.transform_conversation_item_create_tool_result_event(json_message)
+
+ # Handle regular message
+ if item_type == "message":
+ content = item.get("content", [])
+ for content_part in content:
+ if content_part.get("type") == "input_text":
+ text_content_name = str(uuid_lib.uuid4())
+
+ # Content start
+ text_content_start = {
+ "event": {
+ "contentStart": {
+ "promptName": self.prompt_name,
+ "contentName": text_content_name,
+ "type": "TEXT",
+ "interactive": True,
+ "role": "USER",
+ "textInputConfiguration": {
+ "mediaType": self.text_media_type
+ },
+ }
+ }
+ }
+ messages.append(json.dumps(text_content_start))
+
+ # Text input
+ text_input = {
+ "event": {
+ "textInput": {
+ "promptName": self.prompt_name,
+ "contentName": text_content_name,
+ "content": content_part.get("text", ""),
+ }
+ }
+ }
+ messages.append(json.dumps(text_input))
+
+ # Content end
+ text_content_end = {
+ "event": {
+ "contentEnd": {
+ "promptName": self.prompt_name,
+ "contentName": text_content_name,
+ }
+ }
+ }
+ messages.append(json.dumps(text_content_end))
+
+ return messages
+
+ def transform_response_create_event(self, json_message: dict) -> List[str]:
+ """
+ Transform response.create event to Bedrock format.
+
+ Args:
+ json_message: OpenAI response.create message
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ verbose_logger.debug("Handling response.create")
+ # Bedrock starts generating automatically, no explicit trigger needed
+ return []
+
+ def transform_response_cancel_event(self, json_message: dict) -> List[str]:
+ """
+ Transform response.cancel event to Bedrock format.
+
+ Args:
+ json_message: OpenAI response.cancel message
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ verbose_logger.debug("Handling response.cancel")
+ # Send interrupt signal if needed
+ return []
+
+ def transform_realtime_request(
+ self,
+ message: str,
+ model: str,
+ session_configuration_request: Optional[str] = None,
+ ) -> List[str]:
+ """
+ Transform OpenAI realtime request to Bedrock Nova Sonic format.
+
+ Args:
+ message: OpenAI format message (JSON string)
+ model: Model ID
+ session_configuration_request: Previous session config
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ try:
+ json_message = json.loads(message)
+ except json.JSONDecodeError:
+ verbose_logger.warning(f"Invalid JSON message: {message[:200]}")
+ return []
+
+ message_type = json_message.get("type")
+
+ # Route to appropriate transformation method
+ if message_type == "session.update":
+ return self.transform_session_update_event(json_message)
+ elif message_type == "input_audio_buffer.append":
+ return self.transform_input_audio_buffer_append_event(json_message)
+ elif message_type == "input_audio_buffer.commit":
+ return self.transform_input_audio_buffer_commit_event(json_message)
+ elif message_type == "conversation.item.create":
+ return self.transform_conversation_item_create_event(json_message)
+ elif message_type == "response.create":
+ return self.transform_response_create_event(json_message)
+ elif message_type == "response.cancel":
+ return self.transform_response_cancel_event(json_message)
+ else:
+ verbose_logger.warning(f"Unknown message type: {message_type}")
+ return []
+
+ def transform_session_start_event(
+ self,
+ event: dict,
+ model: str,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> OpenAIRealtimeStreamSessionEvents:
+ """
+ Transform Bedrock sessionStart event to OpenAI session.created.
+
+ Args:
+ event: Bedrock sessionStart event
+ model: Model ID
+ logging_obj: Logging object
+
+ Returns:
+ OpenAI session.created event
+ """
+ verbose_logger.debug("Handling sessionStart")
+
+ session = OpenAIRealtimeStreamSession(
+ id=logging_obj.litellm_trace_id,
+ modalities=["text", "audio"],
+ )
+ if model is not None and isinstance(model, str):
+ session["model"] = model
+
+ return OpenAIRealtimeStreamSessionEvents(
+ type="session.created",
+ session=session,
+ event_id=str(uuid.uuid4()),
+ )
+
+ def transform_content_start_event(
+ self,
+ event: dict,
+ current_response_id: Optional[str],
+ current_output_item_id: Optional[str],
+ current_conversation_id: Optional[str],
+ ) -> tuple[
+ List[OpenAIRealtimeEvents],
+ Optional[str],
+ Optional[str],
+ Optional[str],
+ Optional[ALL_DELTA_TYPES],
+ ]:
+ """
+ Transform Bedrock contentStart event to OpenAI response events.
+
+ Args:
+ event: Bedrock contentStart event
+ current_response_id: Current response ID
+ current_output_item_id: Current output item ID
+ current_conversation_id: Current conversation ID
+
+ Returns:
+ Tuple of (events, response_id, output_item_id, conversation_id, delta_type)
+ """
+ content_start = event["contentStart"]
+ role = content_start.get("role")
+
+ if role != "ASSISTANT":
+ return [], current_response_id, current_output_item_id, current_conversation_id, None
+
+ verbose_logger.debug("Handling ASSISTANT contentStart")
+
+ # Initialize IDs if needed
+ if not current_response_id:
+ current_response_id = f"resp_{uuid.uuid4()}"
+ if not current_output_item_id:
+ current_output_item_id = f"item_{uuid.uuid4()}"
+ if not current_conversation_id:
+ current_conversation_id = f"conv_{uuid.uuid4()}"
+
+ # Determine content type
+ content_type = content_start.get("type", "TEXT")
+ current_delta_type: ALL_DELTA_TYPES = "text" if content_type == "TEXT" else "audio"
+
+ returned_messages: List[OpenAIRealtimeEvents] = []
+
+ # Send response.created
+ response_created = OpenAIRealtimeStreamResponseBaseObject(
+ type="response.created",
+ event_id=f"event_{uuid.uuid4()}",
+ response={
+ "object": "realtime.response",
+ "id": current_response_id,
+ "status": "in_progress",
+ "output": [],
+ "conversation_id": current_conversation_id,
+ },
+ )
+ returned_messages.append(response_created)
+
+ # Send response.output_item.added
+ output_item_added = OpenAIRealtimeStreamResponseOutputItemAdded(
+ type="response.output_item.added",
+ response_id=current_response_id,
+ output_index=0,
+ item={
+ "id": current_output_item_id,
+ "object": "realtime.item",
+ "type": "message",
+ "status": "in_progress",
+ "role": "assistant",
+ "content": [],
+ },
+ )
+ returned_messages.append(output_item_added)
+
+ # Send response.content_part.added
+ content_part_added = OpenAIRealtimeResponseContentPartAdded(
+ type="response.content_part.added",
+ content_index=0,
+ output_index=0,
+ event_id=f"event_{uuid.uuid4()}",
+ item_id=current_output_item_id,
+ part=(
+ {"type": "text", "text": ""}
+ if current_delta_type == "text"
+ else {"type": "audio", "transcript": ""}
+ ),
+ response_id=current_response_id,
+ )
+ returned_messages.append(content_part_added)
+
+ return (
+ returned_messages,
+ current_response_id,
+ current_output_item_id,
+ current_conversation_id,
+ current_delta_type,
+ )
+
+ def transform_text_output_event(
+ self,
+ event: dict,
+ current_output_item_id: Optional[str],
+ current_response_id: Optional[str],
+ current_delta_chunks: Optional[List[OpenAIRealtimeResponseDelta]],
+ ) -> tuple[List[OpenAIRealtimeEvents], Optional[List[OpenAIRealtimeResponseDelta]]]:
+ """
+ Transform Bedrock textOutput event to OpenAI response.text.delta.
+
+ Args:
+ event: Bedrock textOutput event
+ current_output_item_id: Current output item ID
+ current_response_id: Current response ID
+ current_delta_chunks: Current delta chunks
+
+ Returns:
+ Tuple of (events, updated_delta_chunks)
+ """
+ verbose_logger.debug("Handling textOutput")
+ text_content = event["textOutput"].get("content", "")
+
+ if not current_output_item_id or not current_response_id:
+ return [], current_delta_chunks
+
+ text_delta = OpenAIRealtimeResponseDelta(
+ type="response.text.delta",
+ content_index=0,
+ event_id=f"event_{uuid.uuid4()}",
+ item_id=current_output_item_id,
+ output_index=0,
+ response_id=current_response_id,
+ delta=text_content,
+ )
+
+ # Track delta chunks
+ if current_delta_chunks is None:
+ current_delta_chunks = []
+ current_delta_chunks.append(text_delta)
+
+ return [text_delta], current_delta_chunks
+
+ def transform_audio_output_event(
+ self,
+ event: dict,
+ current_output_item_id: Optional[str],
+ current_response_id: Optional[str],
+ ) -> List[OpenAIRealtimeEvents]:
+ """
+ Transform Bedrock audioOutput event to OpenAI response.audio.delta.
+
+ Args:
+ event: Bedrock audioOutput event
+ current_output_item_id: Current output item ID
+ current_response_id: Current response ID
+
+ Returns:
+ List of OpenAI events
+ """
+ verbose_logger.debug("Handling audioOutput")
+ audio_content = event["audioOutput"].get("content", "")
+
+ if not current_output_item_id or not current_response_id:
+ return []
+
+ audio_delta = OpenAIRealtimeResponseDelta(
+ type="response.audio.delta",
+ content_index=0,
+ event_id=f"event_{uuid.uuid4()}",
+ item_id=current_output_item_id,
+ output_index=0,
+ response_id=current_response_id,
+ delta=audio_content,
+ )
+
+ return [audio_delta]
+
+ def transform_content_end_event(
+ self,
+ event: dict,
+ current_output_item_id: Optional[str],
+ current_response_id: Optional[str],
+ current_delta_type: Optional[str],
+ current_delta_chunks: Optional[List[OpenAIRealtimeResponseDelta]],
+ ) -> tuple[List[OpenAIRealtimeEvents], Optional[List[OpenAIRealtimeResponseDelta]]]:
+ """
+ Transform Bedrock contentEnd event to OpenAI response done events.
+
+ Args:
+ event: Bedrock contentEnd event
+ current_output_item_id: Current output item ID
+ current_response_id: Current response ID
+ current_delta_type: Current delta type (text or audio)
+ current_delta_chunks: Current delta chunks
+
+ Returns:
+ Tuple of (events, reset_delta_chunks)
+ """
+ content_end = event["contentEnd"]
+ verbose_logger.debug(f"Handling contentEnd: {content_end}")
+
+ if not current_output_item_id or not current_response_id:
+ return [], current_delta_chunks
+
+ returned_messages: List[OpenAIRealtimeEvents] = []
+
+ # Send appropriate done event based on type
+ if current_delta_type == "text":
+ # Accumulate text
+ accumulated_text = ""
+ if current_delta_chunks:
+ accumulated_text = "".join(
+ [chunk.get("delta", "") for chunk in current_delta_chunks]
+ )
+
+ text_done = OpenAIRealtimeResponseTextDone(
+ type="response.text.done",
+ content_index=0,
+ event_id=f"event_{uuid.uuid4()}",
+ item_id=current_output_item_id,
+ output_index=0,
+ response_id=current_response_id,
+ text=accumulated_text,
+ )
+ returned_messages.append(text_done)
+
+ # Send content_part.done
+ content_part_done = OpenAIRealtimeContentPartDone(
+ type="response.content_part.done",
+ content_index=0,
+ event_id=f"event_{uuid.uuid4()}",
+ item_id=current_output_item_id,
+ output_index=0,
+ part={"type": "text", "text": accumulated_text},
+ response_id=current_response_id,
+ )
+ returned_messages.append(content_part_done)
+
+ elif current_delta_type == "audio":
+ audio_done = OpenAIRealtimeResponseAudioDone(
+ type="response.audio.done",
+ content_index=0,
+ event_id=f"event_{uuid.uuid4()}",
+ item_id=current_output_item_id,
+ output_index=0,
+ response_id=current_response_id,
+ )
+ returned_messages.append(audio_done)
+
+ # Send content_part.done
+ content_part_done = OpenAIRealtimeContentPartDone(
+ type="response.content_part.done",
+ content_index=0,
+ event_id=f"event_{uuid.uuid4()}",
+ item_id=current_output_item_id,
+ output_index=0,
+ part={"type": "audio", "transcript": ""},
+ response_id=current_response_id,
+ )
+ returned_messages.append(content_part_done)
+
+ # Send output_item.done
+ output_item_done = OpenAIRealtimeOutputItemDone(
+ type="response.output_item.done",
+ event_id=f"event_{uuid.uuid4()}",
+ output_index=0,
+ response_id=current_response_id,
+ item={
+ "id": current_output_item_id,
+ "object": "realtime.item",
+ "type": "message",
+ "status": "completed",
+ "role": "assistant",
+ "content": [],
+ },
+ )
+ returned_messages.append(output_item_done)
+
+ # Reset delta chunks
+ return returned_messages, None
+
+ def transform_prompt_end_event(
+ self,
+ event: dict,
+ current_response_id: Optional[str],
+ current_conversation_id: Optional[str],
+ ) -> tuple[List[OpenAIRealtimeEvents], Optional[str], Optional[str], Optional[ALL_DELTA_TYPES]]:
+ """
+ Transform Bedrock promptEnd event to OpenAI response.done.
+
+ Args:
+ event: Bedrock promptEnd event
+ current_response_id: Current response ID
+ current_conversation_id: Current conversation ID
+
+ Returns:
+ Tuple of (events, reset_output_item_id, reset_response_id, reset_delta_type)
+ """
+ verbose_logger.debug("Handling promptEnd")
+
+ if not current_response_id or not current_conversation_id:
+ return [], None, None, None
+
+ usage_obj = get_empty_usage()
+ response_done = OpenAIRealtimeDoneEvent(
+ type="response.done",
+ event_id=f"event_{uuid.uuid4()}",
+ response=OpenAIRealtimeResponseDoneObject(
+ object="realtime.response",
+ id=current_response_id,
+ status="completed",
+ output=[],
+ conversation_id=current_conversation_id,
+ usage={
+ "prompt_tokens": usage_obj.prompt_tokens,
+ "completion_tokens": usage_obj.completion_tokens,
+ "total_tokens": usage_obj.total_tokens,
+ },
+ ),
+ )
+
+ # Reset state for next response
+ return [response_done], None, None, None
+
+ def transform_tool_use_event(
+ self,
+ event: dict,
+ current_output_item_id: Optional[str],
+ current_response_id: Optional[str],
+ ) -> tuple[List[OpenAIRealtimeEvents], str, str]:
+ """
+ Transform Bedrock toolUse event to OpenAI format.
+
+ Args:
+ event: Bedrock toolUse event
+ current_output_item_id: Current output item ID
+ current_response_id: Current response ID
+
+ Returns:
+ Tuple of (events, tool_call_id, tool_name) for tracking
+ """
+ verbose_logger.debug("Handling toolUse")
+ tool_use = event["toolUse"]
+
+ if not current_output_item_id or not current_response_id:
+ return [], "", ""
+
+ # Parse the tool input
+ tool_input = {}
+ if "input" in tool_use:
+ try:
+ tool_input = json.loads(tool_use["input"]) if isinstance(tool_use["input"], str) else tool_use["input"]
+ except json.JSONDecodeError:
+ tool_input = {}
+
+ tool_call_id = tool_use.get("toolUseId", "")
+ tool_name = tool_use.get("toolName", "")
+
+ # Create a function call arguments done event
+ # This is a custom event format that matches what clients expect
+ from typing import cast
+ function_call_event: dict[str, Any] = {
+ "type": "response.function_call_arguments.done",
+ "event_id": f"event_{uuid.uuid4()}",
+ "response_id": current_response_id,
+ "item_id": current_output_item_id,
+ "output_index": 0,
+ "call_id": tool_call_id,
+ "name": tool_name,
+ "arguments": json.dumps(tool_input),
+ }
+
+ return [cast(OpenAIRealtimeEvents, function_call_event)], tool_call_id, tool_name
+
+ def transform_conversation_item_create_tool_result_event(self, json_message: dict) -> List[str]:
+ """
+ Transform conversation.item.create with tool result to Bedrock format.
+
+ Args:
+ json_message: OpenAI conversation.item.create message with tool result
+
+ Returns:
+ List of Bedrock format messages (JSON strings)
+ """
+ verbose_logger.debug("Handling conversation.item.create for tool result")
+ messages: List[str] = []
+
+ item = json_message.get("item", {})
+ if item.get("type") == "function_call_output":
+ tool_content_name = str(uuid_lib.uuid4())
+ call_id = item.get("call_id", "")
+ output = item.get("output", "")
+
+ # Content start for tool result
+ tool_content_start = {
+ "event": {
+ "contentStart": {
+ "promptName": self.prompt_name,
+ "contentName": tool_content_name,
+ "interactive": False,
+ "type": "TOOL",
+ "role": "TOOL",
+ "toolResultInputConfiguration": {
+ "toolUseId": call_id,
+ "type": "TEXT",
+ "textInputConfiguration": {
+ "mediaType": "text/plain"
+ }
+ }
+ }
+ }
+ }
+ messages.append(json.dumps(tool_content_start))
+
+ # Tool result
+ tool_result = {
+ "event": {
+ "toolResult": {
+ "promptName": self.prompt_name,
+ "contentName": tool_content_name,
+ "content": output if isinstance(output, str) else json.dumps(output)
+ }
+ }
+ }
+ messages.append(json.dumps(tool_result))
+
+ # Content end
+ tool_content_end = {
+ "event": {
+ "contentEnd": {
+ "promptName": self.prompt_name,
+ "contentName": tool_content_name,
+ }
+ }
+ }
+ messages.append(json.dumps(tool_content_end))
+
+ return messages
+
+ def transform_realtime_response(
+ self,
+ message: Union[str, bytes],
+ model: str,
+ logging_obj: LiteLLMLoggingObj,
+ realtime_response_transform_input: RealtimeResponseTransformInput,
+ ) -> RealtimeResponseTypedDict:
+ """
+ Transform Bedrock Nova Sonic response to OpenAI realtime format.
+
+ Args:
+ message: Bedrock format message (JSON string)
+ model: Model ID
+ logging_obj: Logging object
+ realtime_response_transform_input: Current state
+
+ Returns:
+ Transformed response with updated state
+ """
+ try:
+ json_message = json.loads(message)
+ except json.JSONDecodeError:
+ message_preview = message[:200].decode('utf-8', errors='replace') if isinstance(message, bytes) else message[:200]
+ verbose_logger.warning(f"Invalid JSON message: {message_preview}")
+ return {
+ "response": [],
+ "current_output_item_id": realtime_response_transform_input.get(
+ "current_output_item_id"
+ ),
+ "current_response_id": realtime_response_transform_input.get(
+ "current_response_id"
+ ),
+ "current_delta_chunks": realtime_response_transform_input.get(
+ "current_delta_chunks"
+ ),
+ "current_conversation_id": realtime_response_transform_input.get(
+ "current_conversation_id"
+ ),
+ "current_item_chunks": realtime_response_transform_input.get(
+ "current_item_chunks"
+ ),
+ "current_delta_type": realtime_response_transform_input.get(
+ "current_delta_type"
+ ),
+ "session_configuration_request": realtime_response_transform_input.get(
+ "session_configuration_request"
+ ),
+ }
+
+ # Extract state
+ current_output_item_id = realtime_response_transform_input.get(
+ "current_output_item_id"
+ )
+ current_response_id = realtime_response_transform_input.get(
+ "current_response_id"
+ )
+ current_conversation_id = realtime_response_transform_input.get(
+ "current_conversation_id"
+ )
+ current_delta_chunks = realtime_response_transform_input.get(
+ "current_delta_chunks"
+ )
+ current_delta_type = realtime_response_transform_input.get("current_delta_type")
+ session_configuration_request = realtime_response_transform_input.get(
+ "session_configuration_request"
+ )
+
+ returned_messages: List[OpenAIRealtimeEvents] = []
+
+ # Parse Bedrock event
+ event = json_message.get("event", {})
+
+ # Route to appropriate transformation method
+ if "sessionStart" in event:
+ session_created = self.transform_session_start_event(
+ event, model, logging_obj
+ )
+ returned_messages.append(session_created)
+ session_configuration_request = json.dumps({"configured": True})
+
+ elif "contentStart" in event:
+ (
+ events,
+ current_response_id,
+ current_output_item_id,
+ current_conversation_id,
+ current_delta_type,
+ ) = self.transform_content_start_event(
+ event,
+ current_response_id,
+ current_output_item_id,
+ current_conversation_id,
+ )
+ returned_messages.extend(events)
+
+ elif "textOutput" in event:
+ events, current_delta_chunks = self.transform_text_output_event(
+ event,
+ current_output_item_id,
+ current_response_id,
+ current_delta_chunks,
+ )
+ returned_messages.extend(events)
+
+ elif "audioOutput" in event:
+ events = self.transform_audio_output_event(
+ event, current_output_item_id, current_response_id
+ )
+ returned_messages.extend(events)
+
+ elif "contentEnd" in event:
+ events, current_delta_chunks = self.transform_content_end_event(
+ event,
+ current_output_item_id,
+ current_response_id,
+ current_delta_type,
+ current_delta_chunks,
+ )
+ returned_messages.extend(events)
+
+ elif "toolUse" in event:
+ events, tool_call_id, tool_name = self.transform_tool_use_event(
+ event, current_output_item_id, current_response_id
+ )
+ returned_messages.extend(events)
+ # Store tool call info for potential use
+ verbose_logger.debug(f"Tool use event: {tool_name} (ID: {tool_call_id})")
+
+ elif "promptEnd" in event:
+ (
+ events,
+ current_output_item_id,
+ current_response_id,
+ current_delta_type,
+ ) = self.transform_prompt_end_event(
+ event, current_response_id, current_conversation_id
+ )
+ returned_messages.extend(events)
+
+ return {
+ "response": returned_messages,
+ "current_output_item_id": current_output_item_id,
+ "current_response_id": current_response_id,
+ "current_delta_chunks": current_delta_chunks,
+ "current_conversation_id": current_conversation_id,
+ "current_item_chunks": realtime_response_transform_input.get(
+ "current_item_chunks"
+ ),
+ "current_delta_type": current_delta_type,
+ "session_configuration_request": session_configuration_request,
+ }
diff --git a/litellm/llms/cerebras/chat.py b/litellm/llms/cerebras/chat.py
index 4e9c6811a77..9929e2ab9a2 100644
--- a/litellm/llms/cerebras/chat.py
+++ b/litellm/llms/cerebras/chat.py
@@ -7,6 +7,7 @@ this is OpenAI compatible - no translation needed / occurs
from typing import Optional
from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig
+from litellm.utils import supports_reasoning
class CerebrasConfig(OpenAIGPTConfig):
@@ -24,6 +25,7 @@ class CerebrasConfig(OpenAIGPTConfig):
tool_choice: Optional[str] = None
tools: Optional[list] = None
user: Optional[str] = None
+ reasoning_effort: Optional[str] = None
def __init__(
self,
@@ -37,6 +39,7 @@ class CerebrasConfig(OpenAIGPTConfig):
tool_choice: Optional[str] = None,
tools: Optional[list] = None,
user: Optional[str] = None,
+ reasoning_effort: Optional[str] = None,
) -> None:
locals_ = locals().copy()
for key, value in locals_.items():
@@ -53,7 +56,7 @@ class CerebrasConfig(OpenAIGPTConfig):
"""
- return [
+ supported_params = [
"max_tokens",
"max_completion_tokens",
"response_format",
@@ -67,6 +70,12 @@ class CerebrasConfig(OpenAIGPTConfig):
"user",
]
+ # Only add reasoning_effort for models that support it
+ if supports_reasoning(model=model, custom_llm_provider="cerebras"):
+ supported_params.append("reasoning_effort")
+
+ return supported_params
+
def map_openai_params(
self,
non_default_params: dict,
diff --git a/litellm/llms/chatgpt/responses/transformation.py b/litellm/llms/chatgpt/responses/transformation.py
index 0ce24f63a89..bcb6edd39f9 100644
--- a/litellm/llms/chatgpt/responses/transformation.py
+++ b/litellm/llms/chatgpt/responses/transformation.py
@@ -73,10 +73,6 @@ class ChatGPTResponsesAPIConfig(OpenAIResponsesAPIConfig):
litellm_params,
headers,
)
- request.pop("max_output_tokens", None)
- request.pop("max_tokens", None)
- request.pop("max_completion_tokens", None)
- request.pop("metadata", None)
base_instructions = get_chatgpt_default_instructions()
existing_instructions = request.get("instructions")
if existing_instructions:
@@ -92,7 +88,22 @@ class ChatGPTResponsesAPIConfig(OpenAIResponsesAPIConfig):
if "reasoning.encrypted_content" not in include:
include.append("reasoning.encrypted_content")
request["include"] = include
- return request
+
+ allowed_keys = {
+ "model",
+ "input",
+ "instructions",
+ "stream",
+ "store",
+ "include",
+ "tools",
+ "tool_choice",
+ "reasoning",
+ "previous_response_id",
+ "truncation",
+ }
+
+ return {k: v for k, v in request.items() if k in allowed_keys}
def transform_response_api_response(
self,
diff --git a/litellm/llms/cohere/rerank/guardrail_translation/handler.py b/litellm/llms/cohere/rerank/guardrail_translation/handler.py
index 6893a5991c3..b8133c59f7d 100644
--- a/litellm/llms/cohere/rerank/guardrail_translation/handler.py
+++ b/litellm/llms/cohere/rerank/guardrail_translation/handler.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Optional
from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -49,8 +50,13 @@ class CohereRerankHandler(BaseTranslation):
# Process query only
query = data.get("query")
if query is not None and isinstance(query, str):
+ inputs = GenericGuardrailAPIInputs(texts=[query])
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [query]},
+ inputs=inputs,
request_data=data,
input_type="request",
logging_obj=litellm_logging_obj,
diff --git a/litellm/llms/custom_httpx/aiohttp_transport.py b/litellm/llms/custom_httpx/aiohttp_transport.py
index a7b83d8c802..6cec1f4fe16 100644
--- a/litellm/llms/custom_httpx/aiohttp_transport.py
+++ b/litellm/llms/custom_httpx/aiohttp_transport.py
@@ -1,9 +1,10 @@
import asyncio
import contextlib
import os
+import ssl
import typing
import urllib.request
-from typing import Callable, Dict, Optional, Union
+from typing import Any, Callable, Dict, Optional, Union
import aiohttp
import aiohttp.client_exceptions
@@ -118,8 +119,13 @@ class AiohttpResponseStream(httpx.AsyncByteStream):
class AiohttpTransport(httpx.AsyncBaseTransport):
- def __init__(self, client: Union[ClientSession, Callable[[], ClientSession]]) -> None:
+ def __init__(
+ self,
+ client: Union[ClientSession, Callable[[], ClientSession]],
+ owns_session: bool = True,
+ ) -> None:
self.client = client
+ self._owns_session = owns_session
#########################################################
# Class variables for proxy settings
@@ -127,7 +133,7 @@ class AiohttpTransport(httpx.AsyncBaseTransport):
self.proxy_cache: Dict[str, Optional[str]] = {}
async def aclose(self) -> None:
- if isinstance(self.client, ClientSession):
+ if self._owns_session and isinstance(self.client, ClientSession):
await self.client.close()
@@ -139,9 +145,15 @@ class LiteLLMAiohttpTransport(AiohttpTransport):
Credit to: https://github.com/karpetrosyan/httpx-aiohttp for this implementation
"""
- def __init__(self, client: Union[ClientSession, Callable[[], ClientSession]]):
+ def __init__(
+ self,
+ client: Union[ClientSession, Callable[[], ClientSession]],
+ ssl_verify: Optional[Union[bool, ssl.SSLContext]] = None,
+ owns_session: bool = True,
+ ):
self.client = client
- super().__init__(client=client)
+ self._ssl_verify = ssl_verify # Store for per-request SSL override
+ super().__init__(client=client, owns_session=owns_session)
# Store the client factory for recreating sessions when needed
if callable(client):
self._client_factory = client
@@ -214,6 +226,7 @@ class LiteLLMAiohttpTransport(AiohttpTransport):
timeout: dict,
proxy: Optional[str],
sni_hostname: Optional[str],
+ ssl_verify: Optional[Union[bool, ssl.SSLContext]] = None,
) -> ClientResponse:
"""
Helper function to make an aiohttp request with the given parameters.
@@ -224,6 +237,7 @@ class LiteLLMAiohttpTransport(AiohttpTransport):
timeout: Timeout settings dict with 'connect', 'read', 'pool' keys
proxy: Optional proxy URL
sni_hostname: Optional SNI hostname for SSL
+ ssl_verify: Optional SSL verification setting (False to disable, SSLContext for custom)
Returns:
ClientResponse from aiohttp
@@ -237,21 +251,28 @@ class LiteLLMAiohttpTransport(AiohttpTransport):
data = request.stream # type: ignore
request.headers.pop("transfer-encoding", None) # handled by aiohttp
- response = await client_session.request(
- method=request.method,
- url=YarlURL(str(request.url), encoded=True),
- headers=request.headers,
- data=data,
- allow_redirects=False,
- auto_decompress=False,
- timeout=ClientTimeout(
+ # Only pass ssl kwarg when explicitly configured, to avoid
+ # overriding the session/connector defaults with None (which is
+ # not a valid value for aiohttp's ssl parameter).
+ request_kwargs: Dict[str, Any] = {
+ "method": request.method,
+ "url": YarlURL(str(request.url), encoded=True),
+ "headers": request.headers,
+ "data": data,
+ "allow_redirects": False,
+ "auto_decompress": False,
+ "timeout": ClientTimeout(
sock_connect=timeout.get("connect"),
sock_read=timeout.get("read"),
connect=timeout.get("pool"),
),
- proxy=proxy,
- server_hostname=sni_hostname,
- ).__aenter__()
+ "proxy": proxy,
+ "server_hostname": sni_hostname,
+ }
+ if ssl_verify is not None:
+ request_kwargs["ssl"] = ssl_verify
+
+ response = await client_session.request(**request_kwargs).__aenter__()
return response
@@ -268,6 +289,9 @@ class LiteLLMAiohttpTransport(AiohttpTransport):
# Resolve proxy settings from environment variables
proxy = await self._get_proxy_settings(request)
+ # Use stored SSL configuration for per-request override
+ ssl_config = self._ssl_verify
+
try:
with map_aiohttp_exceptions():
response = await self._make_aiohttp_request(
@@ -276,6 +300,7 @@ class LiteLLMAiohttpTransport(AiohttpTransport):
timeout=timeout,
proxy=proxy,
sni_hostname=sni_hostname,
+ ssl_verify=ssl_config,
)
except RuntimeError as e:
# Handle the case where session was closed between our check and actual use
@@ -296,6 +321,7 @@ class LiteLLMAiohttpTransport(AiohttpTransport):
timeout=timeout,
proxy=proxy,
sni_hostname=sni_hostname,
+ ssl_verify=ssl_config,
)
else:
# Re-raise if it's a different RuntimeError
diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py
index 4f86877a6c0..328097639e5 100644
--- a/litellm/llms/custom_httpx/http_handler.py
+++ b/litellm/llms/custom_httpx/http_handler.py
@@ -50,9 +50,21 @@ try:
except Exception:
version = "0.0.0"
-headers = {
- "User-Agent": f"litellm/{version}",
-}
+def get_default_headers() -> dict:
+ """
+ Get default headers for HTTP requests.
+
+ - Default: `User-Agent: litellm/{version}`
+ - Override: set `LITELLM_USER_AGENT` to fully override the header value.
+ """
+ user_agent = os.environ.get("LITELLM_USER_AGENT")
+ if user_agent is not None:
+ return {"User-Agent": user_agent}
+
+ return {"User-Agent": f"litellm/{version}"}
+
+# Initialize headers (User-Agent)
+headers = get_default_headers()
# https://www.python-httpx.org/advanced/timeouts
_DEFAULT_TIMEOUT = httpx.Timeout(timeout=5.0, connect=5.0)
@@ -371,13 +383,16 @@ class AsyncHTTPHandler:
shared_session=shared_session,
)
+ # Get default headers (User-Agent, overridable via LITELLM_USER_AGENT)
+ default_headers = get_default_headers()
+
return httpx.AsyncClient(
transport=transport,
event_hooks=event_hooks,
timeout=timeout,
verify=ssl_config,
cert=cert,
- headers=headers,
+ headers=default_headers,
follow_redirects=True,
)
@@ -831,6 +846,16 @@ class AsyncHTTPHandler:
if str_to_bool(os.getenv("AIOHTTP_TRUST_ENV", "False")) is True:
trust_env = True
+ #########################################################
+ # Determine SSL config to pass to transport for per-request override
+ # This ensures ssl_verify works even with shared sessions
+ #########################################################
+ ssl_for_transport: Optional[Union[bool, ssl.SSLContext]] = None
+ if ssl_context is not None:
+ ssl_for_transport = ssl_context
+ elif ssl_verify is False:
+ ssl_for_transport = False
+
verbose_logger.debug("Creating AiohttpTransport...")
# Use shared session if provided and valid
@@ -838,7 +863,11 @@ class AsyncHTTPHandler:
verbose_logger.debug(
f"SHARED SESSION: Reusing existing ClientSession (ID: {id(shared_session)})"
)
- return LiteLLMAiohttpTransport(client=shared_session)
+ return LiteLLMAiohttpTransport(
+ client=shared_session,
+ ssl_verify=ssl_for_transport,
+ owns_session=False,
+ )
# Create new session only if none provided or existing one is invalid
verbose_logger.debug(
@@ -862,6 +891,7 @@ class AsyncHTTPHandler:
connector=TCPConnector(**transport_connector_kwargs),
trust_env=trust_env,
),
+ ssl_verify=ssl_for_transport,
)
@staticmethod
@@ -899,6 +929,9 @@ class HTTPHandler:
# /path/to/client.pem
cert = os.getenv("SSL_CERTIFICATE", litellm.ssl_certificate)
+ # Get default headers (User-Agent, overridable via LITELLM_USER_AGENT)
+ default_headers = get_default_headers() if not disable_default_headers else None
+
if client is None:
transport = self._create_sync_transport()
@@ -908,7 +941,7 @@ class HTTPHandler:
timeout=timeout,
verify=ssl_config,
cert=cert,
- headers=headers if not disable_default_headers else None,
+ headers=default_headers,
follow_redirects=True,
)
else:
@@ -1174,7 +1207,28 @@ def get_async_httpx_client(
If not present, creates a new client
Caches the new client and returns it.
+
+ Note: When shared_session is provided, the cache is bypassed to ensure
+ the user's session (with its trace_configs, connector settings, etc.)
+ is used for the request.
"""
+ # When shared_session is provided, bypass cache and create a new handler
+ # that uses the user's session directly. This preserves the user's
+ # session configuration including trace_configs for aiohttp tracing.
+ if shared_session is not None:
+ verbose_logger.debug(
+ f"shared_session provided (ID: {id(shared_session)}), bypassing client cache"
+ )
+ if params is not None:
+ handler_params = {k: v for k, v in params.items() if k != "disable_aiohttp_transport"}
+ handler_params["shared_session"] = shared_session
+ return AsyncHTTPHandler(**handler_params)
+ else:
+ return AsyncHTTPHandler(
+ timeout=httpx.Timeout(timeout=600.0, connect=5.0),
+ shared_session=shared_session,
+ )
+
_params_key_name = ""
if params is not None:
for key, value in params.items():
@@ -1201,12 +1255,10 @@ def get_async_httpx_client(
if params is not None:
# Filter out params that are only used for cache key, not for AsyncHTTPHandler.__init__
handler_params = {k: v for k, v in params.items() if k != "disable_aiohttp_transport"}
- handler_params["shared_session"] = shared_session
_new_client = AsyncHTTPHandler(**handler_params)
else:
_new_client = AsyncHTTPHandler(
timeout=httpx.Timeout(timeout=600.0, connect=5.0),
- shared_session=shared_session,
)
cache.set_cache(
diff --git a/litellm/llms/custom_httpx/httpx_handler.py b/litellm/llms/custom_httpx/httpx_handler.py
index 6f684ba01c2..491cd97f7db 100644
--- a/litellm/llms/custom_httpx/httpx_handler.py
+++ b/litellm/llms/custom_httpx/httpx_handler.py
@@ -1,3 +1,4 @@
+import os
from typing import Optional, Union
import httpx
@@ -7,13 +8,22 @@ try:
except Exception:
version = "0.0.0"
-headers = {
- "User-Agent": f"litellm/{version}",
-}
+def get_default_headers() -> dict:
+ """
+ Get default headers for HTTP requests.
+ - Default: `User-Agent: litellm/{version}`
+ - Override: set `LITELLM_USER_AGENT` to fully override the header value.
+ """
+ user_agent = os.environ.get("LITELLM_USER_AGENT")
+ if user_agent is not None:
+ return {"User-Agent": user_agent}
+
+ return {"User-Agent": f"litellm/{version}"}
class HTTPHandler:
def __init__(self, concurrent_limit=1000):
+ headers = get_default_headers()
# Create a client with a connection pool
self.client = httpx.AsyncClient(
limits=httpx.Limits(
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 6a87967c3aa..0a5364bfcfe 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -21,6 +21,9 @@ import litellm.litellm_core_utils
import litellm.types
import litellm.types.utils
from litellm._logging import verbose_logger
+from litellm.anthropic_beta_headers_manager import (
+ update_headers_with_filtered_beta,
+)
from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES
from litellm.litellm_core_utils.realtime_streaming import RealTimeStreaming
from litellm.llms.base_llm.anthropic_messages.transformation import (
@@ -34,6 +37,7 @@ from litellm.llms.base_llm.batches.transformation import BaseBatchesConfig
from litellm.llms.base_llm.chat.transformation import BaseConfig
from litellm.llms.base_llm.containers.transformation import BaseContainerConfig
from litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig
+from litellm.llms.base_llm.evals.transformation import BaseEvalsAPIConfig
from litellm.llms.base_llm.files.transformation import BaseFilesConfig
from litellm.llms.base_llm.google_genai.transformation import (
BaseGoogleGenAIGenerateContentConfig,
@@ -130,6 +134,16 @@ if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig
+ from litellm.types.llms.openai_evals import (
+ CancelEvalResponse,
+ CancelRunResponse,
+ DeleteEvalResponse,
+ Eval,
+ ListEvalsResponse,
+ ListRunsResponse,
+ Run,
+ RunDeleteResponse,
+ )
LiteLLMLoggingObj = _LiteLLMLoggingObj
else:
@@ -302,7 +316,7 @@ class BaseLLMHTTPHandler:
logging_obj=logging_obj,
signed_json_body=signed_json_body,
)
- return provider_config.transform_response(
+ initial_response = provider_config.transform_response(
model=model,
raw_response=response,
model_response=model_response,
@@ -316,6 +330,20 @@ class BaseLLMHTTPHandler:
json_mode=json_mode,
)
+ # Call agentic chat completion hooks
+ final_response = await self._call_agentic_chat_completion_hooks(
+ response=initial_response,
+ model=model,
+ messages=messages,
+ optional_params=optional_params,
+ logging_obj=logging_obj,
+ stream=False,
+ custom_llm_provider=custom_llm_provider,
+ kwargs=litellm_params,
+ )
+
+ return final_response if final_response is not None else initial_response
+
def completion(
self,
model: str,
@@ -412,6 +440,11 @@ class BaseLLMHTTPHandler:
},
)
+ # Check if stream was converted for WebSearch interception
+ # This is set by the async_pre_request_hook in WebSearchInterceptionLogger
+ if litellm_params.get("_websearch_interception_converted_stream", False):
+ logging_obj.model_call_details["websearch_interception_converted_stream"] = True
+
if acompletion is True:
if stream is True:
data = self._add_stream_param_to_request_body(
@@ -1839,6 +1872,10 @@ class BaseLLMHTTPHandler:
api_key=api_key,
api_base=api_base,
)
+
+ headers = update_headers_with_filtered_beta(
+ headers=headers, provider=custom_llm_provider
+ )
logging_obj.update_environment_variables(
model=model,
@@ -4361,10 +4398,10 @@ class BaseLLMHTTPHandler:
kwargs: Dict,
) -> Optional[Any]:
"""
- Call agentic completion hooks for all custom loggers.
+ Call agentic completion hooks for all custom loggers (Anthropic Messages API).
- 1. Call async_should_run_agentic_completion to check if agentic loop is needed
- 2. If yes, call async_run_agentic_completion to execute the loop
+ 1. Call async_should_run_agentic_loop to check if agentic loop is needed
+ 2. If yes, call async_run_agentic_loop to execute the loop
Returns the response from agentic loop, or None if no hook runs.
"""
@@ -4453,6 +4490,105 @@ class BaseLLMHTTPHandler:
return None
+ async def _call_agentic_chat_completion_hooks(
+ self,
+ response: Any,
+ model: str,
+ messages: List[Dict],
+ optional_params: Dict,
+ logging_obj: "LiteLLMLoggingObj",
+ stream: bool,
+ custom_llm_provider: str,
+ kwargs: Dict,
+ ) -> Optional[Any]:
+ """
+ Call agentic chat completion hooks for all custom loggers (Chat Completions API).
+
+ 1. Call async_should_run_chat_completion_agentic_loop to check if agentic loop is needed
+ 2. If yes, call async_run_chat_completion_agentic_loop to execute the loop
+
+ Returns the response from agentic loop, or None if no hook runs.
+ """
+ from litellm._logging import verbose_logger
+ from litellm.integrations.custom_logger import CustomLogger
+
+ callbacks = litellm.callbacks + (
+ logging_obj.dynamic_success_callbacks or []
+ )
+ tools = optional_params.get("tools", [])
+
+ for callback in callbacks:
+ try:
+ if isinstance(callback, CustomLogger):
+ # Check if callback has the chat completion agentic loop method
+ if not hasattr(callback, "async_should_run_chat_completion_agentic_loop"):
+ continue
+
+ # First: Check if agentic loop should run
+ should_run, tool_calls = (
+ await callback.async_should_run_chat_completion_agentic_loop(
+ response=response,
+ model=model,
+ messages=messages,
+ tools=tools,
+ stream=stream,
+ custom_llm_provider=custom_llm_provider,
+ kwargs=kwargs,
+ )
+ )
+
+ if should_run:
+ # Second: Execute agentic loop
+ # Add custom_llm_provider to kwargs so the agentic loop can reconstruct the full model name
+ kwargs_with_provider = kwargs.copy() if kwargs else {}
+ kwargs_with_provider["custom_llm_provider"] = custom_llm_provider
+ agentic_response = await callback.async_run_chat_completion_agentic_loop(
+ tools=tool_calls,
+ model=model,
+ messages=messages,
+ response=response,
+ optional_params=optional_params,
+ logging_obj=logging_obj,
+ stream=stream,
+ kwargs=kwargs_with_provider,
+ )
+ # First hook that runs agentic loop wins
+ return agentic_response
+
+ except Exception as e:
+ verbose_logger.exception(
+ f"LiteLLM.AgenticHookError: Exception in chat completion agentic hooks: {str(e)}"
+ )
+
+ # Check if we need to convert response to fake stream for chat completions
+ # This happens when:
+ # 1. Stream was originally True but converted to False for WebSearch interception
+ # 2. No agentic loop ran (LLM didn't use the tool)
+ # 3. We have a non-streaming response that needs to be converted to streaming
+ websearch_converted_stream = (
+ logging_obj.model_call_details.get("websearch_interception_converted_stream", False)
+ if logging_obj is not None
+ else False
+ )
+
+ if websearch_converted_stream:
+ from litellm._logging import verbose_logger
+ from litellm.llms.base_llm.base_model_iterator import (
+ convert_model_response_to_streaming,
+ )
+
+ verbose_logger.debug(
+ "WebSearchInterception: No tool call made, converting non-streaming chat completion to fake stream"
+ )
+
+ # Convert the non-streaming ModelResponse to a fake stream
+ if hasattr(response, "choices"):
+ # Use the existing converter for ModelResponse
+ fake_stream = convert_model_response_to_streaming(response)
+ return fake_stream
+
+ return None
+
def _handle_error(
self,
e: Exception,
@@ -4474,6 +4610,7 @@ class BaseLLMHTTPHandler:
BaseSkillsAPIConfig,
"BasePassthroughConfig",
"BaseContainerConfig",
+ BaseEvalsAPIConfig,
],
):
status_code = getattr(e, "status_code", 500)
@@ -7033,17 +7170,31 @@ class BaseLLMHTTPHandler:
litellm_params=dict(litellm_params),
)
- (
- url,
- request_body,
- ) = vector_store_provider_config.transform_search_vector_store_request(
- vector_store_id=vector_store_id,
- query=query,
- vector_store_search_optional_params=vector_store_search_optional_params,
- api_base=api_base,
- litellm_logging_obj=logging_obj,
- litellm_params=dict(litellm_params),
- )
+ # Check if provider has async transform method
+ if hasattr(vector_store_provider_config, "atransform_search_vector_store_request"):
+ (
+ url,
+ request_body,
+ ) = await vector_store_provider_config.atransform_search_vector_store_request(
+ vector_store_id=vector_store_id,
+ query=query,
+ vector_store_search_optional_params=vector_store_search_optional_params,
+ api_base=api_base,
+ litellm_logging_obj=logging_obj,
+ litellm_params=dict(litellm_params),
+ )
+ else:
+ (
+ url,
+ request_body,
+ ) = vector_store_provider_config.transform_search_vector_store_request(
+ vector_store_id=vector_store_id,
+ query=query,
+ vector_store_search_optional_params=vector_store_search_optional_params,
+ api_base=api_base,
+ litellm_logging_obj=logging_obj,
+ litellm_params=dict(litellm_params),
+ )
all_optional_params: Dict[str, Any] = dict(litellm_params)
all_optional_params.update(vector_store_search_optional_params or {})
headers, signed_json_body = vector_store_provider_config.sign_request(
@@ -9177,3 +9328,1209 @@ class BaseLLMHTTPHandler:
raw_response=response,
logging_obj=logging_obj,
)
+
+ # ===================================
+ # Evals API Handlers
+ # ===================================
+
+ def create_eval_handler(
+ self,
+ url: str,
+ request_body: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["Eval", Coroutine[Any, Any, "Eval"]]:
+ """Create an eval"""
+ if _is_async:
+ return self.async_create_eval_handler(
+ url=url,
+ request_body=request_body,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input=request_body.get("display_name", ""),
+ api_key="",
+ additional_args={
+ "complete_input_dict": request_body,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.post(
+ url=url, headers=headers, json=request_body, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_create_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_create_eval_handler(
+ self,
+ url: str,
+ request_body: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "Eval":
+ """Async create an eval"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input=request_body.get("name", ""),
+ api_key="",
+ additional_args={
+ "complete_input_dict": request_body,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.post(
+ url=url, headers=headers, json=request_body, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_create_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def list_evals_handler(
+ self,
+ url: str,
+ query_params: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["ListEvalsResponse", Coroutine[Any, Any, "ListEvalsResponse"]]:
+ """List evals"""
+ if _is_async:
+ return self.async_list_evals_handler(
+ url=url,
+ query_params=query_params,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "complete_input_dict": query_params,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.get(
+ url=url, headers=headers, params=query_params
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_list_evals_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_list_evals_handler(
+ self,
+ url: str,
+ query_params: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "ListEvalsResponse":
+ """Async list evals"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "complete_input_dict": query_params,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.get(
+ url=url, headers=headers, params=query_params
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_list_evals_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def get_eval_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["Eval", Coroutine[Any, Any, "Eval"]]:
+ """Get an eval"""
+ if _is_async:
+ return self.async_get_eval_handler(
+ url=url,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.get(url=url, headers=headers)
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_get_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_get_eval_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "Eval":
+ """Async get an eval"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.get(
+ url=url, headers=headers
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_get_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def update_eval_handler(
+ self,
+ url: str,
+ request_body: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["Eval", Coroutine[Any, Any, "Eval"]]:
+ """Update an eval"""
+ if _is_async:
+ return self.async_update_eval_handler(
+ url=url,
+ request_body=request_body,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input=request_body.get("display_name", ""),
+ api_key="",
+ additional_args={
+ "complete_input_dict": request_body,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.post(
+ url=url, headers=headers, json=request_body, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_update_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_update_eval_handler(
+ self,
+ url: str,
+ request_body: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "Eval":
+ """Async update an eval"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input=request_body.get("display_name", ""),
+ api_key="",
+ additional_args={
+ "complete_input_dict": request_body,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.post(
+ url=url, headers=headers, json=request_body, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_update_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def delete_eval_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["DeleteEvalResponse", Coroutine[Any, Any, "DeleteEvalResponse"]]:
+ """Delete an eval"""
+ if _is_async:
+ return self.async_delete_eval_handler(
+ url=url,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.delete(
+ url=url, headers=headers, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_delete_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_delete_eval_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "DeleteEvalResponse":
+ """Async delete an eval"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.delete(
+ url=url, headers=headers, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_delete_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def cancel_eval_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["CancelEvalResponse", Coroutine[Any, Any, "CancelEvalResponse"]]:
+ """Cancel an eval"""
+ if _is_async:
+ return self.async_cancel_eval_handler(
+ url=url,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.post(
+ url=url, headers=headers, json={}, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_cancel_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_cancel_eval_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "CancelEvalResponse":
+ """Async cancel an eval"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.post(
+ url=url, headers=headers, json={}, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_cancel_eval_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ # ===================================
+ # Eval Runs API Handlers
+ # ===================================
+
+ def create_run_handler(
+ self,
+ url: str,
+ request_body: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["Run", Coroutine[Any, Any, "Run"]]:
+ """Create a run"""
+ if _is_async:
+ return self.async_create_run_handler(
+ url=url,
+ request_body=request_body,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input=request_body.get("name", ""),
+ api_key="",
+ additional_args={
+ "complete_input_dict": request_body,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.post(
+ url=url, headers=headers, json=request_body, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_create_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_create_run_handler(
+ self,
+ url: str,
+ request_body: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "Run":
+ """Async create a run"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input=request_body.get("name", ""),
+ api_key="",
+ additional_args={
+ "complete_input_dict": request_body,
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.post(
+ url=url, headers=headers, json=request_body, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_create_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def list_runs_handler(
+ self,
+ url: str,
+ query_params: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["ListRunsResponse", Coroutine[Any, Any, "ListRunsResponse"]]:
+ """List runs"""
+ if _is_async:
+ return self.async_list_runs_handler(
+ url=url,
+ query_params=query_params,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ "params": query_params,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.get(
+ url=url, headers=headers, params=query_params
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_list_runs_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_list_runs_handler(
+ self,
+ url: str,
+ query_params: Dict,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "ListRunsResponse":
+ """Async list runs"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ "params": query_params,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.get(
+ url=url, headers=headers, params=query_params
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_list_runs_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def get_run_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["Run", Coroutine[Any, Any, "Run"]]:
+ """Get a run"""
+ if _is_async:
+ return self.async_get_run_handler(
+ url=url,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.get(url=url, headers=headers)
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_get_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_get_run_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "Run":
+ """Async get a run"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.get(
+ url=url, headers=headers
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_get_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def cancel_run_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["CancelRunResponse", Coroutine[Any, Any, "CancelRunResponse"]]:
+ """Cancel a run"""
+ if _is_async:
+ return self.async_cancel_run_handler(
+ url=url,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.post(
+ url=url, headers=headers, json={}, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_cancel_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_cancel_run_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "CancelRunResponse":
+ """Async cancel a run"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.post(
+ url=url, headers=headers, json={}, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_cancel_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def delete_run_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ _is_async: bool = False,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Union["RunDeleteResponse", Coroutine[Any, Any, "RunDeleteResponse"]]:
+ """Delete a run"""
+ if _is_async:
+ return self.async_delete_run_handler(
+ url=url,
+ evals_api_provider_config=evals_api_provider_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ client=client,
+ shared_session=shared_session,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = sync_httpx_client.delete(
+ url=url, headers=headers, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_delete_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_delete_run_handler(
+ self,
+ url: str,
+ evals_api_provider_config: "BaseEvalsAPIConfig",
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ shared_session: Optional["ClientSession"] = None,
+ ) -> "RunDeleteResponse":
+ """Async delete a run"""
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = extra_headers or {}
+
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ try:
+ response = await async_httpx_client.delete(
+ url=url, headers=headers, timeout=timeout
+ )
+ except Exception as e:
+ raise self._handle_error(
+ e=e,
+ provider_config=evals_api_provider_config,
+ )
+
+ return evals_api_provider_config.transform_delete_run_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
diff --git a/litellm/llms/databricks/chat/transformation.py b/litellm/llms/databricks/chat/transformation.py
index 2b7f5dd5995..7c2a9569c58 100644
--- a/litellm/llms/databricks/chat/transformation.py
+++ b/litellm/llms/databricks/chat/transformation.py
@@ -60,6 +60,38 @@ from ...anthropic.chat.transformation import AnthropicConfig
from ...openai_like.chat.transformation import OpenAILikeChatConfig
from ..common_utils import DatabricksBase, DatabricksException
+def _sanitize_empty_content(message_dict: dict[str, Any]) -> None:
+ """
+ Remove or filter content so empty text blocks are not sent.
+ Databricks Model Serving uses Anthropic Messages API spec and rejects empty text blocks.
+ """
+ content = message_dict.get("content")
+ if content is None:
+ message_dict.pop("content", None)
+ return
+ if isinstance(content, str):
+ if not content.strip():
+ message_dict.pop("content")
+ return
+ if isinstance(content, list):
+ if not content:
+ message_dict.pop("content")
+ return
+ filtered = [
+ block
+ for block in content
+ if not (
+ isinstance(block, dict)
+ and block.get("type") == "text"
+ and not (block.get("text") or "").strip()
+ )
+ ]
+ if not filtered:
+ message_dict.pop("content")
+ else:
+ message_dict["content"] = filtered
+
+
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
@@ -298,7 +330,8 @@ class DatabricksConfig(DatabricksBase, OpenAILikeChatConfig, AnthropicConfig):
if "reasoning_effort" in non_default_params and "claude" in model:
optional_params["thinking"] = AnthropicConfig._map_reasoning_effort(
- non_default_params.get("reasoning_effort")
+ reasoning_effort=non_default_params.get("reasoning_effort"),
+ model=model
)
optional_params.pop("reasoning_effort", None)
## handle thinking tokens
@@ -349,6 +382,7 @@ class DatabricksConfig(DatabricksBase, OpenAILikeChatConfig, AnthropicConfig):
# Move message-level cache_control into a content block when content is a string.
if "cache_control" in _message and isinstance(_message.get("content"), str):
_message = self._move_cache_control_into_string_content_block(_message)
+ _sanitize_empty_content(cast(dict[str, Any], _message))
new_messages.append(_message)
if is_async:
diff --git a/ui/litellm-dashboard/src/components/teams.tsx b/litellm/llms/databricks/responses/__init__.py
similarity index 100%
rename from ui/litellm-dashboard/src/components/teams.tsx
rename to litellm/llms/databricks/responses/__init__.py
diff --git a/litellm/llms/databricks/responses/transformation.py b/litellm/llms/databricks/responses/transformation.py
new file mode 100644
index 00000000000..0d9f433bfd2
--- /dev/null
+++ b/litellm/llms/databricks/responses/transformation.py
@@ -0,0 +1,100 @@
+"""
+Databricks Responses API configuration.
+
+Inherits from OpenAIResponsesAPIConfig since Databricks' Responses API
+is compatible with OpenAI's for GPT models.
+
+Reference: https://docs.databricks.com/aws/en/machine-learning/foundation-model-apis/api-reference
+"""
+
+import os
+from typing import TYPE_CHECKING, Any, Dict, Optional, Union
+
+from litellm.llms.databricks.common_utils import DatabricksBase
+from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig
+from litellm.types.llms.openai import ResponseInputParam
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import LlmProviders
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+
+
+class DatabricksResponsesAPIConfig(DatabricksBase, OpenAIResponsesAPIConfig):
+ """
+ Configuration for Databricks Responses API.
+
+ Inherits from OpenAIResponsesAPIConfig since Databricks' Responses API
+ is largely compatible with OpenAI's for GPT models.
+
+ Note: The Responses API on Databricks is only compatible with OpenAI GPT models.
+ """
+
+ @property
+ def custom_llm_provider(self) -> LlmProviders:
+ return LlmProviders.DATABRICKS
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ litellm_params: Optional[GenericLiteLLMParams],
+ ) -> dict:
+ litellm_params = litellm_params or GenericLiteLLMParams()
+ api_key = litellm_params.api_key or os.getenv("DATABRICKS_API_KEY")
+ api_base = litellm_params.api_base or os.getenv("DATABRICKS_API_BASE")
+
+ # Reuse Databricks auth logic (OAuth M2M, PAT, SDK fallback).
+ # custom_endpoint=False allows SDK auth fallback; the appended
+ # /chat/completions suffix is harmless since we discard api_base
+ # here and build the URL separately in get_complete_url().
+ _, headers = self.databricks_validate_environment(
+ api_key=api_key,
+ api_base=api_base,
+ endpoint_type="chat_completions",
+ custom_endpoint=False,
+ headers=headers,
+ )
+
+ headers["Content-Type"] = "application/json"
+ return headers
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ litellm_params: dict,
+ ) -> str:
+ api_base = api_base or os.getenv("DATABRICKS_API_BASE")
+ api_base = self._get_api_base(api_base)
+ api_base = api_base.rstrip("/")
+ return f"{api_base}/responses"
+
+ def transform_responses_api_request(
+ self,
+ model: str,
+ input: Union[str, ResponseInputParam],
+ response_api_optional_request_params: Dict,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ """
+ Transform request for Databricks Responses API.
+
+ Strips the 'databricks/' prefix from model name if present,
+ then delegates to OpenAI's transformation.
+ """
+ # Strip provider prefix if present (e.g., "databricks/databricks-gpt-5-nano" -> "databricks-gpt-5-nano")
+ if model.startswith("databricks/"):
+ model = model[len("databricks/") :]
+
+ return super().transform_responses_api_request(
+ model=model,
+ input=input,
+ response_api_optional_request_params=response_api_optional_request_params,
+ litellm_params=litellm_params,
+ headers=headers,
+ )
diff --git a/litellm/llms/deprecated_providers/palm.py b/litellm/llms/deprecated_providers/palm.py
index 3039222c0e2..657a6fdb229 100644
--- a/litellm/llms/deprecated_providers/palm.py
+++ b/litellm/llms/deprecated_providers/palm.py
@@ -139,7 +139,7 @@ def completion(
)
## COMPLETION CALL
try:
- response = palm.generate_text(prompt=prompt, **inference_params)
+ response = palm.generate_text(prompt=prompt, **inference_params) # type: ignore[attr-defined]
except Exception as e:
raise PalmError(
message=str(e),
diff --git a/litellm/llms/duckduckgo/search/__init__.py b/litellm/llms/duckduckgo/search/__init__.py
new file mode 100644
index 00000000000..c0019637838
--- /dev/null
+++ b/litellm/llms/duckduckgo/search/__init__.py
@@ -0,0 +1,6 @@
+"""
+DuckDuckGo Search API module.
+"""
+from litellm.llms.duckduckgo.search.transformation import DuckDuckGoSearchConfig
+
+__all__ = ["DuckDuckGoSearchConfig"]
diff --git a/litellm/llms/duckduckgo/search/transformation.py b/litellm/llms/duckduckgo/search/transformation.py
new file mode 100644
index 00000000000..509d69041fb
--- /dev/null
+++ b/litellm/llms/duckduckgo/search/transformation.py
@@ -0,0 +1,252 @@
+"""
+Calls DuckDuckGo's Instant Answer API to search the web.
+
+DuckDuckGo API Reference: https://duckduckgo.com/api
+"""
+from typing import Dict, List, Literal, Optional, TypedDict, Union
+from urllib.parse import urlencode
+
+import httpx
+
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.llms.base_llm.search.transformation import (
+ BaseSearchConfig,
+ SearchResponse,
+ SearchResult,
+)
+from litellm.secret_managers.main import get_secret_str
+
+
+class _DuckDuckGoSearchRequestRequired(TypedDict):
+ """Required fields for DuckDuckGo Search API request."""
+ q: str # Required - search query
+
+
+class DuckDuckGoSearchRequest(_DuckDuckGoSearchRequestRequired, total=False):
+ """
+ DuckDuckGo Instant Answer API request format.
+ Based on: https://duckduckgo.com/api
+ """
+ format: str # Optional - output format ('json', 'xml'), default 'json'
+ pretty: int # Optional - pretty print (0 or 1), default 1
+ no_redirect: int # Optional - skip HTTP redirects (0 or 1), default 0
+ no_html: int # Optional - remove HTML from text (0 or 1), default 0
+ skip_disambig: int # Optional - skip disambiguation results (0 or 1), default 0
+
+
+class DuckDuckGoSearchConfig(BaseSearchConfig):
+ DUCKDUCKGO_API_BASE = "https://api.duckduckgo.com"
+
+ @staticmethod
+ def ui_friendly_name() -> str:
+ return "DuckDuckGo"
+
+ def get_http_method(self) -> Literal["GET", "POST"]:
+ """
+ Get HTTP method for search requests.
+ DuckDuckGo Instant Answer API uses GET requests.
+
+ Returns:
+ HTTP method 'GET'
+ """
+ return "GET"
+
+ def validate_environment(
+ self,
+ headers: Dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ **kwargs,
+ ) -> Dict:
+ """
+ Validate environment and return headers.
+ DuckDuckGo Instant Answer API does not require authentication.
+ """
+ # DuckDuckGo API is free and doesn't require API key
+ headers["Content-Type"] = "application/json"
+ return headers
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ optional_params: dict,
+ data: Optional[Union[Dict, List[Dict]]] = None,
+ **kwargs,
+ ) -> str:
+ """
+ Get complete URL for Search endpoint.
+ DuckDuckGo uses query parameters, so we construct the URL with the query.
+ """
+ api_base = api_base or get_secret_str("DUCKDUCKGO_API_BASE") or self.DUCKDUCKGO_API_BASE
+
+ # Build query parameters from the transformed request body
+ if data and isinstance(data, dict) and "_duckduckgo_params" in data:
+ params = data["_duckduckgo_params"]
+ query_string = urlencode(params, doseq=True)
+ return f"{api_base}/?{query_string}"
+
+ return api_base
+
+
+ def transform_search_request(
+ self,
+ query: Union[str, List[str]],
+ optional_params: dict,
+ **kwargs,
+ ) -> Dict:
+ """
+ Transform Search request to DuckDuckGo API format.
+
+ Args:
+ query: Search query (string or list of strings). DuckDuckGo only supports single string queries.
+ optional_params: Optional parameters for the request
+ - max_results: Maximum number of search results (DuckDuckGo API doesn't directly support this, used for filtering)
+ - format: Output format ('json', 'xml')
+ - pretty: Pretty print (0 or 1)
+ - no_redirect: Skip HTTP redirects (0 or 1)
+ - no_html: Remove HTML from text (0 or 1)
+ - skip_disambig: Skip disambiguation results (0 or 1)
+
+ Returns:
+ Dict with typed request data following DuckDuckGoSearchRequest spec
+ """
+ if isinstance(query, list):
+ # DuckDuckGo only supports single string queries
+ query = " ".join(query)
+
+ request_data: DuckDuckGoSearchRequest = {
+ "q": query,
+ "format": "json", # Always use JSON format
+ }
+
+ # Convert to dict before dynamic key assignments
+ result_data = dict(request_data)
+
+ if "max_results" in optional_params:
+ result_data["_max_results"] = optional_params["max_results"]
+
+ # Pass through DuckDuckGo-specific parameters
+ ddg_params = ["pretty", "no_redirect", "no_html", "skip_disambig"]
+ for param in ddg_params:
+ if param in optional_params:
+ result_data[param] = optional_params[param]
+
+ return {
+ "_duckduckgo_params": result_data,
+ }
+
+ def transform_search_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ **kwargs,
+ ) -> SearchResponse:
+ """
+ Transform DuckDuckGo API response to LiteLLM unified SearchResponse format.
+
+ DuckDuckGo → LiteLLM mappings:
+ - RelatedTopics[].Text → SearchResult.title + snippet
+ - RelatedTopics[].FirstURL → SearchResult.url
+ - RelatedTopics[].Text → SearchResult.snippet
+ - No date/last_updated fields in DuckDuckGo response (set to None)
+
+ Args:
+ raw_response: Raw httpx response from DuckDuckGo API
+ logging_obj: Logging object for tracking
+
+ Returns:
+ SearchResponse with standardized format
+ """
+ response_json = raw_response.json()
+
+ # Extract max_results from the request URL params
+ query_params = raw_response.request.url.params if raw_response.request else {}
+ max_results = None
+ if "_max_results" in query_params:
+ try:
+ max_results = int(query_params["_max_results"])
+ except (ValueError, TypeError):
+ pass
+
+ # Transform results to SearchResult objects
+ results = []
+
+ # DuckDuckGo can return results in different fields
+ # Priority: Abstract > Answer > RelatedTopics
+
+ # Check if there's an Abstract with URL
+ if response_json.get("AbstractURL") and response_json.get("AbstractText"):
+ abstract_result = SearchResult(
+ title=response_json.get("Heading", ""),
+ url=response_json.get("AbstractURL", ""),
+ snippet=response_json.get("AbstractText", ""),
+ date=None,
+ last_updated=None,
+ )
+ results.append(abstract_result)
+
+ # Process RelatedTopics
+ related_topics = response_json.get("RelatedTopics", [])
+ for topic in related_topics:
+ # Stop if we've reached max_results
+ if max_results is not None and len(results) >= max_results:
+ break
+
+ if isinstance(topic, dict):
+ # Check if it's a direct result
+ if "FirstURL" in topic and "Text" in topic:
+ text = topic.get("Text", "")
+ url = topic.get("FirstURL", "")
+
+ # Try to split title and snippet
+ if " - " in text:
+ parts = text.split(" - ", 1)
+ title = parts[0]
+ snippet = parts[1] if len(parts) > 1 else text
+ else:
+ title = text[:50] + "..." if len(text) > 50 else text
+ snippet = text
+
+ search_result = SearchResult(
+ title=title,
+ url=url,
+ snippet=snippet,
+ date=None,
+ last_updated=None,
+ )
+ results.append(search_result)
+
+ # Check if it contains nested topics
+ elif "Topics" in topic:
+ nested_topics = topic.get("Topics", [])
+ for nested_topic in nested_topics:
+ # Stop if we've reached max_results
+ if max_results is not None and len(results) >= max_results:
+ break
+
+ if "FirstURL" in nested_topic and "Text" in nested_topic:
+ text = nested_topic.get("Text", "")
+ url = nested_topic.get("FirstURL", "")
+
+ # Try to split title and snippet
+ if " - " in text:
+ parts = text.split(" - ", 1)
+ title = parts[0]
+ snippet = parts[1] if len(parts) > 1 else text
+ else:
+ title = text[:50] + "..." if len(text) > 50 else text
+ snippet = text
+
+ search_result = SearchResult(
+ title=title,
+ url=url,
+ snippet=snippet,
+ date=None,
+ last_updated=None,
+ )
+ results.append(search_result)
+
+ return SearchResponse(
+ results=results,
+ object="search",
+ )
diff --git a/litellm/llms/fireworks_ai/chat/transformation.py b/litellm/llms/fireworks_ai/chat/transformation.py
index 86bcd94450f..7ec32fecc46 100644
--- a/litellm/llms/fireworks_ai/chat/transformation.py
+++ b/litellm/llms/fireworks_ai/chat/transformation.py
@@ -236,6 +236,10 @@ class FireworksAIConfig(OpenAIGPTConfig):
disable_add_transform_inline_image_block=disable_add_transform_inline_image_block,
)
filter_value_from_dict(cast(dict, message), "cache_control")
+ # Remove fields not permitted by FireworksAI that may cause:
+ # "Not permitted, field: 'messages[n].provider_specific_fields'"
+ if isinstance(message, dict) and "provider_specific_fields" in message:
+ cast(dict, message).pop("provider_specific_fields", None)
return messages
diff --git a/litellm/llms/gemini/chat/transformation.py b/litellm/llms/gemini/chat/transformation.py
index f6d075392b2..d5a5ab667a6 100644
--- a/litellm/llms/gemini/chat/transformation.py
+++ b/litellm/llms/gemini/chat/transformation.py
@@ -92,7 +92,7 @@ class GoogleAIStudioGeminiConfig(VertexGeminiConfig):
"parallel_tool_calls",
"web_search_options",
]
- if supports_reasoning(model):
+ if supports_reasoning(model, custom_llm_provider="gemini"):
supported_params.append("reasoning_effort")
supported_params.append("thinking")
if self.is_model_gemini_audio_model(model):
diff --git a/litellm/llms/gemini/files/transformation.py b/litellm/llms/gemini/files/transformation.py
index d9ebf69a97a..cc799cfd6aa 100644
--- a/litellm/llms/gemini/files/transformation.py
+++ b/litellm/llms/gemini/files/transformation.py
@@ -4,7 +4,7 @@ Supports writing files to Google AI Studio Files API.
For vertex ai, check out the vertex_ai/files/handler.py file.
"""
import time
-from typing import List, Optional
+from typing import Any, List, Literal, Optional
import httpx
from openai.types.file_deleted import FileDeleted
@@ -17,6 +17,7 @@ from litellm.llms.base_llm.files.transformation import (
)
from litellm.types.llms.gemini import GeminiCreateFilesResponseObject
from litellm.types.llms.openai import (
+ AllMessageValues,
CreateFileRequest,
HttpxBinaryResponseContent,
OpenAICreateFileRequestOptionalParams,
@@ -35,6 +36,27 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig):
def custom_llm_provider(self) -> LlmProviders:
return LlmProviders.GEMINI
+ def validate_environment(
+ self,
+ headers: dict[Any, Any],
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict[Any, Any],
+ litellm_params: dict[Any, Any],
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict[Any, Any]:
+ """
+ Validate environment and add Gemini API key to headers.
+ Google AI Studio uses x-goog-api-key header for authentication.
+ """
+ resolved_api_key = self.get_api_key(api_key)
+ if not resolved_api_key:
+ raise ValueError("GEMINI_API_KEY is required for Google AI Studio file operations")
+
+ headers["x-goog-api-key"] = resolved_api_key
+ return headers
+
def get_complete_url(
self,
api_base: Optional[str],
@@ -56,10 +78,12 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig):
if not api_base:
raise ValueError("api_base is required")
- if not api_key:
+ # Get API key from multiple sources
+ final_api_key = api_key or litellm_params.get("api_key") or self.get_api_key()
+ if not final_api_key:
raise ValueError("api_key is required")
- url = "{}/{}?key={}".format(api_base, endpoint, api_key)
+ url = "{}/{}?key={}".format(api_base, endpoint, final_api_key)
return url
def get_supported_openai_params(
@@ -180,7 +204,26 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig):
optional_params: dict,
litellm_params: dict,
) -> tuple[str, dict]:
- raise NotImplementedError("GoogleAIStudioFilesHandler does not support file retrieval")
+ """
+ Get the URL to retrieve a file from Google AI Studio.
+
+ We expect file_id to be the URI (e.g. https://generativelanguage.googleapis.com/v1beta/files/...)
+ as returned by the upload response.
+ """
+ api_key = litellm_params.get("api_key") or self.get_api_key()
+ if not api_key:
+ raise ValueError("api_key is required")
+
+ if file_id.startswith("http"):
+ url = "{}?key={}".format(file_id, api_key)
+ else:
+ # Fallback for just file name (files/...)
+ api_base = self.get_api_base(litellm_params.get("api_base")) or "https://generativelanguage.googleapis.com"
+ api_base = api_base.rstrip("/")
+ url = "{}/v1beta/{}?key={}".format(api_base, file_id, api_key)
+
+ # Return empty params dict - API key is already in URL, no query params needed
+ return url, {}
def transform_retrieve_file_response(
self,
@@ -188,7 +231,42 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig):
logging_obj: LiteLLMLoggingObj,
litellm_params: dict,
) -> OpenAIFileObject:
- raise NotImplementedError("GoogleAIStudioFilesHandler does not support file retrieval")
+ """
+ Transform Gemini's file retrieval response into OpenAI-style FileObject
+ """
+ try:
+ response_json = raw_response.json()
+
+ # Map Gemini state to OpenAI status
+ gemini_state = response_json.get("state", "STATE_UNSPECIFIED")
+ # Explicitly type status as the Literal union
+ if gemini_state == "ACTIVE":
+ status: Literal["uploaded", "processed", "error"] = "processed"
+ elif gemini_state == "FAILED":
+ status = "error"
+ else:
+ status = "uploaded"
+
+ return OpenAIFileObject(
+ id=response_json.get("uri", ""),
+ bytes=int(response_json.get("sizeBytes", 0)),
+ created_at=int(
+ time.mktime(
+ time.strptime(
+ response_json["createTime"].replace("Z", "+00:00"),
+ "%Y-%m-%dT%H:%M:%S.%f%z",
+ )
+ )
+ ),
+ filename=response_json.get("displayName", ""),
+ object="file",
+ purpose="user_data",
+ status=status,
+ status_details=str(response_json.get("error", "")) if gemini_state == "FAILED" else None,
+ )
+ except Exception as e:
+ verbose_logger.exception(f"Error parsing file retrieve response: {str(e)}")
+ raise ValueError(f"Error parsing file retrieve response: {str(e)}")
def transform_delete_file_request(
self,
@@ -196,7 +274,41 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig):
optional_params: dict,
litellm_params: dict,
) -> tuple[str, dict]:
- raise NotImplementedError("GoogleAIStudioFilesHandler does not support file deletion")
+ """
+ Transform delete file request for Google AI Studio.
+
+ Args:
+ file_id: The file URI (e.g., "files/abc123" or full URI)
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters containing api_key
+
+ Returns:
+ tuple[str, dict]: (url, params) for the DELETE request
+ """
+ api_base = self.get_api_base(litellm_params.get("api_base"))
+ if not api_base:
+ raise ValueError("api_base is required")
+
+ # Get API key from multiple sources (same pattern as get_complete_url)
+ api_key = litellm_params.get("api_key") or self.get_api_key()
+ if not api_key:
+ raise ValueError("api_key is required")
+
+ # Extract file name from URI if full URI is provided
+ # file_id could be "files/abc123" or "https://generativelanguage.googleapis.com/v1beta/files/abc123"
+ if file_id.startswith("http"):
+ # Extract the file path from full URI
+ file_name = file_id.split("/v1beta/")[-1]
+ else:
+ file_name = file_id if file_id.startswith("files/") else f"files/{file_id}"
+
+ # Construct the delete URL
+ url = f"{api_base}/v1beta/{file_name}"
+
+ # Add API key as header (Google AI Studio uses x-goog-api-key header)
+ params: dict = {}
+
+ return url, params
def transform_delete_file_response(
self,
@@ -204,7 +316,34 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig):
logging_obj: LiteLLMLoggingObj,
litellm_params: dict,
) -> FileDeleted:
- raise NotImplementedError("GoogleAIStudioFilesHandler does not support file deletion")
+ """
+ Transform Gemini's file delete response into OpenAI-style FileDeleted.
+
+ Google AI Studio returns an empty JSON object {} on successful deletion.
+ """
+ try:
+ # Google AI Studio returns {} on successful deletion
+ if raw_response.status_code == 200:
+ # Extract file ID from the request URL if possible
+ file_id = "deleted"
+ if hasattr(raw_response, "request") and raw_response.request:
+ url = str(raw_response.request.url)
+ if "/files/" in url:
+ file_id = url.split("/files/")[-1].split("?")[0]
+ # Add the files/ prefix if not present
+ if not file_id.startswith("files/"):
+ file_id = f"files/{file_id}"
+
+ return FileDeleted(
+ id=file_id,
+ deleted=True,
+ object="file"
+ )
+ else:
+ raise ValueError(f"Failed to delete file: {raw_response.text}")
+ except Exception as e:
+ verbose_logger.exception(f"Error parsing file delete response: {str(e)}")
+ raise ValueError(f"Error parsing file delete response: {str(e)}")
def transform_list_files_request(
self,
diff --git a/litellm/llms/gemini/image_edit/transformation.py b/litellm/llms/gemini/image_edit/transformation.py
index 16541138217..c3ea63ad43b 100644
--- a/litellm/llms/gemini/image_edit/transformation.py
+++ b/litellm/llms/gemini/image_edit/transformation.py
@@ -106,7 +106,10 @@ class GeminiImageEditConfig(BaseImageEditConfig):
generation_config: Dict[str, Any] = {}
if "aspectRatio" in image_edit_optional_request_params:
- generation_config["aspectRatio"] = image_edit_optional_request_params[
+ # Move aspectRatio into imageConfig inside generationConfig
+ if "imageConfig" not in generation_config:
+ generation_config["imageConfig"] = {}
+ generation_config["imageConfig"]["aspectRatio"] = image_edit_optional_request_params[
"aspectRatio"
]
diff --git a/litellm/llms/gemini/image_generation/transformation.py b/litellm/llms/gemini/image_generation/transformation.py
index 63b835df9d0..73aef15e4c7 100644
--- a/litellm/llms/gemini/image_generation/transformation.py
+++ b/litellm/llms/gemini/image_generation/transformation.py
@@ -255,9 +255,11 @@ class GoogleImageGenConfig(BaseImageGenerationConfig):
if "inlineData" in part:
inline_data = part["inlineData"]
if "data" in inline_data:
+ thought_sig = part.get("thoughtSignature")
model_response.data.append(ImageObject(
b64_json=inline_data["data"],
url=None,
+ provider_specific_fields={"thought_signature": thought_sig} if thought_sig else None,
))
# Extract usage metadata for Gemini models
diff --git a/litellm/llms/gigachat/chat/transformation.py b/litellm/llms/gigachat/chat/transformation.py
index 4ce333a1309..f546f356e11 100644
--- a/litellm/llms/gigachat/chat/transformation.py
+++ b/litellm/llms/gigachat/chat/transformation.py
@@ -31,6 +31,16 @@ else:
GIGACHAT_BASE_URL = "https://gigachat.devices.sberbank.ru/api/v1"
+def is_valid_json(value: str) -> bool:
+ """Checks whether the value passed is a valid serialized JSON string"""
+ try:
+ json.loads(value)
+ except json.JSONDecodeError:
+ return False
+ else:
+ return True
+
+
class GigaChatError(BaseLLMException):
"""GigaChat API error."""
@@ -101,7 +111,11 @@ class GigaChatConfig(BaseConfig):
Set up headers with OAuth token.
"""
# Get access token
- credentials = api_key or get_secret_str("GIGACHAT_CREDENTIALS") or get_secret_str("GIGACHAT_API_KEY")
+ credentials = (
+ api_key
+ or get_secret_str("GIGACHAT_CREDENTIALS")
+ or get_secret_str("GIGACHAT_API_KEY")
+ )
access_token = get_access_token(credentials=credentials)
# Store credentials for image uploads
@@ -158,13 +172,10 @@ class GigaChatConfig(BaseConfig):
# Convert tools to functions format
optional_params["functions"] = self._convert_tools_to_functions(value)
elif param == "tool_choice":
- if isinstance(value, dict) and value.get("function"):
- optional_params["function_call"] = {"name": value["function"]["name"]}
- elif value == "auto":
- pass # Default behavior
- elif value == "required":
- # GigaChat doesn't have 'required', handled differently
- pass
+ # Map OpenAI tool_choice to GigaChat function_call
+ mapped_choice = self._map_tool_choice(value)
+ if mapped_choice is not None:
+ optional_params["function_call"] = mapped_choice
elif param == "functions":
optional_params["functions"] = value
elif param == "function_call":
@@ -196,13 +207,57 @@ class GigaChatConfig(BaseConfig):
for tool in tools:
if tool.get("type") == "function":
func = tool.get("function", {})
- functions.append({
- "name": func.get("name", ""),
- "description": func.get("description", ""),
- "parameters": func.get("parameters", {}),
- })
+ functions.append(
+ {
+ "name": func.get("name", ""),
+ "description": func.get("description", ""),
+ "parameters": func.get("parameters", {}),
+ }
+ )
return functions
+ def _map_tool_choice(
+ self, tool_choice: Union[str, dict]
+ ) -> Optional[Union[str, dict]]:
+ """
+ Map OpenAI tool_choice to GigaChat function_call format.
+
+ OpenAI format:
+ - "auto": Call zero, one, or multiple functions (default)
+ - "required": Call one or more functions
+ - "none": Don't call any functions
+ - {"type": "function", "function": {"name": "get_weather"}}: Force specific function
+
+ GigaChat format:
+ - "none": Disable function calls
+ - "auto": Automatic mode (default)
+ - {"name": "get_weather"}: Force specific function
+
+ Args:
+ tool_choice: OpenAI tool_choice value
+
+ Returns:
+ GigaChat function_call value or None
+ """
+ if tool_choice == "none":
+ return "none"
+ elif tool_choice == "auto":
+ return "auto"
+ elif tool_choice == "required":
+ # GigaChat doesn't have a direct "required" equivalent
+ # Use "auto" as the closest behavior
+ return "auto"
+ elif isinstance(tool_choice, dict):
+ # OpenAI format: {"type": "function", "function": {"name": "func_name"}}
+ # GigaChat format: {"name": "func_name"}
+ if tool_choice.get("type") == "function":
+ func_name = tool_choice.get("function", {}).get("name")
+ if func_name:
+ return {"name": func_name}
+
+ # Default to None (don't set function_call)
+ return None
+
def _upload_image(self, image_url: str) -> Optional[str]:
"""
Upload image to GigaChat and return file_id.
@@ -242,8 +297,14 @@ class GigaChatConfig(BaseConfig):
}
# Add optional params
- for key in ["temperature", "top_p", "max_tokens", "stream",
- "repetition_penalty", "profanity_check"]:
+ for key in [
+ "temperature",
+ "top_p",
+ "max_tokens",
+ "stream",
+ "repetition_penalty",
+ "profanity_check",
+ ]:
if key in optional_params:
request_data[key] = optional_params[key]
@@ -275,7 +336,7 @@ class GigaChatConfig(BaseConfig):
elif role == "tool":
message["role"] = "function"
content = message.get("content", "")
- if not isinstance(content, str):
+ if not isinstance(content, str) or not is_valid_json(content):
message["content"] = json.dumps(content, ensure_ascii=False)
# Handle None content
@@ -325,33 +386,7 @@ class GigaChatConfig(BaseConfig):
transformed.append(message)
- # Collapse consecutive user messages
- return self._collapse_user_messages(transformed)
-
- def _collapse_user_messages(self, messages: List[dict]) -> List[dict]:
- """Collapse consecutive user messages into one."""
- collapsed: List[dict] = []
- prev_user_msg: Optional[dict] = None
- content_parts: List[str] = []
-
- for msg in messages:
- if msg.get("role") == "user" and prev_user_msg is not None:
- content_parts.append(msg.get("content", ""))
- else:
- if content_parts and prev_user_msg:
- prev_user_msg["content"] = "\n".join(
- [prev_user_msg.get("content", "")] + content_parts
- )
- content_parts = []
- collapsed.append(msg)
- prev_user_msg = msg if msg.get("role") == "user" else None
-
- if content_parts and prev_user_msg:
- prev_user_msg["content"] = "\n".join(
- [prev_user_msg.get("content", "")] + content_parts
- )
-
- return collapsed
+ return transformed
def transform_response(
self,
@@ -402,14 +437,16 @@ class GigaChatConfig(BaseConfig):
# Convert to tool_calls format
if isinstance(args, dict):
args = json.dumps(args, ensure_ascii=False)
- message_data["tool_calls"] = [{
- "id": f"call_{uuid.uuid4().hex[:24]}",
- "type": "function",
- "function": {
- "name": func_call.get("name", ""),
- "arguments": args,
+ message_data["tool_calls"] = [
+ {
+ "id": f"call_{uuid.uuid4().hex[:24]}",
+ "type": "function",
+ "function": {
+ "name": func_call.get("name", ""),
+ "arguments": args,
+ },
}
- }]
+ ]
message_data.pop("function_call", None)
finish_reason = "tool_calls"
diff --git a/litellm/llms/github_copilot/chat/transformation.py b/litellm/llms/github_copilot/chat/transformation.py
index 50f18cedf9b..be8ad7d0877 100644
--- a/litellm/llms/github_copilot/chat/transformation.py
+++ b/litellm/llms/github_copilot/chat/transformation.py
@@ -1,11 +1,16 @@
-from typing import Any, Optional, Tuple, cast, List
+from typing import List, Optional, Tuple
+
from litellm.exceptions import AuthenticationError
from litellm.llms.openai.openai import OpenAIConfig
from litellm.types.llms.openai import AllMessageValues
from ..authenticator import Authenticator
-from ..common_utils import GetAPIKeyError, GITHUB_COPILOT_API_BASE
+from ..common_utils import (
+ GITHUB_COPILOT_API_BASE,
+ GetAPIKeyError,
+ get_copilot_default_headers,
+)
class GithubCopilotConfig(OpenAIConfig):
@@ -25,9 +30,7 @@ class GithubCopilotConfig(OpenAIConfig):
api_key: Optional[str],
custom_llm_provider: str,
) -> Tuple[Optional[str], Optional[str], str]:
- dynamic_api_base = (
- self.authenticator.get_api_base() or GITHUB_COPILOT_API_BASE
- )
+ dynamic_api_base = self.authenticator.get_api_base() or GITHUB_COPILOT_API_BASE
try:
dynamic_api_key = self.authenticator.get_api_key()
except GetAPIKeyError as e:
@@ -45,14 +48,24 @@ class GithubCopilotConfig(OpenAIConfig):
):
import litellm
- disable_copilot_system_to_assistant = (
- litellm.disable_copilot_system_to_assistant
- )
- if not disable_copilot_system_to_assistant:
- for message in messages:
- if "role" in message and message["role"] == "system":
- cast(Any, message)["role"] = "assistant"
- return messages
+ # Check if system-to-assistant conversion is disabled
+ if litellm.disable_copilot_system_to_assistant:
+ # GitHub Copilot API now supports system prompts for all models (Claude, GPT, etc.)
+ # No conversion needed - just return messages as-is
+ return messages
+
+ # Default behavior: convert system messages to assistant for compatibility
+ transformed_messages = []
+ for message in messages:
+ if message.get("role") == "system":
+ # Convert system message to assistant message
+ transformed_message = message.copy()
+ transformed_message["role"] = "assistant"
+ transformed_messages.append(transformed_message)
+ else:
+ transformed_messages.append(message)
+
+ return transformed_messages
def validate_environment(
self,
@@ -69,6 +82,14 @@ class GithubCopilotConfig(OpenAIConfig):
headers, model, messages, optional_params, litellm_params, api_key, api_base
)
+ # Add Copilot-specific headers (editor-version, user-agent, etc.)
+ try:
+ copilot_api_key = self.authenticator.get_api_key()
+ copilot_headers = get_copilot_default_headers(copilot_api_key)
+ validated_headers = {**copilot_headers, **validated_headers}
+ except GetAPIKeyError:
+ pass # Will be handled later in the request flow
+
# Add X-Initiator header based on message roles
initiator = self._determine_initiator(messages)
validated_headers["X-Initiator"] = initiator
@@ -87,7 +108,7 @@ class GithubCopilotConfig(OpenAIConfig):
For other models, returns standard OpenAI parameters (which may include reasoning_effort for o-series models).
"""
from litellm.utils import supports_reasoning
-
+
# Get base OpenAI parameters
base_params = super().get_supported_openai_params(model)
@@ -118,7 +139,7 @@ class GithubCopilotConfig(OpenAIConfig):
"""
Check if any message contains vision content (images).
Returns True if any message has content with vision-related types, otherwise False.
-
+
Checks for:
- image_url content type (OpenAI format)
- Content items with type 'image_url'
diff --git a/litellm/llms/groq/chat/transformation.py b/litellm/llms/groq/chat/transformation.py
index a75ecd8cc7b..34ea7b03dd9 100644
--- a/litellm/llms/groq/chat/transformation.py
+++ b/litellm/llms/groq/chat/transformation.py
@@ -323,4 +323,12 @@ class GroqChatCompletionStreamingHandler(OpenAIChatCompletionStreamingHandler):
status_code=error.get("code"), message=error.get("message"), body=error
)
+ # Map Groq's 'reasoning' field to LiteLLM's 'reasoning_content' field
+ # Groq returns delta.reasoning, but LiteLLM expects delta.reasoning_content
+ choices = chunk.get("choices", [])
+ for choice in choices:
+ delta = choice.get("delta", {})
+ if "reasoning" in delta:
+ delta["reasoning_content"] = delta.pop("reasoning")
+
return super().chunk_parser(chunk)
diff --git a/litellm/llms/hosted_vllm/chat/transformation.py b/litellm/llms/hosted_vllm/chat/transformation.py
index 1d21490ea31..e955800b947 100644
--- a/litellm/llms/hosted_vllm/chat/transformation.py
+++ b/litellm/llms/hosted_vllm/chat/transformation.py
@@ -23,7 +23,7 @@ from ...openai.chat.gpt_transformation import OpenAIGPTConfig
class HostedVLLMChatConfig(OpenAIGPTConfig):
def get_supported_openai_params(self, model: str) -> List[str]:
params = super().get_supported_openai_params(model)
- params.append("reasoning_effort")
+ params.extend(["reasoning_effort", "thinking"])
return params
def map_openai_params(
@@ -41,6 +41,27 @@ class HostedVLLMChatConfig(OpenAIGPTConfig):
_tools = _remove_strict_from_schema(_tools)
if _tools is not None:
non_default_params["tools"] = _tools
+
+ # Handle thinking parameter - convert Anthropic-style to OpenAI-style reasoning_effort
+ # vLLM is OpenAI-compatible, so it understands reasoning_effort, not thinking
+ # Reference: https://github.com/BerriAI/litellm/issues/19761
+ thinking = non_default_params.pop("thinking", None)
+ if thinking is not None and isinstance(thinking, dict):
+ if thinking.get("type") == "enabled":
+ # Only convert if reasoning_effort not already set
+ if "reasoning_effort" not in non_default_params:
+ budget_tokens = thinking.get("budget_tokens", 0)
+ # Map budget_tokens to reasoning_effort level
+ # Same logic as Anthropic adapter (translate_anthropic_thinking_to_reasoning_effort)
+ if budget_tokens >= 10000:
+ non_default_params["reasoning_effort"] = "high"
+ elif budget_tokens >= 5000:
+ non_default_params["reasoning_effort"] = "medium"
+ elif budget_tokens >= 2000:
+ non_default_params["reasoning_effort"] = "low"
+ else:
+ non_default_params["reasoning_effort"] = "minimal"
+
return super().map_openai_params(
non_default_params, optional_params, model, drop_params
)
diff --git a/litellm/llms/hosted_vllm/embedding/transformation.py b/litellm/llms/hosted_vllm/embedding/transformation.py
new file mode 100644
index 00000000000..9c3e8c6c7cc
--- /dev/null
+++ b/litellm/llms/hosted_vllm/embedding/transformation.py
@@ -0,0 +1,180 @@
+"""
+Hosted VLLM Embedding API Configuration.
+
+This module provides the configuration for hosted VLLM's Embedding API.
+VLLM is OpenAI-compatible and supports embeddings via the /v1/embeddings endpoint.
+
+Docs: https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html
+"""
+
+from typing import TYPE_CHECKING, Any, List, Optional, Union
+
+import httpx
+
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.llms.openai import AllEmbeddingInputValues, AllMessageValues
+from litellm.types.utils import EmbeddingResponse
+from litellm.utils import convert_to_model_response_object
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+
+
+class HostedVLLMEmbeddingError(BaseLLMException):
+ """Exception class for Hosted VLLM Embedding errors."""
+
+ pass
+
+
+class HostedVLLMEmbeddingConfig(BaseEmbeddingConfig):
+ """
+ Configuration for Hosted VLLM's Embedding API.
+
+ Reference: https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html
+ """
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ """
+ Validate environment and set up headers for Hosted VLLM API.
+ """
+ if api_key is None:
+ api_key = get_secret_str("HOSTED_VLLM_API_KEY") or "fake-api-key"
+
+ default_headers = {
+ "Content-Type": "application/json",
+ }
+
+ # Only add Authorization header if api_key is not "fake-api-key"
+ if api_key and api_key != "fake-api-key":
+ default_headers["Authorization"] = f"Bearer {api_key}"
+
+ # Merge with existing headers (user's headers take priority)
+ return {**default_headers, **headers}
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ model: str,
+ optional_params: dict,
+ litellm_params: dict,
+ stream: Optional[bool] = None,
+ ) -> str:
+ """
+ Get the complete URL for Hosted VLLM Embedding API endpoint.
+ """
+ if api_base is None:
+ api_base = get_secret_str("HOSTED_VLLM_API_BASE")
+ if api_base is None:
+ raise ValueError("api_base is required for hosted_vllm embeddings")
+
+ # Remove trailing slashes
+ api_base = api_base.rstrip("/")
+
+ # Ensure the URL ends with /embeddings
+ if not api_base.endswith("/embeddings"):
+ api_base = f"{api_base}/embeddings"
+
+ return api_base
+
+ def transform_embedding_request(
+ self,
+ model: str,
+ input: AllEmbeddingInputValues,
+ optional_params: dict,
+ headers: dict,
+ ) -> dict:
+ """
+ Transform embedding request to Hosted VLLM format (OpenAI-compatible).
+ """
+ # Ensure input is a list
+ if isinstance(input, str):
+ input = [input]
+
+ # Strip 'hosted_vllm/' prefix if present
+ if model.startswith("hosted_vllm/"):
+ model = model.replace("hosted_vllm/", "", 1)
+
+ return {
+ "model": model,
+ "input": input,
+ **optional_params,
+ }
+
+ def transform_embedding_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: EmbeddingResponse,
+ logging_obj: LiteLLMLoggingObj,
+ api_key: Optional[str],
+ request_data: dict,
+ optional_params: dict,
+ litellm_params: dict,
+ ) -> EmbeddingResponse:
+ """
+ Transform embedding response from Hosted VLLM format (OpenAI-compatible).
+ """
+ logging_obj.post_call(original_response=raw_response.text)
+
+ # VLLM returns standard OpenAI-compatible embedding response
+ response_json = raw_response.json()
+
+ return convert_to_model_response_object(
+ response_object=response_json,
+ model_response_object=model_response,
+ response_type="embedding",
+ )
+
+ def get_supported_openai_params(self, model: str) -> list:
+ """
+ Get list of supported OpenAI parameters for Hosted VLLM embeddings.
+ """
+ return [
+ "timeout",
+ "dimensions",
+ "encoding_format",
+ "user",
+ ]
+
+ def map_openai_params(
+ self,
+ non_default_params: dict,
+ optional_params: dict,
+ model: str,
+ drop_params: bool,
+ ) -> dict:
+ """
+ Map OpenAI parameters to Hosted VLLM format.
+ """
+ for param, value in non_default_params.items():
+ if param in self.get_supported_openai_params(model):
+ optional_params[param] = value
+ return optional_params
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]
+ ) -> BaseLLMException:
+ """
+ Get the error class for Hosted VLLM errors.
+ """
+ return HostedVLLMEmbeddingError(
+ message=error_message,
+ status_code=status_code,
+ headers=headers,
+ )
diff --git a/litellm/llms/minimax/chat/transformation.py b/litellm/llms/minimax/chat/transformation.py
index ed80ff8aed1..3e9dc0209f2 100644
--- a/litellm/llms/minimax/chat/transformation.py
+++ b/litellm/llms/minimax/chat/transformation.py
@@ -1,11 +1,12 @@
"""
MiniMax OpenAI transformation config - extends OpenAI chat config for MiniMax's OpenAI-compatible API
"""
-from typing import Optional
+from typing import List, Optional, Tuple
import litellm
from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig
from litellm.secret_managers.main import get_secret_str
+from litellm.types.llms.openai import AllMessageValues, ChatCompletionToolParam
class MinimaxChatConfig(OpenAIGPTConfig):
@@ -73,11 +74,33 @@ class MinimaxChatConfig(OpenAIGPTConfig):
else:
return f"{base_url}/v1/chat/completions"
+ def remove_cache_control_flag_from_messages_and_tools(
+ self,
+ model: str,
+ messages: List[AllMessageValues],
+ tools: Optional[List[ChatCompletionToolParam]] = None,
+ ) -> Tuple[List[AllMessageValues], Optional[List[ChatCompletionToolParam]]]:
+ """
+ Override to preserve cache_control for MiniMax.
+ MiniMax supports cache_control - don't strip it.
+ """
+ # MiniMax supports cache_control, so return messages and tools unchanged
+ return messages, tools
+
def get_supported_openai_params(self, model: str) -> list:
"""
Get supported OpenAI parameters for MiniMax.
- Adds reasoning_split to the list of supported params.
+ Adds reasoning_split and thinking to the list of supported params.
"""
base_params = super().get_supported_openai_params(model=model)
- return base_params + ["reasoning_split"]
+ additional_params = ["reasoning_split"]
+
+ # Add thinking parameter if model supports reasoning
+ try:
+ if litellm.supports_reasoning(model=model, custom_llm_provider="minimax"):
+ additional_params.append("thinking")
+ except Exception:
+ pass
+
+ return base_params + additional_params
diff --git a/litellm/llms/oci/chat/transformation.py b/litellm/llms/oci/chat/transformation.py
index 7af7be2094a..1c22602b483 100644
--- a/litellm/llms/oci/chat/transformation.py
+++ b/litellm/llms/oci/chat/transformation.py
@@ -32,6 +32,7 @@ from litellm.types.llms.oci import (
OCICompletionResponse,
OCIContentPartUnion,
OCIImageContentPart,
+ OCIImageUrl,
OCIMessage,
OCIRoles,
OCIServingMode,
@@ -217,6 +218,7 @@ class OCIChatConfig(BaseConfig):
"parallel_tool_calls": False,
"audio": False,
"web_search_options": False,
+ "response_format": "responseFormat",
}
# Cohere and Gemini use the same parameter mapping as GENERIC
@@ -268,6 +270,9 @@ class OCIChatConfig(BaseConfig):
adapted_params[alias] = value
+ if alias == "responseFormat":
+ adapted_params["response_format"] = value
+
return adapted_params
def _sign_with_oci_signer(
@@ -672,6 +677,36 @@ class OCIChatConfig(BaseConfig):
selected_params["tools"] = adapt_tool_definition_to_oci_standard( # type: ignore[assignment]
selected_params["tools"], vendor # type: ignore[arg-type]
)
+
+ # Transform response_format type to OCI uppercase format
+ if "responseFormat" in selected_params:
+ rf = selected_params["responseFormat"]
+ if isinstance(rf, dict) and "type" in rf:
+ rf_payload = dict(rf)
+ selected_params["responseFormat"] = rf_payload
+
+ response_type = rf_payload["type"]
+ schema_payload: Optional[Any] = None
+
+ if "json_schema" in rf_payload:
+ raw_schema_payload = rf_payload.pop("json_schema")
+ if isinstance(raw_schema_payload, dict):
+ schema_payload = dict(raw_schema_payload)
+ else:
+ schema_payload = raw_schema_payload
+
+ if schema_payload is not None:
+ rf_payload["jsonSchema"] = schema_payload
+
+ if vendor == OCIVendors.COHERE:
+ # Cohere expects lower-case type values
+ rf_payload["type"] = response_type
+ else:
+ format_type = response_type.upper()
+ if format_type == "JSON":
+ format_type = "JSON_OBJECT"
+ rf_payload["type"] = format_type
+
return selected_params
def adapt_messages_to_cohere_standard(self, messages: List[AllMessageValues]) -> List[CohereMessage]:
@@ -803,13 +838,24 @@ class OCIChatConfig(BaseConfig):
if not user_messages:
raise Exception("No user message found for Cohere model")
+ # Extract system messages into preambleOverride
+ system_messages = [msg for msg in messages if msg.get("role") == "system"]
+ preamble_override = None
+ if system_messages:
+ preamble = "\n".join(
+ self._extract_text_content(msg["content"]) for msg in system_messages
+ )
+ if preamble:
+ preamble_override = preamble
# Create Cohere-specific chat request
+ optional_cohere_params = self._get_optional_params(OCIVendors.COHERE, optional_params)
chat_request = CohereChatRequest(
apiFormat="COHERE",
message=self._extract_text_content(user_messages[-1]["content"]),
chatHistory=self.adapt_messages_to_cohere_standard(messages),
- **self._get_optional_params(OCIVendors.COHERE, optional_params)
+ preambleOverride=preamble_override,
+ **optional_cohere_params
)
data = OCICompletionPayload(
@@ -1129,7 +1175,7 @@ def adapt_messages_to_generic_oci_standard_content_message(
image_url = image_url.get("url")
if not isinstance(image_url, str):
raise Exception("Prop `image_url` must be a string or an object with a `url` property")
- new_content.append(OCIImageContentPart(imageUrl=image_url))
+ new_content.append(OCIImageContentPart(imageUrl=OCIImageUrl(url=image_url)))
return OCIMessage(
role=open_ai_to_generic_oci_role_map[role],
diff --git a/litellm/llms/ollama/chat/transformation.py b/litellm/llms/ollama/chat/transformation.py
index 8c98cc54050..bc5aa654aad 100644
--- a/litellm/llms/ollama/chat/transformation.py
+++ b/litellm/llms/ollama/chat/transformation.py
@@ -502,13 +502,12 @@ class OllamaChatCompletionResponseIterator(BaseModelResponseIterator):
reasoning_content: Optional[str] = None
content: Optional[str] = None
if chunk["message"].get("thinking") is not None:
- if self.started_reasoning_content is False:
- reasoning_content = chunk["message"].get("thinking")
- self.started_reasoning_content = True
- elif self.finished_reasoning_content is False:
- reasoning_content = chunk["message"].get("thinking")
- self.finished_reasoning_content = True
+ reasoning_content = chunk["message"].get("thinking")
+ self.started_reasoning_content = True
elif chunk["message"].get("content") is not None:
+ if self.started_reasoning_content and not self.finished_reasoning_content:
+ self.finished_reasoning_content = True
+
message_content = chunk["message"].get("content")
if "" in message_content:
message_content = message_content.replace("", "")
diff --git a/litellm/llms/openai/chat/gpt_5_transformation.py b/litellm/llms/openai/chat/gpt_5_transformation.py
index 3fffa335fdc..05c003c8b7a 100644
--- a/litellm/llms/openai/chat/gpt_5_transformation.py
+++ b/litellm/llms/openai/chat/gpt_5_transformation.py
@@ -19,7 +19,9 @@ class OpenAIGPT5Config(OpenAIGPTConfig):
@classmethod
def is_model_gpt_5_model(cls, model: str) -> bool:
- return "gpt-5" in model
+ # gpt-5-chat* behaves like a regular chat model (supports temperature, etc.)
+ # Don't route it through GPT-5 reasoning-specific parameter restrictions.
+ return "gpt-5" in model and "gpt-5-chat" not in model
@classmethod
def is_model_gpt_5_codex_model(cls, model: str) -> bool:
diff --git a/litellm/llms/openai/chat/gpt_transformation.py b/litellm/llms/openai/chat/gpt_transformation.py
index 6cc09dafc2f..59f52e2b81c 100644
--- a/litellm/llms/openai/chat/gpt_transformation.py
+++ b/litellm/llms/openai/chat/gpt_transformation.py
@@ -20,12 +20,12 @@ from typing import (
import httpx
import litellm
+from litellm.litellm_core_utils.core_helpers import map_finish_reason
from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
_extract_reasoning_content,
_handle_invalid_parallel_tool_calls,
_should_convert_tool_call_to_json_mode,
)
-from litellm.litellm_core_utils.core_helpers import map_finish_reason
from litellm.litellm_core_utils.prompt_templates.common_utils import get_tool_call_names
from litellm.litellm_core_utils.prompt_templates.image_handling import (
async_convert_url_to_base64,
@@ -161,6 +161,7 @@ class OpenAIGPTConfig(BaseLLMModelInfo, BaseConfig):
"web_search_options",
"service_tier",
"safety_identifier",
+ "prompt_cache_key",
] # works across all models
model_specific_params = []
@@ -769,14 +770,39 @@ class OpenAIGPTConfig(BaseLLMModelInfo, BaseConfig):
class OpenAIChatCompletionStreamingHandler(BaseModelResponseIterator):
+ def _map_reasoning_to_reasoning_content(self, choices: list) -> list:
+ """
+ Map 'reasoning' field to 'reasoning_content' field in delta.
+
+ Some OpenAI-compatible providers (e.g., GLM-5, hosted_vllm) return
+ delta.reasoning, but LiteLLM expects delta.reasoning_content.
+
+ Args:
+ choices: List of choice objects from the streaming chunk
+
+ Returns:
+ List of choices with reasoning field mapped to reasoning_content
+ """
+ for choice in choices:
+ delta = choice.get("delta", {})
+ if "reasoning" in delta:
+ delta["reasoning_content"] = delta.pop("reasoning")
+ return choices
+
def chunk_parser(self, chunk: dict) -> ModelResponseStream:
try:
- return ModelResponseStream(
- id=chunk["id"],
- object="chat.completion.chunk",
- created=chunk.get("created"),
- model=chunk.get("model"),
- choices=chunk.get("choices", []),
- )
+ choices = chunk.get("choices", [])
+ choices = self._map_reasoning_to_reasoning_content(choices)
+
+ kwargs = {
+ "id": chunk["id"],
+ "object": "chat.completion.chunk",
+ "created": chunk.get("created"),
+ "model": chunk.get("model"),
+ "choices": choices,
+ }
+ if "usage" in chunk and chunk["usage"] is not None:
+ kwargs["usage"] = chunk["usage"]
+ return ModelResponseStream(**kwargs)
except Exception as e:
raise e
diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.py
index d0ed3f165cc..c406f502b45 100644
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@ -21,7 +21,13 @@ from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.main import stream_chunk_builder
from litellm.types.llms.openai import ChatCompletionToolParam
-from litellm.types.utils import Choices, GenericGuardrailAPIInputs, ModelResponse, ModelResponseStream, StreamingChoices
+from litellm.types.utils import (
+ Choices,
+ GenericGuardrailAPIInputs,
+ ModelResponse,
+ ModelResponseStream,
+ StreamingChoices,
+)
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -80,13 +86,17 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
if tool_calls_to_check:
inputs["tool_calls"] = tool_calls_to_check # type: ignore
if messages:
- inputs["structured_messages"] = (
- messages # pass the openai /chat/completions messages to the guardrail, as-is
- )
+ inputs[
+ "structured_messages"
+ ] = messages # pass the openai /chat/completions messages to the guardrail, as-is
# Pass tools (function definitions) to the guardrail
tools = data.get("tools")
if tools:
inputs["tools"] = tools
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
@@ -297,6 +307,9 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
inputs["images"] = images_to_check
if tool_calls_to_check:
inputs["tool_calls"] = tool_calls_to_check # type: ignore
+ # Include model information from the response if available
+ if hasattr(response, "model") and response.model:
+ inputs["model"] = response.model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
@@ -355,14 +368,17 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
# check if the stream has ended
has_stream_ended = False
for chunk in responses_so_far:
- if chunk.choices[0].finish_reason is not None:
+ if chunk.choices and chunk.choices[0].finish_reason is not None:
has_stream_ended = True
break
if has_stream_ended:
# convert to model response
model_response = cast(
- ModelResponse, stream_chunk_builder(chunks=responses_so_far, logging_obj=litellm_logging_obj)
+ ModelResponse,
+ stream_chunk_builder(
+ chunks=responses_so_far, logging_obj=litellm_logging_obj
+ ),
)
# run process_output_response
await self.process_output_response(
@@ -417,6 +433,13 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
inputs = GenericGuardrailAPIInputs(texts=texts_to_check)
if images_to_check:
inputs["images"] = images_to_check
+ # Include model information from the first response if available
+ if (
+ responses_so_far
+ and hasattr(responses_so_far[0], "model")
+ and responses_so_far[0].model
+ ):
+ inputs["model"] = responses_so_far[0].model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
request_data=request_data,
diff --git a/litellm/llms/openai/common_utils.py b/litellm/llms/openai/common_utils.py
index 8bcecd35232..ce470f04aca 100644
--- a/litellm/llms/openai/common_utils.py
+++ b/litellm/llms/openai/common_utils.py
@@ -15,14 +15,12 @@ if TYPE_CHECKING:
from aiohttp import ClientSession
import litellm
-from litellm._logging import verbose_logger
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.custom_httpx.http_handler import (
_DEFAULT_TTL_FOR_HTTPX_CLIENTS,
AsyncHTTPHandler,
get_ssl_configuration,
)
-from litellm.types.utils import LlmProviders
class OpenAIError(BaseLLMException):
@@ -205,67 +203,30 @@ class BaseOpenAILLM:
if litellm.aclient_session is not None:
return litellm.aclient_session
- # Use the global cached client system to prevent memory leaks (issue #14540)
- # This routes through get_async_httpx_client() which provides TTL-based caching
- from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
+ # Get unified SSL configuration
+ ssl_config = get_ssl_configuration()
- try:
- # Get SSL config and include in params for proper cache key
- ssl_config = get_ssl_configuration()
- params = {"ssl_verify": ssl_config} if ssl_config is not None else {}
- params["disable_aiohttp_transport"] = litellm.disable_aiohttp_transport
-
- # Get a cached AsyncHTTPHandler which manages the httpx.AsyncClient
- cached_handler = get_async_httpx_client(
- llm_provider=LlmProviders.OPENAI, # Cache key includes provider
- params=params, # Include SSL config in cache key
+ return httpx.AsyncClient(
+ verify=ssl_config,
+ transport=AsyncHTTPHandler._create_async_transport(
+ ssl_context=ssl_config
+ if isinstance(ssl_config, ssl.SSLContext)
+ else None,
+ ssl_verify=ssl_config if isinstance(ssl_config, bool) else None,
shared_session=shared_session,
- )
- # Return the underlying httpx client from the handler
- return cached_handler.client
- except (ImportError, AttributeError, KeyError) as e:
- # Fallback to creating a client directly if caching system unavailable
- # This preserves backwards compatibility
- verbose_logger.debug(
- f"Client caching unavailable ({type(e).__name__}), using direct client creation"
- )
- ssl_config = get_ssl_configuration()
- return httpx.AsyncClient(
- verify=ssl_config,
- transport=AsyncHTTPHandler._create_async_transport(
- ssl_context=ssl_config
- if isinstance(ssl_config, ssl.SSLContext)
- else None,
- ssl_verify=ssl_config if isinstance(ssl_config, bool) else None,
- shared_session=shared_session,
- ),
- follow_redirects=True,
- )
+ ),
+ follow_redirects=True,
+ )
@staticmethod
def _get_sync_http_client() -> Optional[httpx.Client]:
if litellm.client_session is not None:
return litellm.client_session
- # Use the global cached client system to prevent memory leaks (issue #14540)
- from litellm.llms.custom_httpx.http_handler import _get_httpx_client
+ # Get unified SSL configuration
+ ssl_config = get_ssl_configuration()
- try:
- # Get SSL config and include in params for proper cache key
- ssl_config = get_ssl_configuration()
- params = {"ssl_verify": ssl_config} if ssl_config is not None else None
-
- # Get a cached HTTPHandler which manages the httpx.Client
- cached_handler = _get_httpx_client(params=params)
- # Return the underlying httpx client from the handler
- return cached_handler.client
- except (ImportError, AttributeError, KeyError) as e:
- # Fallback to creating a client directly if caching system unavailable
- verbose_logger.debug(
- f"Client caching unavailable ({type(e).__name__}), using direct client creation"
- )
- ssl_config = get_ssl_configuration()
- return httpx.Client(
- verify=ssl_config,
- follow_redirects=True,
- )
+ return httpx.Client(
+ verify=ssl_config,
+ follow_redirects=True,
+ )
diff --git a/litellm/llms/openai/completion/guardrail_translation/handler.py b/litellm/llms/openai/completion/guardrail_translation/handler.py
index 73d08cfead4..1f8c6159da0 100644
--- a/litellm/llms/openai/completion/guardrail_translation/handler.py
+++ b/litellm/llms/openai/completion/guardrail_translation/handler.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Optional
from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -53,8 +54,13 @@ class OpenAITextCompletionHandler(BaseTranslation):
if isinstance(prompt, str):
# Single string prompt
+ inputs = GenericGuardrailAPIInputs(texts=[prompt])
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [prompt]},
+ inputs=inputs,
request_data=data,
input_type="request",
logging_obj=litellm_logging_obj,
@@ -80,8 +86,13 @@ class OpenAITextCompletionHandler(BaseTranslation):
text_indices.append(idx)
if texts_to_check:
+ inputs = GenericGuardrailAPIInputs(texts=texts_to_check)
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": texts_to_check},
+ inputs=inputs,
request_data=data,
input_type="request",
logging_obj=litellm_logging_obj,
@@ -154,8 +165,12 @@ class OpenAITextCompletionHandler(BaseTranslation):
if user_metadata:
request_data["litellm_metadata"] = user_metadata
+ inputs = GenericGuardrailAPIInputs(texts=texts_to_check)
+ # Include model information from the response if available
+ if hasattr(response, "model") and response.model:
+ inputs["model"] = response.model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": texts_to_check},
+ inputs=inputs,
request_data=request_data,
input_type="response",
logging_obj=litellm_logging_obj,
diff --git a/litellm/llms/openai/embeddings/guardrail_translation/__init__.py b/litellm/llms/openai/embeddings/guardrail_translation/__init__.py
new file mode 100644
index 00000000000..a60662282ca
--- /dev/null
+++ b/litellm/llms/openai/embeddings/guardrail_translation/__init__.py
@@ -0,0 +1,13 @@
+"""OpenAI Embeddings handler for Unified Guardrails."""
+
+from litellm.llms.openai.embeddings.guardrail_translation.handler import (
+ OpenAIEmbeddingsHandler,
+)
+from litellm.types.utils import CallTypes
+
+guardrail_translation_mappings = {
+ CallTypes.embedding: OpenAIEmbeddingsHandler,
+ CallTypes.aembedding: OpenAIEmbeddingsHandler,
+}
+
+__all__ = ["guardrail_translation_mappings", "OpenAIEmbeddingsHandler"]
diff --git a/litellm/llms/openai/embeddings/guardrail_translation/handler.py b/litellm/llms/openai/embeddings/guardrail_translation/handler.py
new file mode 100644
index 00000000000..7458020e109
--- /dev/null
+++ b/litellm/llms/openai/embeddings/guardrail_translation/handler.py
@@ -0,0 +1,179 @@
+"""
+OpenAI Embeddings Handler for Unified Guardrails
+
+This module provides guardrail translation support for OpenAI's embeddings endpoint.
+The handler processes the 'input' parameter for guardrails.
+"""
+
+from typing import TYPE_CHECKING, Any, List, Optional, Union
+
+from litellm._logging import verbose_proxy_logger
+from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.utils import GenericGuardrailAPIInputs
+
+if TYPE_CHECKING:
+ from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.types.utils import EmbeddingResponse
+
+
+class OpenAIEmbeddingsHandler(BaseTranslation):
+ """
+ Handler for processing OpenAI embeddings requests with guardrails.
+
+ This class provides methods to:
+ 1. Process input text (pre-call hook)
+ 2. Process output response (post-call hook) - embeddings don't typically need output guardrails
+
+ The handler specifically processes the 'input' parameter which can be:
+ - A single string
+ - A list of strings (for batch embeddings)
+ - A list of integers (token IDs - not processed by guardrails)
+ - A list of lists of integers (batch token IDs - not processed by guardrails)
+ """
+
+ async def process_input_messages(
+ self,
+ data: dict,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional[Any] = None,
+ ) -> Any:
+ """
+ Process input text by applying guardrails to text content.
+
+ Args:
+ data: Request data dictionary containing 'input' parameter
+ guardrail_to_apply: The guardrail instance to apply
+ litellm_logging_obj: Optional logging object
+
+ Returns:
+ Modified data with guardrails applied to input
+ """
+ input_data = data.get("input")
+ if input_data is None:
+ verbose_proxy_logger.debug(
+ "OpenAI Embeddings: No input found in request data"
+ )
+ return data
+
+ if isinstance(input_data, str):
+ data = await self._process_string_input(
+ data, input_data, guardrail_to_apply, litellm_logging_obj
+ )
+ elif isinstance(input_data, list):
+ data = await self._process_list_input(
+ data, input_data, guardrail_to_apply, litellm_logging_obj
+ )
+ else:
+ verbose_proxy_logger.warning(
+ "OpenAI Embeddings: Unexpected input type: %s. Expected string or list.",
+ type(input_data),
+ )
+
+ return data
+
+ async def _process_string_input(
+ self,
+ data: dict,
+ input_data: str,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional[Any],
+ ) -> dict:
+ """Process a single string input through the guardrail."""
+ inputs = GenericGuardrailAPIInputs(texts=[input_data])
+ if model := data.get("model"):
+ inputs["model"] = model
+
+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data=data,
+ input_type="request",
+ logging_obj=litellm_logging_obj,
+ )
+
+ if guardrailed_texts := guardrailed_inputs.get("texts"):
+ data["input"] = guardrailed_texts[0]
+ verbose_proxy_logger.debug(
+ "OpenAI Embeddings: Applied guardrail to string input. "
+ "Original length: %d, New length: %d",
+ len(input_data),
+ len(data["input"]),
+ )
+
+ return data
+
+ async def _process_list_input(
+ self,
+ data: dict,
+ input_data: List[Union[str, int, List[int]]],
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional[Any],
+ ) -> dict:
+ """Process a list input through the guardrail (if it contains strings)."""
+ if len(input_data) == 0:
+ return data
+
+ first_item = input_data[0]
+
+ # Skip non-text inputs (token IDs)
+ if isinstance(first_item, (int, list)):
+ verbose_proxy_logger.debug(
+ "OpenAI Embeddings: Input is token IDs, skipping guardrail processing"
+ )
+ return data
+
+ if not isinstance(first_item, str):
+ verbose_proxy_logger.warning(
+ "OpenAI Embeddings: Unexpected input list item type: %s",
+ type(first_item),
+ )
+ return data
+
+ # List of strings - apply guardrail
+ inputs = GenericGuardrailAPIInputs(texts=input_data) # type: ignore
+ if model := data.get("model"):
+ inputs["model"] = model
+
+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data=data,
+ input_type="request",
+ logging_obj=litellm_logging_obj,
+ )
+
+ if guardrailed_texts := guardrailed_inputs.get("texts"):
+ data["input"] = guardrailed_texts
+ verbose_proxy_logger.debug(
+ "OpenAI Embeddings: Applied guardrail to %d inputs",
+ len(guardrailed_texts),
+ )
+
+ return data
+
+ async def process_output_response(
+ self,
+ response: "EmbeddingResponse",
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional[Any] = None,
+ user_api_key_dict: Optional[Any] = None,
+ ) -> Any:
+ """
+ Process output response - embeddings responses contain vectors, not text.
+
+ For embeddings, the output is numerical vectors, so there's typically
+ no text content to apply guardrails to. This method is a no-op but
+ is included for interface consistency.
+
+ Args:
+ response: Embedding response object
+ guardrail_to_apply: The guardrail instance to apply
+ litellm_logging_obj: Optional logging object
+ user_api_key_dict: User API key metadata
+
+ Returns:
+ Unmodified response (embeddings don't have text output to guard)
+ """
+ verbose_proxy_logger.debug(
+ "OpenAI Embeddings: Output response processing skipped - "
+ "embeddings contain vectors, not text"
+ )
+ return response
diff --git a/litellm/llms/openai/evals/__init__.py b/litellm/llms/openai/evals/__init__.py
new file mode 100644
index 00000000000..b04d27622bb
--- /dev/null
+++ b/litellm/llms/openai/evals/__init__.py
@@ -0,0 +1,7 @@
+"""
+OpenAI Evals API configuration
+"""
+
+from .transformation import OpenAIEvalsConfig
+
+__all__ = ["OpenAIEvalsConfig"]
diff --git a/litellm/llms/openai/evals/transformation.py b/litellm/llms/openai/evals/transformation.py
new file mode 100644
index 00000000000..c24dbf8637a
--- /dev/null
+++ b/litellm/llms/openai/evals/transformation.py
@@ -0,0 +1,426 @@
+"""
+OpenAI Evals API configuration and transformations
+"""
+
+from typing import Any, Dict, Optional, Tuple
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.llms.base_llm.evals.transformation import (
+ BaseEvalsAPIConfig,
+ LiteLLMLoggingObj,
+)
+from litellm.types.llms.openai_evals import (
+ CancelEvalResponse,
+ CancelRunResponse,
+ CreateEvalRequest,
+ CreateRunRequest,
+ DeleteEvalResponse,
+ Eval,
+ ListEvalsParams,
+ ListEvalsResponse,
+ ListRunsParams,
+ ListRunsResponse,
+ Run,
+ RunDeleteResponse,
+ UpdateEvalRequest,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import LlmProviders
+
+
+class OpenAIEvalsConfig(BaseEvalsAPIConfig):
+ """OpenAI-specific Evals API configuration"""
+
+ @property
+ def custom_llm_provider(self) -> LlmProviders:
+ return LlmProviders.OPENAI
+
+ def validate_environment(
+ self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]
+ ) -> dict:
+ """Add OpenAI-specific headers"""
+ import litellm
+ from litellm.secret_managers.main import get_secret_str
+
+ # Get API key following OpenAI pattern
+ api_key = None
+ if litellm_params:
+ api_key = litellm_params.api_key
+
+ api_key = (
+ api_key
+ or litellm.api_key
+ or litellm.openai_key
+ or get_secret_str("OPENAI_API_KEY")
+ )
+
+ if not api_key:
+ raise ValueError("OPENAI_API_KEY is required for Evals API")
+
+ # Add required headers
+ headers["Authorization"] = f"Bearer {api_key}"
+ headers["Content-Type"] = "application/json"
+
+ return headers
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ endpoint: str,
+ eval_id: Optional[str] = None,
+ ) -> str:
+ """Get complete URL for OpenAI Evals API"""
+ if api_base is None:
+ api_base = "https://api.openai.com"
+
+ if eval_id:
+ return f"{api_base}/v1/evals/{eval_id}"
+ return f"{api_base}/v1/{endpoint}"
+
+ def transform_create_eval_request(
+ self,
+ create_request: CreateEvalRequest,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ """Transform create eval request for OpenAI"""
+ verbose_logger.debug("Transforming create eval request: %s", create_request)
+
+ # OpenAI expects the request body directly
+ request_body = {k: v for k, v in create_request.items() if v is not None}
+
+ return request_body
+
+ def transform_create_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Eval:
+ """Transform OpenAI response to Eval object"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming create eval response: %s", response_json)
+
+ return Eval(**response_json)
+
+ def transform_list_evals_request(
+ self,
+ list_params: ListEvalsParams,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """Transform list evals request for OpenAI"""
+ api_base = "https://api.openai.com"
+ if litellm_params and litellm_params.api_base:
+ api_base = litellm_params.api_base
+
+ url = self.get_complete_url(api_base=api_base, endpoint="evals")
+
+ # Build query parameters
+ query_params: Dict[str, Any] = {}
+ if "limit" in list_params and list_params["limit"]:
+ query_params["limit"] = list_params["limit"]
+ if "after" in list_params and list_params["after"]:
+ query_params["after"] = list_params["after"]
+ if "before" in list_params and list_params["before"]:
+ query_params["before"] = list_params["before"]
+ if "order" in list_params and list_params["order"]:
+ query_params["order"] = list_params["order"]
+ if "order_by" in list_params and list_params["order_by"]:
+ query_params["order_by"] = list_params["order_by"]
+
+ verbose_logger.debug(
+ "List evals request made to OpenAI Evals endpoint with params: %s",
+ query_params,
+ )
+
+ return url, query_params
+
+ def transform_list_evals_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> ListEvalsResponse:
+ """Transform OpenAI response to ListEvalsResponse"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming list evals response: %s", response_json)
+
+ return ListEvalsResponse(**response_json)
+
+ def transform_get_eval_request(
+ self,
+ eval_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """Transform get eval request for OpenAI"""
+ url = self.get_complete_url(
+ api_base=api_base, endpoint="evals", eval_id=eval_id
+ )
+
+ verbose_logger.debug("Get eval request - URL: %s", url)
+
+ return url, headers
+
+ def transform_get_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Eval:
+ """Transform OpenAI response to Eval object"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming get eval response: %s", response_json)
+
+ return Eval(**response_json)
+
+ def transform_update_eval_request(
+ self,
+ eval_id: str,
+ update_request: UpdateEvalRequest,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """Transform update eval request for OpenAI"""
+ url = self.get_complete_url(
+ api_base=api_base, endpoint="evals", eval_id=eval_id
+ )
+
+ # Build request body
+ request_body = {k: v for k, v in update_request.items() if v is not None}
+
+ verbose_logger.debug(
+ "Update eval request - URL: %s, body: %s", url, request_body
+ )
+
+ return url, headers, request_body
+
+ def transform_update_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Eval:
+ """Transform OpenAI response to Eval object"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming update eval response: %s", response_json)
+
+ return Eval(**response_json)
+
+ def transform_delete_eval_request(
+ self,
+ eval_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """Transform delete eval request for OpenAI"""
+ url = self.get_complete_url(
+ api_base=api_base, endpoint="evals", eval_id=eval_id
+ )
+
+ verbose_logger.debug("Delete eval request - URL: %s", url)
+
+ return url, headers
+
+ def transform_delete_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> DeleteEvalResponse:
+ """Transform OpenAI response to DeleteEvalResponse"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming delete eval response: %s", response_json)
+
+ return DeleteEvalResponse(**response_json)
+
+ def transform_cancel_eval_request(
+ self,
+ eval_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """Transform cancel eval request for OpenAI"""
+ url = f"{self.get_complete_url(api_base=api_base, endpoint='evals', eval_id=eval_id)}/cancel"
+
+ # Empty body for cancel request
+ request_body: Dict[str, Any] = {}
+
+ verbose_logger.debug("Cancel eval request - URL: %s", url)
+
+ return url, headers, request_body
+
+ def transform_cancel_eval_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> CancelEvalResponse:
+ """Transform OpenAI response to CancelEvalResponse"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming cancel eval response: %s", response_json)
+
+ return CancelEvalResponse(**response_json)
+
+ # Run API Transformations
+ def transform_create_run_request(
+ self,
+ eval_id: str,
+ create_request: CreateRunRequest,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """Transform create run request for OpenAI"""
+ api_base = "https://api.openai.com"
+ if litellm_params and litellm_params.api_base:
+ api_base = litellm_params.api_base
+
+ url = f"{api_base}/v1/evals/{eval_id}/runs"
+
+ # Build request body
+ request_body = {k: v for k, v in create_request.items() if v is not None}
+
+ verbose_logger.debug(
+ "Create run request - URL: %s, body: %s", url, request_body
+ )
+
+ return url, request_body
+
+ def transform_create_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Run:
+ """Transform OpenAI response to Run object"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming create run response: %s", response_json)
+
+ return Run(**response_json)
+
+ def transform_list_runs_request(
+ self,
+ eval_id: str,
+ list_params: ListRunsParams,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """Transform list runs request for OpenAI"""
+ api_base = "https://api.openai.com"
+ if litellm_params and litellm_params.api_base:
+ api_base = litellm_params.api_base
+
+ url = f"{api_base}/v1/evals/{eval_id}/runs"
+
+ # Build query parameters
+ query_params: Dict[str, Any] = {}
+ if "limit" in list_params and list_params["limit"]:
+ query_params["limit"] = list_params["limit"]
+ if "after" in list_params and list_params["after"]:
+ query_params["after"] = list_params["after"]
+ if "before" in list_params and list_params["before"]:
+ query_params["before"] = list_params["before"]
+ if "order" in list_params and list_params["order"]:
+ query_params["order"] = list_params["order"]
+
+ verbose_logger.debug(
+ "List runs request made to OpenAI Evals endpoint with params: %s",
+ query_params,
+ )
+
+ return url, query_params
+
+ def transform_list_runs_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> ListRunsResponse:
+ """Transform OpenAI response to ListRunsResponse"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming list runs response: %s", response_json)
+
+ return ListRunsResponse(**response_json)
+
+ def transform_get_run_request(
+ self,
+ eval_id: str,
+ run_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """Transform get run request for OpenAI"""
+ url = f"{api_base}/v1/evals/{eval_id}/runs/{run_id}"
+
+ verbose_logger.debug("Get run request - URL: %s", url)
+
+ return url, headers
+
+ def transform_get_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> Run:
+ """Transform OpenAI response to Run object"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming get run response: %s", response_json)
+
+ return Run(**response_json)
+
+ def transform_cancel_run_request(
+ self,
+ eval_id: str,
+ run_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """Transform cancel run request for OpenAI"""
+ url = f"{api_base}/v1/evals/{eval_id}/runs/{run_id}/cancel"
+
+ # Empty body for cancel request
+ request_body: Dict[str, Any] = {}
+
+ verbose_logger.debug("Cancel run request - URL: %s", url)
+
+ return url, headers, request_body
+
+ def transform_cancel_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> CancelRunResponse:
+ """Transform OpenAI response to CancelRunResponse"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming cancel run response: %s", response_json)
+
+ return CancelRunResponse(**response_json)
+
+ def transform_delete_run_request(
+ self,
+ eval_id: str,
+ run_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict, Dict]:
+ """Transform delete run request for OpenAI"""
+ url = f"{api_base}/v1/evals/{eval_id}/runs/{run_id}"
+
+ # Empty body for delete request
+ request_body: Dict[str, Any] = {}
+
+ verbose_logger.debug("Delete run request - URL: %s", url)
+
+ return url, headers, request_body
+
+ def transform_delete_run_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> RunDeleteResponse:
+ """Transform OpenAI response to RunDeleteResponse"""
+ response_json = raw_response.json()
+ verbose_logger.debug("Transforming delete run response: %s", response_json)
+
+ return RunDeleteResponse(**response_json)
diff --git a/litellm/llms/openai/image_generation/guardrail_translation/handler.py b/litellm/llms/openai/image_generation/guardrail_translation/handler.py
index 842a64b1878..e6340ba4705 100644
--- a/litellm/llms/openai/image_generation/guardrail_translation/handler.py
+++ b/litellm/llms/openai/image_generation/guardrail_translation/handler.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Optional
from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -52,8 +53,13 @@ class OpenAIImageGenerationHandler(BaseTranslation):
# Apply guardrail to the prompt
if isinstance(prompt, str):
+ inputs = GenericGuardrailAPIInputs(texts=[prompt])
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [prompt]},
+ inputs=inputs,
request_data=data,
input_type="request",
logging_obj=litellm_logging_obj,
diff --git a/litellm/llms/openai/openai.py b/litellm/llms/openai/openai.py
index 4d623097478..da87852dff5 100644
--- a/litellm/llms/openai/openai.py
+++ b/litellm/llms/openai/openai.py
@@ -501,6 +501,88 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
else:
raise e
+ async def _call_agentic_completion_hooks_openai(
+ self,
+ response: Any,
+ model: str,
+ messages: List[Dict],
+ optional_params: Dict,
+ logging_obj: LiteLLMLoggingObj,
+ stream: bool,
+ litellm_params: Dict,
+ ) -> Optional[Any]:
+ """
+ Call agentic completion hooks for all custom loggers (OpenAI Chat Completions API).
+
+ 1. Call async_should_run_chat_completion_agentic_loop to check if agentic loop is needed
+ 2. If yes, call async_run_chat_completion_agentic_loop to execute the loop
+
+ Returns the response from agentic loop, or None if no hook runs.
+ """
+ from litellm._logging import verbose_logger
+ from litellm.integrations.custom_logger import CustomLogger
+
+ callbacks = litellm.callbacks + (
+ logging_obj.dynamic_success_callbacks or []
+ )
+ # Avoid logging full callback objects to prevent leaking sensitive data
+ verbose_logger.debug(
+ "LiteLLM.AgenticHooks: callbacks_count=%s", len(callbacks)
+ )
+ tools = optional_params.get("tools", [])
+ # Avoid logging full tools payloads; they may contain sensitive parameters
+ verbose_logger.debug(
+ "LiteLLM.AgenticHooks: tools_count=%s", len(tools) if isinstance(tools, list) else 1 if tools else 0
+ )
+ # Get custom_llm_provider from litellm_params
+ custom_llm_provider = litellm_params.get("custom_llm_provider", "openai")
+
+ for callback in callbacks:
+ try:
+ if isinstance(callback, CustomLogger):
+ # Check if the callback has the chat completion agentic loop methods
+ if not hasattr(callback, 'async_should_run_chat_completion_agentic_loop'):
+ continue
+
+ # First: Check if agentic loop should run (using chat completion method)
+ should_run, tool_calls = (
+ await callback.async_should_run_chat_completion_agentic_loop(
+ response=response,
+ model=model,
+ messages=messages,
+ tools=tools,
+ stream=stream,
+ custom_llm_provider=custom_llm_provider,
+ kwargs=litellm_params,
+ )
+ )
+
+ if should_run:
+ # Second: Execute agentic loop
+ kwargs_with_provider = litellm_params.copy() if litellm_params else {}
+ kwargs_with_provider["custom_llm_provider"] = custom_llm_provider
+
+ # For OpenAI Chat Completions, use the chat completion agentic loop method
+ agentic_response = await callback.async_run_chat_completion_agentic_loop(
+ tools=tool_calls,
+ model=model,
+ messages=messages,
+ response=response,
+ optional_params=optional_params,
+ logging_obj=logging_obj,
+ stream=stream,
+ kwargs=kwargs_with_provider,
+ )
+ # First hook that runs agentic loop wins
+ return agentic_response
+
+ except Exception as e:
+ verbose_logger.exception(
+ f"LiteLLM.AgenticHookError: Exception in agentic completion hooks for OpenAI: {str(e)}"
+ )
+
+ return None
+
def mock_streaming(
self,
response: ModelResponse,
@@ -844,7 +926,6 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
logging_obj=logging_obj,
)
stringified_response = response.model_dump()
-
logging_obj.post_call(
input=data["messages"],
api_key=api_key,
@@ -859,6 +940,20 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
_response_headers=headers,
)
+ # Call agentic completion hooks (e.g., for websearch_interception)
+ agentic_response = await self._call_agentic_completion_hooks_openai(
+ response=final_response_obj,
+ model=model,
+ messages=messages,
+ optional_params=optional_params,
+ logging_obj=logging_obj,
+ stream=False,
+ litellm_params=litellm_params,
+ )
+
+ if agentic_response is not None:
+ final_response_obj = agentic_response
+
if fake_stream is True:
return self.mock_streaming(
response=cast(ModelResponse, final_response_obj),
@@ -1923,10 +2018,10 @@ class OpenAIBatchesAPI(BaseLLM):
self,
cancel_batch_data: CancelBatchRequest,
openai_client: AsyncOpenAI,
- ) -> Batch:
+ ) -> LiteLLMBatch:
verbose_logger.debug("async cancelling batch, args= %s", cancel_batch_data)
response = await openai_client.batches.cancel(**cancel_batch_data)
- return response
+ return LiteLLMBatch(**response.model_dump())
def cancel_batch(
self,
@@ -1962,8 +2057,13 @@ class OpenAIBatchesAPI(BaseLLM):
cancel_batch_data=cancel_batch_data, openai_client=openai_client
)
+ # At this point, openai_client is guaranteed to be a sync OpenAI client
+ if not isinstance(openai_client, OpenAI):
+ raise ValueError(
+ "OpenAI client is not an instance of OpenAI. Make sure you passed a sync OpenAI client."
+ )
response = openai_client.batches.cancel(**cancel_batch_data)
- return response
+ return LiteLLMBatch(**response.model_dump())
async def alist_batches(
self,
diff --git a/litellm/llms/openai/realtime/handler.py b/litellm/llms/openai/realtime/handler.py
index fd04ac4d458..ef9cc43c3e1 100644
--- a/litellm/llms/openai/realtime/handler.py
+++ b/litellm/llms/openai/realtime/handler.py
@@ -16,6 +16,62 @@ from ..openai import OpenAIChatCompletion
class OpenAIRealtime(OpenAIChatCompletion):
+ """
+ Base handler for OpenAI-compatible realtime WebSocket connections.
+
+ Subclasses can override template methods to customize:
+ - _get_default_api_base(): Default API base URL
+ - _get_additional_headers(): Extra headers beyond Authorization
+ - _get_ssl_config(): SSL configuration for WebSocket connection
+ """
+
+ def _get_default_api_base(self) -> str:
+ """
+ Get the default API base URL for this provider.
+ Override this in subclasses to set provider-specific defaults.
+ """
+ return "https://api.openai.com/"
+
+ def _get_additional_headers(self, api_key: str) -> dict:
+ """
+ Get additional headers beyond Authorization.
+ Override this in subclasses to customize headers (e.g., remove OpenAI-Beta).
+
+ Args:
+ api_key: API key for authentication
+
+ Returns:
+ Dictionary of additional headers
+ """
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "OpenAI-Beta": "realtime=v1",
+ }
+
+ def _get_ssl_config(self, url: str) -> Any:
+ """
+ Get SSL configuration for WebSocket connection.
+ Override this in subclasses to customize SSL behavior.
+
+ Args:
+ url: WebSocket URL (ws:// or wss://)
+
+ Returns:
+ SSL configuration (None, True, or SSLContext)
+ """
+ if url.startswith("ws://"):
+ return None
+
+ # Use the shared SSL context which respects custom CA certs and SSL settings
+ ssl_config = get_shared_realtime_ssl_context()
+
+ # If ssl_config is False (ssl_verify=False), websockets library needs True instead
+ # to establish connection without verification (False would fail)
+ if ssl_config is False:
+ return True
+
+ return ssl_config
+
def _construct_url(self, api_base: str, query_params: RealtimeQueryParams) -> str:
"""
Construct the backend websocket URL with all query parameters (including 'model').
@@ -45,8 +101,9 @@ class OpenAIRealtime(OpenAIChatCompletion):
):
import websockets
from websockets.asyncio.client import ClientConnection
+
if api_base is None:
- api_base = "https://api.openai.com/"
+ api_base = self._get_default_api_base()
if api_key is None:
raise ValueError("api_key is required for OpenAI realtime calls")
@@ -56,30 +113,27 @@ class OpenAIRealtime(OpenAIChatCompletion):
url = self._construct_url(api_base, query_params)
try:
- # Only use SSL context for secure websocket connections (wss://)
- # websockets library doesn't accept ssl argument for ws:// URIs
- ssl_context = None if url.startswith("ws://") else get_shared_realtime_ssl_context()
+ # Get provider-specific SSL configuration
+ ssl_config = self._get_ssl_config(url)
+
+ # Get provider-specific headers
+ headers = self._get_additional_headers(api_key)
+
# Log a masked request preview consistent with other endpoints.
logging_obj.pre_call(
input=None,
api_key=api_key,
additional_args={
"api_base": url,
- "headers": {
- "Authorization": f"Bearer {api_key}",
- "OpenAI-Beta": "realtime=v1",
- },
+ "headers": headers,
"complete_input_dict": {"query_params": query_params},
},
)
async with websockets.connect( # type: ignore
url,
- additional_headers={
- "Authorization": f"Bearer {api_key}", # type: ignore
- "OpenAI-Beta": "realtime=v1",
- },
+ additional_headers=headers, # type: ignore
max_size=REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES,
- ssl=ssl_context,
+ ssl=ssl_config,
) as backend_ws:
realtime_streaming = RealTimeStreaming(
websocket, cast(ClientConnection, backend_ws), logging_obj
diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py
index 9b8f15c7623..ad3d4c932d4 100644
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@ -105,6 +105,10 @@ class OpenAIResponsesHandler(BaseTranslation):
inputs["tools"] = tools_to_check
if structured_messages:
inputs["structured_messages"] = structured_messages # type: ignore
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
@@ -150,6 +154,10 @@ class OpenAIResponsesHandler(BaseTranslation):
inputs["tools"] = tools_to_check
if structured_messages:
inputs["structured_messages"] = structured_messages # type: ignore
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
request_data=data,
@@ -311,9 +319,7 @@ class OpenAIResponsesHandler(BaseTranslation):
return response
if not response_output:
- verbose_proxy_logger.debug(
- "OpenAI Responses API: Empty output in response"
- )
+ verbose_proxy_logger.debug("OpenAI Responses API: Empty output in response")
return response
# Step 1: Extract all text content and tool calls from response output
@@ -344,6 +350,14 @@ class OpenAIResponsesHandler(BaseTranslation):
inputs["images"] = images_to_check
if tool_calls_to_check:
inputs["tool_calls"] = tool_calls_to_check
+ # Include model information from the response if available
+ response_model = None
+ if isinstance(response, dict):
+ response_model = response.get("model")
+ elif hasattr(response, "model"):
+ response_model = getattr(response, "model", None)
+ if response_model:
+ inputs["model"] = response_model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
@@ -388,12 +402,15 @@ class OpenAIResponsesHandler(BaseTranslation):
tool_calls = model_response_stream.choices[0].delta.tool_calls
if tool_calls:
+ inputs = GenericGuardrailAPIInputs()
+ inputs["tool_calls"] = cast(
+ List[ChatCompletionToolCallChunk], tool_calls
+ )
+ # Include model information if available
+ if hasattr(model_response_stream, "model") and model_response_stream.model:
+ inputs["model"] = model_response_stream.model
_guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={
- "tool_calls": cast(
- List[ChatCompletionToolCallChunk], tool_calls
- )
- },
+ inputs=inputs,
request_data={},
input_type="response",
logging_obj=litellm_logging_obj,
@@ -408,29 +425,42 @@ class OpenAIResponsesHandler(BaseTranslation):
handle_raw_dict_callback=None,
)
- tool_calls = model_response_choices[0].message.tool_calls
- text = model_response_choices[0].message.content
- guardrail_inputs = GenericGuardrailAPIInputs()
- if text:
- guardrail_inputs["texts"] = [text]
- if tool_calls:
- guardrail_inputs["tool_calls"] = cast(
- List[ChatCompletionToolCallChunk], tool_calls
- )
- if tool_calls:
- _guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs=guardrail_inputs,
- request_data={},
- input_type="response",
- logging_obj=litellm_logging_obj,
- )
- return responses_so_far
+ if model_response_choices:
+ tool_calls = model_response_choices[0].message.tool_calls
+ text = model_response_choices[0].message.content
+ guardrail_inputs = GenericGuardrailAPIInputs()
+ if text:
+ guardrail_inputs["texts"] = [text]
+ if tool_calls:
+ guardrail_inputs["tool_calls"] = cast(
+ List[ChatCompletionToolCallChunk], tool_calls
+ )
+ # Include model information from the response if available
+ response_model = final_chunk.get("response", {}).get("model")
+ if response_model:
+ guardrail_inputs["model"] = response_model
+ if tool_calls or text:
+ _guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=guardrail_inputs,
+ request_data={},
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ return responses_so_far
+ else:
+ verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices")
# model_response_stream = OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(final_chunk)
# tool_calls = model_response_stream.choices[0].tool_calls
# convert openai response to model response
string_so_far = self.get_streaming_string_so_far(responses_so_far)
+ inputs = GenericGuardrailAPIInputs(texts=[string_so_far])
+ # Try to get model from the final chunk if available
+ if isinstance(final_chunk, dict):
+ response_model = final_chunk.get("response", {}).get("model") if isinstance(final_chunk.get("response"), dict) else None
+ if response_model:
+ inputs["model"] = response_model
_guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [string_so_far]},
+ inputs=inputs,
request_data={},
input_type="response",
logging_obj=litellm_logging_obj,
@@ -484,11 +514,9 @@ class OpenAIResponsesHandler(BaseTranslation):
# Check if it's an OutputText with text
if isinstance(content_item, OutputText):
if content_item.text:
-
return True
elif isinstance(content_item, dict):
if content_item.get("text"):
-
return True
return False
diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py
index cc2439b431a..3e089682097 100644
--- a/litellm/llms/openai/responses/transformation.py
+++ b/litellm/llms/openai/responses/transformation.py
@@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional, Union, cast, get_type_hin
import httpx
from openai.types.responses import ResponseReasoningItem
-from pydantic import BaseModel
+from pydantic import BaseModel, ValidationError
import litellm
from litellm._logging import verbose_logger
@@ -240,25 +240,26 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
event_pydantic_model = OpenAIResponsesAPIConfig.get_event_model_class(
event_type=event_type
)
- # Defensive: Some OpenAI-compatible providers may send `error.code: null`.
- # Pydantic will raise a ValidationError when it expects a string but gets None.
- # Coalesce a None `error.code` to a stable default string so streaming
- # iteration does not crash (see issue report). This keeps behavior similar
- # to previous fixes (coalesce before validation) and lets higher-level
- # handlers still receive an `ErrorEvent` object.
+ # Some OpenAI-compatible providers send error.code: null; coalesce so validation succeeds.
try:
error_obj = parsed_chunk.get("error")
if isinstance(error_obj, dict) and error_obj.get("code") is None:
- # Preserve other fields, but ensure `code` is a non-null string
parsed_chunk = dict(parsed_chunk)
parsed_chunk["error"] = dict(error_obj)
parsed_chunk["error"]["code"] = "unknown_error"
except Exception:
- # If anything unexpected happens here, fall back to attempting
- # instantiation and let higher-level handlers manage errors.
verbose_logger.debug("Failed to coalesce error.code in parsed_chunk")
- return event_pydantic_model(**parsed_chunk)
+ try:
+ return event_pydantic_model(**parsed_chunk)
+ except ValidationError:
+ verbose_logger.debug(
+ "Pydantic validation failed for %s with chunk %s, "
+ "falling back to model_construct",
+ event_pydantic_model.__name__,
+ parsed_chunk,
+ )
+ return event_pydantic_model.model_construct(**parsed_chunk)
@staticmethod
def get_event_model_class(event_type: str) -> Any:
@@ -307,6 +308,10 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
ResponsesAPIStreamEvents.MCP_CALL_FAILED: MCPCallFailedEvent,
ResponsesAPIStreamEvents.IMAGE_GENERATION_PARTIAL_IMAGE: ImageGenerationPartialImageEvent,
ResponsesAPIStreamEvents.ERROR: ErrorEvent,
+ # Shell tool events: passthrough as GenericEvent so payload is preserved
+ ResponsesAPIStreamEvents.SHELL_CALL_IN_PROGRESS: GenericEvent,
+ ResponsesAPIStreamEvents.SHELL_CALL_COMPLETED: GenericEvent,
+ ResponsesAPIStreamEvents.SHELL_CALL_OUTPUT: GenericEvent,
}
model_class = event_models.get(cast(ResponsesAPIStreamEvents, event_type))
diff --git a/litellm/llms/openai/speech/guardrail_translation/handler.py b/litellm/llms/openai/speech/guardrail_translation/handler.py
index 4c2f71477be..e6796fbac2a 100644
--- a/litellm/llms/openai/speech/guardrail_translation/handler.py
+++ b/litellm/llms/openai/speech/guardrail_translation/handler.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Optional
from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -50,8 +51,13 @@ class OpenAITextToSpeechHandler(BaseTranslation):
return data
if isinstance(input_text, str):
+ inputs = GenericGuardrailAPIInputs(texts=[input_text])
+ # Include model information if available (voice model)
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [input_text]},
+ inputs=inputs,
request_data=data,
input_type="request",
logging_obj=litellm_logging_obj,
diff --git a/litellm/llms/openai/transcriptions/guardrail_translation/handler.py b/litellm/llms/openai/transcriptions/guardrail_translation/handler.py
index ac416f42c81..3d76a21c389 100644
--- a/litellm/llms/openai/transcriptions/guardrail_translation/handler.py
+++ b/litellm/llms/openai/transcriptions/guardrail_translation/handler.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Optional
from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -88,8 +89,12 @@ class OpenAIAudioTranscriptionHandler(BaseTranslation):
if user_metadata:
request_data["litellm_metadata"] = user_metadata
+ inputs = GenericGuardrailAPIInputs(texts=[original_text])
+ # Include model information from the response if available
+ if hasattr(response, "model") and response.model:
+ inputs["model"] = response.model
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [original_text]},
+ inputs=inputs,
request_data=request_data,
input_type="response",
logging_obj=litellm_logging_obj,
diff --git a/litellm/llms/openai/videos/transformation.py b/litellm/llms/openai/videos/transformation.py
index 3073b22e1ca..0dd7940a92e 100644
--- a/litellm/llms/openai/videos/transformation.py
+++ b/litellm/llms/openai/videos/transformation.py
@@ -269,26 +269,27 @@ class OpenAIVideoConfig(BaseVideoConfig):
) -> Tuple[str, Dict]:
"""
Transform the video list request for OpenAI API.
-
+
OpenAI API expects the following request:
- GET /v1/videos
"""
# Use the api_base directly for video list
url = api_base
-
+
# Prepare query parameters
params = {}
if after is not None:
- params["after"] = after
+ # Decode the wrapped video ID back to the original provider ID
+ params["after"] = extract_original_video_id(after)
if limit is not None:
params["limit"] = str(limit)
if order is not None:
params["order"] = order
-
+
# Add any extra query parameters
if extra_query:
params.update(extra_query)
-
+
return url, params
def transform_video_list_response(
@@ -296,18 +297,40 @@ class OpenAIVideoConfig(BaseVideoConfig):
raw_response: httpx.Response,
logging_obj: LiteLLMLoggingObj,
custom_llm_provider: Optional[str] = None,
- ) -> Dict[str,str]:
+ ) -> Dict[str, str]:
response_data = raw_response.json()
-
+
if custom_llm_provider and "data" in response_data:
for video_obj in response_data.get("data", []):
if isinstance(video_obj, dict) and "id" in video_obj:
video_obj["id"] = encode_video_id_with_provider(
- video_obj["id"],
- custom_llm_provider,
- video_obj.get("model")
+ video_obj["id"],
+ custom_llm_provider,
+ video_obj.get("model"),
)
-
+
+ # Encode pagination cursor IDs so they remain consistent
+ # with the wrapped data[].id format
+ data_list = response_data.get("data", [])
+ if response_data.get("first_id"):
+ first_model = None
+ if data_list and isinstance(data_list[0], dict):
+ first_model = data_list[0].get("model")
+ response_data["first_id"] = encode_video_id_with_provider(
+ response_data["first_id"],
+ custom_llm_provider,
+ first_model,
+ )
+ if response_data.get("last_id"):
+ last_model = None
+ if data_list and isinstance(data_list[-1], dict):
+ last_model = data_list[-1].get("model")
+ response_data["last_id"] = encode_video_id_with_provider(
+ response_data["last_id"],
+ custom_llm_provider,
+ last_model,
+ )
+
return response_data
def transform_video_delete_request(
diff --git a/litellm/llms/openai_like/dynamic_config.py b/litellm/llms/openai_like/dynamic_config.py
index 1e7866bebbe..a2ce6b9a531 100644
--- a/litellm/llms/openai_like/dynamic_config.py
+++ b/litellm/llms/openai_like/dynamic_config.py
@@ -4,6 +4,7 @@ Dynamic configuration class generator for JSON-based providers.
from typing import Any, Coroutine, List, Literal, Optional, Tuple, Union, overload
+from litellm._logging import verbose_logger
from litellm.litellm_core_utils.prompt_templates.common_utils import (
handle_messages_with_content_list_to_str_conversion,
)
@@ -96,8 +97,27 @@ def create_config_class(provider: SimpleProviderConfig):
return api_base
def get_supported_openai_params(self, model: str) -> list:
- """Get supported OpenAI params from base class"""
- return super().get_supported_openai_params(model=model)
+ """Get supported OpenAI params, excluding tool-related params for models
+ that don't support function calling."""
+ from litellm.utils import supports_function_calling
+
+ supported_params = super().get_supported_openai_params(model=model)
+
+ _supports_fc = supports_function_calling(
+ model=model, custom_llm_provider=provider.slug
+ )
+
+ if not _supports_fc:
+ tool_params = ["tools", "tool_choice", "function_call", "functions", "parallel_tool_calls"]
+ for param in tool_params:
+ if param in supported_params:
+ supported_params.remove(param)
+ verbose_logger.debug(
+ f"Model {model} on provider {provider.slug} does not support "
+ f"function calling — removed tool-related params from supported params."
+ )
+
+ return supported_params
def map_openai_params(
self,
diff --git a/litellm/llms/openai_like/embedding/handler.py b/litellm/llms/openai_like/embedding/handler.py
index 95a4aa854ad..d0d26d5959f 100644
--- a/litellm/llms/openai_like/embedding/handler.py
+++ b/litellm/llms/openai_like/embedding/handler.py
@@ -105,7 +105,8 @@ class OpenAILikeEmbeddingHandler(OpenAILikeBase):
custom_endpoint=custom_endpoint,
)
model = model
- data = {"model": model, "input": input, **optional_params}
+ filtered_optional_params = {k: v for k, v in optional_params.items() if v not in (None, '')}
+ data = {"model": model, "input": input, **filtered_optional_params}
## LOGGING
logging_obj.pre_call(
diff --git a/litellm/llms/openai_like/providers.json b/litellm/llms/openai_like/providers.json
index b4f9cbe42de..1b1b1c2f8cc 100644
--- a/litellm/llms/openai_like/providers.json
+++ b/litellm/llms/openai_like/providers.json
@@ -26,6 +26,10 @@
"max_completion_tokens": "max_tokens"
}
},
+ "scaleway": {
+ "base_url": "https://api.scaleway.ai/v1",
+ "api_key_env": "SCW_SECRET_KEY"
+ },
"synthetic": {
"base_url": "https://api.synthetic.new/openai/v1",
"api_key_env": "SYNTHETIC_API_KEY",
diff --git a/litellm/llms/openrouter/chat/transformation.py b/litellm/llms/openrouter/chat/transformation.py
index b5610852fd2..e3770dbbf49 100644
--- a/litellm/llms/openrouter/chat/transformation.py
+++ b/litellm/llms/openrouter/chat/transformation.py
@@ -26,6 +26,9 @@ class CacheControlSupportedModels(str, Enum):
"""Models that support cache_control in content blocks."""
CLAUDE = "claude"
GEMINI = "gemini"
+ MINIMAX = "minimax"
+ GLM = "glm"
+ ZAI = "z-ai"
class OpenrouterConfig(OpenAIGPTConfig):
@@ -39,6 +42,7 @@ class OpenrouterConfig(OpenAIGPTConfig):
model=model, custom_llm_provider="openrouter"
) or litellm.supports_reasoning(model=model):
supported_params.append("reasoning_effort")
+ supported_params.append("thinking")
except Exception:
pass
return list(dict.fromkeys(supported_params))
diff --git a/litellm/llms/pass_through/guardrail_translation/handler.py b/litellm/llms/pass_through/guardrail_translation/handler.py
index c0979e37e66..40433d53413 100644
--- a/litellm/llms/pass_through/guardrail_translation/handler.py
+++ b/litellm/llms/pass_through/guardrail_translation/handler.py
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any, List, Optional
from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.proxy._types import PassThroughGuardrailSettings
+from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -118,8 +119,13 @@ class PassThroughEndpointHandler(BaseTranslation):
return data
# Apply guardrail (pass-through doesn't modify the text, just checks it)
+ inputs = GenericGuardrailAPIInputs(texts=[text_to_check])
+ # Include model information if available
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
_guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [text_to_check]},
+ inputs=inputs,
request_data=data,
input_type="request",
logging_obj=litellm_logging_obj,
@@ -178,8 +184,13 @@ class PassThroughEndpointHandler(BaseTranslation):
request_data["litellm_metadata"] = user_metadata
# Apply guardrail (pass-through doesn't modify the text, just checks it)
+ inputs = GenericGuardrailAPIInputs(texts=[text_to_check])
+ # Include model information from the response if available
+ response_model = response.get("model") if isinstance(response, dict) else None
+ if response_model:
+ inputs["model"] = response_model
_guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs={"texts": [text_to_check]},
+ inputs=inputs,
request_data=request_data,
input_type="response",
logging_obj=litellm_logging_obj,
diff --git a/litellm/llms/perplexity/responses/__init__.py b/litellm/llms/perplexity/responses/__init__.py
new file mode 100644
index 00000000000..3285a472113
--- /dev/null
+++ b/litellm/llms/perplexity/responses/__init__.py
@@ -0,0 +1,7 @@
+"""
+Perplexity Agent API (Responses API) module
+"""
+
+from .transformation import PerplexityResponsesConfig
+
+__all__ = ["PerplexityResponsesConfig"]
diff --git a/litellm/llms/perplexity/responses/transformation.py b/litellm/llms/perplexity/responses/transformation.py
new file mode 100644
index 00000000000..6d2ed51600c
--- /dev/null
+++ b/litellm/llms/perplexity/responses/transformation.py
@@ -0,0 +1,492 @@
+"""
+Transformation logic for Perplexity Agent API (Responses API)
+
+This module handles the translation between OpenAI's Responses API format
+and Perplexity's Responses API format, which supports:
+- Third-party model access (OpenAI, Anthropic, Google, xAI, etc.)
+- Presets for optimized configurations
+- Web search and URL fetching tools
+- Reasoning effort control
+- Instructions parameter for system-level guidance
+"""
+
+from typing import Any, Dict, List, Optional, Union
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.llms.openai import (
+ ResponseAPIUsage,
+ ResponseInputParam,
+ ResponsesAPIOptionalRequestParams,
+ ResponsesAPIResponse,
+ ResponsesAPIStreamingResponse,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import LlmProviders
+
+
+class PerplexityResponsesConfig(OpenAIResponsesAPIConfig):
+ """
+ Configuration for Perplexity Agent API (Responses API)
+
+
+ Reference: https://docs.perplexity.ai/docs/agent-api/overview
+ """
+
+ @property
+ def custom_llm_provider(self) -> LlmProviders:
+ return LlmProviders.PERPLEXITY
+
+ def get_supported_openai_params(self, model: str) -> list:
+ """
+ Perplexity Responses API supports a different set of parameters
+
+ Ref: https://docs.perplexity.ai/api-reference/responses-post
+ Params aligned with response-echo fields and Open Responses spec.
+ """
+ return [
+ "max_output_tokens",
+ "stream",
+ "temperature",
+ "top_p",
+ "tools",
+ "reasoning",
+ "preset",
+ "instructions",
+ "models", # Model fallback support
+ "tool_choice",
+ "parallel_tool_calls",
+ "max_tool_calls",
+ "text",
+ "previous_response_id",
+ "store",
+ "background",
+ "truncation",
+ "metadata",
+ "safety_identifier",
+ "user",
+ "stream_options",
+ "top_logprobs",
+ "prompt_cache_key",
+ "frequency_penalty",
+ "presence_penalty",
+ "service_tier",
+ ]
+
+ def validate_environment(
+ self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]
+ ) -> dict:
+ """Validate environment and set up headers"""
+ # Get API key from environment
+ api_key = get_secret_str("PERPLEXITYAI_API_KEY") or get_secret_str(
+ "PERPLEXITY_API_KEY"
+ )
+
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ headers["Content-Type"] = "application/json"
+
+ return headers
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ litellm_params: dict,
+ ) -> str:
+ """Get the complete URL for the Perplexity Responses API"""
+ if api_base is None:
+ api_base = (
+ get_secret_str("PERPLEXITY_API_BASE") or "https://api.perplexity.ai"
+ )
+
+ # Ensure api_base doesn't end with a slash
+ api_base = api_base.rstrip("/")
+
+ # Add the responses endpoint
+ return f"{api_base}/v1/responses"
+
+ def map_openai_params( # noqa: PLR0915
+ self,
+ response_api_optional_params: ResponsesAPIOptionalRequestParams,
+ model: str,
+ drop_params: bool,
+ ) -> Dict:
+ """
+ Map OpenAI Responses API parameters to Perplexity format
+
+ Key differences:
+ - Supports 'preset' parameter for predefined configurations
+ - Supports 'instructions' parameter for system-level guidance
+ - Tools are specified differently (web_search, fetch_url)
+ """
+ mapped_params: Dict[str, Any] = {}
+
+ # Map standard parameters
+ if response_api_optional_params.get("max_output_tokens"):
+ mapped_params["max_output_tokens"] = response_api_optional_params[
+ "max_output_tokens"
+ ]
+
+ if response_api_optional_params.get("temperature"):
+ mapped_params["temperature"] = response_api_optional_params["temperature"]
+
+ if response_api_optional_params.get("top_p"):
+ mapped_params["top_p"] = response_api_optional_params["top_p"]
+
+ if response_api_optional_params.get("stream"):
+ mapped_params["stream"] = response_api_optional_params["stream"]
+
+ if response_api_optional_params.get("stream_options"):
+ mapped_params["stream_options"] = response_api_optional_params[
+ "stream_options"
+ ]
+
+ # Map Perplexity-specific parameters (using .get() with Any dict access)
+ preset = response_api_optional_params.get("preset") # type: ignore
+ if preset:
+ mapped_params["preset"] = preset
+
+ instructions = response_api_optional_params.get("instructions") # type: ignore
+ if instructions:
+ mapped_params["instructions"] = instructions
+
+ if response_api_optional_params.get("reasoning"):
+ mapped_params["reasoning"] = response_api_optional_params["reasoning"]
+
+ tools = response_api_optional_params.get("tools")
+ if tools:
+ # Convert tools to list of dicts for transformation
+ tools_list = [dict(tool) if hasattr(tool, "__dict__") else tool for tool in tools] # type: ignore
+ mapped_params["tools"] = self._transform_tools(tools_list) # type: ignore
+
+ # Tool control
+ if response_api_optional_params.get("tool_choice"):
+ mapped_params["tool_choice"] = response_api_optional_params["tool_choice"]
+ if response_api_optional_params.get("parallel_tool_calls") is not None:
+ mapped_params["parallel_tool_calls"] = response_api_optional_params[
+ "parallel_tool_calls"
+ ]
+ if response_api_optional_params.get("max_tool_calls"):
+ mapped_params["max_tool_calls"] = response_api_optional_params[
+ "max_tool_calls"
+ ]
+
+ # Structured outputs
+ text_param = response_api_optional_params.get("text")
+ if text_param:
+ mapped_params["text"] = text_param
+
+ # Conversation continuity
+ if response_api_optional_params.get("previous_response_id"):
+ mapped_params["previous_response_id"] = response_api_optional_params[
+ "previous_response_id"
+ ]
+
+ # Storage and lifecycle
+ if response_api_optional_params.get("store") is not None:
+ mapped_params["store"] = response_api_optional_params["store"]
+ if response_api_optional_params.get("background") is not None:
+ mapped_params["background"] = response_api_optional_params["background"]
+ if response_api_optional_params.get("truncation"):
+ mapped_params["truncation"] = response_api_optional_params["truncation"]
+
+ # Metadata
+ if response_api_optional_params.get("metadata"):
+ mapped_params["metadata"] = response_api_optional_params["metadata"]
+ if response_api_optional_params.get("safety_identifier"):
+ mapped_params["safety_identifier"] = response_api_optional_params[
+ "safety_identifier"
+ ]
+ if response_api_optional_params.get("user"):
+ mapped_params["user"] = response_api_optional_params["user"]
+
+ # Additional
+ if response_api_optional_params.get("top_logprobs") is not None:
+ mapped_params["top_logprobs"] = response_api_optional_params["top_logprobs"]
+ if response_api_optional_params.get("prompt_cache_key"):
+ mapped_params["prompt_cache_key"] = response_api_optional_params[
+ "prompt_cache_key"
+ ]
+ if response_api_optional_params.get("frequency_penalty") is not None:
+ mapped_params["frequency_penalty"] = response_api_optional_params[
+ "frequency_penalty" # type: ignore[typeddict-item]
+ ]
+ if response_api_optional_params.get("presence_penalty") is not None:
+ mapped_params["presence_penalty"] = response_api_optional_params[
+ "presence_penalty" # type: ignore[typeddict-item]
+ ]
+ if response_api_optional_params.get("service_tier"):
+ mapped_params["service_tier"] = response_api_optional_params["service_tier"]
+
+ return mapped_params
+
+ def _transform_tools(self, tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """
+ Transform tools to Perplexity format.
+
+ Perplexity supports (per public OpenAPI spec):
+ - web_search: Performs web searches
+ - fetch_url: Fetches content from URLs
+ - function: Function Calling
+ """
+ perplexity_tools = []
+
+ for tool in tools:
+ if isinstance(tool, dict):
+ tool_type = tool.get("type", "")
+
+ # Direct Perplexity tool format
+ if tool_type in ["web_search", "fetch_url"]:
+ perplexity_tools.append(tool)
+
+ # Function tools: Perplexity supports them natively
+ elif tool_type == "function":
+ perplexity_tools.append(tool)
+
+ return perplexity_tools
+
+ def transform_responses_api_request(
+ self,
+ model: str,
+ input: Union[str, ResponseInputParam],
+ response_api_optional_request_params: Dict,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ """
+ Transform request to Perplexity Responses API format
+ """
+ # Check if the model is a preset (format: preset/preset-name)
+ if model.startswith("preset/"):
+ preset_name = model.replace("preset/", "")
+ data = {
+ "preset": preset_name,
+ "input": self._format_input(input),
+ }
+ # Check if preset is explicitly provided in params
+ elif response_api_optional_request_params.get("preset"):
+ data = {
+ "preset": response_api_optional_request_params.pop("preset"),
+ "input": self._format_input(input),
+ }
+ else:
+ # Full request format for third-party models
+ data = {
+ "model": model,
+ "input": self._format_input(input),
+ }
+
+ # Add all optional parameters
+ for key, value in response_api_optional_request_params.items():
+ data[key] = value
+
+ return data
+
+ def _format_input(
+ self, input: Union[str, ResponseInputParam]
+ ) -> Union[str, List[Dict[str, Any]]]:
+ """
+ Format input for Perplexity Responses API
+
+ The API accepts either:
+ - A simple string for single-turn queries
+ - An array of message objects for multi-turn conversations
+ """
+ if isinstance(input, str):
+ return input
+
+ # Handle ResponseInputParam format
+ if isinstance(input, list):
+ formatted_messages = []
+ for item in input:
+ if isinstance(item, dict):
+ formatted_message = {
+ "type": "message",
+ "role": item.get("role"),
+ "content": item.get("content", ""),
+ }
+ formatted_messages.append(formatted_message)
+ return formatted_messages
+
+ return str(input)
+
+ def transform_response_api_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> ResponsesAPIResponse:
+ """
+ Transform Perplexity Responses API response to OpenAI Responses API format
+ """
+ try:
+ raw_response_json = raw_response.json()
+ except Exception as e:
+ raise BaseLLMException(
+ status_code=raw_response.status_code,
+ message=f"Failed to parse response: {str(e)}",
+ )
+
+ # Check for error status
+ status = raw_response_json.get("status")
+ if status == "failed":
+ error = raw_response_json.get("error", {})
+ error_message = error.get("message", "Unknown error")
+ raise BaseLLMException(
+ status_code=raw_response.status_code,
+ message=error_message,
+ )
+
+ # Transform usage to handle Perplexity's cost structure
+ usage_data = raw_response_json.get("usage", {})
+ transformed_usage_dict = self._transform_usage(usage_data)
+
+ # Convert usage dict to ResponseAPIUsage object
+ usage_obj = (
+ ResponseAPIUsage(**transformed_usage_dict)
+ if transformed_usage_dict
+ else None
+ )
+
+ # Map Perplexity response to OpenAI Responses API format
+ response = ResponsesAPIResponse(
+ id=raw_response_json.get("id", ""),
+ object="response",
+ created_at=raw_response_json.get("created_at", 0),
+ status=raw_response_json.get("status", "completed"),
+ model=raw_response_json.get("model", model),
+ output=raw_response_json.get("output", []),
+ usage=usage_obj,
+ )
+
+ return response
+
+ def _transform_usage(self, usage_data: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Transform Perplexity usage data to OpenAI format
+
+ Perplexity returns:
+ {
+ "input_tokens": 100,
+ "output_tokens": 200,
+ "total_tokens": 300,
+ "cost": {
+ "currency": "USD",
+ "input_cost": 0.0001,
+ "output_cost": 0.0002,
+ "total_cost": 0.0003
+ }
+ }
+
+ OpenAI expects:
+ {
+ "input_tokens": 100,
+ "output_tokens": 200,
+ "total_tokens": 300,
+ "cost": 0.0003
+ }
+ """
+ transformed = {
+ "input_tokens": usage_data.get("input_tokens", 0),
+ "output_tokens": usage_data.get("output_tokens", 0),
+ "total_tokens": usage_data.get("total_tokens", 0),
+ }
+
+ # Transform cost from Perplexity format (dict) to OpenAI format (float)
+ cost_obj = usage_data.get("cost")
+ if isinstance(cost_obj, dict) and "total_cost" in cost_obj:
+ transformed["cost"] = cost_obj["total_cost"]
+ verbose_logger.debug(
+ "Transformed Perplexity cost object to float: %s -> %s",
+ cost_obj,
+ cost_obj["total_cost"],
+ )
+ elif cost_obj is not None:
+ # If cost is already a float/number, use it as-is
+ transformed["cost"] = cost_obj
+
+ # Add input_tokens_details if present
+ if "input_tokens_details" in usage_data:
+ transformed["input_tokens_details"] = usage_data["input_tokens_details"]
+
+ # Add output_tokens_details if present
+ if "output_tokens_details" in usage_data:
+ transformed["output_tokens_details"] = usage_data["output_tokens_details"]
+
+ return transformed
+
+ def transform_streaming_response(
+ self,
+ model: str,
+ parsed_chunk: dict,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> ResponsesAPIStreamingResponse:
+ """
+ Transform a parsed streaming response chunk into a ResponsesAPIStreamingResponse
+ """
+ # Get the event type from the chunk
+ verbose_logger.debug("Raw Perplexity Chunk=%s", parsed_chunk)
+ event_type = str(parsed_chunk.get("type"))
+ event_pydantic_model = PerplexityResponsesConfig.get_event_model_class(
+ event_type=event_type
+ )
+
+ # Transform Perplexity-specific fields to OpenAI format
+ parsed_chunk = self._transform_perplexity_chunk(parsed_chunk)
+
+ # Defensive: Handle error.code being null (similar to OpenAI implementation)
+ try:
+ error_obj = parsed_chunk.get("error")
+ if isinstance(error_obj, dict) and error_obj.get("code") is None:
+ # Preserve other fields, but ensure `code` is a non-null string
+ parsed_chunk = dict(parsed_chunk)
+ parsed_chunk["error"] = dict(error_obj)
+ parsed_chunk["error"]["code"] = "unknown_error"
+ except Exception:
+ # If anything unexpected happens here, fall back to attempting
+ # instantiation and let higher-level handlers manage errors.
+ verbose_logger.debug("Failed to coalesce error.code in parsed_chunk")
+
+ return event_pydantic_model(**parsed_chunk)
+
+ def _transform_perplexity_chunk(self, chunk: dict) -> dict:
+ """
+ Transform Perplexity-specific fields in a streaming chunk to OpenAI format.
+
+ This handles:
+ - Converting Perplexity's cost object to a simple float
+ """
+ # Make a copy to avoid modifying the original
+ chunk = dict(chunk)
+
+ # Transform usage.cost from Perplexity format to OpenAI format
+ # Perplexity: {"currency": "USD", "input_cost": 0.0001, "output_cost": 0.0002, "total_cost": 0.0003}
+ # OpenAI: 0.0003 (just the total_cost as a float)
+ try:
+ response_obj = chunk.get("response")
+ if isinstance(response_obj, dict):
+ usage_obj = response_obj.get("usage")
+ if isinstance(usage_obj, dict):
+ cost_obj = usage_obj.get("cost")
+ if isinstance(cost_obj, dict) and "total_cost" in cost_obj:
+ # Replace the cost object with just the total_cost value
+ chunk = dict(chunk)
+ chunk["response"] = dict(response_obj)
+ chunk["response"]["usage"] = dict(usage_obj)
+ chunk["response"]["usage"]["cost"] = cost_obj["total_cost"]
+ verbose_logger.debug(
+ "Transformed Perplexity cost object to float: %s -> %s",
+ cost_obj,
+ cost_obj["total_cost"],
+ )
+ except Exception as e:
+ # If transformation fails, log and continue with original chunk
+ verbose_logger.debug("Failed to transform Perplexity cost object: %s", e)
+
+ return chunk
diff --git a/litellm/llms/s3_vectors/__init__.py b/litellm/llms/s3_vectors/__init__.py
new file mode 100644
index 00000000000..e8367949c3e
--- /dev/null
+++ b/litellm/llms/s3_vectors/__init__.py
@@ -0,0 +1 @@
+# S3 Vectors LLM integration
diff --git a/litellm/llms/s3_vectors/vector_stores/__init__.py b/litellm/llms/s3_vectors/vector_stores/__init__.py
new file mode 100644
index 00000000000..ac24b4a38da
--- /dev/null
+++ b/litellm/llms/s3_vectors/vector_stores/__init__.py
@@ -0,0 +1 @@
+# S3 Vectors vector store integration
diff --git a/litellm/llms/s3_vectors/vector_stores/transformation.py b/litellm/llms/s3_vectors/vector_stores/transformation.py
new file mode 100644
index 00000000000..df81a78289a
--- /dev/null
+++ b/litellm/llms/s3_vectors/vector_stores/transformation.py
@@ -0,0 +1,254 @@
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+
+import httpx
+
+from litellm.llms.base_llm.vector_store.transformation import BaseVectorStoreConfig
+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.vector_stores import (
+ VECTOR_STORE_OPENAI_PARAMS,
+ BaseVectorStoreAuthCredentials,
+ VectorStoreIndexEndpoints,
+ VectorStoreResultContent,
+ VectorStoreSearchOptionalRequestParams,
+ VectorStoreSearchResponse,
+ VectorStoreSearchResult,
+)
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+
+
+class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM):
+ """Vector store configuration for AWS S3 Vectors."""
+
+ def __init__(self) -> None:
+ BaseVectorStoreConfig.__init__(self)
+ BaseAWSLLM.__init__(self)
+
+ def get_auth_credentials(
+ self, litellm_params: dict
+ ) -> BaseVectorStoreAuthCredentials:
+ return {}
+
+ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints:
+ return {
+ "read": [("POST", "/QueryVectors")],
+ "write": [],
+ }
+
+ def get_supported_openai_params(
+ self, model: str
+ ) -> List[VECTOR_STORE_OPENAI_PARAMS]:
+ return ["max_num_results"]
+
+ def map_openai_params(
+ self,
+ non_default_params: dict,
+ optional_params: dict,
+ drop_params: bool,
+ ) -> dict:
+ for param, value in non_default_params.items():
+ if param == "max_num_results":
+ optional_params["maxResults"] = value
+ return optional_params
+
+ def validate_environment(
+ self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]
+ ) -> dict:
+ headers = headers or {}
+ headers.setdefault("Content-Type", "application/json")
+ return headers
+
+ def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str:
+ aws_region_name = litellm_params.get("aws_region_name")
+ if not aws_region_name:
+ raise ValueError("aws_region_name is required for S3 Vectors")
+ return f"https://s3vectors.{aws_region_name}.api.aws"
+
+ def transform_search_vector_store_request(
+ self,
+ vector_store_id: str,
+ query: Union[str, List[str]],
+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,
+ api_base: str,
+ litellm_logging_obj: LiteLLMLoggingObj,
+ litellm_params: dict,
+ ) -> Tuple[str, Dict]:
+ """Sync version - generates embedding synchronously."""
+ # For S3 Vectors, vector_store_id should be in format: bucket_name:index_name
+ # If not in that format, try to construct it from litellm_params
+ bucket_name: str
+ index_name: str
+
+ if ":" in vector_store_id:
+ bucket_name, index_name = vector_store_id.split(":", 1)
+ else:
+ # Try to get bucket_name from litellm_params
+ bucket_name_from_params = litellm_params.get("vector_bucket_name")
+ if not bucket_name_from_params or not isinstance(bucket_name_from_params, str):
+ raise ValueError(
+ "vector_store_id must be in format 'bucket_name:index_name' for S3 Vectors, "
+ "or vector_bucket_name must be provided in litellm_params"
+ )
+ bucket_name = bucket_name_from_params
+ index_name = vector_store_id
+
+ if isinstance(query, list):
+ query = " ".join(query)
+
+ # Generate embedding for the query
+ embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small")
+
+ import litellm as litellm_module
+ embedding_response = litellm_module.embedding(model=embedding_model, input=[query])
+ query_embedding = embedding_response.data[0]["embedding"]
+
+ url = f"{api_base}/QueryVectors"
+
+ request_body: Dict[str, Any] = {
+ "vectorBucketName": bucket_name,
+ "indexName": index_name,
+ "queryVector": {"float32": query_embedding},
+ "topK": vector_store_search_optional_params.get("max_num_results", 5), # Default to 5
+ "returnDistance": True,
+ "returnMetadata": True,
+ }
+
+ litellm_logging_obj.model_call_details["query"] = query
+ return url, request_body
+
+ async def atransform_search_vector_store_request(
+ self,
+ vector_store_id: str,
+ query: Union[str, List[str]],
+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,
+ api_base: str,
+ litellm_logging_obj: LiteLLMLoggingObj,
+ litellm_params: dict,
+ ) -> Tuple[str, Dict]:
+ """Async version - generates embedding asynchronously."""
+ # For S3 Vectors, vector_store_id should be in format: bucket_name:index_name
+ # If not in that format, try to construct it from litellm_params
+ bucket_name: str
+ index_name: str
+
+ if ":" in vector_store_id:
+ bucket_name, index_name = vector_store_id.split(":", 1)
+ else:
+ # Try to get bucket_name from litellm_params
+ bucket_name_from_params = litellm_params.get("vector_bucket_name")
+ if not bucket_name_from_params or not isinstance(bucket_name_from_params, str):
+ raise ValueError(
+ "vector_store_id must be in format 'bucket_name:index_name' for S3 Vectors, "
+ "or vector_bucket_name must be provided in litellm_params"
+ )
+ bucket_name = bucket_name_from_params
+ index_name = vector_store_id
+
+ if isinstance(query, list):
+ query = " ".join(query)
+
+ # Generate embedding for the query asynchronously
+ embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small")
+
+ import litellm as litellm_module
+ embedding_response = await litellm_module.aembedding(model=embedding_model, input=[query])
+ query_embedding = embedding_response.data[0]["embedding"]
+
+ url = f"{api_base}/QueryVectors"
+
+ request_body: Dict[str, Any] = {
+ "vectorBucketName": bucket_name,
+ "indexName": index_name,
+ "queryVector": {"float32": query_embedding},
+ "topK": vector_store_search_optional_params.get("max_num_results", 5), # Default to 5
+ "returnDistance": True,
+ "returnMetadata": True,
+ }
+
+ litellm_logging_obj.model_call_details["query"] = query
+ return url, request_body
+
+ def sign_request(
+ self,
+ headers: dict,
+ optional_params: Dict,
+ request_data: Dict,
+ api_base: str,
+ api_key: Optional[str] = None,
+ ) -> Tuple[dict, Optional[bytes]]:
+ return self._sign_request(
+ service_name="s3vectors",
+ headers=headers,
+ optional_params=optional_params,
+ request_data=request_data,
+ api_base=api_base,
+ api_key=api_key,
+ )
+
+ def transform_search_vector_store_response(
+ self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj
+ ) -> VectorStoreSearchResponse:
+ try:
+ response_data = response.json()
+ results: List[VectorStoreSearchResult] = []
+
+ for item in response_data.get("vectors", []) or []:
+ metadata = item.get("metadata", {}) or {}
+ source_text = metadata.get("source_text", "")
+
+ if not source_text:
+ continue
+
+ # Extract file information from metadata
+ chunk_index = metadata.get("chunk_index", "0")
+ file_id = f"s3-vectors-chunk-{chunk_index}"
+ filename = metadata.get("filename", f"document-{chunk_index}")
+
+ # S3 Vectors returns distance, convert to similarity score (0-1)
+ # Lower distance = higher similarity
+ # We'll normalize using 1 / (1 + distance) to get a 0-1 score
+ distance = item.get("distance")
+ score = None
+ if distance is not None:
+ # Convert distance to similarity score between 0 and 1
+ # For cosine distance: similarity = 1 - distance
+ # For euclidean: use 1 / (1 + distance)
+ # Assuming cosine distance here
+ score = max(0.0, min(1.0, 1.0 - float(distance)))
+
+ results.append(
+ VectorStoreSearchResult(
+ score=score,
+ content=[VectorStoreResultContent(text=source_text, type="text")],
+ file_id=file_id,
+ filename=filename,
+ attributes=metadata,
+ )
+ )
+
+ return VectorStoreSearchResponse(
+ object="vector_store.search_results.page",
+ search_query=litellm_logging_obj.model_call_details.get("query", ""),
+ data=results,
+ )
+ except Exception as e:
+ raise self.get_error_class(
+ error_message=str(e),
+ status_code=response.status_code,
+ headers=response.headers,
+ )
+
+ # Vector store creation is not yet implemented
+ def transform_create_vector_store_request(
+ self,
+ vector_store_create_optional_params,
+ api_base: str,
+ ) -> Tuple[str, Dict]:
+ raise NotImplementedError
+
+ def transform_create_vector_store_response(self, response: httpx.Response):
+ raise NotImplementedError
diff --git a/litellm/llms/sagemaker/embedding/transformation.py b/litellm/llms/sagemaker/embedding/transformation.py
index bd8abc5e01a..04b201380fc 100644
--- a/litellm/llms/sagemaker/embedding/transformation.py
+++ b/litellm/llms/sagemaker/embedding/transformation.py
@@ -102,11 +102,18 @@ class SagemakerEmbeddingConfig(BaseEmbeddingConfig):
status_code=raw_response.status_code
)
- if "embedding" not in response_data:
+ # Handle both raw array format (TEI) and wrapped format (standard HF)
+ if isinstance(response_data, list):
+ # TEI and some HF models return raw embedding arrays directly
+ embeddings = response_data
+ elif isinstance(response_data, dict) and "embedding" in response_data:
+ # Standard HF format with "embedding" key
+ embeddings = response_data["embedding"]
+ else:
raise SagemakerError(
- status_code=500, message="HF response missing 'embedding' field"
+ status_code=500,
+ message=f"Unexpected response format. Expected list or dict with 'embedding' key, got: {type(response_data).__name__}",
)
- embeddings = response_data["embedding"]
if not isinstance(embeddings, list):
raise SagemakerError(
diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py
index 152b99ca4db..02b69b94d94 100644
--- a/litellm/llms/vertex_ai/common_utils.py
+++ b/litellm/llms/vertex_ai/common_utils.py
@@ -1,4 +1,5 @@
import re
+from copy import deepcopy
from enum import Enum
from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union, get_type_hints
@@ -684,7 +685,7 @@ def convert_anyof_null_to_nullable(schema, depth=0):
if anyof is not None:
contains_null = False
for atype in anyof:
- if atype == {"type": "null"}:
+ if isinstance(atype, dict) and atype.get("type") == "null":
# remove null type
anyof.remove(atype)
contains_null = True
@@ -801,8 +802,38 @@ def _convert_schema_types(schema, depth=0):
if "type" in schema:
type_val = schema["type"]
if isinstance(type_val, list) and len(type_val) > 1:
- # Convert ["string", "number"] -> {"anyOf": [{"type": "STRING"}, {"type": "NUMBER"}]}
- schema["anyOf"] = [{"type": t} for t in type_val if isinstance(t, str)]
+ # Convert type arrays to anyOf format
+ # Fields that are specific to object/array types and should move into anyOf
+ type_specific_fields = {"properties", "required", "additionalProperties", "items", "minItems", "maxItems", "minProperties", "maxProperties"}
+
+ any_of: List[Dict[str, Any]] = []
+ for t in type_val:
+ if not isinstance(t, str):
+ continue
+ if t == "null":
+ # Keep null entry minimal so we can strip it later.
+ any_of.append({"type": "null"})
+ continue
+
+ # For object/array types, include type-specific fields
+ if t in ("object", "array"):
+ item_schema = {"type": t}
+ # Move type-specific fields into this anyOf item
+ for field in type_specific_fields:
+ if field in schema:
+ item_schema[field] = deepcopy(schema[field])
+ any_of.append(item_schema)
+ else:
+ # For primitive types, only include the type
+ any_of.append({"type": t})
+
+ # Remove type-specific fields from parent if we moved them into anyOf
+ has_object_or_array = any(t in ("object", "array") for t in type_val if isinstance(t, str))
+ if has_object_or_array:
+ for field in type_specific_fields:
+ schema.pop(field, None)
+
+ schema["anyOf"] = any_of
schema.pop("type")
elif isinstance(type_val, list) and len(type_val) == 1:
schema["type"] = type_val[0]
@@ -849,7 +880,7 @@ def get_vertex_model_id_from_url(url: str) -> Optional[str]:
`https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:streamGenerateContent`
"""
- match = re.search(r"/models/([^/:]+)", url)
+ match = re.search(r"/models/([^:]+)", url)
return match.group(1) if match else None
diff --git a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
index 289963e917a..ed4d2d6a740 100644
--- a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
+++ b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
@@ -27,6 +27,8 @@ local_cache_obj = Cache(
type=LiteLLMCacheType.LOCAL
) # only used for calling 'get_cache_key' function
+MAX_PAGINATION_PAGES = 100 # Reasonable upper bound for pagination
+
class ContextCachingEndpoints(VertexBase):
"""
@@ -115,7 +117,7 @@ class ContextCachingEndpoints(VertexBase):
- None
"""
- _, url = self._get_token_and_url_context_caching(
+ _, base_url = self._get_token_and_url_context_caching(
gemini_api_key=api_key,
custom_llm_provider=custom_llm_provider,
api_base=api_base,
@@ -123,43 +125,63 @@ class ContextCachingEndpoints(VertexBase):
vertex_location=vertex_location,
vertex_auth_header=vertex_auth_header
)
- try:
- ## LOGGING
- logging_obj.pre_call(
- input="",
- api_key="",
- additional_args={
- "complete_input_dict": {},
- "api_base": url,
- "headers": headers,
- },
- )
- resp = client.get(url=url, headers=headers)
- resp.raise_for_status()
- except httpx.HTTPStatusError as e:
- if e.response.status_code == 403:
+ page_token: Optional[str] = None
+
+ # Iterate through all pages
+ for _ in range(MAX_PAGINATION_PAGES):
+ # Build URL with pagination token if present
+ if page_token:
+ separator = "&" if "?" in base_url else "?"
+ url = f"{base_url}{separator}pageToken={page_token}"
+ else:
+ url = base_url
+
+ try:
+ ## LOGGING
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "complete_input_dict": {},
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ resp = client.get(url=url, headers=headers)
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 403:
+ return None
+ raise VertexAIError(
+ status_code=e.response.status_code, message=e.response.text
+ )
+ except Exception as e:
+ raise VertexAIError(status_code=500, message=str(e))
+
+ raw_response = resp.json()
+ logging_obj.post_call(original_response=raw_response)
+
+ if "cachedContents" not in raw_response:
return None
- raise VertexAIError(
- status_code=e.response.status_code, message=e.response.text
- )
- except Exception as e:
- raise VertexAIError(status_code=500, message=str(e))
- raw_response = resp.json()
- logging_obj.post_call(original_response=raw_response)
- if "cachedContents" not in raw_response:
- return None
+ all_cached_items = CachedContentListAllResponseBody(**raw_response)
- all_cached_items = CachedContentListAllResponseBody(**raw_response)
+ if "cachedContents" not in all_cached_items:
+ return None
- if "cachedContents" not in all_cached_items:
- return None
+ # Check current page for matching cache_key
+ for cached_item in all_cached_items["cachedContents"]:
+ display_name = cached_item.get("displayName")
+ if display_name is not None and display_name == cache_key:
+ return cached_item.get("name")
- for cached_item in all_cached_items["cachedContents"]:
- display_name = cached_item.get("displayName")
- if display_name is not None and display_name == cache_key:
- return cached_item.get("name")
+ # Check if there are more pages
+ page_token = all_cached_items.get("nextPageToken")
+ if not page_token:
+ # No more pages, cache not found
+ break
return None
@@ -187,7 +209,7 @@ class ContextCachingEndpoints(VertexBase):
- None
"""
- _, url = self._get_token_and_url_context_caching(
+ _, base_url = self._get_token_and_url_context_caching(
gemini_api_key=api_key,
custom_llm_provider=custom_llm_provider,
api_base=api_base,
@@ -195,43 +217,63 @@ class ContextCachingEndpoints(VertexBase):
vertex_location=vertex_location,
vertex_auth_header=vertex_auth_header
)
- try:
- ## LOGGING
- logging_obj.pre_call(
- input="",
- api_key="",
- additional_args={
- "complete_input_dict": {},
- "api_base": url,
- "headers": headers,
- },
- )
- resp = await client.get(url=url, headers=headers)
- resp.raise_for_status()
- except httpx.HTTPStatusError as e:
- if e.response.status_code == 403:
+ page_token: Optional[str] = None
+
+ # Iterate through all pages
+ for _ in range(MAX_PAGINATION_PAGES):
+ # Build URL with pagination token if present
+ if page_token:
+ separator = "&" if "?" in base_url else "?"
+ url = f"{base_url}{separator}pageToken={page_token}"
+ else:
+ url = base_url
+
+ try:
+ ## LOGGING
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "complete_input_dict": {},
+ "api_base": url,
+ "headers": headers,
+ },
+ )
+
+ resp = await client.get(url=url, headers=headers)
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 403:
+ return None
+ raise VertexAIError(
+ status_code=e.response.status_code, message=e.response.text
+ )
+ except Exception as e:
+ raise VertexAIError(status_code=500, message=str(e))
+
+ raw_response = resp.json()
+ logging_obj.post_call(original_response=raw_response)
+
+ if "cachedContents" not in raw_response:
return None
- raise VertexAIError(
- status_code=e.response.status_code, message=e.response.text
- )
- except Exception as e:
- raise VertexAIError(status_code=500, message=str(e))
- raw_response = resp.json()
- logging_obj.post_call(original_response=raw_response)
- if "cachedContents" not in raw_response:
- return None
+ all_cached_items = CachedContentListAllResponseBody(**raw_response)
- all_cached_items = CachedContentListAllResponseBody(**raw_response)
+ if "cachedContents" not in all_cached_items:
+ return None
- if "cachedContents" not in all_cached_items:
- return None
+ # Check current page for matching cache_key
+ for cached_item in all_cached_items["cachedContents"]:
+ display_name = cached_item.get("displayName")
+ if display_name is not None and display_name == cache_key:
+ return cached_item.get("name")
- for cached_item in all_cached_items["cachedContents"]:
- display_name = cached_item.get("displayName")
- if display_name is not None and display_name == cache_key:
- return cached_item.get("name")
+ # Check if there are more pages
+ page_token = all_cached_items.get("nextPageToken")
+ if not page_token:
+ # No more pages, cache not found
+ break
return None
@@ -501,4 +543,4 @@ class ContextCachingEndpoints(VertexBase):
pass
async def async_get_cache(self):
- pass
+ pass
\ No newline at end of file
diff --git a/litellm/llms/vertex_ai/files/transformation.py b/litellm/llms/vertex_ai/files/transformation.py
index b3612113ec2..2470c59bbac 100644
--- a/litellm/llms/vertex_ai/files/transformation.py
+++ b/litellm/llms/vertex_ai/files/transformation.py
@@ -165,7 +165,7 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):
"""
Get the complete url for the request
"""
- bucket_name = litellm_params.get("bucket_name") or os.getenv("GCS_BUCKET_NAME")
+ bucket_name = litellm_params.get("bucket_name") or litellm_params.get("litellm_metadata", {}).pop("gcs_bucket_name", None) or os.getenv("GCS_BUCKET_NAME")
if not bucket_name:
raise ValueError("GCS bucket_name is required")
file_data = data.get("file")
diff --git a/litellm/llms/vertex_ai/gemini/transformation.py b/litellm/llms/vertex_ai/gemini/transformation.py
index 3004f39b973..5d397297891 100644
--- a/litellm/llms/vertex_ai/gemini/transformation.py
+++ b/litellm/llms/vertex_ai/gemini/transformation.py
@@ -437,6 +437,27 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915
else:
assistant_content.append(PartType(text=assistant_text)) # type: ignore
+ ## HANDLE ASSISTANT IMAGES FIELD
+ # Process images field if present (for generated images from assistant)
+ assistant_images = assistant_msg.get("images")
+ if assistant_images is not None and isinstance(assistant_images, list):
+ for image_item in assistant_images:
+ if isinstance(image_item, dict):
+ image_url_obj = image_item.get("image_url")
+ if isinstance(image_url_obj, dict):
+ assistant_image_url = image_url_obj.get("url")
+ format = image_url_obj.get("format")
+ detail = image_url_obj.get("detail")
+ media_resolution_enum = _convert_detail_to_media_resolution_enum(detail)
+ if assistant_image_url:
+ _part = _process_gemini_media(
+ image_url=assistant_image_url,
+ format=format,
+ media_resolution_enum=media_resolution_enum,
+ model=model,
+ )
+ assistant_content.append(_part)
+
## HANDLE ASSISTANT FUNCTION CALL
if (
assistant_msg.get("tool_calls", []) is not None
@@ -508,6 +529,18 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915
raise e
+def _pop_and_merge_extra_body(data: RequestBody, optional_params: dict) -> None:
+ """Pop extra_body from optional_params and shallow-merge into data, deep-merging dict values."""
+ extra_body: Optional[dict] = optional_params.pop("extra_body", None)
+ if extra_body is not None:
+ data_dict: dict = data # type: ignore[assignment]
+ for k, v in extra_body.items():
+ if k in data_dict and isinstance(data_dict[k], dict) and isinstance(v, dict):
+ data_dict[k].update(v)
+ else:
+ data_dict[k] = v
+
+
def _transform_request_body(
messages: List[AllMessageValues],
model: str,
@@ -598,6 +631,7 @@ def _transform_request_body(
# Only add labels for Vertex AI endpoints (not Google GenAI/AI Studio) and only if non-empty
if labels and custom_llm_provider != LlmProviders.GEMINI:
data["labels"] = labels
+ _pop_and_merge_extra_body(data, optional_params)
except Exception as e:
raise e
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index b78ac8f9e98..daa82a46bdc 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -478,6 +478,16 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
if "type" in tool and tool["type"] == "computer_use":
computer_use_config = {k: v for k, v in tool.items() if k != "type"}
tool = {VertexToolName.COMPUTER_USE.value: computer_use_config}
+ # Handle OpenAI-style web_search and web_search_preview tools
+ # Transform them to Gemini's googleSearch tool
+ elif "type" in tool and tool["type"] in (
+ "web_search",
+ "web_search_preview",
+ ):
+ verbose_logger.info(
+ f"Gemini: Transforming OpenAI-style '{tool['type']}' tool to googleSearch"
+ )
+ tool = {VertexToolName.GOOGLE_SEARCH.value: {}}
# Handle tools with 'type' field (OpenAI spec compliance) Ignore this field -> https://github.com/BerriAI/litellm/issues/14644#issuecomment-3342061838
elif "type" in tool:
tool = {k: tool[k] for k in tool if k != "type"}
@@ -1062,7 +1072,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
elif param == "modalities" and isinstance(value, list):
response_modalities = self.map_response_modalities(value)
optional_params["responseModalities"] = response_modalities
- elif param == "web_search_options" and value and isinstance(value, dict):
+ elif param == "web_search_options" and isinstance(value, dict):
_tools = self._map_web_search_options(value)
optional_params = self._add_tools_to_optional_params(
optional_params, [_tools]
@@ -1189,6 +1199,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
"PROHIBITED_CONTENT": "The token generation was stopped as the response was flagged for the prohibited contents.",
"SPII": "The token generation was stopped as the response was flagged for Sensitive Personally Identifiable Information (SPII) contents.",
"IMAGE_SAFETY": "The token generation was stopped as the response was flagged for image safety reasons.",
+ "IMAGE_PROHIBITED_CONTENT": "The token generation was stopped as the response was flagged for prohibited image content.",
}
@staticmethod
@@ -1211,6 +1222,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
"SPII": "content_filter",
"MALFORMED_FUNCTION_CALL": "malformed_function_call", # openai doesn't have a way of representing this
"IMAGE_SAFETY": "content_filter",
+ "IMAGE_PROHIBITED_CONTENT": "content_filter",
}
def translate_exception_str(self, exception_string: str):
@@ -1623,7 +1635,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
completion_image_tokens = response_tokens_details.image_tokens or 0
completion_audio_tokens = response_tokens_details.audio_tokens or 0
calculated_text_tokens = (
- candidates_token_count - completion_image_tokens - completion_audio_tokens
+ candidates_token_count
+ - completion_image_tokens
+ - completion_audio_tokens
)
response_tokens_details.text_tokens = calculated_text_tokens
#########################################################
@@ -1657,7 +1671,17 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
## This is necessary because promptTokensDetails includes both cached and non-cached tokens
## See: https://github.com/BerriAI/litellm/issues/18750
if cached_text_tokens is not None and prompt_text_tokens is not None:
+ # Explicit caching: subtract cached tokens per modality from cacheTokensDetails
prompt_text_tokens = prompt_text_tokens - cached_text_tokens
+ elif (
+ cached_tokens is not None
+ and prompt_text_tokens is not None
+ and cached_text_tokens is None
+ ):
+ # Implicit caching: only cachedContentTokenCount is provided (no cacheTokensDetails)
+ # Subtract from text tokens since implicit caching is primarily for text content
+ # See: https://github.com/BerriAI/litellm/issues/16341
+ prompt_text_tokens = prompt_text_tokens - cached_tokens
if cached_audio_tokens is not None and prompt_audio_tokens is not None:
prompt_audio_tokens = prompt_audio_tokens - cached_audio_tokens
if cached_image_tokens is not None and prompt_image_tokens is not None:
@@ -1715,6 +1739,52 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
else:
return "stop"
+ @staticmethod
+ def _check_prompt_level_content_filter(
+ processed_chunk: GenerateContentResponseBody,
+ response_id: Optional[str],
+ ) -> Optional["ModelResponseStream"]:
+ """
+ Check if prompt is blocked due to content filtering at the prompt level.
+
+ This handles the case where Vertex AI blocks the prompt before generation begins,
+ indicated by promptFeedback.blockReason being present.
+
+ Args:
+ processed_chunk: The parsed response chunk from Vertex AI
+ response_id: The response ID from the chunk
+
+ Returns:
+ ModelResponseStream with content_filter finish_reason if blocked, None otherwise.
+
+ Note:
+ This is consistent with non-streaming _handle_blocked_response() behavior.
+ Candidate-level content filtering (SAFETY, RECITATION, etc.) is handled
+ separately via _process_candidates() → _check_finish_reason().
+ """
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ # Check if prompt is blocked due to content filtering
+ prompt_feedback = processed_chunk.get("promptFeedback")
+ if prompt_feedback and "blockReason" in prompt_feedback:
+ verbose_logger.debug(
+ f"Prompt blocked due to: {prompt_feedback.get('blockReason')} - {prompt_feedback.get('blockReasonMessage')}"
+ )
+
+ # Create a content_filter response (consistent with non-streaming _handle_blocked_response)
+ choice = StreamingChoices(
+ finish_reason="content_filter",
+ index=0,
+ delta=Delta(content=None, role="assistant"),
+ logprobs=None,
+ enhancements=None,
+ )
+
+ model_response = ModelResponseStream(choices=[choice], id=response_id)
+ return model_response
+
+ return None
+
@staticmethod
def _calculate_web_search_requests(grounding_metadata: List[dict]) -> Optional[int]:
web_search_requests: Optional[int] = None
@@ -2185,6 +2255,13 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
citation_metadata # older approach - maintaining to prevent regressions
)
+ ## ADD TRAFFIC TYPE ##
+ traffic_type = completion_response.get("usageMetadata", {}).get(
+ "trafficType"
+ )
+ if traffic_type:
+ model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type
+
except Exception as e:
raise VertexAIError(
message="Received={}, Error converting to valid response block={}. File an issue if litellm error - https://github.com/BerriAI/litellm/issues".format(
@@ -2796,6 +2873,15 @@ class ModelResponseIterator:
processed_chunk = GenerateContentResponseBody(**chunk) # type: ignore
response_id = processed_chunk.get("responseId")
model_response = ModelResponseStream(choices=[], id=response_id)
+
+ # Check if prompt is blocked due to content filtering
+ blocked_response = VertexGeminiConfig._check_prompt_level_content_filter(
+ processed_chunk=processed_chunk,
+ response_id=response_id,
+ )
+ if blocked_response is not None:
+ model_response = blocked_response
+
usage: Optional[Usage] = None
_candidates: Optional[List[Candidates]] = processed_chunk.get("candidates")
grounding_metadata: List[dict] = []
@@ -2834,6 +2920,12 @@ class ModelResponseIterator:
PromptTokensDetailsWrapper, usage.prompt_tokens_details
).web_search_requests = web_search_requests
+ traffic_type = processed_chunk.get("usageMetadata", {}).get(
+ "trafficType"
+ )
+ if traffic_type:
+ model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type
+
setattr(model_response, "usage", usage) # type: ignore
model_response._hidden_params["is_finished"] = False
diff --git a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py
index 89ed9f1a8a5..ba3df88be14 100644
--- a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py
+++ b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py
@@ -295,9 +295,11 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM):
if "inlineData" in part:
inline_data = part["inlineData"]
if "data" in inline_data:
+ thought_sig = part.get("thoughtSignature")
model_response.data.append(ImageObject(
b64_json=inline_data["data"],
url=None,
+ provider_specific_fields={"thought_signature": thought_sig} if thought_sig else None,
))
if usage_metadata := response_data.get("usageMetadata", None):
diff --git a/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py b/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py
index 08b93145e50..1be9cd820a3 100644
--- a/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py
+++ b/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py
@@ -115,8 +115,13 @@ class VertexVectorStoreConfig(BaseVectorStoreConfig, VertexBase):
vertex_project = self.get_vertex_ai_project(litellm_params)
vertex_location = self.get_vertex_ai_location(litellm_params)
- # Construct full rag corpus path
- full_rag_corpus = f"projects/{vertex_project}/locations/{vertex_location}/ragCorpora/{vector_store_id}"
+ # Handle both full corpus path and just corpus ID
+ if vector_store_id.startswith("projects/"):
+ # Already a full path
+ full_rag_corpus = vector_store_id
+ else:
+ # Just the corpus ID, construct full path
+ full_rag_corpus = f"projects/{vertex_project}/locations/{vertex_location}/ragCorpora/{vector_store_id}"
# Build the request body for Vertex AI RAG API
request_body: Dict[str, Any] = {
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py
index fc75376c0cb..54c3f9e0474 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py
@@ -64,7 +64,30 @@ class VertexAIPartnerModelsAnthropicMessagesConfig(AnthropicMessagesConfig, Vert
existing_beta = headers.get("anthropic-beta")
if existing_beta:
beta_values.update(b.strip() for b in existing_beta.split(","))
-
+
+ # Check for context management
+ context_management_param = optional_params.get("context_management")
+ if context_management_param is not None:
+ # Check edits array for compact_20260112 type
+ edits = context_management_param.get("edits", [])
+ has_compact = False
+ has_other = False
+
+ for edit in edits:
+ edit_type = edit.get("type", "")
+ if edit_type == "compact_20260112":
+ has_compact = True
+ else:
+ has_other = True
+
+ # Add compact header if any compact edits exist
+ if has_compact:
+ beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value)
+
+ # Add context management header if any other edits exist
+ if has_other:
+ beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value)
+
# Check for web search tool
for tool in tools:
if isinstance(tool, dict) and tool.get("type", "").startswith(ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value):
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py
index 1df07f405e6..6a5b934661a 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py
@@ -51,6 +51,42 @@ class VertexAIAnthropicConfig(AnthropicConfig):
def custom_llm_provider(self) -> Optional[str]:
return "vertex_ai"
+ def _add_context_management_beta_headers(
+ self, beta_set: set, context_management: dict
+ ) -> None:
+ """
+ Add context_management beta headers to the beta_set.
+
+ - If any edit has type "compact_20260112", add compact-2026-01-12 header
+ - For all other edits, add context-management-2025-06-27 header
+
+ Args:
+ beta_set: Set of beta headers to modify in-place
+ context_management: The context_management dict from optional_params
+ """
+ from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES
+
+ edits = context_management.get("edits", [])
+ has_compact = False
+ has_other = False
+
+ for edit in edits:
+ edit_type = edit.get("type", "")
+ if edit_type == "compact_20260112":
+ has_compact = True
+ else:
+ has_other = True
+
+ # Add compact header if any compact edits exist
+ if has_compact:
+ beta_set.add(ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value)
+
+ # Add context management header if any other edits exist
+ if has_other:
+ beta_set.add(
+ ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value
+ )
+
def transform_request(
self,
model: str,
@@ -68,10 +104,10 @@ class VertexAIAnthropicConfig(AnthropicConfig):
)
data.pop("model", None) # vertex anthropic doesn't accept 'model' parameter
-
+
# VertexAI doesn't support output_format parameter, remove it if present
data.pop("output_format", None)
-
+
tools = optional_params.get("tools")
tool_search_used = self.is_tool_search_used(tools)
auto_betas = self.get_anthropic_beta_list(
@@ -85,11 +121,30 @@ class VertexAIAnthropicConfig(AnthropicConfig):
beta_set = set(auto_betas)
if tool_search_used:
- beta_set.add("tool-search-tool-2025-10-19") # Vertex requires this header for tool search
+ beta_set.add(
+ "tool-search-tool-2025-10-19"
+ ) # Vertex requires this header for tool search
+
+ # Add context_management beta headers (compact and/or context-management)
+ context_management = optional_params.get("context_management")
+ if context_management:
+ self._add_context_management_beta_headers(beta_set, context_management)
+
+ extra_headers = optional_params.get("extra_headers") or {}
+ anthropic_beta_value = extra_headers.get("anthropic-beta", "")
+ if isinstance(anthropic_beta_value, str) and anthropic_beta_value:
+ for beta in anthropic_beta_value.split(","):
+ beta = beta.strip()
+ if beta:
+ beta_set.add(beta)
+ elif isinstance(anthropic_beta_value, list):
+ beta_set.update(anthropic_beta_value)
+
+ data.pop("extra_headers", None)
if beta_set:
data["anthropic_beta"] = list(beta_set)
-
+
return data
def map_openai_params(
@@ -109,7 +164,7 @@ class VertexAIAnthropicConfig(AnthropicConfig):
original_model = model
if "response_format" in non_default_params:
model = "claude-3-sonnet-20240229" # Use a model that will use tool-based approach
-
+
# Call parent method with potentially modified model name
optional_params = super().map_openai_params(
non_default_params=non_default_params,
@@ -117,10 +172,10 @@ class VertexAIAnthropicConfig(AnthropicConfig):
model=model,
drop_params=drop_params,
)
-
+
# Restore original model name for any other processing
model = original_model
-
+
return optional_params
def transform_response(
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py
index 3842159fd7b..c6914ac3d6b 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py
@@ -107,6 +107,11 @@ class VertexAIPartnerModelsTokenCounter(VertexBase):
vertex_project = self.get_vertex_ai_project(litellm_params)
vertex_location = self.get_vertex_ai_location(litellm_params)
+ # Map empty location/cluade models to a supported region for count-tokens endpoint
+ # https://docs.cloud.google.com/vertex-ai/generative-ai/docs/partner-models/claude/count-tokens
+ if not vertex_location or "claude" in model.lower():
+ vertex_location = "us-central1"
+
# Get access token and resolved project ID
access_token, project_id = await self._ensure_access_token_async(
credentials=vertex_credentials,
@@ -118,7 +123,7 @@ class VertexAIPartnerModelsTokenCounter(VertexBase):
endpoint_url = self._build_count_tokens_endpoint(
model=model,
project_id=project_id,
- vertex_location=vertex_location or "us-central1",
+ vertex_location=vertex_location,
api_base=litellm_params.get("api_base"),
)
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py
index 748a5f5fb40..51310e4fa85 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py
@@ -1,12 +1,21 @@
import types
-from typing import Any, List, Optional
+from typing import Any, AsyncIterator, Iterator, List, Optional, Union
import httpx
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
-from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig
+from litellm.llms.openai.chat.gpt_transformation import (
+ OpenAIChatCompletionStreamingHandler,
+ OpenAIGPTConfig,
+)
from litellm.types.llms.openai import AllMessageValues, OpenAIChatCompletionResponse
-from litellm.types.utils import ModelResponse, Usage
+from litellm.types.utils import (
+ Delta,
+ ModelResponse,
+ ModelResponseStream,
+ StreamingChoices,
+ Usage,
+)
from ...common_utils import VertexAIError
@@ -79,6 +88,18 @@ class VertexAILlama3Config(OpenAIGPTConfig):
drop_params=drop_params,
)
+ def get_model_response_iterator(
+ self,
+ streaming_response: Union[Iterator[str], AsyncIterator[str], ModelResponse],
+ sync_stream: bool,
+ json_mode: Optional[bool] = False,
+ ) -> Any:
+ return VertexAILlama3StreamingHandler(
+ streaming_response=streaming_response,
+ sync_stream=sync_stream,
+ json_mode=json_mode,
+ )
+
def transform_response(
self,
model: str,
@@ -124,3 +145,80 @@ class VertexAILlama3Config(OpenAIGPTConfig):
)
return model_response
+
+
+class VertexAILlama3StreamingHandler(OpenAIChatCompletionStreamingHandler):
+ """
+ Vertex AI Llama models may not include role in streaming chunk deltas.
+ This handler ensures the first chunk always has role="assistant".
+
+ When Vertex AI returns a single chunk with both role and finish_reason (empty response),
+ this handler splits it into two chunks:
+ 1. First chunk: role="assistant", content="", finish_reason=None
+ 2. Second chunk: role=None, content=None, finish_reason="stop"
+
+ This matches OpenAI's streaming format where the first chunk has role and
+ the final chunk has finish_reason but no role.
+ """
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.sent_role = False
+ self._pending_chunk: Optional[ModelResponseStream] = None
+
+ def chunk_parser(self, chunk: dict) -> ModelResponseStream:
+ result = super().chunk_parser(chunk)
+ if not self.sent_role and result.choices:
+ delta = result.choices[0].delta
+ finish_reason = result.choices[0].finish_reason
+
+ # If this is both the first chunk AND the final chunk (has finish_reason),
+ # we need to split it into two chunks to match OpenAI format
+ if finish_reason is not None:
+ # Create a pending final chunk with finish_reason but no role
+ self._pending_chunk = ModelResponseStream(
+ id=result.id,
+ object="chat.completion.chunk",
+ created=result.created,
+ model=result.model,
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content=None, role=None),
+ finish_reason=finish_reason,
+ )
+ ],
+ )
+ # Modify current chunk to be the first chunk with role but no finish_reason
+ result.choices[0].finish_reason = None
+ delta.role = "assistant"
+ # Ensure content is empty string for first chunk, not None
+ if delta.content is None:
+ delta.content = ""
+ # Prevent downstream stream wrapper from dropping this chunk
+ # (it drops empty-content chunks unless special fields are present)
+ if delta.provider_specific_fields is None:
+ delta.provider_specific_fields = {}
+ elif delta.role is None:
+ delta.role = "assistant"
+ # If the first chunk has empty content, ensure it's still emitted
+ if (delta.content == "" or delta.content is None) and delta.provider_specific_fields is None:
+ delta.provider_specific_fields = {}
+ self.sent_role = True
+ return result
+
+ def __next__(self):
+ # First return any pending chunk from a previous split
+ if self._pending_chunk is not None:
+ chunk = self._pending_chunk
+ self._pending_chunk = None
+ return chunk
+ return super().__next__()
+
+ async def __anext__(self):
+ # First return any pending chunk from a previous split
+ if self._pending_chunk is not None:
+ chunk = self._pending_chunk
+ self._pending_chunk = None
+ return chunk
+ return await super().__anext__()
diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.py
index a185370e376..4613b6a5715 100644
--- a/litellm/llms/vertex_ai/vertex_llm_base.py
+++ b/litellm/llms/vertex_ai/vertex_llm_base.py
@@ -20,6 +20,7 @@ from .common_utils import (
_get_vertex_url,
all_gemini_url_modes,
get_vertex_base_model_name,
+ get_vertex_base_url,
is_global_only_vertex_model,
)
@@ -200,12 +201,7 @@ class VertexBase:
) -> str:
if api_base:
return api_base
- elif vertex_location == "global":
- return "https://aiplatform.googleapis.com"
- elif vertex_location:
- return f"https://{vertex_location}-aiplatform.googleapis.com"
- else:
- return f"https://{self.get_default_vertex_location()}-aiplatform.googleapis.com"
+ return get_vertex_base_url(vertex_location or self.get_default_vertex_location())
@staticmethod
def create_vertex_url(
@@ -218,7 +214,8 @@ class VertexBase:
) -> str:
"""Return the base url for the vertex partner models"""
- api_base = api_base or f"https://{vertex_location}-aiplatform.googleapis.com"
+ if api_base is None:
+ api_base = get_vertex_base_url(vertex_location)
if partner == VertexPartnerProvider.llama:
return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/endpoints/openapi/chat/completions"
elif partner == VertexPartnerProvider.mistralai:
@@ -247,11 +244,13 @@ class VertexBase:
stream: Optional[bool],
model: str,
) -> str:
+ # Use get_vertex_region to handle global-only models
+ resolved_location = self.get_vertex_region(vertex_location, model)
api_base = self.get_api_base(
- api_base=custom_api_base, vertex_location=vertex_location
+ api_base=custom_api_base, vertex_location=resolved_location
)
default_api_base = VertexBase.create_vertex_url(
- vertex_location=vertex_location or "us-central1",
+ vertex_location=resolved_location,
vertex_project=vertex_project or project_id,
partner=partner,
stream=stream,
@@ -274,7 +273,7 @@ class VertexBase:
url=default_api_base,
model=model,
vertex_project=vertex_project or project_id,
- vertex_location=vertex_location or "us-central1",
+ vertex_location=resolved_location,
vertex_api_version="v1", # Partner models typically use v1
)
return api_base
diff --git a/litellm/llms/watsonx/__init__.py b/litellm/llms/watsonx/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/llms/watsonx/chat/__init__.py b/litellm/llms/watsonx/chat/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/llms/watsonx/common_utils.py b/litellm/llms/watsonx/common_utils.py
index 774f6dc1f3d..230c9f4cf6e 100644
--- a/litellm/llms/watsonx/common_utils.py
+++ b/litellm/llms/watsonx/common_utils.py
@@ -42,6 +42,7 @@ def generate_iam_token(api_key=None, **params) -> str:
get_secret_str("WX_API_KEY")
or get_secret_str("WATSONX_API_KEY")
or get_secret_str("WATSONX_APIKEY")
+ or get_secret_str("WATSONX_ZENAPIKEY")
)
if api_key is None:
raise ValueError("API key is required")
@@ -319,6 +320,7 @@ class IBMWatsonXMixin:
or get_secret_str("WATSONX_APIKEY")
or get_secret_str("WATSONX_API_KEY")
or get_secret_str("WX_API_KEY")
+ or get_secret_str("WATSONX_ZENAPIKEY")
)
api_base = (
diff --git a/litellm/llms/watsonx/completion/__init__.py b/litellm/llms/watsonx/completion/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/llms/watsonx/embed/__init__.py b/litellm/llms/watsonx/embed/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/llms/watsonx/rerank/__init__.py b/litellm/llms/watsonx/rerank/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/llms/watsonx/rerank/transformation.py b/litellm/llms/watsonx/rerank/transformation.py
new file mode 100644
index 00000000000..7b4c2a07c3c
--- /dev/null
+++ b/litellm/llms/watsonx/rerank/transformation.py
@@ -0,0 +1,204 @@
+"""
+Transformation logic for IBM watsonx.ai's /ml/v1/text/rerank endpoint.
+
+Docs - https://cloud.ibm.com/apidocs/watsonx-ai#text-rerank
+"""
+
+import uuid
+from typing import Any, Dict, List, Optional, Union, cast
+
+import httpx
+
+from litellm.llms.base_llm.chat.transformation import LiteLLMLoggingObj
+from litellm.llms.base_llm.rerank.transformation import BaseRerankConfig
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.llms.watsonx import (
+ WatsonXAIEndpoint,
+)
+from litellm.types.rerank import (
+ RerankResponse,
+ RerankResponseMeta,
+ RerankTokens,
+)
+
+from ..common_utils import IBMWatsonXMixin, _generate_watsonx_token, _get_api_params
+
+
+class IBMWatsonXRerankConfig(IBMWatsonXMixin, BaseRerankConfig):
+ """
+ IBM watsonx.ai Rerank API configuration
+ """
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ model: str,
+ optional_params: Optional[dict] = None,
+ ) -> str:
+ base_url = self._get_base_url(api_base=api_base)
+ endpoint = WatsonXAIEndpoint.RERANK.value
+
+ url = base_url.rstrip("/") + endpoint
+
+ params = optional_params or {}
+
+ complete_url = self._add_api_version_to_url(url=url, api_version=(params.get("api_version", None)))
+ return complete_url
+
+ def get_supported_cohere_rerank_params(self, model: str) -> list:
+ return [
+ "query",
+ "documents",
+ "top_n",
+ "return_documents",
+ "max_tokens_per_doc",
+ ]
+
+ def validate_environment( # type: ignore[override]
+ self,
+ headers: dict,
+ model: str,
+ api_key: Optional[str] = None,
+ optional_params: Optional[dict] = None,
+ ) -> Dict:
+ optional_params = optional_params or {}
+
+ default_headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ }
+
+ if "Authorization" in headers:
+ return {**default_headers, **headers}
+ token = cast(
+ Optional[str],
+ optional_params.pop("token", None) or get_secret_str("WATSONX_TOKEN"),
+ )
+ zen_api_key = cast(
+ Optional[str],
+ optional_params.pop("zen_api_key", None) or get_secret_str("WATSONX_ZENAPIKEY"),
+ )
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ elif zen_api_key:
+ headers["Authorization"] = f"ZenApiKey {zen_api_key}"
+ else:
+ token = _generate_watsonx_token(api_key=api_key, token=token)
+ # build auth headers
+ headers["Authorization"] = f"Bearer {token}"
+ return {**default_headers, **headers}
+
+ def map_cohere_rerank_params(
+ self,
+ non_default_params: Optional[dict],
+ model: str,
+ drop_params: bool,
+ query: str,
+ documents: List[Union[str, Dict[str, Any]]],
+ custom_llm_provider: Optional[str] = None,
+ top_n: Optional[int] = None,
+ rank_fields: Optional[List[str]] = None,
+ return_documents: Optional[bool] = True,
+ max_chunks_per_doc: Optional[int] = None,
+ max_tokens_per_doc: Optional[int] = None,
+ ) -> Dict:
+ """
+ Map Cohere rerank params to IBM watsonx.ai rerank params
+ """
+ optional_rerank_params = {}
+ if non_default_params is not None:
+ for k, v in non_default_params.items():
+ if k == "query" and v is not None:
+ optional_rerank_params["query"] = v
+ elif k == "documents" and v is not None:
+ optional_rerank_params["inputs"] = [
+ {"text": el} if isinstance(el, str) else el for el in v
+ ]
+ elif k == "top_n" and v is not None:
+ optional_rerank_params.setdefault("parameters", {}).setdefault("return_options", {})["top_n"] = v
+ elif k == "return_documents" and v is not None and isinstance(v, bool):
+ optional_rerank_params.setdefault("parameters", {}).setdefault("return_options", {})["inputs"] = v
+ elif k == "max_tokens_per_doc" and v is not None:
+ optional_rerank_params.setdefault("parameters", {})["truncate_input_tokens"] = v
+
+ # IBM watsonx.ai require one of below parameters
+ elif k == "project_id" and v is not None:
+ optional_rerank_params["project_id"] = v
+ elif k == "space_id" and v is not None:
+ optional_rerank_params["space_id"] = v
+
+ return dict(optional_rerank_params)
+
+ def transform_rerank_request(
+ self,
+ model: str,
+ optional_rerank_params: Dict,
+ headers: dict,
+ ) -> dict:
+ """
+ Transform request to IBM watsonx.ai rerank format
+ """
+ watsonx_api_params = _get_api_params(params=optional_rerank_params, model=model)
+ watsonx_auth_payload = self._prepare_payload(
+ model=model,
+ api_params=watsonx_api_params,
+ )
+
+ return optional_rerank_params | watsonx_auth_payload
+
+ def transform_rerank_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: RerankResponse,
+ logging_obj: LiteLLMLoggingObj,
+ api_key: Optional[str] = None,
+ request_data: dict = {},
+ optional_params: dict = {},
+ litellm_params: dict = {},
+ ) -> RerankResponse:
+ """
+ Transform IBM watsonx.ai rerank response to LiteLLM RerankResponse format
+ """
+ try:
+ raw_response_json = raw_response.json()
+ except Exception as e:
+ raise self.get_error_class(
+ error_message=f"Failed to parse response: {str(e)}",
+ status_code=raw_response.status_code,
+ headers=raw_response.headers,
+ )
+
+ _results: Optional[List[dict]] = raw_response_json.get("results")
+ if _results is None:
+ raise ValueError(f"No results found in the response={raw_response_json}")
+
+ transformed_results = []
+
+ for result in _results:
+ transformed_result: Dict[str, Any] = {
+ "index": result["index"],
+ "relevance_score": result["score"],
+ }
+
+ if "input" in result:
+ if isinstance(result["input"], str):
+ transformed_result["document"] = {"text": result["input"]}
+ else:
+ transformed_result["document"] = result["input"]
+
+ transformed_results.append(transformed_result)
+
+ response_id = raw_response_json.get("id") or raw_response_json.get("model_id") or str(uuid.uuid4())
+
+ # Extract usage information
+ _tokens = RerankTokens(
+ input_tokens=raw_response_json.get("input_token_count", 0),
+ )
+ rerank_meta = RerankResponseMeta(tokens=_tokens)
+
+ return RerankResponse(
+ id=response_id,
+ results=transformed_results, # type: ignore
+ meta=rerank_meta,
+ )
diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py
index 245e10e45c1..21782fc6fbf 100644
--- a/litellm/llms/xai/chat/transformation.py
+++ b/litellm/llms/xai/chat/transformation.py
@@ -4,6 +4,7 @@ import httpx
import litellm
from litellm._logging import verbose_logger
+from litellm.constants import XAI_API_BASE
from litellm.litellm_core_utils.prompt_templates.common_utils import (
filter_value_from_dict,
strip_name_from_messages,
@@ -14,8 +15,6 @@ from litellm.types.utils import Choices, ModelResponse, Usage, PromptTokensDetai
from ...openai.chat.gpt_transformation import OpenAIGPTConfig
-XAI_API_BASE = "https://api.x.ai/v1"
-
class XAIChatConfig(OpenAIGPTConfig):
@property
diff --git a/litellm/llms/xai/realtime/__init__.py b/litellm/llms/xai/realtime/__init__.py
new file mode 100644
index 00000000000..3b0d345f2c2
--- /dev/null
+++ b/litellm/llms/xai/realtime/__init__.py
@@ -0,0 +1,5 @@
+"""xAI Realtime API handler."""
+
+from .handler import XAIRealtime
+
+__all__ = ["XAIRealtime"]
diff --git a/litellm/llms/xai/realtime/handler.py b/litellm/llms/xai/realtime/handler.py
new file mode 100644
index 00000000000..c79477ba1df
--- /dev/null
+++ b/litellm/llms/xai/realtime/handler.py
@@ -0,0 +1,38 @@
+"""
+This file contains the handler for xAI's Grok Voice Agent API `/v1/realtime` endpoint.
+
+xAI's Realtime API is fully OpenAI-compatible, so we inherit from OpenAIRealtime
+and only override the configuration differences.
+
+This requires websockets, and is currently only supported on LiteLLM Proxy.
+"""
+
+from litellm.constants import XAI_API_BASE
+
+from ...openai.realtime.handler import OpenAIRealtime
+
+
+class XAIRealtime(OpenAIRealtime):
+ """
+ Handler for xAI Grok Voice Agent API.
+
+ xAI's Realtime API uses the same WebSocket protocol as OpenAI but with:
+ - Different endpoint: wss://api.x.ai/v1/realtime (via _get_default_api_base)
+ - No OpenAI-Beta header required (via _get_additional_headers)
+ - Model: grok-4-1-fast-non-reasoning
+
+ All WebSocket logic is inherited from OpenAIRealtime.
+ """
+
+ def _get_default_api_base(self) -> str:
+ """xAI uses a different API base URL."""
+ return XAI_API_BASE
+
+ def _get_additional_headers(self, api_key: str) -> dict:
+ """
+ xAI does NOT require the OpenAI-Beta header.
+ Only send Authorization header.
+ """
+ return {
+ "Authorization": f"Bearer {api_key}",
+ }
diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py
index bd422c8d81e..95873aab846 100644
--- a/litellm/llms/xai/responses/transformation.py
+++ b/litellm/llms/xai/responses/transformation.py
@@ -1,10 +1,12 @@
-from typing import TYPE_CHECKING, Any, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
import litellm
from litellm._logging import verbose_logger
+from litellm.constants import XAI_API_BASE
from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig
from litellm.secret_managers.main import get_secret_str
from litellm.types.llms.openai import ResponsesAPIOptionalRequestParams
+from litellm.types.llms.xai import XAIWebSearchTool, XAIXSearchTool
from litellm.types.router import GenericLiteLLMParams
from litellm.types.utils import LlmProviders
@@ -15,8 +17,6 @@ if TYPE_CHECKING:
else:
LiteLLMLoggingObj = Any
-XAI_API_BASE = "https://api.x.ai/v1"
-
class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
"""
@@ -49,6 +49,85 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
return supported_params
+ def _transform_web_search_tool(self, tool: Dict[str, Any]) -> Union[XAIWebSearchTool, Dict[str, Any]]:
+ """
+ Transform web_search tool to XAI format.
+
+ XAI supports web_search with specific filters:
+ - allowed_domains (max 5)
+ - excluded_domains (max 5)
+ - enable_image_understanding
+
+ XAI does NOT support search_context_size (OpenAI-specific).
+ """
+ xai_tool: Dict[str, Any] = {"type": "web_search"}
+
+ # Remove search_context_size if present (not supported by XAI)
+ if "search_context_size" in tool:
+ verbose_logger.info(
+ "XAI does not support 'search_context_size' parameter. Removing it from web_search tool."
+ )
+
+ # Handle filters (XAI-specific structure)
+ filters = {}
+ if "allowed_domains" in tool:
+ allowed_domains = tool["allowed_domains"]
+ filters["allowed_domains"] = allowed_domains
+
+ if "excluded_domains" in tool:
+ excluded_domains = tool["excluded_domains"]
+ filters["excluded_domains"] = excluded_domains
+
+ # Add filters if any were specified
+ if filters:
+ xai_tool["filters"] = filters
+
+ # Handle enable_image_understanding (top-level in XAI format)
+ if "enable_image_understanding" in tool:
+ xai_tool["enable_image_understanding"] = tool["enable_image_understanding"]
+
+ return xai_tool
+
+ def _transform_x_search_tool(self, tool: Dict[str, Any]) -> Union[XAIXSearchTool, Dict[str, Any]]:
+ """
+ Transform x_search tool to XAI format.
+
+ XAI supports x_search with specific parameters:
+ - allowed_x_handles (max 10)
+ - excluded_x_handles (max 10)
+ - from_date (ISO8601: YYYY-MM-DD)
+ - to_date (ISO8601: YYYY-MM-DD)
+ - enable_image_understanding
+ - enable_video_understanding
+ """
+ xai_tool: Dict[str, Any] = {"type": "x_search"}
+
+ # Handle allowed_x_handles
+ if "allowed_x_handles" in tool:
+ allowed_handles = tool["allowed_x_handles"]
+ xai_tool["allowed_x_handles"] = allowed_handles
+
+ # Handle excluded_x_handles
+ if "excluded_x_handles" in tool:
+ excluded_handles = tool["excluded_x_handles"]
+ xai_tool["excluded_x_handles"] = excluded_handles
+
+ # Handle date range
+ if "from_date" in tool:
+ xai_tool["from_date"] = tool["from_date"]
+
+ if "to_date" in tool:
+ xai_tool["to_date"] = tool["to_date"]
+
+ # Handle media understanding flags
+ if "enable_image_understanding" in tool:
+ xai_tool["enable_image_understanding"] = tool["enable_image_understanding"]
+
+ if "enable_video_understanding" in tool:
+ xai_tool["enable_video_understanding"] = tool["enable_video_understanding"]
+
+ return xai_tool
+
def map_openai_params(
self,
response_api_optional_params: ResponsesAPIOptionalRequestParams,
@@ -61,7 +140,9 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
Handles XAI-specific transformations:
1. Drops 'instructions' parameter (not supported)
2. Transforms code_interpreter tools to remove 'container' field
- 3. Sets store=false when images are detected (recommended by XAI)
+ 3. Transforms web_search tools to XAI format (removes search_context_size, adds filters)
+ 4. Transforms x_search tools to XAI format
+ 5. Sets store=false when images are detected (recommended by XAI)
"""
params = dict(response_api_optional_params)
@@ -72,7 +153,13 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
)
params.pop("instructions")
- # Transform code_interpreter tools - remove container field
+ if "metadata" in params:
+ verbose_logger.debug(
+ "XAI Responses API does not support 'metadata' parameter. Dropping it."
+ )
+ params.pop("metadata")
+
+ # Transform tools
if "tools" in params and params["tools"]:
tools_list = params["tools"]
# Ensure tools is a list for iteration
@@ -81,15 +168,36 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
transformed_tools: List[Any] = []
for tool in tools_list:
- if isinstance(tool, dict) and tool.get("type") == "code_interpreter":
- # XAI supports code_interpreter but doesn't use the container field
- # Keep only the type field
- verbose_logger.debug(
- "XAI: Transforming code_interpreter tool, removing container field"
- )
- transformed_tools.append({"type": "code_interpreter"})
+ if isinstance(tool, dict):
+ tool_type = tool.get("type")
+
+ if tool_type == "code_interpreter":
+ # XAI supports code_interpreter but doesn't use the container field
+ verbose_logger.debug(
+ "XAI: Transforming code_interpreter tool, removing container field"
+ )
+ transformed_tools.append({"type": "code_interpreter"})
+
+ elif tool_type == "web_search":
+ # Transform web_search to XAI format
+ verbose_logger.debug(
+ "XAI: Transforming web_search tool to XAI format"
+ )
+ transformed_tools.append(self._transform_web_search_tool(tool))
+
+ elif tool_type == "x_search":
+ # Transform x_search to XAI format
+ verbose_logger.debug(
+ "XAI: Transforming x_search tool to XAI format"
+ )
+ transformed_tools.append(self._transform_x_search_tool(tool))
+
+ else:
+ # Keep other tools as-is
+ transformed_tools.append(tool)
else:
transformed_tools.append(tool)
+
params["tools"] = transformed_tools
return params
diff --git a/litellm/llms/zai/chat/transformation.py b/litellm/llms/zai/chat/transformation.py
index 4380256f0a4..fb1d67df357 100644
--- a/litellm/llms/zai/chat/transformation.py
+++ b/litellm/llms/zai/chat/transformation.py
@@ -1,6 +1,7 @@
-from typing import Optional, Tuple
+from typing import List, Optional, Tuple
from litellm.secret_managers.main import get_secret_str
+from litellm.types.llms.openai import AllMessageValues, ChatCompletionToolParam
from ...openai.chat.gpt_transformation import OpenAIGPTConfig
@@ -19,6 +20,19 @@ class ZAIChatConfig(OpenAIGPTConfig):
dynamic_api_key = api_key or get_secret_str("ZAI_API_KEY")
return api_base, dynamic_api_key
+ def remove_cache_control_flag_from_messages_and_tools(
+ self,
+ model: str,
+ messages: List[AllMessageValues],
+ tools: Optional[List[ChatCompletionToolParam]] = None,
+ ) -> Tuple[List[AllMessageValues], Optional[List[ChatCompletionToolParam]]]:
+ """
+ Override to preserve cache_control for GLM/ZAI.
+ GLM supports cache_control - don't strip it.
+ """
+ # GLM/ZAI supports cache_control, so return messages and tools unchanged
+ return messages, tools
+
def get_supported_openai_params(self, model: str) -> list:
base_params = [
"max_tokens",
diff --git a/litellm/main.py b/litellm/main.py
index 3d1eb907a18..80a2f74c571 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -148,7 +148,7 @@ from litellm.utils import (
validate_and_fix_openai_messages,
validate_and_fix_openai_tools,
validate_chat_completion_tool_choice,
- validate_openai_optional_params
+ validate_openai_optional_params,
)
from ._logging import verbose_logger
@@ -368,7 +368,7 @@ class AsyncCompletions:
@tracer.wrap()
@client
-async def acompletion( # noqa: PLR0915
+async def acompletion( # noqa: PLR0915
model: str,
# Optional OpenAI params: see https://platform.openai.com/docs/api-reference/chat/create
messages: List = [],
@@ -599,16 +599,8 @@ async def acompletion( # noqa: PLR0915
# Add the context to the function
ctx = contextvars.copy_context()
func_with_context = partial(ctx.run, func)
-
- if timeout is not None and isinstance(timeout, (int, float)):
- timeout_value = float(timeout)
- init_response = await asyncio.wait_for(
- loop.run_in_executor(None, func_with_context),
- timeout=timeout_value
- )
- else:
- init_response = await loop.run_in_executor(None, func_with_context)
+ init_response = await loop.run_in_executor(None, func_with_context)
if isinstance(init_response, dict) or isinstance(
init_response, ModelResponse
): ## CACHING SCENARIO
@@ -616,11 +608,7 @@ async def acompletion( # noqa: PLR0915
response = ModelResponse(**init_response)
response = init_response
elif asyncio.iscoroutine(init_response):
- if timeout is not None and isinstance(timeout, (int, float)):
- timeout_value = float(timeout)
- response = await asyncio.wait_for(init_response, timeout=timeout_value)
- else:
- response = await init_response
+ response = await init_response
else:
response = init_response # type: ignore
@@ -637,14 +625,6 @@ async def acompletion( # noqa: PLR0915
loop=loop
) # sets the logging event loop if the user does sync streaming (e.g. on proxy for sagemaker calls)
return response
- except asyncio.TimeoutError:
- custom_llm_provider = custom_llm_provider or "openai"
- from litellm.exceptions import Timeout
- raise Timeout(
- message=f"Request timed out after {timeout} seconds",
- model=model,
- llm_provider=custom_llm_provider,
- )
except Exception as e:
custom_llm_provider = custom_llm_provider or "openai"
raise exception_type(
@@ -945,6 +925,7 @@ def mock_completion(
def responses_api_bridge_check(
model: str,
custom_llm_provider: str,
+ web_search_options: Optional[OpenAIWebSearchOptions] = None,
) -> Tuple[dict, str]:
model_info: Dict[str, Any] = {}
try:
@@ -958,6 +939,10 @@ def responses_api_bridge_check(
model = model.replace("responses/", "")
mode = "responses"
model_info["mode"] = mode
+
+ if web_search_options is not None and custom_llm_provider == "xai":
+ model_info["mode"] = "responses"
+ model = model.replace("responses/", "")
except Exception as e:
verbose_logger.debug("Error getting model info: {}".format(e))
@@ -1118,7 +1103,6 @@ def completion( # type: ignore # noqa: PLR0915
# validate optional params
stop = validate_openai_optional_params(stop=stop)
-
######### unpacking kwargs #####################
args = locals()
@@ -1135,7 +1119,9 @@ def completion( # type: ignore # noqa: PLR0915
# Check if MCP tools are present (following responses pattern)
# Cast tools to Optional[Iterable[ToolParam]] for type checking
tools_for_mcp = cast(Optional[Iterable[ToolParam]], tools)
- if LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(tools=tools_for_mcp):
+ if LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(
+ tools=tools_for_mcp
+ ):
# Return coroutine - acompletion will await it
# completion() can return a coroutine when MCP tools are present, which acompletion() awaits
return acompletion_with_mcp( # type: ignore[return-value]
@@ -1213,6 +1199,13 @@ def completion( # type: ignore # noqa: PLR0915
headers = {}
if extra_headers is not None:
headers.update(extra_headers)
+ # Inject proxy auth headers if configured
+ if litellm.proxy_auth is not None:
+ try:
+ proxy_headers = litellm.proxy_auth.get_auth_headers()
+ headers.update(proxy_headers)
+ except Exception as e:
+ verbose_logger.warning(f"Failed to get proxy auth headers: {e}")
num_retries = kwargs.get(
"num_retries", None
) ## alt. param for 'max_retries'. Use this to pass retries w/ instructor.
@@ -1536,6 +1529,8 @@ def completion( # type: ignore # noqa: PLR0915
max_retries=max_retries,
timeout=timeout,
litellm_request_debug=kwargs.get("litellm_request_debug", False),
+ tpm=kwargs.get("tpm"),
+ rpm=kwargs.get("rpm"),
)
cast(LiteLLMLoggingObj, logging).update_environment_variables(
model=model,
@@ -1563,7 +1558,7 @@ def completion( # type: ignore # noqa: PLR0915
## RESPONSES API BRIDGE LOGIC ## - check if model has 'mode: responses' in litellm.model_cost map
model_info, model = responses_api_bridge_check(
- model=model, custom_llm_provider=custom_llm_provider
+ model=model, custom_llm_provider=custom_llm_provider, web_search_options=web_search_options
)
if model_info.get("mode") == "responses":
@@ -2211,6 +2206,48 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging, # model call logging done inside the class as we make need to modify I/O to fit aleph alpha's requirements
client=client,
)
+ elif custom_llm_provider == "a2a":
+ # A2A (Agent-to-Agent) Protocol
+ # Resolve agent configuration from registry if model format is "a2a/"
+ api_base, api_key, headers = litellm.A2AConfig.resolve_agent_config_from_registry(
+ model=model,
+ api_base=api_base,
+ api_key=api_key,
+ headers=headers,
+ optional_params=optional_params,
+ )
+
+ # Fall back to environment variables and defaults
+ api_base = api_base or litellm.api_base or get_secret_str("A2A_API_BASE")
+
+ if api_base is None:
+ raise Exception(
+ "api_base is required for A2A provider. "
+ "Either provide api_base parameter, set A2A_API_BASE environment variable, "
+ "or register the agent in the proxy with model='a2a/'."
+ )
+
+ headers = headers or litellm.headers
+
+ response = base_llm_http_handler.completion(
+ model=model,
+ stream=stream,
+ messages=messages,
+ acompletion=acompletion,
+ api_base=api_base,
+ model_response=model_response,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ shared_session=shared_session,
+ custom_llm_provider=custom_llm_provider,
+ timeout=timeout,
+ headers=headers,
+ encoding=_get_encoding(),
+ api_key=api_key,
+ logging_obj=logging,
+ client=client,
+ provider_config=provider_config,
+ )
elif custom_llm_provider == "gigachat":
# GigaChat - Sber AI's LLM (Russia)
api_key = (
@@ -2361,11 +2398,7 @@ def completion( # type: ignore # noqa: PLR0915
input=messages, api_key=api_key, original_response=response
)
elif custom_llm_provider == "minimax":
- api_key = (
- api_key
- or get_secret_str("MINIMAX_API_KEY")
- or litellm.api_key
- )
+ api_key = api_key or get_secret_str("MINIMAX_API_KEY") or litellm.api_key
api_base = (
api_base
@@ -2374,6 +2407,33 @@ def completion( # type: ignore # noqa: PLR0915
or "https://api.minimax.io/v1"
)
+ response = base_llm_http_handler.completion(
+ model=model,
+ messages=messages,
+ api_base=api_base,
+ custom_llm_provider=custom_llm_provider,
+ model_response=model_response,
+ encoding=_get_encoding(),
+ logging_obj=logging,
+ optional_params=optional_params,
+ timeout=timeout,
+ litellm_params=litellm_params,
+ shared_session=shared_session,
+ acompletion=acompletion,
+ stream=stream,
+ api_key=api_key,
+ headers=headers,
+ client=client,
+ provider_config=provider_config,
+ )
+ logging.post_call(
+ input=messages, api_key=api_key, original_response=response
+ )
+ elif custom_llm_provider == "hosted_vllm":
+ api_base = (
+ api_base or litellm.api_base or get_secret_str("HOSTED_VLLM_API_BASE")
+ )
+
response = base_llm_http_handler.completion(
model=model,
messages=messages,
@@ -2413,7 +2473,9 @@ def completion( # type: ignore # noqa: PLR0915
or custom_llm_provider == "wandb"
or custom_llm_provider == "clarifai"
or custom_llm_provider in litellm.openai_compatible_providers
- or JSONProviderRegistry.exists(custom_llm_provider) # JSON-configured providers
+ or JSONProviderRegistry.exists(
+ custom_llm_provider
+ ) # JSON-configured providers
or "ft:gpt-3.5-turbo" in model # finetune gpt-3.5-turbo
): # allow user to make an openai call with a custom base
# note: if a user sets a custom base - we should ensure this works
@@ -2442,6 +2504,20 @@ def completion( # type: ignore # noqa: PLR0915
headers = headers or litellm.headers
+ # Add GitHub Copilot headers (same as /responses endpoint does)
+ if custom_llm_provider == "github_copilot":
+ from litellm.llms.github_copilot.common_utils import (
+ get_copilot_default_headers,
+ )
+ from litellm.llms.github_copilot.authenticator import Authenticator
+
+ copilot_auth = Authenticator()
+ copilot_api_key = copilot_auth.get_api_key()
+ copilot_headers = get_copilot_default_headers(copilot_api_key)
+ if extra_headers:
+ copilot_headers.update(extra_headers)
+ extra_headers = copilot_headers
+
if extra_headers is not None:
optional_params["extra_headers"] = extra_headers
@@ -3100,8 +3176,8 @@ def completion( # type: ignore # noqa: PLR0915
api_key
or litellm.api_key
or litellm.openrouter_key
- or get_secret("OPENROUTER_API_KEY")
- or get_secret("OR_API_KEY")
+ or get_secret_str("OPENROUTER_API_KEY")
+ or get_secret_str("OR_API_KEY")
)
openrouter_site_url = get_secret("OR_SITE_URL") or "https://litellm.ai"
@@ -3610,9 +3686,9 @@ def completion( # type: ignore # noqa: PLR0915
"aws_region_name" not in optional_params
or optional_params["aws_region_name"] is None
):
- optional_params[
- "aws_region_name"
- ] = aws_bedrock_client.meta.region_name
+ optional_params["aws_region_name"] = (
+ aws_bedrock_client.meta.region_name
+ )
bedrock_route = BedrockModelInfo.get_bedrock_route(model)
if bedrock_route == "converse":
@@ -4542,6 +4618,13 @@ def embedding( # noqa: PLR0915
headers = {}
if extra_headers is not None:
headers.update(extra_headers)
+ # Inject proxy auth headers if configured
+ if litellm.proxy_auth is not None:
+ try:
+ proxy_headers = litellm.proxy_auth.get_auth_headers()
+ headers.update(proxy_headers)
+ except Exception as e:
+ verbose_logger.warning(f"Failed to get proxy auth headers: {e}")
### CUSTOM MODEL COST ###
input_cost_per_token = kwargs.get("input_cost_per_token", None)
output_cost_per_token = kwargs.get("output_cost_per_token", None)
@@ -4696,11 +4779,11 @@ def embedding( # noqa: PLR0915
litellm_params=litellm_params_dict,
)
elif (
- model in litellm.open_ai_embedding_models
- or custom_llm_provider == "openai"
+ custom_llm_provider == "openai"
or custom_llm_provider == "together_ai"
or custom_llm_provider == "nvidia_nim"
or custom_llm_provider == "litellm_proxy"
+ or (model in litellm.open_ai_embedding_models and custom_llm_provider is None)
):
api_base = (
api_base
@@ -4724,7 +4807,7 @@ def embedding( # noqa: PLR0915
if headers is not None and headers != {}:
optional_params["extra_headers"] = headers
-
+
if encoding_format is not None:
optional_params["encoding_format"] = encoding_format
else:
@@ -4772,9 +4855,32 @@ def embedding( # noqa: PLR0915
client=client,
aembedding=aembedding,
)
+ elif custom_llm_provider == "hosted_vllm":
+ api_base = (
+ api_base or litellm.api_base or get_secret_str("HOSTED_VLLM_API_BASE")
+ )
+
+ # set API KEY
+ if api_key is None:
+ api_key = litellm.api_key or get_secret_str("HOSTED_VLLM_API_KEY")
+
+ response = base_llm_http_handler.embedding(
+ model=model,
+ input=input,
+ custom_llm_provider=custom_llm_provider,
+ api_base=api_base,
+ api_key=api_key,
+ logging_obj=logging,
+ timeout=timeout,
+ model_response=EmbeddingResponse(),
+ optional_params=optional_params,
+ client=client,
+ aembedding=aembedding,
+ litellm_params=litellm_params_dict,
+ headers=headers or {},
+ )
elif (
custom_llm_provider == "openai_like"
- or custom_llm_provider == "hosted_vllm"
or custom_llm_provider == "llamafile"
or custom_llm_provider == "lm_studio"
):
@@ -4848,8 +4954,8 @@ def embedding( # noqa: PLR0915
api_key
or litellm.api_key
or litellm.openrouter_key
- or get_secret("OPENROUTER_API_KEY")
- or get_secret("OR_API_KEY")
+ or get_secret_str("OPENROUTER_API_KEY")
+ or get_secret_str("OR_API_KEY")
)
openrouter_site_url = get_secret("OR_SITE_URL") or "https://litellm.ai"
@@ -5947,9 +6053,9 @@ def adapter_completion(
new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs)
response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore
- translated_response: Optional[
- Union[BaseModel, AdapterCompletionStreamWrapper]
- ] = None
+ translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = (
+ None
+ )
if isinstance(response, ModelResponse):
translated_response = translation_obj.translate_completion_output_params(
response=response
@@ -6654,9 +6760,9 @@ def speech( # noqa: PLR0915
ElevenLabsTextToSpeechConfig.ELEVENLABS_QUERY_PARAMS_KEY
] = query_params
- litellm_params_dict[
- ElevenLabsTextToSpeechConfig.ELEVENLABS_VOICE_ID_KEY
- ] = voice_id
+ litellm_params_dict[ElevenLabsTextToSpeechConfig.ELEVENLABS_VOICE_ID_KEY] = (
+ voice_id
+ )
if api_base is not None:
litellm_params_dict["api_base"] = api_base
@@ -6789,9 +6895,7 @@ def speech( # noqa: PLR0915
if text_to_speech_provider_config is None:
text_to_speech_provider_config = MinimaxTextToSpeechConfig()
- minimax_config = cast(
- MinimaxTextToSpeechConfig, text_to_speech_provider_config
- )
+ minimax_config = cast(MinimaxTextToSpeechConfig, text_to_speech_provider_config)
if api_base is not None:
litellm_params_dict["api_base"] = api_base
@@ -6931,7 +7035,7 @@ async def ahealth_check(
custom_llm_provider_from_params = model_params.get("custom_llm_provider", None)
api_base_from_params = model_params.get("api_base", None)
api_key_from_params = model_params.get("api_key", None)
-
+
model, custom_llm_provider, _, _ = get_llm_provider(
model=model,
custom_llm_provider=custom_llm_provider_from_params,
@@ -7164,9 +7268,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(content_chunks) > 0:
- response["choices"][0]["message"][
- "content"
- ] = processor.get_combined_content(content_chunks)
+ response["choices"][0]["message"]["content"] = (
+ processor.get_combined_content(content_chunks)
+ )
thinking_blocks = [
chunk
@@ -7177,9 +7281,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(thinking_blocks) > 0:
- response["choices"][0]["message"][
- "thinking_blocks"
- ] = processor.get_combined_thinking_content(thinking_blocks)
+ response["choices"][0]["message"]["thinking_blocks"] = (
+ processor.get_combined_thinking_content(thinking_blocks)
+ )
reasoning_chunks = [
chunk
@@ -7190,9 +7294,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(reasoning_chunks) > 0:
- response["choices"][0]["message"][
- "reasoning_content"
- ] = processor.get_combined_reasoning_content(reasoning_chunks)
+ response["choices"][0]["message"]["reasoning_content"] = (
+ processor.get_combined_reasoning_content(reasoning_chunks)
+ )
annotation_chunks = [
chunk
@@ -7218,6 +7322,23 @@ def stream_chunk_builder( # noqa: PLR0915
_choice = cast(Choices, response.choices[0])
_choice.message.audio = processor.get_combined_audio_content(audio_chunks)
+ # Handle image chunks from models like gemini-2.5-flash-image
+ # See: https://github.com/BerriAI/litellm/issues/19478
+ image_chunks = [
+ chunk
+ for chunk in chunks
+ if len(chunk["choices"]) > 0
+ and "images" in chunk["choices"][0]["delta"]
+ and chunk["choices"][0]["delta"]["images"] is not None
+ ]
+
+ if len(image_chunks) > 0:
+ # Images come complete in a single chunk, collect all images from all chunks
+ all_images = []
+ for chunk in image_chunks:
+ all_images.extend(chunk["choices"][0]["delta"]["images"])
+ response["choices"][0]["message"]["images"] = all_images
+
# Combine provider_specific_fields from streaming chunks (e.g., web_search_results, citations)
# See: https://github.com/BerriAI/litellm/issues/17737
provider_specific_chunks = [
@@ -7262,6 +7383,16 @@ def stream_chunk_builder( # noqa: PLR0915
setattr(response, "usage", usage)
+ # Propagate provider_specific_fields from the last chunk (contains provider
+ # metadata like traffic_type set during streaming)
+ for chunk in reversed(chunks):
+ hidden = getattr(chunk, "_hidden_params", None)
+ if hidden and "provider_specific_fields" in hidden:
+ response._hidden_params.setdefault(
+ "provider_specific_fields", {}
+ ).update(hidden["provider_specific_fields"])
+ break
+
# Add cost to usage object if include_cost_in_streaming_usage is True
if litellm.include_cost_in_streaming_usage and logging_obj is not None:
setattr(
@@ -7301,12 +7432,16 @@ def _get_encoding():
def __getattr__(name: str) -> Any:
"""Lazy import handler for main module"""
if name == "encoding":
- # Lazy load encoding to avoid heavy tiktoken import at module load time
- _encoding = tiktoken.get_encoding("cl100k_base")
+ # Use _get_default_encoding which properly sets TIKTOKEN_CACHE_DIR
+ # before loading tiktoken, ensuring the local cache is used
+ # instead of downloading from the internet
+ from litellm._lazy_imports import _get_default_encoding
+ _encoding = _get_default_encoding()
# Cache it in the module's __dict__ for subsequent accesses
import sys
+
sys.modules[__name__].__dict__["encoding"] = _encoding
global _encoding_cache
_encoding_cache = _encoding
return _encoding
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
\ No newline at end of file
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index ab034d9f51b..2c89e53ada9 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -354,6 +354,25 @@
"supports_video_input": true,
"supports_vision": true
},
+ "amazon.nova-2-pro-preview-20251202-v1:0": {
+ "cache_read_input_token_cost": 5.46875e-07,
+ "input_cost_per_token": 2.1875e-06,
+ "input_cost_per_image_token": 2.1875e-06,
+ "input_cost_per_audio_token": 2.1875e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.75e-05,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_video_input": true,
+ "supports_vision": true
+ },
"apac.amazon.nova-2-lite-v1:0": {
"cache_read_input_token_cost": 8.25e-08,
"input_cost_per_token": 3.3e-07,
@@ -371,6 +390,25 @@
"supports_video_input": true,
"supports_vision": true
},
+ "apac.amazon.nova-2-pro-preview-20251202-v1:0": {
+ "cache_read_input_token_cost": 5.46875e-07,
+ "input_cost_per_token": 2.1875e-06,
+ "input_cost_per_image_token": 2.1875e-06,
+ "input_cost_per_audio_token": 2.1875e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.75e-05,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_video_input": true,
+ "supports_vision": true
+ },
"eu.amazon.nova-2-lite-v1:0": {
"cache_read_input_token_cost": 8.25e-08,
"input_cost_per_token": 3.3e-07,
@@ -388,6 +426,25 @@
"supports_video_input": true,
"supports_vision": true
},
+ "eu.amazon.nova-2-pro-preview-20251202-v1:0": {
+ "cache_read_input_token_cost": 5.46875e-07,
+ "input_cost_per_token": 2.1875e-06,
+ "input_cost_per_image_token": 2.1875e-06,
+ "input_cost_per_audio_token": 2.1875e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.75e-05,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_video_input": true,
+ "supports_vision": true
+ },
"us.amazon.nova-2-lite-v1:0": {
"cache_read_input_token_cost": 8.25e-08,
"input_cost_per_token": 3.3e-07,
@@ -405,6 +462,25 @@
"supports_video_input": true,
"supports_vision": true
},
+ "us.amazon.nova-2-pro-preview-20251202-v1:0": {
+ "cache_read_input_token_cost": 5.46875e-07,
+ "input_cost_per_token": 2.1875e-06,
+ "input_cost_per_image_token": 2.1875e-06,
+ "input_cost_per_audio_token": 2.1875e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.75e-05,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_video_input": true,
+ "supports_vision": true
+ },
"amazon.nova-2-multimodal-embeddings-v1:0": {
"litellm_provider": "bedrock",
"max_input_tokens": 8172,
@@ -668,12 +744,13 @@
"supports_response_schema": true,
"supports_tool_choice": true,
"supports_vision": true,
- "tool_use_system_prompt_tokens": 346
+ "tool_use_system_prompt_tokens": 346,
+ "supports_native_streaming": true
},
"anthropic.claude-3-5-sonnet-20240620-v1:0": {
"input_cost_per_token": 3e-06,
"litellm_provider": "bedrock",
- "max_input_tokens": 200000,
+ "max_input_tokens": 1000000,
"max_output_tokens": 4096,
"max_tokens": 4096,
"mode": "chat",
@@ -682,14 +759,22 @@
"supports_pdf_input": true,
"supports_response_schema": true,
"supports_tool_choice": true,
- "supports_vision": true
+ "supports_vision": true,
+ "input_cost_per_token_above_200k_tokens": 6e-06,
+ "output_cost_per_token_above_200k_tokens": 3e-05,
+ "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
+ "cache_read_input_token_cost_above_200k_tokens": 6e-07,
+ "cache_creation_input_token_cost_above_1hr": 7.5e-06,
+ "cache_creation_input_token_cost_above_1hr_above_200k_tokens": 1.5e-05,
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_read_input_token_cost": 3e-07
},
"anthropic.claude-3-5-sonnet-20241022-v2:0": {
"cache_creation_input_token_cost": 3.75e-06,
"cache_read_input_token_cost": 3e-07,
"input_cost_per_token": 3e-06,
"litellm_provider": "bedrock",
- "max_input_tokens": 200000,
+ "max_input_tokens": 1000000,
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
@@ -701,7 +786,13 @@
"supports_prompt_caching": true,
"supports_response_schema": true,
"supports_tool_choice": true,
- "supports_vision": true
+ "supports_vision": true,
+ "input_cost_per_token_above_200k_tokens": 6e-06,
+ "output_cost_per_token_above_200k_tokens": 3e-05,
+ "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
+ "cache_read_input_token_cost_above_200k_tokens": 6e-07,
+ "cache_creation_input_token_cost_above_1hr": 7.5e-06,
+ "cache_creation_input_token_cost_above_1hr_above_200k_tokens": 1.5e-05
},
"anthropic.claude-3-7-sonnet-20240620-v1:0": {
"cache_creation_input_token_cost": 4.5e-06,
@@ -872,6 +963,306 @@
"supports_vision": true,
"tool_use_system_prompt_tokens": 159
},
+ "anthropic.claude-opus-4-6-v1": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 5e-06,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "global.anthropic.claude-opus-4-6-v1": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 5e-06,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "us.anthropic.claude-opus-4-6-v1": {
+ "cache_creation_input_token_cost": 6.875e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05,
+ "cache_read_input_token_cost": 5.5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1.1e-06,
+ "input_cost_per_token": 5.5e-06,
+ "input_cost_per_token_above_200k_tokens": 1.1e-05,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.75e-05,
+ "output_cost_per_token_above_200k_tokens": 4.125e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "eu.anthropic.claude-opus-4-6-v1": {
+ "cache_creation_input_token_cost": 6.875e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05,
+ "cache_read_input_token_cost": 5.5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1.1e-06,
+ "input_cost_per_token": 5.5e-06,
+ "input_cost_per_token_above_200k_tokens": 1.1e-05,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.75e-05,
+ "output_cost_per_token_above_200k_tokens": 4.125e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "au.anthropic.claude-opus-4-6-v1": {
+ "cache_creation_input_token_cost": 6.875e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05,
+ "cache_read_input_token_cost": 5.5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1.1e-06,
+ "input_cost_per_token": 5.5e-06,
+ "input_cost_per_token_above_200k_tokens": 1.1e-05,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.75e-05,
+ "output_cost_per_token_above_200k_tokens": 4.125e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "anthropic.claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6e-07,
+ "input_cost_per_token": 3e-06,
+ "input_cost_per_token_above_200k_tokens": 6e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "output_cost_per_token_above_200k_tokens": 2.25e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "global.anthropic.claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6e-07,
+ "input_cost_per_token": 3e-06,
+ "input_cost_per_token_above_200k_tokens": 6e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "output_cost_per_token_above_200k_tokens": 2.25e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "us.anthropic.claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 4.125e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 8.25e-06,
+ "cache_read_input_token_cost": 3.3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6.6e-07,
+ "input_cost_per_token": 3.3e-06,
+ "input_cost_per_token_above_200k_tokens": 6.6e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.65e-05,
+ "output_cost_per_token_above_200k_tokens": 2.475e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "eu.anthropic.claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 4.125e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 8.25e-06,
+ "cache_read_input_token_cost": 3.3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6.6e-07,
+ "input_cost_per_token": 3.3e-06,
+ "input_cost_per_token_above_200k_tokens": 6.6e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.65e-05,
+ "output_cost_per_token_above_200k_tokens": 2.475e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "apac.anthropic.claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 4.125e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 8.25e-06,
+ "cache_read_input_token_cost": 3.3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6.6e-07,
+ "input_cost_per_token": 3.3e-06,
+ "input_cost_per_token_above_200k_tokens": 6.6e-06,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.65e-05,
+ "output_cost_per_token_above_200k_tokens": 2.475e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
"anthropic.claude-sonnet-4-20250514-v1:0": {
"cache_creation_input_token_cost": 3.75e-06,
"cache_read_input_token_cost": 3e-07,
@@ -1312,6 +1703,9 @@
"supports_function_calling": true
},
"azure_ai/claude-haiku-4-5": {
+ "cache_creation_input_token_cost": 1.25e-06,
+ "cache_creation_input_token_cost_above_1hr": 2e-06,
+ "cache_read_input_token_cost": 1e-07,
"input_cost_per_token": 1e-06,
"litellm_provider": "azure_ai",
"max_input_tokens": 200000,
@@ -1330,6 +1724,9 @@
"supports_vision": true
},
"azure_ai/claude-opus-4-5": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_1hr": 1e-05,
+ "cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 5e-06,
"litellm_provider": "azure_ai",
"max_input_tokens": 200000,
@@ -1347,7 +1744,37 @@
"supports_tool_choice": true,
"supports_vision": true
},
+ "azure_ai/claude-opus-4-6": {
+ "input_cost_per_token": 5e-06,
+ "output_cost_per_token": 2.5e-05,
+ "litellm_provider": "azure_ai",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_1hr": 1e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 159
+ },
"azure_ai/claude-opus-4-1": {
+ "cache_creation_input_token_cost": 1.875e-05,
+ "cache_creation_input_token_cost_above_1hr": 3e-05,
+ "cache_read_input_token_cost": 1.5e-06,
"input_cost_per_token": 1.5e-05,
"litellm_provider": "azure_ai",
"max_input_tokens": 200000,
@@ -1366,6 +1793,9 @@
"supports_vision": true
},
"azure_ai/claude-sonnet-4-5": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_creation_input_token_cost_above_1hr": 6e-06,
+ "cache_read_input_token_cost": 3e-07,
"input_cost_per_token": 3e-06,
"litellm_provider": "azure_ai",
"max_input_tokens": 200000,
@@ -1383,6 +1813,28 @@
"supports_tool_choice": true,
"supports_vision": true
},
+ "azure_ai/claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_creation_input_token_cost_above_1hr": 6e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "azure_ai",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
"azure/computer-use-preview": {
"input_cost_per_token": 3e-06,
"litellm_provider": "azure",
@@ -1429,6 +1881,14 @@
"supports_response_schema": true,
"supports_tool_choice": true
},
+ "azure_ai/model_router": {
+ "input_cost_per_token": 1.4e-07,
+ "output_cost_per_token": 0,
+ "litellm_provider": "azure_ai",
+ "mode": "chat",
+ "source": "https://azure.microsoft.com/en-us/pricing/details/ai-services/",
+ "comment": "Flat cost of $0.14 per M input tokens for Azure AI Foundry Model Router infrastructure. Use pattern: azure_ai/model_router/ where deployment-name is your Azure deployment (e.g., azure-model-router)"
+ },
"azure/eu/gpt-4o-2024-08-06": {
"deprecation_date": "2026-02-27",
"cache_read_input_token_cost": 1.375e-06,
@@ -3118,7 +3578,7 @@
"supports_reasoning": true,
"supports_response_schema": true,
"supports_system_messages": true,
- "supports_tool_choice": false,
+ "supports_tool_choice": true,
"supports_vision": true
},
"azure/gpt-5-chat-latest": {
@@ -3150,7 +3610,7 @@
"supports_reasoning": true,
"supports_response_schema": true,
"supports_system_messages": true,
- "supports_tool_choice": false,
+ "supports_tool_choice": true,
"supports_vision": true
},
"azure/gpt-5-codex": {
@@ -3638,13 +4098,12 @@
"cache_read_input_token_cost": 1.75e-07,
"input_cost_per_token": 1.75e-06,
"litellm_provider": "azure",
- "max_input_tokens": 128000,
- "max_output_tokens": 16384,
- "max_tokens": 16384,
- "mode": "chat",
+ "max_input_tokens": 272000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "responses",
"output_cost_per_token": 1.4e-05,
"supported_endpoints": [
- "/v1/chat/completions",
"/v1/responses"
],
"supported_modalities": [
@@ -5561,6 +6020,20 @@
"output_cost_per_token": 7e-07,
"supports_tool_choice": true
},
+ "azure_ai/kimi-k2.5": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "azure_ai",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "source": "https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/kimi-k2-5-now-in-microsoft-foundry/4492321",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_video_input": true,
+ "supports_vision": true
+ },
"azure_ai/ministral-3b": {
"input_cost_per_token": 4e-08,
"litellm_provider": "azure_ai",
@@ -5804,6 +6277,97 @@
"output_cost_per_token": 2.4e-05,
"supports_tool_choice": true
},
+ "bedrock/ap-northeast-1/deepseek.v3.2": {
+ "input_cost_per_token": 7.4e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 2.22e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-northeast-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-northeast-1/moonshotai.kimi-k2-thinking": {
+ "input_cost_per_token": 7.3e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.03e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true
+ },
+ "bedrock/ap-northeast-1/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 7.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.6e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-northeast-1/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/moonshotai.kimi-k2-thinking": {
+ "input_cost_per_token": 7.3e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.03e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true
+ },
+ "bedrock/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.03e-06,
+ "source": "https://platform.moonshot.ai/docs/guide/kimi-k2-5-quickstart",
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_video_input": true,
+ "supports_vision": true
+ },
"bedrock/ap-south-1/meta.llama3-70b-instruct-v1:0": {
"input_cost_per_token": 3.18e-06,
"litellm_provider": "bedrock",
@@ -5822,6 +6386,123 @@
"mode": "chat",
"output_cost_per_token": 7.2e-07
},
+ "bedrock/ap-south-1/deepseek.v3.2": {
+ "input_cost_per_token": 7.4e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 2.22e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-south-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-south-1/moonshotai.kimi-k2-thinking": {
+ "input_cost_per_token": 7.1e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 2.94e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true
+ },
+ "bedrock/ap-south-1/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 7.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.6e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-south-1/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-southeast-3/deepseek.v3.2": {
+ "input_cost_per_token": 7.4e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 2.22e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-southeast-3/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-southeast-3/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 7.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.6e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/ap-southeast-3/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/ca-central-1/meta.llama3-70b-instruct-v1:0": {
"input_cost_per_token": 3.05e-06,
"litellm_provider": "bedrock",
@@ -5840,6 +6521,46 @@
"mode": "chat",
"output_cost_per_token": 6.9e-07
},
+ "bedrock/eu-north-1/deepseek.v3.2": {
+ "input_cost_per_token": 7.4e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 2.22e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/eu-north-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/eu-north-1/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 7.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.6e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/eu-central-1/1-month-commitment/anthropic.claude-instant-v1": {
"input_cost_per_second": 0.01635,
"litellm_provider": "bedrock",
@@ -5927,6 +6648,32 @@
"output_cost_per_token": 2.4e-05,
"supports_tool_choice": true
},
+ "bedrock/eu-central-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/eu-central-1/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/eu-west-1/meta.llama3-70b-instruct-v1:0": {
"input_cost_per_token": 2.86e-06,
"litellm_provider": "bedrock",
@@ -5945,6 +6692,32 @@
"mode": "chat",
"output_cost_per_token": 6.5e-07
},
+ "bedrock/eu-west-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/eu-west-1/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/eu-west-2/meta.llama3-70b-instruct-v1:0": {
"input_cost_per_token": 3.45e-06,
"litellm_provider": "bedrock",
@@ -5963,6 +6736,32 @@
"mode": "chat",
"output_cost_per_token": 7.8e-07
},
+ "bedrock/eu-west-2/minimax.minimax-m2.1": {
+ "input_cost_per_token": 4.7e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.86e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/eu-west-2/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 7.8e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.86e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/eu-west-3/mistral.mistral-7b-instruct-v0:2": {
"input_cost_per_token": 2e-07,
"litellm_provider": "bedrock",
@@ -5993,6 +6792,32 @@
"output_cost_per_token": 9.1e-07,
"supports_tool_choice": true
},
+ "bedrock/eu-south-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/eu-south-1/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/invoke/anthropic.claude-3-5-sonnet-20240620-v1:0": {
"input_cost_per_token": 3e-06,
"litellm_provider": "bedrock",
@@ -6027,6 +6852,70 @@
"mode": "chat",
"output_cost_per_token": 1.01e-06
},
+ "bedrock/sa-east-1/deepseek.v3.2": {
+ "input_cost_per_token": 7.4e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 2.22e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/sa-east-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3.6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/sa-east-1/moonshotai.kimi-k2-thinking": {
+ "input_cost_per_token": 7.3e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.03e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true
+ },
+ "bedrock/sa-east-1/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 7.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3.6e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/sa-east-1/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.44e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/us-east-1/1-month-commitment/anthropic.claude-instant-v1": {
"input_cost_per_second": 0.011,
"litellm_provider": "bedrock",
@@ -6163,6 +7052,134 @@
"output_cost_per_token": 7e-07,
"supports_tool_choice": true
},
+ "bedrock/us-east-1/deepseek.v3.2": {
+ "input_cost_per_token": 6.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 1.85e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-east-1/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-east-1/moonshotai.kimi-k2-thinking": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true
+ },
+ "bedrock/us-east-1/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-east-1/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 5e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-east-2/deepseek.v3.2": {
+ "input_cost_per_token": 6.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 1.85e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-east-2/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-east-2/moonshotai.kimi-k2-thinking": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true
+ },
+ "bedrock/us-east-2/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-east-2/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 5e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/us-gov-east-1/amazon.nova-pro-v1:0": {
"input_cost_per_token": 9.6e-07,
"litellm_provider": "bedrock",
@@ -6569,6 +7586,70 @@
"output_cost_per_token": 7e-07,
"supports_tool_choice": true
},
+ "bedrock/us-west-2/deepseek.v3.2": {
+ "input_cost_per_token": 6.2e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 1.85e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-west-2/minimax.minimax-m2.1": {
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-west-2/moonshotai.kimi-k2-thinking": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true
+ },
+ "bedrock/us-west-2/moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
+ "bedrock/us-west-2/qwen.qwen3-coder-next": {
+ "input_cost_per_token": 5e-07,
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"bedrock/us.anthropic.claude-3-5-haiku-20241022-v1:0": {
"cache_creation_input_token_cost": 1e-06,
"cache_read_input_token_cost": 8e-08,
@@ -6620,13 +7701,13 @@
"supports_tool_choice": true
},
"cerebras/gpt-oss-120b": {
- "input_cost_per_token": 2.5e-07,
+ "input_cost_per_token": 3.5e-07,
"litellm_provider": "cerebras",
"max_input_tokens": 131072,
"max_output_tokens": 32768,
"max_tokens": 32768,
"mode": "chat",
- "output_cost_per_token": 6.9e-07,
+ "output_cost_per_token": 7.5e-07,
"source": "https://www.cerebras.ai/blog/openai-gpt-oss-120b-runs-fastest-on-cerebras",
"supports_function_calling": true,
"supports_parallel_function_calling": true,
@@ -6644,6 +7725,7 @@
"output_cost_per_token": 8e-07,
"source": "https://inference-docs.cerebras.ai/support/pricing",
"supports_function_calling": true,
+ "supports_reasoning": true,
"supports_tool_choice": true
},
"cerebras/zai-glm-4.6": {
@@ -7182,6 +8264,67 @@
"supports_web_search": true,
"tool_use_system_prompt_tokens": 346
},
+ "claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6e-07,
+ "input_cost_per_token": 3e-06,
+ "input_cost_per_token_above_200k_tokens": 6e-06,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "output_cost_per_token_above_200k_tokens": 2.25e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "us/claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 4.125e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 8.25e-06,
+ "cache_read_input_token_cost": 3.3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6.6e-07,
+ "input_cost_per_token": 3.3e-06,
+ "input_cost_per_token_above_200k_tokens": 6.6e-06,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.65e-05,
+ "output_cost_per_token_above_200k_tokens": 2.475e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346,
+ "inference_geo": "us"
+ },
"claude-sonnet-4-5-20250929-v1:0": {
"cache_creation_input_token_cost": 3.75e-06,
"cache_read_input_token_cost": 3e-07,
@@ -7344,6 +8487,223 @@
"supports_vision": true,
"tool_use_system_prompt_tokens": 159
},
+ "claude-opus-4-6": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_creation_input_token_cost_above_1hr": 1e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 5e-06,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "fast/claude-opus-4-6": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_creation_input_token_cost_above_1hr": 1e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 3e-05,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 0.00015,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "us/claude-opus-4-6": {
+ "cache_creation_input_token_cost": 6.875e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05,
+ "cache_creation_input_token_cost_above_1hr": 1.1e-05,
+ "cache_read_input_token_cost": 5.5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1.1e-06,
+ "input_cost_per_token": 5.5e-06,
+ "input_cost_per_token_above_200k_tokens": 1.1e-05,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.75e-05,
+ "output_cost_per_token_above_200k_tokens": 4.125e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "fast/us/claude-opus-4-6": {
+ "cache_creation_input_token_cost": 6.875e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05,
+ "cache_creation_input_token_cost_above_1hr": 1.1e-05,
+ "cache_read_input_token_cost": 5.5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1.1e-06,
+ "input_cost_per_token": 3e-05,
+ "input_cost_per_token_above_200k_tokens": 1.1e-05,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 0.00015,
+ "output_cost_per_token_above_200k_tokens": 4.125e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "claude-opus-4-6-20260205": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_creation_input_token_cost_above_1hr": 1e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 5e-06,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "fast/claude-opus-4-6-20260205": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_creation_input_token_cost_above_1hr": 1e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 3e-05,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 0.00015,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "us/claude-opus-4-6-20260205": {
+ "cache_creation_input_token_cost": 6.875e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05,
+ "cache_creation_input_token_cost_above_1hr": 1.1e-05,
+ "cache_read_input_token_cost": 5.5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1.1e-06,
+ "input_cost_per_token": 5.5e-06,
+ "input_cost_per_token_above_200k_tokens": 1.1e-05,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.75e-05,
+ "output_cost_per_token_above_200k_tokens": 4.125e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
"claude-sonnet-4-20250514": {
"deprecation_date": "2026-05-14",
"cache_creation_input_token_cost": 3.75e-06,
@@ -8440,6 +9800,43 @@
}
]
},
+ "dashscope/qwen3-max": {
+ "litellm_provider": "dashscope",
+ "max_input_tokens": 258048,
+ "max_output_tokens": 65536,
+ "max_tokens": 65536,
+ "mode": "chat",
+ "source": "https://www.alibabacloud.com/help/en/model-studio/models",
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "tiered_pricing": [
+ {
+ "input_cost_per_token": 1.2e-06,
+ "output_cost_per_token": 6e-06,
+ "range": [
+ 0,
+ 32000.0
+ ]
+ },
+ {
+ "input_cost_per_token": 2.4e-06,
+ "output_cost_per_token": 1.2e-05,
+ "range": [
+ 32000.0,
+ 128000.0
+ ]
+ },
+ {
+ "input_cost_per_token": 3e-06,
+ "output_cost_per_token": 1.5e-05,
+ "range": [
+ 128000.0,
+ 252000.0
+ ]
+ }
+ ]
+ },
"dashscope/qwq-plus": {
"input_cost_per_token": 8e-07,
"litellm_provider": "dashscope",
@@ -9776,6 +11173,7 @@
"supports_tool_choice": true
},
"deepinfra/google/gemini-2.0-flash-001": {
+ "deprecation_date": "2026-03-31",
"max_tokens": 1000000,
"max_input_tokens": 1000000,
"max_output_tokens": 1000000,
@@ -10112,14 +11510,22 @@
"input_cost_per_token": 2.8e-07,
"input_cost_per_token_cache_hit": 2.8e-08,
"litellm_provider": "deepseek",
- "max_input_tokens": 128000,
+ "max_input_tokens": 131072,
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
"output_cost_per_token": 4.2e-07,
+ "source": "https://api-docs.deepseek.com/quick_start/pricing",
+ "supported_endpoints": [
+ "/v1/chat/completions"
+ ],
"supports_assistant_prefill": true,
"supports_function_calling": true,
+ "supports_native_streaming": true,
+ "supports_parallel_function_calling": true,
"supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
"supports_tool_choice": true
},
"deepseek/deepseek-coder": {
@@ -10156,16 +11562,24 @@
"input_cost_per_token": 2.8e-07,
"input_cost_per_token_cache_hit": 2.8e-08,
"litellm_provider": "deepseek",
- "max_input_tokens": 128000,
- "max_output_tokens": 8192,
- "max_tokens": 8192,
+ "max_input_tokens": 131072,
+ "max_output_tokens": 65536,
+ "max_tokens": 65536,
"mode": "chat",
"output_cost_per_token": 4.2e-07,
+ "source": "https://api-docs.deepseek.com/quick_start/pricing",
+ "supported_endpoints": [
+ "/v1/chat/completions"
+ ],
"supports_assistant_prefill": true,
- "supports_function_calling": true,
+ "supports_function_calling": false,
+ "supports_native_streaming": true,
+ "supports_parallel_function_calling": false,
"supports_prompt_caching": true,
"supports_reasoning": true,
- "supports_tool_choice": true
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": false
},
"deepseek/deepseek-v3": {
"cache_creation_input_token_cost": 0.0,
@@ -10210,6 +11624,19 @@
"supports_reasoning": true,
"supports_tool_choice": true
},
+ "deepseek.v3.2": {
+ "input_cost_per_token": 6.2e-07,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 1.85e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"dolphin": {
"input_cost_per_token": 5e-07,
"litellm_provider": "nlp_cloud",
@@ -10219,6 +11646,48 @@
"mode": "completion",
"output_cost_per_token": 5e-07
},
+ "deepseek-v3-2-251201": {
+ "input_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "max_input_tokens": 98304,
+ "max_output_tokens": 32768,
+ "max_tokens": 32768,
+ "mode": "chat",
+ "output_cost_per_token": 0.0,
+ "supports_assistant_prefill": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
+ "glm-4-7-251222": {
+ "input_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "max_tokens": 131072,
+ "mode": "chat",
+ "output_cost_per_token": 0.0,
+ "supports_assistant_prefill": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
+ "kimi-k2-thinking-251104": {
+ "input_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "max_input_tokens": 229376,
+ "max_output_tokens": 32768,
+ "max_tokens": 32768,
+ "mode": "chat",
+ "output_cost_per_token": 0.0,
+ "supports_assistant_prefill": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
"doubao-embedding": {
"input_cost_per_token": 0.0,
"litellm_provider": "volcengine",
@@ -10421,6 +11890,32 @@
"/v1/audio/transcriptions"
]
},
+ "elevenlabs/eleven_v3": {
+ "input_cost_per_character": 0.00018,
+ "litellm_provider": "elevenlabs",
+ "metadata": {
+ "calculation": "$0.18/1000 characters (Scale plan pricing, 1 credit per character)",
+ "notes": "ElevenLabs Eleven v3 - most expressive TTS model with 70+ languages and audio tags support"
+ },
+ "mode": "audio_speech",
+ "source": "https://elevenlabs.io/pricing",
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ]
+ },
+ "elevenlabs/eleven_multilingual_v2": {
+ "input_cost_per_character": 0.00018,
+ "litellm_provider": "elevenlabs",
+ "metadata": {
+ "calculation": "$0.18/1000 characters (Scale plan pricing, 1 credit per character)",
+ "notes": "ElevenLabs Eleven Multilingual v2 - default TTS model with 29 languages support"
+ },
+ "mode": "audio_speech",
+ "source": "https://elevenlabs.io/pricing",
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ]
+ },
"embed-english-light-v2.0": {
"input_cost_per_token": 1e-07,
"litellm_provider": "cohere",
@@ -11194,6 +12689,19 @@
"supports_tool_choice": true,
"supports_web_search": true
},
+ "fireworks_ai/accounts/fireworks/models/kimi-k2p5": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "fireworks_ai",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "source": "https://fireworks.ai/pricing",
+ "supports_function_calling": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true
+ },
"fireworks_ai/accounts/fireworks/models/llama-v3p1-405b-instruct": {
"input_cost_per_token": 3e-06,
"litellm_provider": "fireworks_ai",
@@ -12093,6 +13601,7 @@
},
"gemini-2.0-flash": {
"cache_read_input_token_cost": 2.5e-08,
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 7e-07,
"input_cost_per_token": 1e-07,
"litellm_provider": "vertex_ai-language-models",
@@ -12132,7 +13641,7 @@
},
"gemini-2.0-flash-001": {
"cache_read_input_token_cost": 3.75e-08,
- "deprecation_date": "2026-02-05",
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 1e-06,
"input_cost_per_token": 1.5e-07,
"litellm_provider": "vertex_ai-language-models",
@@ -12218,6 +13727,7 @@
},
"gemini-2.0-flash-lite": {
"cache_read_input_token_cost": 1.875e-08,
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 7.5e-08,
"input_cost_per_token": 7.5e-08,
"litellm_provider": "vertex_ai-language-models",
@@ -12253,7 +13763,7 @@
},
"gemini-2.0-flash-lite-001": {
"cache_read_input_token_cost": 1.875e-08,
- "deprecation_date": "2026-02-25",
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 7.5e-08,
"input_cost_per_token": 7.5e-08,
"litellm_provider": "vertex_ai-language-models",
@@ -12695,6 +14205,40 @@
"supports_vision": true,
"supports_web_search": true
},
+ "deep-research-pro-preview-12-2025": {
+ "input_cost_per_image": 0.0011,
+ "input_cost_per_token": 2e-06,
+ "input_cost_per_token_batches": 1e-06,
+ "litellm_provider": "vertex_ai-language-models",
+ "max_input_tokens": 65536,
+ "max_output_tokens": 32768,
+ "max_tokens": 32768,
+ "mode": "image_generation",
+ "output_cost_per_image": 0.134,
+ "output_cost_per_image_token": 0.00012,
+ "output_cost_per_token": 1.2e-05,
+ "output_cost_per_token_batches": 6e-06,
+ "source": "https://ai.google.dev/gemini-api/docs/pricing",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions",
+ "/v1/batch"
+ ],
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "image"
+ ],
+ "supports_function_calling": false,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_vision": true,
+ "supports_web_search": true
+ },
"gemini-2.5-flash-lite": {
"cache_read_input_token_cost": 1e-08,
"input_cost_per_audio_token": 3e-07,
@@ -13149,7 +14693,8 @@
"supports_tool_choice": true,
"supports_video_input": true,
"supports_vision": true,
- "supports_web_search": true
+ "supports_web_search": true,
+ "supports_native_streaming": true
},
"vertex_ai/gemini-3-pro-preview": {
"cache_read_input_token_cost": 2e-07,
@@ -13197,7 +14742,8 @@
"supports_tool_choice": true,
"supports_video_input": true,
"supports_vision": true,
- "supports_web_search": true
+ "supports_web_search": true,
+ "supports_native_streaming": true
},
"vertex_ai/gemini-3-flash-preview": {
"cache_read_input_token_cost": 5e-08,
@@ -13240,7 +14786,8 @@
"supports_tool_choice": true,
"supports_video_input": true,
"supports_vision": true,
- "supports_web_search": true
+ "supports_web_search": true,
+ "supports_native_streaming": true
},
"gemini-2.5-pro-exp-03-25": {
"cache_read_input_token_cost": 1.25e-07,
@@ -13465,6 +15012,81 @@
"supports_vision": true,
"supports_web_search": true
},
+ "gemini-robotics-er-1.5-preview": {
+ "cache_read_input_token_cost": 0,
+ "input_cost_per_token": 3e-07,
+ "input_cost_per_audio_token": 1e-06,
+ "litellm_provider": "vertex_ai-language-models",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65535,
+ "max_tokens": 65535,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "output_cost_per_reasoning_token": 2.5e-06,
+ "source": "https://ai.google.dev/gemini-api/docs/models#gemini-robotics-er-1-5-preview",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "video",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_output": false,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_prompt_caching": false,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_url_context": true,
+ "supports_vision": true
+ },
+ "gemini/gemini-robotics-er-1.5-preview": {
+ "cache_read_input_token_cost": 0,
+ "input_cost_per_token": 3e-07,
+ "input_cost_per_audio_token": 1e-06,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65535,
+ "max_tokens": 65535,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "output_cost_per_reasoning_token": 2.5e-06,
+ "source": "https://ai.google.dev/gemini-api/docs/models#gemini-robotics-er-1-5-preview",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "video",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_output": false,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_prompt_caching": false,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_url_context": true,
+ "supports_vision": true,
+ "supports_web_search": true,
+ "tpm": 250000,
+ "rpm": 10
+ },
"gemini-2.5-computer-use-preview-10-2025": {
"input_cost_per_token": 1.25e-06,
"input_cost_per_token_above_200k_tokens": 2.5e-06,
@@ -13918,6 +15540,7 @@
},
"gemini/gemini-2.0-flash": {
"cache_read_input_token_cost": 2.5e-08,
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 7e-07,
"input_cost_per_token": 1e-07,
"litellm_provider": "gemini",
@@ -13958,6 +15581,7 @@
},
"gemini/gemini-2.0-flash-001": {
"cache_read_input_token_cost": 2.5e-08,
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 7e-07,
"input_cost_per_token": 1e-07,
"litellm_provider": "gemini",
@@ -14045,6 +15669,7 @@
},
"gemini/gemini-2.0-flash-lite": {
"cache_read_input_token_cost": 1.875e-08,
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 7.5e-08,
"input_cost_per_token": 7.5e-08,
"litellm_provider": "gemini",
@@ -14531,6 +16156,42 @@
"supports_vision": true,
"supports_web_search": true
},
+ "gemini/deep-research-pro-preview-12-2025": {
+ "input_cost_per_image": 0.0011,
+ "input_cost_per_token": 2e-06,
+ "input_cost_per_token_batches": 1e-06,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 65536,
+ "max_output_tokens": 32768,
+ "max_tokens": 32768,
+ "mode": "image_generation",
+ "output_cost_per_image": 0.134,
+ "output_cost_per_image_token": 0.00012,
+ "output_cost_per_token": 1.2e-05,
+ "rpm": 1000,
+ "tpm": 4000000,
+ "output_cost_per_token_batches": 6e-06,
+ "source": "https://ai.google.dev/gemini-api/docs/pricing",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions",
+ "/v1/batch"
+ ],
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "image"
+ ],
+ "supports_function_calling": false,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_vision": true,
+ "supports_web_search": true
+ },
"gemini/gemini-2.5-flash-lite": {
"cache_read_input_token_cost": 1e-08,
"input_cost_per_audio_token": 3e-07,
@@ -14905,44 +16566,16 @@
"tpm": 250000
},
"gemini/gemini-2.5-flash-preview-tts": {
- "cache_read_input_token_cost": 3.75e-08,
- "input_cost_per_audio_token": 1e-06,
- "input_cost_per_token": 1.5e-07,
+ "input_cost_per_token": 3e-07,
"litellm_provider": "gemini",
- "max_audio_length_hours": 8.4,
- "max_audio_per_prompt": 1,
- "max_images_per_prompt": 3000,
- "max_input_tokens": 1048576,
- "max_output_tokens": 65535,
- "max_pdf_size_mb": 30,
- "max_tokens": 65535,
- "max_video_length": 1,
- "max_videos_per_prompt": 10,
- "mode": "chat",
- "output_cost_per_reasoning_token": 3.5e-06,
- "output_cost_per_token": 6e-07,
- "rpm": 10,
- "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-preview",
+ "mode": "audio_speech",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
"supported_endpoints": [
- "/v1/chat/completions",
- "/v1/completions"
+ "/v1/audio/speech"
],
- "supported_modalities": [
- "text"
- ],
- "supported_output_modalities": [
- "audio"
- ],
- "supports_audio_output": false,
- "supports_function_calling": true,
- "supports_prompt_caching": true,
- "supports_reasoning": true,
- "supports_response_schema": true,
- "supports_system_messages": true,
- "supports_tool_choice": true,
- "supports_vision": true,
- "supports_web_search": true,
- "tpm": 250000
+ "tpm": 4000000,
+ "rpm": 10
},
"gemini/gemini-2.5-pro": {
"cache_read_input_token_cost": 1.25e-07,
@@ -15115,6 +16748,7 @@
"supports_url_context": true,
"supports_vision": true,
"supports_web_search": true,
+ "supports_native_streaming": true,
"tpm": 800000
},
"gemini-3-flash-preview": {
@@ -15160,7 +16794,8 @@
"supports_tool_choice": true,
"supports_url_context": true,
"supports_vision": true,
- "supports_web_search": true
+ "supports_web_search": true,
+ "supports_native_streaming": true
},
"gemini/gemini-2.5-pro-exp-03-25": {
"cache_read_input_token_cost": 0.0,
@@ -15438,7 +17073,9 @@
"source": "https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#foundation_models",
"supports_function_calling": true,
"supports_tool_choice": true,
- "supports_vision": true
+ "supports_vision": true,
+ "tpm": 250000,
+ "rpm": 10
},
"gemini/gemini-gemma-2-9b-it": {
"input_cost_per_token": 3.5e-07,
@@ -15450,7 +17087,9 @@
"source": "https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#foundation_models",
"supports_function_calling": true,
"supports_tool_choice": true,
- "supports_vision": true
+ "supports_vision": true,
+ "tpm": 250000,
+ "rpm": 10
},
"gemini/gemini-pro": {
"input_cost_per_token": 3.5e-07,
@@ -15706,6 +17345,19 @@
"supports_parallel_function_calling": true,
"supports_vision": true
},
+ "github_copilot/claude-opus-4.6-fast": {
+ "litellm_provider": "github_copilot",
+ "max_input_tokens": 128000,
+ "max_output_tokens": 16000,
+ "max_tokens": 16000,
+ "mode": "chat",
+ "supported_endpoints": [
+ "/v1/chat/completions"
+ ],
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_vision": true
+ },
"github_copilot/claude-opus-41": {
"litellm_provider": "github_copilot",
"max_input_tokens": 80000,
@@ -15957,6 +17609,20 @@
"supports_response_schema": true,
"supports_vision": true
},
+ "github_copilot/gpt-5.3-codex": {
+ "litellm_provider": "github_copilot",
+ "max_input_tokens": 128000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "responses",
+ "supported_endpoints": [
+ "/v1/responses"
+ ],
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_response_schema": true,
+ "supports_vision": true
+ },
"github_copilot/text-embedding-3-small": {
"litellm_provider": "github_copilot",
"max_input_tokens": 8191,
@@ -16094,6 +17760,181 @@
"output_cost_per_token": 0.0,
"output_vector_size": 2560
},
+ "gmi/anthropic/claude-opus-4.5": {
+ "input_cost_per_token": 5e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 409600,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/anthropic/claude-sonnet-4.5": {
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 409600,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/anthropic/claude-sonnet-4": {
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 409600,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/anthropic/claude-opus-4": {
+ "input_cost_per_token": 1.5e-05,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 409600,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 7.5e-05,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/openai/gpt-5.2": {
+ "input_cost_per_token": 1.75e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 409600,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 1.4e-05,
+ "supports_function_calling": true
+ },
+ "gmi/openai/gpt-5.1": {
+ "input_cost_per_token": 1.25e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 409600,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true
+ },
+ "gmi/openai/gpt-5": {
+ "input_cost_per_token": 1.25e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 409600,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true
+ },
+ "gmi/openai/gpt-4o": {
+ "input_cost_per_token": 2.5e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 131072,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/openai/gpt-4o-mini": {
+ "input_cost_per_token": 1.5e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 131072,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 6e-07,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/deepseek-ai/DeepSeek-V3.2": {
+ "input_cost_per_token": 2.8e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 4e-07,
+ "supports_function_calling": true
+ },
+ "gmi/deepseek-ai/DeepSeek-V3-0324": {
+ "input_cost_per_token": 2.8e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 8.8e-07,
+ "supports_function_calling": true
+ },
+ "gmi/google/gemini-3-pro-preview": {
+ "input_cost_per_token": 2e-06,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65536,
+ "max_tokens": 65536,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-05,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/google/gemini-3-flash-preview": {
+ "input_cost_per_token": 5e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65536,
+ "max_tokens": 65536,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "supports_function_calling": true,
+ "supports_vision": true
+ },
+ "gmi/moonshotai/Kimi-K2-Thinking": {
+ "input_cost_per_token": 8e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06
+ },
+ "gmi/MiniMaxAI/MiniMax-M2.1": {
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 196608,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06
+ },
+ "gmi/Qwen/Qwen3-VL-235B-A22B-Instruct-FP8": {
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 1.4e-06,
+ "supports_vision": true
+ },
+ "gmi/zai-org/GLM-4.7-FP8": {
+ "input_cost_per_token": 4e-07,
+ "litellm_provider": "gmi",
+ "max_input_tokens": 202752,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "output_cost_per_token": 2e-06
+ },
"google.gemma-3-12b-it": {
"input_cost_per_token": 9e-08,
"litellm_provider": "bedrock_converse",
@@ -18416,7 +20257,7 @@
"input_cost_per_token": 1.75e-06,
"input_cost_per_token_priority": 3.5e-06,
"litellm_provider": "openai",
- "max_input_tokens": 400000,
+ "max_input_tokens": 272000,
"max_output_tokens": 128000,
"max_tokens": 128000,
"mode": "responses",
@@ -20314,6 +22155,19 @@
"output_cost_per_token": 1.2e-06,
"supports_system_messages": true
},
+ "minimax.minimax-m2.1": {
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 196000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"minimax/speech-02-hd": {
"input_cost_per_character": 0.0001,
"litellm_provider": "minimax",
@@ -20356,6 +22210,7 @@
"supports_function_calling": true,
"supports_tool_choice": true,
"supports_prompt_caching": true,
+ "supports_reasoning": true,
"supports_system_messages": true,
"max_input_tokens": 1000000,
"max_output_tokens": 8192
@@ -20370,6 +22225,37 @@
"supports_function_calling": true,
"supports_tool_choice": true,
"supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_system_messages": true,
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 8192
+ },
+ "minimax/MiniMax-M2.5": {
+ "input_cost_per_token": 3e-07,
+ "output_cost_per_token": 1.2e-06,
+ "cache_read_input_token_cost": 3e-08,
+ "cache_creation_input_token_cost": 3.75e-07,
+ "litellm_provider": "minimax",
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_system_messages": true,
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 8192
+ },
+ "minimax/MiniMax-M2.5-lightning": {
+ "input_cost_per_token": 3e-07,
+ "output_cost_per_token": 2.4e-06,
+ "cache_read_input_token_cost": 3e-08,
+ "cache_creation_input_token_cost": 3.75e-07,
+ "litellm_provider": "minimax",
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
"supports_system_messages": true,
"max_input_tokens": 1000000,
"max_output_tokens": 8192
@@ -20384,6 +22270,7 @@
"supports_function_calling": true,
"supports_tool_choice": true,
"supports_prompt_caching": true,
+ "supports_reasoning": true,
"supports_system_messages": true,
"max_input_tokens": 200000,
"max_output_tokens": 8192
@@ -20609,6 +22496,20 @@
"supports_response_schema": true,
"supports_tool_choice": true
},
+ "mistral/devstral-small-latest": {
+ "input_cost_per_token": 1e-07,
+ "litellm_provider": "mistral",
+ "max_input_tokens": 256000,
+ "max_output_tokens": 256000,
+ "max_tokens": 256000,
+ "mode": "chat",
+ "output_cost_per_token": 3e-07,
+ "source": "https://docs.mistral.ai/models/devstral-small-2-25-12",
+ "supports_assistant_prefill": true,
+ "supports_function_calling": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true
+ },
"mistral/labs-devstral-small-2512": {
"input_cost_per_token": 1e-07,
"litellm_provider": "mistral",
@@ -20623,6 +22524,34 @@
"supports_response_schema": true,
"supports_tool_choice": true
},
+ "mistral/devstral-latest": {
+ "input_cost_per_token": 4e-07,
+ "litellm_provider": "mistral",
+ "max_input_tokens": 256000,
+ "max_output_tokens": 256000,
+ "max_tokens": 256000,
+ "mode": "chat",
+ "output_cost_per_token": 2e-06,
+ "source": "https://mistral.ai/news/devstral-2-vibe-cli",
+ "supports_assistant_prefill": true,
+ "supports_function_calling": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true
+ },
+ "mistral/devstral-medium-latest": {
+ "input_cost_per_token": 4e-07,
+ "litellm_provider": "mistral",
+ "max_input_tokens": 256000,
+ "max_output_tokens": 256000,
+ "max_tokens": 256000,
+ "mode": "chat",
+ "output_cost_per_token": 2e-06,
+ "source": "https://mistral.ai/news/devstral-2-vibe-cli",
+ "supports_assistant_prefill": true,
+ "supports_function_calling": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true
+ },
"mistral/devstral-2512": {
"input_cost_per_token": 4e-07,
"litellm_provider": "mistral",
@@ -21037,6 +22966,20 @@
"supports_reasoning": true,
"supports_system_messages": true
},
+ "moonshotai.kimi-k2.5": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"moonshot/kimi-k2-0711-preview": {
"cache_read_input_token_cost": 1.5e-07,
"input_cost_per_token": 6e-07,
@@ -21079,6 +23022,21 @@
"supports_tool_choice": true,
"supports_web_search": true
},
+ "moonshot/kimi-k2.5": {
+ "cache_read_input_token_cost": 1e-07,
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "moonshot",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 3e-06,
+ "source": "https://platform.moonshot.ai/docs/guide/kimi-k2-5-quickstart",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_video_input": true,
+ "supports_vision": true
+ },
"moonshot/kimi-latest": {
"cache_read_input_token_cost": 1.5e-07,
"input_cost_per_token": 2e-06,
@@ -21538,6 +23496,19 @@
"output_cost_per_token": 2.3e-07,
"supports_system_messages": true
},
+ "nvidia.nemotron-nano-3-30b": {
+ "input_cost_per_token": 6e-08,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 2.4e-07,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"o1": {
"cache_read_input_token_cost": 7.5e-06,
"input_cost_per_token": 1.5e-05,
@@ -21548,7 +23519,7 @@
"mode": "chat",
"output_cost_per_token": 6e-05,
"supports_function_calling": true,
- "supports_parallel_function_calling": true,
+ "supports_parallel_function_calling": false,
"supports_pdf_input": true,
"supports_prompt_caching": true,
"supports_reasoning": true,
@@ -22103,7 +24074,7 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 1.5e-07,
+ "output_cost_per_token": 1.5e-05,
"source": "https://www.oracle.com/artificial-intelligence/generative-ai/generative-ai-service/pricing",
"supports_function_calling": true,
"supports_response_schema": false
@@ -22151,7 +24122,7 @@
"max_output_tokens": 128000,
"max_tokens": 128000,
"mode": "chat",
- "output_cost_per_token": 1.5e-07,
+ "output_cost_per_token": 1.5e-05,
"source": "https://www.oracle.com/artificial-intelligence/generative-ai/generative-ai-service/pricing",
"supports_function_calling": true,
"supports_response_schema": false
@@ -22543,36 +24514,6 @@
"output_cost_per_token": 2e-07,
"supports_system_messages": true
},
- "openrouter/anthropic/claude-2": {
- "input_cost_per_token": 1.102e-05,
- "litellm_provider": "openrouter",
- "max_output_tokens": 8191,
- "max_tokens": 8191,
- "mode": "chat",
- "output_cost_per_token": 3.268e-05,
- "supports_tool_choice": true
- },
- "openrouter/anthropic/claude-3-5-haiku": {
- "input_cost_per_token": 1e-06,
- "litellm_provider": "openrouter",
- "max_tokens": 200000,
- "mode": "chat",
- "output_cost_per_token": 5e-06,
- "supports_function_calling": true,
- "supports_tool_choice": true
- },
- "openrouter/anthropic/claude-3-5-haiku-20241022": {
- "input_cost_per_token": 1e-06,
- "litellm_provider": "openrouter",
- "max_input_tokens": 200000,
- "max_output_tokens": 8192,
- "max_tokens": 8192,
- "mode": "chat",
- "output_cost_per_token": 5e-06,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "tool_use_system_prompt_tokens": 264
- },
"openrouter/anthropic/claude-3-haiku": {
"input_cost_per_image": 0.0004,
"input_cost_per_token": 2.5e-07,
@@ -22584,43 +24525,6 @@
"supports_tool_choice": true,
"supports_vision": true
},
- "openrouter/anthropic/claude-3-haiku-20240307": {
- "input_cost_per_token": 2.5e-07,
- "litellm_provider": "openrouter",
- "max_input_tokens": 200000,
- "max_output_tokens": 4096,
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 1.25e-06,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": true,
- "tool_use_system_prompt_tokens": 264
- },
- "openrouter/anthropic/claude-3-opus": {
- "input_cost_per_token": 1.5e-05,
- "litellm_provider": "openrouter",
- "max_input_tokens": 200000,
- "max_output_tokens": 4096,
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 7.5e-05,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": true,
- "tool_use_system_prompt_tokens": 395
- },
- "openrouter/anthropic/claude-3-sonnet": {
- "input_cost_per_image": 0.0048,
- "input_cost_per_token": 3e-06,
- "litellm_provider": "openrouter",
- "max_tokens": 200000,
- "mode": "chat",
- "output_cost_per_token": 1.5e-05,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": true
- },
"openrouter/anthropic/claude-3.5-sonnet": {
"input_cost_per_token": 3e-06,
"litellm_provider": "openrouter",
@@ -22636,20 +24540,6 @@
"supports_vision": true,
"tool_use_system_prompt_tokens": 159
},
- "openrouter/anthropic/claude-3.5-sonnet:beta": {
- "input_cost_per_token": 3e-06,
- "litellm_provider": "openrouter",
- "max_input_tokens": 200000,
- "max_output_tokens": 8192,
- "max_tokens": 8192,
- "mode": "chat",
- "output_cost_per_token": 1.5e-05,
- "supports_computer_use": true,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": true,
- "tool_use_system_prompt_tokens": 159
- },
"openrouter/anthropic/claude-3.7-sonnet": {
"input_cost_per_image": 0.0048,
"input_cost_per_token": 3e-06,
@@ -22667,31 +24557,6 @@
"supports_vision": true,
"tool_use_system_prompt_tokens": 159
},
- "openrouter/anthropic/claude-3.7-sonnet:beta": {
- "input_cost_per_image": 0.0048,
- "input_cost_per_token": 3e-06,
- "litellm_provider": "openrouter",
- "max_input_tokens": 200000,
- "max_output_tokens": 128000,
- "max_tokens": 128000,
- "mode": "chat",
- "output_cost_per_token": 1.5e-05,
- "supports_computer_use": true,
- "supports_function_calling": true,
- "supports_reasoning": true,
- "supports_tool_choice": true,
- "supports_vision": true,
- "tool_use_system_prompt_tokens": 159
- },
- "openrouter/anthropic/claude-instant-v1": {
- "input_cost_per_token": 1.63e-06,
- "litellm_provider": "openrouter",
- "max_output_tokens": 8191,
- "max_tokens": 8191,
- "mode": "chat",
- "output_cost_per_token": 5.51e-06,
- "supports_tool_choice": true
- },
"openrouter/anthropic/claude-opus-4": {
"input_cost_per_image": 0.0048,
"cache_creation_input_token_cost": 1.875e-05,
@@ -22830,30 +24695,6 @@
"source": "https://openrouter.ai/api/v1/models/bytedance/ui-tars-1.5-7b",
"supports_tool_choice": true
},
- "openrouter/cognitivecomputations/dolphin-mixtral-8x7b": {
- "input_cost_per_token": 5e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 32769,
- "mode": "chat",
- "output_cost_per_token": 5e-07,
- "supports_tool_choice": true
- },
- "openrouter/cohere/command-r-plus": {
- "input_cost_per_token": 3e-06,
- "litellm_provider": "openrouter",
- "max_tokens": 128000,
- "mode": "chat",
- "output_cost_per_token": 1.5e-05,
- "supports_tool_choice": true
- },
- "openrouter/databricks/dbrx-instruct": {
- "input_cost_per_token": 6e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 32768,
- "mode": "chat",
- "output_cost_per_token": 6e-07,
- "supports_tool_choice": true
- },
"openrouter/deepseek/deepseek-chat": {
"input_cost_per_token": 1.4e-07,
"litellm_provider": "openrouter",
@@ -22921,17 +24762,6 @@
"supports_reasoning": false,
"supports_tool_choice": true
},
- "openrouter/deepseek/deepseek-coder": {
- "input_cost_per_token": 1.4e-07,
- "litellm_provider": "openrouter",
- "max_input_tokens": 66000,
- "max_output_tokens": 4096,
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 2.8e-07,
- "supports_prompt_caching": true,
- "supports_tool_choice": true
- },
"openrouter/deepseek/deepseek-r1": {
"input_cost_per_token": 5.5e-07,
"input_cost_per_token_cache_hit": 1.4e-07,
@@ -22962,15 +24792,8 @@
"supports_reasoning": true,
"supports_tool_choice": true
},
- "openrouter/fireworks/firellava-13b": {
- "input_cost_per_token": 2e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 2e-07,
- "supports_tool_choice": true
- },
"openrouter/google/gemini-2.0-flash-001": {
+ "deprecation_date": "2026-03-31",
"input_cost_per_audio_token": 7e-07,
"input_cost_per_token": 1e-07,
"litellm_provider": "openrouter",
@@ -23130,46 +24953,6 @@
"supports_web_search": true,
"tpm": 800000
},
- "openrouter/google/gemini-pro-1.5": {
- "input_cost_per_image": 0.00265,
- "input_cost_per_token": 2.5e-06,
- "litellm_provider": "openrouter",
- "max_input_tokens": 1000000,
- "max_output_tokens": 8192,
- "max_tokens": 8192,
- "mode": "chat",
- "output_cost_per_token": 7.5e-06,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": true
- },
- "openrouter/google/gemini-pro-vision": {
- "input_cost_per_image": 0.0025,
- "input_cost_per_token": 1.25e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 45875,
- "mode": "chat",
- "output_cost_per_token": 3.75e-07,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": true
- },
- "openrouter/google/palm-2-chat-bison": {
- "input_cost_per_token": 5e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 25804,
- "mode": "chat",
- "output_cost_per_token": 5e-07,
- "supports_tool_choice": true
- },
- "openrouter/google/palm-2-codechat-bison": {
- "input_cost_per_token": 5e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 20070,
- "mode": "chat",
- "output_cost_per_token": 5e-07,
- "supports_tool_choice": true
- },
"openrouter/gryphe/mythomax-l2-13b": {
"input_cost_per_token": 1.875e-06,
"litellm_provider": "openrouter",
@@ -23178,14 +24961,6 @@
"output_cost_per_token": 1.875e-06,
"supports_tool_choice": true
},
- "openrouter/jondurbin/airoboros-l2-70b-2.1": {
- "input_cost_per_token": 1.3875e-05,
- "litellm_provider": "openrouter",
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 1.3875e-05,
- "supports_tool_choice": true
- },
"openrouter/mancer/weaver": {
"input_cost_per_token": 5.625e-06,
"litellm_provider": "openrouter",
@@ -23194,30 +24969,6 @@
"output_cost_per_token": 5.625e-06,
"supports_tool_choice": true
},
- "openrouter/meta-llama/codellama-34b-instruct": {
- "input_cost_per_token": 5e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 8192,
- "mode": "chat",
- "output_cost_per_token": 5e-07,
- "supports_tool_choice": true
- },
- "openrouter/meta-llama/llama-2-13b-chat": {
- "input_cost_per_token": 2e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 2e-07,
- "supports_tool_choice": true
- },
- "openrouter/meta-llama/llama-2-70b-chat": {
- "input_cost_per_token": 1.5e-06,
- "litellm_provider": "openrouter",
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 1.5e-06,
- "supports_tool_choice": true
- },
"openrouter/meta-llama/llama-3-70b-instruct": {
"input_cost_per_token": 5.9e-07,
"litellm_provider": "openrouter",
@@ -23226,38 +24977,6 @@
"output_cost_per_token": 7.9e-07,
"supports_tool_choice": true
},
- "openrouter/meta-llama/llama-3-70b-instruct:nitro": {
- "input_cost_per_token": 9e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 8192,
- "mode": "chat",
- "output_cost_per_token": 9e-07,
- "supports_tool_choice": true
- },
- "openrouter/meta-llama/llama-3-8b-instruct:extended": {
- "input_cost_per_token": 2.25e-07,
- "litellm_provider": "openrouter",
- "max_tokens": 16384,
- "mode": "chat",
- "output_cost_per_token": 2.25e-06,
- "supports_tool_choice": true
- },
- "openrouter/meta-llama/llama-3-8b-instruct:free": {
- "input_cost_per_token": 0.0,
- "litellm_provider": "openrouter",
- "max_tokens": 8192,
- "mode": "chat",
- "output_cost_per_token": 0.0,
- "supports_tool_choice": true
- },
- "openrouter/microsoft/wizardlm-2-8x22b:nitro": {
- "input_cost_per_token": 1e-06,
- "litellm_provider": "openrouter",
- "max_tokens": 65536,
- "mode": "chat",
- "output_cost_per_token": 1e-06,
- "supports_tool_choice": true
- },
"openrouter/minimax/minimax-m2": {
"input_cost_per_token": 2.55e-07,
"litellm_provider": "openrouter",
@@ -23267,24 +24986,10 @@
"mode": "chat",
"output_cost_per_token": 1.02e-06,
"supports_function_calling": true,
- "supports_prompt_caching": false,
+ "supports_prompt_caching": true,
"supports_reasoning": true,
"supports_tool_choice": true
},
- "openrouter/mistralai/devstral-2512:free": {
- "input_cost_per_image": 0,
- "input_cost_per_token": 0,
- "litellm_provider": "openrouter",
- "max_input_tokens": 262144,
- "max_output_tokens": 262144,
- "max_tokens": 262144,
- "mode": "chat",
- "output_cost_per_token": 0,
- "supports_function_calling": true,
- "supports_prompt_caching": false,
- "supports_tool_choice": true,
- "supports_vision": false
- },
"openrouter/mistralai/devstral-2512": {
"input_cost_per_image": 0,
"input_cost_per_token": 1.5e-07,
@@ -23363,14 +25068,6 @@
"output_cost_per_token": 1.3e-07,
"supports_tool_choice": true
},
- "openrouter/mistralai/mistral-7b-instruct:free": {
- "input_cost_per_token": 0.0,
- "litellm_provider": "openrouter",
- "max_tokens": 8192,
- "mode": "chat",
- "output_cost_per_token": 0.0,
- "supports_tool_choice": true
- },
"openrouter/mistralai/mistral-large": {
"input_cost_per_token": 8e-06,
"litellm_provider": "openrouter",
@@ -23403,13 +25100,20 @@
"output_cost_per_token": 6.5e-07,
"supports_tool_choice": true
},
- "openrouter/nousresearch/nous-hermes-llama2-13b": {
- "input_cost_per_token": 2e-07,
+ "openrouter/moonshotai/kimi-k2.5": {
+ "cache_read_input_token_cost": 1e-07,
+ "input_cost_per_token": 6e-07,
"litellm_provider": "openrouter",
- "max_tokens": 4096,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
"mode": "chat",
- "output_cost_per_token": 2e-07,
- "supports_tool_choice": true
+ "output_cost_per_token": 3e-06,
+ "source": "https://openrouter.ai/moonshotai/kimi-k2.5",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_video_input": true,
+ "supports_vision": true
},
"openrouter/openai/gpt-3.5-turbo": {
"input_cost_per_token": 1.5e-06,
@@ -23435,17 +25139,6 @@
"output_cost_per_token": 6e-05,
"supports_tool_choice": true
},
- "openrouter/openai/gpt-4-vision-preview": {
- "input_cost_per_image": 0.01445,
- "input_cost_per_token": 1e-05,
- "litellm_provider": "openrouter",
- "max_tokens": 130000,
- "mode": "chat",
- "output_cost_per_token": 3e-05,
- "supports_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": true
- },
"openrouter/openai/gpt-4.1": {
"cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 2e-06,
@@ -23463,23 +25156,6 @@
"supports_tool_choice": true,
"supports_vision": true
},
- "openrouter/openai/gpt-4.1-2025-04-14": {
- "cache_read_input_token_cost": 5e-07,
- "input_cost_per_token": 2e-06,
- "litellm_provider": "openrouter",
- "max_input_tokens": 1047576,
- "max_output_tokens": 32768,
- "max_tokens": 32768,
- "mode": "chat",
- "output_cost_per_token": 8e-06,
- "supports_function_calling": true,
- "supports_parallel_function_calling": true,
- "supports_prompt_caching": true,
- "supports_response_schema": true,
- "supports_system_messages": true,
- "supports_tool_choice": true,
- "supports_vision": true
- },
"openrouter/openai/gpt-4.1-mini": {
"cache_read_input_token_cost": 1e-07,
"input_cost_per_token": 4e-07,
@@ -23497,23 +25173,6 @@
"supports_tool_choice": true,
"supports_vision": true
},
- "openrouter/openai/gpt-4.1-mini-2025-04-14": {
- "cache_read_input_token_cost": 1e-07,
- "input_cost_per_token": 4e-07,
- "litellm_provider": "openrouter",
- "max_input_tokens": 1047576,
- "max_output_tokens": 32768,
- "max_tokens": 32768,
- "mode": "chat",
- "output_cost_per_token": 1.6e-06,
- "supports_function_calling": true,
- "supports_parallel_function_calling": true,
- "supports_prompt_caching": true,
- "supports_response_schema": true,
- "supports_system_messages": true,
- "supports_tool_choice": true,
- "supports_vision": true
- },
"openrouter/openai/gpt-4.1-nano": {
"cache_read_input_token_cost": 2.5e-08,
"input_cost_per_token": 1e-07,
@@ -23531,23 +25190,6 @@
"supports_tool_choice": true,
"supports_vision": true
},
- "openrouter/openai/gpt-4.1-nano-2025-04-14": {
- "cache_read_input_token_cost": 2.5e-08,
- "input_cost_per_token": 1e-07,
- "litellm_provider": "openrouter",
- "max_input_tokens": 1047576,
- "max_output_tokens": 32768,
- "max_tokens": 32768,
- "mode": "chat",
- "output_cost_per_token": 4e-07,
- "supports_function_calling": true,
- "supports_parallel_function_calling": true,
- "supports_prompt_caching": true,
- "supports_response_schema": true,
- "supports_system_messages": true,
- "supports_tool_choice": true,
- "supports_vision": true
- },
"openrouter/openai/gpt-4o": {
"input_cost_per_token": 2.5e-06,
"litellm_provider": "openrouter",
@@ -23616,7 +25258,7 @@
"cache_read_input_token_cost": 1.75e-07,
"input_cost_per_token": 1.75e-06,
"litellm_provider": "openrouter",
- "max_input_tokens": 400000,
+ "max_input_tokens": 272000,
"max_output_tokens": 128000,
"max_tokens": 128000,
"mode": "chat",
@@ -23781,58 +25423,6 @@
"supports_tool_choice": true,
"supports_vision": true
},
- "openrouter/openai/o1-mini": {
- "input_cost_per_token": 3e-06,
- "litellm_provider": "openrouter",
- "max_input_tokens": 128000,
- "max_output_tokens": 65536,
- "max_tokens": 65536,
- "mode": "chat",
- "output_cost_per_token": 1.2e-05,
- "supports_function_calling": true,
- "supports_parallel_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": false
- },
- "openrouter/openai/o1-mini-2024-09-12": {
- "input_cost_per_token": 3e-06,
- "litellm_provider": "openrouter",
- "max_input_tokens": 128000,
- "max_output_tokens": 65536,
- "max_tokens": 65536,
- "mode": "chat",
- "output_cost_per_token": 1.2e-05,
- "supports_function_calling": true,
- "supports_parallel_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": false
- },
- "openrouter/openai/o1-preview": {
- "input_cost_per_token": 1.5e-05,
- "litellm_provider": "openrouter",
- "max_input_tokens": 128000,
- "max_output_tokens": 32768,
- "max_tokens": 32768,
- "mode": "chat",
- "output_cost_per_token": 6e-05,
- "supports_function_calling": true,
- "supports_parallel_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": false
- },
- "openrouter/openai/o1-preview-2024-09-12": {
- "input_cost_per_token": 1.5e-05,
- "litellm_provider": "openrouter",
- "max_input_tokens": 128000,
- "max_output_tokens": 32768,
- "max_tokens": 32768,
- "mode": "chat",
- "output_cost_per_token": 6e-05,
- "supports_function_calling": true,
- "supports_parallel_function_calling": true,
- "supports_tool_choice": true,
- "supports_vision": false
- },
"openrouter/openai/o3-mini": {
"input_cost_per_token": 1.1e-06,
"litellm_provider": "openrouter",
@@ -23861,14 +25451,6 @@
"supports_tool_choice": true,
"supports_vision": false
},
- "openrouter/pygmalionai/mythalion-13b": {
- "input_cost_per_token": 1.875e-06,
- "litellm_provider": "openrouter",
- "max_tokens": 4096,
- "mode": "chat",
- "output_cost_per_token": 1.875e-06,
- "supports_tool_choice": true
- },
"openrouter/qwen/qwen-2.5-coder-32b-instruct": {
"input_cost_per_token": 1.8e-07,
"litellm_provider": "openrouter",
@@ -23902,6 +25484,31 @@
"supports_tool_choice": true,
"supports_function_calling": true
},
+ "openrouter/qwen/qwen3-235b-a22b-2507": {
+ "input_cost_per_token": 7.1e-08,
+ "litellm_provider": "openrouter",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 1e-07,
+ "source": "https://openrouter.ai/qwen/qwen3-235b-a22b-2507",
+ "supports_function_calling": true,
+ "supports_tool_choice": true
+ },
+ "openrouter/qwen/qwen3-235b-a22b-thinking-2507": {
+ "input_cost_per_token": 1.1e-07,
+ "litellm_provider": "openrouter",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "max_tokens": 262144,
+ "mode": "chat",
+ "output_cost_per_token": 6e-07,
+ "source": "https://openrouter.ai/qwen/qwen3-235b-a22b-thinking-2507",
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
"openrouter/switchpoint/router": {
"input_cost_per_token": 8.5e-07,
"litellm_provider": "openrouter",
@@ -23935,20 +25542,6 @@
"supports_tool_choice": true,
"supports_web_search": true
},
- "openrouter/x-ai/grok-4-fast:free": {
- "input_cost_per_token": 0,
- "litellm_provider": "openrouter",
- "max_input_tokens": 2000000,
- "max_output_tokens": 30000,
- "max_tokens": 30000,
- "mode": "chat",
- "output_cost_per_token": 0,
- "source": "https://openrouter.ai/x-ai/grok-4-fast:free",
- "supports_function_calling": true,
- "supports_reasoning": true,
- "supports_tool_choice": true,
- "supports_web_search": false
- },
"openrouter/z-ai/glm-4.6": {
"input_cost_per_token": 4e-07,
"litellm_provider": "openrouter",
@@ -23959,6 +25552,7 @@
"output_cost_per_token": 1.75e-06,
"source": "https://openrouter.ai/z-ai/glm-4.6",
"supports_function_calling": true,
+ "supports_prompt_caching": true,
"supports_reasoning": true,
"supports_tool_choice": true
},
@@ -23972,9 +25566,76 @@
"output_cost_per_token": 1.9e-06,
"source": "https://openrouter.ai/z-ai/glm-4.6:exacto",
"supports_function_calling": true,
+ "supports_prompt_caching": true,
"supports_reasoning": true,
"supports_tool_choice": true
},
+ "openrouter/xiaomi/mimo-v2-flash": {
+ "input_cost_per_token": 9e-08,
+ "output_cost_per_token": 2.9e-07,
+ "cache_creation_input_token_cost": 0.0,
+ "cache_read_input_token_cost": 0.0,
+ "litellm_provider": "openrouter",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 16384,
+ "max_tokens": 16384,
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_reasoning": true,
+ "supports_vision": false,
+ "supports_prompt_caching": false
+ },
+ "openrouter/z-ai/glm-4.7": {
+ "input_cost_per_token": 4e-07,
+ "output_cost_per_token": 1.5e-06,
+ "cache_creation_input_token_cost": 0.0,
+ "cache_read_input_token_cost": 0.0,
+ "litellm_provider": "openrouter",
+ "max_input_tokens": 202752,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_reasoning": true,
+ "supports_vision": true,
+ "supports_prompt_caching": false,
+ "supports_assistant_prefill": true
+ },
+ "openrouter/z-ai/glm-4.7-flash": {
+ "input_cost_per_token": 7e-08,
+ "output_cost_per_token": 4e-07,
+ "cache_creation_input_token_cost": 0.0,
+ "cache_read_input_token_cost": 0.0,
+ "litellm_provider": "openrouter",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_reasoning": true,
+ "supports_vision": true,
+ "supports_prompt_caching": false
+ },
+ "openrouter/minimax/minimax-m2.1": {
+ "input_cost_per_token": 2.7e-07,
+ "output_cost_per_token": 1.2e-06,
+ "cache_creation_input_token_cost": 0.0,
+ "cache_read_input_token_cost": 0.0,
+ "litellm_provider": "openrouter",
+ "max_input_tokens": 204000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_reasoning": true,
+ "supports_vision": true,
+ "supports_prompt_caching": false,
+ "supports_computer_use": false
+ },
"ovhcloud/DeepSeek-R1-Distill-Llama-70B": {
"input_cost_per_token": 6.7e-07,
"litellm_provider": "ovhcloud",
@@ -24584,6 +26245,66 @@
"supports_function_calling": true,
"supports_tool_choice": true
},
+ "perplexity/preset/pro-search": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_preset": true
+ },
+ "perplexity/openai/gpt-4o": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": false
+ },
+ "perplexity/openai/gpt-4o-mini": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": false
+ },
+ "perplexity/openai/gpt-5.2": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": true
+ },
+ "perplexity/anthropic/claude-3-5-sonnet-20241022": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": false
+ },
+ "perplexity/anthropic/claude-3-5-haiku-20241022": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": false
+ },
+ "perplexity/google/gemini-2.0-flash-exp": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": false
+ },
+ "perplexity/google/gemini-2.0-flash-thinking-exp": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": true
+ },
+ "perplexity/xai/grok-2-1212": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": false
+ },
+ "perplexity/xai/grok-2-vision-1212": {
+ "litellm_provider": "perplexity",
+ "mode": "responses",
+ "supports_web_search": true,
+ "supports_reasoning": false
+ },
"publicai/aisingapore/Qwen-SEA-LION-v4-32B-IT": {
"input_cost_per_token": 0.0,
"litellm_provider": "publicai",
@@ -24693,6 +26414,19 @@
"supports_system_messages": true,
"supports_vision": true
},
+ "qwen.qwen3-coder-next": {
+ "input_cost_per_token": 5e-07,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 262144,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"recraft/recraftv2": {
"litellm_provider": "recraft",
"mode": "image_generation",
@@ -25839,13 +27573,13 @@
"litellm_provider": "bedrock",
"max_input_tokens": 77,
"mode": "image_edit",
- "output_cost_per_image": 0.40
+ "output_cost_per_image": 0.4
},
"stability.stable-creative-upscale-v1:0": {
"litellm_provider": "bedrock",
"max_input_tokens": 77,
"mode": "image_edit",
- "output_cost_per_image": 0.60
+ "output_cost_per_image": 0.6
},
"stability.stable-fast-upscale-v1:0": {
"litellm_provider": "bedrock",
@@ -26604,6 +28338,34 @@
"supports_reasoning": true,
"supports_tool_choice": true
},
+ "together_ai/zai-org/GLM-4.7": {
+ "input_cost_per_token": 4.5e-07,
+ "litellm_provider": "together_ai",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 200000,
+ "max_tokens": 200000,
+ "mode": "chat",
+ "output_cost_per_token": 2e-06,
+ "source": "https://www.together.ai/models/glm-4-7",
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
+ "together_ai/moonshotai/Kimi-K2.5": {
+ "input_cost_per_token": 5e-07,
+ "litellm_provider": "together_ai",
+ "max_input_tokens": 256000,
+ "max_output_tokens": 256000,
+ "max_tokens": 256000,
+ "mode": "chat",
+ "output_cost_per_token": 2.8e-06,
+ "source": "https://www.together.ai/models/kimi-k2-5",
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "supports_reasoning": true
+ },
"together_ai/moonshotai/Kimi-K2-Instruct-0905": {
"input_cost_per_token": 1e-06,
"litellm_provider": "together_ai",
@@ -27101,6 +28863,30 @@
"supports_reasoning": true,
"supports_tool_choice": false
},
+ "us.deepseek.v3.2": {
+ "input_cost_per_token": 6.2e-07,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 1.85e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
+ "eu.deepseek.v3.2": {
+ "input_cost_per_token": 7.4e-07,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "max_tokens": 163840,
+ "mode": "chat",
+ "output_cost_per_token": 2.22e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
"us.meta.llama3-1-405b-instruct-v1:0": {
"input_cost_per_token": 5.32e-06,
"litellm_provider": "bedrock",
@@ -27320,7 +29106,9 @@
"max_output_tokens": 16384,
"max_tokens": 16384,
"mode": "chat",
- "output_cost_per_token": 3e-07
+ "output_cost_per_token": 3e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/alibaba/qwen3-coder": {
"input_cost_per_token": 4e-07,
@@ -27329,7 +29117,9 @@
"max_output_tokens": 66536,
"max_tokens": 66536,
"mode": "chat",
- "output_cost_per_token": 1.6e-06
+ "output_cost_per_token": 1.6e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/amazon/nova-lite": {
"input_cost_per_token": 6e-08,
@@ -27338,7 +29128,10 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 2.4e-07
+ "output_cost_per_token": 2.4e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/amazon/nova-micro": {
"input_cost_per_token": 3.5e-08,
@@ -27347,7 +29140,9 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 1.4e-07
+ "output_cost_per_token": 1.4e-07,
+ "supports_function_calling": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/amazon/nova-pro": {
"input_cost_per_token": 8e-07,
@@ -27356,7 +29151,10 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 3.2e-06
+ "output_cost_per_token": 3.2e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/amazon/titan-embed-text-v2": {
"input_cost_per_token": 2e-08,
@@ -27376,7 +29174,11 @@
"max_output_tokens": 4096,
"max_tokens": 4096,
"mode": "chat",
- "output_cost_per_token": 1.25e-06
+ "output_cost_per_token": 1.25e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/anthropic/claude-3-opus": {
"cache_creation_input_token_cost": 1.875e-05,
@@ -27387,7 +29189,11 @@
"max_output_tokens": 4096,
"max_tokens": 4096,
"mode": "chat",
- "output_cost_per_token": 7.5e-05
+ "output_cost_per_token": 7.5e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/anthropic/claude-3.5-haiku": {
"cache_creation_input_token_cost": 1e-06,
@@ -27398,7 +29204,11 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 4e-06
+ "output_cost_per_token": 4e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/anthropic/claude-3.5-sonnet": {
"cache_creation_input_token_cost": 3.75e-06,
@@ -27409,7 +29219,11 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 1.5e-05
+ "output_cost_per_token": 1.5e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/anthropic/claude-3.7-sonnet": {
"cache_creation_input_token_cost": 3.75e-06,
@@ -27420,7 +29234,11 @@
"max_output_tokens": 64000,
"max_tokens": 64000,
"mode": "chat",
- "output_cost_per_token": 1.5e-05
+ "output_cost_per_token": 1.5e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/anthropic/claude-4-opus": {
"cache_creation_input_token_cost": 1.875e-05,
@@ -27431,7 +29249,11 @@
"max_output_tokens": 32000,
"max_tokens": 32000,
"mode": "chat",
- "output_cost_per_token": 7.5e-05
+ "output_cost_per_token": 7.5e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/anthropic/claude-4-sonnet": {
"cache_creation_input_token_cost": 3.75e-06,
@@ -27442,7 +29264,196 @@
"max_output_tokens": 64000,
"max_tokens": 64000,
"mode": "chat",
- "output_cost_per_token": 1.5e-05
+ "output_cost_per_token": 1.5e-05,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
+ },
+ "vercel_ai_gateway/anthropic/claude-3-5-sonnet": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-3-5-sonnet-20241022": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-3-7-sonnet": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-haiku-4.5": {
+ "cache_creation_input_token_cost": 1.25e-06,
+ "cache_read_input_token_cost": 1e-07,
+ "input_cost_per_token": 1e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 5e-06,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-opus-4": {
+ "cache_creation_input_token_cost": 1.875e-05,
+ "cache_read_input_token_cost": 1.5e-06,
+ "input_cost_per_token": 1.5e-05,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 7.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-opus-4.1": {
+ "cache_creation_input_token_cost": 1.875e-05,
+ "cache_read_input_token_cost": 1.5e-06,
+ "input_cost_per_token": 1.5e-05,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "chat",
+ "output_cost_per_token": 7.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-opus-4.5": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_read_input_token_cost": 5e-07,
+ "input_cost_per_token": 5e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-opus-4.6": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_read_input_token_cost": 5e-07,
+ "input_cost_per_token": 5e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-sonnet-4": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
+ },
+ "vercel_ai_gateway/anthropic/claude-sonnet-4.5": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "input_cost_per_token": 3e-06,
+ "litellm_provider": "vercel_ai_gateway",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true,
+ "supports_vision": true
},
"vercel_ai_gateway/cohere/command-a": {
"input_cost_per_token": 2.5e-06,
@@ -27451,7 +29462,10 @@
"max_output_tokens": 8000,
"max_tokens": 8000,
"mode": "chat",
- "output_cost_per_token": 1e-05
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/cohere/command-r": {
"input_cost_per_token": 1.5e-07,
@@ -27460,7 +29474,9 @@
"max_output_tokens": 4096,
"max_tokens": 4096,
"mode": "chat",
- "output_cost_per_token": 6e-07
+ "output_cost_per_token": 6e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/cohere/command-r-plus": {
"input_cost_per_token": 2.5e-06,
@@ -27469,7 +29485,9 @@
"max_output_tokens": 4096,
"max_tokens": 4096,
"mode": "chat",
- "output_cost_per_token": 1e-05
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/cohere/embed-v4.0": {
"input_cost_per_token": 1.2e-07,
@@ -27487,7 +29505,8 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 2.19e-06
+ "output_cost_per_token": 2.19e-06,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/deepseek/deepseek-r1-distill-llama-70b": {
"input_cost_per_token": 7.5e-07,
@@ -27496,7 +29515,10 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 9.9e-07
+ "output_cost_per_token": 9.9e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/deepseek/deepseek-v3": {
"input_cost_per_token": 9e-07,
@@ -27505,25 +29527,36 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 9e-07
+ "output_cost_per_token": 9e-07,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/google/gemini-2.0-flash": {
+ "deprecation_date": "2026-03-31",
"input_cost_per_token": 1.5e-07,
"litellm_provider": "vercel_ai_gateway",
"max_input_tokens": 1048576,
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 6e-07
+ "output_cost_per_token": 6e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/google/gemini-2.0-flash-lite": {
+ "deprecation_date": "2026-03-31",
"input_cost_per_token": 7.5e-08,
"litellm_provider": "vercel_ai_gateway",
"max_input_tokens": 1048576,
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 3e-07
+ "output_cost_per_token": 3e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/google/gemini-2.5-flash": {
"input_cost_per_token": 3e-07,
@@ -27532,7 +29565,11 @@
"max_output_tokens": 65536,
"max_tokens": 65536,
"mode": "chat",
- "output_cost_per_token": 2.5e-06
+ "output_cost_per_token": 2.5e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/google/gemini-2.5-pro": {
"input_cost_per_token": 2.5e-06,
@@ -27541,7 +29578,11 @@
"max_output_tokens": 65536,
"max_tokens": 65536,
"mode": "chat",
- "output_cost_per_token": 1e-05
+ "output_cost_per_token": 1e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/google/gemini-embedding-001": {
"input_cost_per_token": 1.5e-07,
@@ -27559,7 +29600,10 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 2e-07
+ "output_cost_per_token": 2e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/google/text-embedding-005": {
"input_cost_per_token": 2.5e-08,
@@ -27595,7 +29639,8 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 7.9e-07
+ "output_cost_per_token": 7.9e-07,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/meta/llama-3-8b": {
"input_cost_per_token": 5e-08,
@@ -27604,7 +29649,8 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 8e-08
+ "output_cost_per_token": 8e-08,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/meta/llama-3.1-70b": {
"input_cost_per_token": 7.2e-07,
@@ -27613,7 +29659,8 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 7.2e-07
+ "output_cost_per_token": 7.2e-07,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/meta/llama-3.1-8b": {
"input_cost_per_token": 5e-08,
@@ -27622,7 +29669,9 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 8e-08
+ "output_cost_per_token": 8e-08,
+ "supports_function_calling": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/meta/llama-3.2-11b": {
"input_cost_per_token": 1.6e-07,
@@ -27631,7 +29680,10 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 1.6e-07
+ "output_cost_per_token": 1.6e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/meta/llama-3.2-1b": {
"input_cost_per_token": 1e-07,
@@ -27649,7 +29701,9 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 1.5e-07
+ "output_cost_per_token": 1.5e-07,
+ "supports_function_calling": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/meta/llama-3.2-90b": {
"input_cost_per_token": 7.2e-07,
@@ -27658,7 +29712,10 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 7.2e-07
+ "output_cost_per_token": 7.2e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/meta/llama-3.3-70b": {
"input_cost_per_token": 7.2e-07,
@@ -27667,7 +29724,9 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 7.2e-07
+ "output_cost_per_token": 7.2e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/meta/llama-4-maverick": {
"input_cost_per_token": 2e-07,
@@ -27676,7 +29735,8 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 6e-07
+ "output_cost_per_token": 6e-07,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/meta/llama-4-scout": {
"input_cost_per_token": 1e-07,
@@ -27685,7 +29745,10 @@
"max_output_tokens": 8192,
"max_tokens": 8192,
"mode": "chat",
- "output_cost_per_token": 3e-07
+ "output_cost_per_token": 3e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/mistral/codestral": {
"input_cost_per_token": 3e-07,
@@ -27694,7 +29757,9 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 9e-07
+ "output_cost_per_token": 9e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/mistral/codestral-embed": {
"input_cost_per_token": 1.5e-07,
@@ -27712,7 +29777,10 @@
"max_output_tokens": 128000,
"max_tokens": 128000,
"mode": "chat",
- "output_cost_per_token": 2.8e-07
+ "output_cost_per_token": 2.8e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/mistral/magistral-medium": {
"input_cost_per_token": 2e-06,
@@ -27721,7 +29789,10 @@
"max_output_tokens": 64000,
"max_tokens": 64000,
"mode": "chat",
- "output_cost_per_token": 5e-06
+ "output_cost_per_token": 5e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/mistral/magistral-small": {
"input_cost_per_token": 5e-07,
@@ -27730,7 +29801,8 @@
"max_output_tokens": 64000,
"max_tokens": 64000,
"mode": "chat",
- "output_cost_per_token": 1.5e-06
+ "output_cost_per_token": 1.5e-06,
+ "supports_function_calling": true
},
"vercel_ai_gateway/mistral/ministral-3b": {
"input_cost_per_token": 4e-08,
@@ -27739,7 +29811,9 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 4e-08
+ "output_cost_per_token": 4e-08,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/mistral/ministral-8b": {
"input_cost_per_token": 1e-07,
@@ -27748,7 +29822,10 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 1e-07
+ "output_cost_per_token": 1e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/mistral/mistral-embed": {
"input_cost_per_token": 1e-07,
@@ -27766,7 +29843,9 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 6e-06
+ "output_cost_per_token": 6e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/mistral/mistral-saba-24b": {
"input_cost_per_token": 7.9e-07,
@@ -27784,7 +29863,10 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 3e-07
+ "output_cost_per_token": 3e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/mistral/mixtral-8x22b-instruct": {
"input_cost_per_token": 1.2e-06,
@@ -27793,7 +29875,8 @@
"max_output_tokens": 2048,
"max_tokens": 2048,
"mode": "chat",
- "output_cost_per_token": 1.2e-06
+ "output_cost_per_token": 1.2e-06,
+ "supports_function_calling": true
},
"vercel_ai_gateway/mistral/pixtral-12b": {
"input_cost_per_token": 1.5e-07,
@@ -27802,7 +29885,11 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 1.5e-07
+ "output_cost_per_token": 1.5e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/mistral/pixtral-large": {
"input_cost_per_token": 2e-06,
@@ -27811,7 +29898,11 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 6e-06
+ "output_cost_per_token": 6e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/moonshotai/kimi-k2": {
"input_cost_per_token": 5.5e-07,
@@ -27820,7 +29911,9 @@
"max_output_tokens": 16384,
"max_tokens": 16384,
"mode": "chat",
- "output_cost_per_token": 2.2e-06
+ "output_cost_per_token": 2.2e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/morph/morph-v3-fast": {
"input_cost_per_token": 8e-07,
@@ -27847,7 +29940,9 @@
"max_output_tokens": 4096,
"max_tokens": 4096,
"mode": "chat",
- "output_cost_per_token": 1.5e-06
+ "output_cost_per_token": 1.5e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/openai/gpt-3.5-turbo-instruct": {
"input_cost_per_token": 1.5e-06,
@@ -27865,7 +29960,10 @@
"max_output_tokens": 4096,
"max_tokens": 4096,
"mode": "chat",
- "output_cost_per_token": 3e-05
+ "output_cost_per_token": 3e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/openai/gpt-4.1": {
"cache_creation_input_token_cost": 0.0,
@@ -27876,7 +29974,11 @@
"max_output_tokens": 32768,
"max_tokens": 32768,
"mode": "chat",
- "output_cost_per_token": 8e-06
+ "output_cost_per_token": 8e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/gpt-4.1-mini": {
"cache_creation_input_token_cost": 0.0,
@@ -27887,7 +29989,11 @@
"max_output_tokens": 32768,
"max_tokens": 32768,
"mode": "chat",
- "output_cost_per_token": 1.6e-06
+ "output_cost_per_token": 1.6e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/gpt-4.1-nano": {
"cache_creation_input_token_cost": 0.0,
@@ -27898,7 +30004,11 @@
"max_output_tokens": 32768,
"max_tokens": 32768,
"mode": "chat",
- "output_cost_per_token": 4e-07
+ "output_cost_per_token": 4e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/gpt-4o": {
"cache_creation_input_token_cost": 0.0,
@@ -27909,7 +30019,11 @@
"max_output_tokens": 16384,
"max_tokens": 16384,
"mode": "chat",
- "output_cost_per_token": 1e-05
+ "output_cost_per_token": 1e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/gpt-4o-mini": {
"cache_creation_input_token_cost": 0.0,
@@ -27920,7 +30034,11 @@
"max_output_tokens": 16384,
"max_tokens": 16384,
"mode": "chat",
- "output_cost_per_token": 6e-07
+ "output_cost_per_token": 6e-07,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/o1": {
"cache_creation_input_token_cost": 0.0,
@@ -27931,7 +30049,11 @@
"max_output_tokens": 100000,
"max_tokens": 100000,
"mode": "chat",
- "output_cost_per_token": 6e-05
+ "output_cost_per_token": 6e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/o3": {
"cache_creation_input_token_cost": 0.0,
@@ -27942,7 +30064,11 @@
"max_output_tokens": 100000,
"max_tokens": 100000,
"mode": "chat",
- "output_cost_per_token": 8e-06
+ "output_cost_per_token": 8e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/o3-mini": {
"cache_creation_input_token_cost": 0.0,
@@ -27953,7 +30079,10 @@
"max_output_tokens": 100000,
"max_tokens": 100000,
"mode": "chat",
- "output_cost_per_token": 4.4e-06
+ "output_cost_per_token": 4.4e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/o4-mini": {
"cache_creation_input_token_cost": 0.0,
@@ -27964,7 +30093,11 @@
"max_output_tokens": 100000,
"max_tokens": 100000,
"mode": "chat",
- "output_cost_per_token": 4.4e-06
+ "output_cost_per_token": 4.4e-06,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_response_schema": true
},
"vercel_ai_gateway/openai/text-embedding-3-large": {
"input_cost_per_token": 1.3e-07,
@@ -28036,7 +30169,10 @@
"max_output_tokens": 32000,
"max_tokens": 32000,
"mode": "chat",
- "output_cost_per_token": 1.5e-05
+ "output_cost_per_token": 1.5e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/vercel/v0-1.5-md": {
"input_cost_per_token": 3e-06,
@@ -28045,7 +30181,10 @@
"max_output_tokens": 32768,
"max_tokens": 32768,
"mode": "chat",
- "output_cost_per_token": 1.5e-05
+ "output_cost_per_token": 1.5e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/xai/grok-2": {
"input_cost_per_token": 2e-06,
@@ -28054,7 +30193,9 @@
"max_output_tokens": 4000,
"max_tokens": 4000,
"mode": "chat",
- "output_cost_per_token": 1e-05
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/xai/grok-2-vision": {
"input_cost_per_token": 2e-06,
@@ -28063,7 +30204,10 @@
"max_output_tokens": 32768,
"max_tokens": 32768,
"mode": "chat",
- "output_cost_per_token": 1e-05
+ "output_cost_per_token": 1e-05,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/xai/grok-3": {
"input_cost_per_token": 3e-06,
@@ -28072,7 +30216,9 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 1.5e-05
+ "output_cost_per_token": 1.5e-05,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/xai/grok-3-fast": {
"input_cost_per_token": 5e-06,
@@ -28081,7 +30227,8 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 2.5e-05
+ "output_cost_per_token": 2.5e-05,
+ "supports_function_calling": true
},
"vercel_ai_gateway/xai/grok-3-mini": {
"input_cost_per_token": 3e-07,
@@ -28090,7 +30237,9 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 5e-07
+ "output_cost_per_token": 5e-07,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/xai/grok-3-mini-fast": {
"input_cost_per_token": 6e-07,
@@ -28099,7 +30248,9 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 4e-06
+ "output_cost_per_token": 4e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/xai/grok-4": {
"input_cost_per_token": 3e-06,
@@ -28108,7 +30259,9 @@
"max_output_tokens": 256000,
"max_tokens": 256000,
"mode": "chat",
- "output_cost_per_token": 1.5e-05
+ "output_cost_per_token": 1.5e-05,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/zai/glm-4.5": {
"input_cost_per_token": 6e-07,
@@ -28117,7 +30270,9 @@
"max_output_tokens": 131072,
"max_tokens": 131072,
"mode": "chat",
- "output_cost_per_token": 2.2e-06
+ "output_cost_per_token": 2.2e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/zai/glm-4.5-air": {
"input_cost_per_token": 2e-07,
@@ -28126,7 +30281,9 @@
"max_output_tokens": 96000,
"max_tokens": 96000,
"mode": "chat",
- "output_cost_per_token": 1.1e-06
+ "output_cost_per_token": 1.1e-06,
+ "supports_function_calling": true,
+ "supports_tool_choice": true
},
"vercel_ai_gateway/zai/glm-4.6": {
"litellm_provider": "vercel_ai_gateway",
@@ -28194,7 +30351,9 @@
"supports_prompt_caching": true,
"supports_reasoning": true,
"supports_response_schema": true,
- "supports_tool_choice": true
+ "supports_tool_choice": true,
+ "supports_native_streaming": true,
+ "supports_vision": true
},
"vertex_ai/claude-3-5-sonnet": {
"input_cost_per_token": 3e-06,
@@ -28465,7 +30624,68 @@
"supports_response_schema": true,
"supports_tool_choice": true,
"supports_vision": true,
- "tool_use_system_prompt_tokens": 159
+ "tool_use_system_prompt_tokens": 159,
+ "supports_native_streaming": true
+ },
+ "vertex_ai/claude-opus-4-6": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 5e-06,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "vertex_ai-anthropic_models",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
+ },
+ "vertex_ai/claude-opus-4-6@default": {
+ "cache_creation_input_token_cost": 6.25e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05,
+ "cache_read_input_token_cost": 5e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 1e-06,
+ "input_cost_per_token": 5e-06,
+ "input_cost_per_token_above_200k_tokens": 1e-05,
+ "litellm_provider": "vertex_ai-anthropic_models",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-05,
+ "output_cost_per_token_above_200k_tokens": 3.75e-05,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ },
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346
},
"vertex_ai/claude-sonnet-4-5": {
"cache_creation_input_token_cost": 3.75e-06,
@@ -28493,6 +30713,36 @@
"supports_tool_choice": true,
"supports_vision": true
},
+ "vertex_ai/claude-sonnet-4-6": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6e-07,
+ "input_cost_per_token": 3e-06,
+ "input_cost_per_token_above_200k_tokens": 6e-06,
+ "litellm_provider": "vertex_ai-anthropic_models",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "output_cost_per_token_above_200k_tokens": 2.25e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ }
+ },
"vertex_ai/claude-sonnet-4-5@20250929": {
"cache_creation_input_token_cost": 3.75e-06,
"cache_read_input_token_cost": 3e-07,
@@ -28517,7 +30767,8 @@
"supports_reasoning": true,
"supports_response_schema": true,
"supports_tool_choice": true,
- "supports_vision": true
+ "supports_vision": true,
+ "supports_native_streaming": true
},
"vertex_ai/claude-opus-4@20250514": {
"cache_creation_input_token_cost": 1.875e-05,
@@ -28799,6 +31050,21 @@
"output_cost_per_token_batches": 6e-06,
"source": "https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/3-pro-image"
},
+ "vertex_ai/deep-research-pro-preview-12-2025": {
+ "input_cost_per_image": 0.0011,
+ "input_cost_per_token": 2e-06,
+ "input_cost_per_token_batches": 1e-06,
+ "litellm_provider": "vertex_ai-language-models",
+ "max_input_tokens": 65536,
+ "max_output_tokens": 32768,
+ "max_tokens": 32768,
+ "mode": "image_generation",
+ "output_cost_per_image": 0.134,
+ "output_cost_per_image_token": 0.00012,
+ "output_cost_per_token": 1.2e-05,
+ "output_cost_per_token_batches": 6e-06,
+ "source": "https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/3-pro-image"
+ },
"vertex_ai/imagegeneration@006": {
"litellm_provider": "vertex_ai-image-models",
"mode": "image_generation",
@@ -29107,6 +31373,21 @@
"supports_reasoning": true,
"supports_tool_choice": true
},
+ "vertex_ai/zai-org/glm-5-maas": {
+ "cache_read_input_token_cost": 1e-07,
+ "input_cost_per_token": 1e-06,
+ "litellm_provider": "vertex_ai-zai_models",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 3.2e-06,
+ "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing#glm-models",
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_tool_choice": true
+ },
"vertex_ai/mistral-medium-3": {
"input_cost_per_token": 4e-07,
"litellm_provider": "vertex_ai-mistral_models",
@@ -29288,6 +31569,9 @@
"mode": "chat",
"output_cost_per_token": 1e-06,
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
+ "supported_regions": [
+ "global"
+ ],
"supports_function_calling": true,
"supports_tool_choice": true
},
@@ -29300,6 +31584,9 @@
"mode": "chat",
"output_cost_per_token": 4e-06,
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
+ "supported_regions": [
+ "global"
+ ],
"supports_function_calling": true,
"supports_tool_choice": true
},
@@ -29312,6 +31599,9 @@
"mode": "chat",
"output_cost_per_token": 1.2e-06,
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
+ "supported_regions": [
+ "global"
+ ],
"supports_function_calling": true,
"supports_tool_choice": true
},
@@ -29324,6 +31614,9 @@
"mode": "chat",
"output_cost_per_token": 1.2e-06,
"source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
+ "supported_regions": [
+ "global"
+ ],
"supports_function_calling": true,
"supports_tool_choice": true
},
@@ -30186,6 +32479,7 @@
"supports_web_search": true
},
"xai/grok-3": {
+ "cache_read_input_token_cost": 7.5e-07,
"input_cost_per_token": 3e-06,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30200,6 +32494,7 @@
"supports_web_search": true
},
"xai/grok-3-beta": {
+ "cache_read_input_token_cost": 7.5e-07,
"input_cost_per_token": 3e-06,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30214,6 +32509,7 @@
"supports_web_search": true
},
"xai/grok-3-fast-beta": {
+ "cache_read_input_token_cost": 1.25e-06,
"input_cost_per_token": 5e-06,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30228,6 +32524,7 @@
"supports_web_search": true
},
"xai/grok-3-fast-latest": {
+ "cache_read_input_token_cost": 1.25e-06,
"input_cost_per_token": 5e-06,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30242,6 +32539,7 @@
"supports_web_search": true
},
"xai/grok-3-latest": {
+ "cache_read_input_token_cost": 7.5e-07,
"input_cost_per_token": 3e-06,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30256,6 +32554,7 @@
"supports_web_search": true
},
"xai/grok-3-mini": {
+ "cache_read_input_token_cost": 7.5e-08,
"input_cost_per_token": 3e-07,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30271,6 +32570,7 @@
"supports_web_search": true
},
"xai/grok-3-mini-beta": {
+ "cache_read_input_token_cost": 7.5e-08,
"input_cost_per_token": 3e-07,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30286,6 +32586,7 @@
"supports_web_search": true
},
"xai/grok-3-mini-fast": {
+ "cache_read_input_token_cost": 1.5e-07,
"input_cost_per_token": 6e-07,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30301,6 +32602,7 @@
"supports_web_search": true
},
"xai/grok-3-mini-fast-beta": {
+ "cache_read_input_token_cost": 1.5e-07,
"input_cost_per_token": 6e-07,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30316,6 +32618,7 @@
"supports_web_search": true
},
"xai/grok-3-mini-fast-latest": {
+ "cache_read_input_token_cost": 1.5e-07,
"input_cost_per_token": 6e-07,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30331,6 +32634,7 @@
"supports_web_search": true
},
"xai/grok-3-mini-latest": {
+ "cache_read_input_token_cost": 7.5e-08,
"input_cost_per_token": 3e-07,
"litellm_provider": "xai",
"max_input_tokens": 131072,
@@ -30587,6 +32891,20 @@
"supports_vision": true,
"supports_web_search": true
},
+ "zai.glm-4.7": {
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "bedrock_converse",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 2.2e-06,
+ "supports_function_calling": true,
+ "supports_reasoning": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "source": "https://aws.amazon.com/bedrock/pricing/"
+ },
"zai/glm-4.7": {
"cache_creation_input_token_cost": 0,
"cache_read_input_token_cost": 1.1e-07,
@@ -30597,11 +32915,14 @@
"max_output_tokens": 128000,
"mode": "chat",
"supports_function_calling": true,
+ "supports_prompt_caching": true,
"supports_reasoning": true,
"supports_tool_choice": true,
"source": "https://docs.z.ai/guides/overview/pricing"
},
"zai/glm-4.6": {
+ "cache_creation_input_token_cost": 0,
+ "cache_read_input_token_cost": 1.1e-07,
"input_cost_per_token": 6e-07,
"output_cost_per_token": 2.2e-06,
"litellm_provider": "zai",
@@ -30609,6 +32930,8 @@
"max_output_tokens": 128000,
"mode": "chat",
"supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
"supports_tool_choice": true,
"source": "https://docs.z.ai/guides/overview/pricing"
},
@@ -30734,6 +33057,23 @@
"1280x720"
]
},
+ "openai/sora-2-pro-high-res": {
+ "litellm_provider": "openai",
+ "mode": "video_generation",
+ "output_cost_per_video_per_second": 0.5,
+ "source": "https://platform.openai.com/docs/api-reference/videos",
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "video"
+ ],
+ "supported_resolutions": [
+ "1024x1792",
+ "1792x1024"
+ ]
+ },
"azure/sora-2": {
"litellm_provider": "azure",
"mode": "video_generation",
@@ -34255,5 +36595,761 @@
"mode": "chat",
"output_cost_per_token": 0,
"supports_reasoning": true
+ },
+ "tts-1-1106": {
+ "input_cost_per_character": 1.5e-05,
+ "litellm_provider": "openai",
+ "mode": "audio_speech",
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ]
+ },
+ "tts-1-hd-1106": {
+ "input_cost_per_character": 3e-05,
+ "litellm_provider": "openai",
+ "mode": "audio_speech",
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ]
+ },
+ "gpt-4o-mini-tts-2025-03-20": {
+ "input_cost_per_token": 2.5e-06,
+ "litellm_provider": "openai",
+ "mode": "audio_speech",
+ "output_cost_per_audio_token": 1.2e-05,
+ "output_cost_per_second": 0.00025,
+ "output_cost_per_token": 1e-05,
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "audio"
+ ]
+ },
+ "gpt-4o-mini-tts-2025-12-15": {
+ "input_cost_per_token": 2.5e-06,
+ "litellm_provider": "openai",
+ "mode": "audio_speech",
+ "output_cost_per_audio_token": 1.2e-05,
+ "output_cost_per_second": 0.00025,
+ "output_cost_per_token": 1e-05,
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "audio"
+ ]
+ },
+ "gpt-4o-mini-transcribe-2025-03-20": {
+ "input_cost_per_audio_token": 3e-06,
+ "input_cost_per_token": 1.25e-06,
+ "litellm_provider": "openai",
+ "max_input_tokens": 16000,
+ "max_output_tokens": 2000,
+ "mode": "audio_transcription",
+ "output_cost_per_token": 5e-06,
+ "supported_endpoints": [
+ "/v1/audio/transcriptions"
+ ]
+ },
+ "gpt-4o-mini-transcribe-2025-12-15": {
+ "input_cost_per_audio_token": 3e-06,
+ "input_cost_per_token": 1.25e-06,
+ "litellm_provider": "openai",
+ "max_input_tokens": 16000,
+ "max_output_tokens": 2000,
+ "mode": "audio_transcription",
+ "output_cost_per_token": 5e-06,
+ "supported_endpoints": [
+ "/v1/audio/transcriptions"
+ ]
+ },
+ "gpt-5-search-api": {
+ "cache_read_input_token_cost": 1.25e-07,
+ "input_cost_per_token": 1.25e-06,
+ "litellm_provider": "openai",
+ "max_input_tokens": 272000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "supports_web_search": true
+ },
+ "gpt-5-search-api-2025-10-14": {
+ "cache_read_input_token_cost": 1.25e-07,
+ "input_cost_per_token": 1.25e-06,
+ "litellm_provider": "openai",
+ "max_input_tokens": 272000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "supports_web_search": true
+ },
+ "gpt-realtime-mini-2025-10-06": {
+ "cache_creation_input_audio_token_cost": 3e-07,
+ "cache_read_input_audio_token_cost": 3e-07,
+ "cache_read_input_token_cost": 6e-08,
+ "input_cost_per_audio_token": 1e-05,
+ "input_cost_per_image": 8e-07,
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "openai",
+ "max_input_tokens": 128000,
+ "max_output_tokens": 4096,
+ "max_tokens": 4096,
+ "mode": "chat",
+ "output_cost_per_audio_token": 2e-05,
+ "output_cost_per_token": 2.4e-06,
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true
+ },
+ "gpt-realtime-mini-2025-12-15": {
+ "cache_creation_input_audio_token_cost": 3e-07,
+ "cache_read_input_audio_token_cost": 3e-07,
+ "cache_read_input_token_cost": 6e-08,
+ "input_cost_per_audio_token": 1e-05,
+ "input_cost_per_image": 8e-07,
+ "input_cost_per_token": 6e-07,
+ "litellm_provider": "openai",
+ "max_input_tokens": 128000,
+ "max_output_tokens": 4096,
+ "max_tokens": 4096,
+ "mode": "chat",
+ "output_cost_per_audio_token": 2e-05,
+ "output_cost_per_token": 2.4e-06,
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true
+ },
+ "sora-2": {
+ "litellm_provider": "openai",
+ "mode": "video_generation",
+ "output_cost_per_video_per_second": 0.1,
+ "source": "https://platform.openai.com/docs/api-reference/videos",
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "video"
+ ],
+ "supported_resolutions": [
+ "720x1280",
+ "1280x720"
+ ]
+ },
+ "sora-2-pro": {
+ "litellm_provider": "openai",
+ "mode": "video_generation",
+ "output_cost_per_video_per_second": 0.3,
+ "source": "https://platform.openai.com/docs/api-reference/videos",
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "video"
+ ],
+ "supported_resolutions": [
+ "720x1280",
+ "1280x720"
+ ]
+ },
+ "sora-2-pro-high-res": {
+ "litellm_provider": "openai",
+ "mode": "video_generation",
+ "output_cost_per_video_per_second": 0.5,
+ "source": "https://platform.openai.com/docs/api-reference/videos",
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "video"
+ ],
+ "supported_resolutions": [
+ "1024x1792",
+ "1792x1024"
+ ]
+ },
+ "chatgpt-image-latest": {
+ "cache_read_input_image_token_cost": 2.5e-06,
+ "cache_read_input_token_cost": 1.25e-06,
+ "input_cost_per_image_token": 1e-05,
+ "input_cost_per_token": 5e-06,
+ "litellm_provider": "openai",
+ "mode": "image_generation",
+ "output_cost_per_image_token": 4e-05,
+ "supported_endpoints": [
+ "/v1/images/generations",
+ "/v1/images/edits"
+ ]
+ },
+ "gemini-2.0-flash-exp-image-generation": {
+ "input_cost_per_token": 0.0,
+ "litellm_provider": "gemini",
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 32768,
+ "max_output_tokens": 32768,
+ "max_tokens": 32768,
+ "mode": "image_generation",
+ "output_cost_per_image": 0.039,
+ "output_cost_per_token": 0.0,
+ "source": "https://ai.google.dev/pricing",
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "image"
+ ],
+ "supports_vision": true
+ },
+ "gemini/gemini-2.0-flash-exp-image-generation": {
+ "input_cost_per_token": 0.0,
+ "litellm_provider": "gemini",
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 32768,
+ "max_output_tokens": 32768,
+ "max_tokens": 32768,
+ "mode": "image_generation",
+ "output_cost_per_image": 0.039,
+ "output_cost_per_token": 0.0,
+ "source": "https://ai.google.dev/pricing",
+ "supported_modalities": [
+ "text",
+ "image"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "image"
+ ],
+ "supports_vision": true,
+ "tpm": 250000,
+ "rpm": 10
+ },
+ "gemini/gemini-2.0-flash-lite-001": {
+ "cache_read_input_token_cost": 1.875e-08,
+ "deprecation_date": "2026-03-31",
+ "input_cost_per_audio_token": 7.5e-08,
+ "input_cost_per_token": 7.5e-08,
+ "litellm_provider": "gemini",
+ "max_audio_length_hours": 8.4,
+ "max_audio_per_prompt": 1,
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 8192,
+ "max_pdf_size_mb": 50,
+ "max_video_length": 1,
+ "max_videos_per_prompt": 10,
+ "mode": "chat",
+ "output_cost_per_token": 3e-07,
+ "rpm": 4000,
+ "source": "https://ai.google.dev/gemini-api/docs/pricing#gemini-2.0-flash-lite",
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio",
+ "video"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_output": true,
+ "supports_function_calling": true,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "supports_web_search": true,
+ "tpm": 4000000
+ },
+ "gemini-2.5-flash-native-audio-latest": {
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true
+ },
+ "gemini-2.5-flash-native-audio-preview-09-2025": {
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true
+ },
+ "gemini-2.5-flash-native-audio-preview-12-2025": {
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true
+ },
+ "gemini/gemini-2.5-flash-native-audio-latest": {
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true,
+ "tpm": 250000,
+ "rpm": 10
+ },
+ "gemini/gemini-2.5-flash-native-audio-preview-09-2025": {
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true,
+ "tpm": 250000,
+ "rpm": 10
+ },
+ "gemini/gemini-2.5-flash-native-audio-preview-12-2025": {
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 8192,
+ "max_tokens": 8192,
+ "mode": "chat",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
+ "supported_endpoints": [
+ "/v1/realtime"
+ ],
+ "supported_modalities": [
+ "text",
+ "audio"
+ ],
+ "supported_output_modalities": [
+ "text",
+ "audio"
+ ],
+ "supports_audio_input": true,
+ "supports_audio_output": true,
+ "tpm": 250000,
+ "rpm": 10
+ },
+ "gemini-2.5-flash-preview-tts": {
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "mode": "audio_speech",
+ "output_cost_per_token": 2.5e-06,
+ "source": "https://ai.google.dev/pricing",
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ]
+ },
+ "gemini-flash-latest": {
+ "cache_read_input_token_cost": 3e-08,
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_audio_length_hours": 8.4,
+ "max_audio_per_prompt": 1,
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65535,
+ "max_pdf_size_mb": 30,
+ "max_tokens": 65535,
+ "max_video_length": 1,
+ "max_videos_per_prompt": 10,
+ "mode": "chat",
+ "output_cost_per_reasoning_token": 2.5e-06,
+ "output_cost_per_token": 2.5e-06,
+ "rpm": 100000,
+ "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-preview",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions",
+ "/v1/batch"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio",
+ "video"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_output": false,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_url_context": true,
+ "supports_vision": true,
+ "supports_web_search": true,
+ "tpm": 8000000
+ },
+ "gemini-flash-lite-latest": {
+ "cache_read_input_token_cost": 1e-08,
+ "input_cost_per_audio_token": 3e-07,
+ "input_cost_per_token": 1e-07,
+ "litellm_provider": "gemini",
+ "max_audio_length_hours": 8.4,
+ "max_audio_per_prompt": 1,
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65535,
+ "max_pdf_size_mb": 30,
+ "max_tokens": 65535,
+ "max_video_length": 1,
+ "max_videos_per_prompt": 10,
+ "mode": "chat",
+ "output_cost_per_reasoning_token": 4e-07,
+ "output_cost_per_token": 4e-07,
+ "rpm": 15,
+ "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-lite",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions",
+ "/v1/batch"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio",
+ "video"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_output": false,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_url_context": true,
+ "supports_vision": true,
+ "supports_web_search": true,
+ "tpm": 250000
+ },
+ "gemini-pro-latest": {
+ "cache_read_input_token_cost": 1.25e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 2.5e-07,
+ "input_cost_per_token": 1.25e-06,
+ "input_cost_per_token_above_200k_tokens": 2.5e-06,
+ "litellm_provider": "gemini",
+ "max_audio_length_hours": 8.4,
+ "max_audio_per_prompt": 1,
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65535,
+ "max_pdf_size_mb": 30,
+ "max_tokens": 65535,
+ "max_video_length": 1,
+ "max_videos_per_prompt": 10,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "output_cost_per_token_above_200k_tokens": 1.5e-05,
+ "rpm": 2000,
+ "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio",
+ "video"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_input": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_video_input": true,
+ "supports_vision": true,
+ "supports_web_search": true,
+ "tpm": 800000
+ },
+ "gemini/gemini-pro-latest": {
+ "cache_read_input_token_cost": 1.25e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 2.5e-07,
+ "input_cost_per_token": 1.25e-06,
+ "input_cost_per_token_above_200k_tokens": 2.5e-06,
+ "litellm_provider": "gemini",
+ "max_audio_length_hours": 8.4,
+ "max_audio_per_prompt": 1,
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65535,
+ "max_pdf_size_mb": 30,
+ "max_tokens": 65535,
+ "max_video_length": 1,
+ "max_videos_per_prompt": 10,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "output_cost_per_token_above_200k_tokens": 1.5e-05,
+ "rpm": 2000,
+ "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio",
+ "video"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_input": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_video_input": true,
+ "supports_vision": true,
+ "supports_web_search": true,
+ "tpm": 800000
+ },
+ "gemini-exp-1206": {
+ "cache_read_input_token_cost": 3e-08,
+ "input_cost_per_audio_token": 1e-06,
+ "input_cost_per_token": 3e-07,
+ "litellm_provider": "gemini",
+ "max_audio_length_hours": 8.4,
+ "max_audio_per_prompt": 1,
+ "max_images_per_prompt": 3000,
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65535,
+ "max_pdf_size_mb": 30,
+ "max_tokens": 65535,
+ "max_video_length": 1,
+ "max_videos_per_prompt": 10,
+ "mode": "chat",
+ "output_cost_per_reasoning_token": 2.5e-06,
+ "output_cost_per_token": 2.5e-06,
+ "rpm": 100000,
+ "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-preview",
+ "supported_endpoints": [
+ "/v1/chat/completions",
+ "/v1/completions",
+ "/v1/batch"
+ ],
+ "supported_modalities": [
+ "text",
+ "image",
+ "audio",
+ "video"
+ ],
+ "supported_output_modalities": [
+ "text"
+ ],
+ "supports_audio_output": false,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_system_messages": true,
+ "supports_tool_choice": true,
+ "supports_url_context": true,
+ "supports_vision": true,
+ "supports_web_search": true,
+ "tpm": 8000000
+ },
+ "vertex_ai/claude-sonnet-4-6@default": {
+ "cache_creation_input_token_cost": 3.75e-06,
+ "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
+ "cache_read_input_token_cost": 3e-07,
+ "cache_read_input_token_cost_above_200k_tokens": 6e-07,
+ "input_cost_per_token": 3e-06,
+ "input_cost_per_token_above_200k_tokens": 6e-06,
+ "litellm_provider": "vertex_ai-anthropic_models",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 1.5e-05,
+ "output_cost_per_token_above_200k_tokens": 2.25e-05,
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "tool_use_system_prompt_tokens": 346,
+ "search_context_cost_per_query": {
+ "search_context_size_high": 0.01,
+ "search_context_size_low": 0.01,
+ "search_context_size_medium": 0.01
+ }
+ },
+ "duckduckgo/search": {
+ "litellm_provider": "duckduckgo",
+ "mode": "search",
+ "input_cost_per_query": 0.0,
+ "metadata": {
+ "notes": "DuckDuckGo Instant Answer API is free and does not require an API key."
+ }
}
-}
+}
\ No newline at end of file
diff --git a/litellm/policy_templates_backup.json b/litellm/policy_templates_backup.json
new file mode 100644
index 00000000000..f27f20187f9
--- /dev/null
+++ b/litellm/policy_templates_backup.json
@@ -0,0 +1,1883 @@
+[
+ {
+ "id": "advanced-au-pii-protection",
+ "title": "Advanced PII Protection (Australia)",
+ "description": "Protects Australian-specific identifiers, international employee data, financial information, credentials, protected class information, and industry-specific sensitive data.",
+ "icon": "ShieldCheckIcon",
+ "iconColor": "text-purple-500",
+ "iconBg": "bg-purple-50",
+ "guardrails": [
+ "au-pii-tax-identifiers",
+ "au-pii-passports",
+ "international-pii-identifiers",
+ "contact-information-pii",
+ "financial-pii",
+ "credentials-api-keys",
+ "network-infrastructure-pii",
+ "protected-class-information"
+ ],
+ "complexity": "High",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "au-pii-tax-identifiers",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "au_tfn",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "au_abn",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "au_medicare",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks Australian Tax File Numbers, Business Numbers, and Medicare Numbers"
+ }
+ },
+ {
+ "guardrail_name": "au-pii-passports",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_australia",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[PASSPORT_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks Australian passport numbers"
+ }
+ },
+ {
+ "guardrail_name": "international-pii-identifiers",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "us_ssn",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "us_ssn_no_dash",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_us",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_uk",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_germany",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_france",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_netherlands",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "nl_bsn_contextual",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_china",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_india",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_japan",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_canada",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "br_cpf",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "br_cpf_unformatted",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "br_rg",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "br_cnpj",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks international PII identifiers including passports and national IDs"
+ }
+ },
+ {
+ "guardrail_name": "contact-information-pii",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "email",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "us_phone",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "br_phone_landline",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "br_phone_mobile",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "street_address",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "br_cep",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks contact information including emails, phone numbers, and addresses"
+ }
+ },
+ {
+ "guardrail_name": "financial-pii",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "visa",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "mastercard",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "amex",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "discover",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "credit_card",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "iban",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks financial information including credit cards and bank account numbers"
+ }
+ },
+ {
+ "guardrail_name": "credentials-api-keys",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "aws_access_key",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "aws_secret_key",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "github_token",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "slack_token",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "generic_api_key",
+ "action": "BLOCK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Blocks requests containing API keys and credentials (AWS, GitHub, Slack)"
+ }
+ },
+ {
+ "guardrail_name": "network-infrastructure-pii",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "ipv4",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "ipv6",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[INTERNAL_IP_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks IP addresses in requests"
+ }
+ },
+ {
+ "guardrail_name": "protected-class-information",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "gender_sexual_orientation",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "race_ethnicity_national_origin",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "religion",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "age_discrimination",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "disability",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "marital_family_status",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "military_status",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "public_assistance",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[PROTECTED_CLASS_INFO_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks protected class information for HR compliance and anti-discrimination"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "advanced-pii-protection-australia",
+ "description": "Comprehensive PII detection and masking policy for Australia. Protects Australian-specific identifiers, international employee data, financial information, credentials, protected class information, and industry-specific sensitive data.",
+ "guardrails_add": [
+ "au-pii-tax-identifiers",
+ "au-pii-passports",
+ "international-pii-identifiers",
+ "contact-information-pii",
+ "financial-pii",
+ "credentials-api-keys",
+ "network-infrastructure-pii",
+ "protected-class-information"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "PII Protection",
+ "Australia"
+ ]
+ },
+ {
+ "id": "baseline-pii-protection",
+ "title": "Baseline PII Protection",
+ "description": "Baseline PII protection for internal tools and testing. Focuses on credentials and high-risk identifiers only. Suitable for non-sensitive internal use.",
+ "icon": "ShieldCheckIcon",
+ "iconColor": "text-blue-500",
+ "iconBg": "bg-blue-50",
+ "guardrails": [
+ "au-pii-tax-identifiers",
+ "credentials-api-keys",
+ "financial-pii"
+ ],
+ "complexity": "Low",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "au-pii-tax-identifiers",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "au_tfn",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "au_abn",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "au_medicare",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks Australian Tax File Numbers, Business Numbers, and Medicare Numbers"
+ }
+ },
+ {
+ "guardrail_name": "credentials-api-keys",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "aws_access_key",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "aws_secret_key",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "github_token",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "slack_token",
+ "action": "BLOCK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "generic_api_key",
+ "action": "BLOCK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Blocks requests containing API keys and credentials (AWS, GitHub, Slack)"
+ }
+ },
+ {
+ "guardrail_name": "financial-pii",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "visa",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "mastercard",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "amex",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "discover",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "credit_card",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "iban",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks financial information including credit cards and bank account numbers"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "baseline-pii-protection",
+ "description": "Baseline PII protection for internal tools and testing. Focuses on credentials and high-risk identifiers only.",
+ "guardrails_add": [
+ "au-pii-tax-identifiers",
+ "credentials-api-keys",
+ "financial-pii"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "PII Protection"
+ ]
+ },
+ {
+ "id": "nsfw-content-filter-australia",
+ "title": "NSFW Content Filter (Australia)",
+ "description": "Blocks profanity, sexual content, NSFW requests, self-harm content, and child safety violations using English and Australian-specific slang. Protects against inappropriate content including sexual solicitation, explicit content, Australian profanity, self-harm, and content involving minors.",
+ "icon": "ShieldExclamationIcon",
+ "iconColor": "text-red-500",
+ "iconBg": "bg-red-50",
+ "guardrails": [
+ "nsfw-content-filter-english",
+ "nsfw-content-filter-australian",
+ "nsfw-self-harm-filter",
+ "nsfw-child-safety-filter",
+ "nsfw-racial-bias-filter"
+ ],
+ "complexity": "Medium",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "nsfw-content-filter-english",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks profanity, sexual content, slurs, and NSFW terms in English"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-content-filter-australian",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse_au",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks Australian-specific slang and profanity (root, perv, bogan, wanker, etc.)"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-self-harm-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harmful_self_harm",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks content related to self-harm, suicide, and eating disorders"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-child-safety-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harmful_child_safety",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks inappropriate content involving minors using identifier + block word combinations"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-racial-bias-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "bias_racial",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks racial and ethnic discrimination, hate speech, and supremacist content"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "nsfw-content-filter-australia",
+ "description": "NSFW content filter for Australia. Blocks profanity, sexual content, inappropriate requests, self-harm content, child safety violations, and racial bias in English and Australian slang.",
+ "guardrails_add": [
+ "nsfw-content-filter-english",
+ "nsfw-content-filter-australian",
+ "nsfw-self-harm-filter",
+ "nsfw-child-safety-filter",
+ "nsfw-racial-bias-filter"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Content Safety",
+ "Australia"
+ ]
+ },
+ {
+ "id": "nsfw-content-filter-basic",
+ "title": "NSFW Content Filter (Basic)",
+ "description": "Basic NSFW content filtering for English only. Blocks profanity, sexual content, slurs, solicitation, explicit requests, self-harm content, and child safety violations. Suitable for most applications requiring content moderation.",
+ "icon": "ShieldExclamationIcon",
+ "iconColor": "text-orange-500",
+ "iconBg": "bg-orange-50",
+ "guardrails": [
+ "nsfw-content-filter-english-only",
+ "nsfw-self-harm-filter-basic",
+ "nsfw-child-safety-filter-basic",
+ "nsfw-racial-bias-filter-basic"
+ ],
+ "complexity": "Low",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "nsfw-content-filter-english-only",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks profanity, sexual content, slurs, and NSFW terms. Includes 485+ keywords covering explicit content, solicitation, sexual behavior, and exploitation."
+ }
+ },
+ {
+ "guardrail_name": "nsfw-self-harm-filter-basic",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harmful_self_harm",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks content related to self-harm, suicide, and eating disorders"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-child-safety-filter-basic",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harmful_child_safety",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks inappropriate content involving minors using identifier + block word combinations"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-racial-bias-filter-basic",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "bias_racial",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks racial and ethnic discrimination, hate speech, and supremacist content"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "nsfw-content-filter-basic",
+ "description": "Basic NSFW content filter. Blocks profanity, sexual content, inappropriate requests, self-harm content, child safety violations, and racial bias in English.",
+ "guardrails_add": [
+ "nsfw-content-filter-english-only",
+ "nsfw-self-harm-filter-basic",
+ "nsfw-child-safety-filter-basic",
+ "nsfw-racial-bias-filter-basic"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Content Safety"
+ ]
+ },
+ {
+ "id": "nsfw-content-filter-all-regions",
+ "title": "NSFW Content Filter (All Regions)",
+ "description": "Comprehensive multi-language NSFW content filtering. Blocks profanity, sexual content, inappropriate requests, self-harm content, and child safety violations in English, Spanish, French, German, and Australian. Best for global applications.",
+ "icon": "ShieldExclamationIcon",
+ "iconColor": "text-purple-500",
+ "iconBg": "bg-purple-50",
+ "guardrails": [
+ "nsfw-filter-english",
+ "nsfw-filter-spanish",
+ "nsfw-filter-french",
+ "nsfw-filter-german",
+ "nsfw-filter-australian",
+ "nsfw-self-harm-filter-global",
+ "nsfw-child-safety-filter-global",
+ "nsfw-racial-bias-filter-global"
+ ],
+ "complexity": "High",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "nsfw-filter-english",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "English profanity, sexual content, slurs, and NSFW terms (485+ keywords)"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-filter-spanish",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse_es",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Spanish profanity and offensive terms (68 keywords)"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-filter-french",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse_fr",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "French profanity and offensive terms (91 keywords)"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-filter-german",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse_de",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "German profanity and offensive terms (65 keywords)"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-filter-australian",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harm_toxic_abuse_au",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Australian slang and profanity (32 keywords: root, perv, bogan, wanker, etc.)"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-self-harm-filter-global",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harmful_self_harm",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks content related to self-harm, suicide, and eating disorders"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-child-safety-filter-global",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "harmful_child_safety",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks inappropriate content involving minors using identifier + block word combinations"
+ }
+ },
+ {
+ "guardrail_name": "nsfw-racial-bias-filter-global",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "bias_racial",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks racial and ethnic discrimination, hate speech, and supremacist content"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "nsfw-content-filter-all-regions",
+ "description": "Comprehensive multi-language NSFW content filter. Blocks profanity, inappropriate content, self-harm, child safety violations, and racial bias in English, Spanish, French, German, and Australian. Total coverage: 741+ keywords across all languages plus self-harm, child safety, and racial bias protection.",
+ "guardrails_add": [
+ "nsfw-filter-english",
+ "nsfw-filter-spanish",
+ "nsfw-filter-french",
+ "nsfw-filter-german",
+ "nsfw-filter-australian",
+ "nsfw-self-harm-filter-global",
+ "nsfw-child-safety-filter-global",
+ "nsfw-racial-bias-filter-global"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Content Safety"
+ ]
+ },
+ {
+ "id": "gdpr-eu-pii-protection",
+ "title": "GDPR Art. 32 \u2014 EU PII Protection",
+ "description": "GDPR Article 32 compliance for EU personal data protection. Masks French national IDs (NIR/INSEE), EU IBANs, French phone numbers, EU VAT numbers, EU passport numbers, and email addresses. Suitable for applications processing EU citizen data requiring GDPR compliance.",
+ "icon": "ShieldCheckIcon",
+ "iconColor": "text-indigo-500",
+ "iconBg": "bg-indigo-50",
+ "guardrails": [
+ "gdpr-eu-national-identifiers",
+ "gdpr-eu-financial-data",
+ "gdpr-eu-contact-information",
+ "gdpr-eu-business-identifiers"
+ ],
+ "complexity": "Medium",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "gdpr-eu-national-identifiers",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "fr_nir",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "eu_passport_generic",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks EU national identification numbers including French NIR/INSEE and EU passport numbers for GDPR compliance"
+ }
+ },
+ {
+ "guardrail_name": "gdpr-eu-financial-data",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "eu_iban_enhanced",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "iban",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[IBAN_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks EU bank account numbers (IBANs) to protect financial data under GDPR Article 32"
+ }
+ },
+ {
+ "guardrail_name": "gdpr-eu-contact-information",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "email",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "fr_phone",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "fr_postal_code",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks contact information including emails, French phone numbers, and postal codes for EU data subjects"
+ }
+ },
+ {
+ "guardrail_name": "gdpr-eu-business-identifiers",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "eu_vat",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[VAT_NUMBER_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks EU VAT identification numbers to protect business entity information under GDPR"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "gdpr-eu-pii-protection",
+ "description": "GDPR Article 32 compliance policy for EU personal data protection. Masks French national IDs, EU IBANs, phone numbers, VAT numbers, passports, and contact information.",
+ "guardrails_add": [
+ "gdpr-eu-national-identifiers",
+ "gdpr-eu-financial-data",
+ "gdpr-eu-contact-information",
+ "gdpr-eu-business-identifiers"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "PII Protection",
+ "Regulatory",
+ "EU"
+ ]
+ },
+ {
+ "id": "eu-ai-act-article5",
+ "title": "EU AI Act Article 5 \u2014 Prohibited Practices",
+ "description": "Comprehensive EU AI Act Article 5 compliance covering all prohibited AI practices. Includes 5 dedicated sub-guardrails per language (English + French) for: subliminal manipulation (Art. 5.1a), vulnerability exploitation (Art. 5.1b), social scoring (Art. 5.1c), emotion recognition in workplace/education (Art. 5.1f), and biometric categorization & predictive profiling (Art. 5.1d/g/h). Uses conditional matching (identifier word + context word).",
+ "icon": "ShieldExclamationIcon",
+ "iconColor": "text-red-500",
+ "iconBg": "bg-red-50",
+ "guardrails": [
+ "eu-ai-act-art5-manipulation",
+ "eu-ai-act-art5-vulnerability",
+ "eu-ai-act-art5-social-scoring",
+ "eu-ai-act-art5-emotion-recognition",
+ "eu-ai-act-art5-biometric-profiling",
+ "eu-ai-act-art5-manipulation-fr",
+ "eu-ai-act-art5-vulnerability-fr",
+ "eu-ai-act-art5-social-scoring-fr",
+ "eu-ai-act-art5-emotion-recognition-fr",
+ "eu-ai-act-art5-biometric-profiling-fr"
+ ],
+ "complexity": "High",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "eu-ai-act-art5-manipulation",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_manipulation",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_manipulation.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(a) \u2014 Blocks subliminal manipulation, deceptive AI techniques, dark patterns, and covert behavioral influence"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-vulnerability",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_vulnerability",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_vulnerability.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(b) \u2014 Blocks AI systems that exploit vulnerabilities of children, elderly, disabled persons, or economically disadvantaged groups"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-social-scoring",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_social_scoring",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_social_scoring.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(c) \u2014 Blocks social credit systems, citizen scoring, trustworthiness classification, and behavioral reputation scoring"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-emotion-recognition",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_emotion_recognition",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_emotion_recognition.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(f) \u2014 Blocks emotion recognition, mood tracking, and sentiment analysis in workplace and educational settings"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-biometric-profiling",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_biometric_profiling",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_biometric_profiling.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(d)(g)(h) \u2014 Blocks biometric categorization by race/ethnicity/religion/politics, facial recognition database scraping, and predictive policing"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-manipulation-fr",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_manipulation_fr",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_manipulation_fr.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(a) FR \u2014 Bloque la manipulation subliminale, les techniques d'IA trompeuses et les dark patterns (fran\u00e7ais)"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-vulnerability-fr",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_vulnerability_fr",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_vulnerability_fr.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(b) FR \u2014 Bloque l'exploitation des vuln\u00e9rabilit\u00e9s des enfants, personnes \u00e2g\u00e9es et handicap\u00e9es (fran\u00e7ais)"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-social-scoring-fr",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_social_scoring_fr",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_social_scoring_fr.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(c) FR \u2014 Bloque les syst\u00e8mes de cr\u00e9dit social, notation des citoyens et classification de fiabilit\u00e9 (fran\u00e7ais)"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-emotion-recognition-fr",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_emotion_recognition_fr",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_emotion_recognition_fr.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(f) FR \u2014 Bloque la reconnaissance des \u00e9motions et l'analyse des sentiments au travail et dans l'\u00e9ducation (fran\u00e7ais)"
+ }
+ },
+ {
+ "guardrail_name": "eu-ai-act-art5-biometric-profiling-fr",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "eu_ai_act_art5_biometric_profiling_fr",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/eu_ai_act_art5_biometric_profiling_fr.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Art. 5.1(d)(g)(h) FR \u2014 Bloque la cat\u00e9gorisation biom\u00e9trique, les bases de reconnaissance faciale et le profilage pr\u00e9dictif (fran\u00e7ais)"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "eu-ai-act-article5",
+ "description": "Comprehensive EU AI Act Article 5 compliance policy. Covers all prohibited AI practices across 5 sub-guardrails per language: subliminal manipulation (Art. 5.1a), vulnerability exploitation (Art. 5.1b), social scoring (Art. 5.1c), emotion recognition (Art. 5.1f), and biometric categorization & predictive profiling (Art. 5.1d/g/h). Includes English and French detection.",
+ "guardrails_add": [
+ "eu-ai-act-art5-manipulation",
+ "eu-ai-act-art5-vulnerability",
+ "eu-ai-act-art5-social-scoring",
+ "eu-ai-act-art5-emotion-recognition",
+ "eu-ai-act-art5-biometric-profiling",
+ "eu-ai-act-art5-manipulation-fr",
+ "eu-ai-act-art5-vulnerability-fr",
+ "eu-ai-act-art5-social-scoring-fr",
+ "eu-ai-act-art5-emotion-recognition-fr",
+ "eu-ai-act-art5-biometric-profiling-fr"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Regulatory",
+ "EU"
+ ]
+ },
+ {
+ "id": "mcp-security-unregistered-server-block",
+ "title": "MCP Security: Block Unregistered Servers",
+ "description": "Blocks requests that reference MCP servers not registered on this LiteLLM gateway. Prevents unauthorized tool access via unregistered MCP endpoints.",
+ "icon": "ShieldCheckIcon",
+ "iconColor": "text-red-500",
+ "iconBg": "bg-red-50",
+ "guardrails": [
+ "mcp-security-block"
+ ],
+ "complexity": "Low",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "mcp-security-block",
+ "litellm_params": {
+ "guardrail": "mcp_security",
+ "mode": "pre_call",
+ "default_on": true,
+ "on_violation": "block"
+ },
+ "guardrail_info": {
+ "description": "Blocks requests referencing MCP servers not in the gateway registry"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "mcp-security-unregistered-server-block",
+ "description": "Blocks requests referencing MCP servers not registered on this gateway.",
+ "guardrails_add": [
+ "mcp-security-block"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Security"
+ ]
+ },
+ {
+ "id": "airline-passenger-data-protection-uae",
+ "title": "Airline Passenger Data Protection (UAE)",
+ "description": "Protects airline passenger PII including PNR/booking references, multi-national passport numbers, frequent flyer (Skywards) numbers, payment cards, IBANs, Emirates ID, UAE phone numbers, and email addresses. Designed for UAE-based airlines operating global routes.",
+ "icon": "ShieldCheckIcon",
+ "iconColor": "text-emerald-500",
+ "iconBg": "bg-emerald-50",
+ "guardrails": [
+ "airline-pnr-skywards-pii",
+ "airline-passport-multinational",
+ "airline-payment-financial",
+ "airline-contact-info-uae"
+ ],
+ "complexity": "High",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "airline-pnr-skywards-pii",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "airline_pnr",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "skywards_number",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks airline PNR/booking references and Emirates Skywards frequent flyer numbers"
+ }
+ },
+ {
+ "guardrail_name": "airline-passport-multinational",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_us",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_uk",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_germany",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_france",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_india",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_china",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_australia",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_japan",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_canada",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "passport_netherlands",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "uae_emirates_id",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks passport numbers from 10+ nationalities and UAE Emirates ID -- covers global route network"
+ }
+ },
+ {
+ "guardrail_name": "airline-payment-financial",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "credit_card",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "visa",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "mastercard",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "amex",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "iban",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks credit card numbers (Visa, Mastercard, Amex) and IBANs"
+ }
+ },
+ {
+ "guardrail_name": "airline-contact-info-uae",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "email",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "uae_phone",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "us_phone",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks email addresses and phone numbers (UAE and international formats)"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "airline-passenger-data-protection-uae",
+ "description": "Airline passenger data protection for UAE-based carriers. Masks PNR/booking references, Skywards numbers, multi-national passports, Emirates ID, payment cards, IBANs, and contact information.",
+ "guardrails_add": [
+ "airline-pnr-skywards-pii",
+ "airline-passport-multinational",
+ "airline-payment-financial",
+ "airline-contact-info-uae"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "PII Protection",
+ "Aviation",
+ "UAE"
+ ]
+ },
+ {
+ "id": "aviation-operations-security",
+ "title": "Aviation Operations Security",
+ "description": "Prevents AI from leaking flight operations data (flight numbers, crew schedules, gate assignments, aircraft tail numbers), generating content about aviation security vulnerabilities or bypass procedures, and producing unauthorized airline statements or fake incident reports.",
+ "icon": "ShieldExclamationIcon",
+ "iconColor": "text-red-500",
+ "iconBg": "bg-red-50",
+ "guardrails": [
+ "aviation-ops-data-protection",
+ "aviation-safety-topic-filter",
+ "airline-brand-protection-filter"
+ ],
+ "complexity": "High",
+ "parameters": [
+ {
+ "name": "brand_name",
+ "label": "Your Airline / Brand Name",
+ "type": "text",
+ "required": true,
+ "placeholder": "e.g. Emirates"
+ }
+ ],
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "aviation-ops-data-protection",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "flight_number",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "regex",
+ "name": "aircraft_tail_number",
+ "pattern": "\\bA6-[A-Z]{3}\\b|\\b[A-Z]-[A-Z]{4}\\b|\\bN[0-9]{1,5}[A-Z]{0,2}\\b",
+ "action": "MASK"
+ }
+ ],
+ "blocked_words": [
+ {
+ "keyword": "crew roster",
+ "action": "BLOCK",
+ "description": "Crew scheduling data"
+ },
+ {
+ "keyword": "crew schedule",
+ "action": "BLOCK",
+ "description": "Crew scheduling data"
+ },
+ {
+ "keyword": "duty roster",
+ "action": "BLOCK",
+ "description": "Staff duty data"
+ },
+ {
+ "keyword": "pilot roster",
+ "action": "BLOCK",
+ "description": "Pilot scheduling data"
+ },
+ {
+ "keyword": "cabin crew list",
+ "action": "BLOCK",
+ "description": "Crew manifest data"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "Masks flight numbers and aircraft registrations. Blocks crew scheduling and gate assignment data leakage."
+ }
+ },
+ {
+ "guardrail_name": "aviation-safety-topic-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "aviation_safety_topics",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/aviation_safety_topics.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks content about aircraft vulnerabilities, security bypass procedures, cockpit access, and aviation system exploitation"
+ }
+ },
+ {
+ "guardrail_name": "airline-brand-protection-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "post_call",
+ "categories": [
+ {
+ "category": "airline_brand_protection",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/airline_brand_protection.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ],
+ "blocked_words": [
+ {
+ "keyword": "{{brand_name}} plane crash",
+ "action": "BLOCK",
+ "description": "Fake crash report"
+ },
+ {
+ "keyword": "{{brand_name}} flight crashed",
+ "action": "BLOCK",
+ "description": "Fake crash report"
+ },
+ {
+ "keyword": "{{brand_name}} crash landing",
+ "action": "BLOCK",
+ "description": "Fake incident"
+ },
+ {
+ "keyword": "{{brand_name}} emergency",
+ "action": "BLOCK",
+ "description": "Fake emergency"
+ },
+ {
+ "keyword": "{{brand_name}} passengers dead",
+ "action": "BLOCK",
+ "description": "Fake fatality report"
+ },
+ {
+ "keyword": "{{brand_name}} confirms fatalities",
+ "action": "BLOCK",
+ "description": "Fake fatality confirmation"
+ },
+ {
+ "keyword": "{{brand_name}} safety scandal",
+ "action": "BLOCK",
+ "description": "Fake scandal"
+ },
+ {
+ "keyword": "{{brand_name}} cover up",
+ "action": "BLOCK",
+ "description": "Fake coverup claim"
+ },
+ {
+ "keyword": "{{brand_name}} fleet grounded",
+ "action": "BLOCK",
+ "description": "Fake grounding claim"
+ },
+ {
+ "keyword": "{{brand_name}} discrimination lawsuit",
+ "action": "BLOCK",
+ "description": "Fake lawsuit"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks AI-generated fake incident reports, unauthorized statements, and reputation-damaging content about your brand (runs on output)"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "aviation-operations-security",
+ "description": "Aviation operations security policy. Protects flight ops data, blocks aviation security vulnerability content, and prevents fake airline incident reports and unauthorized statements.",
+ "guardrails_add": [
+ "aviation-ops-data-protection",
+ "aviation-safety-topic-filter",
+ "airline-brand-protection-filter"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Aviation",
+ "Security"
+ ]
+ },
+ {
+ "id": "uae-regulatory-compliance",
+ "title": "UAE Regulatory Compliance",
+ "description": "Compliance with UAE Federal Decree-Law No. 45/2021 (Data Protection) and Federal Decree-Law No. 2/2015 (Anti-Discrimination). Protects Emirates ID numbers, UAE phone numbers, and ensures cultural sensitivity including royal family references and religious content policies.",
+ "icon": "CheckCircleIcon",
+ "iconColor": "text-blue-500",
+ "iconBg": "bg-blue-50",
+ "guardrails": [
+ "uae-data-protection-pii",
+ "uae-cultural-sensitivity-filter",
+ "uae-anti-discrimination-filter"
+ ],
+ "complexity": "Medium",
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "uae-data-protection-pii",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "patterns": [
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "uae_emirates_id",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "uae_phone",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "email",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "iban",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "prebuilt",
+ "pattern_name": "credit_card",
+ "action": "MASK"
+ },
+ {
+ "pattern_type": "regex",
+ "name": "uae_po_box",
+ "pattern": "\\b[Pp]\\.?[Oo]\\.?\\s*[Bb]ox\\s*\\d{1,6}\\b",
+ "action": "MASK"
+ }
+ ],
+ "pattern_redaction_format": "[{pattern_name}_REDACTED]"
+ },
+ "guardrail_info": {
+ "description": "UAE Federal Decree-Law No. 45/2021 compliance -- masks Emirates ID, UAE phone numbers, email, IBAN, payment cards, and PO Box addresses"
+ }
+ },
+ {
+ "guardrail_name": "uae-cultural-sensitivity-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "uae_cultural_sensitivity",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/uae_cultural_sensitivity.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "Blocks content disrespecting UAE royal family, cultural norms, and religious sensitivities"
+ }
+ },
+ {
+ "guardrail_name": "uae-anti-discrimination-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "pre_call",
+ "categories": [
+ {
+ "category": "uae_anti_discrimination",
+ "category_file": "litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/policy_templates/uae_anti_discrimination.yaml",
+ "enabled": true,
+ "action": "BLOCK",
+ "severity_threshold": "medium"
+ }
+ ]
+ },
+ "guardrail_info": {
+ "description": "UAE Federal Decree-Law No. 2/2015 compliance -- blocks discriminatory content based on race, religion, caste, ethnicity, or nationality"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "uae-regulatory-compliance",
+ "description": "UAE regulatory compliance policy. Covers Federal Decree-Law No. 45/2021 (Data Protection) and Federal Decree-Law No. 2/2015 (Anti-Discrimination). Protects Emirates ID, UAE contact info, and ensures cultural and religious sensitivity.",
+ "guardrails_add": [
+ "uae-data-protection-pii",
+ "uae-cultural-sensitivity-filter",
+ "uae-anti-discrimination-filter"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Regulatory",
+ "UAE"
+ ]
+ },
+ {
+ "id": "competitor-mention-detection",
+ "title": "Competitor Mention Detection",
+ "description": "Automatically detects and blocks AI from recommending or promoting competitor brands. Uses LLM-powered discovery to identify your top competitors, then monitors both inputs and outputs for competitor mentions, referrals, and comparisons that could divert business.",
+ "icon": "ShieldExclamationIcon",
+ "iconColor": "text-orange-500",
+ "iconBg": "bg-orange-50",
+ "guardrails": [
+ "competitor-output-blocker",
+ "competitor-recommendation-filter",
+ "competitor-comparison-filter"
+ ],
+ "complexity": "Medium",
+ "parameters": [
+ {
+ "name": "brand_name",
+ "label": "Your Brand Name",
+ "type": "text",
+ "required": true,
+ "placeholder": "e.g. Emirates"
+ }
+ ],
+ "llm_enrichment": {
+ "parameter": "brand_name",
+ "prompt": "List the top 10 direct competitors of {{brand_name}} in the same industry. Return ONLY company/brand names, one per line, no numbering, no explanations.",
+ "result_key": "competitors"
+ },
+ "guardrailDefinitions": [
+ {
+ "guardrail_name": "competitor-output-blocker",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "post_call",
+ "blocked_words": "{{competitors_blocked_words}}"
+ },
+ "guardrail_info": {
+ "description": "Blocks AI outputs that mention or promote competitor brands (auto-discovered via LLM)"
+ }
+ },
+ {
+ "guardrail_name": "competitor-recommendation-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "post_call",
+ "blocked_words": "{{competitor_recommendation_words}}"
+ },
+ "guardrail_info": {
+ "description": "Blocks AI from recommending, suggesting, or directing users to competitor services"
+ }
+ },
+ {
+ "guardrail_name": "competitor-comparison-filter",
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "post_call",
+ "blocked_words": "{{competitor_comparison_words}}"
+ },
+ "guardrail_info": {
+ "description": "Blocks unfavorable comparisons between your brand and competitors in AI outputs"
+ }
+ }
+ ],
+ "templateData": {
+ "policy_name": "competitor-mention-detection",
+ "description": "Detects and blocks competitor mentions in AI outputs. Uses LLM-powered competitor discovery based on your brand name.",
+ "guardrails_add": [
+ "competitor-output-blocker",
+ "competitor-recommendation-filter",
+ "competitor-comparison-filter"
+ ],
+ "guardrails_remove": []
+ },
+ "tags": [
+ "Brand Protection"
+ ]
+ }
+]
\ No newline at end of file
diff --git a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
index 081d83dd1c8..75b75d3ba44 100644
--- a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
+++ b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
@@ -27,6 +27,7 @@ class MCPAuthenticatedUser(AuthenticatedUser):
oauth2_headers: Optional[Dict[str, str]] = None,
mcp_protocol_version: Optional[str] = None,
raw_headers: Optional[Dict[str, str]] = None,
+ client_ip: Optional[str] = None,
):
self.user_api_key_auth = user_api_key_auth
self.mcp_auth_header = mcp_auth_header
@@ -35,3 +36,4 @@ class MCPAuthenticatedUser(AuthenticatedUser):
self.mcp_protocol_version = mcp_protocol_version
self.oauth2_headers = oauth2_headers
self.raw_headers = raw_headers
+ self.client_ip = client_ip
diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
index 49d6ac7d898..ed4fb133478 100644
--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
@@ -1,11 +1,17 @@
from typing import Dict, List, Optional, Set, Tuple
+from fastapi import HTTPException
from starlette.datastructures import Headers
from starlette.requests import Request
from starlette.types import Scope
from litellm._logging import verbose_logger
-from litellm.proxy._types import LiteLLM_TeamTable, SpecialHeaders, UserAPIKeyAuth
+from litellm.proxy._types import (
+ LiteLLM_TeamTable,
+ ProxyException,
+ SpecialHeaders,
+ UserAPIKeyAuth,
+)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
@@ -63,6 +69,13 @@ class MCPRequestHandler:
HTTPException: If headers are invalid or missing required headers
"""
headers = MCPRequestHandler._safe_get_headers_from_scope(scope)
+
+ # Check if there is an explicit LiteLLM API key (primary header)
+ has_explicit_litellm_key = (
+ headers.get(MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_PRIMARY)
+ is not None
+ )
+
litellm_api_key = (
MCPRequestHandler.get_litellm_api_key_from_headers(headers) or ""
)
@@ -106,16 +119,38 @@ class MCPRequestHandler:
request.body = mock_body # type: ignore
if ".well-known" in str(request.url): # public routes
validated_user_api_key_auth = UserAPIKeyAuth()
- # elif litellm_api_key == "":
- # from fastapi import HTTPException
-
- # raise HTTPException(
- # status_code=401,
- # detail="LiteLLM API key is missing. Please add it or use OAuth authentication.",
- # headers={
- # "WWW-Authenticate": f'Bearer resource_metadata=f"{request.base_url}/.well-known/oauth-protected-resource"',
- # },
- # )
+ elif has_explicit_litellm_key:
+ # Explicit x-litellm-api-key provided - always validate normally
+ validated_user_api_key_auth = await user_api_key_auth(
+ api_key=litellm_api_key, request=request
+ )
+ elif oauth2_headers:
+ # No x-litellm-api-key, but Authorization header present.
+ # Could be a LiteLLM key (backward compat) OR an OAuth2 token
+ # from an upstream MCP provider (e.g. Atlassian).
+ # Try LiteLLM auth first; on auth failure, treat as OAuth2 passthrough.
+ try:
+ validated_user_api_key_auth = await user_api_key_auth(
+ api_key=litellm_api_key, request=request
+ )
+ except HTTPException as e:
+ if e.status_code in (401, 403):
+ verbose_logger.debug(
+ "MCP OAuth2: Authorization header is not a valid LiteLLM key, "
+ "treating as OAuth2 token passthrough"
+ )
+ validated_user_api_key_auth = UserAPIKeyAuth()
+ else:
+ raise
+ except ProxyException as e:
+ if str(e.code) in ("401", "403"):
+ verbose_logger.debug(
+ "MCP OAuth2: Authorization header is not a valid LiteLLM key, "
+ "treating as OAuth2 token passthrough"
+ )
+ validated_user_api_key_auth = UserAPIKeyAuth()
+ else:
+ raise
else:
validated_user_api_key_auth = await user_api_key_auth(
api_key=litellm_api_key, request=request
@@ -342,55 +377,44 @@ class MCPRequestHandler:
return []
@staticmethod
- async def _get_key_object_permission(
+ def _get_key_object_permission(
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
):
- """Helper to get key object_permission from cache or DB."""
- from litellm.proxy.auth.auth_checks import get_object_permission
- from litellm.proxy.proxy_server import (
- prisma_client,
- proxy_logging_obj,
- user_api_key_cache,
- )
+ """
+ Get key object_permission - already loaded by get_key_object() in main auth flow.
+ Note: object_permission is automatically populated when the key is fetched via
+ get_key_object() in litellm/proxy/auth/auth_checks.py
+ """
if not user_api_key_auth:
return None
- # Already loaded
- if user_api_key_auth.object_permission:
- return user_api_key_auth.object_permission
-
- # Need to fetch from DB
- if user_api_key_auth.object_permission_id and prisma_client:
- return await get_object_permission(
- object_permission_id=user_api_key_auth.object_permission_id,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- parent_otel_span=user_api_key_auth.parent_otel_span,
- proxy_logging_obj=proxy_logging_obj,
- )
-
- return None
+ return user_api_key_auth.object_permission
@staticmethod
async def _get_team_object_permission(
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
):
- """Helper to get team object_permission from cache or DB."""
- from litellm.proxy.auth.auth_checks import (
- get_object_permission,
- get_team_object,
- )
+ """
+ Get team object_permission - automatically loaded by get_team_object() in main auth flow.
+
+ Note: object_permission is automatically populated when the team is fetched via
+ get_team_object() in litellm/proxy/auth/auth_checks.py
+ """
+ from litellm.proxy.auth.auth_checks import get_team_object
from litellm.proxy.proxy_server import (
prisma_client,
proxy_logging_obj,
user_api_key_cache,
)
+ verbose_logger.debug(
+ f"MCP team permission lookup: team_id={user_api_key_auth.team_id if user_api_key_auth else None}"
+ )
if not user_api_key_auth or not user_api_key_auth.team_id or not prisma_client:
return None
- # First get the team object (which may have object_permission already loaded)
+ # Get the team object (which has object_permission already loaded)
team_obj: Optional[LiteLLM_TeamTable] = await get_team_object(
team_id=user_api_key_auth.team_id,
prisma_client=prisma_client,
@@ -402,21 +426,7 @@ class MCPRequestHandler:
if not team_obj:
return None
- # Already loaded
- if team_obj.object_permission:
- return team_obj.object_permission
-
- # Need to fetch from DB using object_permission_id
- if team_obj.object_permission_id:
- return await get_object_permission(
- object_permission_id=team_obj.object_permission_id,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- parent_otel_span=user_api_key_auth.parent_otel_span,
- proxy_logging_obj=proxy_logging_obj,
- )
-
- return None
+ return team_obj.object_permission
@staticmethod
async def get_allowed_tools_for_server(
@@ -438,8 +448,8 @@ class MCPRequestHandler:
return None
try:
- # Get key and team object permissions
- key_obj_perm = await MCPRequestHandler._get_key_object_permission(
+ # Get key and team object permissions (already loaded in main auth flow)
+ key_obj_perm = MCPRequestHandler._get_key_object_permission(
user_api_key_auth
)
team_obj_perm = await MCPRequestHandler._get_team_object_permission(
@@ -526,9 +536,25 @@ class MCPRequestHandler:
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
) -> List[str]:
try:
- key_object_permission = await MCPRequestHandler._get_key_object_permission(
+ # Get key object permission (already loaded in main auth flow, or fetch from DB)
+ key_object_permission = MCPRequestHandler._get_key_object_permission(
user_api_key_auth
)
+ if key_object_permission is None and user_api_key_auth and user_api_key_auth.object_permission_id:
+ from litellm.proxy.auth.auth_checks import get_object_permission
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
+ )
+ if prisma_client is not None:
+ key_object_permission = await get_object_permission(
+ object_permission_id=user_api_key_auth.object_permission_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=user_api_key_auth.parent_otel_span,
+ proxy_logging_obj=proxy_logging_obj,
+ )
if key_object_permission is None:
return []
@@ -558,12 +584,10 @@ class MCPRequestHandler:
"""
Get allowed MCP servers for a team.
- Uses the helper _get_team_object_permission which:
- 1. First checks if object_permission is already loaded on the team
- 2. If not, fetches from DB using object_permission_id if it exists
+ Note: object_permission is automatically loaded by get_team_object() in main auth flow.
"""
try:
- # Use the helper method that properly handles fetching from DB if needed
+ # Get team object permission (already loaded in main auth flow)
object_permissions = await MCPRequestHandler._get_team_object_permission(
user_api_key_auth
)
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
index ded591a8f53..b731bc7bc2f 100644
--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
@@ -1,6 +1,6 @@
import json
from typing import Optional
-from urllib.parse import urlencode, urlparse, urlunparse
+from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
from fastapi import APIRouter, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
@@ -9,13 +9,15 @@ from litellm.llms.custom_httpx.http_handler import (
get_async_httpx_client,
httpxSpecialProvider,
)
+from litellm.proxy.auth.ip_address_utils import IPAddressUtils
from litellm.proxy.common_utils.encrypt_decrypt_utils import (
decrypt_value_helper,
encrypt_value_helper,
)
from litellm.proxy.common_utils.http_parsing_utils import _read_request_body
-from litellm.types.mcp_server.mcp_server_manager import MCPServer
from litellm.proxy.utils import get_server_root_path
+from litellm.types.mcp import MCPAuth
+from litellm.types.mcp_server.mcp_server_manager import MCPServer
router = APIRouter(
tags=["mcp"],
@@ -124,6 +126,29 @@ def decode_state_hash(encrypted_state: str) -> dict:
return state_data
+def _resolve_oauth2_server_for_root_endpoints(
+ client_ip: Optional[str] = None,
+) -> Optional[MCPServer]:
+ """
+ Resolve the MCP server for root-level OAuth endpoints (no server name in path).
+
+ When the MCP SDK hits root-level endpoints like /register, /authorize, /token
+ without a server name prefix, we try to find the right server automatically.
+ Returns the server if exactly one OAuth2 server is configured, else None.
+ """
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
+ global_mcp_server_manager,
+ )
+
+ registry = global_mcp_server_manager.get_filtered_registry(client_ip=client_ip)
+ oauth2_servers = [
+ s for s in registry.values() if s.auth_type == MCPAuth.oauth2
+ ]
+ if len(oauth2_servers) == 1:
+ return oauth2_servers[0]
+ return None
+
+
async def authorize_with_server(
request: Request,
mcp_server: MCPServer,
@@ -169,7 +194,13 @@ async def authorize_with_server(
if code_challenge_method:
params["code_challenge_method"] = code_challenge_method
- return RedirectResponse(f"{mcp_server.authorization_url}?{urlencode(params)}")
+ parsed_auth_url = urlparse(mcp_server.authorization_url)
+ existing_params = dict(parse_qsl(parsed_auth_url.query))
+ existing_params.update(params)
+ final_url = urlunparse(
+ parsed_auth_url._replace(query=urlencode(existing_params))
+ )
+ return RedirectResponse(final_url)
async def exchange_token_with_server(
@@ -300,7 +331,12 @@ async def authorize(
)
lookup_name = mcp_server_name or client_id
- mcp_server = global_mcp_server_manager.get_mcp_server_by_name(lookup_name)
+ client_ip = IPAddressUtils.get_mcp_client_ip(request)
+ mcp_server = global_mcp_server_manager.get_mcp_server_by_name(
+ lookup_name, client_ip=client_ip
+ )
+ if mcp_server is None and mcp_server_name is None:
+ mcp_server = _resolve_oauth2_server_for_root_endpoints()
if mcp_server is None:
raise HTTPException(status_code=404, detail="MCP server not found")
return await authorize_with_server(
@@ -342,7 +378,12 @@ async def token_endpoint(
)
lookup_name = mcp_server_name or client_id
- mcp_server = global_mcp_server_manager.get_mcp_server_by_name(lookup_name)
+ client_ip = IPAddressUtils.get_mcp_client_ip(request)
+ mcp_server = global_mcp_server_manager.get_mcp_server_by_name(
+ lookup_name, client_ip=client_ip
+ )
+ if mcp_server is None and mcp_server_name is None:
+ mcp_server = _resolve_oauth2_server_for_root_endpoints()
if mcp_server is None:
raise HTTPException(status_code=404, detail="MCP server not found")
return await exchange_token_with_server(
@@ -387,25 +428,67 @@ async def callback(code: str, state: str):
1. Try resource_metadata from WWW-Authenticate header (if present)
2. Fall back to path-based well-known URI: /.well-known/oauth-protected-resource/{path}
(
- If the resource identifier value contains a path or query component, any terminating slash (/)
- following the host component MUST be removed before inserting /.well-known/ and the well-known
- URI path suffix between the host component and the path(include root path) and/or query components.
+ If the resource identifier value contains a path or query component, any terminating slash (/)
+ following the host component MUST be removed before inserting /.well-known/ and the well-known
+ URI path suffix between the host component and the path(include root path) and/or query components.
https://datatracker.ietf.org/doc/html/rfc9728#section-3.1)
3. Fall back to root-based well-known URI: /.well-known/oauth-protected-resource
+
+ Dual Pattern Support:
+ - Standard MCP pattern: /mcp/{server_name} (recommended, used by mcp-inspector, VSCode Copilot)
+ - LiteLLM legacy pattern: /{server_name}/mcp (backward compatibility)
+
+ The resource URL returned matches the pattern used in the discovery request.
"""
-@router.get(f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}/mcp")
-@router.get("/.well-known/oauth-protected-resource")
-async def oauth_protected_resource_mcp(
- request: Request, mcp_server_name: Optional[str] = None
-):
+
+
+def _build_oauth_protected_resource_response(
+ request: Request,
+ mcp_server_name: Optional[str],
+ use_standard_pattern: bool,
+) -> dict:
+ """
+ Build OAuth protected resource response with the appropriate URL pattern.
+
+ Args:
+ request: FastAPI Request object
+ mcp_server_name: Name of the MCP server
+ use_standard_pattern: If True, use /mcp/{server_name} pattern;
+ if False, use /{server_name}/mcp pattern
+
+ Returns:
+ OAuth protected resource metadata dict
+ """
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)
- # Get the correct base URL considering X-Forwarded-* headers
+
request_base_url = get_request_base_url(request)
+
+ # When no server name provided, try to resolve the single OAuth2 server
+ if mcp_server_name is None:
+ resolved = _resolve_oauth2_server_for_root_endpoints()
+ if resolved:
+ mcp_server_name = resolved.server_name or resolved.name
+
mcp_server: Optional[MCPServer] = None
if mcp_server_name:
- mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name)
+ client_ip = IPAddressUtils.get_mcp_client_ip(request)
+ mcp_server = global_mcp_server_manager.get_mcp_server_by_name(
+ mcp_server_name, client_ip=client_ip
+ )
+
+ # Build resource URL based on the pattern
+ if mcp_server_name:
+ if use_standard_pattern:
+ # Standard MCP pattern: /mcp/{server_name}
+ resource_url = f"{request_base_url}/mcp/{mcp_server_name}"
+ else:
+ # LiteLLM legacy pattern: /{server_name}/mcp
+ resource_url = f"{request_base_url}/{mcp_server_name}/mcp"
+ else:
+ resource_url = f"{request_base_url}/mcp"
+
return {
"authorization_servers": [
(
@@ -414,14 +497,55 @@ async def oauth_protected_resource_mcp(
else f"{request_base_url}"
)
],
- "resource": (
- f"{request_base_url}/{mcp_server_name}/mcp"
- if mcp_server_name
- else f"{request_base_url}/mcp"
- ), # this is what Claude will call
- "scopes_supported": mcp_server.scopes if mcp_server else [],
+ "resource": resource_url,
+ "scopes_supported": mcp_server.scopes if mcp_server and mcp_server.scopes else [],
}
+
+# Standard MCP pattern: /.well-known/oauth-protected-resource/mcp/{server_name}
+# This is the pattern expected by standard MCP clients (mcp-inspector, VSCode Copilot)
+@router.get(f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/mcp/{{mcp_server_name}}")
+async def oauth_protected_resource_mcp_standard(
+ request: Request, mcp_server_name: str
+):
+ """
+ OAuth protected resource discovery endpoint using standard MCP URL pattern.
+
+ Standard pattern: /mcp/{server_name}
+ Discovery path: /.well-known/oauth-protected-resource/mcp/{server_name}
+
+ This endpoint is compliant with MCP specification and works with standard
+ MCP clients like mcp-inspector and VSCode Copilot.
+ """
+ return _build_oauth_protected_resource_response(
+ request=request,
+ mcp_server_name=mcp_server_name,
+ use_standard_pattern=True,
+ )
+
+
+# LiteLLM legacy pattern: /.well-known/oauth-protected-resource/{server_name}/mcp
+# Kept for backward compatibility with existing deployments
+@router.get(f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}/mcp")
+@router.get("/.well-known/oauth-protected-resource")
+async def oauth_protected_resource_mcp(
+ request: Request, mcp_server_name: Optional[str] = None
+):
+ """
+ OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern.
+
+ Legacy pattern: /{server_name}/mcp
+ Discovery path: /.well-known/oauth-protected-resource/{server_name}/mcp
+
+ This endpoint is kept for backward compatibility. New integrations should
+ use the standard MCP pattern (/mcp/{server_name}) instead.
+ """
+ return _build_oauth_protected_resource_response(
+ request=request,
+ mcp_server_name=mcp_server_name,
+ use_standard_pattern=False,
+ )
+
"""
https://datatracker.ietf.org/doc/html/rfc8414#section-3.1
RFC 8414: Path-aware OAuth discovery
@@ -430,17 +554,34 @@ async def oauth_protected_resource_mcp(
the well-known URI suffix between the host component and the path(include root path)
component.
"""
-@router.get(f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}")
-@router.get("/.well-known/oauth-authorization-server")
-async def oauth_authorization_server_mcp(
- request: Request, mcp_server_name: Optional[str] = None
-):
+
+
+def _build_oauth_authorization_server_response(
+ request: Request,
+ mcp_server_name: Optional[str],
+) -> dict:
+ """
+ Build OAuth authorization server metadata response.
+
+ Args:
+ request: FastAPI Request object
+ mcp_server_name: Name of the MCP server
+
+ Returns:
+ OAuth authorization server metadata dict
+ """
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)
- # Get the correct base URL considering X-Forwarded-* headers
+
request_base_url = get_request_base_url(request)
+ # When no server name provided, try to resolve the single OAuth2 server
+ if mcp_server_name is None:
+ resolved = _resolve_oauth2_server_for_root_endpoints()
+ if resolved:
+ mcp_server_name = resolved.server_name or resolved.name
+
authorization_endpoint = (
f"{request_base_url}/{mcp_server_name}/authorize"
if mcp_server_name
@@ -454,14 +595,17 @@ async def oauth_authorization_server_mcp(
mcp_server: Optional[MCPServer] = None
if mcp_server_name:
- mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name)
+ client_ip = IPAddressUtils.get_mcp_client_ip(request)
+ mcp_server = global_mcp_server_manager.get_mcp_server_by_name(
+ mcp_server_name, client_ip=client_ip
+ )
return {
"issuer": request_base_url, # point to your proxy
"authorization_endpoint": authorization_endpoint,
"token_endpoint": token_endpoint,
"response_types_supported": ["code"],
- "scopes_supported": mcp_server.scopes if mcp_server else [],
+ "scopes_supported": mcp_server.scopes if mcp_server and mcp_server.scopes else [],
"grant_types_supported": ["authorization_code", "refresh_token"],
"code_challenge_methods_supported": ["S256"],
"token_endpoint_auth_methods_supported": ["client_secret_post"],
@@ -470,18 +614,58 @@ async def oauth_authorization_server_mcp(
}
+# Standard MCP pattern: /.well-known/oauth-authorization-server/mcp/{server_name}
+@router.get(f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/mcp/{{mcp_server_name}}")
+async def oauth_authorization_server_mcp_standard(
+ request: Request, mcp_server_name: str
+):
+ """
+ OAuth authorization server discovery endpoint using standard MCP URL pattern.
+
+ Standard pattern: /mcp/{server_name}
+ Discovery path: /.well-known/oauth-authorization-server/mcp/{server_name}
+ """
+ return _build_oauth_authorization_server_response(
+ request=request,
+ mcp_server_name=mcp_server_name,
+ )
+
+
+# LiteLLM legacy pattern and root endpoint
+@router.get(f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}")
+@router.get("/.well-known/oauth-authorization-server")
+async def oauth_authorization_server_mcp(
+ request: Request, mcp_server_name: Optional[str] = None
+):
+ """
+ OAuth authorization server discovery endpoint.
+
+ Supports both legacy pattern (/{server_name}) and root endpoint.
+ """
+ return _build_oauth_authorization_server_response(
+ request=request,
+ mcp_server_name=mcp_server_name,
+ )
+
+
# Alias for standard OpenID discovery
@router.get("/.well-known/openid-configuration")
async def openid_configuration(request: Request):
return await oauth_authorization_server_mcp(request)
+# Additional legacy pattern support
@router.get("/.well-known/oauth-authorization-server/{mcp_server_name}/mcp")
-@router.get("/.well-known/oauth-authorization-server")
-async def oauth_authorization_server_root(
- request: Request, mcp_server_name: Optional[str] = None
+async def oauth_authorization_server_legacy(
+ request: Request, mcp_server_name: str
):
- return await oauth_authorization_server_mcp(request, mcp_server_name)
+ """
+ OAuth authorization server discovery for legacy /{server_name}/mcp pattern.
+ """
+ return _build_oauth_authorization_server_response(
+ request=request,
+ mcp_server_name=mcp_server_name,
+ )
@router.post("/{mcp_server_name}/register")
@@ -503,9 +687,25 @@ async def register_client(request: Request, mcp_server_name: Optional[str] = Non
"redirect_uris": [f"{request_base_url}/callback"],
}
if not mcp_server_name:
+ resolved = _resolve_oauth2_server_for_root_endpoints()
+ if resolved:
+ return await register_client_with_server(
+ request=request,
+ mcp_server=resolved,
+ client_name=data.get("client_name", ""),
+ grant_types=data.get("grant_types", []),
+ response_types=data.get("response_types", []),
+ token_endpoint_auth_method=data.get(
+ "token_endpoint_auth_method", ""
+ ),
+ fallback_client_id=resolved.server_name or resolved.name,
+ )
return dummy_return
- mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name)
+ client_ip = IPAddressUtils.get_mcp_client_ip(request)
+ mcp_server = global_mcp_server_manager.get_mcp_server_by_name(
+ mcp_server_name, client_ip=client_ip
+ )
if mcp_server is None:
return dummy_return
return await register_client_with_server(
diff --git a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py
index 8d6d236b884..14bbb82808d 100644
--- a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py
+++ b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py
@@ -1,26 +1,37 @@
"""
MCP Guardrail Handler for Unified Guardrails.
-This handler works with the synthetic "messages" payload generated by
-`ProxyLogging._convert_mcp_to_llm_format`, which always produces a single user
-message whose `content` string encodes the MCP tool name and arguments. The
-handler simply feeds that text through the configured guardrail and writes the
-result back onto the message.
+Converts an MCP call_tool (name + arguments) into a single OpenAI-compatible
+tool_call and passes it to apply_guardrail. Works with the synthetic payload
+from ProxyLogging._convert_mcp_to_llm_format.
+
+Note: For MCP tool definitions (schema) -> OpenAI tools=[], see
+litellm.experimental_mcp_client.tools.transform_mcp_tool_to_openai_tool
+when you have a full MCP Tool from list_tools. Here we only have the call
+payload (name + arguments) so we just build the tool_call.
"""
from typing import TYPE_CHECKING, Any, Dict, Optional
+from mcp.types import Tool as MCPTool
+
from litellm._logging import verbose_proxy_logger
+from litellm.experimental_mcp_client.tools import transform_mcp_tool_to_openai_tool
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.types.llms.openai import (
+ ChatCompletionToolParam,
+ ChatCompletionToolParamFunctionChunk,
+)
from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
- from litellm.integrations.custom_guardrail import CustomGuardrail
from mcp.types import CallToolResult
+ from litellm.integrations.custom_guardrail import CustomGuardrail
+
class MCPGuardrailTranslationHandler(BaseTranslation):
- """Guardrail translation handler for MCP tool calls."""
+ """Guardrail translation handler for MCP tool calls (passes a single tool_call to guardrail)."""
async def process_input_messages(
self,
@@ -28,51 +39,51 @@ class MCPGuardrailTranslationHandler(BaseTranslation):
guardrail_to_apply: "CustomGuardrail",
litellm_logging_obj: Optional[Any] = None,
) -> Dict[str, Any]:
- messages = data.get("messages")
- if not isinstance(messages, list) or not messages:
- verbose_proxy_logger.debug("MCP Guardrail: No messages to process")
+ mcp_tool_name = data.get("mcp_tool_name") or data.get("name")
+ mcp_arguments = data.get("mcp_arguments") or data.get("arguments")
+ mcp_tool_description = data.get("mcp_tool_description") or data.get(
+ "description"
+ )
+ if mcp_arguments is None or not isinstance(mcp_arguments, dict):
+ mcp_arguments = {}
+
+ if not mcp_tool_name:
+ verbose_proxy_logger.debug("MCP Guardrail: mcp_tool_name missing")
return data
- first_message = messages[0]
- content: Optional[str] = None
- if isinstance(first_message, dict):
- content = first_message.get("content")
- else:
- content = getattr(first_message, "content", None)
+ # Convert MCP input via transform_mcp_tool_to_openai_tool, then map to litellm
+ # ChatCompletionToolParam (openai SDK type has incompatible strict/cache_control).
+ mcp_tool = MCPTool(
+ name=mcp_tool_name,
+ description=mcp_tool_description or "",
+ inputSchema={}, # Call payload has no schema; guardrail gets args from request_data
+ )
+ openai_tool = transform_mcp_tool_to_openai_tool(mcp_tool)
+ fn = openai_tool["function"]
+ tool_def: ChatCompletionToolParam = {
+ "type": "function",
+ "function": ChatCompletionToolParamFunctionChunk(
+ name=fn["name"],
+ description=fn.get("description") or "",
+ parameters=fn.get("parameters")
+ or {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": False,
+ },
+ strict=fn.get("strict", False) or False, # Default to False if None
+ ),
+ }
+ inputs: GenericGuardrailAPIInputs = GenericGuardrailAPIInputs(
+ tools=[tool_def],
+ )
- if not isinstance(content, str):
- verbose_proxy_logger.debug(
- "MCP Guardrail: Message content missing or not a string",
- )
- return data
-
- guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs=GenericGuardrailAPIInputs(texts=[content]),
+ await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
request_data=data,
input_type="request",
logging_obj=litellm_logging_obj,
)
- guardrailed_texts = (
- guardrailed_inputs.get("texts", []) if guardrailed_inputs else []
- )
-
- if guardrailed_texts:
- new_content = guardrailed_texts[0]
- if isinstance(first_message, dict):
- first_message["content"] = new_content
- else:
- setattr(first_message, "content", new_content)
-
- verbose_proxy_logger.debug(
- "MCP Guardrail: Updated content for tool %s",
- data.get("mcp_tool_name"),
- )
- else:
- verbose_proxy_logger.debug(
- "MCP Guardrail: Guardrail returned no text updates for tool %s",
- data.get("mcp_tool_name"),
- )
-
return data
async def process_output_response(
@@ -82,7 +93,6 @@ class MCPGuardrailTranslationHandler(BaseTranslation):
litellm_logging_obj: Optional[Any] = None,
user_api_key_dict: Optional[Any] = None,
) -> Any:
- # Not implemented: MCP guardrail translation never calls this path today.
verbose_proxy_logger.debug(
"MCP Guardrail: Output processing not implemented for MCP tools",
)
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_debug.py b/litellm/proxy/_experimental/mcp_server/mcp_debug.py
new file mode 100644
index 00000000000..46741a9df98
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/mcp_debug.py
@@ -0,0 +1,329 @@
+"""
+MCP OAuth2 Debug Headers
+========================
+
+Client-side debugging for MCP authentication flows.
+
+When a client sends the ``x-litellm-mcp-debug: true`` header, LiteLLM
+returns masked diagnostic headers in the response so operators can
+troubleshoot OAuth2 issues without SSH access to the gateway.
+
+Response headers returned (all values are masked for safety):
+
+ x-mcp-debug-inbound-auth
+ Which inbound auth headers were present and how they were classified.
+ Example: ``x-litellm-api-key=Bearer sk-12****1234``
+
+ x-mcp-debug-oauth2-token
+ The OAuth2 token extracted from the Authorization header (masked).
+ Shows ``(none)`` if absent, or flags ``SAME_AS_LITELLM_KEY`` when
+ the LiteLLM API key is accidentally leaking to the MCP server.
+
+ x-mcp-debug-auth-resolution
+ Which auth priority was used for the outbound MCP call:
+ ``per-request-header``, ``m2m-client-credentials``, ``static-token``,
+ ``oauth2-passthrough``, or ``no-auth``.
+
+ x-mcp-debug-outbound-url
+ The upstream MCP server URL that will receive the request.
+
+ x-mcp-debug-server-auth-type
+ The ``auth_type`` configured on the MCP server (e.g. ``oauth2``,
+ ``bearer_token``, ``none``).
+
+Debugging Guide
+---------------
+
+**Common issue: LiteLLM API key leaking to the MCP server**
+
+Symptom: ``x-mcp-debug-oauth2-token`` shows ``SAME_AS_LITELLM_KEY``.
+
+This means the ``Authorization`` header carries the LiteLLM API key and
+it's being forwarded to the upstream MCP server instead of an OAuth2 token.
+
+Fix: Move the LiteLLM key to ``x-litellm-api-key`` so the ``Authorization``
+header is free for OAuth2 discovery::
+
+ # WRONG — blocks OAuth2 discovery
+ claude mcp add --transport http my_server http://proxy/mcp/server \\
+ --header "Authorization: Bearer sk-..."
+
+ # CORRECT — LiteLLM key in dedicated header, Authorization free for OAuth2
+ claude mcp add --transport http my_server http://proxy/mcp/server \\
+ --header "x-litellm-api-key: Bearer sk-..." \\
+ --header "x-litellm-mcp-debug: true"
+
+**Common issue: No OAuth2 token present**
+
+Symptom: ``x-mcp-debug-oauth2-token`` shows ``(none)`` and
+``x-mcp-debug-auth-resolution`` shows ``no-auth``.
+
+This means the client didn't go through the OAuth2 flow. Check that:
+1. The ``Authorization`` header is NOT set as a static header in the client config.
+2. The ``.well-known/oauth-protected-resource`` endpoint returns valid metadata.
+3. The MCP server in LiteLLM config has ``auth_type: oauth2``.
+
+**Common issue: M2M token used instead of user token**
+
+Symptom: ``x-mcp-debug-auth-resolution`` shows ``m2m-client-credentials``.
+
+This means the server has ``client_id``/``client_secret``/``token_url``
+configured and LiteLLM is fetching a machine-to-machine token instead of
+using the per-user OAuth2 token. If you want per-user tokens, remove the
+client credentials from the server config.
+
+Usage from Claude Code::
+
+ claude mcp add --transport http my_server http://proxy/mcp/server \\
+ --header "x-litellm-api-key: Bearer sk-..." \\
+ --header "x-litellm-mcp-debug: true"
+
+Usage with curl::
+
+ curl -H "x-litellm-mcp-debug: true" \\
+ -H "x-litellm-api-key: Bearer sk-..." \\
+ http://localhost:4000/mcp/atlassian_mcp
+"""
+
+from typing import TYPE_CHECKING, Dict, List, Optional
+
+from starlette.types import Message, Send
+
+from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker
+
+if TYPE_CHECKING:
+ from litellm.types.mcp_server.mcp_server_manager import MCPServer
+
+# Header the client sends to opt into debug mode
+MCP_DEBUG_REQUEST_HEADER = "x-litellm-mcp-debug"
+
+# Prefix for all debug response headers
+_RESPONSE_HEADER_PREFIX = "x-mcp-debug"
+
+
+class MCPDebug:
+ """
+ Static helper class for MCP OAuth2 debug headers.
+
+ Provides opt-in client-side diagnostics by injecting masked
+ authentication info into HTTP response headers.
+ """
+
+ # Masker: show first 6 and last 4 chars so you can distinguish token types
+ # e.g. "Bearer****ef01" vs "sk-123****cdef"
+ _masker = SensitiveDataMasker(
+ sensitive_patterns={
+ "authorization",
+ "token",
+ "key",
+ "secret",
+ "auth",
+ "bearer",
+ },
+ visible_prefix=6,
+ visible_suffix=4,
+ )
+
+ @staticmethod
+ def _mask(value: Optional[str]) -> str:
+ """Mask a single value for safe display in headers."""
+ if not value:
+ return "(none)"
+ return MCPDebug._masker._mask_value(value)
+
+ @staticmethod
+ def is_debug_enabled(headers: Dict[str, str]) -> bool:
+ """
+ Check if the client opted into MCP debug mode.
+
+ Looks for ``x-litellm-mcp-debug: true`` (case-insensitive) in the
+ request headers.
+ """
+ for key, val in headers.items():
+ if key.lower() == MCP_DEBUG_REQUEST_HEADER:
+ return val.strip().lower() in ("true", "1", "yes")
+ return False
+
+ @staticmethod
+ def resolve_auth_resolution(
+ server: "MCPServer",
+ mcp_auth_header: Optional[str],
+ mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]],
+ oauth2_headers: Optional[Dict[str, str]],
+ ) -> str:
+ """
+ Determine which auth priority will be used for the outbound MCP call.
+
+ Returns one of: ``per-request-header``, ``m2m-client-credentials``,
+ ``static-token``, ``oauth2-passthrough``, or ``no-auth``.
+ """
+ from litellm.types.mcp import MCPAuth
+
+ has_server_specific = bool(
+ mcp_server_auth_headers
+ and (
+ mcp_server_auth_headers.get(server.alias or "")
+ or mcp_server_auth_headers.get(server.server_name or "")
+ )
+ )
+ if has_server_specific or mcp_auth_header:
+ return "per-request-header"
+ if server.has_client_credentials:
+ return "m2m-client-credentials"
+ if server.authentication_token:
+ return "static-token"
+ if oauth2_headers and server.auth_type == MCPAuth.oauth2:
+ return "oauth2-passthrough"
+ return "no-auth"
+
+ @staticmethod
+ def build_debug_headers(
+ *,
+ inbound_headers: Dict[str, str],
+ oauth2_headers: Optional[Dict[str, str]],
+ litellm_api_key: Optional[str],
+ auth_resolution: str,
+ server_url: Optional[str],
+ server_auth_type: Optional[str],
+ ) -> Dict[str, str]:
+ """
+ Build masked debug response headers.
+
+ Parameters
+ ----------
+ inbound_headers : dict
+ Raw headers received from the MCP client.
+ oauth2_headers : dict or None
+ Extracted OAuth2 headers (``{"Authorization": "Bearer ..."}``).
+ litellm_api_key : str or None
+ The LiteLLM API key extracted from ``x-litellm-api-key`` or
+ ``Authorization`` header.
+ auth_resolution : str
+ Which auth priority was selected for the outbound call.
+ server_url : str or None
+ Upstream MCP server URL.
+ server_auth_type : str or None
+ The ``auth_type`` configured on the server (e.g. ``oauth2``).
+
+ Returns
+ -------
+ dict
+ Headers to include in the response (all values masked).
+ """
+ debug: Dict[str, str] = {}
+
+ # --- Inbound auth summary ---
+ inbound_parts = []
+ for hdr_name in ("x-litellm-api-key", "authorization", "x-mcp-auth"):
+ for k, v in inbound_headers.items():
+ if k.lower() == hdr_name:
+ inbound_parts.append(f"{hdr_name}={MCPDebug._mask(v)}")
+ break
+ debug[f"{_RESPONSE_HEADER_PREFIX}-inbound-auth"] = (
+ "; ".join(inbound_parts) if inbound_parts else "(none)"
+ )
+
+ # --- OAuth2 token ---
+ oauth2_token = (oauth2_headers or {}).get("Authorization")
+ if oauth2_token and litellm_api_key:
+ oauth2_raw = oauth2_token.removeprefix("Bearer ").strip()
+ litellm_raw = litellm_api_key.removeprefix("Bearer ").strip()
+ if oauth2_raw == litellm_raw:
+ debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = (
+ f"{MCPDebug._mask(oauth2_token)} "
+ f"(SAME_AS_LITELLM_KEY - likely misconfigured)"
+ )
+ else:
+ debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask(
+ oauth2_token
+ )
+ else:
+ debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask(
+ oauth2_token
+ )
+
+ # --- Auth resolution ---
+ debug[f"{_RESPONSE_HEADER_PREFIX}-auth-resolution"] = auth_resolution
+
+ # --- Server info ---
+ debug[f"{_RESPONSE_HEADER_PREFIX}-outbound-url"] = server_url or "(unknown)"
+ debug[f"{_RESPONSE_HEADER_PREFIX}-server-auth-type"] = (
+ server_auth_type or "(none)"
+ )
+
+ return debug
+
+ @staticmethod
+ def wrap_send_with_debug_headers(
+ send: Send, debug_headers: Dict[str, str]
+ ) -> Send:
+ """
+ Return a new ASGI ``send`` callable that injects *debug_headers*
+ into the ``http.response.start`` message.
+ """
+
+ async def _send_with_debug(message: Message) -> None:
+ if message["type"] == "http.response.start":
+ headers = list(message.get("headers", []))
+ for k, v in debug_headers.items():
+ headers.append((k.encode(), v.encode()))
+ message = {**message, "headers": headers}
+ await send(message)
+
+ return _send_with_debug
+
+ @staticmethod
+ def maybe_build_debug_headers(
+ *,
+ raw_headers: Optional[Dict[str, str]],
+ scope: Dict,
+ mcp_servers: Optional[List[str]],
+ mcp_auth_header: Optional[str],
+ mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]],
+ oauth2_headers: Optional[Dict[str, str]],
+ client_ip: Optional[str],
+ ) -> Dict[str, str]:
+ """
+ Build debug headers if debug mode is enabled, otherwise return empty dict.
+
+ This is the single entry point called from the MCP request handler.
+ """
+ if not raw_headers or not MCPDebug.is_debug_enabled(raw_headers):
+ return {}
+
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
+ global_mcp_server_manager,
+ )
+
+ server_url: Optional[str] = None
+ server_auth_type: Optional[str] = None
+ auth_resolution = "no-auth"
+
+ for server_name in mcp_servers or []:
+ server = global_mcp_server_manager.get_mcp_server_by_name(
+ server_name, client_ip=client_ip
+ )
+ if server:
+ server_url = server.url
+ server_auth_type = server.auth_type
+ auth_resolution = MCPDebug.resolve_auth_resolution(
+ server, mcp_auth_header, mcp_server_auth_headers, oauth2_headers
+ )
+ break
+
+ scope_headers = MCPRequestHandler._safe_get_headers_from_scope(scope)
+ litellm_key = MCPRequestHandler.get_litellm_api_key_from_headers(
+ scope_headers
+ )
+
+ return MCPDebug.build_debug_headers(
+ inbound_headers=raw_headers,
+ oauth2_headers=oauth2_headers,
+ litellm_api_key=litellm_key,
+ auth_resolution=auth_resolution,
+ server_url=server_url,
+ server_auth_type=server_auth_type,
+ )
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index 53dc6e512c5..49c4a0ce681 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -11,9 +11,10 @@ import datetime
import hashlib
import json
import re
-from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union, cast
+from typing import Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union, cast
from urllib.parse import urlparse
+import anyio
from fastapi import HTTPException
from httpx import HTTPStatusError
from mcp import ReadResourceResult, Resource
@@ -30,18 +31,19 @@ from pydantic import AnyUrl
import litellm
from litellm._logging import verbose_logger
-from litellm.types.utils import CallTypes
from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException
from litellm.experimental_mcp_client.client import MCPClient
from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
MCPRequestHandler,
)
+from litellm.proxy._experimental.mcp_server.oauth2_token_cache import resolve_mcp_auth
from litellm.proxy._experimental.mcp_server.utils import (
MCP_TOOL_PREFIX_SEPARATOR,
add_server_prefix_to_name,
get_server_prefix,
is_tool_name_prefixed,
+ merge_mcp_headers,
normalize_server_name,
split_server_prefix_from_name,
validate_mcp_server_name,
@@ -53,6 +55,7 @@ from litellm.proxy._types import (
MCPTransportType,
UserAPIKeyAuth,
)
+from litellm.proxy.auth.ip_address_utils import IPAddressUtils
from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_value_helper
from litellm.proxy.utils import ProxyLogging
from litellm.types.llms.custom_http import httpxSpecialProvider
@@ -62,7 +65,24 @@ from litellm.types.mcp_server.mcp_server_manager import (
MCPOAuthMetadata,
MCPServer,
)
-from mcp.shared.tool_name_validation import SEP_986_URL, validate_tool_name
+from litellm.types.utils import CallTypes
+
+try:
+ from mcp.shared.tool_name_validation import (
+ validate_tool_name, # pyright: ignore[reportAssignmentType]
+ )
+ from mcp.shared.tool_name_validation import SEP_986_URL
+except ImportError:
+ from pydantic import BaseModel
+
+ SEP_986_URL = "https://github.com/modelcontextprotocol/protocol/blob/main/proposals/0001-tool-name-validation.md"
+
+ class _ToolNameValidationResult(BaseModel):
+ is_valid: bool = True
+ warnings: list = []
+
+ def validate_tool_name(name: str) -> _ToolNameValidationResult: # type: ignore[misc]
+ return _ToolNameValidationResult()
# Probe includes characters on both sides of the separator to mimic real prefixed tool names.
@@ -89,7 +109,9 @@ def _warn_on_server_name_fields(
if result.is_valid:
return
- warning_text = "; ".join(result.warnings) if result.warnings else "Validation failed"
+ warning_text = (
+ "; ".join(result.warnings) if result.warnings else "Validation failed"
+ )
verbose_logger.warning(
"MCP server '%s' has invalid %s '%s': %s",
server_id,
@@ -102,7 +124,6 @@ def _warn_on_server_name_fields(
_warn("server_name", server_name)
-
def _deserialize_json_dict(data: Any) -> Optional[Dict[str, str]]:
"""
Deserialize optional JSON mappings stored in the database.
@@ -135,13 +156,13 @@ class MCPServerManager:
[
"server-1": {
"name": "zapier_mcp_server",
- "url": "https://actions.zapier.com/mcp/sk-ak-2ew3bofIeQIkNoeKIdXrF1Hhhp/sse"
+ "url": "https://actions.zapier.com/mcp//sse"
"transport": "sse",
"auth_type": "api_key"
},
"uuid-2": {
"name": "google_drive_mcp_server",
- "url": "https://actions.zapier.com/mcp/sk-ak-2ew3bofIeQIkNoeKIdXrF1Hhhp/sse"
+ "url": "https://actions.zapier.com/mcp//sse"
}
]
"""
@@ -307,6 +328,9 @@ class MCPServerManager:
access_groups=server_config.get("access_groups", None),
static_headers=server_config.get("static_headers", None),
allow_all_keys=bool(server_config.get("allow_all_keys", False)),
+ available_on_public_internet=bool(
+ server_config.get("available_on_public_internet", False)
+ ),
)
self.config_mcp_servers[server_id] = new_server
@@ -316,7 +340,7 @@ class MCPServerManager:
verbose_logger.info(
f"Loading OpenAPI spec from {spec_path} for server {server_name}"
)
- self._register_openapi_tools(
+ await self._register_openapi_tools(
spec_path=spec_path,
server=new_server,
base_url=server_config.get("url", ""),
@@ -328,7 +352,9 @@ class MCPServerManager:
self.initialize_tool_name_to_mcp_server_name_mapping()
- def _register_openapi_tools(self, spec_path: str, server: MCPServer, base_url: str):
+ async def _register_openapi_tools(
+ self, spec_path: str, server: MCPServer, base_url: str
+ ):
"""
Register tools from an OpenAPI specification for a given server.
@@ -350,15 +376,15 @@ class MCPServerManager:
get_base_url as get_openapi_base_url,
)
from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (
- load_openapi_spec,
+ load_openapi_spec_async,
)
from litellm.proxy._experimental.mcp_server.tool_registry import (
global_mcp_tool_registry,
)
try:
- # Load OpenAPI spec
- spec = load_openapi_spec(spec_path)
+ # Load OpenAPI spec (async to avoid "called from within a running event loop")
+ spec = await load_openapi_spec_async(spec_path)
# Use base_url from config if provided, otherwise extract from spec
if not base_url:
@@ -372,7 +398,7 @@ class MCPServerManager:
server_prefix = get_server_prefix(server)
# Build headers from server configuration
- headers = {}
+ headers: Dict[str, str] = {}
# Add authentication headers if configured
if server.authentication_token:
@@ -385,10 +411,18 @@ class MCPServerManager:
elif server.auth_type == MCPAuth.basic:
headers["Authorization"] = f"Basic {server.authentication_token}"
- # Add any extra headers from server config
- # Note: extra_headers is a List[str] of header names to forward, not a dict
- # For OpenAPI tools, we'll just use the authentication headers
- # If extra_headers were needed, they would be processed separately
+ # Add any static headers from server config.
+ #
+ # Note: `extra_headers` on MCPServer is a List[str] of header names to forward
+ # from the client request (not available in this OpenAPI tool generation step).
+ # `static_headers` is a dict of concrete headers to always send.
+ headers = (
+ merge_mcp_headers(
+ extra_headers=headers,
+ static_headers=server.static_headers,
+ )
+ or {}
+ )
verbose_logger.debug(
f"Using headers for OpenAPI tools (excluding sensitive values): "
@@ -444,12 +478,12 @@ class MCPServerManager:
)
# Update tool name to server name mapping (for both prefixed and base names)
- self.tool_name_to_mcp_server_name_mapping[
- base_tool_name
- ] = server_prefix
- self.tool_name_to_mcp_server_name_mapping[
- prefixed_tool_name
- ] = server_prefix
+ self.tool_name_to_mcp_server_name_mapping[base_tool_name] = (
+ server_prefix
+ )
+ self.tool_name_to_mcp_server_name_mapping[prefixed_tool_name] = (
+ server_prefix
+ )
registered_count += 1
verbose_logger.debug(
@@ -597,6 +631,9 @@ class MCPServerManager:
allowed_tools=getattr(mcp_server, "allowed_tools", None),
disallowed_tools=getattr(mcp_server, "disallowed_tools", None),
allow_all_keys=mcp_server.allow_all_keys,
+ available_on_public_internet=bool(
+ getattr(mcp_server, "available_on_public_internet", False)
+ ),
updated_at=getattr(mcp_server, "updated_at", None),
)
return new_server
@@ -635,24 +672,47 @@ class MCPServerManager:
return [
server.server_id
for server in self.get_registry().values()
- if server.allow_all_keys
+ if server.allow_all_keys is True
]
async def get_allowed_mcp_servers(
self, user_api_key_auth: Optional[UserAPIKeyAuth] = None
) -> List[str]:
"""
- Get the allowed MCP Servers for the user
+ Get the allowed MCP Servers for the user.
+
+ Priority:
+ 1. If object_permission.mcp_servers is explicitly set, use it (even for admins)
+ 2. If admin and no object_permission, return all servers
+ 3. Otherwise, use standard permission checks
"""
from litellm.proxy.management_endpoints.common_utils import _user_has_admin_view
- # If admin, get all servers
- if user_api_key_auth and _user_has_admin_view(user_api_key_auth):
- return list(self.get_registry().keys())
-
allow_all_server_ids = self.get_allow_all_keys_server_ids()
try:
+ # Check if object_permission.mcp_servers is explicitly set
+ has_explicit_object_permission = False
+ if user_api_key_auth and user_api_key_auth.object_permission:
+ # Check if mcp_servers is explicitly set (not None, empty list is valid)
+ if user_api_key_auth.object_permission.mcp_servers is not None:
+ has_explicit_object_permission = True
+ verbose_logger.debug(
+ f"Object permission mcp_servers explicitly set: {user_api_key_auth.object_permission.mcp_servers}"
+ )
+
+ # If admin but NO explicit object permission, get all servers
+ if (
+ user_api_key_auth
+ and _user_has_admin_view(user_api_key_auth)
+ and not has_explicit_object_permission
+ ):
+ verbose_logger.debug(
+ "Admin user without explicit object_permission - returning all servers"
+ )
+ return list(self.get_registry().keys())
+
+ # Get allowed servers from object permissions (respects object_permission even for admins)
allowed_mcp_servers = await MCPRequestHandler.get_allowed_mcp_servers(
user_api_key_auth
)
@@ -671,6 +731,23 @@ class MCPServerManager:
verbose_logger.warning(f"Failed to get allowed MCP servers: {str(e)}.")
return allow_all_server_ids
+ def filter_server_ids_by_ip(
+ self, server_ids: List[str], client_ip: Optional[str]
+ ) -> List[str]:
+ """
+ Filter server IDs by client IP — external callers only see public servers.
+
+ Returns server_ids unchanged when client_ip is None (no filtering).
+ """
+ if client_ip is None:
+ return server_ids
+ return [
+ sid
+ for sid in server_ids
+ if (s := self.get_mcp_server_by_id(sid)) is not None
+ and self._is_server_accessible_from_ip(s, client_ip)
+ ]
+
async def get_tools_for_server(self, server_id: str) -> List[MCPTool]:
"""
Get the tools for a given server
@@ -781,7 +858,7 @@ class MCPServerManager:
return resolved_env
- def _create_mcp_client(
+ async def _create_mcp_client(
self,
server: MCPServer,
mcp_auth_header: Optional[Union[str, Dict[str, str]]] = None,
@@ -791,19 +868,35 @@ class MCPServerManager:
"""
Create an MCPClient instance for the given server.
+ Auth resolution (single place for all auth logic):
+ 1. ``mcp_auth_header`` — per-request/per-user override
+ 2. OAuth2 client_credentials token — auto-fetched and cached
+ 3. ``server.authentication_token`` — static token from config/DB
+
Args:
- server (MCPServer): The server configuration
- mcp_auth_header: MCP auth header to be passed to the MCP server. This is optional and will be used if provided.
+ server: The server configuration.
+ mcp_auth_header: Optional per-request auth override.
+ extra_headers: Additional headers to forward.
+ stdio_env: Environment variables for stdio transport.
Returns:
- MCPClient: Configured MCP client instance
+ Configured MCP client instance.
"""
+ auth_value = await resolve_mcp_auth(server, mcp_auth_header)
+
transport = server.transport or MCPTransport.sse
# Handle stdio transport
if transport == MCPTransport.stdio:
- # For stdio, we need to get the stdio config from the server
- resolved_env = stdio_env if stdio_env is not None else server.env or {}
+ resolved_env = stdio_env if stdio_env is not None else dict(server.env or {})
+
+ # Ensure npm-based STDIO MCP servers have a writable cache dir.
+ # In containers the default (~/.npm or /app/.npm) may not exist
+ # or be read-only, causing npx to fail with ENOENT.
+ if "NPM_CONFIG_CACHE" not in resolved_env:
+ from litellm.constants import MCP_NPM_CACHE_DIR
+
+ resolved_env["NPM_CONFIG_CACHE"] = MCP_NPM_CACHE_DIR
stdio_config: Optional[MCPStdioConfig] = None
if server.command and server.args is not None:
stdio_config = MCPStdioConfig(
@@ -816,7 +909,7 @@ class MCPServerManager:
server_url="", # Not used for stdio
transport_type=transport,
auth_type=server.auth_type,
- auth_value=mcp_auth_header or server.authentication_token,
+ auth_value=auth_value,
timeout=60.0,
stdio_config=stdio_config,
extra_headers=extra_headers,
@@ -828,7 +921,7 @@ class MCPServerManager:
server_url=server_url,
transport_type=transport,
auth_type=server.auth_type,
- auth_value=mcp_auth_header or server.authentication_token,
+ auth_value=auth_value,
timeout=60.0,
extra_headers=extra_headers,
)
@@ -868,7 +961,7 @@ class MCPServerManager:
stdio_env = self._build_stdio_env(server, raw_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=server,
mcp_auth_header=mcp_auth_header,
extra_headers=extra_headers,
@@ -928,7 +1021,7 @@ class MCPServerManager:
stdio_env = self._build_stdio_env(server, raw_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=server,
mcp_auth_header=mcp_auth_header,
extra_headers=extra_headers,
@@ -972,7 +1065,7 @@ class MCPServerManager:
stdio_env = self._build_stdio_env(server, raw_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=server,
mcp_auth_header=mcp_auth_header,
extra_headers=extra_headers,
@@ -1016,7 +1109,7 @@ class MCPServerManager:
stdio_env = self._build_stdio_env(server, raw_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=server,
mcp_auth_header=mcp_auth_header,
extra_headers=extra_headers,
@@ -1057,7 +1150,7 @@ class MCPServerManager:
stdio_env = self._build_stdio_env(server, raw_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=server,
mcp_auth_header=mcp_auth_header,
extra_headers=extra_headers,
@@ -1087,7 +1180,7 @@ class MCPServerManager:
stdio_env = self._build_stdio_env(server, raw_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=server,
mcp_auth_header=mcp_auth_header,
extra_headers=extra_headers,
@@ -1352,6 +1445,9 @@ class MCPServerManager:
"""
Fetch tools from MCP client with timeout and error handling.
+ Uses anyio.fail_after() instead of asyncio.wait_for() to avoid conflicts
+ with the MCP SDK's anyio TaskGroup. See GitHub issue #20715 for details.
+
Args:
client: MCP client instance
server_name: Name of the server for logging
@@ -1359,24 +1455,12 @@ class MCPServerManager:
Returns:
List of tools from the server
"""
-
- async def _list_tools_task():
- try:
+ try:
+ with anyio.fail_after(30.0):
tools = await client.list_tools()
verbose_logger.debug(f"Tools from {server_name}: {tools}")
return tools
- except asyncio.CancelledError:
- verbose_logger.warning(f"Client operation cancelled for {server_name}")
- return []
- except Exception as e:
- verbose_logger.warning(
- f"Client operation failed for {server_name}: {str(e)}"
- )
- return []
-
- try:
- return await asyncio.wait_for(_list_tools_task(), timeout=30.0)
- except asyncio.TimeoutError:
+ except TimeoutError:
verbose_logger.warning(f"Timeout while listing tools from {server_name}")
return []
except asyncio.CancelledError:
@@ -1819,6 +1903,7 @@ class MCPServerManager:
oauth2_headers: Optional[Dict[str, str]],
raw_headers: Optional[Dict[str, str]],
proxy_logging_obj: Optional[ProxyLogging],
+ host_progress_callback: Optional[Callable] = None,
) -> CallToolResult:
"""
Call a regular MCP tool using the MCP client.
@@ -1890,7 +1975,7 @@ class MCPServerManager:
stdio_env = self._build_stdio_env(mcp_server, raw_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=mcp_server,
mcp_auth_header=server_auth_header,
extra_headers=extra_headers,
@@ -1903,7 +1988,9 @@ class MCPServerManager:
)
async def _call_tool_via_client(client, params):
- return await client.call_tool(params)
+ return await client.call_tool(
+ params, host_progress_callback=host_progress_callback
+ )
tasks.append(
asyncio.create_task(_call_tool_via_client(client, call_tool_params))
@@ -1940,6 +2027,7 @@ class MCPServerManager:
proxy_logging_obj: Optional[ProxyLogging] = None,
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
+ host_progress_callback: Optional[Callable] = None,
) -> CallToolResult:
"""
Call a tool with the given name and arguments
@@ -2015,6 +2103,7 @@ class MCPServerManager:
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
proxy_logging_obj=proxy_logging_obj,
+ host_progress_callback=host_progress_callback,
)
# For OpenAPI tools, await outside the client context
@@ -2062,8 +2151,8 @@ class MCPServerManager:
Note: This now handles prefixed tool names
"""
for server in self.get_registry().values():
- if server.auth_type == MCPAuth.oauth2:
- # Skip OAuth2 servers for now as they may require user-specific tokens
+ if server.needs_user_oauth_token:
+ # Skip OAuth2 servers that rely on user-provided tokens
continue
tools = await self._get_tools_from_server(server)
for tool in tools:
@@ -2171,6 +2260,43 @@ class MCPServerManager:
servers.append(server)
return servers
+ def _get_general_settings(self) -> Dict[str, Any]:
+ """Get general_settings, importing lazily to avoid circular imports."""
+ try:
+ from litellm.proxy.proxy_server import (
+ general_settings as proxy_general_settings,
+ )
+
+ return proxy_general_settings
+ except ImportError:
+ # Fallback if proxy_server not available
+ return {}
+
+ def _is_server_accessible_from_ip(
+ self, server: MCPServer, client_ip: Optional[str]
+ ) -> bool:
+ """
+ Check if a server is accessible from the given client IP.
+
+ - If client_ip is None, no IP filtering is applied (internal callers).
+ - If the server has available_on_public_internet=True, it's always accessible.
+ - Otherwise, only internal/private IPs can access it.
+ """
+ if client_ip is None:
+ return True
+ if server.available_on_public_internet:
+ return True
+ # Check backwards compat: litellm.public_mcp_servers
+ public_ids = set(litellm.public_mcp_servers or [])
+ if server.server_id in public_ids:
+ return True
+ # Non-public server: only accessible from internal IPs
+ general_settings = self._get_general_settings()
+ internal_networks = IPAddressUtils.parse_internal_networks(
+ general_settings.get("mcp_internal_ip_ranges")
+ )
+ return IPAddressUtils.is_internal_ip(client_ip, internal_networks)
+
def get_mcp_server_by_id(self, server_id: str) -> Optional[MCPServer]:
"""
Get the MCP Server from the server id
@@ -2183,27 +2309,72 @@ class MCPServerManager:
def get_public_mcp_servers(self) -> List[MCPServer]:
"""
- Get the public MCP servers
+ Get the public MCP servers (available_on_public_internet=True flag on server).
+ Also includes servers from litellm.public_mcp_servers for backwards compat.
"""
servers: List[MCPServer] = []
- if litellm.public_mcp_servers is None:
- return servers
- for server_id in litellm.public_mcp_servers:
- server = self.get_mcp_server_by_id(server_id)
- if server:
+ public_ids = set(litellm.public_mcp_servers or [])
+ for server in self.get_registry().values():
+ if server.available_on_public_internet or server.server_id in public_ids:
servers.append(server)
return servers
- def get_mcp_server_by_name(self, server_name: str) -> Optional[MCPServer]:
+ def get_mcp_server_by_name(
+ self, server_name: str, client_ip: Optional[str] = None
+ ) -> Optional[MCPServer]:
"""
- Get the MCP Server from the server name
+ Get the MCP Server from the server name.
+
+ Uses priority-based matching to avoid collisions:
+ 1. First pass: exact alias match (highest priority)
+ 2. Second pass: exact server_name match
+ 3. Third pass: exact name match (lowest priority)
+
+ Args:
+ server_name: The server name to look up.
+ client_ip: Optional client IP for access control. When provided,
+ non-public servers are hidden from external IPs.
"""
registry = self.get_registry()
+ # Pass 1: Match by alias (highest priority)
+ for server in registry.values():
+ if server.alias == server_name:
+ if not self._is_server_accessible_from_ip(server, client_ip):
+ return None
+ return server
+ # Pass 2: Match by server_name
for server in registry.values():
if server.server_name == server_name:
+ if not self._is_server_accessible_from_ip(server, client_ip):
+ return None
+ return server
+ # Pass 3: Match by name (lowest priority)
+ for server in registry.values():
+ if server.name == server_name:
+ if not self._is_server_accessible_from_ip(server, client_ip):
+ return None
return server
return None
+ def get_filtered_registry(
+ self, client_ip: Optional[str] = None
+ ) -> Dict[str, MCPServer]:
+ """
+ Get registry filtered by client IP access control.
+
+ Args:
+ client_ip: Optional client IP. When provided, non-public servers
+ are hidden from external IPs. When None, returns all servers.
+ """
+ registry = self.get_registry()
+ if client_ip is None:
+ return registry
+ return {
+ k: v
+ for k, v in registry.items()
+ if self._is_server_accessible_from_ip(v, client_ip)
+ }
+
def _generate_stable_server_id(
self,
server_name: str,
@@ -2276,7 +2447,7 @@ class MCPServerManager:
should_skip_health_check = False
# Skip if auth_type is oauth2
- if server.auth_type == MCPAuth.oauth2:
+ if server.needs_user_oauth_token:
should_skip_health_check = True
# Skip if auth_type is not none and authentication_token is missing
elif (
@@ -2291,7 +2462,7 @@ class MCPServerManager:
if server.static_headers:
extra_headers.update(server.static_headers)
- client = self._create_mcp_client(
+ client = await self._create_mcp_client(
server=server,
mcp_auth_header=None,
extra_headers=extra_headers,
@@ -2309,6 +2480,9 @@ class MCPServerManager:
except asyncio.TimeoutError:
health_check_error = "Health check timed out after 10 seconds"
status = "unhealthy"
+ except asyncio.CancelledError:
+ health_check_error = "Health check was cancelled"
+ status = "unknown"
except Exception as e:
health_check_error = str(e)
status = "unhealthy"
@@ -2433,6 +2607,7 @@ class MCPServerManager:
token_url=server.token_url,
registration_url=server.registration_url,
allow_all_keys=server.allow_all_keys,
+ available_on_public_internet=server.available_on_public_internet,
)
async def get_all_mcp_servers_unfiltered(self) -> List[LiteLLM_MCPServerTable]:
diff --git a/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py
new file mode 100644
index 00000000000..0de381ee1df
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py
@@ -0,0 +1,163 @@
+"""
+OAuth2 client_credentials token cache for MCP servers.
+
+Automatically fetches and refreshes access tokens for MCP servers configured
+with ``client_id``, ``client_secret``, and ``token_url``.
+"""
+
+import asyncio
+from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.caching.in_memory_cache import InMemoryCache
+from litellm.constants import (
+ MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL,
+ MCP_OAUTH2_TOKEN_CACHE_MAX_SIZE,
+ MCP_OAUTH2_TOKEN_CACHE_MIN_TTL,
+ MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS,
+)
+from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
+from litellm.types.llms.custom_http import httpxSpecialProvider
+
+if TYPE_CHECKING:
+ from litellm.types.mcp_server.mcp_server_manager import MCPServer
+
+
+class MCPOAuth2TokenCache(InMemoryCache):
+ """
+ In-memory cache for OAuth2 client_credentials tokens, keyed by server_id.
+
+ Inherits from ``InMemoryCache`` for TTL-based storage and eviction.
+ Adds per-server ``asyncio.Lock`` to prevent duplicate concurrent fetches.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(
+ max_size_in_memory=MCP_OAUTH2_TOKEN_CACHE_MAX_SIZE,
+ default_ttl=MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL,
+ )
+ self._locks: Dict[str, asyncio.Lock] = {}
+
+ def _get_lock(self, server_id: str) -> asyncio.Lock:
+ return self._locks.setdefault(server_id, asyncio.Lock())
+
+ async def async_get_token(self, server: "MCPServer") -> Optional[str]:
+ """Return a valid access token, fetching or refreshing as needed.
+
+ Returns ``None`` when the server lacks client credentials config.
+ """
+ if not server.has_client_credentials:
+ return None
+
+ server_id = server.server_id
+
+ # Fast path — cached token is still valid
+ cached = self.get_cache(server_id)
+ if cached is not None:
+ return cached
+
+ # Slow path — acquire per-server lock then double-check
+ async with self._get_lock(server_id):
+ cached = self.get_cache(server_id)
+ if cached is not None:
+ return cached
+
+ token, ttl = await self._fetch_token(server)
+ self.set_cache(server_id, token, ttl=ttl)
+ return token
+
+ async def _fetch_token(self, server: "MCPServer") -> Tuple[str, int]:
+ """POST to ``token_url`` with ``grant_type=client_credentials``.
+
+ Returns ``(access_token, ttl_seconds)`` where ttl accounts for the
+ expiry buffer so the cache entry expires before the real token does.
+ """
+ client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP)
+
+ if not server.client_id or not server.client_secret or not server.token_url:
+ raise ValueError(
+ f"MCP server '{server.server_id}' missing required OAuth2 fields: "
+ f"client_id={bool(server.client_id)}, "
+ f"client_secret={bool(server.client_secret)}, "
+ f"token_url={bool(server.token_url)}"
+ )
+
+ data: Dict[str, str] = {
+ "grant_type": "client_credentials",
+ "client_id": server.client_id,
+ "client_secret": server.client_secret,
+ }
+ if server.scopes:
+ data["scope"] = " ".join(server.scopes)
+
+ verbose_logger.debug(
+ "Fetching OAuth2 client_credentials token for MCP server %s",
+ server.server_id,
+ )
+
+ try:
+ response = await client.post(server.token_url, data=data)
+ response.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ raise ValueError(
+ f"OAuth2 token request for MCP server '{server.server_id}' "
+ f"failed with status {exc.response.status_code}"
+ ) from exc
+
+ body = response.json()
+
+ if not isinstance(body, dict):
+ raise ValueError(
+ f"OAuth2 token response for MCP server '{server.server_id}' "
+ f"returned non-object JSON (got {type(body).__name__})"
+ )
+
+ access_token = body.get("access_token")
+ if not access_token:
+ raise ValueError(
+ f"OAuth2 token response for MCP server '{server.server_id}' "
+ f"missing 'access_token'"
+ )
+
+ # Safely parse expires_in — providers may return null or non-numeric values
+ raw_expires_in = body.get("expires_in")
+ try:
+ expires_in = int(raw_expires_in) if raw_expires_in is not None else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL
+ except (TypeError, ValueError):
+ expires_in = MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL
+
+ ttl = max(expires_in - MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS, MCP_OAUTH2_TOKEN_CACHE_MIN_TTL)
+
+ verbose_logger.info(
+ "Fetched OAuth2 token for MCP server %s (expires in %ds)",
+ server.server_id,
+ expires_in,
+ )
+ return access_token, ttl
+
+ def invalidate(self, server_id: str) -> None:
+ """Remove a cached token (e.g. after a 401)."""
+ self.delete_cache(server_id)
+
+
+mcp_oauth2_token_cache = MCPOAuth2TokenCache()
+
+
+async def resolve_mcp_auth(
+ server: "MCPServer",
+ mcp_auth_header: Optional[Union[str, Dict[str, str]]] = None,
+) -> Optional[Union[str, Dict[str, str]]]:
+ """Resolve the auth value for an MCP server.
+
+ Priority:
+ 1. ``mcp_auth_header`` — per-request/per-user override
+ 2. OAuth2 client_credentials token — auto-fetched and cached
+ 3. ``server.authentication_token`` — static token from config/DB
+ """
+ if mcp_auth_header:
+ return mcp_auth_header
+ if server.has_client_credentials:
+ return await mcp_oauth2_token_cache.async_get_token(server)
+ return server.authentication_token
diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py
index b635f15ed09..deb0b4f9549 100644
--- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py
+++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py
@@ -3,6 +3,8 @@ This module is used to generate MCP tools from OpenAPI specs.
"""
import json
+import asyncio
+import os
from pathlib import PurePosixPath
from typing import Any, Dict, Optional
from urllib.parse import quote
@@ -45,8 +47,36 @@ def _sanitize_path_parameter_value(param_value: Any, param_name: str) -> str:
def load_openapi_spec(filepath: str) -> Dict[str, Any]:
- """Load OpenAPI specification from JSON file."""
- with open(filepath, "r") as f:
+ """
+ Sync wrapper. For URL specs, use the shared/custom MCP httpx client.
+ """
+ try:
+ # If we're already inside an event loop, prefer the async function.
+ asyncio.get_running_loop()
+ raise RuntimeError(
+ "load_openapi_spec() was called from within a running event loop. "
+ "Use 'await load_openapi_spec_async(...)' instead."
+ )
+ except RuntimeError as e:
+ # "no running event loop" is fine; other RuntimeErrors we re-raise
+ if "no running event loop" not in str(e).lower():
+ raise
+ return asyncio.run(load_openapi_spec_async(filepath))
+
+async def load_openapi_spec_async(filepath: str) -> Dict[str, Any]:
+ if filepath.startswith("http://") or filepath.startswith("https://"):
+ client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP)
+ # NOTE: do not close shared client if get_async_httpx_client returns a shared singleton.
+ # If it returns a new client each time, consider wrapping it in an async context manager.
+ r = await client.get(filepath)
+ r.raise_for_status()
+ return r.json()
+
+ # fallback: local file
+ # Local filesystem path
+ if not os.path.exists(filepath):
+ raise FileNotFoundError(f"OpenAPI spec not found at {filepath}")
+ with open(filepath, "r", encoding="utf-8") as f:
return json.load(f)
diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
index 48f7a8b0b7b..aed81afd254 100644
--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
@@ -1,6 +1,6 @@
import importlib
from datetime import datetime
-from typing import Dict, List, Optional, Union
+from typing import Any, Awaitable, Callable, Dict, List, Optional, Union
from fastapi import APIRouter, Depends, HTTPException, Query, Request
@@ -8,9 +8,12 @@ from litellm._logging import verbose_logger
from litellm.proxy._experimental.mcp_server.ui_session_utils import (
build_effective_auth_contexts,
)
+from litellm.proxy._experimental.mcp_server.utils import merge_mcp_headers
from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.auth.ip_address_utils import IPAddressUtils
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.types.mcp import MCPAuth
+from litellm.types.utils import CallTypes
MCP_AVAILABLE: bool = True
try:
@@ -27,12 +30,14 @@ router = APIRouter(
if MCP_AVAILABLE:
from mcp.types import Tool as MCPTool
+
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)
from litellm.proxy._experimental.mcp_server.server import (
ListMCPToolsRestAPIResponseObject,
MCPServer,
+ _tool_name_matches,
execute_mcp_tool,
filter_tools_by_allowed_tools,
)
@@ -75,10 +80,87 @@ if MCP_AVAILABLE:
for tool in tools
]
+ def _extract_mcp_headers_from_request(
+ request: Request,
+ mcp_request_handler_cls,
+ ) -> tuple:
+ """
+ Extract MCP auth headers from HTTP request.
+
+ Returns:
+ Tuple of (mcp_auth_header, mcp_server_auth_headers, raw_headers)
+ """
+ headers = request.headers
+ raw_headers = dict(headers)
+ mcp_auth_header = mcp_request_handler_cls._get_mcp_auth_header_from_headers(
+ headers
+ )
+ mcp_server_auth_headers = (
+ mcp_request_handler_cls._get_mcp_server_auth_headers_from_headers(headers)
+ )
+ return mcp_auth_header, mcp_server_auth_headers, raw_headers
+
+ async def _resolve_allowed_mcp_servers_with_ip_filter(
+ request: Request,
+ user_api_key_dict: UserAPIKeyAuth,
+ server_id: str,
+ ) -> List[MCPServer]:
+ """
+ Resolve allowed MCP servers for a tool call with IP filtering.
+
+ Args:
+ request: The HTTP request object
+ user_api_key_dict: The user's API key auth object
+ server_id: The server ID to validate access for
+
+ Returns:
+ List of allowed MCPServer objects
+
+ Raises:
+ HTTPException: If the server_id is not allowed
+ """
+ # Get all auth contexts
+ auth_contexts = await build_effective_auth_contexts(user_api_key_dict)
+
+ # Collect allowed server IDs from all contexts, then apply IP filtering
+ _rest_client_ip = IPAddressUtils.get_mcp_client_ip(request)
+ allowed_server_ids_set = set()
+ for auth_context in auth_contexts:
+ servers = await global_mcp_server_manager.get_allowed_mcp_servers(
+ user_api_key_auth=auth_context,
+ )
+ allowed_server_ids_set.update(servers)
+
+ allowed_server_ids_set = set(
+ global_mcp_server_manager.filter_server_ids_by_ip(
+ list(allowed_server_ids_set), _rest_client_ip
+ )
+ )
+
+ # Check if the specified server_id is allowed
+ if server_id not in allowed_server_ids_set:
+ raise HTTPException(
+ status_code=403,
+ detail={
+ "error": "access_denied",
+ "message": f"The key is not allowed to access server {server_id}",
+ },
+ )
+
+ # Build allowed_mcp_servers list (only include allowed servers)
+ allowed_mcp_servers: List[MCPServer] = []
+ for allowed_server_id in allowed_server_ids_set:
+ server = global_mcp_server_manager.get_mcp_server_by_id(allowed_server_id)
+ if server is not None:
+ allowed_mcp_servers.append(server)
+
+ return allowed_mcp_servers
+
async def _get_tools_for_single_server(
server,
server_auth_header,
raw_headers: Optional[Dict[str, str]] = None,
+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,
):
"""Helper function to get tools for a single server."""
tools = await global_mcp_server_manager._get_tools_from_server(
@@ -93,8 +175,58 @@ if MCP_AVAILABLE:
if server.allowed_tools is not None and len(server.allowed_tools) > 0:
tools = filter_tools_by_allowed_tools(tools, server)
+ # Filter tools based on user_api_key_auth.object_permission.mcp_tool_permissions
+ # This provides per-key/team/org control over which tools can be accessed
+ if (
+ user_api_key_auth
+ and user_api_key_auth.object_permission
+ and user_api_key_auth.object_permission.mcp_tool_permissions
+ ):
+ allowed_tools_for_server = (
+ user_api_key_auth.object_permission.mcp_tool_permissions.get(
+ server.server_id
+ )
+ )
+ if (
+ allowed_tools_for_server is not None
+ and len(allowed_tools_for_server) > 0
+ ):
+ # Filter tools to only include those in the allowed list
+ tools = [
+ tool
+ for tool in tools
+ if _tool_name_matches(tool.name, allowed_tools_for_server)
+ ]
+
return _create_tool_response_objects(tools, server.mcp_info)
+ async def _resolve_allowed_mcp_servers_for_tool_call(
+ user_api_key_dict: UserAPIKeyAuth,
+ server_id: str,
+ ) -> List[MCPServer]:
+ """Resolve allowed MCP servers for the given user and validate server_id access."""
+ auth_contexts = await build_effective_auth_contexts(user_api_key_dict)
+ allowed_server_ids_set = set()
+ for auth_context in auth_contexts:
+ servers = await global_mcp_server_manager.get_allowed_mcp_servers(
+ user_api_key_auth=auth_context
+ )
+ allowed_server_ids_set.update(servers)
+ if server_id not in allowed_server_ids_set:
+ raise HTTPException(
+ status_code=403,
+ detail={
+ "error": "access_denied",
+ "message": f"The key is not allowed to access server {server_id}",
+ },
+ )
+ allowed_mcp_servers: List[MCPServer] = []
+ for allowed_server_id in allowed_server_ids_set:
+ server = global_mcp_server_manager.get_mcp_server_by_id(allowed_server_id)
+ if server is not None:
+ allowed_mcp_servers.append(server)
+ return allowed_mcp_servers
+
########################################################
@router.get("/tools/list", dependencies=[Depends(user_api_key_auth)])
async def list_tool_rest_api(
@@ -141,21 +273,25 @@ if MCP_AVAILABLE:
auth_contexts = await build_effective_auth_contexts(user_api_key_dict)
+ _rest_client_ip = IPAddressUtils.get_mcp_client_ip(request)
+
allowed_server_ids_set = set()
for auth_context in auth_contexts:
servers = await global_mcp_server_manager.get_allowed_mcp_servers(
- user_api_key_auth=auth_context
+ user_api_key_auth=auth_context,
)
allowed_server_ids_set.update(servers)
- allowed_server_ids = list(allowed_server_ids_set)
+ allowed_server_ids = global_mcp_server_manager.filter_server_ids_by_ip(
+ list(allowed_server_ids_set), _rest_client_ip
+ )
list_tools_result = []
error_message = None
# If server_id is specified, only query that specific server
if server_id:
- if server_id not in allowed_server_ids_set:
+ if server_id not in allowed_server_ids:
raise HTTPException(
status_code=403,
detail={
@@ -177,7 +313,10 @@ if MCP_AVAILABLE:
try:
list_tools_result = await _get_tools_for_single_server(
- server, server_auth_header, raw_headers_from_request
+ server,
+ server_auth_header,
+ raw_headers_from_request,
+ user_api_key_dict,
)
except Exception as e:
verbose_logger.exception(
@@ -213,7 +352,10 @@ if MCP_AVAILABLE:
try:
tools_result = await _get_tools_for_single_server(
- server, server_auth_header, raw_headers_from_request
+ server,
+ server_auth_header,
+ raw_headers_from_request,
+ user_api_key_dict,
)
list_tools_result.extend(tools_result)
except Exception as e:
@@ -260,7 +402,14 @@ if MCP_AVAILABLE:
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
MCPRequestHandler,
)
- from litellm.proxy.proxy_server import add_litellm_data_to_request, proxy_config
+ from litellm.proxy.common_request_processing import (
+ ProxyBaseLLMRequestProcessing,
+ )
+ from litellm.proxy.proxy_server import (
+ general_settings,
+ proxy_config,
+ proxy_logging_obj,
+ )
try:
data = await request.json()
@@ -288,28 +437,22 @@ if MCP_AVAILABLE:
tool_arguments = data.get("arguments")
- data = await add_litellm_data_to_request(
- data=data,
- request=request,
- user_api_key_dict=user_api_key_dict,
- proxy_config=proxy_config,
+ proxy_base_llm_response_processor = ProxyBaseLLMRequestProcessing(data=data)
+ data, logging_obj = (
+ await proxy_base_llm_response_processor.common_processing_pre_call_logic(
+ request=request,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=proxy_config,
+ route_type=CallTypes.call_mcp_tool.value,
+ proxy_logging_obj=proxy_logging_obj,
+ general_settings=general_settings,
+ )
)
- # FIX: Extract MCP auth headers from request
- # The UI sends bearer token in x-mcp-auth header and server-specific headers,
- # but they weren't being extracted and passed to call_mcp_tool.
- # This fix ensures auth headers are properly extracted from the HTTP request
- # and passed through to the MCP server for authentication.
- headers = request.headers
- raw_headers_from_request = dict(headers)
- mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers(
- headers
+ # Extract MCP auth headers from request and add to data dict
+ mcp_auth_header, mcp_server_auth_headers, raw_headers_from_request = (
+ _extract_mcp_headers_from_request(request, MCPRequestHandler)
)
- mcp_server_auth_headers = (
- MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
- )
-
- # Add extracted headers to data dict to pass to call_mcp_tool
if mcp_auth_header:
data["mcp_auth_header"] = mcp_auth_header
if mcp_server_auth_headers:
@@ -321,35 +464,10 @@ if MCP_AVAILABLE:
if "metadata" in data and "user_api_key_auth" in data["metadata"]:
data["user_api_key_auth"] = data["metadata"]["user_api_key_auth"]
- # Get all auth contexts
- auth_contexts = await build_effective_auth_contexts(user_api_key_dict)
-
- # Collect allowed server IDs from all contexts
- allowed_server_ids_set = set()
- for auth_context in auth_contexts:
- servers = await global_mcp_server_manager.get_allowed_mcp_servers(
- user_api_key_auth=auth_context
- )
- allowed_server_ids_set.update(servers)
-
- # Check if the specified server_id is allowed
- if server_id not in allowed_server_ids_set:
- raise HTTPException(
- status_code=403,
- detail={
- "error": "access_denied",
- "message": f"The key is not allowed to access server {server_id}",
- },
- )
-
- # Build allowed_mcp_servers list (only include allowed servers)
- allowed_mcp_servers: List[MCPServer] = []
- for allowed_server_id in allowed_server_ids_set:
- server = global_mcp_server_manager.get_mcp_server_by_id(
- allowed_server_id
- )
- if server is not None:
- allowed_mcp_servers.append(server)
+ # Resolve allowed MCP servers with IP filtering
+ allowed_mcp_servers = await _resolve_allowed_mcp_servers_with_ip_filter(
+ request, user_api_key_dict, server_id
+ )
# Call execute_mcp_tool directly (permission checks already done)
result = await execute_mcp_tool(
@@ -410,24 +528,50 @@ if MCP_AVAILABLE:
NewMCPServerRequest,
)
+ def _extract_credentials(
+ request: NewMCPServerRequest,
+ ) -> tuple:
+ """
+ Extract OAuth credentials from the nested ``request.credentials`` dict.
+
+ Returns:
+ (client_id, client_secret, scopes) — any value may be ``None``.
+ """
+ creds = request.credentials if isinstance(request.credentials, dict) else {}
+ client_id: Optional[str] = creds.get("client_id")
+ client_secret: Optional[str] = creds.get("client_secret")
+ scopes_raw = creds.get("scopes")
+ scopes: Optional[List[str]] = scopes_raw if isinstance(scopes_raw, list) else None
+ return client_id, client_secret, scopes
+
async def _execute_with_mcp_client(
request: NewMCPServerRequest,
- operation,
+ operation: Callable[..., Awaitable[Any]],
mcp_auth_header: Optional[Union[str, Dict[str, str]]] = None,
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
- ):
+ ) -> dict:
"""
- Common helper to create MCP client, execute operation, and ensure proper cleanup.
+ Create a temporary MCP client from *request*, run *operation*, and return the result.
+
+ For M2M OAuth servers (those with ``client_id``, ``client_secret``, and
+ ``token_url``), the incoming ``oauth2_headers`` are dropped so that
+ ``resolve_mcp_auth`` can auto-fetch a token via ``client_credentials``.
Args:
- request: MCP server configuration
- operation: Async function that takes a client and returns the operation result
+ request: MCP server configuration submitted by the UI.
+ operation: Async callable that receives the created client and returns a result dict.
+ mcp_auth_header: Pre-resolved credential header (API-key / bearer token).
+ oauth2_headers: Headers extracted from the incoming request (may contain the
+ litellm API key — must NOT be forwarded for M2M servers).
+ raw_headers: Raw request headers forwarded for stdio env construction.
Returns:
- Operation result or error response
+ The dict returned by *operation*, or an error dict on failure.
"""
try:
+ client_id, client_secret, scopes = _extract_credentials(request)
+
server_model = MCPServer(
server_id=request.server_id or "",
name=request.alias or request.server_name or "",
@@ -438,26 +582,47 @@ if MCP_AVAILABLE:
command=request.command,
args=request.args,
env=request.env,
+ static_headers=request.static_headers,
+ client_id=client_id,
+ client_secret=client_secret,
+ token_url=request.token_url,
+ scopes=scopes,
+ authorization_url=request.authorization_url,
+ registration_url=request.registration_url,
)
stdio_env = global_mcp_server_manager._build_stdio_env(
server_model, raw_headers
)
- client = global_mcp_server_manager._create_mcp_client(
+ # For M2M OAuth servers, drop the incoming Authorization header so that
+ # resolve_mcp_auth can auto-fetch a token via client_credentials.
+ effective_oauth2_headers = (
+ None if server_model.has_client_credentials else oauth2_headers
+ )
+
+ merged_headers = merge_mcp_headers(
+ extra_headers=effective_oauth2_headers,
+ static_headers=request.static_headers,
+ )
+
+ client = await global_mcp_server_manager._create_mcp_client(
server=server_model,
mcp_auth_header=mcp_auth_header,
- extra_headers=oauth2_headers,
+ extra_headers=merged_headers,
stdio_env=stdio_env,
)
return await operation(client)
- except Exception as e:
- verbose_logger.error(f"Error in MCP operation: {e}", exc_info=True)
+ except (KeyboardInterrupt, SystemExit):
+ raise
+ except BaseException as e:
+ verbose_logger.error("Error in MCP operation: %s", e, exc_info=True)
return {
"status": "error",
- "message": "An internal error has occurred while testing the MCP server.",
+ "error": True,
+ "message": "Failed to connect to MCP server. Check proxy logs for details.",
}
@router.post("/test/connection", dependencies=[Depends(user_api_key_auth)])
diff --git a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py
new file mode 100644
index 00000000000..e5cb6a0098d
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py
@@ -0,0 +1,250 @@
+"""
+Semantic MCP Tool Filtering using semantic-router
+
+Filters MCP tools semantically for /chat/completions and /responses endpoints.
+"""
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
+
+from litellm._logging import verbose_logger
+
+if TYPE_CHECKING:
+ from semantic_router.routers import SemanticRouter
+
+ from litellm.router import Router
+
+
+class SemanticMCPToolFilter:
+ """Filters MCP tools using semantic similarity to reduce context window size."""
+
+ def __init__(
+ self,
+ embedding_model: str,
+ litellm_router_instance: "Router",
+ top_k: int = 10,
+ similarity_threshold: float = 0.3,
+ enabled: bool = True,
+ ):
+ """
+ Initialize the semantic tool filter.
+
+ Args:
+ embedding_model: Model to use for embeddings (e.g., "text-embedding-3-small")
+ litellm_router_instance: Router instance for embedding generation
+ top_k: Maximum number of tools to return
+ similarity_threshold: Minimum similarity score for filtering
+ enabled: Whether filtering is enabled
+ """
+ self.enabled = enabled
+ self.top_k = top_k
+ self.similarity_threshold = similarity_threshold
+ self.embedding_model = embedding_model
+ self.router_instance = litellm_router_instance
+ self.tool_router: Optional["SemanticRouter"] = None
+ self._tool_map: Dict[str, Any] = {} # MCPTool objects or OpenAI function dicts
+
+ async def build_router_from_mcp_registry(self) -> None:
+ """Build semantic router from all MCP tools in the registry (no auth checks)."""
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
+ global_mcp_server_manager,
+ )
+
+ try:
+ # Get all servers from registry without auth checks
+ registry = global_mcp_server_manager.get_registry()
+ if not registry:
+ verbose_logger.warning("MCP registry is empty")
+ self.tool_router = None
+ return
+
+ # Fetch tools from all servers in parallel
+ all_tools = []
+ for server_id, server in registry.items():
+ try:
+ tools = await global_mcp_server_manager.get_tools_for_server(server_id)
+ all_tools.extend(tools)
+ except Exception as e:
+ verbose_logger.warning(f"Failed to fetch tools from server {server_id}: {e}")
+ continue
+
+ if not all_tools:
+ verbose_logger.warning("No MCP tools found in registry")
+ self.tool_router = None
+ return
+
+ verbose_logger.info(f"Fetched {len(all_tools)} tools from {len(registry)} MCP servers")
+ self._build_router(all_tools)
+
+ except Exception as e:
+ verbose_logger.error(f"Failed to build router from MCP registry: {e}")
+ self.tool_router = None
+ raise
+
+ def _extract_tool_info(self, tool) -> tuple[str, str]:
+ """Extract name and description from MCP tool or OpenAI function dict."""
+ name: str
+ description: str
+
+ if isinstance(tool, dict):
+ # OpenAI function format
+ name = tool.get("name", "")
+ description = tool.get("description", name)
+ else:
+ # MCPTool object
+ name = str(tool.name)
+ description = str(tool.description) if tool.description else str(tool.name)
+
+ return name, description
+
+ def _build_router(self, tools: List) -> None:
+ """Build semantic router with tools (MCPTool objects or OpenAI function dicts)."""
+ from semantic_router.routers import SemanticRouter
+ from semantic_router.routers.base import Route
+
+ from litellm.router_strategy.auto_router.litellm_encoder import (
+ LiteLLMRouterEncoder,
+ )
+
+ if not tools:
+ self.tool_router = None
+ return
+
+ try:
+ # Convert tools to routes
+ routes = []
+ self._tool_map = {}
+
+ for tool in tools:
+ name, description = self._extract_tool_info(tool)
+ self._tool_map[name] = tool
+
+ routes.append(
+ Route(
+ name=name,
+ description=description,
+ utterances=[description],
+ score_threshold=self.similarity_threshold,
+ )
+ )
+
+ self.tool_router = SemanticRouter(
+ routes=routes,
+ encoder=LiteLLMRouterEncoder(
+ litellm_router_instance=self.router_instance,
+ model_name=self.embedding_model,
+ score_threshold=self.similarity_threshold,
+ ),
+ auto_sync="local",
+ )
+
+ verbose_logger.info(
+ f"Built semantic router with {len(routes)} tools"
+ )
+
+ except Exception as e:
+ verbose_logger.error(f"Failed to build semantic router: {e}")
+ self.tool_router = None
+ raise
+
+ async def filter_tools(
+ self,
+ query: str,
+ available_tools: List[Any],
+ top_k: Optional[int] = None,
+ ) -> List[Any]:
+ """
+ Filter tools semantically based on query.
+
+ Args:
+ query: User query to match against tools
+ available_tools: Full list of available MCP tools
+ top_k: Override default top_k (optional)
+
+ Returns:
+ Filtered and ordered list of tools (up to top_k)
+ """
+ # Early returns for cases where we can't/shouldn't filter
+ if not self.enabled:
+ return available_tools
+
+ if not available_tools:
+ return available_tools
+
+ if not query or not query.strip():
+ return available_tools
+
+ # Router should be built on startup - if not, something went wrong
+ if self.tool_router is None:
+ verbose_logger.warning("Router not initialized - was build_router_from_mcp_registry() called on startup?")
+ return available_tools
+
+ # Run semantic filtering
+ try:
+ limit = top_k or self.top_k
+ matches = self.tool_router(text=query, limit=limit)
+ matched_tool_names = self._extract_tool_names_from_matches(matches)
+
+ if not matched_tool_names:
+ return available_tools
+
+ return self._get_tools_by_names(matched_tool_names, available_tools)
+
+ except Exception as e:
+ verbose_logger.error(f"Semantic tool filter failed: {e}", exc_info=True)
+ return available_tools
+
+ def _extract_tool_names_from_matches(self, matches) -> List[str]:
+ """Extract tool names from semantic router match results."""
+ if not matches:
+ return []
+
+ # Handle single match
+ if hasattr(matches, "name") and matches.name:
+ return [matches.name]
+
+ # Handle list of matches
+ if isinstance(matches, list):
+ return [m.name for m in matches if hasattr(m, "name") and m.name]
+
+ return []
+
+ def _get_tools_by_names(
+ self, tool_names: List[str], available_tools: List[Any]
+ ) -> List[Any]:
+ """Get tools from available_tools by their names, preserving order."""
+ # Match tools from available_tools (preserves format - dict or MCPTool)
+ matched_tools = []
+ for tool in available_tools:
+ tool_name, _ = self._extract_tool_info(tool)
+ if tool_name in tool_names:
+ matched_tools.append(tool)
+
+ # Reorder to match semantic router's ordering
+ tool_map = {self._extract_tool_info(t)[0]: t for t in matched_tools}
+ return [tool_map[name] for name in tool_names if name in tool_map]
+
+ def extract_user_query(self, messages: List[Dict[str, Any]]) -> str:
+ """
+ Extract user query from messages for /chat/completions or /responses.
+
+ Args:
+ messages: List of message dictionaries (from 'messages' or 'input' field)
+
+ Returns:
+ Extracted query string
+ """
+ for msg in reversed(messages):
+ if msg.get("role") == "user":
+ content = msg.get("content", "")
+
+ if isinstance(content, str):
+ return content
+
+ if isinstance(content, list):
+ texts = [
+ block.get("text", "") if isinstance(block, dict) else str(block)
+ for block in content
+ if isinstance(block, (dict, str))
+ ]
+ return " ".join(texts)
+
+ return ""
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 03652ae155e..31836a27509 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -5,13 +5,25 @@ LiteLLM MCP Server Routes
import asyncio
import contextlib
-from datetime import datetime
import traceback
import uuid
-from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Union, cast
+from datetime import datetime
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
from fastapi import FastAPI, HTTPException
from pydantic import AnyUrl, ConfigDict
+from starlette.requests import Request as StarletteRequest
+from starlette.responses import JSONResponse
from starlette.types import Receive, Scope, Send
from litellm._logging import verbose_logger
@@ -20,12 +32,20 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
MCPRequestHandler,
)
+from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (
+ get_request_base_url,
+)
+from litellm.proxy._experimental.mcp_server.mcp_debug import MCPDebug
from litellm.proxy._experimental.mcp_server.utils import (
LITELLM_MCP_SERVER_DESCRIPTION,
LITELLM_MCP_SERVER_NAME,
LITELLM_MCP_SERVER_VERSION,
)
from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.auth.ip_address_utils import IPAddressUtils
+from litellm.proxy.litellm_pre_call_utils import (
+ LiteLLMProxyRequestSetup,
+)
from litellm.types.mcp import MCPAuth
from litellm.types.mcp_server.mcp_server_manager import MCPInfo, MCPServer
from litellm.types.utils import CallTypes, StandardLoggingMCPToolCall
@@ -74,7 +94,11 @@ if MCP_AVAILABLE:
AuthContextMiddleware,
auth_context_var,
)
- from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
+
+ try:
+ from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
+ except ImportError:
+ StreamableHTTPSessionManager = None # type: ignore
from mcp.types import (
CallToolResult,
EmbeddedResource,
@@ -124,7 +148,7 @@ if MCP_AVAILABLE:
session_manager = StreamableHTTPSessionManager(
app=server,
event_store=None,
- json_response=True, # Use JSON responses instead of SSE by default
+ json_response=False, # enables SSE streaming
stateless=True,
)
@@ -210,6 +234,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers,
oauth2_headers,
raw_headers,
+ _client_ip,
) = get_auth_context()
verbose_logger.debug(
f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}"
@@ -273,11 +298,36 @@ if MCP_AVAILABLE:
mcp_server_auth_headers,
oauth2_headers,
raw_headers,
+ _client_ip,
) = get_auth_context()
verbose_logger.debug(
f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}"
)
+ host_progress_callback = None
+ try:
+ host_ctx = server.request_context
+ if host_ctx and hasattr(host_ctx, 'meta') and host_ctx.meta:
+ host_token = getattr(host_ctx.meta, 'progressToken', None)
+ if host_token and hasattr(host_ctx, 'session') and host_ctx.session:
+ host_session = host_ctx.session
+
+ async def forward_progress(progress: float, total: float | None):
+ """Forward progress notifications from external MCP to Host"""
+ try:
+ await host_session.send_progress_notification(
+ progress_token=host_token,
+ progress=progress,
+ total=total
+ )
+ verbose_logger.debug(f"Forwarded progress {progress}/{total} to Host")
+ except Exception as e:
+ verbose_logger.error(f"Failed to forward progress to Host: {e}")
+
+ host_progress_callback = forward_progress
+ verbose_logger.debug(f"Host progressToken captured: {host_token[:8]}...")
+ except Exception as e:
+ verbose_logger.warning(f"Could not capture host progress context: {e}")
try:
# Create a body date for logging
body_data = {"name": name, "arguments": arguments}
@@ -307,6 +357,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers=mcp_server_auth_headers,
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
+ host_progress_callback=host_progress_callback,
**data, # for logging
)
except BlockedPiiEntityError as e:
@@ -359,6 +410,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers,
oauth2_headers,
raw_headers,
+ _client_ip,
) = get_auth_context()
verbose_logger.debug(
f"MCP list_prompts - User API Key Auth from context: {user_api_key_auth}"
@@ -412,6 +464,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers,
oauth2_headers,
raw_headers,
+ _client_ip,
) = get_auth_context()
verbose_logger.debug(
@@ -439,6 +492,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers,
oauth2_headers,
raw_headers,
+ _client_ip,
) = get_auth_context()
verbose_logger.debug(
f"MCP list_resources - User API Key Auth from context: {user_api_key_auth}"
@@ -477,6 +531,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers,
oauth2_headers,
raw_headers,
+ _client_ip,
) = get_auth_context()
verbose_logger.debug(
f"MCP list_resource_templates - User API Key Auth from context: {user_api_key_auth}"
@@ -516,6 +571,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers,
oauth2_headers,
raw_headers,
+ _client_ip,
) = get_auth_context()
read_resource_result = await mcp_read_resource(
@@ -674,13 +730,57 @@ if MCP_AVAILABLE:
return tools_to_return
+ def _get_client_ip_from_context() -> Optional[str]:
+ """
+ Extract client_ip from auth context.
+ Returns None if context not set (caller should handle this as "no IP filtering").
+ """
+ try:
+ auth_user = auth_context_var.get()
+ if auth_user and isinstance(auth_user, MCPAuthenticatedUser):
+ return auth_user.client_ip
+ except Exception:
+ pass
+ return None
+
async def _get_allowed_mcp_servers(
user_api_key_auth: Optional[UserAPIKeyAuth],
mcp_servers: Optional[List[str]],
+ client_ip: Optional[str] = None,
) -> List[MCPServer]:
- """Return allowed MCP servers for a request after applying filters."""
+ """Return allowed MCP servers for a request after applying filters.
+
+ Args:
+ user_api_key_auth: The authenticated user's API key info.
+ mcp_servers: Optional list of server names to filter to.
+ client_ip: Client IP for IP-based access control. If None, falls back to
+ auth context. Pass explicitly from request handlers for safety.
+ Note: If client_ip is None and auth context is not set, IP filtering is skipped.
+ This is intentional for internal callers but may indicate a bug if called
+ from a request handler without proper context setup.
+ """
+ # Use explicit client_ip if provided, otherwise try auth context
+ if client_ip is None:
+ client_ip = _get_client_ip_from_context()
+ if client_ip is None:
+ verbose_logger.debug(
+ "MCP _get_allowed_mcp_servers called without client_ip and no auth context. "
+ "IP filtering will be skipped. This is expected for internal calls."
+ )
+
allowed_mcp_server_ids = (
- await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth)
+ await global_mcp_server_manager.get_allowed_mcp_servers(
+ user_api_key_auth
+ )
+ )
+ allowed_mcp_server_ids = (
+ global_mcp_server_manager.filter_server_ids_by_ip(
+ allowed_mcp_server_ids, client_ip
+ )
+ )
+ verbose_logger.debug(
+ "MCP IP filter: client_ip=%s, allowed_server_ids=%s",
+ client_ip, allowed_mcp_server_ids,
)
allowed_mcp_servers: List[MCPServer] = []
for allowed_mcp_server_id in allowed_mcp_server_ids:
@@ -747,6 +847,7 @@ if MCP_AVAILABLE:
raw_headers: Optional[Dict[str, str]] = None,
log_list_tools_to_spendlogs: bool = False,
list_tools_log_source: Optional[str] = None,
+ litellm_trace_id: Optional[str] = None,
) -> List[MCPTool]:
"""
Helper method to fetch tools from MCP servers based on server filtering criteria.
@@ -784,6 +885,7 @@ if MCP_AVAILABLE:
"model": "MCP: list_tools",
"call_type": CallTypes.list_mcp_tools.value,
"litellm_call_id": list_tools_call_id,
+ "litellm_trace_id": litellm_trace_id,
"metadata": {
"spend_logs_metadata": spend_logs_metadata,
},
@@ -799,13 +901,14 @@ if MCP_AVAILABLE:
],
}
- # Attach user identifiers when available (matches call_mcp_tool style)
+ # Attach user identifiers using the standard helper
if user_api_key_auth is not None:
- user_api_key = getattr(user_api_key_auth, "api_key", None)
- if user_api_key:
- cast(dict, list_tools_request_data["metadata"])[
- "user_api_key"
- ] = user_api_key
+
+ LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata(
+ data=list_tools_request_data,
+ user_api_key_dict=user_api_key_auth,
+ _metadata_variable_name="metadata",
+ )
user_identifier = getattr(
user_api_key_auth, "end_user_id", None
@@ -1341,6 +1444,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]] = None,
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
+ host_progress_callback: Optional[Callable] = None,
**kwargs: Any,
) -> CallToolResult:
"""
@@ -1438,6 +1542,7 @@ if MCP_AVAILABLE:
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
litellm_logging_obj=litellm_logging_obj,
+ host_progress_callback=host_progress_callback,
)
# Fall back to local tool registry with original name (legacy support)
@@ -1685,6 +1790,7 @@ if MCP_AVAILABLE:
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
litellm_logging_obj: Optional[Any] = None,
+ host_progress_callback: Optional[Callable] = None,
) -> CallToolResult:
"""Handle tool execution for managed server tools"""
# Import here to avoid circular import
@@ -1700,6 +1806,7 @@ if MCP_AVAILABLE:
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
proxy_logging_obj=proxy_logging_obj,
+ host_progress_callback=host_progress_callback,
)
verbose_logger.debug("CALL TOOL RESULT: %s", call_tool_result)
return call_tool_result
@@ -1808,6 +1915,73 @@ if MCP_AVAILABLE:
raw_headers,
)
+ async def _handle_stale_mcp_session(
+ scope: Scope,
+ receive: Receive,
+ send: Send,
+ mgr: "StreamableHTTPSessionManager",
+ ) -> bool:
+ """
+ Handle stale MCP session IDs to prevent "Session not found" errors.
+
+ When clients reconnect after a server restart or session cleanup, they may
+ send a session ID that no longer exists. This function handles two scenarios:
+
+ 1. Non-DELETE requests: Strip the stale session ID header so the session
+ manager creates a fresh session transparently.
+
+ 2. DELETE requests: Return success (200) immediately for idempotent behavior,
+ since the desired state (session doesn't exist) is already achieved.
+
+ Returns:
+ True if the request was handled (DELETE on non-existent session)
+ False if the request should continue to the session manager
+
+ Fixes https://github.com/BerriAI/litellm/issues/20292
+ """
+ _mcp_session_header = b"mcp-session-id"
+ _session_id: Optional[str] = None
+ for header_name, header_value in scope.get("headers", []):
+ if header_name == _mcp_session_header:
+ _session_id = header_value.decode("utf-8", errors="replace")
+ break
+
+ if _session_id is None:
+ return False
+
+ known_sessions = getattr(mgr, "_server_instances", None)
+ if known_sessions is None or _session_id in known_sessions:
+ # Session exists or we can't check - let the session manager handle it
+ return False
+
+ # Session doesn't exist - handle based on request method
+ method = scope.get("method", "").upper()
+
+ if method == "DELETE":
+ # Idempotent DELETE: session doesn't exist, return success
+ verbose_logger.info(
+ f"DELETE request for non-existent MCP session '{_session_id}'. "
+ "Returning success (idempotent DELETE)."
+ )
+ success_response = JSONResponse(
+ status_code=200,
+ content={"message": "Session terminated successfully"}
+ )
+ await success_response(scope, receive, send)
+ return True
+ else:
+ # Non-DELETE: strip stale session ID to allow new session creation
+ verbose_logger.warning(
+ "MCP session ID '%s' not found in active sessions. "
+ "Stripping stale header to force new session creation.",
+ _session_id,
+ )
+ scope["headers"] = [
+ (k, v) for k, v in scope["headers"]
+ if k != _mcp_session_header
+ ]
+ return False
+
async def handle_streamable_http_mcp(
scope: Scope, receive: Receive, send: Send
) -> None:
@@ -1822,6 +1996,10 @@ if MCP_AVAILABLE:
oauth2_headers,
raw_headers,
) = await extract_mcp_auth_context(scope, path)
+
+ # Extract client IP for MCP access control
+ _client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope))
+
verbose_logger.debug(
f"MCP request mcp_servers (header/path): {mcp_servers}"
)
@@ -1830,12 +2008,12 @@ if MCP_AVAILABLE:
)
# https://datatracker.ietf.org/doc/html/rfc9728#name-www-authenticate-response
for server_name in mcp_servers or []:
- server = global_mcp_server_manager.get_mcp_server_by_name(server_name)
+ server = global_mcp_server_manager.get_mcp_server_by_name(
+ server_name, client_ip=_client_ip
+ )
if server and server.auth_type == MCPAuth.oauth2 and not oauth2_headers:
- from starlette.requests import Request
-
- request = Request(scope)
- base_url = str(request.base_url).rstrip("/")
+ request = StarletteRequest(scope)
+ base_url = get_request_base_url(request)
authorization_uri = (
f"Bearer authorization_uri="
@@ -1848,6 +2026,19 @@ if MCP_AVAILABLE:
headers={"www-authenticate": authorization_uri},
)
+ # Inject masked debug headers when client sends x-litellm-mcp-debug: true
+ _debug_headers = MCPDebug.maybe_build_debug_headers(
+ raw_headers=raw_headers,
+ scope=dict(scope),
+ mcp_servers=mcp_servers,
+ mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
+ oauth2_headers=oauth2_headers,
+ client_ip=_client_ip,
+ )
+ if _debug_headers:
+ send = MCPDebug.wrap_send_with_debug_headers(send, _debug_headers)
+
# Set the auth context variable for easy access in MCP functions
set_auth_context(
user_api_key_auth=user_api_key_auth,
@@ -1856,6 +2047,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers=mcp_server_auth_headers,
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
+ client_ip=_client_ip,
)
# Ensure session managers are initialized
@@ -1864,13 +2056,21 @@ if MCP_AVAILABLE:
# Give it a moment to start up
await asyncio.sleep(0.1)
+ # Handle stale session IDs - either strip them for reconnection
+ # or return success for idempotent DELETE operations
+ handled = await _handle_stale_mcp_session(scope, receive, send, session_manager)
+ if handled:
+ # Request was fully handled (e.g., DELETE on non-existent session)
+ return
+
await session_manager.handle_request(scope, receive, send)
+ except HTTPException:
+ # Re-raise HTTP exceptions to preserve status codes and details
+ raise
except Exception as e:
- raise e
verbose_logger.exception(f"Error handling MCP request: {e}")
- # Instead of re-raising, try to send a graceful error response
+ # Try to send a graceful error response for non-HTTP exceptions
try:
- # Send a proper HTTP error response instead of letting the exception bubble up
from starlette.responses import JSONResponse
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
@@ -1898,6 +2098,10 @@ if MCP_AVAILABLE:
oauth2_headers,
raw_headers,
) = await extract_mcp_auth_context(scope, path)
+
+ # Extract client IP for MCP access control
+ _sse_client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope))
+
verbose_logger.debug(
f"MCP request mcp_servers (header/path): {mcp_servers}"
)
@@ -1911,6 +2115,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers=mcp_server_auth_headers,
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
+ client_ip=_sse_client_ip,
)
if not _SESSION_MANAGERS_INITIALIZED:
@@ -1974,6 +2179,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]] = None,
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
+ client_ip: Optional[str] = None,
) -> None:
"""
Set the UserAPIKeyAuth in the auth context variable.
@@ -1983,6 +2189,7 @@ if MCP_AVAILABLE:
mcp_auth_header: MCP auth header to be passed to the MCP server (deprecated)
mcp_servers: Optional list of server names and access groups to filter by
mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
+ client_ip: Client IP address for MCP access control
"""
auth_user = MCPAuthenticatedUser(
user_api_key_auth=user_api_key_auth,
@@ -1991,6 +2198,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers=mcp_server_auth_headers,
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
+ client_ip=client_ip,
)
auth_context_var.set(auth_user)
@@ -2002,14 +2210,15 @@ if MCP_AVAILABLE:
Optional[Dict[str, Dict[str, str]]],
Optional[Dict[str, str]],
Optional[Dict[str, str]],
+ Optional[str],
]
):
"""
Get the UserAPIKeyAuth from the auth context variable.
Returns:
- Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[Dict[str, str]]]:
- UserAPIKeyAuth object, MCP auth header (deprecated), MCP servers (can include access groups), and server-specific auth headers
+ Tuple containing: UserAPIKeyAuth, MCP auth header (deprecated),
+ MCP servers, server-specific auth headers, OAuth2 headers, raw headers, client IP
"""
auth_user = auth_context_var.get()
if auth_user and isinstance(auth_user, MCPAuthenticatedUser):
@@ -2020,8 +2229,9 @@ if MCP_AVAILABLE:
auth_user.mcp_server_auth_headers,
auth_user.oauth2_headers,
auth_user.raw_headers,
+ auth_user.client_ip,
)
- return None, None, None, None, None, None
+ return None, None, None, None, None, None, None
########################################################
############ End of Auth Context Functions #############
diff --git a/litellm/proxy/_experimental/mcp_server/utils.py b/litellm/proxy/_experimental/mcp_server/utils.py
index d801b312aac..8189f212bcb 100644
--- a/litellm/proxy/_experimental/mcp_server/utils.py
+++ b/litellm/proxy/_experimental/mcp_server/utils.py
@@ -1,7 +1,7 @@
"""
MCP Server Utilities
"""
-from typing import Tuple, Any
+from typing import Any, Dict, Mapping, Optional, Tuple
import os
import importlib
@@ -137,3 +137,31 @@ def validate_mcp_server_name(
)
else:
raise Exception(error_message)
+
+
+def merge_mcp_headers(
+ *,
+ extra_headers: Optional[Mapping[str, str]] = None,
+ static_headers: Optional[Mapping[str, str]] = None,
+) -> Optional[Dict[str, str]]:
+ """Merge outbound HTTP headers for MCP calls.
+
+ This is used when calling out to external MCP servers (or OpenAPI-based MCP tools).
+
+ Merge rules:
+ - Start with `extra_headers` (typically OAuth2-derived headers)
+ - Overlay `static_headers` (user-configured per MCP server)
+
+ If both contain the same key, `static_headers` wins. This matches the existing
+ behavior in `MCPServerManager` where `server.static_headers` is applied after
+ any caller-provided headers.
+ """
+ merged: Dict[str, str] = {}
+
+ if extra_headers:
+ merged.update({str(k): str(v) for k, v in extra_headers.items()})
+
+ if static_headers:
+ merged.update({str(k): str(v) for k, v in static_headers.items()})
+
+ return merged or None
diff --git a/litellm/proxy/_experimental/out/404/index.html b/litellm/proxy/_experimental/out/404/index.html
new file mode 100644
index 00000000000..c73aba563bc
--- /dev/null
+++ b/litellm/proxy/_experimental/out/404/index.html
@@ -0,0 +1 @@
+404: This page could not be found.LiteLLM Dashboard