The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Litellm sameer oct staging (#15806)
Sameer Kankute0f9996a4d0c3
diff --git a/docs/my-website/docs/providers/azure/videos.md b/docs/my-website/docs/providers/azure/videos.mdnew file mode 100644index 00000000000..22e714a8ecf--- /dev/null+++ b/docs/my-website/docs/providers/azure/videos.md@@ -0,0 +1,290 @@+import Tabs from '@theme/Tabs';+import TabItem from '@theme/TabItem';++# Azure Video Generation++LiteLLM supports Azure OpenAI's video generation models including Sora with full end-to-end integration.++| Property | Details |+|-------|-------|+| Description | Azure OpenAI's video generation models including Sora-2 |+| Provider Route on LiteLLM | `azure/` |+| Supported Models | `sora-2` |+| Cost Tracking | ✅ Duration-based pricing ($0.10/second) |+| Logging Support | ✅ Full request/response logging |+| Guardrails Support | ✅ Content moderation and safety checks |+| Proxy Server Support | ✅ Full proxy integration with virtual keys |+| Spend Management | ✅ Budget tracking and rate limiting |+| Link to Provider Doc | [Azure OpenAI Video Generation ↗](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/concepts/video-generation) |++## Quick Start++### Required API Keys++```python+import os+os.environ["AZURE_OPENAI_API_KEY"] = "your-azure-api-key"+os.environ["AZURE_OPENAI_API_BASE"] = "https://your-resource.openai.azure.com/"+os.environ["AZURE_OPENAI_API_VERSION"] = "2024-02-15-preview"+```++### Basic Usage++```python+from litellm import video_generation, video_status, video_retrieval+import os+import time++os.environ["AZURE_OPENAI_API_KEY"] = "your-azure-api-key"+os.environ["AZURE_OPENAI_API_BASE"] = "https://your-resource.openai.azure.com/"+os.environ["AZURE_OPENAI_API_VERSION"] = "2024-02-15-preview"++# Generate video+response = video_generation(+ model="azure/sora-2",+ prompt="A cat playing with a ball of yarn in a sunny garden",+ seconds="8",+ size="720x1280"+)++print(f"Video ID: {response.id}")+print(f"Initial Status: {response.status}")++# Check status until video is ready+while True:+ status_response = video_status(+ video_id=response.id,+ model="azure/sora-2"+ )++ print(f"Current Status: {status_response.status}")++ if status_response.status == "completed":+ break+ elif status_response.status == "failed":+ print("Video generation failed")+ break++ time.sleep(10) # Wait 10 seconds before checking again++# Download video content when ready+video_bytes = video_retrieval(+ video_id=response.id,+ model="azure/sora-2"+)++# Save to file+with open("generated_video.mp4", "wb") as f:+ f.write(video_bytes)+```++## Usage - LiteLLM Proxy Server++Here's how to call Azure video generation models with the LiteLLM Proxy Server++### 1. Save key in your environment++```bash+export AZURE_OPENAI_API_KEY="your-azure-api-key"+export AZURE_OPENAI_API_BASE="https://your-resource.openai.azure.com/"+export AZURE_OPENAI_API_VERSION="2024-02-15-preview"+```++### 2. Start the proxy++<Tabs>+<TabItem value="config" label="config.yaml">++```yaml+model_list:+ - model_name: azure-sora-2+ litellm_params:+ model: azure/sora-2+ api_key: os.environ/AZURE_OPENAI_API_KEY+ api_base: os.environ/AZURE_OPENAI_API_BASE+ api_version: "2024-02-15-preview"+```++</TabItem>+<TabItem value="cli" label="CLI">++```bash+$ litellm --model azure/sora-2++# Server running on http://0.0.0.0:4000+```++</TabItem>++</Tabs>++### 3. Test it++<Tabs>+<TabItem value="Curl" label="Curl Request">++```shell+curl --location 'http://0.0.0.0:4000/videos/generations' \+--header 'Content-Type: application/json' \+--header 'Authorization: Bearer sk-1234' \+--data '{+ "model": "azure-sora-2",+ "prompt": "A cat playing with a ball of yarn in a sunny garden",+ "seconds": "8",+ "size": "720x1280"+}'+```++</TabItem>+<TabItem value="openai" label="OpenAI v1.0.0+">++```python+import openai+client = openai.OpenAI(+ api_key="anything",+ base_url="http://0.0.0.0:4000"+)++# request sent to model set on litellm proxy, `litellm --model`+response = client.videos.generations.create(+ model="azure-sora-2",+ prompt="A cat playing with a ball of yarn in a sunny garden",+ seconds="8",+ size="720x1280"+)++print(response)+```++</TabItem>+</Tabs>++## Supported Models++| Model Name |+|------------|+| sora-2 |+|sora-2-pro |+|sora-2-pro-high-res|+++## Logging & Observability++### Request/Response Logging++All video generation requests are automatically logged with:++- **Request details**: prompt, model, duration, size+- **Response details**: video ID, status, creation time+- **Cost tracking**: duration-based pricing calculation+- **Performance metrics**: request latency, processing time++### Logging Providers++Video generation works with all LiteLLM logging providers:++- **Datadog**: Real-time monitoring and alerting+- **Helicone**: Request tracing and debugging+- **LangSmith**: LangChain integration and tracing+- **Custom webhooks**: Send logs to your own endpoints++**Example: Enable Datadog logging**++```yaml+general_settings:+ alerting: ["datadog"]+ datadog_api_key: os.environ/DATADOG_API_KEY+```+++## Video Generation Parameters++- `prompt` (required): Text description of the desired video+- `model` (optional): Model to use, defaults to "azure/sora-2"+- `seconds` (optional): Video duration in seconds (e.g., "8", "16")+- `size` (optional): Video dimensions (e.g., "720x1280", "1280x720")+- `input_reference` (optional): Reference image for video editing+- `user` (optional): User identifier for tracking++## Video Content Retrieval++```python+# Download video content+video_bytes = video_retrieval(+ video_id="video_1234567890",+ model="azure/sora-2"+)++# Save to file+with open("video.mp4", "wb") as f:+ f.write(video_bytes)+```++## Complete Workflow++```python+import litellm+import time++def generate_and_download_video(prompt):+ # Step 1: Generate video+ response = litellm.video_generation(+ prompt=prompt,+ model="azure/sora-2",+ seconds="8",+ size="720x1280"+ )++ video_id = response.id+ print(f"Video ID: {video_id}")++ # Step 2: Wait for processing (in practice, poll status)+ time.sleep(30)++ # Step 3: Download video+ video_bytes = litellm.video_retrieval(+ video_id=video_id,+ model="azure/sora-2"+ )++ # Step 4: Save to file+ with open(f"video_{video_id}.mp4", "wb") as f:+ f.write(video_bytes)++ return f"video_{video_id}.mp4"++# Usage+video_file = generate_and_download_video(+ "A cat playing with a ball of yarn in a sunny garden"+)+```++## Video Remix (Video Editing)++```python+# Video editing with reference image+response = litellm.video_remix(+ prompt="Make the cat jump higher",+ input_reference=open("path/to/image.jpg", "rb"), # Reference image as file object+ model="azure/sora-2",+ seconds="8"+)++print(f"Video ID: {response.id}")+```++## Error Handling++```python+from litellm.exceptions import BadRequestError, AuthenticationError++try:+ response = video_generation(+ prompt="A cat playing with a ball of yarn",+ model="azure/sora-2"+ )+except AuthenticationError as e:+ print(f"Authentication failed: {e}")+except BadRequestError as e:+ print(f"Bad request: {e}")+```diff --git a/docs/my-website/docs/providers/bedrock.md b/docs/my-website/docs/providers/bedrock.mdindex 28cae80cc42..9429b6dad43 100644--- a/docs/my-website/docs/providers/bedrock.md+++ b/docs/my-website/docs/providers/bedrock.md@@ -7,7 +7,7 @@ ALL Bedrock models (Anthropic, Meta, Deepseek, Mistral, Amazon, etc.) are Suppor| Property | Details ||-------|-------|| 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) |+| 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) || 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` || Rerank Endpoint | `/rerank` |@@ -1734,7 +1734,69 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \</TabItem></Tabs>+### Qwen3 Imported Models+| Property | Details |+|----------|---------|+| Provider Route | `bedrock/qwen3/{model_arn}` |+| Provider Documentation | [Bedrock Imported Models](https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-import-model.html), [Qwen3 Models](https://aws.amazon.com/about-aws/whats-new/2025/09/qwen3-models-fully-managed-amazon-bedrock/) |++<Tabs>+<TabItem value="sdk" label="SDK">++```python+from litellm import completion+import os++response = completion(+ model="bedrock/qwen3/arn:aws:bedrock:us-east-1:086734376398:imported-model/your-qwen3-model", # bedrock/qwen3/{your-model-arn}+ messages=[{"role": "user", "content": "Tell me a joke"}],+ max_tokens=100,+ temperature=0.7+)+```++</TabItem>++<TabItem value="proxy" label="Proxy">++**1. Add to config**++```yaml+model_list:+ - model_name: Qwen3-32B+ litellm_params:+ model: bedrock/qwen3/arn:aws:bedrock:us-east-1:086734376398:imported-model/your-qwen3-model++```++**2. Start proxy**++```bash+litellm --config /path/to/config.yaml++# RUNNING at http://0.0.0.0:4000+```++**3. Test it!**++```bash+curl --location 'http://0.0.0.0:4000/chat/completions' \+ --header 'Authorization: Bearer sk-1234' \+ --header 'Content-Type: application/json' \+ --data '{+ "model": "Qwen3-32B", # 👈 the 'model_name' in config+ "messages": [+ {+ "role": "user",+ "content": "what llm are you"+ }+ ],+ }'+```++</TabItem>+</Tabs>### OpenAI GPT OSSdiff --git a/docs/my-website/docs/providers/cohere.md b/docs/my-website/docs/providers/cohere.mdindex 9c424010570..1c3181d1884 100644--- a/docs/my-website/docs/providers/cohere.md+++ b/docs/my-website/docs/providers/cohere.md@@ -15,30 +15,51 @@ os.environ["COHERE_API_KEY"] = ""### LiteLLM Python SDK+#### Cohere v2 API (Default)+```python showLineNumbersfrom litellm import completion## set ENV variablesos.environ["COHERE_API_KEY"] = "cohere key"-# cohere call+# cohere v2 call+response = completion(+ model="cohere_chat/command-a-03-2025",+ messages = [{ "content": "Hello, how are you?","role": "user"}]+)+```++#### Cohere v1 API++To use the Cohere v1/chat API, prefix your model name with `cohere_chat/v1/`:++```python showLineNumbers+from litellm import completion++## set ENV variables+os.environ["COHERE_API_KEY"] = "cohere key"++# cohere v1 callresponse = completion(- model="command-r",+ model="cohere_chat/v1/command-a-03-2025",messages = [{ "content": "Hello, how are you?","role": "user"}])```#### Streaming+**Cohere v2 Streaming:**+```python showLineNumbersfrom litellm import completion## set ENV variablesos.environ["COHERE_API_KEY"] = "cohere key"-# cohere call+# cohere v2 streamingresponse = completion(- model="command-r",+ model="cohere_chat/command-a-03-2025",messages = [{ "content": "Hello, how are you?","role": "user"}],stream=True)@@ -48,6 +69,25 @@ for chunk in response:```+**Cohere v1 Streaming:**++```python showLineNumbers+from litellm import completion++## set ENV variables+os.environ["COHERE_API_KEY"] = "cohere key"++# cohere v1 streaming+response = completion(+ model="cohere_chat/v1/command-a-03-2025",+ messages = [{ "content": "Hello, how are you?","role": "user"}],+ stream=True+)++for chunk in response:+ print(chunk)+```+## Usage with LiteLLM Proxy@@ -63,11 +103,21 @@ export COHERE_API_KEY="your-api-key"Define the cohere models you want to use in the config.yaml+**For Cohere v1 models:**```yaml showLineNumbersmodel_list:- model_name: command-a-03-2025litellm_params:- model: command-a-03-2025+ model: cohere_chat/v1/command-a-03-2025+ api_key: "os.environ/COHERE_API_KEY"+```++**For Cohere v2 models:**+```yaml showLineNumbers+model_list:+ - model_name: command-a-03-2025-v2+ litellm_params:+ model: cohere_chat/command-a-03-2025api_key: "os.environ/COHERE_API_KEY"```@@ -78,9 +128,8 @@ litellm --config /path/to/config.yaml### 3. Test it-<Tabs>-<TabItem value="Curl" label="Curl Request">+<TabItem value="v1-curl" label="Cohere v1 - Curl Request">```shell showLineNumberscurl --location 'http://0.0.0.0:4000/chat/completions' \@@ -98,7 +147,25 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \'```</TabItem>-<TabItem value="openai" label="OpenAI v1.0.0+">+<TabItem value="v2-curl" label="Cohere v2 - Curl Request">++```shell showLineNumbers+curl --location 'http://0.0.0.0:4000/chat/completions' \+--header 'Content-Type: application/json' \+--header 'Authorization: Bearer <your-litellm-api-key>' \+--data ' {+ "model": "command-a-03-2025-v2",+ "messages": [+ {+ "role": "user",+ "content": "what llm are you"+ }+ ]+ }+'+```+</TabItem>+<TabItem value="v1-openai" label="Cohere v1 - OpenAI SDK">```python showLineNumbersimport openai@@ -107,7 +174,7 @@ client = openai.OpenAI(base_url="http://0.0.0.0:4000")-# request sent to model set on litellm proxy+# request sent to cohere v1 modelresponse = client.chat.completions.create(model="command-a-03-2025", messages = [{"role": "user",@@ -116,7 +183,26 @@ response = client.chat.completions.create(model="command-a-03-2025", messages =])print(response)+```+</TabItem>+<TabItem value="v2-openai" label="Cohere v2 - OpenAI SDK">++```python showLineNumbers+import openai+client = openai.OpenAI(+ api_key="anything",+ base_url="http://0.0.0.0:4000"+)+# request sent to cohere v2 model+response = client.chat.completions.create(model="command-a-03-2025-v2", messages = [+ {+ "role": "user",+ "content": "this is a test request, write a short poem"+ }+])++print(response)```</TabItem></Tabs>diff --git a/docs/my-website/docs/providers/openai.md b/docs/my-website/docs/providers/openai.mdindex e8fd076b51f..f9831c6d8be 100644--- a/docs/my-website/docs/providers/openai.md+++ b/docs/my-website/docs/providers/openai.md@@ -840,4 +840,10 @@ response = completion(model="gpt-5-pro",messages=[{"role": "user", "content": "Solve this complex reasoning problem..."}])-```\ No newline at end of file+```++## Video Generation++LiteLLM supports OpenAI's video generation models including Sora.++For detailed documentation on video generation, see [OpenAI Video Generation →](./openai/video_generation.md)\ No newline at end of filediff --git a/docs/my-website/docs/providers/openai/videos.md b/docs/my-website/docs/providers/openai/videos.mdnew file mode 100644index 00000000000..4dc18da77bd--- /dev/null+++ b/docs/my-website/docs/providers/openai/videos.md@@ -0,0 +1,143 @@+import Tabs from '@theme/Tabs';+import TabItem from '@theme/TabItem';++# OpenAI Video Generation++LiteLLM supports OpenAI's video generation models including Sora.++## Quick Start++### Required API Keys++```python+import os+os.environ["OPENAI_API_KEY"] = "your-api-key"+```++### Basic Usage++```python+from litellm import video_generation, video_retrieval+import os++os.environ["OPENAI_API_KEY"] = "your-api-key"++# Generate a video+response = video_generation(+ prompt="A cat playing with a ball of yarn in a sunny garden",+ model="sora-2",+ seconds="8",+ size="720x1280"+)++print(f"Video ID: {response.id}")+print(f"Status: {response.status}")++# Download video content when ready+video_bytes = video_retrieval(+ video_id=response.id,+ model="sora-2"+)++# Save to file+with open("generated_video.mp4", "wb") as f:+ f.write(video_bytes)+```++## Supported Models++| Model Name | Description | Max Duration | Supported Sizes |+|------------|-------------|--------------|-----------------|+| sora-2 | OpenAI's latest video generation model | 8 seconds | 720x1280, 1280x720 |++## Video Generation Parameters++- `prompt` (required): Text description of the desired video+- `model` (optional): Model to use, defaults to "sora-2"+- `seconds` (optional): Video duration in seconds (e.g., "8", "16")+- `size` (optional): Video dimensions (e.g., "720x1280", "1280x720")+- `input_reference` (optional): Reference image for video editing+- `user` (optional): User identifier for tracking++## Video Content Retrieval++```python+# Download video content+video_bytes = video_retrieval(+ video_id="video_1234567890",+ model="sora-2"+)++# Save to file+with open("video.mp4", "wb") as f:+ f.write(video_bytes)+```++## Complete Workflow++```python+import litellm+import time++def generate_and_download_video(prompt):+ # Step 1: Generate video+ response = litellm.video_generation(+ prompt=prompt,+ model="sora-2",+ seconds="8",+ size="720x1280"+ )++ video_id = response.id+ print(f"Video ID: {video_id}")++ # Step 2: Wait for processing (in practice, poll status)+ time.sleep(30)++ # Step 3: Download video+ video_bytes = litellm.video_retrieval(+ video_id=video_id,+ model="sora-2"+ )++ # Step 4: Save to file+ with open(f"video_{video_id}.mp4", "wb") as f:+ f.write(video_bytes)++ return f"video_{video_id}.mp4"++# Usage+video_file = generate_and_download_video(+ "A cat playing with a ball of yarn in a sunny garden"+)+```++## Video Editing with Reference Images++```python+# Video editing with reference image+response = litellm.video_generation(+ prompt="Make the cat jump higher",+ input_reference="path/to/image.jpg", # Reference image+ model="sora-2",+ seconds="8"+)++print(f"Video ID: {response.id}")+```++## Error Handling++```python+from litellm.exceptions import BadRequestError, AuthenticationError++try:+ response = video_generation(+ prompt="A cat playing with a ball of yarn",+ model="sora-2"+ )+except AuthenticationError as e:+ print(f"Authentication failed: {e}")+except BadRequestError as e:+ print(f"Bad request: {e}")+```diff --git a/docs/my-website/docs/providers/vertex_batch.md b/docs/my-website/docs/providers/vertex_batch.mdindex 046c60f2ebd..730f31be87d 100644--- a/docs/my-website/docs/providers/vertex_batch.md+++ b/docs/my-website/docs/providers/vertex_batch.md@@ -162,7 +162,7 @@ Check the status of your batch job. The batch will progress through states: `val```python showLineNumbers title="retrieve_batch.py"retrieved_batch = oai_client.batches.retrieve(batch_id=create_batch_response.id, # Created batch id, e.g. 7814463557919047680- extra_body={"custom_llm_provider": "vertex_ai"}+ extra_query={"custom_llm_provider": "vertex_ai"})print(f"Batch status: {retrieved_batch.status}")diff --git a/docs/my-website/docs/vertex_batch_passthrough.md b/docs/my-website/docs/vertex_batch_passthrough.mdnew file mode 100644index 00000000000..3203d7d792a--- /dev/null+++ b/docs/my-website/docs/vertex_batch_passthrough.md@@ -0,0 +1,160 @@+import Tabs from '@theme/Tabs';+import TabItem from '@theme/TabItem';++# /batchPredictionJobs++LiteLLM supports Vertex AI batch prediction jobs through passthrough endpoints, allowing you to create and manage batch jobs directly through the proxy server.++## Features++- **Batch Job Creation**: Create batch prediction jobs using Vertex AI models+- **Cost Tracking**: Automatic cost calculation and usage tracking for batch operations+- **Status Monitoring**: Track job status and retrieve results+- **Model Support**: Works with all supported Vertex AI models (Gemini, Text Embedding)++## Cost Tracking Support++| Feature | Supported | Notes |+|---------|-----------|-------|+| Cost Tracking | ✅ | Automatic cost calculation for batch operations |+| Usage Monitoring | ✅ | Track token usage and costs across batch jobs |+| Logging | ✅ | Supported |++## Quick Start++1. **Configure your model** in the proxy configuration:++```yaml+model_list:+ - model_name: gemini-1.5-flash+ litellm_params:+ model: vertex_ai/gemini-1.5-flash+ vertex_project: your-project-id+ vertex_location: us-central1+ vertex_credentials: path/to/service-account.json+```++2. **Create a batch job**:++```bash+curl -X POST "http://localhost:4000/v1/projects/your-project/locations/us-central1/batchPredictionJobs" \+ -H "Authorization: Bearer your-api-key" \+ -H "Content-Type: application/json" \+ -d '{+ "displayName": "my-batch-job",+ "model": "projects/your-project/locations/us-central1/publishers/google/models/gemini-1.5-flash",+ "inputConfig": {+ "gcsSource": {+ "uris": ["gs://my-bucket/input.jsonl"]+ },+ "instancesFormat": "jsonl"+ },+ "outputConfig": {+ "gcsDestination": {+ "outputUriPrefix": "gs://my-bucket/output/"+ },+ "predictionsFormat": "jsonl"+ }+ }'+```++3. **Monitor job status**:++```bash+curl -X GET "http://localhost:4000/v1/projects/your-project/locations/us-central1/batchPredictionJobs/job-id" \+ -H "Authorization: Bearer your-api-key"+```++## Model Configuration++When configuring models for batch operations, use these naming conventions:++- **`model_name`**: Base model name (e.g., `gemini-1.5-flash`)+- **`model`**: Full LiteLLM identifier (e.g., `vertex_ai/gemini-1.5-flash`)++## Supported Models++- `gemini-1.5-flash` / `vertex_ai/gemini-1.5-flash`+- `gemini-1.5-pro` / `vertex_ai/gemini-1.5-pro`+- `gemini-2.0-flash` / `vertex_ai/gemini-2.0-flash`+- `gemini-2.0-pro` / `vertex_ai/gemini-2.0-pro`++## Advanced Usage++### Batch Job with Custom Parameters++```bash+curl -X POST "http://localhost:4000/v1/projects/your-project/locations/us-central1/batchPredictionJobs" \+ -H "Authorization: Bearer your-api-key" \+ -H "Content-Type: application/json" \+ -d '{+ "displayName": "advanced-batch-job",+ "model": "projects/your-project/locations/us-central1/publishers/google/models/gemini-1.5-pro",+ "inputConfig": {+ "gcsSource": {+ "uris": ["gs://my-bucket/advanced-input.jsonl"]+ },+ "instancesFormat": "jsonl"+ },+ "outputConfig": {+ "gcsDestination": {+ "outputUriPrefix": "gs://my-bucket/advanced-output/"+ },+ "predictionsFormat": "jsonl"+ },+ "labels": {+ "environment": "production",+ "team": "ml-engineering"+ }+ }'+```++### List All Batch Jobs++```bash+curl -X GET "http://localhost:4000/v1/projects/your-project/locations/us-central1/batchPredictionJobs" \+ -H "Authorization: Bearer your-api-key"+```++### Cancel a Batch Job++```bash+curl -X POST "http://localhost:4000/v1/projects/your-project/locations/us-central1/batchPredictionJobs/job-id:cancel" \+ -H "Authorization: Bearer your-api-key"+```++## Cost Tracking Details++LiteLLM provides comprehensive cost tracking for Vertex AI batch operations:++- **Token Usage**: Tracks input and output tokens for each batch request+- **Cost Calculation**: Automatically calculates costs based on current Vertex AI pricing+- **Usage Aggregation**: Aggregates costs across all requests in a batch job+- **Real-time Monitoring**: Monitor costs as batch jobs progress++The cost tracking works seamlessly with the `generateContent` API and provides detailed insights into your batch processing expenses.++## Error Handling++Common error scenarios and their solutions:++| Error | Description | Solution |+|-------|-------------|----------|+| `INVALID_ARGUMENT` | Invalid model or configuration | Verify model name and project settings |+| `PERMISSION_DENIED` | Insufficient permissions | Check Vertex AI IAM roles |+| `RESOURCE_EXHAUSTED` | Quota exceeded | Check Vertex AI quotas and limits |+| `NOT_FOUND` | Job or resource not found | Verify job ID and project configuration |++## Best Practices++1. **Use appropriate batch sizes**: Balance between processing efficiency and resource usage+2. **Monitor job status**: Regularly check job status to handle failures promptly+3. **Set up alerts**: Configure monitoring for job completion and failures+4. **Optimize costs**: Use cost tracking to identify optimization opportunities+5. **Test with small batches**: Validate your setup with small test batches first++## Related Documentation++- [Vertex AI Provider Documentation](./vertex.md)+- [General Batches API Documentation](../batches.md)+- [Cost Tracking and Monitoring](../observability/telemetry.md)diff --git a/docs/my-website/docs/videos.md b/docs/my-website/docs/videos.mdnew file mode 100644index 00000000000..dd96398f8d6--- /dev/null+++ b/docs/my-website/docs/videos.md@@ -0,0 +1,419 @@+# /videos++| Feature | Supported |+|---------|-----------|+| Cost Tracking | ✅ |+| Logging | ✅ (Full request/response logging) |+Fallbacks | ✅ (Between supported models) |+| Load Balancing | ✅ |+| Guardrails Support | ✅ Content moderation and safety checks |+| Proxy Server Support | ✅ Full proxy integration with virtual keys |+| Spend Management | ✅ Budget tracking and rate limiting |+| Supported Providers | `openai`, `azure` |++:::tip++LiteLLM follows the [OpenAI Video Generation API specification](https://platform.openai.com/docs/guides/video-generation)++:::++## **LiteLLM Python SDK Usage**+### Quick Start++```python+from litellm import video_generation, video_status, video_retrieval+import os+import time++os.environ["OPENAI_API_KEY"] = "sk-.."++# Generate video+response = video_generation(+ model="openai/sora-2",+ prompt="A cat playing with a ball of yarn in a sunny garden",+ seconds="8",+ size="720x1280"+)++print(f"Video ID: {response.id}")+print(f"Initial Status: {response.status}")++# Check status until video is ready+while True:+ status_response = video_status(+ video_id=response.id,+ model="openai/sora-2"+ )++ print(f"Current Status: {status_response.status}")++ if status_response.status == "completed":+ break+ elif status_response.status == "failed":+ print("Video generation failed")+ break++ time.sleep(10) # Wait 10 seconds before checking again++# Download video content when ready+video_bytes = video_retrieval(+ video_id=response.id,+ model="openai/sora-2"+)++# Save to file+with open("generated_video.mp4", "wb") as f:+ f.write(video_bytes)+```++### Async Usage++```python+from litellm import avideo_generation, avideo_status, avideo_retrieval+import os, asyncio++os.environ["OPENAI_API_KEY"] = "sk-.."++async def test_async_video():+ response = await avideo_generation(+ model="openai/sora-2",+ prompt="A cat playing with a ball of yarn in a sunny garden",+ seconds="8",+ size="720x1280"+ )++ print(f"Video ID: {response.id}")+ print(f"Initial Status: {response.status}")++ # Check status until video is ready+ while True:+ status_response = await avideo_status(+ video_id=response.id,+ model="openai/sora-2"+ )++ print(f"Current Status: {status_response.status}")++ if status_response.status == "completed":+ break+ elif status_response.status == "failed":+ print("Video generation failed")+ break++ await asyncio.sleep(10) # Wait 10 seconds before checking again++ # Download video content when ready+ video_bytes = await avideo_retrieval(+ video_id=response.id,+ model="openai/sora-2"+ )++ # Save to file+ with open("generated_video.mp4", "wb") as f:+ f.write(video_bytes)++asyncio.run(test_async_video())+```++### Video Status Checking++```python+from litellm import video_status++# Check the status of a video generation+status_response = video_status(+ video_id="video_1234567890",+ model="openai/sora-2"+)++print(f"Video Status: {status_response.status}")+print(f"Created At: {status_response.created_at}")+print(f"Model: {status_response.model}")++# Possible status values:+# - "queued": Video is in the queue+# - "processing": Video is being generated+# - "completed": Video is ready for download+# - "failed": Video generation failed+```++### Video Generation with Reference Image++```python+from litellm import video_generation++# Video generation with reference image+response = video_generation(+ model="openai/sora-2",+ prompt="A cat playing with a ball of yarn in a sunny garden",+ input_reference=open("path/to/image.jpg", "rb"), # Reference image as file object+ seconds="8",+ size="720x1280"+)++print(f"Video ID: {response.id}")+```++### Video Remix (Video Editing)++```python+from litellm import video_remix++# Video remix with reference image+response = video_remix(+ model="openai/sora-2",+ prompt="Make the cat jump higher",+ input_reference=open("path/to/image.jpg", "rb"), # Reference image as file object+ seconds="8"+)++print(f"Video ID: {response.id}")+```++### Optional Parameters++```python+response = video_generation(+ model="openai/sora-2",+ prompt="A cat playing with a ball of yarn in a sunny garden",+ seconds="8", # Video duration in seconds+ size="720x1280", # Video dimensions+ input_reference=open("path/to/image.jpg", "rb"), # Reference image as file object+ user="user_123" # User identifier for tracking+)+```++### Azure Video Generation++```python+from litellm import video_generation+import os++os.environ["AZURE_OPENAI_API_KEY"] = "your-azure-api-key"+os.environ["AZURE_OPENAI_API_BASE"] = "https://your-resource.openai.azure.com/"+os.environ["AZURE_OPENAI_API_VERSION"] = "2024-02-15-preview"++response = video_generation(+ model="azure/sora-2",+ prompt="A cat playing with a ball of yarn in a sunny garden",+ seconds="8",+ size="720x1280"+)++print(f"Video ID: {response.id}")+```++## **LiteLLM Proxy Usage**++LiteLLM provides OpenAI API compatible video endpoints for complete video generation workflow:++- `/videos/generations` - Generate new videos+- `/videos/remix` - Edit existing videos with reference images+- `/videos/status` - Check video generation status+- `/videos/retrieval` - Download completed videos++**Setup**++Add this to your litellm proxy config.yaml++```yaml+model_list:+ - model_name: sora-2+ litellm_params:+ model: openai/sora-2+ api_key: os.environ/OPENAI_API_KEY+ - model_name: azure-sora-2+ litellm_params:+ model: azure/sora-2+ api_key: os.environ/AZURE_OPENAI_API_KEY+ api_base: os.environ/AZURE_OPENAI_API_BASE+ api_version: "2024-02-15-preview"+```++Start litellm++```bash+litellm --config /path/to/config.yaml++# RUNNING on http://0.0.0.0:4000+```++Test video generation request++```bash+curl http://0.0.0.0:4000/videos/generations \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "model": "sora-2",+ "prompt": "A cat playing with a ball of yarn in a sunny garden",+ "seconds": "8",+ "size": "720x1280"+ }'+```++Test video status request++```bash+curl http://0.0.0.0:4000/videos/status \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "video_id": "video_1234567890",+ "model": "sora-2"+ }'+```++Test video retrieval request++```bash+curl http://0.0.0.0:4000/videos/retrieval \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "video_id": "video_1234567890",+ "model": "sora-2"+ }'+```++Test video remix request++```bash+curl http://0.0.0.0:4000/videos/remix \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: multipart/form-data" \+ -F 'model=sora-2' \+ -F 'prompt=Make the cat jump higher' \+ -F 'input_reference=@path/to/image.jpg' \+ -F 'seconds=8'+```++Test Azure video generation request++```bash+curl http://0.0.0.0:4000/videos/generations \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "model": "azure-sora-2",+ "prompt": "A cat playing with a ball of yarn in a sunny garden",+ "seconds": "8",+ "size": "720x1280"+ }'+```++## **Request/Response Format**++:::info++LiteLLM follows the **OpenAI Video Generation API specification**.++See the [official OpenAI Video Generation documentation](https://platform.openai.com/docs/guides/video-generation) for complete details.++:::++### Example Request++```python+{+ "model": "openai/sora-2",+ "prompt": "A cat playing with a ball of yarn in a sunny garden",+ "seconds": "8",+ "size": "720x1280",+ "user": "user_123"+}+```++### Request Parameters++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `model` | string | Yes | The video generation model to use (e.g., `"openai/sora-2"`) |+| `prompt` | string | Yes | Text description of the desired video |+| `seconds` | string | No | Video duration in seconds (e.g., "8", "16") |+| `size` | string | No | Video dimensions (e.g., "720x1280", "1280x720") |+| `input_reference` | file object | No | Reference image for video generation or editing (both generation and remix) |+| `user` | string | No | User identifier for tracking |+| `video_id` | string | Yes (status/retrieval) | Video ID for status checking or retrieval |++#### Video Generation Request Example++**For video generation:**+```json+{+ "model": "sora-2",+ "prompt": "A cat playing with a ball of yarn in a sunny garden",+ "seconds": "8",+ "size": "720x1280"+}+```++**For video generation with reference image:**+```python+{+ "model": "sora-2",+ "prompt": "A cat playing with a ball of yarn in a sunny garden",+ "input_reference": open("path/to/image.jpg", "rb"), # File object+ "seconds": "8",+ "size": "720x1280"+}+```++**For video status check:**+```json+{+ "video_id": "video_1234567890",+ "model": "sora-2"+}+```++**For video retrieval:**+```json+{+ "video_id": "video_1234567890",+ "model": "sora-2"+}+```++### Response Format++The response follows OpenAI's video generation format with the following structure:++```json+{+ "id": "video_1234567890",+ "object": "video",+ "status": "queued",+ "created_at": 1712697600,+ "model": "sora-2",+ "size": "720x1280",+ "seconds": "8",+ "usage": {+ "prompt_tokens": 0,+ "completion_tokens": 0,+ "total_tokens": 0,+ "duration_seconds": 8.0+ }+}+```++#### Response Fields++| Field | Type | Description |+|-------|------|-------------|+| `id` | string | Unique identifier for the video |+| `object` | string | Always `"video"` for video responses |+| `status` | string | Video processing status (`"queued"`, `"processing"`, `"completed"`) |+| `created_at` | integer | Unix timestamp when the video was created |+| `model` | string | The model used for video generation |+| `size` | string | Video dimensions |+| `seconds` | string | Video duration in seconds |+| `usage` | object | Token usage and duration information |+++## **Supported Providers**++| Provider | Link to Usage |+|-------------|--------------------|+| OpenAI | [Usage](providers/openai/videos) |+| Azure | [Usage](providers/azure/videos) |\ No newline at end of filediff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.pyindex 4b1bb024ac6..d4ee4042b1a 100644--- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py+++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py@@ -57,7 +57,6 @@ class CheckBatchCost:"file_purpose": "batch",})-completed_jobs = []for job in jobs:@@ -139,7 +138,7 @@ class CheckBatchCost:custom_llm_provider = deployment_info.litellm_params.custom_llm_providerlitellm_model_name = deployment_info.litellm_params.model- _, llm_provider, _, _ = get_llm_provider(+ model_name, llm_provider, _, _ = get_llm_provider(model=litellm_model_name,custom_llm_provider=custom_llm_provider,)@@ -148,9 +147,9 @@ class CheckBatchCost:await calculate_batch_cost_and_usage(file_content_dictionary=file_content_as_dict,custom_llm_provider=llm_provider, # type: ignore+ model_name=model_name,))-logging_obj = LiteLLMLogging(model=batch_models[0],messages=[{"role": "user", "content": "<retrieve_batch>"}],diff --git a/litellm/__init__.py b/litellm/__init__.pyindex 9df8daebc09..b3a57b0ac75 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -105,7 +105,7 @@ if litellm_mode == "DEV":# Register async client cleanup to prevent resource leaksregister_async_client_cleanup()####################################################-if set_verbose == True:+if set_verbose:_turn_on_debug()####################################################### Callbacks /Logging / Success / Failure Handlers #####@@ -981,6 +981,9 @@ all_embedding_models = (####### IMAGE GENERATION MODELS ###################openai_image_generation_models = ["dall-e-2", "dall-e-3"]+####### VIDEO GENERATION MODELS ###################+openai_video_generation_models = ["sora-2"]+from .timeout import timeoutfrom .cost_calculator import completion_costfrom litellm.litellm_core_utils.litellm_logging import Logging, modify_integration@@ -1139,6 +1142,9 @@ from .llms.bedrock.chat.invoke_transformations.amazon_ai21_transformation importfrom .llms.bedrock.chat.invoke_transformations.amazon_nova_transformation import (AmazonInvokeNovaConfig,)+from .llms.bedrock.chat.invoke_transformations.amazon_qwen3_transformation import (+ AmazonQwen3Config,+)from .llms.bedrock.chat.invoke_transformations.anthropic_claude2_transformation import (AmazonAnthropicConfig,)@@ -1175,6 +1181,7 @@ from .llms.bedrock.embed.amazon_titan_v2_transformation import (AmazonTitanV2Config,)from .llms.cohere.chat.transformation import CohereChatConfig+from .llms.cohere.chat.v2_transformation import CohereV2ChatConfigfrom .llms.bedrock.embed.cohere_transformation import BedrockCohereEmbeddingConfigfrom .llms.bedrock.embed.twelvelabs_marengo_transformation import TwelveLabsMarengoEmbeddingConfigfrom .llms.openai.openai import OpenAIConfig, MistralEmbeddingConfig@@ -1207,7 +1214,6 @@ from .llms.openai.chat.o_series_transformation import (OpenAIOSeriesConfig,)-from .llms.snowflake.chat.transformation import SnowflakeConfigfrom .llms.gradient_ai.chat.transformation import GradientAIConfigopenaiOSeriesConfig = OpenAIOSeriesConfig()@@ -1243,7 +1249,6 @@ from .llms.cerebras.chat import CerebrasConfigfrom .llms.baseten.chat import BasetenConfigfrom .llms.sambanova.chat import SambanovaConfigfrom .llms.sambanova.embedding.transformation import SambaNovaEmbeddingConfig-from .llms.ai21.chat.transformation import AI21ChatConfigfrom .llms.fireworks_ai.chat.transformation import FireworksAIConfigfrom .llms.fireworks_ai.completion.transformation import FireworksAITextCompletionConfigfrom .llms.fireworks_ai.audio_transcription.transformation import (@@ -1330,6 +1335,7 @@ from .router import Routerfrom .assistants.main import *from .batches.main import *from .images.main import *+from .videos.main import *from .batch_completion.main import * # type: ignorefrom .rerank_api.main import *from .llms.anthropic.experimental_pass_through.messages.handler import *diff --git a/litellm/batches/batch_utils.py b/litellm/batches/batch_utils.pyindex 814851e560b..027c0b219c8 100644--- a/litellm/batches/batch_utils.py+++ b/litellm/batches/batch_utils.py@@ -1,5 +1,5 @@import json-from typing import Any, List, Literal, Tuple+from typing import Any, List, Literal, Tuple, Optionalimport litellmfrom litellm._logging import verbose_logger@@ -10,21 +10,22 @@ from litellm.types.utils import CallTypes, Usageasync def calculate_batch_cost_and_usage(file_content_dictionary: List[dict],custom_llm_provider: Literal["openai", "azure", "vertex_ai"],+ model_name: Optional[str] = None,) -> Tuple[float, Usage, List[str]]:"""Calculate the cost and usage of a batch"""- # Calculate costs and usagebatch_cost = _batch_cost_calculator(custom_llm_provider=custom_llm_provider,file_content_dictionary=file_content_dictionary,+ model_name=model_name,)batch_usage = _get_batch_job_total_usage_from_file_content(file_content_dictionary=file_content_dictionary,custom_llm_provider=custom_llm_provider,+ model_name=model_name,)-- batch_models = _get_batch_models_from_file_content(file_content_dictionary)+ batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name)return batch_cost, batch_usage, batch_models@@ -32,6 +33,7 @@ async def calculate_batch_cost_and_usage(async def _handle_completed_batch(batch: Batch,custom_llm_provider: Literal["openai", "azure", "vertex_ai"],+ model_name: Optional[str] = None,) -> Tuple[float, Usage, List[str]]:"""Helper function to process a completed batch and handle logging"""# Get batch results@@ -43,23 +45,28 @@ async def _handle_completed_batch(batch_cost = _batch_cost_calculator(custom_llm_provider=custom_llm_provider,file_content_dictionary=file_content_dictionary,+ model_name=model_name,)batch_usage = _get_batch_job_total_usage_from_file_content(file_content_dictionary=file_content_dictionary,custom_llm_provider=custom_llm_provider,+ model_name=model_name,)- batch_models = _get_batch_models_from_file_content(file_content_dictionary)+ batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name)return batch_cost, batch_usage, batch_modelsdef _get_batch_models_from_file_content(file_content_dictionary: List[dict],+ model_name: Optional[str] = None,) -> List[str]:"""Get the models from the file content"""+ if model_name:+ return [model_name]batch_models = []for _item in file_content_dictionary:if _batch_response_was_successful(_item):@@ -73,12 +80,18 @@ def _get_batch_models_from_file_content(def _batch_cost_calculator(file_content_dictionary: List[dict],custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",+ model_name: Optional[str] = None,) -> float:"""Calculate the cost of a batch based on the output file id"""- if custom_llm_provider == "vertex_ai":- raise ValueError("Vertex AI does not support file content retrieval")+ # Handle Vertex AI with specialized method+ if custom_llm_provider == "vertex_ai" and model_name:+ batch_cost, _ = calculate_vertex_ai_batch_cost_and_usage(file_content_dictionary, model_name)+ verbose_logger.debug("vertex_ai_total_cost=%s", batch_cost)+ return batch_cost++ # For other providers, use the existing logictotal_cost = _get_batch_job_cost_from_file_content(file_content_dictionary=file_content_dictionary,custom_llm_provider=custom_llm_provider,@@ -87,6 +100,87 @@ def _batch_cost_calculator(return total_cost+def calculate_vertex_ai_batch_cost_and_usage(+ vertex_ai_batch_responses: List[dict],+ model_name: Optional[str] = None,+) -> Tuple[float, Usage]:+ """+ Calculate both cost and usage from Vertex AI batch responses+ """+ total_cost = 0.0+ total_tokens = 0+ prompt_tokens = 0+ completion_tokens = 0++ for response in vertex_ai_batch_responses:+ if response.get("status") == "JOB_STATE_SUCCEEDED": # Check if response was successful+ # Transform Vertex AI response to OpenAI format if needed+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig+ from litellm import ModelResponse+ from litellm.litellm_core_utils.litellm_logging import Logging+ from litellm.types.utils import CallTypes+ from litellm._uuid import uuid+ import httpx+ import time++ # Create required arguments for the transformation method+ model_response = ModelResponse()++ # Ensure model_name is not None+ actual_model_name = model_name or "gemini-2.5-flash"++ # Create a real LiteLLM logging object+ logging_obj = Logging(+ model=actual_model_name,+ messages=[{"role": "user", "content": "batch_request"}],+ stream=False,+ call_type=CallTypes.aretrieve_batch,+ start_time=time.time(),+ litellm_call_id="batch_" + str(uuid.uuid4()),+ function_id="batch_processing",+ litellm_trace_id=str(uuid.uuid4()),+ kwargs={"optional_params": {}}+ )++ # Add the optional_params attribute that the Vertex AI transformation expects+ logging_obj.optional_params = {}+ raw_response = httpx.Response(200) # Mock response object++ openai_format_response = VertexGeminiConfig()._transform_google_generate_content_to_openai_model_response(+ completion_response=response["response"],+ model_response=model_response,+ model=actual_model_name,+ logging_obj=logging_obj,+ raw_response=raw_response,+ )++ # Calculate cost using existing function+ cost = litellm.completion_cost(+ completion_response=openai_format_response,+ custom_llm_provider="vertex_ai",+ call_type=CallTypes.aretrieve_batch.value,+ )+ total_cost += cost++ # Extract usage from the transformed response+ if hasattr(openai_format_response, 'usage') and openai_format_response.usage:+ usage = openai_format_response.usage+ else:+ # Fallback: create usage from response dict+ response_dict = openai_format_response.dict() if hasattr(openai_format_response, 'dict') else {}+ usage = _get_batch_job_usage_from_response_body(response_dict)++ total_tokens += usage.total_tokens+ prompt_tokens += usage.prompt_tokens+ completion_tokens += usage.completion_tokens++ return total_cost, Usage(+ total_tokens=total_tokens,+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ )++async def _get_batch_output_file_content_as_dictionary(batch: Batch,custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",@@ -157,10 +251,17 @@ def _get_batch_job_cost_from_file_content(def _get_batch_job_total_usage_from_file_content(file_content_dictionary: List[dict],custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",+ model_name: Optional[str] = None,) -> Usage:"""Get the tokens of a batch job from the file content"""+ # Handle Vertex AI with specialized method+ if custom_llm_provider == "vertex_ai" and model_name:+ _, batch_usage = calculate_vertex_ai_batch_cost_and_usage(file_content_dictionary, model_name)+ return batch_usage++ # For other providers, use the existing logictotal_tokens: int = 0prompt_tokens: int = 0completion_tokens: int = 0diff --git a/litellm/constants.py b/litellm/constants.pyindex 8553ca6ced6..db2794a770a 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -273,6 +273,7 @@ ANTHROPIC_WEB_SEARCH_TOOL_MAX_USES = {"high": 10,}DEFAULT_IMAGE_ENDPOINT_MODEL = "dall-e-2"+DEFAULT_VIDEO_ENDPOINT_MODEL = "sora-2"### DATAFORSEO CONSTANTS ###DEFAULT_DATAFORSEO_LOCATION_CODE = int(@@ -823,6 +824,7 @@ BEDROCK_INVOKE_PROVIDERS_LITERAL = Literal["ai21","nova","deepseek_r1",+ "qwen3",]BEDROCK_EMBEDDING_PROVIDERS_LITERAL = Literal[diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex 37c76e5584b..d5910a3af86 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -888,6 +888,35 @@ def completion_cost( # noqa: PLR0915size=size,optional_params=optional_params,)+ elif (+ call_type == CallTypes.create_video.value+ or call_type == CallTypes.acreate_video.value+ or call_type == CallTypes.video_remix.value+ or call_type == CallTypes.avideo_remix.value+ ):+ ### VIDEO GENERATION COST CALCULATION ###+ if completion_response is not None and hasattr(completion_response, 'usage'):+ usage_obj = completion_response.usage+ # Handle both dict and Pydantic Usage object+ if isinstance(usage_obj, dict):+ duration_seconds = usage_obj.get('duration_seconds', None)+ else:+ duration_seconds = getattr(usage_obj, 'duration_seconds', None)++ if duration_seconds is not None:+ # Calculate cost based on video duration using video-specific cost calculation+ from litellm.llms.openai.cost_calculation import video_generation_cost+ return video_generation_cost(+ model=model,+ duration_seconds=duration_seconds,+ custom_llm_provider=custom_llm_provider+ )+ # Fallback to default video cost calculation if no duration available+ return default_video_cost_calculator(+ model=model,+ duration_seconds=0.0, # Default to 0 if no duration available+ custom_llm_provider=custom_llm_provider+ )elif (call_type == CallTypes.speech.valueor call_type == CallTypes.aspeech.value@@ -1358,6 +1387,80 @@ def default_image_cost_calculator(return cost_info["input_cost_per_pixel"] * height * width * n+def default_video_cost_calculator(+ model: str,+ duration_seconds: float,+ custom_llm_provider: Optional[str] = None,+) -> float:+ """+ Default video cost calculator for video generation++ Args:+ model (str): Model name+ duration_seconds (float): Duration of the generated video in seconds+ custom_llm_provider (Optional[str]): Custom LLM provider++ Returns:+ float: Cost in USD for the video generation++ Raises:+ Exception: If model pricing not found in cost map+ """+ # Build model names for cost lookup+ base_model_name = model+ model_name_without_custom_llm_provider: Optional[str] = None+ if custom_llm_provider and model.startswith(f"{custom_llm_provider}/"):+ model_name_without_custom_llm_provider = model.replace(+ f"{custom_llm_provider}/", ""+ )+ base_model_name = f"{custom_llm_provider}/{model_name_without_custom_llm_provider}"++ verbose_logger.debug(+ f"Looking up cost for video model: {base_model_name}"+ )++ model_without_provider = model.split('/')[-1]++ # Try model with provider first, fall back to base model name+ cost_info: Optional[dict] = None+ models_to_check: List[Optional[str]] = [+ base_model_name,+ model,+ model_without_provider,+ model_name_without_custom_llm_provider,+ ]+ for _model in models_to_check:+ if _model is not None and _model in litellm.model_cost:+ cost_info = litellm.model_cost[_model]+ break++ # If still not found, try with custom_llm_provider prefix+ if cost_info is None and custom_llm_provider:+ prefixed_model = f"{custom_llm_provider}/{model}"+ if prefixed_model in litellm.model_cost:+ cost_info = litellm.model_cost[prefixed_model]+ if cost_info is None:+ raise Exception(+ f"Model not found in cost map. Tried checking {models_to_check}"+ )++ # Check for video-specific cost per second first+ video_cost_per_second = cost_info.get("output_cost_per_video_per_second")+ if video_cost_per_second is not None:+ return video_cost_per_second * duration_seconds++ # Fallback to general output cost per second+ output_cost_per_second = cost_info.get("output_cost_per_second")+ if output_cost_per_second is not None:+ return output_cost_per_second * duration_seconds++ # If no cost information found, return 0+ verbose_logger.info(+ f"No cost information found for video model {model}. Please add pricing to model_prices_and_context_window.json"+ )+ return 0.0++def batch_cost_calculator(usage: Usage,model: str,diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.pyindex 7da38e193b6..3efe5873786 100644--- a/litellm/integrations/SlackAlerting/slack_alerting.py+++ b/litellm/integrations/SlackAlerting/slack_alerting.py@@ -134,6 +134,27 @@ class SlackAlerting(CustomBatchLogger):if llm_router is not None:self.llm_router = llm_router+ def _prepare_outage_value_for_cache(self, outage_value: Union[dict, ProviderRegionOutageModel, OutageModel]) -> dict:+ """+ Helper method to prepare outage value for Redis caching.+ Converts set objects to lists for JSON serialization.+ """+ # Convert to dict for processing+ cache_value = dict(outage_value)++ if "deployment_ids" in cache_value and isinstance(cache_value["deployment_ids"], set):+ cache_value["deployment_ids"] = list(cache_value["deployment_ids"])+ return cache_value++ def _restore_outage_value_from_cache(self, outage_value: Optional[dict]) -> Optional[dict]:+ """+ Helper method to restore outage value after retrieving from cache.+ Converts list objects back to sets for proper handling.+ """+ if outage_value and isinstance(outage_value.get("deployment_ids"), list):+ outage_value["deployment_ids"] = set(outage_value["deployment_ids"])+ return outage_value+async def deployment_in_cooldown(self):pass@@ -809,6 +830,10 @@ class SlackAlerting(CustomBatchLogger):ProviderRegionOutageModel] = await self.internal_usage_cache.async_get_cache(key=cache_key)+ # Convert deployment_ids back to set if it was stored as a list+ if outage_value is not None:+ outage_value = self._restore_outage_value_from_cache(outage_value) # type: ignore+if (getattr(exception, "status_code", None) is Noneor (@@ -832,9 +857,11 @@ class SlackAlerting(CustomBatchLogger):)## add to cache ##+ # Convert set to list for JSON serialization+ cache_value = self._prepare_outage_value_for_cache(outage_value)await self.internal_usage_cache.async_set_cache(key=cache_key,- value=outage_value,+ value=cache_value,ttl=self.alerting_args.region_outage_alert_ttl,)return@@ -900,8 +927,10 @@ class SlackAlerting(CustomBatchLogger):outage_value["major_alert_sent"] = True## update cache ##+ # Convert set to list for JSON serialization+ cache_value = self._prepare_outage_value_for_cache(outage_value)await self.internal_usage_cache.async_set_cache(- key=cache_key, value=outage_value+ key=cache_key, value=cache_value)async def outage_alerts(@@ -1025,8 +1054,10 @@ class SlackAlerting(CustomBatchLogger):outage_value["major_alert_sent"] = True## update cache ##+ # Convert set to list for JSON serialization+ cache_value = self._prepare_outage_value_for_cache(outage_value)await self.internal_usage_cache.async_set_cache(- key=deployment_id, value=outage_value+ key=deployment_id, value=cache_value)except Exception:passdiff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.pyindex 275f2a63a1b..fb25c5ed840 100644--- a/litellm/litellm_core_utils/get_llm_provider_logic.py+++ b/litellm/litellm_core_utils/get_llm_provider_logic.py@@ -279,6 +279,7 @@ def get_llm_provider( # noqa: PLR0915or "ft:gpt-3.5-turbo" in modelor "ft:gpt-4" in model # catches ft:gpt-4-0613, ft:gpt-4oor model in litellm.openai_image_generation_models+ or model in litellm.openai_video_generation_models):custom_llm_provider = "openai"elif model in litellm.open_ai_text_completion_models:diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 8e042ef0d79..7d727554783 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -115,6 +115,7 @@ from litellm.types.utils import (TranscriptionResponse,Usage,)+from litellm.types.videos.main import VideoObjectfrom litellm.utils import _get_base_model_from_metadata, executor, print_verbosefrom ..integrations.argilla import ArgillaLogger@@ -1614,6 +1615,7 @@ class Logging(LiteLLMLoggingBaseClass):or isinstance(logging_result, OpenAIFileObject)or isinstance(logging_result, LiteLLMRealtimeStreamLoggingObject)or isinstance(logging_result, OpenAIModerationResponse)+ or isinstance(logging_result, VideoObject)or (self.call_type == CallTypes.call_mcp_tool.value)):return Truediff --git a/litellm/llms/azure/videos/transformation.py b/litellm/llms/azure/videos/transformation.pynew file mode 100644index 00000000000..3af9e0778bc--- /dev/null+++ b/litellm/llms/azure/videos/transformation.py@@ -0,0 +1,89 @@+from typing import TYPE_CHECKING, Any, Dict, Optional++from litellm.types.videos.main import VideoCreateOptionalRequestParams+from litellm.secret_managers.main import get_secret_str+from litellm.llms.azure.common_utils import BaseAzureLLM+import litellm+from litellm.llms.openai.videos.transformation import OpenAIVideoConfig+if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj++ from ...base_llm.videos.transformation import BaseVideoConfig as _BaseVideoConfig+ from ...base_llm.chat.transformation import BaseLLMException as _BaseLLMException++ LiteLLMLoggingObj = _LiteLLMLoggingObj+ BaseVideoConfig = _BaseVideoConfig+ BaseLLMException = _BaseLLMException+else:+ LiteLLMLoggingObj = Any+ BaseVideoConfig = Any+ BaseLLMException = Any+++class AzureVideoConfig(OpenAIVideoConfig):+ """+ Configuration class for OpenAI video generation.+ """++ def __init__(self):+ super().__init__()++ def get_supported_openai_params(self, model: str) -> list:+ """+ Get the list of supported OpenAI parameters for video generation.+ """+ return [+ "model",+ "prompt",+ "input_reference",+ "seconds",+ "size",+ "user",+ "extra_headers",+ ]++ def map_openai_params(+ self,+ video_create_optional_params: VideoCreateOptionalRequestParams,+ model: str,+ drop_params: bool,+ ) -> Dict:+ """No mapping applied since inputs are in OpenAI spec already"""+ return dict(video_create_optional_params)++ def validate_environment(+ self,+ headers: dict,+ model: str,+ api_key: Optional[str] = None,+ ) -> dict:+ api_key = (+ api_key+ or litellm.api_key+ or litellm.azure_key+ or get_secret_str("AZURE_OPENAI_API_KEY")+ or get_secret_str("AZURE_API_KEY")+ )++ headers.update(+ {+ "Authorization": f"Bearer {api_key}",+ }+ )+ return headers++ def get_complete_url(+ self,+ model: str,+ api_base: Optional[str],+ litellm_params: dict,+ ) -> str:+ """+ Constructs a complete URL for the API request.+ """+ return BaseAzureLLM._get_base_azure_url(+ api_base=api_base,+ litellm_params=litellm_params,+ route="/openai/v1/videos",+ default_api_version="",+ )\ No newline at end of filediff --git a/litellm/llms/base_llm/videos/transformation.py b/litellm/llms/base_llm/videos/transformation.pynew file mode 100644index 00000000000..223b308dc08--- /dev/null+++ b/litellm/llms/base_llm/videos/transformation.py@@ -0,0 +1,254 @@+import types+from abc import ABC, abstractmethod+from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union++import httpx+from httpx._types import RequestFiles++from litellm.types.videos.main import VideoCreateOptionalRequestParams+from litellm.types.responses.main import *+from litellm.types.router import GenericLiteLLMParams++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj+ from litellm.types.videos.main import VideoObject as _VideoObject++ from ..chat.transformation import BaseLLMException as _BaseLLMException++ LiteLLMLoggingObj = _LiteLLMLoggingObj+ BaseLLMException = _BaseLLMException+ VideoObject = _VideoObject+else:+ LiteLLMLoggingObj = Any+ BaseLLMException = Any+ VideoObject = Any+++class BaseVideoConfig(ABC):+ def __init__(self):+ pass++ @classmethod+ def get_config(cls):+ return {+ k: v+ for k, v in cls.__dict__.items()+ if not k.startswith("__")+ and not k.startswith("_abc")+ and not isinstance(+ v,+ (+ types.FunctionType,+ types.BuiltinFunctionType,+ classmethod,+ staticmethod,+ ),+ )+ and v is not None+ }++ @abstractmethod+ def get_supported_openai_params(self, model: str) -> list:+ pass++ @abstractmethod+ def map_openai_params(+ self,+ video_create_optional_params: VideoCreateOptionalRequestParams,+ model: str,+ drop_params: bool,+ ) -> Dict:+ pass++ @abstractmethod+ def validate_environment(+ self,+ headers: dict,+ model: str,+ api_key: Optional[str] = None,+ ) -> dict:+ return {}++ @abstractmethod+ def get_complete_url(+ self,+ model: str,+ api_base: Optional[str],+ litellm_params: dict,+ ) -> str:+ """+ OPTIONAL++ Get the complete url for the request++ Some providers need `model` in `api_base`+ """+ if api_base is None:+ raise ValueError("api_base is required")+ return api_base++ @abstractmethod+ def transform_video_create_request(+ self,+ model: str,+ prompt: str,+ video_create_optional_request_params: Dict,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[Dict, RequestFiles]:+ pass++ @abstractmethod+ def transform_video_create_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ pass++ @abstractmethod+ def transform_video_content_request(+ self,+ video_id: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[str, Dict]:+ """+ Transform the video content request into a URL and data/params++ Returns:+ Tuple[str, Dict]: (url, params) for the video content request+ """+ pass++ @abstractmethod+ def transform_video_content_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> bytes:+ pass++ @abstractmethod+ def transform_video_remix_request(+ self,+ video_id: str,+ prompt: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ extra_body: Optional[Dict[str, Any]] = None,+ ) -> Tuple[str, Dict]:+ """+ Transform the video remix request into a URL and data++ Returns:+ Tuple[str, Dict]: (url, data) for the video remix request+ """+ pass++ @abstractmethod+ def transform_video_remix_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ pass++ @abstractmethod+ def transform_video_list_request(+ self,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ after: Optional[str] = None,+ limit: Optional[int] = None,+ order: Optional[str] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ ) -> Tuple[str, Dict]:+ """+ Transform the video list request into a URL and params++ Returns:+ Tuple[str, Dict]: (url, params) for the video list request+ """+ pass++ @abstractmethod+ def transform_video_list_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> Dict[str,str]:+ pass++ @abstractmethod+ def transform_video_delete_request(+ self,+ video_id: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[str, Dict]:+ """+ Transform the video delete request into a URL and data++ Returns:+ Tuple[str, Dict]: (url, data) for the video delete request+ """+ pass++ @abstractmethod+ def transform_video_delete_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ pass++ @abstractmethod+ def transform_video_status_retrieve_request(+ self,+ video_id: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[str, Dict]:+ """+ Transform the video retrieve request into a URL and data/params++ Returns:+ Tuple[str, Dict]: (url, params) for the video retrieve request+ """+ pass++ @abstractmethod+ def transform_video_status_retrieve_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ pass++ def get_error_class(+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]+ ) -> BaseLLMException:+ from ..chat.transformation import BaseLLMException++ raise BaseLLMException(+ status_code=status_code,+ message=error_message,+ headers=headers,+ )diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.pynew file mode 100644index 00000000000..b3a957ce0f8--- /dev/null+++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py@@ -0,0 +1,219 @@+"""+Handles transforming requests for `bedrock/invoke/{qwen3} models`++Inherits from `AmazonInvokeConfig`++Qwen3 + Invoke API Tutorial: https://docs.aws.amazon.com/bedrock/latest/userguide/invoke-imported-model.html+"""++from typing import Any, List, Optional++import httpx++from litellm.llms.base_llm.chat.transformation import BaseConfig+from litellm.llms.bedrock.chat.invoke_transformations.base_invoke_transformation import (+ AmazonInvokeConfig,+ LiteLLMLoggingObj,+)+from litellm.types.llms.openai import AllMessageValues+from litellm.types.utils import ModelResponse+++class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig):+ """+ Config for sending `qwen3` requests to `/bedrock/invoke/`++ Reference: https://docs.aws.amazon.com/bedrock/latest/userguide/invoke-imported-model.html+ """++ max_tokens: Optional[int] = None+ temperature: Optional[float] = None+ top_p: Optional[float] = None+ top_k: Optional[int] = None+ stop: Optional[List[str]] = None++ def __init__(+ self,+ max_tokens: Optional[int] = None,+ temperature: Optional[float] = None,+ top_p: Optional[float] = None,+ top_k: Optional[int] = None,+ stop: Optional[List[str]] = None,+ ) -> None:+ locals_ = locals().copy()+ for key, value in locals_.items():+ if key != "self" and value is not None:+ setattr(self.__class__, key, value)+ AmazonInvokeConfig.__init__(self)++ def get_supported_openai_params(self, model: str) -> List[str]:+ return [+ "max_tokens",+ "temperature",+ "top_p",+ "top_k",+ "stop",+ "stream",+ ]++ def map_openai_params(+ self,+ non_default_params: dict,+ optional_params: dict,+ model: str,+ drop_params: bool,+ ) -> dict:+ for k, v in non_default_params.items():+ if k == "max_tokens":+ optional_params["max_tokens"] = v+ if k == "temperature":+ optional_params["temperature"] = v+ if k == "top_p":+ optional_params["top_p"] = v+ if k == "top_k":+ optional_params["top_k"] = v+ if k == "stop":+ optional_params["stop"] = v+ if k == "stream":+ optional_params["stream"] = v+ return optional_params++ def transform_request(+ self,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ headers: dict,+ ) -> dict:+ """+ Transform OpenAI format to Qwen3 Bedrock invoke format+ """+ # Convert messages to prompt format+ prompt = self._convert_messages_to_prompt(messages)++ # Build the request body+ request_body = {+ "prompt": prompt,+ }++ # Add optional parameters+ if "max_tokens" in optional_params:+ request_body["max_gen_len"] = optional_params["max_tokens"]+ if "temperature" in optional_params:+ request_body["temperature"] = optional_params["temperature"]+ if "top_p" in optional_params:+ request_body["top_p"] = optional_params["top_p"]+ if "top_k" in optional_params:+ request_body["top_k"] = optional_params["top_k"]+ if "stop" in optional_params:+ request_body["stop"] = optional_params["stop"]++ return request_body++ def _convert_messages_to_prompt(self, messages: List[AllMessageValues]) -> str:+ """+ Convert OpenAI messages format to Qwen3 prompt format+ Supports tool calls, multimodal content, and various message types+ """+ prompt_parts = []++ for message in messages:+ role = message.get("role", "")+ content = message.get("content", "")+ tool_calls = message.get("tool_calls", [])++ if role == "system":+ prompt_parts.append(f"<|im_start|>system\n{content}<|im_end|>")+ elif role == "user":+ # Handle multimodal content+ if isinstance(content, list):+ text_content = []+ for item in content:+ if item.get("type") == "text":+ text_content.append(item.get("text", ""))+ elif item.get("type") == "image_url":+ # For Qwen3, we can include image placeholders+ text_content.append("<|vision_start|><|image_pad|><|vision_end|>")+ content = "".join(text_content)+ prompt_parts.append(f"<|im_start|>user\n{content}<|im_end|>")+ elif role == "assistant":+ if tool_calls and isinstance(tool_calls, list):+ # Handle tool calls+ for tool_call in tool_calls:+ function_name = tool_call.get("function", {}).get("name", "")+ function_args = tool_call.get("function", {}).get("arguments", "")+ prompt_parts.append(f"<|im_start|>assistant\n<tool_call>\n{{\"name\": \"{function_name}\", \"arguments\": \"{function_args}\"}}\n</tool_call><|im_end|>")+ else:+ prompt_parts.append(f"<|im_start|>assistant\n{content}<|im_end|>")+ elif role == "tool":+ # Handle tool responses+ prompt_parts.append(f"<|im_start|>tool\n{content}<|im_end|>")++ # Add assistant start token for response generation+ prompt_parts.append("<|im_start|>assistant\n")++ return "\n".join(prompt_parts)++ def transform_response(+ self,+ model: str,+ raw_response: httpx.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 Qwen3 Bedrock response to OpenAI format+ """+ try:+ if hasattr(raw_response, 'json'):+ response_data = raw_response.json()+ else:+ response_data = raw_response++ # Extract the generated text - Qwen3 uses "generation" field+ generated_text = response_data.get("generation", "")++ # Clean up the response (remove assistant start token if present)+ if generated_text.startswith("<|im_start|>assistant\n"):+ generated_text = generated_text[len("<|im_start|>assistant\n"):]+ if generated_text.endswith("<|im_end|>"):+ generated_text = generated_text[:-len("<|im_end|>")]++ # Set the content in the existing model_response structure+ if hasattr(model_response, 'choices') and len(model_response.choices) > 0:+ choice = model_response.choices[0]+ if hasattr(choice, 'message'):+ choice.message.content = generated_text+ choice.finish_reason = "stop"+ else:+ # Handle streaming choices+ choice.delta.content = generated_text+ choice.finish_reason = "stop"++ # Set usage information if available in response+ if "usage" in response_data:+ usage_data = response_data["usage"]+ if hasattr(model_response, 'usage'):+ model_response.usage.prompt_tokens = usage_data.get("prompt_tokens", 0)+ model_response.usage.completion_tokens = usage_data.get("completion_tokens", 0)+ model_response.usage.total_tokens = usage_data.get("total_tokens", 0)++ return model_response++ except Exception as e:+ if logging_obj:+ logging_obj.post_call(+ input=messages,+ api_key=api_key,+ original_response=raw_response,+ additional_args={"error": str(e)},+ )+ raise ediff --git a/litellm/llms/cohere/chat/v2_transformation.py b/litellm/llms/cohere/chat/v2_transformation.pyindex 76948e7f8b9..50426a0883b 100644--- a/litellm/llms/cohere/chat/v2_transformation.py+++ b/litellm/llms/cohere/chat/v2_transformation.py@@ -4,14 +4,14 @@ from typing import TYPE_CHECKING, Any, AsyncIterator, Iterator, List, Optional,import httpximport litellm-from litellm.litellm_core_utils.prompt_templates.factory import cohere_messages_pt_v2-from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException+from litellm.llms.base_llm.chat.transformation import BaseLLMExceptionfrom litellm.types.llms.cohere import CohereV2ChatResponsefrom litellm.types.llms.openai import AllMessageValues, ChatCompletionToolCallChunk+from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfigfrom litellm.types.utils import ModelResponse, Usagefrom ..common_utils import CohereError-from ..common_utils import ModelResponseIterator as CohereModelResponseIterator+from ..common_utils import CohereV2ModelResponseIteratorfrom ..common_utils import validate_environment as cohere_validate_environmentif TYPE_CHECKING:@@ -22,7 +22,7 @@ else:LiteLLMLoggingObj = Any-class CohereV2ChatConfig(BaseConfig):+class CohereV2ChatConfig(OpenAIGPTConfig):"""Configuration class for Cohere's API interface.@@ -164,32 +164,12 @@ class CohereV2ChatConfig(BaseConfig):litellm_params: dict,headers: dict,) -> dict:- ## Load Config- for k, v in litellm.CohereChatConfig.get_config().items():- if (- k not in optional_params- ): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in- optional_params[k] = v-- most_recent_message, chat_history = cohere_messages_pt_v2(- messages=messages, model=model, llm_provider="cohere_chat"- )-- ## Handle Tool Calling- if "tools" in optional_params:- _is_function_call = True- cohere_tools = self._construct_cohere_tool(tools=optional_params["tools"])- optional_params["tools"] = cohere_tools- if isinstance(most_recent_message, dict):- optional_params["tool_results"] = [most_recent_message]- elif isinstance(most_recent_message, str):- optional_params["message"] = most_recent_message-- ## check if chat history message is 'user' and 'tool_results' is given -> force_single_step=True, else cohere api fails- if len(chat_history) > 0 and chat_history[-1]["role"] == "USER":- optional_params["force_single_step"] = True-- return optional_params+ """+ Cohere v2 chat api is in openai format, so we can use the openai transform request function to transform the request.+ """+ data = super().transform_request(model, messages, optional_params, litellm_params, headers)++ return datadef transform_response(self,@@ -263,93 +243,35 @@ class CohereV2ChatConfig(BaseConfig):setattr(model_response, "usage", usage)return model_response- def _construct_cohere_tool(- self,- tools: Optional[list] = None,- ):- if tools is None:- tools = []- cohere_tools = []- for tool in tools:- cohere_tool = self._translate_openai_tool_to_cohere(tool)- cohere_tools.append(cohere_tool)- return cohere_tools-- def _translate_openai_tool_to_cohere(- self,- openai_tool: dict,- ):- # cohere tools look like this- """- {- "name": "query_daily_sales_report",- "description": "Connects to a database to retrieve overall sales volumes and sales information for a given day.",- "parameter_definitions": {- "day": {- "description": "Retrieves sales data for this day, formatted as YYYY-MM-DD.",- "type": "str",- "required": True- }- }- }- """-- # OpenAI tools look like this- """- {- "type": "function",- "function": {- "name": "get_current_weather",- "description": "Get the current weather in a given location",- "parameters": {- "type": "object",- "properties": {- "location": {- "type": "string",- "description": "The city and state, e.g. San Francisco, CA",- },- "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},- },- "required": ["location"],- },- },- }- """- cohere_tool = {- "name": openai_tool["function"]["name"],- "description": openai_tool["function"]["description"],- "parameter_definitions": {},- }-- for param_name, param_def in openai_tool["function"]["parameters"][- "properties"- ].items():- required_params = (- openai_tool.get("function", {})- .get("parameters", {})- .get("required", [])- )- cohere_param_def = {- "description": param_def.get("description", ""),- "type": param_def.get("type", ""),- "required": param_name in required_params,- }- cohere_tool["parameter_definitions"][param_name] = cohere_param_def-- return cohere_tool-def get_model_response_iterator(self,streaming_response: Union[Iterator[str], AsyncIterator[str], ModelResponse],sync_stream: bool,json_mode: Optional[bool] = False,):- return CohereModelResponseIterator(+ return CohereV2ModelResponseIterator(streaming_response=streaming_response,sync_stream=sync_stream,json_mode=json_mode,)+ 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 Cohere v2 chat completion.+ The api_base should already include the full path.+ """+ if api_base is None:+ raise ValueError("api_base is required")+ return api_base+def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]) -> BaseLLMException:diff --git a/litellm/llms/cohere/common_utils.py b/litellm/llms/cohere/common_utils.pyindex d194d9556b6..333916fffa3 100644--- a/litellm/llms/cohere/common_utils.py+++ b/litellm/llms/cohere/common_utils.py@@ -1,12 +1,14 @@import json-from typing import List, Optional+from typing import List, Optional, Literal, Tuple+from litellm.llms.base_llm.base_utils import BaseLLMModelInfofrom litellm.llms.base_llm.chat.transformation import BaseLLMExceptionfrom litellm.types.llms.openai import AllMessageValuesfrom litellm.types.utils import (ChatCompletionToolCallChunk,ChatCompletionUsageBlock,GenericStreamingChunk,+ ProviderSpecificModelInfo,)@@ -15,6 +17,74 @@ class CohereError(BaseLLMException):super().__init__(status_code=status_code, message=message)+class CohereModelInfo(BaseLLMModelInfo):+ def get_provider_info(+ self,+ model: str,+ ) -> Optional[ProviderSpecificModelInfo]:+ """+ Default values all models of this provider support.+ """+ return None++ def get_models(+ self, api_key: Optional[str] = None, api_base: Optional[str] = None+ ) -> List[str]:+ """+ Returns a list of models supported by this provider.+ """+ return []++ @staticmethod+ def get_api_key(api_key: Optional[str] = None) -> Optional[str]:+ return api_key++ @staticmethod+ def get_api_base(+ api_base: Optional[str] = None,+ ) -> Optional[str]:+ return api_base++ 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:+ return {}++ @staticmethod+ def get_base_model(model: str) -> Optional[str]:+ """+ Returns the base model name from the given model name.++ Some providers like bedrock - can receive model=`invoke/anthropic.claude-3-opus-20240229-v1:0` or `converse/anthropic.claude-3-opus-20240229-v1:0`+ This function will return `anthropic.claude-3-opus-20240229-v1:0`+ """+ pass++ @staticmethod+ def get_cohere_route(model: str) -> Literal["v1", "v2"]:+ """+ Get the Cohere route for the given model.++ Args:+ model: The model name (e.g., "cohere_chat/v2/command-r-plus", "command-r-plus")++ Returns:+ "v2" for standard Cohere v2 API (default), "v1" for Cohere v1 API+ """+ # Check for explicit v1 route+ if "v1/" in model:+ return "v1"++ # Default to v2 for all other cases+ return "v2"+def validate_environment(headers: dict,model: str,@@ -145,3 +215,197 @@ class ModelResponseIterator:raise StopAsyncIterationexcept ValueError as e:raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}")++class CohereV2ModelResponseIterator:+ """V2-specific response iterator for Cohere streaming"""++ def __init__(+ self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False+ ):+ self.streaming_response = streaming_response+ self.response_iterator = self.streaming_response+ self.content_blocks: List = []+ self.tool_index = -1+ self.json_mode = json_mode++ def _parse_content_delta(self, chunk: dict) -> str:+ """Parse content-delta chunks to extract text."""+ delta = chunk.get("delta", {})+ message = delta.get("message", {})+ content = message.get("content", {})+ if isinstance(content, dict) and "text" in content:+ return content["text"]+ elif isinstance(content, str):+ return content+ return ""++ def _parse_tool_call_delta(self, chunk: dict) -> Optional[ChatCompletionToolCallChunk]:+ """Parse tool-call-delta chunks to extract tool calls."""+ delta = chunk.get("delta", {})+ tool_calls = delta.get("tool_calls", [])+ if tool_calls:+ return {+ "id": tool_calls[0].get("id", ""),+ "type": "function",+ "function": {+ "name": tool_calls[0].get("name", ""),+ "arguments": tool_calls[0].get("arguments", "")+ }+ } # type: ignore+ return None++ def _parse_tool_plan_delta(self, chunk: dict) -> Optional[dict]:+ """Parse tool-plan-delta events to extract tool plan."""+ data = chunk.get("data", {})+ delta = data.get("delta", {})+ message = delta.get("message", {})+ tool_plan = message.get("tool_plan", "")+ if tool_plan:+ return {"tool_plan": tool_plan}+ return None++ def _parse_citation_start(self, chunk: dict) -> Optional[dict]:+ """Parse citation-start events to extract citations."""+ data = chunk.get("data", {})+ delta = data.get("delta", {})+ message = delta.get("message", {})+ citations = message.get("citations", {})+ if citations:+ citation_data = {+ "start": citations.get("start", 0),+ "end": citations.get("end", 0),+ "text": citations.get("text", ""),+ "sources": citations.get("sources", []),+ "type": citations.get("type", "TEXT_CONTENT")+ }+ return {"citations": [citation_data]}+ return None++ def _parse_message_end(self, chunk: dict) -> Tuple[bool, str, Optional[ChatCompletionUsageBlock]]:+ """Parse message-end events to extract finish info and usage."""+ data = chunk.get("data", {})+ delta = data.get("delta", {})+ is_finished = True+ finish_reason = delta.get("finish_reason", "stop")++ usage = None+ usage_data = delta.get("usage", {})+ if usage_data:+ tokens_data = usage_data.get("tokens", {})+ usage = ChatCompletionUsageBlock(+ prompt_tokens=tokens_data.get("input_tokens", 0),+ completion_tokens=tokens_data.get("output_tokens", 0),+ total_tokens=tokens_data.get("input_tokens", 0) + tokens_data.get("output_tokens", 0)+ )++ return is_finished, finish_reason, usage++ def chunk_parser(self, chunk: dict) -> GenericStreamingChunk:+ """+ Parse Cohere v2 streaming chunks.++ v2 format:+ - Content: chunk.type == "content-delta" -> chunk.delta.message.content.text+ - Tool calls: chunk.type == "tool-call-delta" -> chunk.delta.tool_calls+ - Tool plan: chunk.event == "tool-plan-delta" -> chunk.data.delta.message.tool_plan+ - Citations: chunk.event == "citation-start" -> chunk.data.delta.message.citations+ - Finish: chunk.event == "message-end" -> chunk.data.delta.finish_reason+ """+ try:+ text = ""+ tool_use: Optional[ChatCompletionToolCallChunk] = None+ is_finished = False+ finish_reason = ""+ usage: Optional[ChatCompletionUsageBlock] = None+ provider_specific_fields = None++ index = int(chunk.get("index", 0))+ chunk_type = chunk.get("type", "")+ event_type = chunk.get("event", "")++ # Handle different chunk types+ if chunk_type == "content-delta":+ text = self._parse_content_delta(chunk)+ elif chunk_type == "tool-call-delta":+ tool_use = self._parse_tool_call_delta(chunk)+ elif event_type == "tool-plan-delta":+ provider_specific_fields = self._parse_tool_plan_delta(chunk)+ elif event_type == "citation-start":+ provider_specific_fields = self._parse_citation_start(chunk)+ elif event_type == "message-end":+ is_finished, finish_reason, usage = self._parse_message_end(chunk)++ # Handle citations in any chunk type (fallback)+ if "citations" in chunk:+ if provider_specific_fields is None:+ provider_specific_fields = {}+ provider_specific_fields["citations"] = chunk["citations"]++ return GenericStreamingChunk(+ text=text,+ tool_use=tool_use,+ is_finished=is_finished,+ finish_reason=finish_reason,+ usage=usage,+ index=index,+ provider_specific_fields=provider_specific_fields,+ )++ except Exception as e:+ raise ValueError(f"Failed to parse v2 chunk: {e}, chunk: {chunk}")++ # Sync iterator+ def __iter__(self):+ return self++ def __next__(self):+ try:+ chunk = self.response_iterator.__next__()+ except StopIteration:+ raise StopIteration+ except ValueError as e:+ raise RuntimeError(f"Error receiving chunk from stream: {e}")++ try:+ return self.convert_str_chunk_to_generic_chunk(chunk=chunk)+ except StopIteration:+ raise StopIteration+ except ValueError as e:+ raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}")++ def convert_str_chunk_to_generic_chunk(self, chunk: str) -> GenericStreamingChunk:+ """+ Convert a string chunk to a GenericStreamingChunk for v2++ Note: This is used for Cohere v2 pass through streaming logging+ """+ str_line = chunk+ if isinstance(chunk, bytes): # Handle binary data+ str_line = chunk.decode("utf-8") # Convert bytes to string+ index = str_line.find("data:")+ if index != -1:+ str_line = str_line[index:]++ data_json = json.loads(str_line)+ return self.chunk_parser(chunk=data_json)++ # Async iterator+ def __aiter__(self):+ self.async_response_iterator = self.streaming_response.__aiter__()+ return self++ async def __anext__(self):+ try:+ chunk = await self.async_response_iterator.__anext__()+ except StopAsyncIteration:+ raise StopAsyncIteration+ except ValueError as e:+ raise RuntimeError(f"Error receiving chunk from stream: {e}")++ try:+ return self.convert_str_chunk_to_generic_chunk(chunk=chunk)+ except StopAsyncIteration:+ raise StopAsyncIteration+ except ValueError as e:+ raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}")+diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 56e5f0c948c..b67e8823d0c 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -47,6 +47,7 @@ from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfifrom litellm.llms.base_llm.search.transformation import BaseSearchConfig, SearchResponsefrom litellm.llms.base_llm.text_to_speech.transformation import BaseTextToSpeechConfigfrom litellm.llms.base_llm.vector_store.transformation import BaseVectorStoreConfig+from litellm.llms.base_llm.videos.transformation import BaseVideoConfigfrom litellm.llms.custom_httpx.http_handler import (AsyncHTTPHandler,HTTPHandler,@@ -85,6 +86,7 @@ from litellm.types.vector_stores import (VectorStoreSearchOptionalRequestParams,VectorStoreSearchResponse,)+from litellm.types.videos.main import VideoObjectfrom litellm.utils import (CustomStreamWrapper,ImageResponse,@@ -2018,7 +2020,7 @@ class BaseLLMHTTPHandler:headers=headers,json=data,timeout=timeout- or response_api_optional_request_params.get("timeout"),+ or float(response_api_optional_request_params.get("timeout", 0)),stream=stream,)if fake_stream is True:@@ -2046,7 +2048,7 @@ class BaseLLMHTTPHandler:headers=headers,json=data,timeout=timeout- or response_api_optional_request_params.get("timeout"),+ or float(response_api_optional_request_params.get("timeout", 0)),)except Exception as e:raise self._handle_error(@@ -2139,7 +2141,7 @@ class BaseLLMHTTPHandler:headers=headers,json=data,timeout=timeout- or response_api_optional_request_params.get("timeout"),+ or float(response_api_optional_request_params.get("timeout", 0)),stream=stream,)@@ -2169,7 +2171,7 @@ class BaseLLMHTTPHandler:headers=headers,json=data,timeout=timeout- or response_api_optional_request_params.get("timeout"),+ or float(response_api_optional_request_params.get("timeout", 0)),)except Exception as e:@@ -3475,6 +3477,7 @@ class BaseLLMHTTPHandler:BaseAnthropicMessagesConfig,BaseBatchesConfig,BaseOCRConfig,+ BaseVideoConfig,BaseSearchConfig,BaseTextToSpeechConfig,"BasePassthroughConfig",@@ -3981,6 +3984,952 @@ class BaseLLMHTTPHandler:return model_response+ ###### VIDEO GENERATION HANDLER ######+ def video_generation_handler(+ self,+ model: str,+ prompt: str,+ video_generation_provider_config: BaseVideoConfig,+ video_generation_optional_request_params: Dict,+ custom_llm_provider: str,+ litellm_params: GenericLiteLLMParams,+ logging_obj: LiteLLMLoggingObj,+ timeout: Union[float, httpx.Timeout],+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ _is_async: bool = False,+ fake_stream: bool = False,+ litellm_metadata: Optional[Dict[str, Any]] = None,+ api_key: Optional[str] = None,+ ) -> Union[+ VideoObject,+ Coroutine[Any, Any, VideoObject],+ ]:+ """+ Handles video generation requests.+ When _is_async=True, returns a coroutine instead of making the call directly.+ """+ if _is_async:+ # Return the async coroutine if called with _is_async=True+ return self.async_video_generation_handler(+ model=model,+ prompt=prompt,+ video_generation_provider_config=video_generation_provider_config,+ video_generation_optional_request_params=video_generation_optional_request_params,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ extra_headers=extra_headers,+ extra_body=extra_body,+ timeout=timeout,+ client=client if isinstance(client, AsyncHTTPHandler) else None,+ fake_stream=fake_stream,+ litellm_metadata=litellm_metadata,+ api_key=api_key,+ )++ 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 = video_generation_provider_config.validate_environment(+ api_key=api_key,+ headers=video_generation_optional_request_params.get("extra_headers", {})+ or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_generation_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ data, files = video_generation_provider_config.transform_video_create_request(+ model=model,+ prompt=prompt,+ video_create_optional_request_params=video_generation_optional_request_params,+ litellm_params=litellm_params,+ headers=headers,+ )++ ## LOGGING+ logging_obj.pre_call(+ input=prompt,+ api_key="",+ additional_args={+ "complete_input_dict": data,+ "api_base": api_base,+ "headers": headers,+ },+ )++ try:+ # Use JSON when no files, otherwise use form data with files+ if files and len(files) > 0:+ # Use multipart/form-data when files are present+ response = sync_httpx_client.post(+ url=api_base,+ headers=headers,+ data=data,+ files=files,+ timeout=timeout,+ )++ # --- END MOCK VIDEO RESPONSE ---+ else:+ response = sync_httpx_client.post(+ url=api_base,+ headers=headers,+ json=data,+ timeout=timeout,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_generation_provider_config,+ )++ return video_generation_provider_config.transform_video_create_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ async def async_video_generation_handler(+ self,+ model: str,+ prompt: str,+ video_generation_provider_config: "BaseVideoConfig",+ video_generation_optional_request_params: Dict,+ custom_llm_provider: str,+ litellm_params: GenericLiteLLMParams,+ logging_obj: LiteLLMLoggingObj,+ timeout: Union[float, httpx.Timeout],+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ fake_stream: bool = False,+ litellm_metadata: Optional[Dict[str, Any]] = None,+ api_key: Optional[str] = None,+ ) -> VideoObject:+ """+ Async version of the video generation handler.+ Uses async HTTP client to make requests.+ """+ 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 = video_generation_provider_config.validate_environment(+ api_key=api_key,+ headers=video_generation_optional_request_params.get("extra_headers", {})+ or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_generation_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ data, files = video_generation_provider_config.transform_video_create_request(+ model=model,+ prompt=prompt,+ video_create_optional_request_params=video_generation_optional_request_params,+ litellm_params=litellm_params,+ headers=headers,+ )++ ## LOGGING+ logging_obj.pre_call(+ input=prompt,+ api_key="",+ additional_args={+ "complete_input_dict": data,+ "api_base": api_base,+ "headers": headers,+ },+ )++ try:+ # Use JSON when no files, otherwise use form data with files+ if files is None or len(files) == 0:+ response = await async_httpx_client.post(+ url=api_base,+ headers=headers,+ json=data,+ timeout=timeout,+ )+ else:+ response = await async_httpx_client.post(+ url=api_base,+ headers=headers,+ data=data,+ files=files,+ timeout=timeout,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_generation_provider_config,+ )++ return video_generation_provider_config.transform_video_create_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ ###### VIDEO CONTENT HANDLER ######+ def video_content_handler(+ self,+ video_id: str,+ model: str,+ video_content_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params: GenericLiteLLMParams,+ logging_obj: LiteLLMLoggingObj,+ timeout: Union[float, httpx.Timeout],+ extra_headers: Optional[Dict[str, Any]] = None,+ api_key: Optional[str] = None,+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ _is_async: bool = False,+ ) -> Union[bytes, Coroutine[Any, Any, bytes]]:+ """+ Handle video content download requests.+ """+ if _is_async:+ return self.async_video_content_handler(+ video_id=video_id,+ model=model,+ video_content_provider_config=video_content_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ timeout=timeout,+ extra_headers=extra_headers,+ api_key=api_key,+ client=client,+ )++ 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 = video_content_provider_config.validate_environment(+ headers=extra_headers or {},+ model=model,+ api_key=api_key,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_content_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, params = video_content_provider_config.transform_video_content_request(+ video_id=video_id,+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ )++ try:+ # Make the GET request to download content+ response = sync_httpx_client.get(+ url=url,+ headers=headers,+ params=params,+ )++ # Transform the response using the provider config+ return video_content_provider_config.transform_video_content_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_content_provider_config,+ )++ async def async_video_content_handler(+ self,+ video_id: str,+ model: str,+ video_content_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params: GenericLiteLLMParams,+ logging_obj: LiteLLMLoggingObj,+ timeout: Union[float, httpx.Timeout],+ extra_headers: Optional[Dict[str, Any]] = None,+ api_key: Optional[str] = None,+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ ) -> bytes:+ """+ Async version of the video content download handler.+ """+ 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 = video_content_provider_config.validate_environment(+ headers=extra_headers or {},+ model=model,+ api_key=api_key,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_content_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, params = video_content_provider_config.transform_video_content_request(+ video_id=video_id,+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ )++ try:+ # Make the GET request to download content+ response = await async_httpx_client.get(+ url=url,+ headers=headers,+ params=params,+ )++ # Transform the response using the provider config+ return video_content_provider_config.transform_video_content_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_content_provider_config,+ )++ def video_remix_handler(+ self,+ video_id: str,+ prompt: str,+ model: str,+ video_remix_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params,+ logging_obj,+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ timeout: Optional[float] = None,+ _is_async: bool = False,+ client=None,+ api_key: Optional[str] = None,+ ):+ """+ Handler for video remix requests.+ When _is_async=True, returns a coroutine instead of making the call directly.+ """+ if _is_async:+ # Return the async coroutine if called with _is_async=True+ return self.async_video_remix_handler(+ video_id=video_id,+ prompt=prompt,+ model=model,+ video_remix_provider_config=video_remix_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ extra_headers=extra_headers,+ extra_body=extra_body,+ timeout=timeout,+ client=client,+ api_key=api_key,+ )++ # For sync calls, use sync HTTP client directly (like video_generation does)+ 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 = video_remix_provider_config.validate_environment(+ api_key=api_key,+ headers=extra_headers or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_remix_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, data = video_remix_provider_config.transform_video_remix_request(+ video_id=video_id,+ prompt=prompt,+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ extra_body=extra_body,+ )++ ## LOGGING+ logging_obj.pre_call(+ input=prompt,+ api_key="",+ additional_args={+ "complete_input_dict": data,+ "api_base": url,+ "headers": headers,+ "video_id": video_id,+ },+ )++ try:+ response = sync_httpx_client.post(+ url=url,+ headers=headers,+ json=data,+ timeout=timeout,+ )++ return video_remix_provider_config.transform_video_remix_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_remix_provider_config,+ )++ async def async_video_remix_handler(+ self,+ video_id: str,+ prompt: str,+ model: str,+ video_remix_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params,+ logging_obj,+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ timeout: Optional[float] = None,+ client=None,+ api_key: Optional[str] = None,+ ):+ """+ Async version of the video remix handler.+ """+ 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 = video_remix_provider_config.validate_environment(+ api_key=api_key,+ headers=extra_headers or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_remix_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, data = video_remix_provider_config.transform_video_remix_request(+ video_id=video_id,+ prompt=prompt,+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ extra_body=extra_body,+ )++ ## LOGGING+ logging_obj.pre_call(+ input=prompt,+ api_key="",+ additional_args={+ "complete_input_dict": data,+ "api_base": url,+ "headers": headers,+ "video_id": video_id,+ },+ )++ try:+ response = await async_httpx_client.post(+ url=url,+ headers=headers,+ json=data,+ timeout=timeout,+ )++ return video_remix_provider_config.transform_video_remix_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_remix_provider_config,+ )++ def video_list_handler(+ self,+ after: Optional[str],+ limit: Optional[int],+ order: Optional[str],+ model: str,+ video_list_provider_config,+ custom_llm_provider: str,+ litellm_params,+ logging_obj,+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ timeout: Optional[float] = None,+ _is_async: bool = False,+ client=None,+ api_key: Optional[str] = None,+ ):+ """+ Handler for video list requests.+ """+ if _is_async:+ return self.async_video_list_handler(+ after=after,+ limit=limit,+ order=order,+ model=model,+ video_list_provider_config=video_list_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ extra_headers=extra_headers,+ extra_query=extra_query,+ timeout=timeout,+ client=client,+ api_key=api_key,+ )+ else:+ # For sync calls, we'll use the async handler in a sync context+ import asyncio+ return asyncio.run(+ self.async_video_list_handler(+ after=after,+ limit=limit,+ order=order,+ model=model,+ video_list_provider_config=video_list_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ extra_headers=extra_headers,+ extra_query=extra_query,+ timeout=timeout,+ client=client,+ )+ )++ async def async_video_list_handler(+ self,+ after: Optional[str],+ limit: Optional[int],+ order: Optional[str],+ model: str,+ video_list_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params,+ logging_obj,+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ timeout: Optional[float] = None,+ client=None,+ api_key: Optional[str] = None,+ ):+ """+ Async version of the video list handler.+ """+ 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 = video_list_provider_config.validate_environment(+ api_key=api_key,+ headers=extra_headers or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_list_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, params = video_list_provider_config.transform_video_list_request(+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ after=after,+ limit=limit,+ order=order,+ extra_query=extra_query,+ )++ ## LOGGING+ logging_obj.pre_call(+ input="",+ api_key="",+ additional_args={+ "api_base": url,+ "headers": headers,+ "params": params,+ },+ )++ try:+ response = await async_httpx_client.get(+ url=url,+ headers=headers,+ params=params,+ )++ return video_list_provider_config.transform_video_list_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_list_provider_config,+ )++ async def async_video_delete_handler(+ self,+ video_id: str,+ model: str,+ video_delete_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params,+ logging_obj,+ extra_headers: Optional[Dict[str, Any]] = None,+ timeout: Optional[float] = None,+ client=None,+ api_key: Optional[str] = None,+ ):+ """+ Async version of the video delete handler.+ """+ 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 = video_delete_provider_config.validate_environment(+ api_key=api_key,+ headers=extra_headers or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_delete_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, data = video_delete_provider_config.transform_video_delete_request(+ video_id=video_id,+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ )++ ## LOGGING+ logging_obj.pre_call(+ input="",+ api_key="",+ additional_args={+ "api_base": url,+ "headers": headers,+ "video_id": video_id,+ },+ )++ try:+ response = await async_httpx_client.delete(+ url=url,+ headers=headers,+ timeout=timeout,+ )++ return video_delete_provider_config.transform_video_delete_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_delete_provider_config,+ )++ def video_status_handler(+ self,+ video_id: str,+ model: str,+ video_status_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params,+ logging_obj,+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ timeout: Optional[float] = None,+ _is_async: bool = False,+ client=None,+ api_key: Optional[str] = None,+ ):+ """+ Handler for video status requests.+ When _is_async=True, returns a coroutine instead of making the call directly.+ """+ if _is_async:+ # Return the async coroutine if called with _is_async=True+ return self.async_video_status_handler(+ video_id=video_id,+ model=model,+ video_status_provider_config=video_status_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ extra_headers=extra_headers,+ extra_body=extra_body,+ timeout=timeout,+ client=client,+ api_key=api_key,+ )++ # For sync calls, use sync HTTP client directly (like video_generation does)+ 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 = video_status_provider_config.validate_environment(+ api_key=api_key,+ headers=extra_headers or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_status_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, data = video_status_provider_config.transform_video_status_retrieve_request(+ video_id=video_id,+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ )++ ## LOGGING+ logging_obj.pre_call(+ input="",+ api_key="",+ additional_args={+ "api_base": url,+ "headers": headers,+ "video_id": video_id,+ },+ )++ try:+ response = sync_httpx_client.get(+ url=url,+ headers=headers,+ )++ return video_status_provider_config.transform_video_status_retrieve_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_status_provider_config,+ )++ async def async_video_status_handler(+ self,+ video_id: str,+ model: str,+ video_status_provider_config: BaseVideoConfig,+ custom_llm_provider: str,+ litellm_params,+ logging_obj,+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ timeout: Optional[float] = None,+ client=None,+ api_key: Optional[str] = None,+ ):+ """+ Async version of the video status handler.+ """+ 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 = video_status_provider_config.validate_environment(+ api_key=api_key,+ headers=extra_headers or {},+ model=model,+ )++ if extra_headers:+ headers.update(extra_headers)++ api_base = video_status_provider_config.get_complete_url(+ model=model,+ api_base=litellm_params.get("api_base", None),+ litellm_params=dict(litellm_params),+ )++ # Transform the request using the provider config+ url, data = video_status_provider_config.transform_video_status_retrieve_request(+ video_id=video_id,+ model=model,+ api_base=api_base,+ litellm_params=litellm_params,+ headers=headers,+ )++ ## LOGGING+ logging_obj.pre_call(+ input="",+ api_key="",+ additional_args={+ "api_base": url,+ "headers": headers,+ "video_id": video_id,+ },+ )++ try:+ response = await async_httpx_client.get(+ url=url,+ headers=headers,+ )++ return video_status_provider_config.transform_video_status_retrieve_response(+ model=model,+ raw_response=response,+ logging_obj=logging_obj,+ )++ except Exception as e:+ raise self._handle_error(+ e=e,+ provider_config=video_status_provider_config,+ )+###### VECTOR STORE HANDLER ######async def async_vector_store_search_handler(self,diff --git a/litellm/llms/openai/cost_calculation.py b/litellm/llms/openai/cost_calculation.pyindex 229f75f2657..65a50224bb8 100644--- a/litellm/llms/openai/cost_calculation.py+++ b/litellm/llms/openai/cost_calculation.py@@ -120,3 +120,47 @@ def cost_per_second(completion_cost = 0.0return prompt_cost, completion_cost+++def video_generation_cost(+ model: str,+ duration_seconds: float,+ custom_llm_provider: Optional[str] = None+) -> float:+ """+ Calculates the cost for video generation based on duration in seconds.++ Input:+ - model: str, the model name without provider prefix+ - duration_seconds: float, the duration of the generated video in seconds+ - custom_llm_provider: str, the custom llm provider++ Returns:+ float - total_cost_in_usd+ """+ ## GET MODEL INFO+ model_info = get_model_info(+ model=model, custom_llm_provider=custom_llm_provider or "openai"+ )++ # Check for video-specific cost per second+ video_cost_per_second = model_info.get("output_cost_per_video_per_second")+ if video_cost_per_second is not None:+ verbose_logger.debug(+ f"For model={model} - output_cost_per_video_per_second: {video_cost_per_second}; duration: {duration_seconds}"+ )+ return video_cost_per_second * duration_seconds++ # Fallback to general output cost per second+ output_cost_per_second = model_info.get("output_cost_per_second")+ if output_cost_per_second is not None:+ verbose_logger.debug(+ f"For model={model} - output_cost_per_second: {output_cost_per_second}; duration: {duration_seconds}"+ )+ return output_cost_per_second * duration_seconds++ # If no cost information found, return 0+ verbose_logger.warning(+ f"No cost information found for video model {model}. Please add pricing to model_prices_and_context_window.json"+ )+ return 0.0diff --git a/litellm/llms/openai/videos/transformation.py b/litellm/llms/openai/videos/transformation.pynew file mode 100644index 00000000000..09c7787a28b--- /dev/null+++ b/litellm/llms/openai/videos/transformation.py@@ -0,0 +1,394 @@+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union+from io import BufferedReader+from typing import cast+import httpx+from httpx._types import RequestFiles++from litellm.types.videos.main import VideoCreateOptionalRequestParams+from litellm.types.llms.openai import CreateVideoRequest+from litellm.types.router import GenericLiteLLMParams+from litellm.secret_managers.main import get_secret_str+from litellm.types.videos.main import VideoObject+import litellm+from litellm.llms.openai.image_edit.transformation import ImageEditRequestUtils+if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj++ from ...base_llm.videos.transformation import BaseVideoConfig as _BaseVideoConfig+ from ...base_llm.chat.transformation import BaseLLMException as _BaseLLMException++ LiteLLMLoggingObj = _LiteLLMLoggingObj+ BaseVideoConfig = _BaseVideoConfig+ BaseLLMException = _BaseLLMException+else:+ LiteLLMLoggingObj = Any+ BaseVideoConfig = Any+ BaseLLMException = Any+++class OpenAIVideoConfig(BaseVideoConfig):+ """+ Configuration class for OpenAI video generation.+ """++ def __init__(self):+ super().__init__()++ def get_supported_openai_params(self, model: str) -> list:+ """+ Get the list of supported OpenAI parameters for video generation.+ """+ return [+ "model",+ "prompt",+ "input_reference",+ "seconds",+ "size",+ "user",+ "extra_headers",+ ]++ def map_openai_params(+ self,+ video_create_optional_params: VideoCreateOptionalRequestParams,+ model: str,+ drop_params: bool,+ ) -> Dict:+ """No mapping applied since inputs are in OpenAI spec already"""+ return dict(video_create_optional_params)++ def validate_environment(+ self,+ headers: dict,+ model: str,+ api_key: Optional[str] = None,+ ) -> dict:+ api_key = (+ api_key+ or litellm.api_key+ or litellm.openai_key+ or get_secret_str("OPENAI_API_KEY")+ )+ headers.update(+ {+ "Authorization": f"Bearer {api_key}",+ }+ )+ return headers++ def get_complete_url(+ self,+ model: str,+ api_base: Optional[str],+ litellm_params: dict,+ ) -> str:+ """+ Get the complete URL for OpenAI video generation.+ """+ if api_base is None:+ api_base = "https://api.openai.com/v1"++ return f"{api_base.rstrip('/')}/videos"++ def transform_video_create_request(+ self,+ model: str,+ prompt: str,+ video_create_optional_request_params: Dict,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[Dict, RequestFiles]:+ """+ Transform the video creation request for OpenAI API.+ """+ # Remove model and extra_headers from optional params as they're handled separately+ video_create_optional_request_params = {+ k: v for k, v in video_create_optional_request_params.items()+ if k not in ["model", "extra_headers"]+ }++ # Create the request data+ video_create_request = CreateVideoRequest(+ model=model,+ prompt=prompt,+ **video_create_optional_request_params+ )+ request_dict = cast(Dict, video_create_request)++ # Handle input_reference parameter if provided+ _input_reference = video_create_optional_request_params.get("input_reference")+ data_without_files = {+ k: v for k, v in request_dict.items() if k not in ["input_reference"]+ }+ files_list: List[Tuple[str, Any]] = []++ # Handle input_reference parameter+ if _input_reference is not None:+ self._add_image_to_files(+ files_list=files_list,+ image=_input_reference,+ field_name="input_reference",+ )+ # Convert to dict for JSON serialization+ return data_without_files, files_list++ def transform_video_create_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ """+ Transform the OpenAI video creation response.+ """+ response_data = raw_response.json()++ # Transform the response data++ video_obj = VideoObject(**response_data) # type: ignore[arg-type]++ # Create usage object with duration information for cost calculation+ # Video generation API doesn't provide usage, so we create one with duration+ usage_data = {}+ if video_obj:+ if hasattr(video_obj, 'seconds') and video_obj.seconds:+ try:+ usage_data["duration_seconds"] = float(video_obj.seconds)+ except (ValueError, TypeError):+ pass+ # Create the response+ video_obj.usage = usage_data+++ return video_obj++ def transform_video_content_request(+ self,+ video_id: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[str, Dict]:+ """+ Transform the video content request for OpenAI API.++ OpenAI API expects the following request:+ - GET /v1/videos/{video_id}/content+ """+ # Construct the URL for video content download+ url = f"{api_base.rstrip('/')}/{video_id}/content"++ # Add video_id as query parameter+ params = {"video_id": video_id}++ return url, params++ def transform_video_remix_request(+ self,+ video_id: str,+ prompt: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ extra_body: Optional[Dict[str, Any]] = None,+ ) -> Tuple[str, Dict]:+ """+ Transform the video remix request for OpenAI API.++ OpenAI API expects the following request:+ - POST /v1/videos/{video_id}/remix+ """+ # Construct the URL for video remix+ url = f"{api_base.rstrip('/')}/{video_id}/remix"++ # Prepare the request data+ data = {"prompt": prompt}++ # Add any extra body parameters+ if extra_body:+ data.update(extra_body)++ return url, data++ def transform_video_content_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> bytes:+ """+ Transform the OpenAI video content download response.+ Returns raw video content as bytes.+ """+ # For video content download, return the raw content as bytes+ return raw_response.content++ def transform_video_remix_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ """+ Transform the OpenAI video remix response.+ """+ response_data = raw_response.json()++ # Transform the response data+ video_obj = VideoObject(**response_data) # type: ignore[arg-type]++ # Create usage object with duration information for cost calculation+ # Video remix API doesn't provide usage, so we create one with duration+ usage_data = {}+ if video_obj:+ if hasattr(video_obj, 'seconds') and video_obj.seconds:+ try:+ usage_data["duration_seconds"] = float(video_obj.seconds)+ except (ValueError, TypeError):+ pass+ # Create the response+ video_obj.usage = usage_data++ return video_obj++ def transform_video_list_request(+ self,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ after: Optional[str] = None,+ limit: Optional[int] = None,+ order: Optional[str] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ ) -> 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+ 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(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> Dict[str,str]:+ return raw_response.json()++ def transform_video_delete_request(+ self,+ video_id: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[str, Dict]:+ """+ Transform the video delete request for OpenAI API.++ OpenAI API expects the following request:+ - DELETE /v1/videos/{video_id}+ """+ # Construct the URL for video delete+ url = f"{api_base.rstrip('/')}/{video_id}"++ # No data needed for DELETE request+ data: Dict[str, Any] = {}++ return url, data++ def transform_video_delete_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ """+ Transform the OpenAI video delete response.+ """+ response_data = raw_response.json()++ # Transform the response data+ video_obj = VideoObject(**response_data) # type: ignore[arg-type] # type: ignore[arg-type]++ return video_obj++ def transform_video_status_retrieve_request(+ self,+ video_id: str,+ model: str,+ api_base: str,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[str, Dict]:+ """+ Transform the OpenAI video retrieve request.+ """+ # For video retrieve, we just need to construct the URL+ url = f"{api_base.rstrip('/')}/{video_id}"++ # No additional data needed for GET request+ data: Dict[str, Any] = {}++ return url, data++ def transform_video_status_retrieve_response(+ self,+ model: str,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ ) -> VideoObject:+ """+ Transform the OpenAI video retrieve response.+ """+ response_data = raw_response.json()+ # Transform the response data+ video_obj = VideoObject(**response_data) # type: ignore[arg-type]++ return video_obj++ def get_error_class(+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]+ ) -> BaseLLMException:+ from ...base_llm.chat.transformation import BaseLLMException++ raise BaseLLMException(+ status_code=status_code,+ message=error_message,+ headers=headers,+ )++ def _add_image_to_files(+ self,+ files_list: List[Tuple[str, Any]],+ image: Any,+ field_name: str,+ ) -> None:+ """Add an image to the files list with appropriate content type"""+ image_content_type = ImageEditRequestUtils.get_image_content_type(image)++ if isinstance(image, BufferedReader):+ files_list.append((field_name, (image.name, image, image_content_type)))+ else:+ files_list.append((field_name, ("input_reference.png", image, image_content_type)))\ No newline at end of filediff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.pyindex 3e650ecd111..a750b5e985f 100644--- a/litellm/llms/vertex_ai/common_utils.py+++ b/litellm/llms/vertex_ai/common_utils.py@@ -239,12 +239,12 @@ def _check_text_in_content(parts: List[PartType]) -> bool:"""check that user_content has 'text' parameter.- Known Vertex Error: Unable to submit request because it must have a text parameter.- - 'text' param needs to be len > 0+ - 'text' param needs to be present (empty strings are valid)- Relevant Issue: https://github.com/BerriAI/litellm/issues/5515"""has_text_param = Falsefor part in parts:- if "text" in part and part.get("text"):+ if "text" in part and part.get("text") is not None:has_text_param = Truereturn has_text_paramdiff --git a/litellm/llms/vertex_ai/gemini/transformation.py b/litellm/llms/vertex_ai/gemini/transformation.pyindex 28211fff6c9..4f84586cfc1 100644--- a/litellm/llms/vertex_ai/gemini/transformation.py+++ b/litellm/llms/vertex_ai/gemini/transformation.py@@ -263,7 +263,6 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915elif (_message_content is not Noneand isinstance(_message_content, str)- and len(_message_content) > 0):_part = PartType(text=_message_content)user_content.append(_part)@@ -335,9 +334,8 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915elif (_message_content is not Noneand isinstance(_message_content, str)- and _message_content):- assistant_text = _message_content # either string or none+ assistant_text = _message_contentassistant_content.append(PartType(text=assistant_text)) # type: ignore## HANDLE ASSISTANT FUNCTION CALLdiff --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.pyindex 98eecf6fb8c..257c6a599f9 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@@ -46,6 +46,8 @@ from litellm.types.llms.anthropic import AnthropicThinkingParamfrom litellm.types.llms.gemini import BidiGenerateContentServerMessagefrom litellm.types.llms.openai import (AllMessageValues,+ ChatCompletionAnnotation,+ ChatCompletionAnnotationURLCitation,ChatCompletionResponseMessage,ChatCompletionThinkingBlock,ChatCompletionToolCallChunk,@@ -1298,6 +1300,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):"""from litellm.types.utils import Delta, StreamingChoices+ annotations = chat_completion_message.get("annotations") # type: ignore# create a streaming choice objectchoice = StreamingChoices(finish_reason=VertexGeminiConfig._check_finish_reason(@@ -1310,6 +1313,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):tool_calls=tools,images=image_response,function_call=functions,+ annotations=annotations, # type: ignore),logprobs=chat_completion_logprobs,enhancements=None,@@ -1358,7 +1362,63 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):)@staticmethod- def _process_candidates(+ def _convert_grounding_metadata_to_annotations(+ grounding_metadata: List[dict],+ content_text: Optional[str],+ ) -> List[ChatCompletionAnnotation]:+ """+ Convert Vertex AI grounding metadata to OpenAI-style annotations.+ """++ annotations: List[ChatCompletionAnnotation] = []+++ for metadata in grounding_metadata:+ # Extract groundingSupports - these map text segments to sources+ grounding_supports = metadata.get("groundingSupports", [])+ grounding_chunks = metadata.get("groundingChunks", [])++ # Build a map of chunk indices to web URIs+ chunk_to_uri_map: Dict[int, Dict[str, str]] = {}+ for idx, chunk in enumerate(grounding_chunks):+ if "web" in chunk:+ web_data = chunk["web"]+ chunk_to_uri_map[idx] = {+ "url": web_data.get("uri", ""),+ "title": web_data.get("title", ""),+ }++ # Process each grounding support to create annotations+ for support in grounding_supports:+ segment = support.get("segment", {})+ start_index = segment.get("startIndex")+ end_index = segment.get("endIndex")++ # Get the chunk indices for this support+ chunk_indices = support.get("groundingChunkIndices", [])++ if start_index is not None and end_index is not None and chunk_indices:+ # Use the first chunk's URL for the annotation+ first_chunk_idx = chunk_indices[0]+ if first_chunk_idx in chunk_to_uri_map:+ uri_info = chunk_to_uri_map[first_chunk_idx]++ url_citation: ChatCompletionAnnotationURLCitation = {+ "start_index": start_index,+ "end_index": end_index,+ "url": uri_info["url"],+ "title": uri_info["title"],+ }++ annotation: ChatCompletionAnnotation = {+ "type": "url_citation",+ "url_citation": url_citation,+ }+ annotations.append(annotation)+ return annotations++ @staticmethod+ def _process_candidates( # noqa: PLR0915_candidates: List[Candidates],model_response: Union[ModelResponse, "ModelResponseStream"],standard_optional_params: dict,@@ -1446,6 +1506,14 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):if reasoning_content is not None:chat_completion_message["reasoning_content"] = reasoning_content++ if candidate_grounding_metadata:+ annotations = VertexGeminiConfig._convert_grounding_metadata_to_annotations(+ grounding_metadata=candidate_grounding_metadata,+ content_text=content,+ )+ if annotations:+ chat_completion_message["annotations"] = annotations # type: ignore(functions,tools,diff --git a/litellm/main.py b/litellm/main.pyindex 8e3f9a0b3d8..14aca084f9d 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -84,6 +84,7 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import ()from litellm.llms.base_llm import BaseConfig, BaseImageGenerationConfigfrom litellm.llms.bedrock.common_utils import BedrockModelInfo+from litellm.llms.cohere.common_utils import CohereModelInfofrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerfrom litellm.llms.vertex_ai.common_utils import (VertexAIModelRoute,@@ -2420,7 +2421,7 @@ def completion( # type: ignore # noqa: PLR0915)return responseresponse = model_response- elif custom_llm_provider == "cohere_chat" or custom_llm_provider == "cohere":+ elif custom_llm_provider == "cohere_chat" or custom_llm_provider == "cohere":cohere_key = (api_keyor litellm.cohere_key@@ -2429,12 +2430,26 @@ def completion( # type: ignore # noqa: PLR0915or litellm.api_key)- api_base = (- api_base- or litellm.api_base- or get_secret_str("COHERE_API_BASE")- or "https://api.cohere.ai/v1/chat"- )+ cohere_route = CohereModelInfo.get_cohere_route(model)+ verbose_logger.debug(f"Cohere route: {cohere_route}")+ # Set API base based on route+ if cohere_route == "v2":+ api_base = (+ api_base+ or litellm.api_base+ or get_secret_str("COHERE_API_BASE")+ or "https://api.cohere.com/v2/chat"+ )+ # Remove v2/ prefix from model name for the actual API call+ if "v2/" in model:+ model = model.replace("v2/", "")+ else:+ api_base = (+ api_base+ or litellm.api_base+ or get_secret_str("COHERE_API_BASE")+ or "https://api.cohere.ai/v1/chat"+ )headers = headers or litellm.headers or {}if headers is None:@@ -2443,6 +2458,8 @@ def completion( # type: ignore # noqa: PLR0915if extra_headers is not None:headers.update(extra_headers)+ verbose_logger.debug(f"Model: {model}, API Base: {api_base}")+ verbose_logger.debug(f"Provider Config: {provider_config}")response = base_llm_http_handler.completion(model=model,stream=stream,@@ -2458,6 +2475,7 @@ def completion( # type: ignore # noqa: PLR0915headers=headers,encoding=encoding,api_key=cohere_key,+ provider_config=provider_config,logging_obj=logging, # model call logging done inside the class as we make need to modify I/O to fit aleph alpha's requirements)elif custom_llm_provider == "maritalk":@@ -6266,6 +6284,18 @@ def stream_chunk_builder( # noqa: PLR0915processor.get_combined_reasoning_content(reasoning_chunks))+ annotation_chunks = [+ chunk+ for chunk in chunks+ if len(chunk["choices"]) > 0+ and "annotations" in chunk["choices"][0]["delta"]+ and chunk["choices"][0]["delta"]["annotations"] is not None+ ]++ if len(annotation_chunks) > 0:+ annotations = annotation_chunks[0]["choices"][0]["delta"]["annotations"]+ response["choices"][0]["message"]["annotations"] = annotations+audio_chunks = [chunkfor chunk in chunksdiff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 4804ae1de74..660fac49140 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -23832,5 +23832,60 @@"supports_tool_choice": true,"supports_vision": true,"supports_web_search": true+ },+ "sora-2": {+ "input_cost_per_second": 0.0,+ "litellm_provider": "openai",+ "mode": "video_generation",+ "output_cost_per_second": 0.0,+ "supports_video_generation": true+ },+ "azure/sora-2": {+ "litellm_provider": "azure",+ "mode": "video_generation",+ "output_cost_per_video_per_second": 0.10,+ "source": "https://azure.microsoft.com/en-us/products/ai-services/video-generation",+ "supported_modalities": [+ "text"+ ],+ "supported_output_modalities": [+ "video"+ ],+ "supported_resolutions": [+ "720x1280",+ "1280x720"+ ]+ },+ "azure/sora-2-pro": {+ "litellm_provider": "azure",+ "mode": "video_generation",+ "output_cost_per_video_per_second": 0.30,+ "source": "https://azure.microsoft.com/en-us/products/ai-services/video-generation",+ "supported_modalities": [+ "text"+ ],+ "supported_output_modalities": [+ "video"+ ],+ "supported_resolutions": [+ "720x1280",+ "1280x720"+ ]+ },+ "azure/sora-2-pro-high-res": {+ "litellm_provider": "azure",+ "mode": "video_generation",+ "output_cost_per_video_per_second": 0.50,+ "source": "https://azure.microsoft.com/en-us/products/ai-services/video-generation",+ "supported_modalities": [+ "text"+ ],+ "supported_output_modalities": [+ "video"+ ],+ "supported_resolutions": [+ "1024x1792",+ "1792x1024"+ ]}}diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 8c87622ad6e..83c5a49edf2 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -312,6 +312,11 @@ class ProxyBaseLLMRequestProcessing:"avector_store_create","aocr","asearch",+ "avideo_generation",+ "avideo_list",+ "avideo_status",+ "avideo_content",+ "avideo_remix",],version: Optional[str] = None,user_model: Optional[str] = None,@@ -404,6 +409,11 @@ class ProxyBaseLLMRequestProcessing:"avector_store_create","aocr","asearch",+ "avideo_generation",+ "avideo_list",+ "avideo_status",+ "avideo_content",+ "avideo_remix",],proxy_logging_obj: ProxyLogging,general_settings: dict,diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.pyindex 5b22b2746c9..8fb07ee2ca9 100644--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py@@ -18,14 +18,19 @@ from litellm.types.utils import (ImageResponse,ModelResponse,TextCompletionResponse,+ Choices,)+from litellm.types.utils import SpecialEnumsif TYPE_CHECKING:from ..success_handler import PassThroughEndpointLogging- from ..types import EndpointType+ from litellm.types.utils import LiteLLMBatchelse:PassThroughEndpointLogging = Any- EndpointType = Any+ LiteLLMBatch = Any++# Define EndpointType locally to avoid import issues+EndpointType = Anyclass VertexPassthroughLoggingHandler:@@ -204,6 +209,17 @@ class VertexPassthroughLoggingHandler:"result": litellm_prediction_response,"kwargs": kwargs,}+ elif "batchPredictionJobs" in url_route:+ return VertexPassthroughLoggingHandler.batch_prediction_jobs_handler(+ httpx_response=httpx_response,+ logging_obj=logging_obj,+ url_route=url_route,+ result=result,+ start_time=start_time,+ end_time=end_time,+ cache_hit=cache_hit,+ **kwargs,+ )else:return {"result": None,@@ -324,6 +340,38 @@ class VertexPassthroughLoggingHandler:return match.group(1)return "unknown"+ @staticmethod+ def extract_model_name_from_vertex_path(vertex_model_path: str) -> str:+ """+ Extract the actual model name from a Vertex AI model path.++ Examples:+ - publishers/google/models/gemini-2.5-flash -> gemini-2.5-flash+ - projects/PROJECT_ID/locations/LOCATION/models/MODEL_ID -> MODEL_ID++ Args:+ vertex_model_path: The full Vertex AI model path++ Returns:+ The extracted model name for use with LiteLLM+ """+ # Handle publishers/google/models/ format+ if "publishers/" in vertex_model_path and "models/" in vertex_model_path:+ # Extract everything after the last models/+ parts = vertex_model_path.split("models/")+ if len(parts) > 1:+ return parts[-1]++ # Handle projects/PROJECT_ID/locations/LOCATION/models/MODEL_ID format+ elif "projects/" in vertex_model_path and "models/" in vertex_model_path:+ # Extract everything after the last models/+ parts = vertex_model_path.split("models/")+ if len(parts) > 1:+ return parts[-1]++ # If no recognized pattern, return the original path+ return vertex_model_path+@staticmethoddef _get_vertex_publisher_or_api_spec_from_url(url: str) -> Optional[str]:# Check for specific Vertex AI partner publishers@@ -388,7 +436,7 @@ class VertexPassthroughLoggingHandler:end_time: datetime,logging_obj: LiteLLMLoggingObj,custom_llm_provider: str,- ):+ ) -> dict:"""Create the standard logging object for Vertex passthrough generateContent (streaming and non-streaming)@@ -412,3 +460,255 @@ class VertexPassthroughLoggingHandler:logging_obj.model_call_details["model"] = logging_obj.modellogging_obj.model_call_details["custom_llm_provider"] = custom_llm_providerreturn kwargs++ @staticmethod+ def batch_prediction_jobs_handler( # noqa: PLR0915+ httpx_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ url_route: str,+ result: str,+ start_time: datetime,+ end_time: datetime,+ cache_hit: bool,+ **kwargs,+ ) -> PassThroughEndpointLoggingTypedDict:+ """+ Handle batch prediction jobs passthrough logging.+ Creates a managed object for cost tracking when batch job is successfully created.+ """+ from litellm.llms.vertex_ai.batches.transformation import VertexAIBatchTransformation+ from litellm._uuid import uuid+ import base64++ try:+ _json_response = httpx_response.json()++ # Only handle successful batch job creation (POST requests)+ if httpx_response.status_code == 200 and "name" in _json_response:+ # Transform Vertex AI response to LiteLLM batch format+ litellm_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(+ response=_json_response+ )++ # Extract batch ID and model from the response+ batch_id = VertexAIBatchTransformation._get_batch_id_from_vertex_ai_batch_response(_json_response)+ model_name = _json_response.get("model", "unknown")++ # Create unified object ID for tracking+ # Format: base64(litellm_proxy;model_id:{};llm_batch_id:{})+ actual_model_id = VertexPassthroughLoggingHandler.get_actual_model_id_from_router(model_name)++ unified_id_string = SpecialEnums.LITELLM_MANAGED_BATCH_COMPLETE_STR.value.format(actual_model_id, batch_id)+ unified_object_id = base64.urlsafe_b64encode(unified_id_string.encode()).decode().rstrip("=")++ # Store the managed object for cost tracking+ # This will be picked up by check_batch_cost polling mechanism+ VertexPassthroughLoggingHandler._store_batch_managed_object(+ unified_object_id=unified_object_id,+ batch_object=litellm_batch_response,+ model_object_id=batch_id,+ logging_obj=logging_obj,+ **kwargs,+ )++ # Create a batch job response for logging+ litellm_model_response = ModelResponse()+ litellm_model_response.id = str(uuid.uuid4())+ litellm_model_response.model = model_name+ litellm_model_response.object = "batch_prediction_job"+ litellm_model_response.created = int(start_time.timestamp())++ # Add batch-specific metadata to indicate this is a pending batch job+ litellm_model_response.choices = [Choices(+ finish_reason="batch_pending",+ index=0,+ message={+ "role": "assistant",+ "content": f"Batch prediction job {batch_id} created and is pending. Status will be updated when the batch completes.",+ "tool_calls": None,+ "function_call": None,+ "provider_specific_fields": {+ "batch_job_id": batch_id,+ "batch_job_state": "JOB_STATE_PENDING",+ "unified_object_id": unified_object_id+ }+ }+ )]++ # Set response cost to 0 initially (will be updated when batch completes)+ response_cost = 0.0+ kwargs["response_cost"] = response_cost+ kwargs["model"] = model_name+ kwargs["batch_id"] = batch_id+ kwargs["unified_object_id"] = unified_object_id+ kwargs["batch_job_state"] = "JOB_STATE_PENDING"++ logging_obj.model = model_name+ logging_obj.model_call_details["model"] = logging_obj.model+ logging_obj.model_call_details["response_cost"] = response_cost+ logging_obj.model_call_details["batch_id"] = batch_id++ return {+ "result": litellm_model_response,+ "kwargs": kwargs,+ }+ else:+ # Handle non-successful responses+ litellm_model_response = ModelResponse()+ litellm_model_response.id = str(uuid.uuid4())+ litellm_model_response.model = "vertex_ai_batch"+ litellm_model_response.object = "batch_prediction_job"+ litellm_model_response.created = int(start_time.timestamp())++ # Add error-specific metadata+ litellm_model_response.choices = [Choices(+ finish_reason="batch_error",+ index=0,+ message={+ "role": "assistant",+ "content": f"Batch prediction job creation failed. Status: {httpx_response.status_code}",+ "tool_calls": None,+ "function_call": None,+ "provider_specific_fields": {+ "batch_job_state": "JOB_STATE_FAILED",+ "status_code": httpx_response.status_code+ }+ }+ )]++ kwargs["response_cost"] = 0.0+ kwargs["model"] = "vertex_ai_batch"+ kwargs["batch_job_state"] = "JOB_STATE_FAILED"++ return {+ "result": litellm_model_response,+ "kwargs": kwargs,+ }++ except Exception as e:+ verbose_proxy_logger.error(f"Error in batch_prediction_jobs_handler: {e}")+ # Return basic response on error+ litellm_model_response = ModelResponse()+ litellm_model_response.id = str(uuid.uuid4())+ litellm_model_response.model = "vertex_ai_batch"+ litellm_model_response.object = "batch_prediction_job"+ litellm_model_response.created = int(start_time.timestamp())++ # Add error-specific metadata+ litellm_model_response.choices = [Choices(+ finish_reason="batch_error",+ index=0,+ message={+ "role": "assistant",+ "content": f"Error creating batch prediction job: {str(e)}",+ "tool_calls": None,+ "function_call": None,+ "provider_specific_fields": {+ "batch_job_state": "JOB_STATE_FAILED",+ "error": str(e)+ }+ }+ )]++ kwargs["response_cost"] = 0.0+ kwargs["model"] = "vertex_ai_batch"+ kwargs["batch_job_state"] = "JOB_STATE_FAILED"++ return {+ "result": litellm_model_response,+ "kwargs": kwargs,+ }++ @staticmethod+ def _store_batch_managed_object(+ unified_object_id: str,+ batch_object: LiteLLMBatch,+ model_object_id: str,+ logging_obj: LiteLLMLoggingObj,+ **kwargs,+ ) -> None:+ """+ Store batch managed object for cost tracking.+ This will be picked up by the check_batch_cost polling mechanism.+ """+ try:+ # Get the managed files hook from the logging object+ # This is a bit of a hack, but we need access to the proxy logging system+ from litellm.proxy.proxy_server import proxy_logging_obj++ managed_files_hook = proxy_logging_obj.get_proxy_hook("managed_files")+ if managed_files_hook is not None and hasattr(managed_files_hook, 'store_unified_object_id'):+ # Create a mock user API key dict for the managed object storage+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.proxy._types import LitellmUserRoles+ user_api_key_dict = UserAPIKeyAuth(+ user_id=kwargs.get("user_id", "default-user"),+ api_key="",+ team_id=None,+ team_alias=None,+ user_role=LitellmUserRoles.CUSTOMER, # Use proper enum value+ user_email=None,+ max_budget=None,+ spend=0.0, # Set to 0.0 instead of None+ models=[], # Set to empty list instead of None+ tpm_limit=None,+ rpm_limit=None,+ budget_duration=None,+ budget_reset_at=None,+ max_parallel_requests=None,+ allowed_model_region=None,+ metadata={}, # Set to empty dict instead of None+ key_alias=None,+ permissions={}, # Set to empty dict instead of None+ model_max_budget={}, # Set to empty dict instead of None+ model_spend={}, # Set to empty dict instead of None+ )++ # Store the unified object for batch cost tracking+ import asyncio+ asyncio.create_task(+ managed_files_hook.store_unified_object_id(+ unified_object_id=unified_object_id,+ file_object=batch_object,+ litellm_parent_otel_span=None,+ model_object_id=model_object_id,+ file_purpose="batch",+ user_api_key_dict=user_api_key_dict,+ )+ )++ verbose_proxy_logger.info(+ f"Stored batch managed object with unified_object_id={unified_object_id}, batch_id={model_object_id}"+ )+ else:+ verbose_proxy_logger.warning("Managed files hook not available, cannot store batch object for cost tracking")++ except Exception as e:+ verbose_proxy_logger.error(f"Error storing batch managed object: {e}")++ @staticmethod+ def get_actual_model_id_from_router(model_name: str) -> str:+ from litellm.proxy.proxy_server import llm_router++ if llm_router is not None:+ # Try to find the model in the router by the extracted model name+ extracted_model_name = VertexPassthroughLoggingHandler.extract_model_name_from_vertex_path(model_name)++ # Use the existing get_model_ids method from router+ model_ids = llm_router.get_model_ids(model_name=extracted_model_name)+ if model_ids and len(model_ids) > 0:+ # Use the first model ID found+ actual_model_id = model_ids[0]+ verbose_proxy_logger.info(f"Found model ID in router: {actual_model_id}")+ return actual_model_id+ else:+ # Fallback to constructed model name+ actual_model_id = extracted_model_name+ verbose_proxy_logger.warning(f"Model not found in router, using constructed name: {actual_model_id}")+ return actual_model_id+ else:+ # Fallback if router is not available+ extracted_model_name = VertexPassthroughLoggingHandler.extract_model_name_from_vertex_path(model_name)+ verbose_proxy_logger.warning(f"Router not available, using constructed model name: {extracted_model_name}")+ return extracted_model_name+diff --git a/litellm/proxy/pass_through_endpoints/success_handler.py b/litellm/proxy/pass_through_endpoints/success_handler.pyindex a819c429f10..0c0ade848ea 100644--- a/litellm/proxy/pass_through_endpoints/success_handler.py+++ b/litellm/proxy/pass_through_endpoints/success_handler.py@@ -40,6 +40,7 @@ class PassThroughEndpointLogging:"predict","rawPredict","streamRawPredict",+ "batchPredictionJobs",]# Anthropicdiff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 3d892938ab4..0bd5ffc584b 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -309,6 +309,7 @@ from litellm.proxy.management_endpoints.user_agent_analytics_endpoints import (from litellm.proxy.management_helpers.audit_logs import create_audit_log_for_updatefrom litellm.proxy.middleware.prometheus_auth_middleware import PrometheusAuthMiddlewarefrom litellm.proxy.ocr_endpoints.endpoints import router as ocr_router+from litellm.proxy.video_endpoints.endpoints import router as video_routerfrom litellm.proxy.openai_files_endpoints.files_endpoints import (router as openai_files_router,)@@ -4177,8 +4178,12 @@ class ProxyStartupEvent:"interval",seconds=proxy_batch_polling_interval, # these can run infrequently, as batch jobs take time to complete)+ verbose_proxy_logger.info("Batch cost check job scheduled successfully")- except Exception:+ except Exception as e:+ verbose_proxy_logger.error(+ f"Failed to setup batch cost checking: {e}"+ )verbose_proxy_logger.debug("Checking batch cost for LiteLLM Managed Files is an Enterprise Feature. Skipping...")@@ -9898,6 +9903,7 @@ app.include_router(batches_router)app.include_router(public_endpoints_router)app.include_router(rerank_router)app.include_router(ocr_router)+app.include_router(video_router)app.include_router(search_router)app.include_router(image_router)app.include_router(fine_tuning_router)diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex 3afe564f7a1..735cc955ef9 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -27,6 +27,11 @@ ROUTE_ENDPOINT_MAPPING = {"acancel_responses": "/responses/{response_id}/cancel","aocr": "/ocr","asearch": "/search",+ "avideo_generation": "/videos",+ "avideo_list": "/videos",+ "avideo_status": "/videos/{video_id}",+ "avideo_content": "/videos/{video_id}/content",+ "avideo_remix": "/videos/{video_id}/remix",}@@ -102,6 +107,11 @@ async def route_request("avector_store_create","aocr","asearch",+ "avideo_generation",+ "avideo_list",+ "avideo_status",+ "avideo_content",+ "avideo_remix",],):"""diff --git a/litellm/proxy/video_endpoints/__init__.py b/litellm/proxy/video_endpoints/__init__.pynew file mode 100644index 00000000000..fe1c05f3d19--- /dev/null+++ b/litellm/proxy/video_endpoints/__init__.py@@ -0,0 +1 @@+"""Video endpoints module."""diff --git a/litellm/proxy/video_endpoints/endpoints.py b/litellm/proxy/video_endpoints/endpoints.pynew file mode 100644index 00000000000..cd1c8c40d79--- /dev/null+++ b/litellm/proxy/video_endpoints/endpoints.py@@ -0,0 +1,425 @@+#### Video Endpoints #####++import orjson+from fastapi import APIRouter, Depends, Request, Response, UploadFile, File+from fastapi.responses import ORJSONResponse+from typing import Optional++from litellm.proxy._types import *+from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth+from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing+from litellm.proxy.image_endpoints.endpoints import batch_to_bytesio+from litellm.proxy.common_utils.http_parsing_utils import _read_request_body++router = APIRouter()+++ "/v1/videos",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+ "/videos",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+async def video_generation(+ request: Request,+ fastapi_response: Response,+ input_reference: Optional[UploadFile] = File(None),+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Video generation endpoint for creating videos from text prompts.++ Follows the OpenAI Videos API spec:+ https://platform.openai.com/docs/api-reference/videos++ Example:+ ```bash+ curl -X POST "http://localhost:4000/v1/videos" \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "model": "sora-2",+ "prompt": "A beautiful sunset over the ocean"+ }'+ ```+ """+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ # Read request body+ data = await _read_request_body(request=request)+ if input_reference is not None:+ input_reference_file = await batch_to_bytesio([input_reference])+ if input_reference_file:+ data["input_reference"] = input_reference_file[0]++ # Process request using ProxyBaseLLMRequestProcessing+ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ return await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type="avideo_generation",+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )+++ "/v1/videos",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+ "/videos",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+async def video_list(+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Video list endpoint for retrieving a list of videos.++ Follows the OpenAI Videos API spec:+ https://platform.openai.com/docs/api-reference/videos++ Example:+ ```bash+ curl -X GET "http://localhost:4000/v1/videos" \+ -H "Authorization: Bearer sk-1234"+ ```+ """+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ # Read query parameters+ query_params = dict(request.query_params)+ data = {"query_params": query_params}++ # Process request using ProxyBaseLLMRequestProcessing+ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ return await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type="avideo_list",+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )+++ "/v1/videos/{video_id}",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+ "/videos/{video_id}",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+async def video_status(+ video_id: str,+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Video status endpoint for retrieving video status and metadata.++ Follows the OpenAI Videos API spec:+ https://platform.openai.com/docs/api-reference/videos++ Example:+ ```bash+ curl -X GET "http://localhost:4000/v1/videos/video_123" \+ -H "Authorization: Bearer sk-1234"+ ```+ """+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ # Create data with video_id+ data = {"video_id": video_id}++ # Process request using ProxyBaseLLMRequestProcessing+ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ return await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type="avideo_status",+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )+++ "/v1/videos/{video_id}/content",+ dependencies=[Depends(user_api_key_auth)],+ response_class=Response,+ tags=["videos"],+)+ "/videos/{video_id}/content",+ dependencies=[Depends(user_api_key_auth)],+ response_class=Response,+ tags=["videos"],+)+async def video_content(+ video_id: str,+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Video content endpoint for downloading video content.++ Follows the OpenAI Videos API spec:+ https://platform.openai.com/docs/api-reference/videos++ Example:+ ```bash+ curl -X GET "http://localhost:4000/v1/videos/video_123/content" \+ -H "Authorization: Bearer sk-1234" \+ --output video.mp4+ ```+ """+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ # Create data with video_id+ data = {"video_id": video_id}++ # Process request using ProxyBaseLLMRequestProcessing+ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ # Call the video content function directly to get raw bytes+ video_bytes = await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type="avideo_content",+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )++ # Return raw video bytes with proper content type+ return Response(+ content=video_bytes,+ media_type="video/mp4",+ headers={+ "Content-Disposition": f"attachment; filename=video_{video_id}.mp4"+ }+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )+++ "/v1/videos/{video_id}/remix",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+ "/videos/{video_id}/remix",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["videos"],+)+async def video_remix(+ video_id: str,+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Video remix endpoint for remixing existing videos with new prompts.++ Follows the OpenAI Videos API spec:+ https://platform.openai.com/docs/api-reference/videos++ Example:+ ```bash+ curl -X POST "http://localhost:4000/v1/videos/video_123/remix" \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "prompt": "A new version with different colors"+ }'+ ```+ """+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ # Read request body+ body = await request.body()+ data = orjson.loads(body)+ data["video_id"] = video_id++ # Process request using ProxyBaseLLMRequestProcessing+ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ return await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type="avideo_remix",+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.pyindex 0582780e87d..7c79c575a5b 100644--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py@@ -29,6 +29,7 @@ from litellm.types.llms.openai import (ResponsesAPIResponse,ResponsesAPIStreamEvents,ResponsesAPIStreamingResponse,+ OutputTextAnnotationAddedEvent)from litellm.types.utils import Delta as ChatCompletionDeltafrom litellm.types.utils import (@@ -73,6 +74,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):self.sent_output_text_done_event: bool = Falseself.sent_output_content_part_done_event: bool = Falseself.sent_output_item_done_event: bool = False+ self.sent_annotation_events: bool = Falseself.litellm_model_response: Optional[Union[ModelResponse, TextCompletionResponse]] = None@@ -201,6 +203,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):text = getattr(litellm_complete_object.choices[0].message, "content", "") or "" # type: ignorereasoning_content = getattr(litellm_complete_object.choices[0].message, "reasoning_content", "") or "" # type: ignore+ annotations = getattr(litellm_complete_object.choices[0].message, "annotations", None) # type: ignorepart: Optional[PART_UNION_TYPES] = Noneif reasoning_content:@@ -210,10 +213,13 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):)else:+ response_annotations = LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(+ annotations=annotations+ )part = ContentPartDonePartOutputText(type="output_text",text=text,- annotations=[],+ annotations=response_annotations, # type: ignorelogprobs=None,)@@ -229,6 +235,11 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):self, litellm_complete_object: ModelResponse) -> OutputItemDoneEvent:text = self.litellm_model_response.choices[0].message.content or "" # type: ignore+ annotations = getattr(self.litellm_model_response.choices[0].message, "annotations", None) # type: ignore++ response_annotations = LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(+ annotations=annotations+ )return OutputItemDoneEvent(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,output_index=0,@@ -243,7 +254,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):{"type": "output_text","text": text,- "annotations": [],+ "annotations": response_annotations,}],}@@ -397,7 +408,33 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):This currently handles emitting the OutputTextDeltaEvent, which is used by other tools using the responses APIand the ReasoningSummaryTextDeltaEvent, which is used by the responses API to emit reasoning content.+ It also handles emitting annotation.added events when annotations are detected in the chunk."""+ # Check if this chunk has annotations first (before processing text/reasoning)+ # This ensures we detect and queue annotation events from the annotation chunk+ if chunk.choices and hasattr(chunk.choices[0].delta, "annotations"):+ annotations = chunk.choices[0].delta.annotations+ if annotations and self.sent_annotation_events is False:+ self.sent_annotation_events = True+ # Store annotation events to emit them one by one+ if not hasattr(self, '_pending_annotation_events'):++ response_annotations = LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(+ annotations=annotations+ )+ self._pending_annotation_events = []+ for idx, annotation in enumerate(response_annotations):+ annotation_dict = annotation.model_dump() if hasattr(annotation, 'model_dump') else dict(annotation)+ event = OutputTextAnnotationAddedEvent(+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_ANNOTATION_ADDED,+ item_id=chunk.id,+ output_index=0,+ content_index=0,+ annotation_index=idx,+ annotation=annotation_dict,+ )+ self._pending_annotation_events.append(event)+ # Priority 1: Handle reasoning content (highest priority)if (chunk.choicesand hasattr(chunk.choices[0].delta, "reasoning_content")@@ -411,16 +448,23 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):output_index=0,delta=reasoning_content,)- else:- delta_content = self._get_delta_string_from_streaming_choices(chunk.choices)- if delta_content:- return OutputTextDeltaEvent(- type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,- item_id=chunk.id,- output_index=0,- content_index=0,- delta=delta_content,- )++ # Priority 2: Handle text deltas+ delta_content = self._get_delta_string_from_streaming_choices(chunk.choices)+ if delta_content:+ return OutputTextDeltaEvent(+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,+ item_id=chunk.id,+ output_index=0,+ content_index=0,+ delta=delta_content,+ )++ # Priority 3: If we have pending annotation events, emit the next one+ # This happens when the current chunk has no text/reasoning content+ if hasattr(self, '_pending_annotation_events') and self._pending_annotation_events:+ event = self._pending_annotation_events.pop(0)+ return eventreturn Nonediff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex 31637f6657e..cec34712c1e 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -841,12 +841,15 @@ class LiteLLMCompletionResponsesConfig:def _transform_chat_message_to_response_output_text(message: Message,) -> OutputText:+ annotations = getattr(message, "annotations", None)+ transformed_annotations = LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(+ annotations=annotations+ )+return OutputText(type="output_text",text=message.content,- annotations=LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(- annotations=getattr(message, "annotations", None)- ),+ annotations=transformed_annotations,)@staticmethoddiff --git a/litellm/router.py b/litellm/router.pyindex 18499cd6ac0..5b6fc56f292 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -890,6 +890,32 @@ class Router:self.asearch = self.factory_function(asearch, call_type="asearch")self.search = self.factory_function(search, call_type="search")+ # Video routes+ #########################################################+ from litellm.videos import (+ avideo_generation,+ video_generation,+ avideo_list,+ video_list,+ avideo_status,+ video_status,+ avideo_content,+ video_content,+ avideo_remix,+ video_remix,+ )++ self.avideo_generation = self.factory_function(avideo_generation, call_type="avideo_generation")+ self.video_generation = self.factory_function(video_generation, call_type="video_generation")+ self.avideo_list = self.factory_function(avideo_list, call_type="avideo_list")+ self.video_list = self.factory_function(video_list, call_type="video_list")+ self.avideo_status = self.factory_function(avideo_status, call_type="avideo_status")+ self.video_status = self.factory_function(video_status, call_type="video_status")+ self.avideo_content = self.factory_function(avideo_content, call_type="avideo_content")+ self.video_content = self.factory_function(video_content, call_type="video_content")+ self.avideo_remix = self.factory_function(avideo_remix, call_type="avideo_remix")+ self.video_remix = self.factory_function(video_remix, call_type="video_remix")+def validate_fallbacks(self, fallback_param: Optional[List]):"""Validate the fallbacks parameter.@@ -3624,7 +3650,17 @@ class Router:"ocr","asearch","search",- "aadapter_generate_content"+ "aadapter_generate_content",+ "avideo_generation",+ "video_generation",+ "avideo_list",+ "video_list",+ "avideo_status",+ "video_status",+ "avideo_content",+ "video_content",+ "avideo_remix",+ "video_remix"] = "assistants",):"""@@ -3643,6 +3679,11 @@ class Router:"vector_store_create","ocr","search",+ "video_generation",+ "video_list",+ "video_status",+ "video_content",+ "video_remix",):def sync_wrapper(@@ -3692,6 +3733,11 @@ class Router:"agenerate_content_stream","aocr","ocr",+ "avideo_generation",+ "avideo_list",+ "avideo_status",+ "avideo_content",+ "avideo_remix",):return await self._ageneric_api_call_with_fallbacks(original_function=original_function,diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.pyindex a9333e0061d..00410fe7732 100644--- a/litellm/types/llms/openai.py+++ b/litellm/types/llms/openai.py@@ -1847,3 +1847,88 @@ class OpenAIMcpServerTool(TypedDict, total=False):require_approval: strallowed_tools: Optional[List[str]]headers: Optional[Dict[str, str]]+++# Video Generation Types+class CreateVideoRequest(TypedDict, total=False):+ """+ CreateVideoRequest for OpenAI video generation API++ Required Params:+ prompt: str - Text prompt that describes the video to generate++ Optional Params:+ input_reference: Optional[str] - Optional image reference that guides generation+ model: Optional[str] - The video generation model to use (defaults to sora-2)+ seconds: Optional[str] - Clip duration in seconds (defaults to 4 seconds)+ size: Optional[str] - Output resolution formatted as width x height (defaults to 720x1280)+ user: Optional[str] - A unique identifier representing your end-user+ extra_headers: Optional[Dict[str, str]] - Additional headers+ extra_body: Optional[Dict[str, str]] - Additional body parameters+ timeout: Optional[float] - Request timeout+ """+ prompt: Required[str]+ input_reference: Optional[str]+ model: Optional[str]+ seconds: Optional[str]+ size: Optional[str]+ user: Optional[str]+ extra_headers: Optional[Dict[str, str]]+ extra_body: Optional[Dict[str, str]]+ timeout: Optional[float]+++class OpenAIVideoObject(BaseModel):+ """OpenAI Video Object representing a video generation job."""+ id: str+ """Unique identifier for the video job."""++ object: Literal["video"]+ """The object type, which is always 'video'."""++ status: str+ """Current lifecycle status of the video job."""++ created_at: int+ """Unix timestamp (seconds) for when the job was created."""++ completed_at: Optional[int] = None+ """Unix timestamp (seconds) for when the job completed, if finished."""++ expires_at: Optional[int] = None+ """Unix timestamp (seconds) for when the downloadable assets expire, if set."""++ error: Optional[Dict[str, Any]] = None+ """Error payload that explains why generation failed, if applicable."""++ progress: Optional[int] = None+ """Approximate completion percentage for the generation task."""++ remixed_from_video_id: Optional[str] = None+ """Identifier of the source video if this video is a remix."""++ seconds: Optional[str] = None+ """Duration of the generated clip in seconds."""++ size: Optional[str] = None+ """The resolution of the generated video."""++ model: Optional[str] = None+ """The video generation model that produced the job."""++ _hidden_params: Dict[str, Any] = {}++ def __contains__(self, key):+ return hasattr(self, key)++ def get(self, key, default=None):+ return getattr(self, key, default)++ def __getitem__(self, key):+ return getattr(self, key)++ def json(self, **kwargs): # type: ignore+ try:+ return self.model_dump(**kwargs)+ except Exception:+ return self.dict()diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 8a100f9c35e..31daaaf24fd 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -278,6 +278,24 @@ class CallTypes(str, Enum):file_content = "file_content"create_fine_tuning_job = "create_fine_tuning_job"acreate_fine_tuning_job = "acreate_fine_tuning_job"++ #########################################################+ # Video Generation Call Types+ #########################################################+ create_video = "create_video"+ acreate_video = "acreate_video"+ avideo_retrieve = "avideo_retrieve"+ video_retrieve = "video_retrieve"+ avideo_content = "avideo_content"+ video_content = "video_content"+ video_remix = "video_remix"+ avideo_remix = "avideo_remix"+ video_list = "video_list"+ avideo_list = "avideo_list"+ video_retrieve_job = "video_retrieve_job"+ avideo_retrieve_job = "avideo_retrieve_job"+ video_delete = "video_delete"+ avideo_delete = "avideo_delete"acancel_fine_tuning_job = "acancel_fine_tuning_job"cancel_fine_tuning_job = "cancel_fine_tuning_job"alist_fine_tuning_jobs = "alist_fine_tuning_jobs"@@ -1157,7 +1175,6 @@ class StreamingChatCompletionChunk(OpenAIChatCompletionChunk):super().__init__(**kwargs)-from openai.types.chat import ChatCompletionChunkclass ModelResponseBase(OpenAIObject):diff --git a/litellm/types/videos/main.py b/litellm/types/videos/main.pynew file mode 100644index 00000000000..f33e1d5a441--- /dev/null+++ b/litellm/types/videos/main.py@@ -0,0 +1,89 @@+from typing import Any, Dict, List, Literal, Optional+from typing_extensions import TypedDict++from pydantic import BaseModel+from litellm.types.utils import FileTypes+++class VideoObject(BaseModel):+ """Represents a generated video object."""+ id: str+ object: Literal["video"]+ status: str+ created_at: int+ completed_at: Optional[int] = None+ expires_at: Optional[int] = None+ error: Optional[Dict[str, Any]] = None+ progress: Optional[int] = None+ remixed_from_video_id: Optional[str] = None+ seconds: Optional[str] = None+ size: Optional[str] = None+ model: Optional[str] = None+ usage: Optional[Dict[str, Any]] = None+ _hidden_params: Dict[str, Any] = {}++ def __contains__(self, key):+ # Define custom behavior for the 'in' operator+ return hasattr(self, key)++ def get(self, key, default=None):+ # Custom .get() method to access attributes with a default value if the attribute doesn't exist+ return getattr(self, key, default)++ def __getitem__(self, key):+ # Allow dictionary-style access to attributes+ return getattr(self, key)++ def json(self, **kwargs): # type: ignore+ try:+ return self.model_dump(**kwargs)+ except Exception:+ # if using pydantic v1+ return self.dict()+++++class VideoResponse(BaseModel):+ """Response object for video generation requests."""+ data: List[VideoObject]+ hidden_params: Dict[str, Any] = {}++ def __contains__(self, key):+ return hasattr(self, key)++ def get(self, key, default=None):+ return getattr(self, key, default)++ def __getitem__(self, key):+ return getattr(self, key)++ def json(self, **kwargs): # type: ignore+ try:+ return self.model_dump(**kwargs)+ except Exception:+ return self.dict()+++class VideoCreateOptionalRequestParams(TypedDict, total=False):+ """+ TypedDict for Optional parameters supported by OpenAI's video creation API.++ Params here: https://platform.openai.com/docs/api-reference/videos/create+ """+ input_reference: Optional[FileTypes] # File reference for input image+ model: Optional[str]+ seconds: Optional[str]+ size: Optional[str]+ user: Optional[str]+ extra_headers: Optional[Dict[str, str]]+ extra_body: Optional[Dict[str, str]]+++class VideoCreateRequestParams(VideoCreateOptionalRequestParams, total=False):+ """+ TypedDict for request parameters supported by OpenAI's video creation API.++ Params here: https://platform.openai.com/docs/api-reference/videos/create+ """+ prompt: strdiff --git a/litellm/utils.py b/litellm/utils.pyindex b1a0b13e776..cb712b69684 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -147,6 +147,7 @@ from litellm.llms.base_llm.ocr.transformation import BaseOCRConfigfrom litellm.llms.base_llm.search.transformation import BaseSearchConfigfrom litellm.llms.base_llm.text_to_speech.transformation import BaseTextToSpeechConfigfrom litellm.llms.bedrock.common_utils import BedrockModelInfo+from litellm.llms.cohere.common_utils import CohereModelInfofrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerfrom litellm.llms.mistral.ocr.transformation import MistralOCRConfigfrom litellm.router_utils.get_retry_from_policy import (@@ -265,6 +266,7 @@ from litellm.llms.base_llm.image_generation.transformation import (from litellm.llms.base_llm.image_variations.transformation import (BaseImageVariationConfig,)+from litellm.llms.base_llm.videos.transformation import BaseVideoConfigfrom litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfigfrom litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfigfrom litellm.llms.base_llm.rerank.transformation import BaseRerankConfig@@ -4974,6 +4976,7 @@ def _get_model_info_helper( # noqa: PLR0915"output_cost_per_token_above_200k_tokens", None),output_cost_per_second=_model_info.get("output_cost_per_second", None),+ output_cost_per_video_per_second=_model_info.get("output_cost_per_video_per_second", None),output_cost_per_image=_model_info.get("output_cost_per_image", None),output_vector_size=_model_info.get("output_vector_size", None),citation_cost_per_token=_model_info.get(@@ -6978,7 +6981,12 @@ class ProviderConfigManager:litellm.LlmProviders.COHERE_CHAT == provideror litellm.LlmProviders.COHERE == provider):- return litellm.CohereChatConfig()+ route = CohereModelInfo.get_cohere_route(model)+ if route == "v2":+ return litellm.CohereV2ChatConfig()+ else:++ return litellm.CohereChatConfig()elif litellm.LlmProviders.SNOWFLAKE == provider:return litellm.SnowflakeConfig()elif litellm.LlmProviders.CLARIFAI == provider:@@ -7179,6 +7187,8 @@ class ProviderConfigManager:return litellm.AmazonDeepSeekR1Config()elif bedrock_invoke_provider == "nova":return litellm.AmazonInvokeNovaConfig()+ elif bedrock_invoke_provider == "qwen3":+ return litellm.AmazonQwen3Config()else:return litellm.AmazonInvokeConfig()elif litellm.LlmProviders.LITELLM_PROXY == provider:@@ -7589,6 +7599,26 @@ class ProviderConfigManager:return LiteLLMProxyImageGenerationConfig()return None+ @staticmethod+ def get_provider_video_config(+ model: str,+ provider: LlmProviders,+ ) -> Optional[BaseVideoConfig]:+ if LlmProviders.OPENAI == provider:+ from litellm.llms.openai.videos.transformation import (+ OpenAIVideoConfig,+ )++ return OpenAIVideoConfig()+ elif LlmProviders.AZURE == provider:+ from litellm.llms.azure.videos.transformation import (+ AzureVideoConfig,+ )++ return AzureVideoConfig()+ return None++@staticmethoddef get_provider_realtime_config(model: str,diff --git a/litellm/videos/__init__.py b/litellm/videos/__init__.pynew file mode 100644index 00000000000..716add5f5d7--- /dev/null+++ b/litellm/videos/__init__.py@@ -0,0 +1,27 @@+"""Video generation and management functions for LiteLLM."""++from .main import (+ avideo_generation,+ video_generation,+ avideo_list,+ video_list,+ avideo_status,+ video_status,+ avideo_content,+ video_content,+ avideo_remix,+ video_remix,+)++__all__ = [+ "avideo_generation",+ "video_generation",+ "avideo_list",+ "video_list",+ "avideo_status",+ "video_status",+ "avideo_content",+ "video_content",+ "avideo_remix",+ "video_remix",+]diff --git a/litellm/videos/main.py b/litellm/videos/main.pynew file mode 100644index 00000000000..9f99c47ca4e--- /dev/null+++ b/litellm/videos/main.py@@ -0,0 +1,1137 @@+import asyncio+import contextvars+from functools import partial+from typing import Any, Coroutine, Literal, Optional, Union, overload, Dict, List++import json+import litellm+from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider+from litellm.types.videos.main import (+ VideoCreateOptionalRequestParams,+ VideoObject,+)+from litellm.videos.utils import VideoGenerationRequestUtils+from litellm.constants import DEFAULT_VIDEO_ENDPOINT_MODEL, request_timeout as DEFAULT_REQUEST_TIMEOUT+from litellm.main import base_llm_http_handler+from litellm.utils import client, ProviderConfigManager+from litellm.types.utils import FileTypes, CallTypes+from litellm.types.router import GenericLiteLLMParams+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.base_llm.videos.transformation import BaseVideoConfig+from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler++#################### Initialize provider clients ####################+llm_http_handler: BaseLLMHTTPHandler = BaseLLMHTTPHandler()++##### Video Generation #######################+@client+async def avideo_generation(+ prompt: str,+ model: Optional[str] = None,+ input_reference: Optional[FileTypes] = None,+ seconds: Optional[str] = None,+ size: Optional[str] = None,+ user: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> VideoObject:+ """+ Asynchronously calls the `video_generation` function with the given arguments and keyword arguments.++ Parameters:+ - `prompt` (str): Text prompt that describes the video to generate+ - `model` (Optional[str]): The video generation model to use+ - `input_reference` (Optional[FileTypes]): Optional image reference that guides generation+ - `seconds` (Optional[str]): Clip duration in seconds+ - `size` (Optional[str]): Output resolution formatted as width x height+ - `user` (Optional[str]): A unique identifier representing your end-user+ - `timeout` (int): Request timeout in seconds+ - `custom_llm_provider` (Optional[str]): The LLM provider to use+ - `extra_headers` (Optional[Dict[str, Any]]): Additional headers+ - `extra_query` (Optional[Dict[str, Any]]): Additional query parameters+ - `extra_body` (Optional[Dict[str, Any]]): Additional body parameters+ - `kwargs` (dict): Additional keyword arguments++ Returns:+ - `response` (VideoResponse): The response returned by the `video_generation` function.+ """+ local_vars = locals()+ try:+ loop = asyncio.get_event_loop()+ kwargs["async_call"] = True++ # get custom llm provider so we can use this for mapping exceptions+ if custom_llm_provider is None:+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL, api_base=local_vars.get("api_base", None)+ )++ func = partial(+ video_generation,+ prompt=prompt,+ model=model,+ input_reference=input_reference,+ seconds=seconds,+ size=size,+ user=user,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ extra_query=extra_query,+ extra_body=extra_body,+ **kwargs,+ )++ ctx = contextvars.copy_context()+ func_with_context = partial(ctx.run, func)+ init_response = await loop.run_in_executor(None, func_with_context)++ if asyncio.iscoroutine(init_response):+ response = await init_response+ else:+ response = init_response++ return response+ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++# fmt: off++# Overload for when avideo_generation=True (returns Coroutine)+@overload+def video_generation(+ prompt: str,+ model: Optional[str] = None,+ input_reference: Optional[str] = None,+ size: Optional[str] = None,+ user: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_generation: Literal[True],+ **kwargs,+) -> Coroutine[Any, Any, VideoObject]:+ ...+++@overload+def video_generation(+ prompt: str,+ model: Optional[str] = None,+ input_reference: Optional[str] = None,+ seconds: Optional[str] = None,+ size: Optional[str] = None,+ user: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_generation: Literal[False] = False,+ **kwargs,+) -> VideoObject:+ ...++# fmt: on+++@client+def video_generation( # noqa: PLR0915+ prompt: str,+ model: Optional[str] = None,+ input_reference: Optional[FileTypes] = None,+ seconds: Optional[str] = None,+ size: Optional[str] = None,+ user: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> Union[+ VideoObject,+ Coroutine[Any, Any, VideoObject],+]:+ """+ Maps the https://api.openai.com/v1/videos endpoint.++ Currently supports OpenAI+ """+ local_vars = locals()+ try:+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.pop("litellm_logging_obj") # type: ignore+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)+ _is_async = kwargs.pop("async_call", False) is True++ # Check for mock response first+ mock_response = kwargs.get("mock_response", None)+ if mock_response is not None:+ if isinstance(mock_response, str):+ mock_response = json.loads(mock_response)++ response = VideoObject(**mock_response)+ return response++ # get llm provider logic+ litellm_params = GenericLiteLLMParams(**kwargs)+ model, custom_llm_provider, _, _ = get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL,+ custom_llm_provider=custom_llm_provider,+ )++ # get provider config+ video_generation_provider_config: Optional[BaseVideoConfig] = (+ ProviderConfigManager.get_provider_video_config(+ model=model,+ provider=litellm.LlmProviders(custom_llm_provider),+ )+ )++ if video_generation_provider_config is None:+ raise ValueError(f"image edit is not supported for {custom_llm_provider}")++ local_vars.update(kwargs)+ # Get VideoGenerationOptionalRequestParams with only valid parameters+ video_generation_optional_params: VideoCreateOptionalRequestParams = (+ VideoGenerationRequestUtils.get_requested_video_generation_optional_param(local_vars)+ )++ # Get optional parameters for the responses API+ video_generation_request_params: Dict = (+ VideoGenerationRequestUtils.get_optional_params_video_generation(+ model=model,+ video_generation_provider_config=video_generation_provider_config,+ video_generation_optional_params=video_generation_optional_params,+ )+ )++ # Pre Call logging+ litellm_logging_obj.update_environment_variables(+ model=model,+ user=user,+ optional_params=dict(video_generation_request_params),+ litellm_params={+ "litellm_call_id": litellm_call_id,+ **video_generation_request_params,+ },+ custom_llm_provider=custom_llm_provider,+ )++ # Set the correct call type for video generation+ litellm_logging_obj.call_type = CallTypes.create_video.value++ # Call the handler with _is_async flag instead of directly calling the async handler+ return base_llm_http_handler.video_generation_handler(+ model=model,+ prompt=prompt,+ video_generation_provider_config=video_generation_provider_config,+ video_generation_optional_request_params=video_generation_request_params,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=litellm_logging_obj,+ extra_headers=extra_headers,+ extra_body=extra_body,+ timeout=timeout or DEFAULT_REQUEST_TIMEOUT,+ _is_async=_is_async,+ client=kwargs.get("client"),+ )++ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++@client+def video_content(+ video_id: str,+ model: Optional[str] = None,+ api_base: Optional[str] = None,+ timeout: Optional[float] = None,+ custom_llm_provider: Optional[str] = None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> Union[+ bytes,+ Coroutine[Any, Any, bytes],+]:+ """+ Download video content from OpenAI's video API.++ Args:+ video_id (str): The identifier of the video whose content to download.+ model (Optional[str]): The model to use. If not provided, will be auto-detected.+ api_key (Optional[str]): The API key to use for authentication.+ api_base (Optional[str]): The base URL for the API.+ timeout (Optional[float]): The timeout for the request in seconds.+ custom_llm_provider (Optional[str]): The LLM provider to use. If not provided, will be auto-detected.+ variant (Optional[str]): Which downloadable asset to return. Defaults to the MP4 video.+ extra_headers (Optional[Dict[str, Any]]): Additional headers to include in the request.+ extra_query (Optional[Dict[str, Any]]): Additional query parameters.+ extra_body (Optional[Dict[str, Any]]): Additional body parameters.++ Returns:+ bytes: The raw video content as bytes.++ Example:+ ```python+ import litellm++ # Download video content+ video_bytes = litellm.video_content(+ video_id="video_123",+ custom_llm_provider="openai"+ )++ # Save to file+ with open("video.mp4", "wb") as f:+ f.write(video_bytes)+ ```+ """+ local_vars = locals()+ try:+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)+ _is_async = kwargs.pop("async_call", False) is True++ # get llm provider logic+ litellm_params = GenericLiteLLMParams(**kwargs)+ model, custom_llm_provider, _, _ = get_llm_provider(+ model=model or "sora-2", # Default model for video content+ custom_llm_provider=custom_llm_provider,+ )++ # get provider config+ video_provider_config: Optional[BaseVideoConfig] = (+ ProviderConfigManager.get_provider_video_config(+ model=model,+ provider=litellm.LlmProviders(custom_llm_provider),+ )+ )++ if video_provider_config is None:+ raise ValueError(f"video support download is not supported for {custom_llm_provider}")++ local_vars.update(kwargs)+ # For video content download, we don't need complex optional parameter handling+ # Just pass the basic parameters that are relevant for content download+ video_content_request_params: Dict = {+ "video_id": video_id,+ }++ # Pre Call logging+ litellm_logging_obj.update_environment_variables(+ model=model,+ user=kwargs.get("user"),+ optional_params=dict(video_content_request_params),+ litellm_params={+ "litellm_call_id": litellm_call_id,+ **video_content_request_params,+ },+ custom_llm_provider=custom_llm_provider,+ )++ # Call the handler with _is_async flag instead of directly calling the async handler+ return base_llm_http_handler.video_content_handler(+ video_id=video_id,+ model=model,+ video_content_provider_config=video_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=litellm_logging_obj,+ timeout=timeout or DEFAULT_REQUEST_TIMEOUT,+ extra_headers=extra_headers,+ client=kwargs.get("client"),+ _is_async=_is_async,+ )++ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++##### Video Content Download #######################+@client+async def avideo_content(+ video_id: str,+ model: Optional[str] = None,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ timeout: Optional[float] = None,+ custom_llm_provider: Optional[str] = None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> bytes:+ """+ Asynchronously download video content.++ Parameters:+ - `video_id` (str): The identifier of the video whose content to download+ - `model` (Optional[str]): The model to use. If not provided, will be auto-detected+ - `api_key` (Optional[str]): The API key to use for authentication+ - `api_base` (Optional[str]): The base URL for the API+ - `timeout` (Optional[float]): The timeout for the request in seconds+ - `custom_llm_provider` (Optional[str]): The LLM provider to use+ - `extra_headers` (Optional[Dict[str, Any]]): Additional headers+ - `extra_query` (Optional[Dict[str, Any]]): Additional query parameters+ - `extra_body` (Optional[Dict[str, Any]]): Additional body parameters+ - `kwargs` (dict): Additional keyword arguments++ Returns:+ - `bytes`: The raw video content as bytes+ """+ local_vars = locals()+ try:+ loop = asyncio.get_event_loop()+ kwargs["async_call"] = True++ # get custom llm provider so we can use this for mapping exceptions+ if custom_llm_provider is None:+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL, api_base=api_base+ )++ func = partial(+ video_content,+ video_id=video_id,+ model=model,+ api_key=api_key,+ api_base=api_base,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ extra_query=extra_query,+ extra_body=extra_body,+ **kwargs,+ )++ ctx = contextvars.copy_context()+ func_with_context = partial(ctx.run, func)+ init_response = await loop.run_in_executor(None, func_with_context)++ if asyncio.iscoroutine(init_response):+ response = await init_response+ else:+ response = init_response++ return response+ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )++##### Video Remix #######################+@client+async def avideo_remix(+ video_id: str,+ prompt: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> VideoObject:+ """+ Asynchronously calls the `video_remix` function with the given arguments and keyword arguments.++ Parameters:+ - `video_id` (str): The identifier of the completed video to remix+ - `prompt` (str): Updated text prompt that directs the remix generation+ - `model` (Optional[str]): The video generation model to use+ - `timeout` (int): Request timeout in seconds+ - `custom_llm_provider` (Optional[str]): The LLM provider to use+ - `extra_headers` (Optional[Dict[str, Any]]): Additional headers+ - `extra_query` (Optional[Dict[str, Any]]): Additional query parameters+ - `extra_body` (Optional[Dict[str, Any]]): Additional body parameters+ - `kwargs` (dict): Additional keyword arguments++ Returns:+ - `response` (VideoObject): The response returned by the `video_remix` function.+ """+ local_vars = locals()+ try:+ loop = asyncio.get_event_loop()+ kwargs["async_call"] = True++ # get custom llm provider so we can use this for mapping exceptions+ if custom_llm_provider is None:+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL, api_base=local_vars.get("api_base", None)+ )++ func = partial(+ video_remix,+ video_id=video_id,+ prompt=prompt,+ model=model,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ extra_query=extra_query,+ extra_body=extra_body,+ **kwargs,+ )++ ctx = contextvars.copy_context()+ func_with_context = partial(ctx.run, func)+ init_response = await loop.run_in_executor(None, func_with_context)++ if asyncio.iscoroutine(init_response):+ response = await init_response+ else:+ response = init_response++ return response+ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++# fmt: off++# Overload for when avideo_remix=True (returns Coroutine)+@overload+def video_remix(+ video_id: str,+ prompt: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_remix: Literal[True],+ **kwargs,+) -> Coroutine[Any, Any, VideoObject]:+ ...+++@overload+def video_remix(+ video_id: str,+ prompt: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_remix: Literal[False] = False,+ **kwargs,+) -> VideoObject:+ ...++# fmt: on+++@client+def video_remix( # noqa: PLR0915+ video_id: str,+ prompt: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> Union[+ VideoObject,+ Coroutine[Any, Any, VideoObject],+]:+ """+ Maps the https://api.openai.com/v1/videos/{video_id}/remix endpoint.++ Currently supports OpenAI+ """+ local_vars = locals()+ try:+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.pop("litellm_logging_obj") # type: ignore+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)+ _is_async = kwargs.pop("async_call", False) is True++ # Check for mock response first+ mock_response = kwargs.get("mock_response", None)+ if mock_response is not None:+ if isinstance(mock_response, str):+ mock_response = json.loads(mock_response)++ response = VideoObject(**mock_response)+ return response++ # get llm provider logic+ litellm_params = GenericLiteLLMParams(**kwargs)+ model, custom_llm_provider, _, _ = get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL,+ custom_llm_provider=custom_llm_provider,+ )++ # get provider config+ video_remix_provider_config: Optional[BaseVideoConfig] = (+ ProviderConfigManager.get_provider_video_config(+ model=model,+ provider=litellm.LlmProviders(custom_llm_provider),+ )+ )++ if video_remix_provider_config is None:+ raise ValueError(f"video remix is not supported for {custom_llm_provider}")++ local_vars.update(kwargs)+ # For video remix, we need the video_id and prompt+ video_remix_request_params: Dict = {+ "video_id": video_id,+ "prompt": prompt,+ }++ # Pre Call logging+ litellm_logging_obj.update_environment_variables(+ model=model,+ user=kwargs.get("user"),+ optional_params=dict(video_remix_request_params),+ litellm_params={+ "litellm_call_id": litellm_call_id,+ **video_remix_request_params,+ },+ custom_llm_provider=custom_llm_provider,+ )++ # Set the correct call type for video remix+ litellm_logging_obj.call_type = CallTypes.video_remix.value++ # Call the handler with _is_async flag instead of directly calling the async handler+ return base_llm_http_handler.video_remix_handler(+ video_id=video_id,+ prompt=prompt,+ model=model,+ video_remix_provider_config=video_remix_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=litellm_logging_obj,+ extra_headers=extra_headers,+ extra_body=extra_body,+ timeout=timeout or DEFAULT_REQUEST_TIMEOUT,+ _is_async=_is_async,+ client=kwargs.get("client"),+ )++ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++##### Video List #######################+@client+async def avideo_list(+ after: Optional[str] = None,+ limit: Optional[int] = None,+ order: Optional[str] = None,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> List[VideoObject]:+ """+ Asynchronously calls the `video_list` function with the given arguments and keyword arguments.++ Parameters:+ - `after` (Optional[str]): Identifier for the last item from the previous pagination request+ - `limit` (Optional[int]): Number of items to retrieve+ - `order` (Optional[str]): Sort order of results by timestamp. Use asc for ascending order or desc for descending order+ - `model` (Optional[str]): The video generation model to use+ - `timeout` (int): Request timeout in seconds+ - `custom_llm_provider` (Optional[str]): The LLM provider to use+ - `extra_headers` (Optional[Dict[str, Any]]): Additional headers+ - `extra_query` (Optional[Dict[str, Any]]): Additional query parameters+ - `extra_body` (Optional[Dict[str, Any]]): Additional body parameters+ - `kwargs` (dict): Additional keyword arguments++ Returns:+ - `response` (Dict[str, Any]): The response returned by the `video_list` function.+ """+ local_vars = locals()+ try:+ loop = asyncio.get_event_loop()+ kwargs["async_call"] = True++ # get custom llm provider so we can use this for mapping exceptions+ if custom_llm_provider is None:+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL, api_base=local_vars.get("api_base", None)+ )++ func = partial(+ video_list,+ after=after,+ limit=limit,+ order=order,+ model=model,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ extra_query=extra_query,+ extra_body=extra_body,+ **kwargs,+ )++ ctx = contextvars.copy_context()+ func_with_context = partial(ctx.run, func)+ init_response = await loop.run_in_executor(None, func_with_context)++ if asyncio.iscoroutine(init_response):+ response = await init_response+ else:+ response = init_response++ return response+ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++# fmt: off++# Overload for when avideo_list=True (returns Coroutine)+@overload+def video_list(+ after: Optional[str] = None,+ limit: Optional[int] = None,+ order: Optional[str] = None,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_list: Literal[True],+ **kwargs,+) -> Coroutine[Any, Any, List[VideoObject]]:+ ...+++@overload+def video_list(+ after: Optional[str] = None,+ limit: Optional[int] = None,+ order: Optional[str] = None,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_list: Literal[False] = False,+ **kwargs,+) -> List[VideoObject]:+ ...++# fmt: on+++@client+def video_list( # noqa: PLR0915+ after: Optional[str] = None,+ limit: Optional[int] = None,+ order: Optional[str] = None,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> Union[+ List[VideoObject],+ Coroutine[Any, Any, List[VideoObject]],+]:+ """+ Maps the https://api.openai.com/v1/videos endpoint.++ Currently supports OpenAI+ """+ local_vars = locals()+ try:+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)+ _is_async = kwargs.pop("async_call", False) is True++ # Check for mock response first+ mock_response = kwargs.get("mock_response", None)+ if mock_response is not None:+ if isinstance(mock_response, str):+ mock_response = json.loads(mock_response)+ return [VideoObject(**item) for item in mock_response]++ # get llm provider logic+ litellm_params = GenericLiteLLMParams(**kwargs)+ model, custom_llm_provider, _, _ = get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL,+ custom_llm_provider=custom_llm_provider,+ )++ # get provider config+ video_list_provider_config: Optional[BaseVideoConfig] = (+ ProviderConfigManager.get_provider_video_config(+ model=model,+ provider=litellm.LlmProviders(custom_llm_provider),+ )+ )++ if video_list_provider_config is None:+ raise ValueError(f"video list is not supported for {custom_llm_provider}")++ local_vars.update(kwargs)+ # For video list, we need the query parameters+ video_list_request_params: Dict = {+ "after": after,+ "limit": limit,+ "order": order,+ }++ # Pre Call logging+ litellm_logging_obj.update_environment_variables(+ model=model,+ user=kwargs.get("user"),+ optional_params=dict(video_list_request_params),+ litellm_params={+ "litellm_call_id": litellm_call_id,+ **video_list_request_params,+ },+ custom_llm_provider=custom_llm_provider,+ )++ # Set the correct call type for video list+ litellm_logging_obj.call_type = CallTypes.video_list.value++ # Call the handler with _is_async flag instead of directly calling the async handler+ return base_llm_http_handler.video_list_handler(+ after=after,+ limit=limit,+ order=order,+ model=model,+ video_list_provider_config=video_list_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=litellm_logging_obj,+ extra_headers=extra_headers,+ extra_query=extra_query,+ timeout=timeout or DEFAULT_REQUEST_TIMEOUT,+ _is_async=_is_async,+ client=kwargs.get("client"),+ )++ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++##### Video Status/Retrieve #######################+@client+async def avideo_status(+ video_id: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> VideoObject:+ """+ Asynchronously retrieve video status from OpenAI's video API.++ Parameters:+ - `video_id` (str): The identifier of the video whose status to retrieve+ - `model` (Optional[str]): The model to use. If not provided, will be auto-detected+ - `timeout` (int): Request timeout in seconds+ - `custom_llm_provider` (Optional[str]): The LLM provider to use+ - `extra_headers` (Optional[Dict[str, Any]]): Additional headers+ - `extra_query` (Optional[Dict[str, Any]]): Additional query parameters+ - `extra_body` (Optional[Dict[str, Any]]): Additional body parameters+ - `kwargs` (dict): Additional keyword arguments++ Returns:+ - `response` (VideoObject): The response returned by the `video_status` function.+"""+ local_vars = locals()+ try:+ loop = asyncio.get_event_loop()+ kwargs["async_call"] = True++ # get custom llm provider so we can use this for mapping exceptions+ if custom_llm_provider is None:+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL, api_base=local_vars.get("api_base", None)+ )++ func = partial(+ video_status,+ video_id=video_id,+ model=model,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ extra_query=extra_query,+ extra_body=extra_body,+ **kwargs,+ )++ ctx = contextvars.copy_context()+ func_with_context = partial(ctx.run, func)+ init_response = await loop.run_in_executor(None, func_with_context)++ if asyncio.iscoroutine(init_response):+ response = await init_response+ else:+ response = init_response++ return response+ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++# fmt: off++# Overload for when avideo_status=True (returns Coroutine)+@overload+def video_status(+ video_id: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_status: Literal[True],+ **kwargs,+) -> Coroutine[Any, Any, VideoObject]:+ ...++# Overload for when avideo_status=False (returns VideoObject)+@overload+def video_status(+ video_id: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider=None,+ *,+ avideo_status: Literal[False] = False,+ **kwargs,+) -> VideoObject:+ ...++# fmt: on+++@client+def video_status( # noqa: PLR0915+ video_id: str,+ model: Optional[str] = None,+ timeout=600, # default to 10 minutes+ custom_llm_provider=None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> Union[+ VideoObject,+ Coroutine[Any, Any, VideoObject],+]:+ """+ Retrieve video status from OpenAI's video API.++ Args:+ video_id (str): The identifier of the video whose status to retrieve.+ model (Optional[str]): The model to use. If not provided, will be auto-detected.+ timeout (int): The timeout for the request in seconds.+ custom_llm_provider (Optional[str]): The LLM provider to use. If not provided, will be auto-detected.+ extra_headers (Optional[Dict[str, Any]]): Additional headers to include in the request.+ extra_query (Optional[Dict[str, Any]]): Additional query parameters.+ extra_body (Optional[Dict[str, Any]]): Additional body parameters.++ Returns:+ VideoObject: The video status information.++ Example:+ ```python+ import litellm++ # Get video status+ video_status = litellm.video_status(+ video_id="video_123",+ custom_llm_provider="openai"+ )++ print(f"Video status: {video_status.status}")+ print(f"Progress: {video_status.progress}%")+ ```+ """+ local_vars = locals()+ try:+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)+ _is_async = kwargs.pop("async_call", False) is True++ # Check for mock response first+ mock_response = kwargs.get("mock_response", None)+ if mock_response is not None:+ if isinstance(mock_response, str):+ mock_response = json.loads(mock_response)++ response = VideoObject(**mock_response)+ return response++ # get llm provider logic+ litellm_params = GenericLiteLLMParams(**kwargs)+ model, custom_llm_provider, _, _ = get_llm_provider(+ model=model or DEFAULT_VIDEO_ENDPOINT_MODEL,+ custom_llm_provider=custom_llm_provider,+ )++ # get provider config+ video_status_provider_config: Optional[BaseVideoConfig] = (+ ProviderConfigManager.get_provider_video_config(+ model=model,+ provider=litellm.LlmProviders(custom_llm_provider),+ )+ )++ if video_status_provider_config is None:+ raise ValueError(f"video status is not supported for {custom_llm_provider}")++ local_vars.update(kwargs)+ # For video status, we need the video_id+ video_status_request_params: Dict = {+ "video_id": video_id,+ }++ # Pre Call logging+ litellm_logging_obj.update_environment_variables(+ model=model,+ user=kwargs.get("user"),+ optional_params=dict(video_status_request_params),+ litellm_params={+ "litellm_call_id": litellm_call_id,+ **video_status_request_params,+ },+ custom_llm_provider=custom_llm_provider,+ )++ # Set the correct call type for video status+ litellm_logging_obj.call_type = CallTypes.video_retrieve.value++ # Call the handler with _is_async flag instead of directly calling the async handler+ return base_llm_http_handler.video_status_handler(+ video_id=video_id,+ model=model,+ video_status_provider_config=video_status_provider_config,+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ logging_obj=litellm_logging_obj,+ extra_headers=extra_headers,+ extra_body=extra_body,+ timeout=timeout or DEFAULT_REQUEST_TIMEOUT,+ _is_async=_is_async,+ client=kwargs.get("client"),+ )++ except Exception as e:+ raise litellm.exception_type(+ model=model,+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )diff --git a/litellm/videos/utils.py b/litellm/videos/utils.pynew file mode 100644index 00000000000..7cfccab6720--- /dev/null+++ b/litellm/videos/utils.py@@ -0,0 +1,74 @@+from typing import Any, Dict, cast, get_type_hints++import litellm+from litellm.llms.base_llm.videos.transformation import BaseVideoConfig+from litellm.types.videos.main import VideoCreateOptionalRequestParams+++class VideoGenerationRequestUtils:+ """Helper utils for constructing video generation requests"""++ @staticmethod+ def get_optional_params_video_generation(+ model: str,+ video_generation_provider_config: BaseVideoConfig,+ video_generation_optional_params: VideoCreateOptionalRequestParams,+ ) -> Dict:+ """+ Get optional parameters for the video generation API.++ Args:+ model: The model name+ video_generation_provider_config: The provider configuration for video generation API+ video_generation_optional_params: The optional parameters for video generation++ Returns:+ A dictionary of supported parameters for the video generation API+ """+ # Get supported parameters for the model+ supported_params = video_generation_provider_config.get_supported_openai_params(model)++ # Check for unsupported parameters+ unsupported_params = [+ param+ for param in video_generation_optional_params+ if param not in supported_params+ ]++ if unsupported_params:+ raise litellm.UnsupportedParamsError(+ model=model,+ message=(+ f"The following parameters are not supported for model {model}: "+ f"{', '.join(unsupported_params)}"+ ),+ )++ # Map parameters to provider-specific format+ mapped_params = video_generation_provider_config.map_openai_params(+ video_create_optional_params=video_generation_optional_params,+ model=model,+ drop_params=litellm.drop_params,+ )++ return mapped_params++ @staticmethod+ def get_requested_video_generation_optional_param(+ params: Dict[str, Any],+ ) -> VideoCreateOptionalRequestParams:+ """+ Filter parameters to only include those defined in VideoCreateOptionalRequestParams.++ Args:+ params: Dictionary of parameters to filter++ Returns:+ VideoCreateOptionalRequestParams instance with only the valid parameters+ """+ valid_keys = get_type_hints(VideoCreateOptionalRequestParams).keys()+ filtered_params = {+ k: v for k, v in params.items() if k in valid_keys and v is not None+ }++ return cast(VideoCreateOptionalRequestParams, filtered_params)diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 4804ae1de74..21c9f53dc4f 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -23832,5 +23832,69 @@"supports_tool_choice": true,"supports_vision": true,"supports_web_search": true+ },+ "openai/sora-2": {+ "litellm_provider": "openai",+ "mode": "video_generation",+ "output_cost_per_video_per_second": 0.10,+ "source": "https://platform.openai.com/docs/api-reference/videos",+ "supported_modalities": [+ "text"+ ],+ "supported_output_modalities": [+ "video"+ ],+ "supported_resolutions": [+ "720x1280",+ "1280x720"+ ]+ },+ "azure/sora-2": {+ "litellm_provider": "azure",+ "mode": "video_generation",+ "output_cost_per_video_per_second": 0.10,+ "source": "https://azure.microsoft.com/en-us/products/ai-services/video-generation",+ "supported_modalities": [+ "text"+ ],+ "supported_output_modalities": [+ "video"+ ],+ "supported_resolutions": [+ "720x1280",+ "1280x720"+ ]+ },+ "azure/sora-2-pro": {+ "litellm_provider": "azure",+ "mode": "video_generation",+ "output_cost_per_video_per_second": 0.30,+ "source": "https://azure.microsoft.com/en-us/products/ai-services/video-generation",+ "supported_modalities": [+ "text"+ ],+ "supported_output_modalities": [+ "video"+ ],+ "supported_resolutions": [+ "720x1280",+ "1280x720"+ ]+ },+ "azure/sora-2-pro-high-res": {+ "litellm_provider": "azure",+ "mode": "video_generation",+ "output_cost_per_video_per_second": 0.50,+ "source": "https://azure.microsoft.com/en-us/products/ai-services/video-generation",+ "supported_modalities": [+ "text"+ ],+ "supported_output_modalities": [+ "video"+ ],+ "supported_resolutions": [+ "1024x1792",+ "1792x1024"+ ]}}diff --git a/tests/llm_translation/test_cohere.py b/tests/llm_translation/test_cohere.pyindex 110c0c281a7..a47fc5443af 100644--- a/tests/llm_translation/test_cohere.py+++ b/tests/llm_translation/test_cohere.py@@ -37,7 +37,7 @@ async def test_chat_completion_cohere_citations(stream):},]response = await litellm.acompletion(- model="cohere_chat/command-r",+ model="cohere_chat/v1/command-r",messages=messages,documents=[{"title": "Tall penguins", "text": "Emperor penguins are the tallest."},@@ -96,7 +96,7 @@ def test_completion_cohere_command_r_plus_function_call():try:# test without max tokensresponse = completion(- model="command-r-plus",+ model="cohere_chat/v1/command-r-plus",messages=messages,tools=tools,tool_choice="auto",@@ -128,7 +128,7 @@ def test_completion_cohere():},]response = completion(- model="command-r",+ model="cohere_chat/v1/command-r",messages=messages,)print(response)@@ -152,13 +152,13 @@ async def test_chat_completion_cohere(sync_mode):]if sync_mode is False:response = await litellm.acompletion(- model="cohere_chat/command-r",+ model="cohere_chat/v1/command-r",messages=messages,max_tokens=10,)else:response = completion(- model="cohere_chat/command-r",+ model="cohere_chat/v1/command-r",messages=messages,max_tokens=10,)@@ -181,7 +181,7 @@ async def test_chat_completion_cohere_stream(sync_mode):]if sync_mode is False:response = await litellm.acompletion(- model="cohere_chat/command-r",+ model="cohere_chat/v1/command-r",messages=messages,max_tokens=10,stream=True,@@ -191,7 +191,7 @@ async def test_chat_completion_cohere_stream(sync_mode):print(chunk)else:response = completion(- model="cohere_chat/command-r",+ model="cohere_chat/v1/command-r",messages=messages,max_tokens=10,stream=True,@@ -242,7 +242,7 @@ async def test_cohere_request_body_with_allowed_params():with patch("litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post", return_value=mock_response) as mock_post:try:await litellm.acompletion(- model="cohere/command",+ model="cohere/v1/command",messages=[{"content": "what llm are you", "role": "user"}],allowed_openai_params=["tools", "response_format", "reasoning_effort"],response_format=test_response_format,@@ -487,5 +487,359 @@ def test_cohere_embed_v4_with_optional_params():assert all(isinstance(x, float) for x in response.data[0]['embedding'])assert isinstance(response.usage, litellm.Usage)+ except Exception as e:+ pytest.fail(f"Error occurred: {e}")+++# ==================== COHERE V2 API TESTS ====================+[email protected]("sync_mode", [True, False])[email protected](retries=3, delay=1)+async def test_cohere_v2_chat_completion(sync_mode):+ """Test basic Cohere v2 chat completion functionality."""+ try:+ litellm.set_verbose = True+ messages = [+ {"role": "system", "content": "You are a helpful assistant."},+ {"role": "user", "content": "Hello, how are you?"}+ ]++ if sync_mode:+ response = completion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=messages,+ max_tokens=50+ )+ else:+ response = await litellm.acompletion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=messages,+ max_tokens=50+ )++ # Validate response structure+ assert response.choices is not None+ assert len(response.choices) > 0+ assert response.choices[0].message.content is not None+ assert response.usage is not None+ assert response.usage.total_tokens > 0+ print(f"Cohere v2 response: {response}")++ except litellm.ServiceUnavailableError:+ pass # Skip if service is unavailable+ except Exception as e:+ pytest.fail(f"Error occurred: {e}")++[email protected]("stream", [True, False])[email protected](retries=3, delay=1)+async def test_cohere_v2_streaming(stream):+ """Test Cohere v2 streaming functionality."""+ try:+ litellm.set_verbose = True+ messages = [+ {"role": "user", "content": "Tell me a short story about a robot."}+ ]++ response = await litellm.acompletion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=messages,+ max_tokens=100,+ stream=stream+ )++ if stream:+ # Test streaming response+ chunks = []+ async for chunk in response:+ chunks.append(chunk)+ if len(chunks) >= 3: # Test first few chunks+ break+ assert len(chunks) > 0+ print(f"Received {len(chunks)} streaming chunks")+ else:+ # Test non-streaming response+ assert response.choices is not None+ assert len(response.choices) > 0+ assert response.choices[0].message.content is not None+ print(f"Non-streaming response: {response.choices[0].message.content}")++ except litellm.ServiceUnavailableError:+ pass+ except Exception as e:+ pytest.fail(f"Error occurred: {e}")+++def test_cohere_v2_tool_calling():+ """Test Cohere v2 tool calling functionality."""+ try:+ litellm.set_verbose = True+ tools = [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get the current weather in a given location",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {+ "type": "string",+ "description": "The city and state, e.g. San Francisco, CA"+ },+ "unit": {+ "type": "string",+ "enum": ["celsius", "fahrenheit"]+ }+ },+ "required": ["location"]+ }+ }+ }+ ]++ messages = [+ {"role": "user", "content": "What's the weather like in New York?"}+ ]++ response = completion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=messages,+ tools=tools,+ tool_choice="auto",+ max_tokens=100+ )++ # Validate tool calling response+ assert response.choices is not None+ assert len(response.choices) > 0+ message = response.choices[0].message++ # Check if tool calls are present+ if hasattr(message, 'tool_calls') and message.tool_calls:+ assert len(message.tool_calls) > 0+ tool_call = message.tool_calls[0]+ assert tool_call.function.name == "get_weather"+ assert tool_call.function.arguments is not None+ print(f"Tool call: {tool_call.function.name} - {tool_call.function.arguments}")+ else:+ # If no tool calls, check that we got a regular response+ assert message.content is not None+ print(f"Regular response: {message.content}")++ except litellm.ServiceUnavailableError:+ pass+ except Exception as e:+ pytest.fail(f"Error occurred: {e}")++[email protected]("stream", [True, False])[email protected](retries=3, delay=1)+async def test_cohere_v2_citations(stream):+ """Test Cohere v2 citations functionality."""+ try:+ litellm.set_verbose = True+ messages = [+ {"role": "user", "content": "What are the benefits of renewable energy?"}+ ]++ documents = [+ {+ "data": {+ "title": "Test Document 1",+ "snippet": "This is test content 1"+ }+ },+ {+ "data": {+ "title": "Test Document 2",+ "snippet": "This is test content 2"+ }+ }+ ]++ response = await litellm.acompletion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=messages,+ documents=documents,+ max_tokens=100,+ stream=stream+ )++ if stream:+ # Test streaming with citations+ citations_found = False+ async for chunk in response:+ if hasattr(chunk, 'citations') and chunk.citations:+ citations_found = True+ print(f"Streaming citations: {chunk.citations}")+ break+ # Note: Citations might not appear in every chunk during streaming+ else:+ # Test non-streaming with citations+ assert response.choices is not None+ assert len(response.choices) > 0++ # Check for citations in response+ if hasattr(response, 'citations') and response.citations:+ assert len(response.citations) > 0+ print(f"Citations: {response.citations}")+ else:+ # Citations might not always be present depending on the response+ print("No citations in this response")++ except litellm.ServiceUnavailableError:+ pass+ except Exception as e:+ pytest.fail(f"Error occurred: {e}")+++def test_cohere_v2_parameter_mapping():+ """Test Cohere v2 parameter mapping and validation."""+ try:+ litellm.set_verbose = True+ messages = [+ {"role": "user", "content": "Generate a creative story."}+ ]++ # Test various parameters that should be mapped correctly+ response = completion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=messages,+ temperature=0.7,+ max_tokens=50,+ top_p=0.9,+ frequency_penalty=0.1,+ presence_penalty=0.1,+ stop=["END", "STOP"],+ seed=42+ )++ # Validate response+ assert response.choices is not None+ assert len(response.choices) > 0+ assert response.choices[0].message.content is not None+ assert response.usage is not None+ print(f"Parameter mapping test response: {response.choices[0].message.content}")++ except litellm.ServiceUnavailableError:+ pass+ except Exception as e:+ pytest.fail(f"Error occurred: {e}")++def test_cohere_v2_error_handling():+ """Test Cohere v2 error handling with invalid parameters."""+ try:+ # Test with invalid model name+ try:+ response = completion(+ model="cohere_chat/v2/invalid-model",+ messages=[{"role": "user", "content": "Hello"}],+ max_tokens=10+ )+ # If we get here, the test should fail+ pytest.fail("Should have failed with invalid model")+ except Exception as e:+ # Expected to fail with invalid model+ print(f"Expected error with invalid model: {e}")++ # Test with empty messages+ try:+ response = completion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=[], # Empty messages+ max_tokens=10+ )+ pytest.fail("Should have failed with empty messages")+ except Exception as e:+ # Expected to fail with empty messages+ print(f"Expected error with empty messages: {e}")++ except Exception as e:+ pytest.fail(f"Unexpected error in error handling test: {e}")+++async def test_cohere_documents_options_in_request_body():+ """+ Test that documents parameters is properly included+ in the request body after transformation (sent via extra_body).+ """+ # Create a mock response+ mock_response = AsyncMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "text": "Test response with citations",+ "generation_id": "mock-generation-id",+ "finish_reason": "COMPLETE"+ }++ # Mock the AsyncHTTPHandler.post method+ with patch("litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post", return_value=mock_response) as mock_post:+ try:+ # Test documents and citation_options parameters+ test_documents = [+ {+ "data": {+ "title": "Test Document 1",+ "snippet": "This is test content 1"+ }+ },+ {+ "data": {+ "title": "Test Document 2",+ "snippet": "This is test content 2"+ }+ }+ ]+ await litellm.acompletion(+ model="cohere_chat/command-a-03-2025",+ messages=[{"role": "user", "content": "Test message"}],+ documents=test_documents,+ )+ except Exception:+ pass # We only care about the request body validation++ # Verify the API call was made+ mock_post.assert_called_once()++ # Get and parse the request body+ request_data = json.loads(mock_post.call_args.kwargs["data"])+ print(f"Request body: {request_data}")++ # Validate that documents and citation_options are in the request body+ assert "documents" in request_data+ assert request_data["documents"] == test_documents+++async def test_cohere_v2_conversation_history():+ """Test Cohere v2 with conversation history."""+ try:+ litellm.set_verbose = True+ messages = [+ {"role": "system", "content": "You are a helpful assistant."},+ {"role": "user", "content": "What is 2+2?"},+ {"role": "assistant", "content": "2+2 equals 4."},+ {"role": "user", "content": "What about 3+3?"}+ ]++ response = await litellm.acompletion(+ model="cohere_chat/v2/command-a-03-2025",+ messages=messages,+ max_tokens=50+ )++ # Validate response with conversation history+ assert response.choices is not None+ assert len(response.choices) > 0+ assert response.choices[0].message.content is not None+ print(f"Conversation history response: {response.choices[0].message.content}")++ except litellm.ServiceUnavailableError:+ passexcept Exception as e:pytest.fail(f"Error occurred: {e}")\ No newline at end of filediff --git a/tests/test_litellm/integrations/SlackAlerting/test_slack_alerting.py b/tests/test_litellm/integrations/SlackAlerting/test_slack_alerting.pyindex 9cccdb51799..128a88a0f12 100644--- a/tests/test_litellm/integrations/SlackAlerting/test_slack_alerting.py+++ b/tests/test_litellm/integrations/SlackAlerting/test_slack_alerting.py@@ -196,3 +196,47 @@ class TestSlackAlerting(unittest.TestCase):self.assertIn("Level: `Medium`", formatted_message)self.assertIn("Timestamp: `12:34:56`", formatted_message)self.assertIn("Message: Test alert message", formatted_message)++ def test_original_redis_error_reproduction(self):+ """Test that reproduces the original Redis serialization error."""+ # This test verifies that the original error would occur without our fix+ outage_value = {+ "alerts": [408],+ "deployment_ids": {"zapier-multi-provider-gemini-2.5-flash-1ite-vertex"},+ "last_updated_at": 1760601633.6620142,+ "major_alert_sent": False,+ "minor_alert_sent": False,+ "provider_region_id": "vertex_aius-east1"+ }++ # This should raise a TypeError due to set not being JSON serializable+ with self.assertRaises(TypeError) as context:+ json.dumps(outage_value)++ # Verify the specific error message+ self.assertIn("Object of type set is not JSON serializable", str(context.exception))++ def test_fixed_redis_serialization(self):+ """Test that our fix resolves the Redis serialization error."""+ # Same data that caused the original error+ outage_value = {+ "alerts": [408],+ "deployment_ids": {"zapier-multi-provider-gemini-2.5-flash-1ite-vertex"},+ "last_updated_at": 1760601633.6620142,+ "major_alert_sent": False,+ "minor_alert_sent": False,+ "provider_region_id": "vertex_aius-east1"+ }++ # Apply our fix+ cache_value = self.slack_alerting._prepare_outage_value_for_cache(outage_value)++ # This should now work without errors+ json_str = json.dumps(cache_value)+ self.assertIsInstance(json_str, str)++ # Verify the data is correct+ parsed_data = json.loads(json_str)+ self.assertEqual(parsed_data["deployment_ids"], ["zapier-multi-provider-gemini-2.5-flash-1ite-vertex"])+ self.assertEqual(parsed_data["alerts"], [408])+ self.assertEqual(parsed_data["provider_region_id"], "vertex_aius-east1")diff --git a/tests/test_litellm/llms/azure/test_azure_common_utils.py b/tests/test_litellm/llms/azure/test_azure_common_utils.pyindex 582c7db8187..d4f6e3d8fb3 100644--- a/tests/test_litellm/llms/azure/test_azure_common_utils.py+++ b/tests/test_litellm/llms/azure/test_azure_common_utils.py@@ -510,6 +510,18 @@ async def test_ensure_initialize_azure_sdk_client_always_used(call_type):"custom_llm_provider": "azure","file_id": "123",},+ "avideo_content": {+ "custom_llm_provider": "azure",+ "video_id": "123",+ },+ "avideo_list": {+ "custom_llm_provider": "azure",+ },+ "avideo_remix": {+ "custom_llm_provider": "azure",+ "video_id": "123",+ "prompt": "A new video based on this one",+ },}# Get appropriate input for this call type@@ -543,6 +555,13 @@ async def test_ensure_initialize_azure_sdk_client_always_used(call_type):patch_target = ("litellm.files.main.azure_files_instance.initialize_azure_sdk_client")+ elif (+ call_type == CallTypes.avideo_content+ or call_type == CallTypes.avideo_list+ or call_type == CallTypes.avideo_remix+ ):+ # Skip video call types as they don't use Azure SDK client initialization+ pytest.skip(f"Skipping {call_type.value} because Azure video calls don't use initialize_azure_sdk_client")# Mock the initialize_azure_sdk_client functionwith patch(patch_target) as mock_init_azure:diff --git a/tests/test_litellm/llms/azure/videos/test_azure_video_transformation.py b/tests/test_litellm/llms/azure/videos/test_azure_video_transformation.pynew file mode 100644index 00000000000..dd59461fdc5--- /dev/null+++ b/tests/test_litellm/llms/azure/videos/test_azure_video_transformation.py@@ -0,0 +1,389 @@+import json+import os+import sys+from typing import Any, Dict, Optional+from unittest.mock import MagicMock, patch, Mock, mock_open+import pytest+import httpx++# Add the parent directory to the system path+sys.path.insert(+ 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../../.."))+)++import litellm+from litellm.llms.azure.videos.transformation import AzureVideoConfig+from litellm.types.videos.main import VideoObject, VideoResponse, VideoCreateOptionalRequestParams+from litellm.types.router import GenericLiteLLMParams+++class TestAzureVideoConfig:+ """Test class for Azure video configuration and transformations."""++ def setup_method(self):+ """Set up test fixtures before each test method."""+ self.config = AzureVideoConfig()+ self.model = "azure/sora-2"+ self.api_base = "https://your-resource.openai.azure.com"+ self.api_key = "test-api-key"++ def test_get_supported_openai_params(self):+ """Test getting supported OpenAI parameters for video generation."""+ supported_params = self.config.get_supported_openai_params(self.model)++ expected_params = [+ "model",+ "prompt",+ "input_reference",+ "seconds",+ "size",+ "user",+ "extra_headers",+ ]++ assert supported_params == expected_params+ assert len(supported_params) == 7++ def test_map_openai_params(self):+ """Test mapping OpenAI parameters for video generation."""+ video_params = VideoCreateOptionalRequestParams(+ prompt="A beautiful sunset over mountains",+ seconds=10,+ size="1280x720",+ user="test_user"+ )++ result = self.config.map_openai_params(+ video_create_optional_params=video_params,+ model=self.model,+ drop_params=False+ )++ # Should return the same dict since no mapping is needed+ assert result["prompt"] == "A beautiful sunset over mountains"+ assert result["seconds"] == 10+ assert result["size"] == "1280x720"+ assert result["user"] == "test_user"++ def test_validate_environment_with_api_key(self):+ """Test environment validation with provided API key."""+ headers = {"Content-Type": "application/json"}++ result_headers = self.config.validate_environment(+ headers=headers,+ model=self.model,+ api_key=self.api_key+ )++ assert "Authorization" in result_headers+ assert result_headers["Authorization"] == f"Bearer {self.api_key}"+ assert result_headers["Content-Type"] == "application/json"++ @patch('litellm.llms.azure.videos.transformation.get_secret_str')+ @patch('litellm.llms.azure.videos.transformation.litellm')+ def test_validate_environment_without_api_key(self, mock_litellm, mock_get_secret):+ """Test environment validation without provided API key."""+ mock_litellm.api_key = None+ mock_litellm.azure_key = None+ mock_get_secret.return_value = "secret-api-key"++ headers = {"Content-Type": "application/json"}++ result_headers = self.config.validate_environment(+ headers=headers,+ model=self.model,+ api_key=None+ )++ assert "Authorization" in result_headers+ assert result_headers["Authorization"] == "Bearer secret-api-key"++ def test_get_complete_url(self):+ """Test URL construction for Azure video API."""+ litellm_params = {+ "api_base": self.api_base,+ "api_version": "2024-02-15-preview"+ }++ url = self.config.get_complete_url(+ model=self.model,+ api_base=self.api_base,+ litellm_params=litellm_params+ )++ # Should contain the Azure base URL and video endpoint+ assert "/openai/v1/videos" in url+ assert self.api_base in url++ def test_transform_video_create_request(self):+ """Test video creation request transformation."""+ video_params = {+ "seconds": 8,+ "size": "720x1280"+ }++ litellm_params = GenericLiteLLMParams(+ model=self.model,+ api_base=self.api_base,+ api_key=self.api_key+ )++ headers = {"Authorization": f"Bearer {self.api_key}"}++ data, files = self.config.transform_video_create_request(+ model=self.model,+ prompt="A cinematic shot of a city at night",+ video_create_optional_request_params=video_params,+ litellm_params=litellm_params,+ headers=headers+ )++ assert data["prompt"] == "A cinematic shot of a city at night"+ assert data["seconds"] == 8+ assert data["size"] == "720x1280"+ assert data["model"] == self.model++ def test_transform_video_create_response(self):+ """Test video creation response transformation."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "id": "video_azure_123",+ "object": "video",+ "status": "queued",+ "created_at": 1712697600,+ "model": "sora-2"+ }++ logging_obj = MagicMock()++ result = self.config.transform_video_create_response(+ model=self.model,+ raw_response=mock_response,+ logging_obj=logging_obj+ )++ assert isinstance(result, VideoObject)+ assert result.id == "video_azure_123"+ assert result.object == "video"+ assert result.status == "queued"+ assert result.model == "sora-2"++ def test_transform_video_remix_response(self):+ """Test video remix response transformation."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "id": "video_remix_azure_123",+ "object": "video",+ "status": "queued",+ "created_at": 1712697600,+ "model": "sora-2",+ "remixed_from_video_id": "video_azure_123"+ }++ logging_obj = MagicMock()++ result = self.config.transform_video_remix_response(+ model=self.model,+ raw_response=mock_response,+ logging_obj=logging_obj+ )++ assert isinstance(result, VideoObject)+ assert result.id == "video_remix_azure_123"+ assert result.status == "queued"+ assert hasattr(result, 'remixed_from_video_id')+ assert result.remixed_from_video_id == "video_azure_123"++ def test_transform_video_delete_response(self):+ """Test video delete response transformation."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "id": "video_azure_123",+ "object": "video",+ "deleted": True,+ "status": "deleted",+ "created_at": 1712697600+ }++ logging_obj = MagicMock()++ result = self.config.transform_video_delete_response(+ model=self.model,+ raw_response=mock_response,+ logging_obj=logging_obj+ )++ assert isinstance(result, VideoObject)+ assert result.id == "video_azure_123"+ assert result.object == "video"+ assert result.status == "deleted"++ def test_transform_video_content_response(self):+ """Test video content response transformation."""+ mock_response = MagicMock()+ mock_response.content = b"fake video content"++ logging_obj = MagicMock()++ result = self.config.transform_video_content_response(+ model=self.model,+ raw_response=mock_response,+ logging_obj=logging_obj+ )++ assert isinstance(result, bytes)+ assert result == b"fake video content"++ def test_url_construction_with_trailing_slash(self):+ """Test URL construction with API base that has trailing slash."""+ api_base_with_slash = "https://your-resource.openai.azure.com/"+ litellm_params = {"api_base": api_base_with_slash}++ url = self.config.get_complete_url(+ model=self.model,+ api_base=api_base_with_slash,+ litellm_params=litellm_params+ )++ # Should not have double slashes+ assert "//openai/v1/videos" not in url+ assert "/openai/v1/videos" in url++ def test_url_construction_without_trailing_slash(self):+ """Test URL construction with API base that doesn't have trailing slash."""+ api_base_without_slash = "https://your-resource.openai.azure.com"+ litellm_params = {"api_base": api_base_without_slash}++ url = self.config.get_complete_url(+ model=self.model,+ api_base=api_base_without_slash,+ litellm_params=litellm_params+ )++ # Should have proper slash separation+ assert "/openai/v1/videos" in url+ assert url.startswith(api_base_without_slash)++ def test_video_create_with_file_upload(self):+ """Test video creation with file upload (input_reference)."""+ video_params = {+ "seconds": 10,+ "input_reference": "test_image.png"+ }++ litellm_params = GenericLiteLLMParams(+ model=self.model,+ api_base=self.api_base,+ api_key=self.api_key+ )++ headers = {"Authorization": f"Bearer {self.api_key}"}++ # Mock file existence+ with patch('os.path.exists', return_value=True):+ with patch('builtins.open', mock_open(read_data=b"fake image data")):+ data, files = self.config.transform_video_create_request(+ model=self.model,+ prompt="A video with reference image",+ video_create_optional_request_params=video_params,+ litellm_params=litellm_params,+ headers=headers+ )++ assert data["prompt"] == "A video with reference image"+ assert data["seconds"] == 10+ assert len(files) == 1+ assert files[0][0] == "input_reference"++ def test_error_handling_in_response_transformation(self):+ """Test error handling in response transformation methods."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "error": {+ "message": "Invalid API key",+ "type": "authentication_error"+ }+ }+ mock_response.status_code = 401++ logging_obj = MagicMock()++ # Test that error responses raise exceptions+ with pytest.raises(Exception):+ self.config.transform_video_create_response(+ model=self.model,+ raw_response=mock_response,+ logging_obj=logging_obj+ )++ def test_azure_specific_environment_validation(self):+ """Test Azure-specific environment validation with different key sources."""+ headers = {"Content-Type": "application/json"}++ # Test with azure_key+ with patch('litellm.llms.azure.videos.transformation.litellm') as mock_litellm:+ mock_litellm.api_key = None+ mock_litellm.azure_key = "azure-test-key"+ mock_litellm.openai_key = None++ result_headers = self.config.validate_environment(+ headers=headers,+ model=self.model,+ api_key=None+ )++ assert result_headers["Authorization"] == "Bearer azure-test-key"++ def test_usage_data_creation_in_video_create(self):+ """Test that usage data is created correctly in video create response."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "id": "video_azure_123",+ "object": "video",+ "status": "completed",+ "created_at": 1712697600,+ "model": "sora-2",+ "seconds": "10"+ }++ logging_obj = MagicMock()++ result = self.config.transform_video_create_response(+ model=self.model,+ raw_response=mock_response,+ logging_obj=logging_obj+ )++ assert hasattr(result, 'usage')+ assert result.usage is not None+ assert "duration_seconds" in result.usage+ assert result.usage["duration_seconds"] == 10.0++ def test_usage_data_creation_in_video_remix(self):+ """Test that usage data is created correctly in video remix response."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "id": "video_remix_azure_123",+ "object": "video",+ "status": "completed",+ "created_at": 1712697600,+ "model": "sora-2",+ "seconds": "15"+ }++ logging_obj = MagicMock()++ result = self.config.transform_video_remix_response(+ model=self.model,+ raw_response=mock_response,+ logging_obj=logging_obj+ )++ assert hasattr(result, 'usage')+ assert result.usage is not None+ assert "duration_seconds" in result.usage+ assert result.usage["duration_seconds"] == 15.0+++if __name__ == "__main__":+ pytest.main([__file__])diff --git a/tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_amazon_qwen3_transformation.py b/tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_amazon_qwen3_transformation.pynew file mode 100644index 00000000000..4e2b267ee2f--- /dev/null+++ b/tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_amazon_qwen3_transformation.py@@ -0,0 +1,211 @@+import asyncio+import json+import os+import sys+from unittest.mock import Mock++import pytest++# Ensure the project root is on the import path so `litellm` can be imported when+# tests are executed from any working directory.+sys.path.insert(0, os.path.abspath("../../../../../.."))++from litellm.llms.bedrock.chat.invoke_transformations.amazon_qwen3_transformation import (+ AmazonQwen3Config,+)+from litellm.types.utils import ModelResponse+++def test_qwen3_get_supported_params():+ """Test that Qwen3 config returns correct supported parameters"""+ config = AmazonQwen3Config()+ params = config.get_supported_openai_params(model="qwen3/test-model")++ expected_params = ["max_tokens", "temperature", "top_p", "top_k", "stop", "stream"]+ for param in expected_params:+ assert param in params+++def test_qwen3_map_openai_params():+ """Test that OpenAI parameters are correctly mapped to Qwen3 format"""+ config = AmazonQwen3Config()+ non_default_params = {+ "max_tokens": 100,+ "temperature": 0.7,+ "top_p": 0.9,+ "top_k": 40,+ "stop": ["</s>", "<|im_end|>"],+ "stream": True+ }+ optional_params = {}++ result = config.map_openai_params(+ non_default_params=non_default_params,+ optional_params=optional_params,+ model="qwen3/test-model",+ drop_params=False+ )++ assert result["max_tokens"] == 100+ assert result["temperature"] == 0.7+ assert result["top_p"] == 0.9+ assert result["top_k"] == 40+ assert result["stop"] == ["</s>", "<|im_end|>"]+ assert result["stream"] is True+++def test_qwen3_convert_messages_to_prompt():+ """Test that messages are correctly converted to Qwen3 prompt format"""+ config = AmazonQwen3Config()++ messages = [+ {"role": "system", "content": "You are a helpful assistant."},+ {"role": "user", "content": "Hello, how are you?"},+ {"role": "assistant", "content": "I'm doing well, thank you!"},+ {"role": "user", "content": "What's the weather like?"}+ ]++ prompt = config._convert_messages_to_prompt(messages)++ expected_prompt = """<|im_start|>system+You are a helpful assistant.<|im_end|>+<|im_start|>user+Hello, how are you?<|im_end|>+<|im_start|>assistant+I'm doing well, thank you!<|im_end|>+<|im_start|>user+What's the weather like?<|im_end|>+<|im_start|>assistant+"""++ assert prompt == expected_prompt+++def test_qwen3_transform_request():+ """Test that the request is correctly transformed to Qwen3 format"""+ config = AmazonQwen3Config()++ messages = [+ {"role": "user", "content": "Hello, world!"}+ ]++ optional_params = {+ "max_tokens": 50,+ "temperature": 0.8,+ "top_p": 0.9+ }++ request_body = config.transform_request(+ model="qwen3/test-model",+ messages=messages,+ optional_params=optional_params,+ litellm_params={},+ headers={}+ )++ assert "prompt" in request_body+ assert request_body["max_gen_len"] == 50+ assert request_body["temperature"] == 0.8+ assert request_body["top_p"] == 0.9++ # Check that the prompt contains the expected format+ assert "<|im_start|>user" in request_body["prompt"]+ assert "Hello, world!" in request_body["prompt"]+ assert "<|im_end|>" in request_body["prompt"]+++def test_qwen3_transform_response():+ """Test that Qwen3 response is correctly transformed to OpenAI format"""+ config = AmazonQwen3Config()++ # Mock response data+ mock_response_data = {+ "generation": "<|im_start|>assistant\nHello! How can I help you today?<|im_end|>",+ "usage": {+ "prompt_tokens": 10,+ "completion_tokens": 15,+ "total_tokens": 25+ }+ }++ # Mock the raw response+ mock_raw_response = Mock()+ mock_raw_response.json.return_value = mock_response_data++ model_response = ModelResponse()+ messages = [{"role": "user", "content": "Hello!"}]++ result = config.transform_response(+ model="qwen3/test-model",+ messages=messages,+ raw_response=mock_raw_response,+ model_response=model_response,+ logging_obj=Mock(),+ optional_params={},+ litellm_params={},+ api_key="test-key",+ request_data={},+ encoding=None+ )++ # Check that the response is correctly formatted+ assert len(result.choices) == 1+ assert result.choices[0]["message"]["role"] == "assistant"+ assert result.choices[0]["message"]["content"] == "Hello! How can I help you today?"+ assert result.choices[0]["finish_reason"] == "stop"++ # Check usage information+ assert result.usage["prompt_tokens"] == 10+ assert result.usage["completion_tokens"] == 15+ assert result.usage["total_tokens"] == 25+++def test_qwen3_transform_response_without_usage():+ """Test response transformation when usage information is not provided"""+ config = AmazonQwen3Config()++ # Mock response data without usage+ mock_response_data = {+ "generation": "Hello! How can I help you today?"+ }++ # Mock the raw response+ mock_raw_response = Mock()+ mock_raw_response.json.return_value = mock_response_data++ model_response = ModelResponse()+ messages = [{"role": "user", "content": "Hello!"}]++ result = config.transform_response(+ model="qwen3/test-model",+ messages=messages,+ raw_response=mock_raw_response,+ model_response=model_response,+ logging_obj=Mock(),+ optional_params={},+ litellm_params={},+ api_key="test-key",+ request_data={},+ encoding=None+ )++ # Check that the response is correctly formatted+ assert len(result.choices) == 1+ assert result.choices[0]["message"]["role"] == "assistant"+ assert result.choices[0]["message"]["content"] == "Hello! How can I help you today?"+ assert result.choices[0]["finish_reason"] == "stop"+++def test_qwen3_provider_detection():+ """Test that Qwen3 provider is correctly detected from model names"""+ from litellm.utils import ProviderConfigManager+ from litellm.types.utils import LlmProviders++ # Test with qwen3/ prefix+ config = ProviderConfigManager.get_provider_chat_config(+ model="qwen3/arn:aws:bedrock:us-east-1:123456789012:imported-model/test-qwen3",+ provider=LlmProviders.BEDROCK+ )++ assert config is not None+ assert isinstance(config, AmazonQwen3Config)diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_ai_gemini_transformation.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_ai_gemini_transformation.pyindex 4da2976e1f9..e8a0e7f5fb3 100644--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_ai_gemini_transformation.py+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_ai_gemini_transformation.py@@ -1,6 +1,7 @@from litellm.llms.vertex_ai.gemini.transformation import (check_if_part_exists_in_parts,_transform_request_body,+ _gemini_convert_messages_with_history,)@@ -155,3 +156,23 @@ def test_metadata_to_labels_vertex_only():)assert "labels" in resultassert result["labels"] == {"user": "john_doe", "project": "test-project"}+++def test_empty_content_handling():+ """Test that empty content strings are properly handled in Gemini message transformation"""+ # Test with empty content in user message+ messages = [+ {+ "content": "",+ "role": "user"+ }+ ]++ contents = _gemini_convert_messages_with_history(messages=messages)++ # Verify that the content was properly transformed+ assert len(contents) == 1+ assert contents[0]["role"] == "user"+ assert len(contents[0]["parts"]) == 1+ assert "text" in contents[0]["parts"][0]+ assert contents[0]["parts"][0]["text"] == ""diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.pyindex 971c71696d1..3127f72f528 100644--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py@@ -1204,4 +1204,225 @@ def test_vertex_ai_penalty_parameters_validation():assert "temperature" in result, "temperature should still be included"assert "max_output_tokens" in result, "max_output_tokens should still be included"assert result["temperature"] == 0.7- assert result["max_output_tokens"] == 100\ No newline at end of file+ assert result["max_output_tokens"] == 100+++def test_vertex_ai_annotation_streaming_events():+ """+ Test that annotation events are properly emitted during streaming for Vertex AI Gemini.++ This test verifies:+ 1. Grounding metadata is converted to annotations in streaming chunks+ 2. Annotations are included in the delta of streaming chunks+ 3. Multiple annotations are handled correctly+ """+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (+ ModelResponseIterator,+ )+ from litellm.types.llms.openai import ChatCompletionAnnotation++ litellm_logging = MagicMock()++ # Simulate a streaming chunk with grounding metadata (as Gemini sends it)+ chunk_with_annotations = {+ "candidates": [+ {+ "content": {+ "parts": [{"text": "The weather in San Francisco today is clear."}]+ },+ "groundingMetadata": {+ "webSearchQueries": ["weather San Francisco today"],+ "searchEntryPoint": {+ "renderedContent": '<div>Search results</div>'+ },+ "groundingChunks": [+ {+ "web": {+ "uri": "https://www.google.com/search?q=weather+in+San+Francisco,+CA",+ "title": "Weather information for San Francisco, CA",+ "domain": "google.com",+ }+ }+ ],+ "groundingSupports": [+ {+ "segment": {+ "startIndex": 0,+ "endIndex": 50,+ "text": "The weather in San Francisco today is clear.",+ },+ "groundingChunkIndices": [0],+ "confidenceScores": [0.95],+ }+ ],+ },+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 10,+ "candidatesTokenCount": 15,+ "totalTokenCount": 25,+ },+ }++ # Create iterator and parse chunk+ iterator = ModelResponseIterator(+ streaming_response=[], sync_stream=True, logging_obj=litellm_logging+ )+ streaming_chunk = iterator.chunk_parser(chunk_with_annotations)++ # Verify the chunk was parsed correctly+ assert streaming_chunk.choices is not None+ assert len(streaming_chunk.choices) == 1++ # Check that annotations are present in the delta+ delta = streaming_chunk.choices[0].delta+ assert hasattr(delta, "annotations")+ assert delta.annotations is not None+ assert len(delta.annotations) > 0++ # Verify annotation structure+ annotation = delta.annotations[0]+ assert isinstance(annotation, dict) # ChatCompletionAnnotation is a TypedDict+ assert annotation["type"] == "url_citation"+ assert annotation["url_citation"]["start_index"] == 0+ assert annotation["url_citation"]["end_index"] == 50+ assert "google.com" in annotation["url_citation"]["url"]+ assert "Weather information" in annotation["url_citation"]["title"]+++def test_vertex_ai_annotation_conversion():+ """+ Test the conversion of Vertex AI grounding metadata to OpenAI annotations.++ This test verifies the _convert_grounding_metadata_to_annotations method+ correctly transforms grounding metadata into the expected format.+ """+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (+ VertexGeminiConfig,+ )++ # Sample grounding metadata as returned by Vertex AI+ grounding_metadata = {+ "webSearchQueries": ["weather San Francisco", "current time San Francisco"],+ "searchEntryPoint": {+ "renderedContent": '<div>Search interface</div>'+ },+ "groundingChunks": [+ {+ "web": {+ "uri": "https://www.google.com/search?q=weather+in+San+Francisco,+CA",+ "title": "Weather information for San Francisco, CA",+ "domain": "google.com",+ }+ },+ {+ "web": {+ "uri": "https://www.google.com/search?q=time+in+San+Francisco,+CA",+ "title": "Current time in San Francisco, CA",+ "domain": "google.com",+ }+ }+ ],+ "groundingSupports": [+ {+ "segment": {+ "startIndex": 0,+ "endIndex": 30,+ "text": "The weather in San Francisco",+ },+ "groundingChunkIndices": [0],+ "confidenceScores": [0.95],+ },+ {+ "segment": {+ "startIndex": 32,+ "endIndex": 60,+ "text": "is currently 72°F",+ },+ "groundingChunkIndices": [0],+ "confidenceScores": [0.88],+ },+ {+ "segment": {+ "startIndex": 62,+ "endIndex": 85,+ "text": "and the time is 2:30 PM",+ },+ "groundingChunkIndices": [1],+ "confidenceScores": [0.92],+ }+ ],+ }++ # Convert grounding metadata to annotations+ content_text = "The weather in San Francisco is currently 72°F and the time is 2:30 PM"+ annotations = VertexGeminiConfig._convert_grounding_metadata_to_annotations(+ [grounding_metadata], content_text+ )++ # Verify annotations were created+ assert len(annotations) == 3 # One for each grounding support++ # Check first annotation (weather)+ weather_annotation = annotations[0]+ assert weather_annotation["type"] == "url_citation"+ assert weather_annotation["url_citation"]["start_index"] == 0+ assert weather_annotation["url_citation"]["end_index"] == 30+ assert "google.com" in weather_annotation["url_citation"]["url"]+ assert "Weather information" in weather_annotation["url_citation"]["title"]++ # Check second annotation (weather continuation)+ weather_cont_annotation = annotations[1]+ assert weather_cont_annotation["type"] == "url_citation"+ assert weather_cont_annotation["url_citation"]["start_index"] == 32+ assert weather_cont_annotation["url_citation"]["end_index"] == 60+ assert "google.com" in weather_cont_annotation["url_citation"]["url"]+ assert "Weather information" in weather_cont_annotation["url_citation"]["title"]++ # Check third annotation (time)+ time_annotation = annotations[2]+ assert time_annotation["type"] == "url_citation"+ assert time_annotation["url_citation"]["start_index"] == 62+ assert time_annotation["url_citation"]["end_index"] == 85+ assert "google.com" in time_annotation["url_citation"]["url"]+ assert "Current time" in time_annotation["url_citation"]["title"]+++def test_vertex_ai_annotation_empty_grounding_metadata():+ """+ Test handling of empty or missing grounding metadata.++ This test ensures the annotation conversion handles edge cases gracefully.+ """+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (+ VertexGeminiConfig,+ )++ # Test with empty grounding metadata+ empty_metadata = {}+ annotations = VertexGeminiConfig._convert_grounding_metadata_to_annotations(+ [empty_metadata], "test content"+ )+ assert len(annotations) == 0++ # Test with missing groundingSupports+ metadata_no_supports = {+ "webSearchQueries": ["test query"],+ "groundingChunks": [{"web": {"uri": "https://example.com", "title": "Test"}}],+ }+ annotations = VertexGeminiConfig._convert_grounding_metadata_to_annotations(+ [metadata_no_supports], "test content"+ )+ assert len(annotations) == 0++ # Test with empty groundingSupports+ metadata_empty_supports = {+ "webSearchQueries": ["test query"],+ "groundingChunks": [{"web": {"uri": "https://example.com", "title": "Test"}}],+ "groundingSupports": [],+ }+ annotations = VertexGeminiConfig._convert_grounding_metadata_to_annotations(+ [metadata_empty_supports], "test content"+ )+ assert len(annotations) == 0\ No newline at end of filediff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_vertex_ai_batch_passthrough.py b/tests/test_litellm/proxy/pass_through_endpoints/test_vertex_ai_batch_passthrough.pynew file mode 100644index 00000000000..68c6bf98cb2--- /dev/null+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_vertex_ai_batch_passthrough.py@@ -0,0 +1,539 @@+"""+Test cases for Vertex AI passthrough batch prediction functionality+"""+import base64+import json+import pytest+from unittest.mock import Mock, patch, MagicMock+from datetime import datetime+from typing import Dict, Any++from litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler import (+ VertexPassthroughLoggingHandler,+)+from litellm.types.utils import SpecialEnums+from litellm.types.llms.openai import BatchJobStatus+++class TestVertexAIBatchPassthroughHandler:+ """Test cases for Vertex AI batch prediction passthrough functionality"""++ @pytest.fixture+ def mock_httpx_response(self):+ """Mock httpx response for batch job creation"""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "name": "projects/test-project/locations/us-central1/batchPredictionJobs/123456789",+ "displayName": "litellm-vertex-batch-test",+ "model": "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash",+ "createTime": "2024-01-01T00:00:00Z",+ "state": "JOB_STATE_PENDING",+ "inputConfig": {+ "gcsSource": {+ "uris": ["gs://test-bucket/input.jsonl"]+ },+ "instancesFormat": "jsonl"+ },+ "outputConfig": {+ "gcsDestination": {+ "outputUriPrefix": "gs://test-bucket/output/"+ },+ "predictionsFormat": "jsonl"+ }+ }+ return mock_response++ @pytest.fixture+ def mock_logging_obj(self):+ """Mock logging object"""+ mock = Mock()+ mock.litellm_call_id = "test-call-id-123"+ mock.model_call_details = {}+ mock.optional_params = {}+ return mock++ @pytest.fixture+ def mock_managed_files_hook(self):+ """Mock managed files hook"""+ mock_hook = Mock()+ mock_hook.afile_content.return_value = Mock(content=b'{"test": "data"}')+ return mock_hook++ def test_batch_prediction_jobs_handler_success(self, mock_httpx_response, mock_logging_obj):+ """Test successful batch job creation and tracking"""+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.verbose_proxy_logger') as mock_logger:+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.VertexPassthroughLoggingHandler.get_actual_model_id_from_router') as mock_get_model_id:+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.VertexPassthroughLoggingHandler._store_batch_managed_object') as mock_store:+ with patch('litellm.llms.vertex_ai.batches.transformation.VertexAIBatchTransformation') as mock_transformation:++ # Setup mocks+ mock_get_model_id.return_value = "vertex_ai/gemini-1.5-flash"+ mock_transformation.transform_vertex_ai_batch_response_to_openai_batch_response.return_value = {+ "id": "123456789",+ "object": "batch",+ "status": "validating",+ "created_at": 1704067200,+ "input_file_id": "file-123",+ "output_file_id": "file-456",+ "error_file_id": None,+ "completion_window": "24hrs"+ }+ mock_transformation._get_batch_id_from_vertex_ai_batch_response.return_value = "123456789"++ # Test the handler+ result = VertexPassthroughLoggingHandler.batch_prediction_jobs_handler(+ httpx_response=mock_httpx_response,+ logging_obj=mock_logging_obj,+ url_route="/v1/projects/test-project/locations/us-central1/batchPredictionJobs",+ result="success",+ start_time=datetime.now(),+ end_time=datetime.now(),+ cache_hit=False,+ user_api_key_dict={"user_id": "test-user"}+ )++ # Verify the result+ assert result is not None+ assert "kwargs" in result+ assert result["kwargs"]["model"] == "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash"+ assert result["kwargs"]["batch_id"] == "123456789"++ # Verify mocks were called+ mock_get_model_id.assert_called_once()+ mock_store.assert_called_once()++ def test_batch_prediction_jobs_handler_failure(self, mock_logging_obj):+ """Test batch job creation failure handling"""+ # Mock failed response+ mock_httpx_response = Mock()+ mock_httpx_response.status_code = 400+ mock_httpx_response.json.return_value = {"error": "Invalid request"}++ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.verbose_proxy_logger') as mock_logger:+ # Test the handler with failed response+ result = VertexPassthroughLoggingHandler.batch_prediction_jobs_handler(+ httpx_response=mock_httpx_response,+ logging_obj=mock_logging_obj,+ url_route="/v1/projects/test-project/locations/us-central1/batchPredictionJobs",+ result="error",+ start_time=datetime.now(),+ end_time=datetime.now(),+ cache_hit=False,+ user_api_key_dict={"user_id": "test-user"}+ )++ # Should return a structured response for failed responses+ assert result is not None+ assert "result" in result+ assert "kwargs" in result+ assert result["result"].choices[0].finish_reason == "batch_error"+ assert result["kwargs"]["batch_job_state"] == "JOB_STATE_FAILED"++ def test_get_actual_model_id_from_router_with_router(self):+ """Test getting model ID when router is available"""+ with patch('litellm.proxy.proxy_server.llm_router') as mock_router:+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.VertexPassthroughLoggingHandler.extract_model_name_from_vertex_path') as mock_extract:++ # Setup mocks+ mock_router.get_model_ids.return_value = ["vertex_ai/gemini-1.5-flash"]+ mock_extract.return_value = "gemini-1.5-flash"++ # Test the method+ result = VertexPassthroughLoggingHandler.get_actual_model_id_from_router(+ "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash"+ )++ # Verify result+ assert result == "vertex_ai/gemini-1.5-flash"+ mock_router.get_model_ids.assert_called_once_with(model_name="gemini-1.5-flash")++ def test_get_actual_model_id_from_router_without_router(self):+ """Test getting model ID when router is not available"""+ with patch('litellm.proxy.proxy_server.llm_router', None):+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.VertexPassthroughLoggingHandler.extract_model_name_from_vertex_path') as mock_extract:++ # Setup mocks+ mock_extract.return_value = "gemini-1.5-flash"++ # Test the method+ result = VertexPassthroughLoggingHandler.get_actual_model_id_from_router(+ "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash"+ )++ # Verify result+ assert result == "gemini-1.5-flash"++ def test_get_actual_model_id_from_router_model_not_found(self):+ """Test getting model ID when model is not found in router"""+ with patch('litellm.proxy.proxy_server.llm_router') as mock_router:+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.VertexPassthroughLoggingHandler.extract_model_name_from_vertex_path') as mock_extract:++ # Setup mocks - router returns empty list+ mock_router.get_model_ids.return_value = []+ mock_extract.return_value = "gemini-1.5-flash"++ # Test the method+ result = VertexPassthroughLoggingHandler.get_actual_model_id_from_router(+ "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash"+ )++ # Verify result - should fallback to extracted model name+ assert result == "gemini-1.5-flash"++ def test_unified_object_id_generation(self):+ """Test unified object ID generation for batch tracking"""+ model_id = "vertex_ai/gemini-1.5-flash"+ batch_id = "123456789"++ # Generate the expected unified ID+ unified_id_string = SpecialEnums.LITELLM_MANAGED_BATCH_COMPLETE_STR.value.format(model_id, batch_id)+ expected_unified_id = base64.urlsafe_b64encode(unified_id_string.encode()).decode().rstrip("=")++ # Test the generation+ actual_unified_id = base64.urlsafe_b64encode(unified_id_string.encode()).decode().rstrip("=")++ assert actual_unified_id == expected_unified_id+ assert isinstance(actual_unified_id, str)+ assert len(actual_unified_id) > 0++ def test_store_batch_managed_object(self, mock_logging_obj, mock_managed_files_hook):+ """Test storing batch managed object for cost tracking"""+ with patch('litellm.proxy.proxy_server.proxy_logging_obj') as mock_proxy_logging_obj:+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.verbose_proxy_logger') as mock_logger:++ # Setup mock proxy logging obj+ mock_proxy_logging_obj.get_proxy_hook.return_value = mock_managed_files_hook++ # Test data+ unified_object_id = "test-unified-id"+ batch_object = {+ "id": "123456789",+ "object": "batch",+ "status": "validating"+ }+ model_object_id = "123456789"++ # Test the method+ VertexPassthroughLoggingHandler._store_batch_managed_object(+ unified_object_id=unified_object_id,+ batch_object=batch_object,+ model_object_id=model_object_id,+ logging_obj=mock_logging_obj,+ user_api_key_dict={"user_id": "test-user"}+ )++ # Verify the managed files hook was called+ mock_managed_files_hook.store_unified_object_id.assert_called_once()++ def test_batch_cost_calculation_integration(self):+ """Test integration with batch cost calculation"""+ from litellm.batches.batch_utils import calculate_vertex_ai_batch_cost_and_usage++ # Mock Vertex AI batch responses+ vertex_ai_batch_responses = [+ {+ "status": "JOB_STATE_SUCCEEDED",+ "response": {+ "candidates": [+ {+ "content": {+ "parts": [+ {"text": "Hello, world!"}+ ]+ }+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 10,+ "candidatesTokenCount": 5,+ "totalTokenCount": 15+ }+ }+ }+ ]++ with patch('litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini.VertexGeminiConfig') as mock_config:+ with patch('litellm.completion_cost') as mock_completion_cost:++ # Setup mocks+ mock_config.return_value._transform_google_generate_content_to_openai_model_response.return_value = Mock(+ usage=Mock(total_tokens=15, prompt_tokens=10, completion_tokens=5)+ )+ mock_completion_cost.return_value = 0.001++ # Test the cost calculation+ total_cost, usage = calculate_vertex_ai_batch_cost_and_usage(+ vertex_ai_batch_responses,+ model_name="gemini-1.5-flash"+ )++ # Verify results+ assert total_cost == 0.001+ assert usage.total_tokens == 15+ assert usage.prompt_tokens == 10+ assert usage.completion_tokens == 5++ def test_batch_response_transformation(self):+ """Test transformation of Vertex AI batch responses to OpenAI format"""+ from litellm.llms.vertex_ai.batches.transformation import VertexAIBatchTransformation++ # Mock Vertex AI batch response+ vertex_ai_response = {+ "name": "projects/test-project/locations/us-central1/batchPredictionJobs/123456789",+ "displayName": "test-batch",+ "model": "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash",+ "createTime": "2024-01-01T00:00:00.000Z",+ "state": "JOB_STATE_SUCCEEDED"+ }++ # Test transformation+ result = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response(+ vertex_ai_response+ )++ # Verify the transformation+ assert result["id"] == "123456789"+ assert result["object"] == "batch"+ assert result["status"] == "completed" # JOB_STATE_SUCCEEDED should map to completed++ def test_batch_id_extraction(self):+ """Test extraction of batch ID from Vertex AI response"""+ from litellm.llms.vertex_ai.batches.transformation import VertexAIBatchTransformation++ # Test various batch ID formats+ test_cases = [+ "projects/123/locations/us-central1/batchPredictionJobs/456789",+ "projects/abc/locations/europe-west1/batchPredictionJobs/def123",+ "batchPredictionJobs/999",+ "invalid-format"+ ]++ expected_results = ["456789", "def123", "999", "invalid-format"]++ for test_case, expected in zip(test_cases, expected_results):+ result = VertexAIBatchTransformation._get_batch_id_from_vertex_ai_batch_response(+ {"name": test_case}+ )+ assert result == expected++ def test_model_name_extraction_from_vertex_path(self):+ """Test extraction of model name from Vertex AI path"""+ from litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler import (+ VertexPassthroughLoggingHandler+ )++ # Test various model path formats+ test_cases = [+ "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash",+ "projects/abc/locations/europe-west1/publishers/google/models/gemini-2.0-flash",+ "publishers/google/models/gemini-pro",+ "invalid-path"+ ]++ expected_results = ["gemini-1.5-flash", "gemini-2.0-flash", "gemini-pro", "invalid-path"]++ for test_case, expected in zip(test_cases, expected_results):+ result = VertexPassthroughLoggingHandler.extract_model_name_from_vertex_path(test_case)+ assert result == expected++ @pytest.mark.asyncio+ async def test_batch_completion_workflow(self, mock_httpx_response, mock_logging_obj, mock_managed_files_hook):+ """Test the complete batch completion workflow"""+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.verbose_proxy_logger') as mock_logger:+ with patch('litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler.VertexPassthroughLoggingHandler.get_actual_model_id_from_router') as mock_get_model_id:+ with patch('litellm.proxy.proxy_server.proxy_logging_obj') as mock_proxy_logging_obj:+ mock_proxy_logging_obj.get_proxy_hook.return_value = mock_managed_files_hook+ with patch('litellm.llms.vertex_ai.batches.transformation.VertexAIBatchTransformation') as mock_transformation:++ # Setup mocks+ mock_get_model_id.return_value = "vertex_ai/gemini-1.5-flash"+ mock_transformation.transform_vertex_ai_batch_response_to_openai_batch_response.return_value = {+ "id": "123456789",+ "object": "batch",+ "status": "completed",+ "created_at": 1704067200,+ "input_file_id": "file-123",+ "output_file_id": "file-456",+ "error_file_id": None,+ "completion_window": "24hrs"+ }+ mock_transformation._get_batch_id_from_vertex_ai_batch_response.return_value = "123456789"++ # Test the complete workflow+ result = VertexPassthroughLoggingHandler.batch_prediction_jobs_handler(+ httpx_response=mock_httpx_response,+ logging_obj=mock_logging_obj,+ url_route="/v1/projects/test-project/locations/us-central1/batchPredictionJobs",+ result="success",+ start_time=datetime.now(),+ end_time=datetime.now(),+ cache_hit=False,+ user_api_key_dict={"user_id": "test-user"}+ )++ # Verify the complete workflow+ assert result is not None+ assert "kwargs" in result+ assert result["kwargs"]["model"] == "projects/test-project/locations/us-central1/publishers/google/models/gemini-1.5-flash"+ assert result["kwargs"]["batch_id"] == "123456789"++ # Verify all mocks were called+ mock_get_model_id.assert_called_once()+ mock_transformation.transform_vertex_ai_batch_response_to_openai_batch_response.assert_called_once()+ # Note: store_unified_object_id is called asynchronously, so we can't easily verify it in this test+++class TestVertexAIBatchCostCalculation:+ """Test cases for Vertex AI batch cost calculation functionality"""++ def test_calculate_vertex_ai_batch_cost_and_usage_success(self):+ """Test successful batch cost and usage calculation"""+ from litellm.batches.batch_utils import calculate_vertex_ai_batch_cost_and_usage++ # Mock successful batch responses+ vertex_ai_batch_responses = [+ {+ "status": "JOB_STATE_SUCCEEDED",+ "response": {+ "candidates": [+ {+ "content": {+ "parts": [+ {"text": "Hello, world!"}+ ]+ }+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 10,+ "candidatesTokenCount": 5,+ "totalTokenCount": 15+ }+ }+ },+ {+ "status": "JOB_STATE_SUCCEEDED",+ "response": {+ "candidates": [+ {+ "content": {+ "parts": [+ {"text": "How are you?"}+ ]+ }+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 8,+ "candidatesTokenCount": 3,+ "totalTokenCount": 11+ }+ }+ }+ ]++ with patch('litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini.VertexGeminiConfig') as mock_config:+ with patch('litellm.completion_cost') as mock_completion_cost:++ # Setup mocks+ mock_model_response = Mock()+ mock_model_response.usage = Mock(total_tokens=15, prompt_tokens=10, completion_tokens=5)+ mock_config.return_value._transform_google_generate_content_to_openai_model_response.return_value = mock_model_response+ mock_completion_cost.return_value = 0.001++ # Test the calculation+ total_cost, usage = calculate_vertex_ai_batch_cost_and_usage(+ vertex_ai_batch_responses,+ model_name="gemini-1.5-flash"+ )++ # Verify results+ assert total_cost == 0.002 # 2 responses * 0.001 each+ assert usage.total_tokens == 30 # 15 + 15+ assert usage.prompt_tokens == 20 # 10 + 10+ assert usage.completion_tokens == 10 # 5 + 5++ def test_calculate_vertex_ai_batch_cost_and_usage_with_failed_responses(self):+ """Test batch cost calculation with some failed responses"""+ from litellm.batches.batch_utils import calculate_vertex_ai_batch_cost_and_usage++ # Mock batch responses with some failures+ vertex_ai_batch_responses = [+ {+ "status": "JOB_STATE_SUCCEEDED",+ "response": {+ "candidates": [+ {+ "content": {+ "parts": [+ {"text": "Hello, world!"}+ ]+ }+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 10,+ "candidatesTokenCount": 5,+ "totalTokenCount": 15+ }+ }+ },+ {+ "status": "JOB_STATE_FAILED", # Failed response+ "response": None+ },+ {+ "status": "JOB_STATE_SUCCEEDED",+ "response": {+ "candidates": [+ {+ "content": {+ "parts": [+ {"text": "How are you?"}+ ]+ }+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 8,+ "candidatesTokenCount": 3,+ "totalTokenCount": 11+ }+ }+ }+ ]++ with patch('litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini.VertexGeminiConfig') as mock_config:+ with patch('litellm.completion_cost') as mock_completion_cost:++ # Setup mocks+ mock_model_response = Mock()+ mock_model_response.usage = Mock(total_tokens=15, prompt_tokens=10, completion_tokens=5)+ mock_config.return_value._transform_google_generate_content_to_openai_model_response.return_value = mock_model_response+ mock_completion_cost.return_value = 0.001++ # Test the calculation+ total_cost, usage = calculate_vertex_ai_batch_cost_and_usage(+ vertex_ai_batch_responses,+ model_name="gemini-1.5-flash"+ )++ # Verify results - should only process successful responses+ assert total_cost == 0.002 # 2 successful responses * 0.001 each+ assert usage.total_tokens == 30 # 15 + 15+ assert usage.prompt_tokens == 20 # 10 + 10+ assert usage.completion_tokens == 10 # 5 + 5++ def test_calculate_vertex_ai_batch_cost_and_usage_empty_responses(self):+ """Test batch cost calculation with empty response list"""+ from litellm.batches.batch_utils import calculate_vertex_ai_batch_cost_and_usage++ # Test with empty list+ total_cost, usage = calculate_vertex_ai_batch_cost_and_usage([], model_name="gemini-1.5-flash")++ # Verify results+ assert total_cost == 0.0+ assert usage.total_tokens == 0+ assert usage.prompt_tokens == 0+ assert usage.completion_tokens == 0diff --git a/tests/test_litellm/test_azure_video_router.py b/tests/test_litellm/test_azure_video_router.pynew file mode 100644index 00000000000..b2a108dcdea--- /dev/null+++ b/tests/test_litellm/test_azure_video_router.py@@ -0,0 +1,53 @@+"""+Test suite for Azure video router functionality.+Tests that the router method gets called correctly for Azure video generation.+"""++import pytest+from unittest.mock import Mock, patch, MagicMock+import litellm+++class TestAzureVideoRouter:+ """Test suite for Azure video router functionality"""++ def setup_method(self):+ """Setup test fixtures"""+ self.model = "azure/sora-2"+ self.prompt = "A beautiful sunset over mountains"+ self.seconds = "5"+ self.size = "1280x720"++ @patch("litellm.videos.main.base_llm_http_handler")+ def test_azure_video_generation_router_call_mock(self, mock_handler):+ """Test that Azure video generation calls the router method with mock response"""+ # Setup mock response+ mock_response = {+ "id": "video_123",+ "model": "sora-2",+ "object": "video",+ "status": "processing",+ "created_at": 1234567890,+ "progress": 0+ }++ # Configure the mock handler+ mock_handler.video_generation_handler.return_value = mock_response++ # Call the video generation function with mock response+ result = litellm.video_generation(+ prompt=self.prompt,+ model=self.model,+ seconds=self.seconds,+ size=self.size,+ custom_llm_provider="azure",+ mock_response=mock_response+ )++ # Verify the result is a VideoObject with the expected data+ assert result.id == mock_response["id"]+ assert result.model == mock_response["model"]+ assert result.object == mock_response["object"]+ assert result.status == mock_response["status"]+ assert result.created_at == mock_response["created_at"]+ assert result.progress == mock_response["progress"]diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex e073af0eed6..45877e1ac6a 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -591,6 +591,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid():"output_cost_per_token_above_200k_tokens": {"type": "number"},"output_cost_per_token_batches": {"type": "number"},"output_cost_per_reasoning_token": {"type": "number"},+ "output_cost_per_video_per_second": {"type": "number"},"output_db_cost_per_token": {"type": "number"},"output_dbu_cost_per_token": {"type": "number"},"output_vector_size": {"type": "number"},@@ -667,6 +668,12 @@ def test_aaamodel_prices_and_context_window_json_is_valid():"enum": ["text", "image", "audio", "code", "video"],},},+ "supported_resolutions": {+ "type": "array",+ "items": {+ "type": "string",+ },+ },"supports_native_streaming": {"type": "boolean"},"tiered_pricing": {"type": "array",diff --git a/tests/test_litellm/test_video_generation.py b/tests/test_litellm/test_video_generation.pynew file mode 100644index 00000000000..56f4f680c27--- /dev/null+++ b/tests/test_litellm/test_video_generation.py@@ -0,0 +1,730 @@+import json+import os+import sys+from unittest.mock import MagicMock, patch+import asyncio++import pytest++sys.path.insert(+ 0, os.path.abspath("../..")+) # Adds the parent directory to the system path++import litellm+from litellm.types.videos.main import VideoObject, VideoResponse+from litellm.videos.main import video_generation, avideo_generation, video_status, avideo_status+from litellm.llms.openai.videos.transformation import OpenAIVideoConfig+from litellm.cost_calculator import default_video_cost_calculator+from litellm.litellm_core_utils.litellm_logging import Logging as LitellmLogging+from litellm.integrations.custom_logger import CustomLogger+++class TestVideoGeneration:+ """Test suite for video generation functionality."""++ def test_video_generation_basic(self):+ """Test basic video generation functionality."""+ # Mock the video generation response+ mock_response = VideoObject(+ id="video_123",+ object="video",+ status="queued",+ created_at=1712697600,+ model="sora-2",+ size="720x1280",+ seconds="8"+ )++ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_generation_handler.return_value = mock_response++ response = video_generation(+ prompt="Show them running around the room",+ model="sora-2",+ seconds="8",+ size="720x1280"+ )++ assert isinstance(response, VideoObject)+ assert response.id == "video_123"+ assert response.model == "sora-2"+ assert response.size == "720x1280"+ assert response.seconds == "8"++ def test_video_generation_with_mock_response(self):+ """Test video generation with mock response."""+ mock_data = {+ "id": "video_456",+ "object": "video",+ "status": "completed",+ "created_at": 1712697600,+ "completed_at": 1712697660,+ "model": "sora-2",+ "size": "1280x720",+ "seconds": "10"+ }++ response = video_generation(+ prompt="A beautiful sunset over the ocean",+ model="sora-2",+ seconds="10",+ size="1280x720",+ mock_response=mock_data+ )++ assert isinstance(response, VideoObject)+ assert response.id == "video_456"+ assert response.status == "completed"+ assert response.model == "sora-2"+ assert response.size == "1280x720"+ assert response.seconds == "10"++ def test_video_generation_async(self):+ """Test async video generation functionality."""+ mock_response = VideoObject(+ id="video_async_123",+ object="video",+ status="processing",+ created_at=1712697600,+ model="sora-2",+ progress=50+ )++ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_generation_handler.return_value = mock_response++ import asyncio++ async def test_async():+ response = await avideo_generation(+ prompt="A cat playing with a ball",+ model="sora-2",+ seconds="5",+ size="720x1280"+ )+ return response++ response = asyncio.run(test_async())++ assert isinstance(response, VideoObject)+ assert response.id == "video_async_123"+ assert response.status == "processing"+ assert response.progress == 50++ def test_video_generation_parameter_validation(self):+ """Test video generation parameter validation."""+ # Test with minimal required parameters+ response = video_generation(+ prompt="Test video",+ model="sora-2",+ mock_response={"id": "test", "object": "video", "status": "queued", "created_at": 1712697600}+ )++ assert isinstance(response, VideoObject)+ assert response.id == "test"++ def test_video_generation_error_handling(self):+ """Test video generation error handling."""+ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_generation_handler.side_effect = Exception("API Error")++ with pytest.raises(Exception):+ video_generation(+ prompt="Test video",+ model="sora-2"+ )++ def test_video_generation_provider_config(self):+ """Test video generation provider configuration."""+ config = OpenAIVideoConfig()++ # Test supported parameters+ supported_params = config.get_supported_openai_params("sora-2")+ assert "prompt" in supported_params+ assert "model" in supported_params+ assert "seconds" in supported_params+ assert "size" in supported_params++ def test_video_generation_request_transformation(self):+ """Test video generation request transformation."""+ config = OpenAIVideoConfig()++ # Test request transformation+ data, files = config.transform_video_create_request(+ model="sora-2",+ prompt="Test video prompt",+ video_create_optional_request_params={+ "seconds": "8",+ "size": "720x1280"+ },+ litellm_params=MagicMock(),+ headers={}+ )++ assert data["model"] == "sora-2"+ assert data["prompt"] == "Test video prompt"+ assert data["seconds"] == "8"+ assert data["size"] == "720x1280"+ assert files == []++ def test_video_generation_response_transformation(self):+ """Test video generation response transformation."""+ config = OpenAIVideoConfig()++ # Mock HTTP response+ mock_http_response = MagicMock()+ mock_http_response.json.return_value = {+ "id": "video_789",+ "object": "video",+ "status": "completed",+ "created_at": 1712697600,+ "model": "sora-2",+ "size": "1280x720",+ "seconds": "12"+ }++ response = config.transform_video_create_response(+ model="sora-2",+ raw_response=mock_http_response,+ logging_obj=MagicMock()+ )++ assert isinstance(response, VideoObject)+ assert response.id == "video_789"+ assert response.status == "completed"+ assert response.model == "sora-2"++ def test_video_generation_cost_calculation(self):+ """Test video generation cost calculation."""+ # Load the local model cost map instead of online+ import json+ with open("model_prices_and_context_window.json", "r") as f:+ litellm.model_cost = json.load(f)++ # Test with sora-2 model+ cost = default_video_cost_calculator(+ model="openai/sora-2",+ duration_seconds=10.0,+ custom_llm_provider="openai"+ )++ # Should calculate cost based on duration (10 seconds * $0.10 per second = $1.00)+ assert cost == 1.0++ def test_video_generation_cost_calculation_unknown_model(self):+ """Test video generation cost calculation for unknown model."""+ with pytest.raises(Exception, match="Model not found in cost map"):+ default_video_cost_calculator(+ model="unknown-model",+ duration_seconds=5.0,+ custom_llm_provider="openai"+ )++ def test_video_generation_with_files(self):+ """Test video generation with file uploads."""+ config = OpenAIVideoConfig()++ # Mock file data+ mock_file = MagicMock()+ mock_file.read.return_value = b"fake_image_data"++ data, files = config.transform_video_create_request(+ model="sora-2",+ prompt="Test video with image",+ video_create_optional_request_params={+ "input_reference": mock_file,+ "seconds": "8",+ "size": "720x1280"+ },+ litellm_params=MagicMock(),+ headers={}+ )++ assert data["model"] == "sora-2"+ assert data["prompt"] == "Test video with image"+ assert len(files) > 0 # Should have files when input_reference is provided++ def test_video_generation_environment_validation(self):+ """Test video generation environment validation."""+ config = OpenAIVideoConfig()++ # Test environment validation+ headers = config.validate_environment(+ headers={},+ model="sora-2",+ api_key="test-api-key"+ )++ assert "Authorization" in headers+ assert headers["Authorization"] == "Bearer test-api-key"++ def test_video_generation_url_generation(self):+ """Test video generation URL generation."""+ config = OpenAIVideoConfig()++ # Test URL generation+ url = config.get_complete_url(+ model="sora-2",+ api_base="https://api.openai.com/v1",+ litellm_params={}+ )++ assert url == "https://api.openai.com/v1/videos"++ def test_video_generation_parameter_mapping(self):+ """Test video generation parameter mapping."""+ config = OpenAIVideoConfig()++ # Test parameter mapping+ mapped_params = config.map_openai_params(+ video_create_optional_params={+ "seconds": "8",+ "size": "720x1280",+ "user": "test-user"+ },+ model="sora-2",+ drop_params=False+ )++ assert mapped_params["seconds"] == "8"+ assert mapped_params["size"] == "720x1280"+ assert mapped_params["user"] == "test-user"++ def test_video_generation_unsupported_parameters(self):+ """Test video generation with unsupported parameters."""+ from litellm.videos.utils import VideoGenerationRequestUtils++ # Test unsupported parameter detection+ with pytest.raises(litellm.UnsupportedParamsError):+ VideoGenerationRequestUtils.get_optional_params_video_generation(+ model="sora-2",+ video_generation_provider_config=OpenAIVideoConfig(),+ video_generation_optional_params={+ "unsupported_param": "value"+ }+ )++ def test_video_generation_request_utils(self):+ """Test video generation request utilities."""+ from litellm.videos.utils import VideoGenerationRequestUtils++ # Test parameter filtering+ params = {+ "prompt": "Test video",+ "model": "sora-2",+ "seconds": "8",+ "size": "720x1280",+ "user": "test-user",+ "invalid_param": "should_be_filtered"+ }++ filtered_params = VideoGenerationRequestUtils.get_requested_video_generation_optional_param(params)++ # Should only contain valid parameters+ assert "prompt" not in filtered_params # prompt is required, not optional+ assert "seconds" in filtered_params+ assert "size" in filtered_params+ assert "user" in filtered_params+ assert "invalid_param" not in filtered_params+ # Note: model is included in the filtered params as it's part of the TypedDict++ def test_video_generation_types(self):+ """Test video generation type definitions."""+ # Test VideoObject+ video_obj = VideoObject(+ id="test_id",+ object="video",+ status="completed",+ created_at=1712697600,+ model="sora-2"+ )++ assert video_obj.id == "test_id"+ assert video_obj.object == "video"+ assert video_obj.status == "completed"++ # Test dictionary-like access+ assert video_obj["id"] == "test_id"+ assert video_obj["status"] == "completed"+ assert "id" in video_obj+ assert video_obj.get("id") == "test_id"+ assert video_obj.get("nonexistent", "default") == "default"++ # Test JSON serialization+ json_data = video_obj.json()+ assert json_data["id"] == "test_id"+ assert json_data["object"] == "video"++ def test_video_generation_response_types(self):+ """Test video generation response types."""+ # Test VideoResponse+ video_obj = VideoObject(+ id="test_id",+ object="video",+ status="completed",+ created_at=1712697600+ )++ response = VideoResponse(data=[video_obj])++ assert len(response.data) == 1+ assert response.data[0].id == "test_id"++ # Test dictionary-like access+ assert response["data"][0]["id"] == "test_id"+ assert "data" in response+ assert response.get("data")[0]["id"] == "test_id"++ # Test JSON serialization+ json_data = response.json()+ assert len(json_data["data"]) == 1+ assert json_data["data"][0]["id"] == "test_id"++ def test_video_status_basic(self):+ """Test basic video status functionality."""+ # Mock the video status response+ mock_response = VideoObject(+ id="video_123",+ object="video",+ status="completed",+ created_at=1712697600,+ completed_at=1712697660,+ model="sora-2",+ progress=100,+ size="720x1280",+ seconds="8"+ )++ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_status_handler.return_value = mock_response++ response = video_status(+ video_id="video_123",+ model="sora-2"+ )++ assert isinstance(response, VideoObject)+ assert response.id == "video_123"+ assert response.status == "completed"+ assert response.progress == 100+ assert response.model == "sora-2"++ def test_video_status_with_mock_response(self):+ """Test video status with mock response."""+ mock_data = {+ "id": "video_456",+ "object": "video",+ "status": "processing",+ "created_at": 1712697600,+ "model": "sora-2",+ "progress": 75,+ "size": "1280x720",+ "seconds": "10"+ }++ response = video_status(+ video_id="video_456",+ model="sora-2",+ mock_response=mock_data+ )++ assert isinstance(response, VideoObject)+ assert response.id == "video_456"+ assert response.status == "processing"+ assert response.progress == 75+ assert response.model == "sora-2"++ def test_video_status_async(self):+ """Test async video status functionality."""+ mock_response = VideoObject(+ id="video_async_123",+ object="video",+ status="queued",+ created_at=1712697600,+ model="sora-2",+ progress=0+ )++ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_status_handler.return_value = mock_response++ import asyncio++ async def test_async():+ response = await avideo_status(+ video_id="video_async_123",+ model="sora-2"+ )+ return response++ response = asyncio.run(test_async())++ assert isinstance(response, VideoObject)+ assert response.id == "video_async_123"+ assert response.status == "queued"+ assert response.progress == 0++ def test_video_status_parameter_validation(self):+ """Test video status parameter validation."""+ # Test with minimal required parameters+ response = video_status(+ video_id="test_video_id",+ model="sora-2",+ mock_response={"id": "test", "object": "video", "status": "completed", "created_at": 1712697600}+ )++ assert isinstance(response, VideoObject)+ assert response.id == "test"++ def test_video_status_error_handling(self):+ """Test video status error handling."""+ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_status_handler.side_effect = Exception("API Error")++ with pytest.raises(Exception):+ video_status(+ video_id="test_video_id",+ model="sora-2"+ )++ def test_video_status_request_transformation(self):+ """Test video status request transformation."""+ config = OpenAIVideoConfig()++ # Test request transformation+ url, data = config.transform_video_status_retrieve_request(+ video_id="video_123",+ model="sora-2",+ api_base="https://api.openai.com/v1/videos",+ litellm_params=MagicMock(),+ headers={}+ )++ assert url == "https://api.openai.com/v1/videos/video_123"+ assert data == {}++ def test_video_status_response_transformation(self):+ """Test video status response transformation."""+ config = OpenAIVideoConfig()++ # Mock HTTP response+ mock_http_response = MagicMock()+ mock_http_response.json.return_value = {+ "id": "video_789",+ "object": "video",+ "status": "completed",+ "created_at": 1712697600,+ "completed_at": 1712697660,+ "model": "sora-2",+ "progress": 100,+ "size": "1280x720",+ "seconds": "12"+ }++ response = config.transform_video_status_retrieve_response(+ model="sora-2",+ raw_response=mock_http_response,+ logging_obj=MagicMock()+ )++ assert isinstance(response, VideoObject)+ assert response.id == "video_789"+ assert response.status == "completed"+ assert response.progress == 100+ assert response.model == "sora-2"++ def test_video_status_different_states(self):+ """Test video status with different video states."""+ # Test queued state+ queued_response = video_status(+ video_id="video_queued",+ model="sora-2",+ mock_response={+ "id": "video_queued",+ "object": "video",+ "status": "queued",+ "created_at": 1712697600,+ "model": "sora-2",+ "progress": 0+ }+ )+ assert queued_response.status == "queued"+ assert queued_response.progress == 0++ # Test processing state+ processing_response = video_status(+ video_id="video_processing",+ model="sora-2",+ mock_response={+ "id": "video_processing",+ "object": "video",+ "status": "processing",+ "created_at": 1712697600,+ "model": "sora-2",+ "progress": 50+ }+ )+ assert processing_response.status == "processing"+ assert processing_response.progress == 50++ # Test completed state+ completed_response = video_status(+ video_id="video_completed",+ model="sora-2",+ mock_response={+ "id": "video_completed",+ "object": "video",+ "status": "completed",+ "created_at": 1712697600,+ "completed_at": 1712697660,+ "model": "sora-2",+ "progress": 100+ }+ )+ assert completed_response.status == "completed"+ assert completed_response.progress == 100++ def test_video_status_with_remix_info(self):+ """Test video status with remix information."""+ mock_data = {+ "id": "video_remix_123",+ "object": "video",+ "status": "completed",+ "created_at": 1712697600,+ "completed_at": 1712697660,+ "model": "sora-2",+ "progress": 100,+ "remixed_from_video_id": "video_original_123",+ "size": "720x1280",+ "seconds": "8"+ }++ response = video_status(+ video_id="video_remix_123",+ model="sora-2",+ mock_response=mock_data+ )++ assert isinstance(response, VideoObject)+ assert response.id == "video_remix_123"+ assert response.status == "completed"+ assert hasattr(response, 'remixed_from_video_id')+ assert response.remixed_from_video_id == "video_original_123"++ def test_video_status_async_inside_async_function(self):+ """Test that sync video_status works inside async functions (no asyncio.run issues)."""+ mock_response = VideoObject(+ id="video_sync_in_async",+ object="video",+ status="completed",+ created_at=1712697600,+ model="sora-2",+ progress=100+ )++ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_status_handler.return_value = mock_response++ import asyncio++ async def test_sync_in_async():+ # This should work without asyncio.run() issues+ response = video_status(+ video_id="video_sync_in_async",+ model="sora-2"+ )+ return response++ response = asyncio.run(test_sync_in_async())++ assert isinstance(response, VideoObject)+ assert response.id == "video_sync_in_async"+ assert response.status == "completed"++ def test_video_status_url_construction(self):+ """Test video status URL construction."""+ config = OpenAIVideoConfig()++ # Test with different API bases+ test_cases = [+ ("https://api.openai.com/v1/videos", "video_123", "https://api.openai.com/v1/videos/video_123"),+ ("https://api.openai.com/v1/videos/", "video_123", "https://api.openai.com/v1/videos/video_123"),+ ("https://custom-api.com/v1/videos", "video_456", "https://custom-api.com/v1/videos/video_456"),+ ]++ for api_base, video_id, expected_url in test_cases:+ url, data = config.transform_video_status_retrieve_request(+ video_id=video_id,+ model="sora-2",+ api_base=api_base,+ litellm_params=MagicMock(),+ headers={}+ )+ assert url == expected_url+ assert data == {}+++class TestVideoLogging:+ """Test video generation logging functionality."""++ class TestVideoLogger(CustomLogger):+ def __init__(self):+ self.standard_logging_payload = None++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ self.standard_logging_payload = kwargs.get("standard_logging_object")++ @pytest.mark.asyncio+ async def test_video_generation_logging(self):+ """Test that video generation creates proper logging payload with cost tracking."""+ custom_logger = self.TestVideoLogger()+ litellm.logging_callback_manager._reset_all_callbacks()+ litellm.callbacks = [custom_logger]++ # Mock video generation response+ mock_response = VideoObject(+ id="video_test_123",+ object="video",+ status="queued",+ created_at=1712697600,+ model="sora-2",+ size="720x1280",+ seconds="8"+ )++ with patch('litellm.videos.main.base_llm_http_handler') as mock_handler:+ mock_handler.video_generation_handler.return_value = mock_response++ response = await litellm.avideo_generation(+ prompt="A cat running in a garden",+ model="sora-2",+ seconds="8",+ size="720x1280"+ )++ await asyncio.sleep(1) # Allow logging to complete++ # Verify logging payload was created+ assert custom_logger.standard_logging_payload is not None++ payload = custom_logger.standard_logging_payload++ # Verify basic logging fields+ assert payload["call_type"] == "avideo_generation"+ assert payload["status"] == "success"+ assert payload["model"] == "sora-2"+ assert payload["custom_llm_provider"] == "openai"++ # Verify response object is recognized for logging+ assert payload["response"] is not None+ assert payload["response"]["id"] == "video_test_123"+ assert payload["response"]["object"] == "video"++ # Verify cost tracking is present (may be 0 in test environment)+ assert payload["response_cost"] is not None+ # Note: Cost calculation may not work in test environment due to mocking+ # The important thing is that the logging payload is created and recognized+++if __name__ == "__main__":+ pytest.main([__file__])