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]

initial int live api

Sameerlite9d4eb814d4f6
diff --git a/docs/my-website/docs/pass_through/vertex_ai.md b/docs/my-website/docs/pass_through/vertex_ai.md
index d3f4e75e31d..77095667113 100644
--- a/docs/my-website/docs/pass_through/vertex_ai.md
+++ b/docs/my-website/docs/pass_through/vertex_ai.md
@@ -15,10 +15,11 @@ Pass-through endpoints for Vertex AI - call provider-specific endpoint, in nativ
## Supported Endpoints
-LiteLLM supports 2 vertex ai passthrough routes:
+LiteLLM supports 3 vertex ai passthrough routes:
1. `/vertex_ai` → routes to `https://{vertex_location}-aiplatform.googleapis.com/`
2. `/vertex_ai/discovery` → routes to [`https://discoveryengine.googleapis.com`](https://discoveryengine.googleapis.com/)
+3. `/vertex_ai/live` → upgrades to the Vertex AI Live API WebSocket (`google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent`)
## How to use
@@ -170,6 +171,50 @@ generateContent();
</Tabs>
+## Vertex AI Live API WebSocket
+
+LiteLLM can now proxy the Vertex AI Live API to help you experiment with streaming audio/text from Gemini Live models without exposing Google credentials to clients.
+
+- Configure default Vertex credentials via `default_vertex_config` or environment variables (see examples above).
+- Connect to `wss://<PROXY_URL>/vertex_ai/live`. LiteLLM will exchange your saved credentials for a short-lived access token and forward messages bidirectionally.
+- Optional query params `vertex_project`, `vertex_location`, and `model` let you override defaults for multi-project setups or global-only models.
+
+```python title="client.py"
+import asyncio
+import json
+
+from websockets.asyncio.client import connect
+
+
+async def main() -> None:
+ headers = {
+ "x-litellm-api-key": "Bearer sk-your-litellm-key",
+ "Content-Type": "application/json",
+ }
+ async with connect(
+ "ws://localhost:4000/vertex_ai/live",
+ additional_headers=headers,
+ ) as ws:
+ await ws.send(
+ json.dumps(
+ {
+ "setup": {
+ "model": "projects/your-project/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09",
+ "generation_config": {"response_modalities": ["TEXT"]},
+ }
+ }
+ )
+ )
+
+ async for message in ws:
+ print("server:", message)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+
## Quick Start
Let's call the Vertex AI [`/generateContent` endpoint](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference)
@@ -415,4 +460,4 @@ generateContent();
```
</TabItem>
-</Tabs>
\ No newline at end of file
+</Tabs>
diff --git a/docs/my-website/docs/pass_through/vertex_ai_live_websocket.md b/docs/my-website/docs/pass_through/vertex_ai_live_websocket.md
new file mode 100644
index 00000000000..cca40d10fd8
--- /dev/null
+++ b/docs/my-website/docs/pass_through/vertex_ai_live_websocket.md
@@ -0,0 +1,284 @@
+# Vertex AI Live API WebSocket Passthrough
+
+LiteLLM now supports WebSocket passthrough for the Vertex AI Live API, enabling real-time bidirectional communication with Gemini models.
+
+## Overview
+
+The Vertex AI Live API WebSocket passthrough allows you to:
+- Connect to Vertex AI Live API through LiteLLM proxy
+- Use existing Vertex AI authentication methods
+- Pass through all WebSocket messages bidirectionally
+- Support text, audio, video, and multimodal interactions
+- Track costs automatically for all usage types
+
+## Configuration
+
+### Environment Variables
+
+Set the following environment variables for Vertex AI authentication:
+
+```bash
+# Required
+DEFAULT_VERTEXAI_PROJECT=your-project-id
+DEFAULT_VERTEXAI_LOCATION=us-central1
+
+# Optional - use one of these for authentication
+DEFAULT_GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
+# OR run: gcloud auth application-default login
+```
+
+### Configuration File
+
+Alternatively, configure in your `config.yaml`:
+
+```yaml
+litellm_settings:
+ default_vertex_config:
+ vertex_project: "your-project-id"
+ vertex_location: "us-central1"
+ vertex_credentials: "os.environ/GOOGLE_APPLICATION_CREDENTIALS"
+```
+
+## Usage
+
+### WebSocket Endpoints
+
+- `ws://your-proxy-host/v1/vertex-ai/live`
+- `ws://your-proxy-host/vertex-ai/live`
+
+### Query Parameters
+
+- `project_id` (optional): Google Cloud project ID (can be set in config)
+- `location` (optional): Vertex AI location (can be set in config, default: us-central1)
+
+### Example Connection
+
+```javascript
+// If project_id and location are set in config, you can connect without query params
+const ws = new WebSocket('ws://localhost:4000/v1/vertex-ai/live');
+
+// Or specify them explicitly
+const ws = new WebSocket('ws://localhost:4000/v1/vertex-ai/live?project_id=your-project-id&location=us-central1');
+```
+
+## Cost Tracking
+
+The WebSocket passthrough automatically tracks costs for all usage types based on the [Vertex AI pricing](https://cloud.google.com/vertex-ai/generative-ai/pricing#model-optimizer-pricing):
+
+### Supported Cost Tracking
+
+- **Text**: Character-based or token-based pricing depending on model
+- **Audio**: Per-second pricing for audio input/output
+- **Video**: Per-second pricing for video input
+- **Images**: Per-image pricing for image input
+
+### Cost Calculation
+
+Costs are calculated using the same methods as other Vertex AI models in LiteLLM:
+- Uses `cost_per_character` for Gemini models
+- Uses `cost_per_token` for partner models (Claude, Llama, etc.)
+- Includes audio, video, and image costs when applicable
+
+### Cost Logging
+
+Costs are automatically logged to:
+- LiteLLM proxy logs
+- Database (if configured)
+- Spend tracking system
+- Admin dashboard
+
+Example log output:
+```
+Vertex AI Live WebSocket session cost: $0.001234 (input: $0.000800, output: $0.000434) tokens: 150, characters: 1200, duration: 45.2s
+```
+
+## API Reference
+
+### Setup Message
+
+Send this message first to initialize the session:
+
+```json
+{
+ "setup": {
+ "model": "projects/your-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09",
+ "generation_config": {
+ "response_modalities": ["TEXT"]
+ }
+ }
+}
+```
+
+### Text Input
+
+```json
+{
+ "client_content": {
+ "turns": [
+ {
+ "role": "user",
+ "parts": [{"text": "Hello! How are you?"}]
+ }
+ ],
+ "turn_complete": true
+ }
+}
+```
+
+### Audio Input
+
+```json
+{
+ "realtime_input": {
+ "media_chunks": [
+ {
+ "data": "base64-encoded-audio-data",
+ "mime_type": "audio/pcm"
+ }
+ ]
+ }
+}
+```
+
+## Supported Features
+
+### Response Modalities
+
+- **TEXT**: Text responses
+- **AUDIO**: Audio responses with voice synthesis
+
+### Tools
+
+- **Function Calling**: Define and use custom functions
+- **Code Execution**: Execute Python code
+- **Google Search**: Search the web
+- **Voice Activity Detection**: Detect when user is speaking
+
+### Advanced Features
+
+- **Audio Transcription**: Transcribe input and output audio
+- **Proactive Audio**: Model responds only when relevant
+- **Affective Dialog**: Understand emotional expressions
+
+## Examples
+
+### Python Client
+
+```python
+import asyncio
+import json
+import websockets
+
+async def chat_with_gemini():
+ uri = "ws://localhost:4000/v1/vertex-ai/live?project_id=your-project-id"
+
+ async with websockets.connect(uri) as websocket:
+ # Setup
+ setup = {
+ "setup": {
+ "model": "projects/your-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09",
+ "generation_config": {"response_modalities": ["TEXT"]}
+ }
+ }
+ await websocket.send(json.dumps(setup))
+
+ # Wait for setup response
+ response = await websocket.recv()
+ print(f"Setup: {response}")
+
+ # Send message
+ message = {
+ "client_content": {
+ "turns": [{"role": "user", "parts": [{"text": "Hello!"}]}],
+ "turn_complete": True
+ }
+ }
+ await websocket.send(json.dumps(message))
+
+ # Receive response
+ async for response in websocket:
+ print(f"Response: {response}")
+ # Check if turn is complete
+ data = json.loads(response)
+ if data.get("serverContent", {}).get("turnComplete"):
+ break
+
+asyncio.run(chat_with_gemini())
+```
+
+### JavaScript Client
+
+```javascript
+const ws = new WebSocket('ws://localhost:4000/v1/vertex-ai/live?project_id=your-project-id');
+
+ws.onopen = function() {
+ // Send setup
+ const setup = {
+ setup: {
+ model: "projects/your-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09",
+ generation_config: { response_modalities: ["TEXT"] }
+ }
+ };
+ ws.send(JSON.stringify(setup));
+};
+
+ws.onmessage = function(event) {
+ const data = JSON.parse(event.data);
+ console.log('Received:', data);
+
+ // Check if setup is complete
+ if (data.setupComplete) {
+ // Send a message
+ const message = {
+ client_content: {
+ turns: [{ role: "user", parts: [{ text: "Hello!" }] }],
+ turn_complete: true
+ }
+ };
+ ws.send(JSON.stringify(message));
+ }
+};
+```
+
+## Error Handling
+
+The WebSocket connection may close with these codes:
+
+- `4001`: Vertex AI credentials not configured
+- `4002`: Project ID not provided
+- `1011`: Internal server error
+
+## Authentication
+
+The WebSocket passthrough uses the same authentication as other LiteLLM endpoints:
+
+1. **API Key**: Pass `Authorization: Bearer your-api-key` header
+2. **Vertex AI Credentials**: Set environment variables or config file
+
+## Limitations
+
+- Requires valid Google Cloud project with Vertex AI API enabled
+- WebSocket connections are not persistent across server restarts
+- Rate limits apply based on your Google Cloud quotas
+
+## Troubleshooting
+
+### Common Issues
+
+1. **Authentication Error**: Ensure Vertex AI credentials are properly configured
+2. **Project Not Found**: Verify the project ID exists and has Vertex AI enabled
+3. **Connection Refused**: Check that the LiteLLM proxy server is running
+
+### Debug Mode
+
+Enable debug logging to see detailed connection information:
+
+```bash
+export LITELLM_LOG=DEBUG
+```
+
+## Related Documentation
+
+- [Vertex AI Live API Reference](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/multimodal-live)
+- [LiteLLM Proxy Configuration](../proxy/)
+- [Vertex AI Passthrough Endpoints](./vertex_ai.md)
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 472aeb140cf..34bed4465c3 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -151,6 +151,7 @@ from litellm.litellm_core_utils.credential_accessor import CredentialAccessor
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
+from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
router as mcp_rest_endpoints_router,
)
@@ -412,6 +413,8 @@ from fastapi import (
Request,
Response,
UploadFile,
+ WebSocket,
+ WebSocketDisconnect,
applications,
status,
)
@@ -685,6 +688,8 @@ app = FastAPI(
lifespan=proxy_startup_event,
)
+vertex_live_passthrough_vertex_base = VertexBase()
+
### CUSTOM API DOCS [ENTERPRISE FEATURE] ###
# Custom OpenAPI schema generator to include only selected routes
@@ -4892,11 +4897,202 @@ async def audio_transcriptions(
######################################################################
-# /v1/realtime Endpoints
+# Vertex AI Live API WebSocket Pass-through
+
+######################################################################
+
+
[email protected]("/vertex_ai/live")
+async def vertex_ai_live_passthrough_endpoint(
+ websocket: WebSocket,
+ model: Optional[str] = fastapi.Query(
+ None,
+ description="Optional model name, used to determine Vertex region for global models.",
+ ),
+ vertex_project: Optional[str] = fastapi.Query(
+ None,
+ description="Override the Vertex AI project id used for the upstream connection.",
+ ),
+ vertex_location: Optional[str] = fastapi.Query(
+ None,
+ description="Override the Vertex AI region (for example, 'us-central1').",
+ ),
+ user_api_key_dict=Depends(user_api_key_auth_websocket),
+):
+ from starlette.websockets import WebSocketState
+ from websockets.asyncio.client import connect
+ from websockets.exceptions import (
+ ConnectionClosedError,
+ ConnectionClosedOK,
+ InvalidStatusCode,
+ )
+
+ _ = user_api_key_dict # passthrough route already authenticated; avoid lint warnings
+
+ await websocket.accept()
+
+ incoming_headers = dict(websocket.headers)
+ vertex_credentials_config = passthrough_endpoint_router.get_vertex_credentials(
+ project_id=vertex_project,
+ location=vertex_location,
+ )
+
+ if vertex_credentials_config is None:
+ # Attempt to load defaults from environment/config if not already initialised
+ passthrough_endpoint_router.set_default_vertex_config()
+ vertex_credentials_config = passthrough_endpoint_router.get_vertex_credentials(
+ project_id=vertex_project,
+ location=vertex_location,
+ )
+
+ resolved_project = vertex_project
+ resolved_location = vertex_location
+ credentials_value: Optional[str] = None
+
+ if vertex_credentials_config is not None:
+ resolved_project = resolved_project or vertex_credentials_config.vertex_project
+ resolved_location = resolved_location or vertex_credentials_config.vertex_location
+ credentials_value = vertex_credentials_config.vertex_credentials
+
+ try:
+ resolved_location = resolved_location or (
+ vertex_live_passthrough_vertex_base.get_default_vertex_location()
+ )
+ if model:
+ resolved_location = vertex_live_passthrough_vertex_base.get_vertex_region(
+ vertex_region=resolved_location,
+ model=model,
+ )
+
+ access_token, resolved_project = await vertex_live_passthrough_vertex_base._ensure_access_token_async(
+ credentials=credentials_value,
+ project_id=resolved_project,
+ custom_llm_provider="vertex_ai_beta",
+ )
+ except Exception:
+ verbose_proxy_logger.exception(
+ "Failed to prepare Vertex AI credentials for live passthrough"
+ )
+ if websocket.client_state != WebSocketState.DISCONNECTED:
+ await websocket.close(code=1011, reason="Vertex AI authentication failed")
+ return
+
+ host_location = resolved_location or vertex_live_passthrough_vertex_base.get_default_vertex_location()
+ host = (
+ "aiplatform.googleapis.com"
+ if host_location == "global"
+ else f"{host_location}-aiplatform.googleapis.com"
+ )
+ service_url = (
+ f"wss://{host}/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent"
+ )
+
+ upstream_headers = {
+ "Authorization": f"Bearer {access_token}",
+ "Content-Type": "application/json",
+ }
+ if resolved_project:
+ upstream_headers["x-goog-user-project"] = resolved_project
+
+ # Forward any custom x-goog-* headers provided by the caller if we haven't overridden them
+ for header_name, header_value in incoming_headers.items():
+ lower_header = header_name.lower()
+ if lower_header.startswith("x-goog-") and header_name not in upstream_headers:
+ upstream_headers[header_name] = header_value
+
+ try:
+ async with connect(
+ service_url,
+ additional_headers=upstream_headers,
+ ) as upstream_ws:
+
+ async def forward_client_to_vertex() -> None:
+ try:
+ while True:
+ message = await websocket.receive()
+ message_type = message.get("type")
+ if message_type == "websocket.disconnect":
+ await upstream_ws.close()
+ break
+
+ text_data = message.get("text")
+ bytes_data = message.get("bytes")
+
+ if text_data is not None:
+ await upstream_ws.send(text_data)
+ elif bytes_data is not None:
+ await upstream_ws.send(bytes_data)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ verbose_proxy_logger.exception(
+ "Vertex AI live passthrough: error forwarding client message"
+ )
+ await upstream_ws.close()
+
+ async def forward_vertex_to_client() -> None:
+ try:
+ async for upstream_message in upstream_ws:
+ if isinstance(upstream_message, bytes):
+ await websocket.send_bytes(upstream_message)
+ else:
+ await websocket.send_text(upstream_message)
+ except (ConnectionClosedOK, ConnectionClosedError):
+ pass
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ verbose_proxy_logger.exception(
+ "Vertex AI live passthrough: error forwarding upstream message"
+ )
+ raise
+
+ tasks = [
+ asyncio.create_task(forward_client_to_vertex()),
+ asyncio.create_task(forward_vertex_to_client()),
+ ]
+
+ done, pending = await asyncio.wait(
+ tasks, return_when=asyncio.FIRST_COMPLETED
+ )
+
+ for task in pending:
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+ for task in done:
+ exception = task.exception()
+ if exception is not None:
+ raise exception
+
+ except InvalidStatusCode as exc:
+ verbose_proxy_logger.exception(
+ "Vertex AI live passthrough: upstream rejected WebSocket connection"
+ )
+ if websocket.client_state != WebSocketState.DISCONNECTED:
+ await websocket.close(
+ code=exc.status_code if hasattr(exc, "status_code") else 1011,
+ reason="Upstream connection rejected",
+ )
+ except Exception:
+ verbose_proxy_logger.exception(
+ "Vertex AI live passthrough: unexpected error while proxying WebSocket"
+ )
+ if websocket.client_state != WebSocketState.DISCONNECTED:
+ await websocket.close(code=1011, reason="Vertex AI passthrough error")
+ finally:
+ if websocket.client_state != WebSocketState.DISCONNECTED:
+ await websocket.close()
+
######################################################################
-from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+# /v1/realtime Endpoints
+
+######################################################################
from litellm import _arealtime