Skip to content

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]

[Feat] New model/provider - Adds support for Google Cloud Chirp3 HD on /speech (#17391)

Ishaan Jaff6c188c5ae2fa
diff --git a/docs/my-website/docs/providers/vertex.md b/docs/my-website/docs/providers/vertex.md
index 70babea3814..da2997f6202 100644
--- a/docs/my-website/docs/providers/vertex.md
+++ b/docs/my-website/docs/providers/vertex.md
@@ -2550,355 +2550,6 @@ print(response)
</TabItem>
</Tabs>
-
-## **Gemini TTS (Text-to-Speech) Audio Output**
-
-:::info
-
-LiteLLM supports Gemini TTS models on Vertex AI that can generate audio responses using the OpenAI-compatible `audio` parameter format.
-
-:::
-
-### Supported Models
-
-LiteLLM supports Gemini TTS models with audio capabilities on Vertex AI (e.g. `vertex_ai/gemini-2.5-flash-preview-tts` and `vertex_ai/gemini-2.5-pro-preview-tts`). For the complete list of available TTS models and voices, see the [official Gemini TTS documentation](https://ai.google.dev/gemini-api/docs/speech-generation).
-
-### Limitations
-
-:::warning
-
-**Important Limitations**:
-- Gemini TTS models only support the `pcm16` audio format
-- **Streaming support has not been added** to TTS models yet
-- The `modalities` parameter must be set to `['audio']` for TTS requests
-
-:::
-
-### Quick Start
-
-<Tabs>
-<TabItem value="sdk" label="SDK">
-
-```python
-from litellm import completion
-import json
-
-## GET CREDENTIALS
-file_path = 'path/to/vertex_ai_service_account.json'
-
-# Load the JSON file
-with open(file_path, 'r') as file:
- vertex_credentials = json.load(file)
-
-# Convert to JSON string
-vertex_credentials_json = json.dumps(vertex_credentials)
-
-response = completion(
- model="vertex_ai/gemini-2.5-flash-preview-tts",
- messages=[{"role": "user", "content": "Say hello in a friendly voice"}],
- modalities=["audio"], # Required for TTS models
- audio={
- "voice": "Kore",
- "format": "pcm16" # Required: must be "pcm16"
- },
- vertex_credentials=vertex_credentials_json
-)
-
-print(response)
-```
-
-</TabItem>
-<TabItem value="proxy" label="PROXY">
-
-1. Setup config.yaml
-
-```yaml
-model_list:
- - model_name: gemini-tts-flash
- litellm_params:
- model: vertex_ai/gemini-2.5-flash-preview-tts
- vertex_project: "your-project-id"
- vertex_location: "us-central1"
- vertex_credentials: "/path/to/service_account.json"
- - model_name: gemini-tts-pro
- litellm_params:
- model: vertex_ai/gemini-2.5-pro-preview-tts
- vertex_project: "your-project-id"
- vertex_location: "us-central1"
- vertex_credentials: "/path/to/service_account.json"
-```
-
-2. Start proxy
-
-```bash
-litellm --config /path/to/config.yaml
-```
-
-3. Make TTS request
-
-```bash
-curl http://0.0.0.0:4000/v1/chat/completions \
- -H "Content-Type: application/json" \
- -H "Authorization: Bearer <YOUR-LITELLM-KEY>" \
- -d '{
- "model": "gemini-tts-flash",
- "messages": [{"role": "user", "content": "Say hello in a friendly voice"}],
- "modalities": ["audio"],
- "audio": {
- "voice": "Kore",
- "format": "pcm16"
- }
- }'
-```
-
-</TabItem>
-</Tabs>
-
-### Advanced Usage
-
-You can combine TTS with other Gemini features:
-
-```python
-response = completion(
- model="vertex_ai/gemini-2.5-pro-preview-tts",
- messages=[
- {"role": "system", "content": "You are a helpful assistant that speaks clearly."},
- {"role": "user", "content": "Explain quantum computing in simple terms"}
- ],
- modalities=["audio"],
- audio={
- "voice": "Charon",
- "format": "pcm16"
- },
- temperature=0.7,
- max_tokens=150,
- vertex_credentials=vertex_credentials_json
-)
-```
-
-For more information about Gemini's TTS capabilities and available voices, see the [official Gemini TTS documentation](https://ai.google.dev/gemini-api/docs/speech-generation).
-
-## **Text to Speech APIs**
-
-:::info
-
-LiteLLM supports calling [Vertex AI Text to Speech API](https://console.cloud.google.com/vertex-ai/generative/speech/text-to-speech) in the OpenAI text to speech API format
-
-:::
-
-
-
-### Usage - Basic
-
-<Tabs>
-<TabItem value="sdk" label="SDK">
-
-Vertex AI does not support passing a `model` param - so passing `model=vertex_ai/` is the only required param
-
-**Sync Usage**
-
-```python
-speech_file_path = Path(__file__).parent / "speech_vertex.mp3"
-response = litellm.speech(
- model="vertex_ai/",
- input="hello what llm guardrail do you have",
-)
-response.stream_to_file(speech_file_path)
-```
-
-**Async Usage**
-```python
-speech_file_path = Path(__file__).parent / "speech_vertex.mp3"
-response = litellm.aspeech(
- model="vertex_ai/",
- input="hello what llm guardrail do you have",
-)
-response.stream_to_file(speech_file_path)
-```
-
-</TabItem>
-<TabItem value="proxy" label="LiteLLM PROXY (Unified Endpoint)">
-
-1. Add model to config.yaml
-```yaml
-model_list:
- - model_name: vertex-tts
- litellm_params:
- model: vertex_ai/ # Vertex AI does not support passing a `model` param - so passing `model=vertex_ai/` is the only required param
- vertex_project: "adroit-crow-413218"
- vertex_location: "us-central1"
- vertex_credentials: adroit-crow-413218-a956eef1a2a8.json
-
-litellm_settings:
- drop_params: True
-```
-
-2. Start Proxy
-
-```
-$ litellm --config /path/to/config.yaml
-```
-
-3. Make Request use OpenAI Python SDK
-
-
-```python
-import openai
-
-client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
-
-# see supported values for "voice" on vertex here:
-# https://console.cloud.google.com/vertex-ai/generative/speech/text-to-speech
-response = client.audio.speech.create(
- model = "vertex-tts",
- input="the quick brown fox jumped over the lazy dogs",
- voice={'languageCode': 'en-US', 'name': 'en-US-Studio-O'}
-)
-print("response from proxy", response)
-```
-
-</TabItem>
-</Tabs>
-
-
-### Usage - `ssml` as input
-
-Pass your `ssml` as input to the `input` param, if it contains `<speak>`, it will be automatically detected and passed as `ssml` to the Vertex AI API
-
-If you need to force your `input` to be passed as `ssml`, set `use_ssml=True`
-
-<Tabs>
-<TabItem value="sdk" label="SDK">
-
-Vertex AI does not support passing a `model` param - so passing `model=vertex_ai/` is the only required param
-
-
-```python
-speech_file_path = Path(__file__).parent / "speech_vertex.mp3"
-
-
-ssml = """
-<speak>
- <p>Hello, world!</p>
- <p>This is a test of the <break strength="medium" /> text-to-speech API.</p>
-</speak>
-"""
-
-response = litellm.speech(
- input=ssml,
- model="vertex_ai/test",
- voice={
- "languageCode": "en-UK",
- "name": "en-UK-Studio-O",
- },
- audioConfig={
- "audioEncoding": "LINEAR22",
- "speakingRate": "10",
- },
-)
-response.stream_to_file(speech_file_path)
-```
-
-</TabItem>
-
-<TabItem value="proxy" label="LiteLLM PROXY (Unified Endpoint)">
-
-```python
-import openai
-
-client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
-
-ssml = """
-<speak>
- <p>Hello, world!</p>
- <p>This is a test of the <break strength="medium" /> text-to-speech API.</p>
-</speak>
-"""
-
-# see supported values for "voice" on vertex here:
-# https://console.cloud.google.com/vertex-ai/generative/speech/text-to-speech
-response = client.audio.speech.create(
- model = "vertex-tts",
- input=ssml,
- voice={'languageCode': 'en-US', 'name': 'en-US-Studio-O'},
-)
-print("response from proxy", response)
-```
-
-</TabItem>
-</Tabs>
-
-
-### Forcing SSML Usage
-
-You can force the use of SSML by setting the `use_ssml` parameter to `True`. This is useful when you want to ensure that your input is treated as SSML, even if it doesn't contain the `<speak>` tags.
-
-Here are examples of how to force SSML usage:
-
-
-<Tabs>
-<TabItem value="sdk" label="SDK">
-
-Vertex AI does not support passing a `model` param - so passing `model=vertex_ai/` is the only required param
-
-
-```python
-speech_file_path = Path(__file__).parent / "speech_vertex.mp3"
-
-
-ssml = """
-<speak>
- <p>Hello, world!</p>
- <p>This is a test of the <break strength="medium" /> text-to-speech API.</p>
-</speak>
-"""
-
-response = litellm.speech(
- input=ssml,
- use_ssml=True,
- model="vertex_ai/test",
- voice={
- "languageCode": "en-UK",
- "name": "en-UK-Studio-O",
- },
- audioConfig={
- "audioEncoding": "LINEAR22",
- "speakingRate": "10",
- },
-)
-response.stream_to_file(speech_file_path)
-```
-
-</TabItem>
-
-<TabItem value="proxy" label="LiteLLM PROXY (Unified Endpoint)">
-
-```python
-import openai
-
-client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
-
-ssml = """
-<speak>
- <p>Hello, world!</p>
- <p>This is a test of the <break strength="medium" /> text-to-speech API.</p>
-</speak>
-"""
-
-# see supported values for "voice" on vertex here:
-# https://console.cloud.google.com/vertex-ai/generative/speech/text-to-speech
-response = client.audio.speech.create(
- model = "vertex-tts",
- input=ssml, # pass as None since OpenAI SDK requires this param
- voice={'languageCode': 'en-US', 'name': 'en-US-Studio-O'},
- extra_body={"use_ssml": True},
-)
-print("response from proxy", response)
-```
-
-</TabItem>
-</Tabs>
-
## **Fine Tuning APIs**
diff --git a/docs/my-website/docs/providers/vertex_speech.md b/docs/my-website/docs/providers/vertex_speech.md
new file mode 100644
index 00000000000..d0acacb5aec
--- /dev/null
+++ b/docs/my-website/docs/providers/vertex_speech.md
@@ -0,0 +1,423 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Vertex AI Text to Speech
+
+| Property | Details |
+|-------|-------|
+| Description | Google Cloud Text-to-Speech with Chirp3 HD voices and Gemini TTS |
+| Provider Route on LiteLLM | `vertex_ai/chirp` (Chirp), `vertex_ai/gemini-*-tts` (Gemini) |
+
+## Chirp3 HD Voices
+
+Google Cloud Text-to-Speech API with high-quality Chirp3 HD voices.
+
+### Quick Start
+
+#### LiteLLM Python SDK
+
+```python showLineNumbers title="Chirp3 Quick Start"
+from litellm import speech
+from pathlib import Path
+
+speech_file_path = Path(__file__).parent / "speech.mp3"
+response = speech(
+ model="vertex_ai/chirp",
+ voice="alloy", # OpenAI voice name - automatically mapped
+ input="Hello, this is Vertex AI Text to Speech",
+ vertex_project="your-project-id",
+ vertex_location="us-central1",
+)
+response.stream_to_file(speech_file_path)
+```
+
+#### LiteLLM AI Gateway
+
+**1. Setup config.yaml**
+
+```yaml showLineNumbers title="config.yaml"
+model_list:
+ - model_name: vertex-tts
+ litellm_params:
+ model: vertex_ai/chirp
+ vertex_project: "your-project-id"
+ vertex_location: "us-central1"
+ vertex_credentials: "/path/to/service_account.json"
+```
+
+**2. Start the proxy**
+
+```bash title="Start LiteLLM Proxy"
+litellm --config /path/to/config.yaml
+```
+
+**3. Make requests**
+
+<Tabs>
+<TabItem value="curl" label="curl">
+
+```bash showLineNumbers title="Chirp3 Quick Start"
+curl http://0.0.0.0:4000/v1/audio/speech \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "vertex-tts",
+ "voice": "alloy",
+ "input": "Hello, this is Vertex AI Text to Speech"
+ }' \
+ --output speech.mp3
+```
+
+</TabItem>
+<TabItem value="openai-sdk" label="OpenAI Python SDK">
+
+```python showLineNumbers title="Chirp3 Quick Start"
+import openai
+
+client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
+
+response = client.audio.speech.create(
+ model="vertex-tts",
+ voice="alloy",
+ input="Hello, this is Vertex AI Text to Speech",
+)
+response.stream_to_file("speech.mp3")
+```
+
+</TabItem>
+</Tabs>
+
+### Voice Mapping
+
+LiteLLM maps OpenAI voice names to Google Cloud voices. You can use either OpenAI voices or Google Cloud voices directly.
+
+| OpenAI Voice | Google Cloud Voice |
+|-------------|-------------------|
+| `alloy` | en-US-Studio-O |
+| `echo` | en-US-Studio-M |
+| `fable` | en-GB-Studio-B |
+| `onyx` | en-US-Wavenet-D |
+| `nova` | en-US-Studio-O |
+| `shimmer` | en-US-Wavenet-F |
+
+### Using Google Cloud Voices Directly
+
+#### LiteLLM Python SDK
+
+```python showLineNumbers title="Chirp3 HD Voice"
+from litellm import speech
+
+# Pass Chirp3 HD voice name directly
+response = speech(
+ model="vertex_ai/chirp",
+ voice="en-US-Chirp3-HD-Charon",
+ input="Hello with a Chirp3 HD voice",
+ vertex_project="your-project-id",
+)
+response.stream_to_file("speech.mp3")
+```
+
+```python showLineNumbers title="Voice as Dict (Multilingual)"
+from litellm import speech
+
+# Pass as dict for full control over language and voice
+response = speech(
+ model="vertex_ai/chirp",
+ voice={
+ "languageCode": "de-DE",
+ "name": "de-DE-Chirp3-HD-Charon",
+ },
+ input="Hallo, dies ist ein Test",
+ vertex_project="your-project-id",
+)
+response.stream_to_file("speech.mp3")
+```
+
+#### LiteLLM AI Gateway
+
+<Tabs>
+<TabItem value="curl" label="curl">
+
+```bash showLineNumbers title="Chirp3 HD Voice"
+curl http://0.0.0.0:4000/v1/audio/speech \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "vertex-tts",
+ "voice": "en-US-Chirp3-HD-Charon",
+ "input": "Hello with a Chirp3 HD voice"
+ }' \
+ --output speech.mp3
+```
+
+```bash showLineNumbers title="Voice as Dict (Multilingual)"
+curl http://0.0.0.0:4000/v1/audio/speech \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "vertex-tts",
+ "voice": {"languageCode": "de-DE", "name": "de-DE-Chirp3-HD-Charon"},
+ "input": "Hallo, dies ist ein Test"
+ }' \
+ --output speech.mp3
+```
+
+</TabItem>
+<TabItem value="openai-sdk" label="OpenAI Python SDK">
+
+```python showLineNumbers title="Chirp3 HD Voice"
+import openai
+
+client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
+
+response = client.audio.speech.create(
+ model="vertex-tts",
+ voice="en-US-Chirp3-HD-Charon",
+ input="Hello with a Chirp3 HD voice",
+)
+response.stream_to_file("speech.mp3")
+```
+
+```python showLineNumbers title="Voice as Dict (Multilingual)"
+import openai
+
+client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
+
+response = client.audio.speech.create(
+ model="vertex-tts",
+ voice={"languageCode": "de-DE", "name": "de-DE-Chirp3-HD-Charon"},
+ input="Hallo, dies ist ein Test",
+)
+response.stream_to_file("speech.mp3")
+```
+
+</TabItem>
+</Tabs>
+
+Browse available voices: [Google Cloud Text-to-Speech Console](https://console.cloud.google.com/vertex-ai/generative/speech/text-to-speech)
+
+### Passing Raw SSML
+
+LiteLLM auto-detects SSML when your input contains `<speak>` tags and passes it through unchanged.
+
+#### LiteLLM Python SDK
+
+```python showLineNumbers title="SSML Input"
+from litellm import speech
+
+ssml = """
+<speak>
+ <p>Hello, world!</p>
+ <p>This is a test of the <break strength="medium" /> text-to-speech API.</p>
+</speak>
+"""
+
+response = speech(
+ model="vertex_ai/chirp",
+ voice="en-US-Studio-O",
+ input=ssml, # Auto-detected as SSML
+ vertex_project="your-project-id",
+)
+response.stream_to_file("speech.mp3")
+```
+
+```python showLineNumbers title="Force SSML Mode"
+from litellm import speech
+
+# Force SSML mode with use_ssml=True
+response = speech(
+ model="vertex_ai/chirp",
+ voice="en-US-Studio-O",
+ input="<speak><prosody rate='slow'>Speaking slowly</prosody></speak>",
+ use_ssml=True,
+ vertex_project="your-project-id",
+)
+response.stream_to_file("speech.mp3")
+```
+
+#### LiteLLM AI Gateway
+
+<Tabs>
+<TabItem value="curl" label="curl">
+
+```bash showLineNumbers title="SSML Input"
+curl http://0.0.0.0:4000/v1/audio/speech \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "vertex-tts",
+ "voice": "en-US-Studio-O",
+ "input": "<speak><p>Hello!</p><break time=\"500ms\"/><p>How are you?</p></speak>"
+ }' \
+ --output speech.mp3
+```
+
+</TabItem>
+<TabItem value="openai-sdk" label="OpenAI Python SDK">
+
+```python showLineNumbers title="SSML Input"
+import openai
+
+client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
+
+ssml = """<speak><p>Hello!</p><break time="500ms"/><p>How are you?</p></speak>"""
+
+response = client.audio.speech.create(
+ model="vertex-tts",
+ voice="en-US-Studio-O",
+ input=ssml,
+)
+response.stream_to_file("speech.mp3")
+```
+
+</TabItem>
+</Tabs>
+
+### Supported Parameters
+
+| Parameter | Description | Values |
+|-----------|-------------|--------|
+| `voice` | Voice selection | OpenAI voice, Google Cloud voice name, or dict |
+| `input` | Text to convert | Plain text or SSML |
+| `speed` | Speaking rate | 0.25 to 4.0 (default: 1.0) |
+| `response_format` | Audio format | `mp3`, `opus`, `wav`, `pcm`, `flac` |
+| `use_ssml` | Force SSML mode | `True` / `False` |
+
+### Async Usage
+
+```python showLineNumbers title="Async Speech Generation"
+import asyncio
+from litellm import aspeech
+
+async def main():
+ response = await aspeech(
+ model="vertex_ai/chirp",
+ voice="alloy",
+ input="Hello from async",
+ vertex_project="your-project-id",
+ )
+ response.stream_to_file("speech.mp3")
+
+asyncio.run(main())
+```
+
+---
+
+## Gemini TTS
+
+Gemini models with audio output capabilities using the chat completions API.
+
+:::warning
+**Limitations:**
+- Only supports `pcm16` audio format
+- Streaming not yet supported
+- Must set `modalities: ["audio"]`
+:::
+
+### Quick Start
+
+#### LiteLLM Python SDK
+
+```python showLineNumbers title="Gemini TTS Quick Start"
+from litellm import completion
+import json
+
+# Load credentials
+with open('path/to/service_account.json', 'r') as file:
+ vertex_credentials = json.dumps(json.load(file))
+
+response = completion(
+ model="vertex_ai/gemini-2.5-flash-preview-tts",
+ messages=[{"role": "user", "content": "Say hello in a friendly voice"}],
+ modalities=["audio"],
+ audio={
+ "voice": "Kore",
+ "format": "pcm16"
+ },
+ vertex_credentials=vertex_credentials
+)
+print(response)
+```
+
+#### LiteLLM AI Gateway
+
+**1. Setup config.yaml**
+
+```yaml showLineNumbers title="config.yaml"
+model_list:
+ - model_name: gemini-tts
+ litellm_params:
+ model: vertex_ai/gemini-2.5-flash-preview-tts
+ vertex_project: "your-project-id"
+ vertex_location: "us-central1"
+ vertex_credentials: "/path/to/service_account.json"
+```
+
+**2. Start the proxy**
+
+```bash title="Start LiteLLM Proxy"
+litellm --config /path/to/config.yaml
+```
+
+**3. Make requests**
+
+<Tabs>
+<TabItem value="curl" label="curl">
+
+```bash showLineNumbers title="Gemini TTS Request"
+curl http://0.0.0.0:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gemini-tts",
+ "messages": [{"role": "user", "content": "Say hello in a friendly voice"}],
+ "modalities": ["audio"],
+ "audio": {"voice": "Kore", "format": "pcm16"}
+ }'
+```
+
+</TabItem>
+<TabItem value="openai-sdk" label="OpenAI Python SDK">
+
+```python showLineNumbers title="Gemini TTS Request"
+import openai
+
+client = openai.OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
+
+response = client.chat.completions.create(
+ model="gemini-tts",
+ messages=[{"role": "user", "content": "Say hello in a friendly voice"}],
+ modalities=["audio"],
+ audio={"voice": "Kore", "format": "pcm16"},
+)
+print(response)
+```
+
+</TabItem>
+</Tabs>
+
+### Supported Models
+
+- `vertex_ai/gemini-2.5-flash-preview-tts`
+- `vertex_ai/gemini-2.5-pro-preview-tts`
+
+See [Gemini TTS documentation](https://ai.google.dev/gemini-api/docs/speech-generation) for available voices.
+
+### Advanced Usage
+
+```python showLineNumbers title="Gemini TTS with System Prompt"
+from litellm import completion
+
+response = completion(
+ model="vertex_ai/gemini-2.5-pro-preview-tts",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant that speaks clearly."},
+ {"role": "user", "content": "Explain quantum computing in simple terms"}
+ ],
+ modalities=["audio"],
+ audio={"voice": "Charon", "format": "pcm16"},
+ temperature=0.7,
+ max_tokens=150,
+ vertex_credentials=vertex_credentials
+)
+```
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index a4a2956ff6a..983816ed216 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -521,6 +521,7 @@ const sidebars = {
"providers/vertex_partner",
"providers/vertex_self_deployed",
"providers/vertex_image",
+ "providers/vertex_speech",
"providers/vertex_batch",
"providers/vertex_ocr",
]
diff --git a/litellm/llms/vertex_ai/text_to_speech/transformation.py b/litellm/llms/vertex_ai/text_to_speech/transformation.py
new file mode 100644
index 00000000000..aff14b1004f
--- /dev/null
+++ b/litellm/llms/vertex_ai/text_to_speech/transformation.py
@@ -0,0 +1,472 @@
+"""
+Vertex AI Text-to-Speech transformation
+
+Maps OpenAI TTS spec to Google Cloud Text-to-Speech API
+Reference: https://cloud.google.com/text-to-speech/docs/reference/rest/v1/text/synthesize
+"""
+
+import base64
+from typing import TYPE_CHECKING, Any, Coroutine, Dict, Optional, Tuple, Union
+
+import httpx
+
+from litellm.llms.base_llm.text_to_speech.transformation import (
+ BaseTextToSpeechConfig,
+ TextToSpeechRequestData,
+)
+from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
+from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES
+from litellm.types.llms.vertex_ai_text_to_speech import (
+ VertexTextToSpeechAudioConfig,
+ VertexTextToSpeechInput,
+ VertexTextToSpeechVoice,
+)
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.types.llms.openai import HttpxBinaryResponseContent
+else:
+ LiteLLMLoggingObj = Any
+ HttpxBinaryResponseContent = Any
+
+
+class VertexAITextToSpeechConfig(BaseTextToSpeechConfig, VertexBase):
+ """
+ Configuration for Google Cloud/Vertex AI Text-to-Speech
+
+ Reference: https://cloud.google.com/text-to-speech/docs/reference/rest/v1/text/synthesize
+ """
+
+ # Default values
+ DEFAULT_LANGUAGE_CODE = "en-US"
+ DEFAULT_VOICE_NAME = "en-US-Studio-O"
+ DEFAULT_AUDIO_ENCODING = "LINEAR16"
+ DEFAULT_SPEAKING_RATE = "1"
+
+ # API endpoint
+ TTS_API_URL = "https://texttospeech.googleapis.com/v1/text:synthesize"
+
+ # Voice name mappings from OpenAI voices to Google Cloud voices
+ # Users can pass either:
+ # 1. OpenAI voice names (alloy, echo, fable, onyx, nova, shimmer) - will be mapped
+ # 2. Google Cloud/Vertex AI voice names (en-US-Studio-O, en-US-Wavenet-D, etc.) - used directly
+ VOICE_MAPPINGS = {
+ "alloy": "en-US-Studio-O",
+ "echo": "en-US-Studio-M",
+ "fable": "en-GB-Studio-B",
+ "onyx": "en-US-Wavenet-D",
+ "nova": "en-US-Studio-O",
+ "shimmer": "en-US-Wavenet-F",
+ }
+
+ # Response format mappings from OpenAI to Google Cloud audio encoding
+ FORMAT_MAPPINGS = {
+ "mp3": "MP3",
+ "opus": "OGG_OPUS",
+ "aac": "MP3", # Google doesn't have AAC, use MP3
+ "flac": "FLAC",
+ "wav": "LINEAR16",
+ "pcm": "LINEAR16",
+ }
+
+ def __init__(self) -> None:
+ BaseTextToSpeechConfig.__init__(self)
+ VertexBase.__init__(self)
+
+ def _map_voice_to_vertex_format(
+ self,
+ voice: Optional[Union[str, Dict]],
+ ) -> Tuple[Optional[str], Optional[Dict]]:
+ """
+ Map voice to Vertex AI format.
+
+ Supports both:
+ 1. OpenAI voice names (alloy, echo, fable, onyx, nova, shimmer) - will be mapped
+ 2. Vertex AI voice names (en-US-Studio-O, en-US-Wavenet-D, etc.) - used directly
+ 3. Dict with languageCode and name - used as-is
+
+ Returns:
+ Tuple of (voice_str, voice_dict) where:
+ - voice_str: Original string voice (for interface compatibility)
+ - voice_dict: Vertex AI format dict with languageCode and name
+ """
+ if voice is None:
+ return None, None
+
+ if isinstance(voice, dict):
+ # Already in Vertex AI format
+ return None, voice
+
+ # voice is a string
+ voice_str = voice
+
+ # Map OpenAI voice if it's a known OpenAI voice, otherwise use directly
+ if voice in self.VOICE_MAPPINGS:
+ mapped_voice_name = self.VOICE_MAPPINGS[voice]
+ else:
+ # Assume it's already a Vertex AI voice name
+ mapped_voice_name = voice
+
+ # Extract language code from voice name (e.g., "en-US-Studio-O" -> "en-US")
+ parts = mapped_voice_name.split("-")
+ if len(parts) >= 2:
+ language_code = f"{parts[0]}-{parts[1]}"
+ else:
+ language_code = self.DEFAULT_LANGUAGE_CODE
+
+ voice_dict = {
+ "languageCode": language_code,
+ "name": mapped_voice_name,
+ }
+
+ return voice_str, voice_dict
+
+ def dispatch_text_to_speech(
+ self,
+ model: str,
+ input: str,
+ voice: Optional[Union[str, Dict]],
+ optional_params: Dict,
+ litellm_params_dict: Dict,
+ logging_obj: "LiteLLMLoggingObj",
+ timeout: Union[float, httpx.Timeout],
+ extra_headers: Optional[Dict[str, Any]],
+ base_llm_http_handler: Any,
+ aspeech: bool,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ **kwargs: Any,
+ ) -> Union[
+ "HttpxBinaryResponseContent",
+ Coroutine[Any, Any, "HttpxBinaryResponseContent"],
+ ]:
+ """
+ Dispatch method to handle Vertex AI TTS requests
+
+ This method encapsulates Vertex AI-specific credential resolution and parameter handling.
+ Voice mapping is handled in map_openai_params (similar to Azure AVA pattern).
+
+ Args:
+ base_llm_http_handler: The BaseLLMHTTPHandler instance from main.py
+ """
+ # Resolve Vertex AI credentials using VertexBase helpers
+ vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params_dict)
+ vertex_project = self.safe_get_vertex_ai_project(litellm_params_dict)
+ vertex_location = self.safe_get_vertex_ai_location(litellm_params_dict)
+
+ # Convert voice to string if it's a dict (extract name)
+ # Actual voice mapping happens in map_openai_params
+ voice_str: Optional[str] = None
+ if isinstance(voice, str):
+ voice_str = voice
+ elif isinstance(voice, dict):
+ # Extract voice name from dict if needed
+ voice_str = voice.get("name") if voice else None
+
+ # Store credentials in litellm_params for use in transform methods
+ litellm_params_dict.update({
+ "vertex_credentials": vertex_credentials,
+ "vertex_project": vertex_project,
+ "vertex_location": vertex_location,
+ "api_base": api_base,
+ })
+
+ # Call the text_to_speech_handler
+ response = base_llm_http_handler.text_to_speech_handler(
+ model=model,
+ input=input,
+ voice=voice_str,
+ text_to_speech_provider_config=self,
+ text_to_speech_optional_params=optional_params,
+ custom_llm_provider="vertex_ai",
+ litellm_params=litellm_params_dict,
+ logging_obj=logging_obj,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ client=None,
+ _is_async=aspeech,
+ )
+
+ return response
+
+ def get_supported_openai_params(self, model: str) -> list:
+ """
+ Vertex AI TTS supports these OpenAI parameters
+
+ Note: Vertex AI also supports additional parameters like audioConfig
+ which can be passed but are not part of the OpenAI spec
+ """
+ return ["voice", "response_format", "speed"]
+
+ def map_openai_params(
+ self,
+ model: str,
+ optional_params: Dict,
+ voice: Optional[Union[str, Dict]] = None,
+ drop_params: bool = False,
+ kwargs: Dict = {},
+ ) -> Tuple[Optional[str], Dict]:
+ """
+ Map OpenAI parameters to Vertex AI TTS parameters
+
+ Voice handling (similar to Azure AVA):
+ - If voice is an OpenAI voice name (alloy, echo, etc.), it maps to a Vertex AI voice
+ - If voice is already a Vertex AI voice name (en-US-Studio-O, etc.), it's used directly
+ - If voice is a dict with languageCode and name, it's used as-is
+
+ Note: For Vertex AI, voice dict is stored in mapped_params["vertex_voice_dict"]
+ because the base class interface expects voice to be a string.
+
+ Returns:
+ Tuple of (mapped_voice_str, mapped_params)
+ """
+ mapped_params = {}
+
+ ##########################################################
+ # Map voice using helper
+ ##########################################################
+ mapped_voice_str, voice_dict = self._map_voice_to_vertex_format(voice)
+ if voice_dict is not None:
+ mapped_params["vertex_voice_dict"] = voice_dict
+
+ # Map response format
+ if "response_format" in optional_params:
+ format_name = optional_params["response_format"]
+ if format_name in self.FORMAT_MAPPINGS:
+ mapped_params["audioEncoding"] = self.FORMAT_MAPPINGS[format_name]
+ else:
+ # Try to use it directly as Google Cloud format
+ mapped_params["audioEncoding"] = format_name
+ else:
+ # Default to LINEAR16
+ mapped_params["audioEncoding"] = self.DEFAULT_AUDIO_ENCODING
+
+ # Map speed (OpenAI: 0.25-4.0, Vertex AI: speakingRate 0.25-4.0)
+ if "speed" in optional_params:
+ speed = optional_params["speed"]
+ if speed is not None:
+ mapped_params["speakingRate"] = str(speed)
+
+ # Pass through Vertex AI-specific parameters from kwargs
+ if "audioConfig" in kwargs:
+ mapped_params["audioConfig"] = kwargs["audioConfig"]
+
+ if "use_ssml" in kwargs:
+ mapped_params["use_ssml"] = kwargs["use_ssml"]
+
+ return mapped_voice_str, mapped_params
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ """
+ Validate Vertex AI environment and set up authentication headers
+
+ Note: Actual authentication is handled in transform_text_to_speech_request
+ because Vertex AI requires OAuth2 token refresh
+ """
+ validated_headers = headers.copy()
+
+ # Content-Type for JSON
+ validated_headers["Content-Type"] = "application/json"
+ validated_headers["charset"] = "UTF-8"
+
+ return validated_headers
+
+ def get_complete_url(
+ self,
+ model: str,
+ api_base: Optional[str],
+ litellm_params: dict,
+ ) -> str:
+ """
+ Get the complete URL for Vertex AI TTS request
+
+ Google Cloud TTS endpoint: https://texttospeech.googleapis.com/v1/text:synthesize
+ """
+ if api_base:
+ return api_base
+
+ return self.TTS_API_URL
+
+ def _validate_vertex_input(
+ self,
+ input_data: VertexTextToSpeechInput,
+ optional_params: Dict,
+ ) -> VertexTextToSpeechInput:
+ """
+ Validate and transform input for Vertex AI TTS
+
+ Handles text vs SSML input detection and validation
+ """
+ # Remove None values
+ if input_data.get("text") is None:
+ input_data.pop("text", None)
+ if input_data.get("ssml") is None:
+ input_data.pop("ssml", None)
+
+ # Check if use_ssml is set
+ use_ssml = optional_params.get("use_ssml", False)
+
+ if use_ssml:
+ if "text" in input_data:
+ input_data["ssml"] = input_data.pop("text")
+ elif "ssml" not in input_data:
+ raise ValueError("SSML input is required when use_ssml is True.")
+ else:
+ # LiteLLM will auto-detect if text is in ssml format
+ # check if "text" is an ssml - in this case we should pass it as ssml instead of text
+ if input_data:
+ _text = input_data.get("text", None) or ""
+ if "<speak>" in _text:
+ input_data["ssml"] = input_data.pop("text")
+
+ if not input_data:
+ raise ValueError("Either 'text' or 'ssml' must be provided.")
+ if "text" in input_data and "ssml" in input_data:
+ raise ValueError("Only one of 'text' or 'ssml' should be provided, not both.")
+
+ return input_data
+
+ def transform_text_to_speech_request(
+ self,
+ model: str,
+ input: str,
+ voice: Optional[str],
+ optional_params: Dict,
+ litellm_params: Dict,
+ headers: dict,
+ ) -> TextToSpeechRequestData:
+ """
+ Transform OpenAI TTS request to Vertex AI TTS format
+
+ This method handles:
+ 1. Authentication with Vertex AI
+ 2. Building the request body
+ 3. Setting up headers
+
+ Returns:
+ TextToSpeechRequestData: Contains dict_body and headers
+ """
+ # Get Vertex AI credentials from litellm_params
+ vertex_credentials: Optional[VERTEX_CREDENTIALS_TYPES] = litellm_params.get(
+ "vertex_credentials"
+ )
+ vertex_project: Optional[str] = litellm_params.get("vertex_project")
+
+ ####### Authenticate with Vertex AI ########
+ _auth_header, vertex_project = self._ensure_access_token(
+ credentials=vertex_credentials,
+ project_id=vertex_project,
+ custom_llm_provider="vertex_ai_beta",
+ )
+
+ auth_header, _ = self._get_token_and_url(
+ model="",
+ auth_header=_auth_header,
+ gemini_api_key=None,
+ vertex_credentials=vertex_credentials,
+ vertex_project=vertex_project,
+ vertex_location=litellm_params.get("vertex_location"),
+ stream=False,
+ custom_llm_provider="vertex_ai_beta",
+ api_base=litellm_params.get("api_base"),
+ )
+
+ # Set authentication headers
+ headers["Authorization"] = f"Bearer {auth_header}"
+ headers["x-goog-user-project"] = vertex_project
+
+ ####### Build the request ################
+ vertex_input = VertexTextToSpeechInput(text=input)
+ vertex_input = self._validate_vertex_input(vertex_input, optional_params)
+
+ # Build voice configuration
+ # Check for voice dict stored in:
+ # 1. litellm_params by dispatch method
+ # 2. optional_params by map_openai_params
+ voice_dict = (
+ litellm_params.get("vertex_voice_dict")
+ or optional_params.get("vertex_voice_dict")
+ )
+ if voice_dict is not None and isinstance(voice_dict, dict):
+ vertex_voice = VertexTextToSpeechVoice(**voice_dict)
+ elif voice is not None and isinstance(voice, str):
+ # Handle string voice (shouldn't normally happen if dispatch was called)
+ parts = voice.split("-")
+ if len(parts) >= 2:
+ language_code = f"{parts[0]}-{parts[1]}"
+ else:
+ language_code = self.DEFAULT_LANGUAGE_CODE
+ vertex_voice = VertexTextToSpeechVoice(
+ languageCode=language_code,
+ name=voice,
+ )
+ else:
+ # Use defaults
+ vertex_voice = VertexTextToSpeechVoice(
+ languageCode=self.DEFAULT_LANGUAGE_CODE,
+ name=self.DEFAULT_VOICE_NAME,
+ )
+
+ # Build audio configuration
+ audio_encoding = optional_params.get("audioEncoding", self.DEFAULT_AUDIO_ENCODING)
+ speaking_rate = optional_params.get("speakingRate", self.DEFAULT_SPEAKING_RATE)
+
+ # Check for full audioConfig in optional_params
+ if "audioConfig" in optional_params:
+ vertex_audio_config = VertexTextToSpeechAudioConfig(**optional_params["audioConfig"])
+ else:
+ vertex_audio_config = VertexTextToSpeechAudioConfig(
+ audioEncoding=audio_encoding,
+ speakingRate=speaking_rate,
+ )
+
+ request_body: Dict[str, Any] = {
+ "input": dict(vertex_input),
+ "voice": dict(vertex_voice),
+ "audioConfig": dict(vertex_audio_config),
+ }
+
+ return TextToSpeechRequestData(
+ dict_body=request_body,
+ headers=headers,
+ )
+
+ def transform_text_to_speech_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ logging_obj: "LiteLLMLoggingObj",
+ ) -> "HttpxBinaryResponseContent":
+ """
+ Transform Vertex AI TTS response to standard format
+
+ Vertex AI returns JSON with base64-encoded audio content.
+ We decode it and return as HttpxBinaryResponseContent.
+ """
+ from litellm.types.llms.openai import HttpxBinaryResponseContent
+
+ # Parse JSON response
+ _json_response = raw_response.json()
+
+ # Get base64-encoded audio content
+ response_content = _json_response.get("audioContent")
+ if not response_content:
+ raise ValueError("No audioContent in Vertex AI TTS response")
+
+ # Decode base64 to get binary content
+ binary_data = base64.b64decode(response_content)
+
+ # Create an httpx.Response object with the binary data
+ response = httpx.Response(
+ status_code=200,
+ content=binary_data,
+ )
+
+ # Initialize the HttpxBinaryResponseContent instance
+ return HttpxBinaryResponseContent(response)
diff --git a/litellm/main.py b/litellm/main.py
index a09a9453017..fa9172632cf 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -206,7 +206,6 @@ from .llms.vertex_ai.image_generation.image_generation_handler import (
from .llms.vertex_ai.multimodal_embeddings.embedding_handler import (
VertexMultimodalEmbedding,
)
-from .llms.vertex_ai.text_to_speech.text_to_speech_handler import VertexTextToSpeechAPI
from .llms.vertex_ai.vertex_ai_partner_models.main import VertexAIPartnerModels
from .llms.vertex_ai.vertex_embeddings.embedding_handler import VertexEmbedding
from .llms.vertex_ai.vertex_gemma_models.main import VertexAIGemmaModels
@@ -277,7 +276,7 @@ google_batch_embeddings = GoogleBatchEmbeddings()
vertex_partner_models_chat_completion = VertexAIPartnerModels()
vertex_gemma_chat_completion = VertexAIGemmaModels()
vertex_model_garden_chat_completion = VertexAIModelGardenModels()
-vertex_text_to_speech = VertexTextToSpeechAPI()
+# vertex_text_to_speech is now replaced by VertexAITextToSpeechConfig
sagemaker_llm = SagemakerLLM()
watsonx_chat_completion = WatsonXChatHandler()
openai_like_embedding = OpenAILikeEmbeddingHandler()
@@ -6145,30 +6144,13 @@ def speech( # noqa: PLR0915
_is_async=aspeech or False,
)
elif custom_llm_provider == "vertex_ai" or custom_llm_provider == "vertex_ai_beta":
- generic_optional_params = GenericLiteLLMParams(**kwargs)
-
- api_base = generic_optional_params.api_base or ""
- vertex_ai_project = (
- generic_optional_params.vertex_project
- or litellm.vertex_project
- or get_secret_str("VERTEXAI_PROJECT")
- )
- vertex_ai_location = (
- generic_optional_params.vertex_location
- or litellm.vertex_location
- or get_secret_str("VERTEXAI_LOCATION")
- )
- vertex_credentials = (
- generic_optional_params.vertex_credentials
- or get_secret_str("VERTEXAI_CREDENTIALS")
+ from litellm.llms.vertex_ai.text_to_speech.transformation import (
+ VertexAITextToSpeechConfig,
)
- if voice is not None and not isinstance(voice, dict):
- raise litellm.BadRequestError(
- message=f"'voice' is required to be passed as a dict for Vertex AI TTS, passed in voice={voice}",
- model=model,
- llm_provider=custom_llm_provider,
- )
+ generic_optional_params = GenericLiteLLMParams(**kwargs)
+
+ # Handle Gemini models separately (they use speech_to_completion_bridge)
if "gemini" in model:
from .endpoints.speech.speech_to_completion_bridge.handler import (
speech_to_completion_bridge_handler,
@@ -6184,19 +6166,37 @@ def speech( # noqa: PLR0915
logging_obj=logging_obj,
custom_llm_provider=custom_llm_provider,
)
- response = vertex_text_to_speech.audio_speech(
- _is_async=aspeech,
- vertex_credentials=vertex_credentials,
- vertex_project=vertex_ai_project,
- vertex_location=vertex_ai_location,
- timeout=timeout,
- api_base=api_base,
+
+ # Vertex AI Text-to-Speech (Google Cloud TTS)
+ if text_to_speech_provider_config is None:
+ text_to_speech_provider_config = VertexAITextToSpeechConfig()
+
+ # Cast to specific Vertex AI config type to access dispatch method
+ vertex_config = cast(
+ VertexAITextToSpeechConfig, text_to_speech_provider_config
+ )
+
+ # Store Vertex AI specific params in litellm_params_dict
+ litellm_params_dict.update({
+ "vertex_project": generic_optional_params.vertex_project,
+ "vertex_location": generic_optional_params.vertex_location,
+ "vertex_credentials": generic_optional_params.vertex_credentials,
+ })
+
+ response = vertex_config.dispatch_text_to_speech(
model=model,
input=input,
voice=voice,
optional_params=optional_params,
- kwargs=kwargs,
+ litellm_params_dict=litellm_params_dict,
logging_obj=logging_obj,
+ timeout=timeout,
+ extra_headers=headers,
+ base_llm_http_handler=base_llm_http_handler,
+ aspeech=aspeech or False,
+ api_base=generic_optional_params.api_base,
+ api_key=None, # Vertex AI uses OAuth, not API key
+ **kwargs,
)
elif custom_llm_provider == "gemini":
from .endpoints.speech.speech_to_completion_bridge.handler import (
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index f28e9b1290f..f3398e470d8 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -24825,6 +24825,15 @@
"supports_parallel_function_calling": true,
"supports_tool_choice": true
},
+ "vertex_ai/chirp": {
+ "input_cost_per_character": 30e-06,
+ "litellm_provider": "vertex_ai",
+ "mode": "audio_speech",
+ "source": "https://cloud.google.com/text-to-speech/pricing",
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ]
+ },
"vertex_ai/claude-3-5-haiku": {
"input_cost_per_token": 1e-06,
"litellm_provider": "vertex_ai-anthropic_models",
diff --git a/litellm/types/llms/vertex_ai_text_to_speech.py b/litellm/types/llms/vertex_ai_text_to_speech.py
new file mode 100644
index 00000000000..e65b75356bf
--- /dev/null
+++ b/litellm/types/llms/vertex_ai_text_to_speech.py
@@ -0,0 +1,54 @@
+"""
+Type definitions for Vertex AI Text-to-Speech API
+
+Reference: https://cloud.google.com/text-to-speech/docs/reference/rest/v1/text/synthesize
+"""
+
+from typing import Optional
+
+from typing_extensions import TypedDict
+
+
+class VertexTextToSpeechInput(TypedDict, total=False):
+ """
+ Input for Vertex AI Text-to-Speech synthesis.
+
+ Exactly one of text or ssml must be provided.
+ """
+ text: Optional[str]
+ ssml: Optional[str]
+
+
+class VertexTextToSpeechVoice(TypedDict, total=False):
+ """
+ Voice configuration for Vertex AI Text-to-Speech.
+
+ Attributes:
+ languageCode: The language code (e.g., "en-US", "de-DE")
+ name: The voice name (e.g., "en-US-Studio-O", "en-US-Wavenet-D")
+ """
+ languageCode: str
+ name: str
+
+
+class VertexTextToSpeechAudioConfig(TypedDict, total=False):
+ """
+ Audio configuration for Vertex AI Text-to-Speech.
+
+ Attributes:
+ audioEncoding: The audio encoding format (e.g., "LINEAR16", "MP3", "OGG_OPUS")
+ speakingRate: The speaking rate (0.25 to 4.0, default "1")
+ """
+ audioEncoding: str
+ speakingRate: str
+
+
+class VertexTextToSpeechRequest(TypedDict, total=False):
+ """
+ Request body for Vertex AI Text-to-Speech API.
+
+ Reference: https://cloud.google.com/text-to-speech/docs/reference/rest/v1/text/synthesize
+ """
+ input: VertexTextToSpeechInput
+ voice: VertexTextToSpeechVoice
+ audioConfig: Optional[VertexTextToSpeechAudioConfig]
diff --git a/litellm/utils.py b/litellm/utils.py
index 6c50afc5f49..3775506e248 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -7910,6 +7910,12 @@ class ProviderConfigManager:
)
return RunwayMLTextToSpeechConfig()
+ elif litellm.LlmProviders.VERTEX_AI == provider:
+ from litellm.llms.vertex_ai.text_to_speech.transformation import (
+ VertexAITextToSpeechConfig,
+ )
+
+ return VertexAITextToSpeechConfig()
return None
@staticmethod
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index f28e9b1290f..f3398e470d8 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -24825,6 +24825,15 @@
"supports_parallel_function_calling": true,
"supports_tool_choice": true
},
+ "vertex_ai/chirp": {
+ "input_cost_per_character": 30e-06,
+ "litellm_provider": "vertex_ai",
+ "mode": "audio_speech",
+ "source": "https://cloud.google.com/text-to-speech/pricing",
+ "supported_endpoints": [
+ "/v1/audio/speech"
+ ]
+ },
"vertex_ai/claude-3-5-haiku": {
"input_cost_per_token": 1e-06,
"litellm_provider": "vertex_ai-anthropic_models",
diff --git a/provider_endpoints_support.json b/provider_endpoints_support.json
index b5bde3e5ce4..441391dc742 100644
--- a/provider_endpoints_support.json
+++ b/provider_endpoints_support.json
@@ -734,6 +734,22 @@
"ocr": true
}
},
+ "vertex_ai/chirp": {
+ "display_name": "Google - Vertex AI Chirp3 HD (`vertex_ai/chirp`)",
+ "url": "https://docs.litellm.ai/docs/providers/vertex_speech",
+ "endpoints": {
+ "chat_completions": false,
+ "messages": false,
+ "responses": false,
+ "embeddings": false,
+ "image_generations": false,
+ "audio_transcriptions": false,
+ "audio_speech": true,
+ "moderations": false,
+ "batches": false,
+ "rerank": false
+ }
+ },
"gemini": {
"display_name": "Google AI Studio - Gemini (`gemini`)",
"url": "https://docs.litellm.ai/docs/providers/gemini",
diff --git a/tests/audio_tests/speech_vertex.mp3 b/tests/audio_tests/speech_vertex.mp3
new file mode 100644
index 00000000000..91efaea150c
Binary files /dev/null and b/tests/audio_tests/speech_vertex.mp3 differ
diff --git a/tests/litellm/llms/vertex_ai/text_to_speech/test_transformation.py b/tests/litellm/llms/vertex_ai/text_to_speech/test_transformation.py
new file mode 100644
index 00000000000..9a5888e8506
--- /dev/null
+++ b/tests/litellm/llms/vertex_ai/text_to_speech/test_transformation.py
@@ -0,0 +1,190 @@
+import json
+import os
+import sys
+from unittest.mock import MagicMock, Mock, patch
+
+import httpx
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../../../..")
+) # Adds the parent directory to the system path
+
+import litellm
+from litellm.llms.vertex_ai.text_to_speech.transformation import (
+ VertexAITextToSpeechConfig,
+)
+
+
+class TestVertexAITextToSpeechConfig:
+ """Tests for VertexAITextToSpeechConfig transformation"""
+
+ def test_get_complete_url(self):
+ """Test that get_complete_url returns the correct Google Cloud TTS API URL"""
+ config = VertexAITextToSpeechConfig()
+
+ url = config.get_complete_url(
+ model="vertex_ai/chirp",
+ api_base=None,
+ litellm_params={},
+ )
+
+ assert url == "https://texttospeech.googleapis.com/v1/text:synthesize"
+
+ def test_get_complete_url_with_custom_api_base(self):
+ """Test that get_complete_url uses custom api_base when provided"""
+ config = VertexAITextToSpeechConfig()
+
+ custom_url = "https://custom-tts-endpoint.example.com/v1/synthesize"
+ url = config.get_complete_url(
+ model="vertex_ai/chirp",
+ api_base=custom_url,
+ litellm_params={},
+ )
+
+ assert url == custom_url
+
+ @patch.object(VertexAITextToSpeechConfig, "_ensure_access_token")
+ @patch.object(VertexAITextToSpeechConfig, "_get_token_and_url")
+ def test_transform_text_to_speech_request_body(
+ self, mock_get_token, mock_ensure_token
+ ):
+ """Test that transform_text_to_speech_request generates correct request body"""
+ # Mock authentication
+ mock_ensure_token.return_value = ("mock-token", "test-project")
+ mock_get_token.return_value = ("mock-token", "mock-url")
+
+ config = VertexAITextToSpeechConfig()
+
+ # Test with voice dict in litellm_params (as set by dispatch)
+ result = config.transform_text_to_speech_request(
+ model="vertex_ai/chirp",
+ input="Hello, this is a test",
+ voice=None,
+ optional_params={
+ "vertex_voice_dict": {
+ "languageCode": "en-US",
+ "name": "en-US-Chirp3-HD-Charon",
+ }
+ },
+ litellm_params={
+ "vertex_credentials": None,
+ "vertex_project": "test-project",
+ "vertex_location": "us-central1",
+ },
+ headers={},
+ )
+
+ # Verify request body structure
+ assert "dict_body" in result
+ request_body = result["dict_body"]
+
+ assert "input" in request_body
+ assert request_body["input"] == {"text": "Hello, this is a test"}
+
+ assert "voice" in request_body
+ assert request_body["voice"]["languageCode"] == "en-US"
+ assert request_body["voice"]["name"] == "en-US-Chirp3-HD-Charon"
+
+ assert "audioConfig" in request_body
+
+ # Verify headers contain auth
+ assert "headers" in result
+ assert "Authorization" in result["headers"]
+
+ def test_voice_mapping_openai_to_vertex(self):
+ """Test that OpenAI voice names are correctly mapped to Vertex AI voices"""
+ config = VertexAITextToSpeechConfig()
+
+ # Test the _map_voice_to_vertex_format helper
+ voice_str, voice_dict = config._map_voice_to_vertex_format("alloy")
+
+ assert voice_str == "alloy"
+ assert voice_dict is not None
+ assert voice_dict["name"] == "en-US-Studio-O"
+ assert voice_dict["languageCode"] == "en-US"
+
+ def test_voice_mapping_vertex_voice_passthrough(self):
+ """Test that Vertex AI voice names are passed through directly"""
+ config = VertexAITextToSpeechConfig()
+
+ # Test with a Chirp3 HD voice
+ voice_str, voice_dict = config._map_voice_to_vertex_format(
+ "en-US-Chirp3-HD-Charon"
+ )
+
+ assert voice_str == "en-US-Chirp3-HD-Charon"
+ assert voice_dict is not None
+ assert voice_dict["name"] == "en-US-Chirp3-HD-Charon"
+ assert voice_dict["languageCode"] == "en-US"
+
+ def test_voice_mapping_dict_passthrough(self):
+ """Test that voice dict is passed through unchanged"""
+ config = VertexAITextToSpeechConfig()
+
+ voice_input = {
+ "languageCode": "de-DE",
+ "name": "de-DE-Chirp3-HD-Charon",
+ }
+ voice_str, voice_dict = config._map_voice_to_vertex_format(voice_input)
+
+ assert voice_str is None
+ assert voice_dict == voice_input
+
+
+@patch("litellm.llms.custom_httpx.llm_http_handler.HTTPHandler.post")
[email protected](VertexAITextToSpeechConfig, "_ensure_access_token")
[email protected](VertexAITextToSpeechConfig, "_get_token_and_url")
+def test_litellm_speech_vertex_ai_chirp(mock_get_token, mock_ensure_token, mock_post):
+ """
+ Test that litellm.speech(model="vertex_ai/chirp") sends the correct URL and request body
+ """
+ # Mock authentication
+ mock_ensure_token.return_value = ("mock-token", "test-project")
+ mock_get_token.return_value = ("mock-token", "mock-url")
+
+ # Mock HTTP response
+ mock_response = Mock(spec=httpx.Response)
+ mock_response.content = b'{"audioContent": "SGVsbG8gV29ybGQ="}' # base64 encoded "Hello World"
+ mock_response.status_code = 200
+ mock_response.headers = {"content-type": "application/json"}
+ mock_response.json.return_value = {"audioContent": "SGVsbG8gV29ybGQ="}
+ mock_post.return_value = mock_response
+
+ litellm.speech(
+ model="vertex_ai/chirp",
+ input="Hello, this is a test",
+ voice="en-US-Chirp3-HD-Charon",
+ vertex_project="test-project",
+ vertex_location="us-central1",
+ )
+
+ # Verify the HTTP call was made
+ mock_post.assert_called_once()
+ call_kwargs = mock_post.call_args.kwargs
+
+ # Verify the URL is the Google Cloud TTS API
+ assert call_kwargs["url"] == "https://texttospeech.googleapis.com/v1/text:synthesize"
+
+ # Verify request body structure
+ assert "data" in call_kwargs
+ request_body = json.loads(call_kwargs["data"])
+
+ # Verify input
+ assert "input" in request_body
+ assert request_body["input"] == {"text": "Hello, this is a test"}
+
+ # Verify voice
+ assert "voice" in request_body
+ assert request_body["voice"]["name"] == "en-US-Chirp3-HD-Charon"
+ assert request_body["voice"]["languageCode"] == "en-US"
+
+ # Verify audioConfig
+ assert "audioConfig" in request_body
+
+ # Verify headers contain authorization
+ assert "headers" in call_kwargs
+ assert "Authorization" in call_kwargs["headers"]
+ assert call_kwargs["headers"]["Authorization"] == "Bearer mock-token"
+
+