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
VertexAI Search Vector Store - Passthrough endpoint support + Vector store search Cost tracking support (#15824)
Krish Dholakia86524fcaf558
diff --git a/VERTEX_ENV_SETUP.md b/VERTEX_ENV_SETUP.mdnew file mode 100644index 00000000000..93a631c82f1--- /dev/null+++ b/VERTEX_ENV_SETUP.md@@ -0,0 +1,261 @@+# Vertex AI Environment Variables Setup Guide++## Overview++LiteLLM can load Vertex AI credentials from environment variables instead of storing them in config files. This is more secure and easier to manage for local development.++## Environment Variables++LiteLLM looks for these environment variables (in order of precedence):++### 1. **DEFAULT_VERTEXAI_PROJECT** (Required)+Your GCP project ID that has Vertex AI enabled.++```bash+export DEFAULT_VERTEXAI_PROJECT="my-gcp-project-id"+```++### 2. **DEFAULT_VERTEXAI_LOCATION** (Required)+The region/location for Vertex AI services.++```bash+export DEFAULT_VERTEXAI_LOCATION="global"+# or+export DEFAULT_VERTEXAI_LOCATION="us-central1"+```++Common locations:+- `global` - For Discovery Engine and global services+- `us-central1` - US Central region+- `us-east1` - US East region+- `europe-west1` - Europe West region+- `asia-southeast1` - Asia Southeast region++### 3. **DEFAULT_GOOGLE_APPLICATION_CREDENTIALS** (Required)+Path to your service account JSON key file.++```bash+export DEFAULT_GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"+```++### 4. **GOOGLE_APPLICATION_CREDENTIALS** (Fallback)+Standard Google Cloud environment variable (used as fallback).++```bash+export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"+```++## Quick Setup++### Option 1: Interactive Script++```bash+chmod +x setup_vertex_env.sh+source setup_vertex_env.sh+```++### Option 2: Manual Setup++1. **Set environment variables** (for current session):++```bash+export DEFAULT_VERTEXAI_PROJECT="your-project-id"+export DEFAULT_VERTEXAI_LOCATION="global"+export DEFAULT_GOOGLE_APPLICATION_CREDENTIALS="$HOME/.gcp/service-account.json"+export GOOGLE_APPLICATION_CREDENTIALS="$HOME/.gcp/service-account.json"+```++2. **Make them persistent** (add to `~/.zshrc` or `~/.bashrc`):++```bash+echo 'export DEFAULT_VERTEXAI_PROJECT="your-project-id"' >> ~/.zshrc+echo 'export DEFAULT_VERTEXAI_LOCATION="global"' >> ~/.zshrc+echo 'export DEFAULT_GOOGLE_APPLICATION_CREDENTIALS="$HOME/.gcp/service-account.json"' >> ~/.zshrc+echo 'export GOOGLE_APPLICATION_CREDENTIALS="$HOME/.gcp/service-account.json"' >> ~/.zshrc+```++3. **Reload your shell**:++```bash+source ~/.zshrc+```++## Service Account Setup++### 1. Create a Service Account++```bash+gcloud iam service-accounts create litellm-vertex-sa \+ --display-name="LiteLLM Vertex AI Service Account"+```++### 2. Grant Necessary Permissions++For Discovery Engine (vector stores):+```bash+gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \+ --member="serviceAccount:litellm-vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com" \+ --role="roles/discoveryengine.viewer"++gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \+ --member="serviceAccount:litellm-vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com" \+ --role="roles/discoveryengine.dataStoreEditor"+```++For general Vertex AI:+```bash+gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \+ --member="serviceAccount:litellm-vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com" \+ --role="roles/aiplatform.user"+```++### 3. Create and Download Key++```bash+gcloud iam service-accounts keys create ~/service-account-key.json \+ --iam-account=litellm-vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com+```++## Verify Setup++### Check Environment Variables++```bash+python3 << 'EOF'+import os+print("✓ Environment Variables:")+print(f" DEFAULT_VERTEXAI_PROJECT: {os.getenv('DEFAULT_VERTEXAI_PROJECT')}")+print(f" DEFAULT_VERTEXAI_LOCATION: {os.getenv('DEFAULT_VERTEXAI_LOCATION')}")+print(f" DEFAULT_GOOGLE_APPLICATION_CREDENTIALS: {os.getenv('DEFAULT_GOOGLE_APPLICATION_CREDENTIALS')}")+print(f" GOOGLE_APPLICATION_CREDENTIALS: {os.getenv('GOOGLE_APPLICATION_CREDENTIALS')}")++# Check if credentials file exists+creds_path = os.getenv('DEFAULT_GOOGLE_APPLICATION_CREDENTIALS')+if creds_path and os.path.exists(creds_path):+ print(f"\n✅ Credentials file found at: {creds_path}")+else:+ print(f"\n❌ Credentials file NOT found at: {creds_path}")+EOF+```++### Test Authentication++```bash+python3 << 'EOF'+import os+import json+from google.oauth2 import service_account+from google.auth.transport.requests import Request++creds_path = os.getenv('DEFAULT_GOOGLE_APPLICATION_CREDENTIALS')+project = os.getenv('DEFAULT_VERTEXAI_PROJECT')++try:+ # Load credentials+ credentials = service_account.Credentials.from_service_account_file(+ creds_path,+ scopes=['https://www.googleapis.com/auth/cloud-platform']+ )++ # Get access token+ credentials.refresh(Request())++ print("✅ Authentication successful!")+ print(f" Project: {project}")+ print(f" Service Account: {credentials.service_account_email}")+ print(f" Token expiry: {credentials.expiry}")++except Exception as e:+ print(f"❌ Authentication failed: {e}")+EOF+```++## Using with Vector Store Passthrough++Once your environment is set up, the vector store passthrough will work in two ways:++### 1. **With Vector Store Config** (Priority 1)+If you have a vector store configured with its own credentials in `litellm_params`, those will be used first:++```yaml+vector_stores:+ - vector_store_id: test-store-123+ custom_llm_provider: vertex_ai+ litellm_params:+ vertex_project: "specific-project"+ vertex_location: "us-central1"+ vertex_credentials: "{...}" # Inline credentials+```++### 2. **Environment Variables Fallback** (Priority 2)+If the vector store doesn't have explicit credentials, it falls back to your environment variables:++```yaml+vector_stores:+ - vector_store_id: test-store-123+ custom_llm_provider: vertex_ai+ # No litellm_params - will use DEFAULT_VERTEXAI_PROJECT, DEFAULT_VERTEXAI_LOCATION, etc.+```++### 3. **Model Config Fallback** (Priority 3)+If neither above work, it looks for credentials in your model configuration.++## Troubleshooting++### "No credentials found"++Check that all environment variables are set:+```bash+env | grep -E "(DEFAULT_VERTEXAI|GOOGLE_APPLICATION_CREDENTIALS)"+```++### "Authentication failed"++Verify your service account key is valid:+```bash+cat $DEFAULT_GOOGLE_APPLICATION_CREDENTIALS | python3 -m json.tool+```++### "Permission denied"++Ensure your service account has the necessary roles:+```bash+gcloud projects get-iam-policy YOUR_PROJECT_ID \+ --flatten="bindings[].members" \+ --filter="bindings.members:serviceAccount:litellm-vertex-sa@*"+```++### Different Credentials for Different Projects++If you need to use different credentials for different vector stores, configure them explicitly in the vector store config rather than relying on environment variables.++## Start LiteLLM Proxy++Once your environment is configured:++```bash+# Start the proxy (it will automatically load env vars)+litellm --config proxy_server_config.yaml++# Or with debug logging+export LITELLM_LOG=DEBUG+litellm --config proxy_server_config.yaml+```++You should see logs like:+```+Vertex: Loading vertex credentials from /path/to/service-account.json+Found credentials for vertex_ai_default+```++## Test the Endpoint++```bash+curl -X POST http://0.0.0.0:4000/vertex_ai/discovery/v1/projects/fake-project/locations/global/dataStores/test-store-123/servingConfigs/default_config:search \+ -H 'Authorization: Bearer YOUR_LITELLM_API_KEY' \+ -H 'Content-Type: application/json' \+ -d '{"query": "test query"}'+```++The proxy will use your environment credentials to make the request to Vertex AI!+diff --git a/docs/my-website/docs/pass_through/vertex_ai.md b/docs/my-website/docs/pass_through/vertex_ai.mdindex 77095667113..2efef60070d 100644--- a/docs/my-website/docs/pass_through/vertex_ai.md+++ b/docs/my-website/docs/pass_through/vertex_ai.md@@ -18,8 +18,8 @@ Pass-through endpoints for Vertex AI - call provider-specific endpoint, in nativLiteLLM 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`)+2. `/vertex_ai/discovery` → routes to [`https://discoveryengine.googleapis.com`](https://discoveryengine.googleapis.com/) - [See Search Datastores Guide](./vertex_ai_search_datastores.md)+3. `/vertex_ai/live` → upgrades to the Vertex AI Live API WebSocket (`google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent`) - [See Live WebSocket Guide](./vertex_ai_live_websocket.md)## How to usediff --git a/docs/my-website/docs/pass_through/vertex_ai_search_datastores.md b/docs/my-website/docs/pass_through/vertex_ai_search_datastores.mdnew file mode 100644index 00000000000..90a85312fab--- /dev/null+++ b/docs/my-website/docs/pass_through/vertex_ai_search_datastores.md@@ -0,0 +1,122 @@+# Vertex AI Search Datastores++Call Vertex AI Discovery Engine Search API through LiteLLM.++Provider Doc: https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/projects.locations.dataStores.servingConfigs/search++## What you get++- Reference datastores by ID. LiteLLM finds the credentials.+- No project/location in every request.+- Configure credentials once, use everywhere.+- Cost tracking works automatically.++## Quick Start++**Step 1. Set credentials**++```bash+export DEFAULT_VERTEXAI_PROJECT="your-project-id"+export DEFAULT_VERTEXAI_LOCATION="us-central1"+export DEFAULT_GOOGLE_APPLICATION_CREDENTIALS="/path/to/credentials.json"+```++**Step 2. Start proxy**++```bash+litellm+```++**Step 3. Search your datastore**++```bash+curl -X POST \+ "http://localhost:4000/vertex_ai/discovery/v1/projects/my-project/locations/global/collections/default_collection/dataStores/my-datastore/servingConfigs/default_config:search" \+ -H "Content-Type: application/json" \+ -H "x-litellm-api-key: Bearer sk-1234" \+ -d '{+ "query": "How do I authenticate?",+ "pageSize": 10+ }'+```++## Managed Vector Stores (Recommended)++Register your datastore once. Reference it by ID.++**In config.yaml:**++```yaml+vector_store_registry:+ - vector_store_name: "vertex-ai-litellm-website-knowledgebase"+ litellm_params:+ vector_store_id: "litellm-docs_1761094140318"+ custom_llm_provider: "vertex_ai/search_api"+ vertex_app_id: "test-litellm-app_1761094730750"+ vertex_project: "test-vector-store-db"+ vertex_location: "global"+ vector_store_description: "Vertex AI vector store for the Litellm website knowledgebase"+ vector_store_metadata:+ source: "https://www.litellm.com/docs"+```++**How it works:**++LiteLLM sees `dataStores/my-datastore` in your URL. It looks up the vector store. Uses the right project and credentials automatically.++## Endpoint++`{PROXY_BASE_URL}/vertex_ai/discovery/{endpoint:path}`++Routes to `https://discoveryengine.googleapis.com`++## Examples++### Basic Search++```bash+curl -X POST \+ "http://localhost:4000/vertex_ai/discovery/v1/projects/my-project/locations/global/collections/default_collection/dataStores/my-datastore/servingConfigs/default_config:search" \+ -H "Content-Type: application/json" \+ -H "x-litellm-api-key: Bearer sk-1234" \+ -d '{+ "query": "pricing",+ "pageSize": 10+ }'+```++### Search with Filters++```bash+curl -X POST \+ "http://localhost:4000/vertex_ai/discovery/v1/projects/my-project/locations/global/collections/default_collection/dataStores/my-datastore/servingConfigs/default_config:search" \+ -H "Content-Type: application/json" \+ -H "x-litellm-api-key: Bearer sk-1234" \+ -d '{+ "query": "tutorials",+ "pageSize": 20,+ "filter": "category = \"beginner\"",+ "spellCorrectionSpec": {"mode": "AUTO"}+ }'+```++### Python++```python+import requests++url = "http://localhost:4000/vertex_ai/discovery/v1/projects/my-project/locations/global/collections/default_collection/dataStores/my-datastore/servingConfigs/default_config:search"++response = requests.post(url,+ headers={+ "Content-Type": "application/json",+ "x-litellm-api-key": "Bearer sk-1234"+ },+ json={"query": "pricing", "pageSize": 10}+)++for result in response.json().get("results", []):+ data = result["document"]["derivedStructData"]+ print(f"{data['title']}: {data['link']}")+```+diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex 6811aeada1d..e2753932f55 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -374,6 +374,7 @@ const sidebars = {items: ["pass_through/vertex_ai","pass_through/vertex_ai_live_websocket",+ "pass_through/vertex_ai_search_datastores",]},"pass_through/vllm",diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex d5910a3af86..9935eed292e 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -82,6 +82,7 @@ from litellm.types.utils import (ModelInfo,StandardBuiltInToolsParams,Usage,+ VectorStoreSearchResponse,)from litellm.utils import (CallTypes,@@ -174,6 +175,7 @@ def cost_per_token( # noqa: PLR0915Returns:tuple: A tuple containing the cost in USD dollars for prompt tokens and completion tokens, respectively."""+if model is None:raise Exception("Invalid arg. Model cannot be none.")@@ -295,6 +297,12 @@ def cost_per_token( # noqa: PLR0915custom_llm_provider=custom_llm_provider,billed_units=rerank_billed_units,)+ elif call_type == "avector_store_search" or call_type == "vector_store_search":+ return vector_store_search_cost(+ model=model,+ custom_llm_provider=custom_llm_provider,+ response=cast(VectorStoreSearchResponse, response),+ )elif call_type == "ocr" or call_type == "aocr":return ocr_cost(model=model,@@ -351,7 +359,9 @@ def cost_per_token( # noqa: PLR0915elif custom_llm_provider == "bedrock":return bedrock_cost_per_token(model=model, usage=usage_block)elif custom_llm_provider == "openai":- return openai_cost_per_token(model=model, usage=usage_block, service_tier=service_tier)+ return openai_cost_per_token(+ model=model, usage=usage_block, service_tier=service_tier+ )elif custom_llm_provider == "databricks":return databricks_cost_per_token(model=model, usage=usage_block)elif custom_llm_provider == "fireworks_ai":@@ -374,6 +384,7 @@ def cost_per_token( # noqa: PLR0915from litellm.llms.dashscope.cost_calculator import (cost_per_token as dashscope_cost_per_token,)+return dashscope_cost_per_token(model=model, usage=usage_block)else:model_info = _cached_get_model_info_helper(@@ -613,30 +624,30 @@ def _apply_cost_discount() -> Tuple[float, float, float]:"""Apply provider-specific cost discount from module-level config.-+Args:base_cost: The base cost before discountcustom_llm_provider: The LLM provider name-+Returns:Tuple of (final_cost, discount_percent, discount_amount)"""original_cost = base_costdiscount_percent = 0.0discount_amount = 0.0-+if custom_llm_provider and custom_llm_provider in litellm.cost_discount_config:discount_percent = litellm.cost_discount_config[custom_llm_provider]discount_amount = original_cost * discount_percentfinal_cost = original_cost - discount_amount-+verbose_logger.debug(f"Applied {discount_percent*100}% discount to {custom_llm_provider}: "f"${original_cost:.6f} -> ${final_cost:.6f} (saved ${discount_amount:.6f})")-+return final_cost, discount_percent, discount_amount-+return base_cost, discount_percent, discount_amount@@ -652,7 +663,7 @@ def _store_cost_breakdown_in_logging_obj() -> None:"""Helper function to store cost breakdown in the logging object.-+Args:litellm_logging_obj: The logging object to store breakdown inprompt_tokens_cost_usd_dollar: Cost of input tokens@@ -663,9 +674,9 @@ def _store_cost_breakdown_in_logging_obj(discount_percent: Discount percentage applied (0.05 = 5%)discount_amount: Discount amount in USD"""- if (litellm_logging_obj is None):+ if litellm_logging_obj is None:return-+try:# Store the cost breakdownlitellm_logging_obj.set_cost_breakdown(@@ -677,7 +688,7 @@ def _store_cost_breakdown_in_logging_obj(discount_percent=discount_percent,discount_amount=discount_amount,)-+except Exception as breakdown_error:verbose_logger.debug(f"Error storing cost breakdown: {str(breakdown_error)}")# Don't fail the main cost calculation if breakdown storage fails@@ -763,7 +774,7 @@ def completion_cost( # noqa: PLR0915completion_response=completion_response)rerank_billed_units: Optional[RerankBilledUnits] = None-+# Extract service_tier from optional_params if not provided directlyif service_tier is None and optional_params is not None:service_tier = optional_params.get("service_tier")@@ -792,9 +803,9 @@ def completion_cost( # noqa: PLR0915or isinstance(completion_response, dict)): # tts returns a custom classif isinstance(completion_response, dict):- usage_obj: Optional[- Union[dict, Usage]- ] = completion_response.get("usage", {})+ usage_obj: Optional[Union[dict, Usage]] = (+ completion_response.get("usage", {})+ )else:usage_obj = getattr(completion_response, "usage", {})if isinstance(usage_obj, BaseModel) and not _is_known_usage_objects(@@ -1063,14 +1074,14 @@ def completion_cost( # noqa: PLR0915))_final_cost += cost_for_built_in_tools-+# Apply discount from module-level config if configuredoriginal_cost = _final_cost_final_cost, discount_percent, discount_amount = _apply_cost_discount(base_cost=_final_cost,custom_llm_provider=custom_llm_provider,)-+# Store cost breakdown in logging object if available_store_cost_breakdown_in_logging_obj(litellm_logging_obj=litellm_logging_obj,@@ -1082,7 +1093,7 @@ def completion_cost( # noqa: PLR0915discount_percent=discount_percent,discount_amount=discount_amount,)-+return _final_costexcept Exception as e:verbose_logger.debug(@@ -1231,15 +1242,17 @@ def ocr_cost(# validate it's an OCR response#########################################################if response is None or not isinstance(response, OCRResponse):- raise ValueError(f"response must be of type OCRResponse got type={type(response)}")-+ raise ValueError(+ f"response must be of type OCRResponse got type={type(response)}"+ )+if response.usage_info is None:raise ValueError("OCR response usage_info is None")-+pages_processed = response.usage_info.pages_processedif pages_processed is None:raise ValueError("OCR response pages_processed is None")-+try:model_info: Optional[ModelInfo] = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider@@ -1250,11 +1263,45 @@ def ocr_cost(ocr_cost_per_page: float = 0.0if model_info is not None:ocr_cost_per_page = model_info.get("ocr_cost_per_page") or 0.0-+total_ocr_processing_cost: float = ocr_cost_per_page * pages_processedreturn total_ocr_processing_cost, 0.0+def vector_store_search_cost(+ model: Optional[str],+ custom_llm_provider: str,+ response: VectorStoreSearchResponse,+) -> Tuple[float, float]:+ """+ Returns+ - float or None: cost of vector store search+ """+ api_type: Optional[str] = None+ if custom_llm_provider is None:+ custom_llm_provider = "openai"++ if model is not None and "/" in model:+ api_type, custom_llm_provider, _, _ = litellm.get_llm_provider(+ model=model,+ )++ config = ProviderConfigManager.get_provider_vector_stores_config(+ provider=LlmProviders(custom_llm_provider),+ api_type=api_type,+ )++ if config is None:+ verbose_logger.debug(+ f"Vector store search is not supported for {custom_llm_provider}"+ )+ return 0.0, 0.0++ return config.calculate_vector_store_cost(+ response=response,+ )++def rerank_cost(model: str,custom_llm_provider: Optional[str],diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex f4958527252..e4e67502390 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -1212,8 +1212,6 @@ class Logging(LiteLLMLoggingBaseClass):if discount_amount is not None:self.cost_breakdown["discount_amount"] = discount_amount--def _response_cost_calculator(self,result: Union[@@ -1307,6 +1305,7 @@ class Logging(LiteLLMLoggingBaseClass):return Nonetry:+response_cost = litellm.response_cost_calculator(**response_cost_calculator_kwargs)@@ -1620,6 +1619,8 @@ class Logging(LiteLLMLoggingBaseClass):or isinstance(logging_result, OpenAIFileObject)or isinstance(logging_result, LiteLLMRealtimeStreamLoggingObject)or isinstance(logging_result, OpenAIModerationResponse)+ or isinstance(logging_result, dict)+ and logging_result.get("object") == "vector_store.search_results.page"or isinstance(logging_result, VideoObject)or (self.call_type == CallTypes.call_mcp_tool.value)):@@ -3110,7 +3111,7 @@ def _get_masked_values((v[: unmasked_length // 2]+ "*" * number_of_asterisks- + v[-unmasked_length // 2:]+ + v[-unmasked_length // 2 :])if (isinstance(v, str)@@ -3121,7 +3122,7 @@ def _get_masked_values((v[: unmasked_length // 2]+ "*" * (len(v) - unmasked_length)- + v[-unmasked_length // 2:]+ + v[-unmasked_length // 2 :])if (isinstance(v, str) and len(v) > unmasked_length)else ("*****" if isinstance(v, str) else v)@@ -4506,7 +4507,6 @@ def _get_status_fields(# Set LLM API statusllm_api_status: StandardLoggingPayloadStatus = status-########################################################## Map - guardrail_information.guardrail_status to guardrail_status#########################################################diff --git a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py b/litellm/litellm_core_utils/llm_response_utils/response_metadata.pyindex c5ef7237628..ccfdcfeb2ed 100644--- a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py+++ b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py@@ -85,7 +85,7 @@ class ResponseMetadata:# Set total response time if supportedif self.supports_response_time:self.result._response_ms = total_response_time_ms-+########################################################## 1. Add _response_ms total duration#########################################################@@ -106,12 +106,21 @@ class ResponseMetadata:"litellm_overhead_time_ms": overhead_ms,})-+########################################################## 3. Add duration for reading from cache# In this case overhead from litellm is the difference between the cache read duration and the total response time#########################################################- if logging_obj.caching_details is not None and logging_obj.caching_details.get("cache_hit") is True and (cache_duration_ms := logging_obj.caching_details.get("cache_duration_ms")) is not None:+ if (+ logging_obj.caching_details is not None+ and logging_obj.caching_details.get("cache_hit") is True+ and (+ cache_duration_ms := logging_obj.caching_details.get(+ "cache_duration_ms"+ )+ )+ is not None+ ):overhead_ms = total_response_time_ms - cache_duration_msself._update_hidden_params({diff --git a/litellm/llms/base_llm/vector_store/transformation.py b/litellm/llms/base_llm/vector_store/transformation.pyindex b50fd957587..9d7ba7d61a8 100644--- a/litellm/llms/base_llm/vector_store/transformation.py+++ b/litellm/llms/base_llm/vector_store/transformation.py@@ -22,6 +22,7 @@ else:LiteLLMLoggingObj = AnyBaseLLMException = Any+class BaseVectorStoreConfig:@abstractmethoddef transform_search_vector_store_request(@@ -36,7 +37,9 @@ class BaseVectorStoreConfig:pass@abstractmethod- def transform_search_vector_store_response(self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj) -> VectorStoreSearchResponse:+ def transform_search_vector_store_response(+ self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj+ ) -> VectorStoreSearchResponse:pass@abstractmethod@@ -48,7 +51,9 @@ class BaseVectorStoreConfig:pass@abstractmethod- def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse:+ def transform_create_vector_store_response(+ self, response: httpx.Response+ ) -> VectorStoreCreateResponse:pass@abstractmethod@@ -73,7 +78,6 @@ class BaseVectorStoreConfig: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]@@ -102,3 +106,8 @@ class BaseVectorStoreConfig:"""return headers, None+ def calculate_vector_store_cost(+ self,+ response: VectorStoreSearchResponse,+ ) -> Tuple[float, float]:+ return 0.0, 0.0diff --git a/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py b/litellm/llms/vertex_ai/vector_stores/search_api/transformation.pyindex 3d13c99840c..31837146485 100644--- a/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py+++ b/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Unionimport httpx+from litellm import get_model_infofrom litellm.llms.base_llm.vector_store.transformation import BaseVectorStoreConfigfrom litellm.llms.vertex_ai.vertex_llm_base import VertexBasefrom litellm.types.router import GenericLiteLLMParams@@ -70,7 +71,7 @@ class VertexSearchAPIVectorStoreConfig(BaseVectorStoreConfig, VertexBase):"""vertex_location = self.get_vertex_ai_location(litellm_params)vertex_project = self.get_vertex_ai_project(litellm_params)- engine_id = litellm_params.get("vector_store_id")+ engine_id = litellm_params.get("vertex_app_id")collection_id = (litellm_params.get("vertex_collection_id") or "default_collection")@@ -239,3 +240,14 @@ class VertexSearchAPIVectorStoreConfig(BaseVectorStoreConfig, VertexBase):self, response: httpx.Response) -> VectorStoreCreateResponse:raise NotImplementedError++ def calculate_vector_store_cost(+ self,+ response: VectorStoreSearchResponse,+ ) -> Tuple[float, float]:+ model_info = get_model_info(+ model="vertex_ai/search_api",+ )++ input_cost_per_query = model_info.get("input_cost_per_query") or 0.0+ return input_cost_per_query, 0.0diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.pyindex 6d194d41add..8f7c846bd7d 100644--- a/litellm/llms/vertex_ai/vertex_llm_base.py+++ b/litellm/llms/vertex_ai/vertex_llm_base.py@@ -155,6 +155,7 @@ class VertexBase:)def _credentials_from_default_auth(self, scopes):+import google.auth as google_authreturn google_auth.default(scopes=scopes)diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex a1f3a190251..0c9a5349ab3 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -23922,6 +23922,11 @@"supports_vision": true,"supports_web_search": true},+ "vertex_ai/search_api": {+ "input_cost_per_query": 1.5e-03,+ "litellm_provider": "vertex_ai",+ "mode": "vector_store"+ },"openai/sora-2": {"litellm_provider": "openai","mode": "video_generation",diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.pyindex 567905e62e1..c2faa756774 100644--- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py+++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py@@ -8,7 +8,7 @@ Use litellm with Anthropic SDK, Vertex AI SDK, Cohere SDK, etc.import jsonimport os-from typing import Any, Optional, Union, cast+from typing import Any, Optional, Tuple, Union, castimport httpxfrom fastapi import APIRouter, Depends, HTTPException, Request, Response, WebSocket@@ -498,26 +498,26 @@ BEDROCK_STREAMING_ACTIONS = {"invoke-with-response-stream", "converse-stream"}def _extract_model_from_bedrock_endpoint(endpoint: str) -> str:"""Extract model name from Bedrock endpoint path.-+Handles model names with slashes (e.g., aws/anthropic/bedrock-claude-3-5-sonnet-v1)by finding the action in the endpoint and extracting everything between "model" and the action.-+Args:endpoint: The endpoint path (e.g., "/model/aws/anthropic/model-name/invoke")-+Returns:The extracted model name (e.g., "aws/anthropic/model-name")-+Raises:ValueError: If model cannot be extracted from endpoint"""try:endpoint_parts = endpoint.split("/")-+if "application-inference-profile" in endpoint:# Format: model/application-inference-profile/{profile-id}/{action}return "/".join(endpoint_parts[1:3])-+# Format: model/{modelId}/{action}# Find the index of the action in the endpoint partsaction_index = None@@ -525,14 +525,14 @@ def _extract_model_from_bedrock_endpoint(endpoint: str) -> str:if part in BEDROCK_ENDPOINT_ACTIONS:action_index = idxbreak-+if action_index is not None and action_index > 1:# Join all parts between "model" and the actionreturn "/".join(endpoint_parts[1:action_index])-+# Fallback to taking everything after "model" if no action foundreturn "/".join(endpoint_parts[1:])-+except Exception as e:raise ValueError(f"Model missing from endpoint. Expected format: /model/{{modelId}}/{{action}}. Got: {endpoint}"@@ -559,10 +559,10 @@ async def handle_bedrock_passthrough_router_model() -> Union[Response, StreamingResponse]:"""Handle Bedrock passthrough for router models (models defined in config.yaml).-+Uses the same common processing path as non-router models to ensuremetadata and hooks are properly initialized.-+Args:model: The router model name (e.g., "aws/anthropic/bedrock-claude-3-5-sonnet-v1")endpoint: The Bedrock endpoint path (e.g., "/model/{modelId}/invoke")@@ -571,7 +571,7 @@ async def handle_bedrock_passthrough_router_model(llm_router: The LiteLLM router instanceuser_api_key_dict: The user API key authentication dictionary(additional args for common processing)-+Returns:Response or StreamingResponse depending on endpoint type"""@@ -581,22 +581,22 @@ async def handle_bedrock_passthrough_router_model(# Detect streaming based on endpointis_streaming = any(action in endpoint for action in BEDROCK_STREAMING_ACTIONS)-+verbose_proxy_logger.debug(f"Bedrock router passthrough: model='{model}', endpoint='{endpoint}', streaming={is_streaming}")-+# Use the common processing path (same as non-router models)# This ensures all metadata, hooks, and logging are properly initializeddata: Dict[str, Any] = {}base_llm_response_processor = ProxyBaseLLMRequestProcessing(data=data)-+data["model"] = modeldata["method"] = request.methoddata["endpoint"] = endpointdata["data"] = request_bodydata["custom_llm_provider"] = "bedrock"-+# Use the common passthrough processing to handle metadata and hooks# This also handles all response formatting (streaming/non-streaming) and exceptionstry:@@ -705,9 +705,9 @@ async def bedrock_llm_proxy_route():"""Handles Bedrock LLM API calls.-+Supports both direct Bedrock models and router models from config.yaml.-+Endpoints:- /model/{modelId}/invoke- /model/{modelId}/invoke-with-response-stream@@ -782,10 +782,10 @@ async def bedrock_llm_proxy_route(verbose_proxy_logger.debug(f"Bedrock passthrough: Using direct Bedrock model '{model}' for endpoint '{endpoint}'")-+data: Dict[str, Any] = {}base_llm_response_processor = ProxyBaseLLMRequestProcessing(data=data)-+data["method"] = request.methoddata["endpoint"] = endpointdata["data"] = request_body@@ -1161,18 +1161,177 @@ def get_vertex_pass_through_handler(raise ValueError(f"Invalid call type: {call_type}")+def _override_vertex_params_from_router_credentials(+ router_credentials: Optional[Any],+ vertex_project: Optional[str],+ vertex_location: Optional[str],+) -> tuple[Optional[str], Optional[str]]:+ """+ Override vertex_project and vertex_location with values from router_credentials if available.++ Args:+ router_credentials: Optional vector store credentials from registry (LiteLLM_ManagedVectorStore)+ vertex_project: Current vertex project ID (from URL)+ vertex_location: Current vertex location (from URL)++ Returns:+ Tuple of (vertex_project, vertex_location) with overridden values if applicable+ """+ if router_credentials is None:+ return vertex_project, vertex_location++ verbose_proxy_logger.debug(+ "Using vector store credentials to override vertex project and location"+ )++ litellm_params = router_credentials.get("litellm_params", {})+ if not litellm_params:+ verbose_proxy_logger.warning(+ "Vector store credentials found but litellm_params is empty"+ )+ return vertex_project, vertex_location++ # Extract vertex_project and vertex_location from litellm_params+ vector_store_project = litellm_params.get("vertex_project")+ vector_store_location = litellm_params.get("vertex_location")++ if vector_store_project:+ verbose_proxy_logger.debug(+ "Overriding vertex_project from URL (%s) with vector store value: %s",+ vertex_project,+ vector_store_project,+ )+ vertex_project = vector_store_project+ else:+ verbose_proxy_logger.warning(+ "Vector store credentials found but missing vertex_project in litellm_params"+ )++ if vector_store_location:+ verbose_proxy_logger.debug(+ "Overriding vertex_location from URL (%s) with vector store value: %s",+ vertex_location,+ vector_store_location,+ )+ vertex_location = vector_store_location+ else:+ verbose_proxy_logger.warning(+ "Vector store credentials found but missing vertex_location in litellm_params"+ )++ return vertex_project, vertex_location+++async def _prepare_vertex_auth_headers(+ request: Request,+ vertex_credentials: Optional[Any],+ router_credentials: Optional[Any],+ vertex_project: Optional[str],+ vertex_location: Optional[str],+ base_target_url: Optional[str],+ get_vertex_pass_through_handler: BaseVertexAIPassThroughHandler,+) -> Tuple[dict, Optional[str], bool, Optional[str], Optional[str]]:+ """+ Prepare authentication headers for Vertex AI pass-through requests.++ Args:+ request: FastAPI request object+ vertex_credentials: Vertex AI credentials from config+ router_credentials: Optional vector store credentials from registry+ vertex_project: Vertex project ID+ vertex_location: Vertex location+ base_target_url: Base URL for the Vertex AI service+ get_vertex_pass_through_handler: Handler for the specific Vertex AI service++ Returns:+ Tuple containing:+ - headers: dict - Authentication headers to use+ - base_target_url: Optional[str] - Updated base target URL+ - headers_passed_through: bool - Whether headers were passed through from request+ - vertex_project: Optional[str] - Updated vertex project ID+ - vertex_location: Optional[str] - Updated vertex location+ """+ vertex_llm_base = VertexBase()+ headers_passed_through = False++ # Use headers from the incoming request if no vertex credentials are found+ if (+ vertex_credentials is None or vertex_credentials.vertex_project is None+ ) and router_credentials is None:+ headers = dict(request.headers) or {}+ headers_passed_through = True+ verbose_proxy_logger.debug(+ "default_vertex_config not set, incoming request headers %s", headers+ )+ headers.pop("content-length", None)+ headers.pop("host", None)+ else:+ if router_credentials is not None:+ vertex_credentials_str = None+ elif vertex_credentials is not None:+ vertex_project = vertex_credentials.vertex_project+ vertex_location = vertex_credentials.vertex_location+ vertex_credentials_str = vertex_credentials.vertex_credentials+ else:+ raise ValueError("No vertex credentials found")++ _auth_header, vertex_project = await vertex_llm_base._ensure_access_token_async(+ credentials=vertex_credentials_str,+ project_id=vertex_project,+ custom_llm_provider="vertex_ai_beta",+ )++ auth_header, _ = vertex_llm_base._get_token_and_url(+ model="",+ auth_header=_auth_header,+ gemini_api_key=None,+ vertex_credentials=vertex_credentials_str,+ vertex_project=vertex_project,+ vertex_location=vertex_location,+ stream=False,+ custom_llm_provider="vertex_ai_beta",+ api_base="",+ )++ headers = {+ "Authorization": f"Bearer {auth_header}",+ }++ if base_target_url is not None:+ base_target_url = get_vertex_pass_through_handler.update_base_target_url_with_credential_location(+ base_target_url, vertex_location+ )++ return (+ headers,+ base_target_url,+ headers_passed_through,+ vertex_project,+ vertex_location,+ )++async def _base_vertex_proxy_route(endpoint: str,request: Request,fastapi_response: Response,get_vertex_pass_through_handler: BaseVertexAIPassThroughHandler,user_api_key_dict: Optional[UserAPIKeyAuth] = None,+ router_credentials: Optional[Any] = None,):"""Base function for Vertex AI passthrough routes.Handles common logic for all Vertex AI services.Default base_target_url is `https://{vertex_location}-aiplatform.googleapis.com/`++ Args:+ endpoint: The endpoint path+ request: FastAPI request object+ fastapi_response: FastAPI response object+ get_vertex_pass_through_handler: Handler for the specific Vertex AI service+ user_api_key_dict: User API key authentication dict+ router_credentials: Optional vector store credentials from registry (LiteLLM_ManagedVectorStore)"""from litellm.llms.vertex_ai.common_utils import (construct_target_url,@@ -1198,6 +1357,14 @@ async def _base_vertex_proxy_route(vertex_project: Optional[str] = get_vertex_project_id_from_url(endpoint)vertex_location: Optional[str] = get_vertex_location_from_url(endpoint)++ # Override with vector store credentials if available+ vertex_project, vertex_location = _override_vertex_params_from_router_credentials(+ router_credentials=router_credentials,+ vertex_project=vertex_project,+ vertex_location=vertex_location,+ )+vertex_credentials = passthrough_endpoint_router.get_vertex_credentials(project_id=vertex_project,location=vertex_location,@@ -1207,46 +1374,22 @@ async def _base_vertex_proxy_route(vertex_location)- headers_passed_through = False- # Use headers from the incoming request if no vertex credentials are found- if vertex_credentials is None or vertex_credentials.vertex_project is None:- headers = dict(request.headers) or {}- headers_passed_through = True- verbose_proxy_logger.debug(- "default_vertex_config not set, incoming request headers %s", headers- )- headers.pop("content-length", None)- headers.pop("host", None)- else:- vertex_project = vertex_credentials.vertex_project- vertex_location = vertex_credentials.vertex_location- vertex_credentials_str = vertex_credentials.vertex_credentials-- _auth_header, vertex_project = await vertex_llm_base._ensure_access_token_async(- credentials=vertex_credentials_str,- project_id=vertex_project,- custom_llm_provider="vertex_ai_beta",- )-- auth_header, _ = vertex_llm_base._get_token_and_url(- model="",- auth_header=_auth_header,- gemini_api_key=None,- vertex_credentials=vertex_credentials_str,- vertex_project=vertex_project,- vertex_location=vertex_location,- stream=False,- custom_llm_provider="vertex_ai_beta",- api_base="",- )-- headers = {- "Authorization": f"Bearer {auth_header}",- }-- base_target_url = get_vertex_pass_through_handler.update_base_target_url_with_credential_location(- base_target_url, vertex_location- )+ # Prepare authentication headers+ (+ headers,+ base_target_url,+ headers_passed_through,+ vertex_project,+ vertex_location,+ ) = await _prepare_vertex_auth_headers( # type: ignore+ request=request,+ vertex_credentials=vertex_credentials,+ router_credentials=router_credentials,+ vertex_project=vertex_project,+ vertex_location=vertex_location,+ base_target_url=base_target_url,+ get_vertex_pass_through_handler=get_vertex_pass_through_handler,+ )if base_target_url is None:base_target_url = get_vertex_base_url(vertex_location)@@ -1314,6 +1457,36 @@ async def vertex_discovery_proxy_route(Target url: `https://discoveryengine.googleapis.com`"""+ import re++ from litellm.types.vector_stores import LiteLLM_ManagedVectorStore++ # Extract vector store ID from endpoint if present (e.g., dataStores/test-litellm-app_1761094730750)+ vector_store_credentials: Optional[LiteLLM_ManagedVectorStore] = None+ vector_store_id_match = re.search(r"dataStores/([^/]+)", endpoint)++ if vector_store_id_match:+ vector_store_id = vector_store_id_match.group(1)+ verbose_proxy_logger.debug(+ "Extracted vector store ID from endpoint: %s", vector_store_id+ )++ # Retrieve vector store credentials from the registry+ vector_store_credentials = (+ passthrough_endpoint_router.get_vector_store_credentials(+ vector_store_id=vector_store_id+ )+ )++ if vector_store_credentials:+ verbose_proxy_logger.debug(+ "Found vector store credentials for ID: %s", vector_store_id+ )+ else:+ verbose_proxy_logger.warning(+ "Vector store ID %s found in endpoint but no credentials found in registry",+ vector_store_id,+ )discovery_handler = get_vertex_pass_through_handler(call_type="discovery")return await _base_vertex_proxy_route(@@ -1321,6 +1494,7 @@ async def vertex_discovery_proxy_route(request=request,fastapi_response=fastapi_response,get_vertex_pass_through_handler=discovery_handler,+ router_credentials=vector_store_credentials,)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 8fb07ee2ca9..c53c2f6e763 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@@ -1,7 +1,7 @@import jsonimport refrom datetime import datetime-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, castfrom urllib.parse import urlparseimport httpx@@ -12,16 +12,21 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingfrom litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (ModelResponseIterator as VertexModelResponseIterator,)+from litellm.llms.vertex_ai.vector_stores.search_api.transformation import (+ VertexSearchAPIVectorStoreConfig,+)from litellm.proxy._types import PassThroughEndpointLoggingTypedDictfrom litellm.types.utils import (EmbeddingResponse,ImageResponse,ModelResponse,+ StandardPassThroughResponseObject,TextCompletionResponse,Choices,)from litellm.types.utils import SpecialEnums+vertex_search_api_config = VertexSearchAPIVectorStoreConfig()if TYPE_CHECKING:from ..success_handler import PassThroughEndpointLoggingfrom litellm.types.utils import LiteLLMBatch@@ -34,6 +39,7 @@ EndpointType = Anyclass VertexPassthroughLoggingHandler:+@staticmethoddef vertex_passthrough_handler(httpx_response: httpx.Response,@@ -209,6 +215,37 @@ class VertexPassthroughLoggingHandler:"result": litellm_prediction_response,"kwargs": kwargs,}+ elif "search" in url_route:++ litellm_vs_response = (+ vertex_search_api_config.transform_search_vector_store_response(+ response=httpx_response,+ litellm_logging_obj=logging_obj,+ )+ )+ response_cost = litellm.completion_cost(+ completion_response=litellm_vs_response,+ model="vertex_ai/search_api",+ custom_llm_provider="vertex_ai",+ call_type="vector_store_search",+ )++ standard_pass_through_response_object: StandardPassThroughResponseObject = {+ "response": cast(dict, litellm_vs_response),+ }++ kwargs["response_cost"] = response_cost+ kwargs["model"] = "vertex_ai/search_api"+ logging_obj.model_call_details.setdefault("litellm_params", {})+ logging_obj.model_call_details["litellm_params"][+ "base_model"+ ] = "vertex_ai/search_api"+ logging_obj.model_call_details["response_cost"] = response_cost++ return {+ "result": standard_pass_through_response_object,+ "kwargs": kwargs,+ }elif "batchPredictionJobs" in url_route:return VertexPassthroughLoggingHandler.batch_prediction_jobs_handler(httpx_response=httpx_response,diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.pyindex ebb0f42288c..64dea058a27 100644--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py@@ -1603,12 +1603,12 @@ class SafeRouteAdder:def _is_path_registered(app: FastAPI, path: str, methods: List[str]) -> bool:"""Check if a path with any of the specified methods is already registered on the app.-+Args:app: The FastAPI application instancepath: The path to check (e.g., "/v1/chat/completions")methods: List of HTTP methods to check (e.g., ["GET", "POST"])-+Returns:True if the path is already registered with any of the methods, False otherwise"""@@ -1616,7 +1616,7 @@ class SafeRouteAdder:# Use getattr to safely access route attributesroute_path = getattr(route, "path", None)route_methods = getattr(route, "methods", None)-+if route_path == path and route_methods is not None:# Check if any of the methods overlapif any(method in route_methods for method in methods):@@ -1633,14 +1633,14 @@ class SafeRouteAdder:) -> bool:"""Add an API route to the app only if it doesn't already exist.-+Args:app: The FastAPI application instancepath: The path for the routeendpoint: The endpoint function/callablemethods: List of HTTP methodsdependencies: Optional list of dependencies-+Returns:True if route was added, False if it already existed"""diff --git a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.pyindex 9335ce49bb7..a32659e45bd 100644--- a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py+++ b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py@@ -1,6 +1,10 @@from typing import Dict, Optional+import litellmfrom litellm._logging import verbose_router_logger+from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import (+ LiteLLM_ManagedVectorStore,+)from litellm.secret_managers.main import get_secret_strfrom litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPESfrom litellm.types.passthrough_endpoints.vertex_ai import VertexPassThroughCredentials@@ -130,9 +134,9 @@ class PassthroughEndpointRouter:vertex_location=location,vertex_credentials=vertex_credentials,)- self.deployment_key_to_vertex_credentials[- deployment_key- ] = vertex_pass_through_credentials+ self.deployment_key_to_vertex_credentials[deployment_key] = (+ vertex_pass_through_credentials+ )def _get_deployment_key(self, project_id: Optional[str], location: Optional[str]@@ -144,6 +148,21 @@ class PassthroughEndpointRouter:return Nonereturn f"{project_id}-{location}"+ def get_vector_store_credentials(+ self, vector_store_id: str+ ) -> Optional[LiteLLM_ManagedVectorStore]:+ """+ Get the vector store credentials for the given vector store id+ """+ if litellm.vector_store_registry is None:+ return None+ vector_store_to_run: Optional[LiteLLM_ManagedVectorStore] = (+ litellm.vector_store_registry.get_litellm_managed_vector_store_from_registry(+ vector_store_id=vector_store_id+ )+ )+ return vector_store_to_run+def get_vertex_credentials(self, project_id: Optional[str], location: Optional[str]) -> Optional[VertexPassThroughCredentials]:diff --git a/litellm/proxy/pass_through_endpoints/success_handler.py b/litellm/proxy/pass_through_endpoints/success_handler.pyindex 0c0ade848ea..6a0cfd44438 100644--- a/litellm/proxy/pass_through_endpoints/success_handler.py+++ b/litellm/proxy/pass_through_endpoints/success_handler.py@@ -22,12 +22,12 @@ from .llm_provider_handlers.assembly_passthrough_logging_handler import (from .llm_provider_handlers.cohere_passthrough_logging_handler import (CoherePassthroughLoggingHandler,)-from .llm_provider_handlers.vertex_passthrough_logging_handler import (- VertexPassthroughLoggingHandler,-)from .llm_provider_handlers.gemini_passthrough_logging_handler import (GeminiPassthroughLoggingHandler,)+from .llm_provider_handlers.vertex_passthrough_logging_handler import (+ VertexPassthroughLoggingHandler,+)cohere_passthrough_logging_handler = CoherePassthroughLoggingHandler()@@ -40,6 +40,7 @@ class PassThroughEndpointLogging:"predict","rawPredict","streamRawPredict",+ "search","batchPredictionJobs",]@@ -48,7 +49,9 @@ class PassThroughEndpointLogging:# Cohereself.TRACKED_COHERE_ROUTES = ["/v2/chat"]- self.assemblyai_passthrough_logging_handler = AssemblyAIPassthroughLoggingHandler()+ self.assemblyai_passthrough_logging_handler = (+ AssemblyAIPassthroughLoggingHandler()+ )# Langfuseself.TRACKED_LANGFUSE_ROUTES = ["/langfuse/"]@@ -86,7 +89,11 @@ class PassThroughEndpointLogging:# Handle async loggingawait logging_obj.async_success_handler(- result=(json.dumps(result) if isinstance(result, dict) else standard_logging_response_object),+ result=(+ json.dumps(result)+ if isinstance(result, dict)+ else standard_logging_response_object+ ),start_time=start_time,end_time=end_time,cache_hit=False,@@ -114,32 +121,40 @@ class PassThroughEndpointLogging:standard_logging_response_object: Optional[Any] = Noneif self.is_gemini_route(url_route, custom_llm_provider):- gemini_passthrough_logging_handler_result = GeminiPassthroughLoggingHandler.gemini_passthrough_handler(- httpx_response=httpx_response,- response_body=response_body or {},- logging_obj=logging_obj,- url_route=url_route,- result=result,- start_time=start_time,- end_time=end_time,- cache_hit=cache_hit,- request_body=request_body,- **kwargs,+ gemini_passthrough_logging_handler_result = (+ GeminiPassthroughLoggingHandler.gemini_passthrough_handler(+ httpx_response=httpx_response,+ response_body=response_body or {},+ logging_obj=logging_obj,+ url_route=url_route,+ result=result,+ start_time=start_time,+ end_time=end_time,+ cache_hit=cache_hit,+ request_body=request_body,+ **kwargs,+ )+ )+ standard_logging_response_object = (+ gemini_passthrough_logging_handler_result["result"])- standard_logging_response_object = gemini_passthrough_logging_handler_result["result"]kwargs = gemini_passthrough_logging_handler_result["kwargs"]elif self.is_vertex_route(url_route):- vertex_passthrough_logging_handler_result = VertexPassthroughLoggingHandler.vertex_passthrough_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,+ vertex_passthrough_logging_handler_result = (+ VertexPassthroughLoggingHandler.vertex_passthrough_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,+ )+ )+ standard_logging_response_object = (+ vertex_passthrough_logging_handler_result["result"])- standard_logging_response_object = vertex_passthrough_logging_handler_result["result"]kwargs = vertex_passthrough_logging_handler_result["kwargs"]elif self.is_anthropic_route(url_route):anthropic_passthrough_logging_handler_result = (@@ -156,22 +171,28 @@ class PassThroughEndpointLogging:))- standard_logging_response_object = anthropic_passthrough_logging_handler_result["result"]+ standard_logging_response_object = (+ anthropic_passthrough_logging_handler_result["result"]+ )kwargs = anthropic_passthrough_logging_handler_result["kwargs"]elif self.is_cohere_route(url_route):- cohere_passthrough_logging_handler_result = cohere_passthrough_logging_handler.passthrough_chat_handler(- httpx_response=httpx_response,- response_body=response_body or {},- logging_obj=logging_obj,- url_route=url_route,- result=result,- start_time=start_time,- end_time=end_time,- cache_hit=cache_hit,- request_body=request_body,- **kwargs,+ cohere_passthrough_logging_handler_result = (+ cohere_passthrough_logging_handler.passthrough_chat_handler(+ httpx_response=httpx_response,+ response_body=response_body or {},+ logging_obj=logging_obj,+ url_route=url_route,+ result=result,+ start_time=start_time,+ end_time=end_time,+ cache_hit=cache_hit,+ request_body=request_body,+ **kwargs,+ )+ )+ standard_logging_response_object = (+ cohere_passthrough_logging_handler_result["result"])- standard_logging_response_object = cohere_passthrough_logging_handler_result["result"]kwargs = cohere_passthrough_logging_handler_result["kwargs"]elif self.is_openai_route(url_route) and self._is_supported_openai_endpoint(url_route@@ -180,29 +201,36 @@ class PassThroughEndpointLogging:OpenAIPassthroughLoggingHandler,)- openai_passthrough_logging_handler_result = OpenAIPassthroughLoggingHandler.openai_passthrough_handler(- httpx_response=httpx_response,- response_body=response_body or {},- logging_obj=logging_obj,- url_route=url_route,- result=result,- start_time=start_time,- end_time=end_time,- cache_hit=cache_hit,- request_body=request_body,- **kwargs,+ openai_passthrough_logging_handler_result = (+ OpenAIPassthroughLoggingHandler.openai_passthrough_handler(+ httpx_response=httpx_response,+ response_body=response_body or {},+ logging_obj=logging_obj,+ url_route=url_route,+ result=result,+ start_time=start_time,+ end_time=end_time,+ cache_hit=cache_hit,+ request_body=request_body,+ **kwargs,+ )+ )+ standard_logging_response_object = (+ openai_passthrough_logging_handler_result["result"])- standard_logging_response_object = openai_passthrough_logging_handler_result["result"]kwargs = openai_passthrough_logging_handler_result["kwargs"]elif self.is_vertex_ai_live_route(url_route):from .llm_provider_handlers.vertex_ai_live_passthrough_logging_handler import (VertexAILivePassthroughLoggingHandler,)+vertex_ai_live_handler = VertexAILivePassthroughLoggingHandler()# For WebSocket responses, response_body should be a list of messages- websocket_messages: list[dict[str, Any]] = response_body if isinstance(response_body, list) else []+ websocket_messages: list[dict[str, Any]] = (+ response_body if isinstance(response_body, list) else []+ )vertex_ai_live_handler_result = (vertex_ai_live_handler.vertex_ai_live_passthrough_handler(@@ -218,9 +246,9 @@ class PassThroughEndpointLogging:standard_logging_response_object = vertex_ai_live_handler_result["result"]kwargs = vertex_ai_live_handler_result["kwargs"]- return_dict[- "standard_logging_response_object"- ] = standard_logging_response_object+ return_dict["standard_logging_response_object"] = (+ standard_logging_response_object+ )return_dict["kwargs"] = kwargsreturn return_dict@@ -240,10 +268,19 @@ class PassThroughEndpointLogging:custom_llm_provider: Optional[str] = None,**kwargs,):- standard_logging_response_object: Optional[PassThroughEndpointLoggingResultValues] = None- logging_obj.model_call_details["passthrough_logging_payload"] = passthrough_logging_payload+ standard_logging_response_object: Optional[+ PassThroughEndpointLoggingResultValues+ ] = None+ logging_obj.model_call_details["passthrough_logging_payload"] = (+ passthrough_logging_payload+ )if self.is_assemblyai_route(url_route):- if AssemblyAIPassthroughLoggingHandler._should_log_request(httpx_response.request.method) is not True:+ if (+ AssemblyAIPassthroughLoggingHandler._should_log_request(+ httpx_response.request.method+ )+ is not True+ ):returnself.assemblyai_passthrough_logging_handler.assemblyai_passthrough_logging_handler(httpx_response=httpx_response,@@ -261,25 +298,31 @@ class PassThroughEndpointLogging:# Don't log langfuse pass-through requestsreturnelse:- normalized_llm_passthrough_logging_payload = self.normalize_llm_passthrough_logging_payload(- httpx_response=httpx_response,- response_body=response_body,- request_body=request_body,- logging_obj=logging_obj,- url_route=url_route,- result=result,- start_time=start_time,- end_time=end_time,- cache_hit=cache_hit,- custom_llm_provider=custom_llm_provider,- **kwargs,+ normalized_llm_passthrough_logging_payload = (+ self.normalize_llm_passthrough_logging_payload(+ httpx_response=httpx_response,+ response_body=response_body,+ request_body=request_body,+ logging_obj=logging_obj,+ url_route=url_route,+ result=result,+ start_time=start_time,+ end_time=end_time,+ cache_hit=cache_hit,+ custom_llm_provider=custom_llm_provider,+ **kwargs,+ )+ )+ standard_logging_response_object = (+ normalized_llm_passthrough_logging_payload[+ "standard_logging_response_object"+ ])- standard_logging_response_object = normalized_llm_passthrough_logging_payload[- "standard_logging_response_object"- ]kwargs = normalized_llm_passthrough_logging_payload["kwargs"]if standard_logging_response_object is None:- standard_logging_response_object = StandardPassThroughResponseObject(response=httpx_response.text)+ standard_logging_response_object = StandardPassThroughResponseObject(+ response=httpx_response.text+ )kwargs = self._set_cost_per_request(logging_obj=logging_obj,@@ -345,10 +388,13 @@ class PassThroughEndpointLogging:return Falseparsed_url = urlparse(url_route)return parsed_url.hostname and (- "api.openai.com" in parsed_url.hostname or "openai.azure.com" in parsed_url.hostname+ "api.openai.com" in parsed_url.hostname+ or "openai.azure.com" in parsed_url.hostname)- def is_gemini_route(self, url_route: str, custom_llm_provider: Optional[str] = None):+ def is_gemini_route(+ self, url_route: str, custom_llm_provider: Optional[str] = None+ ):"""Check if the URL route is a Gemini API route."""for route in self.TRACKED_GEMINI_ROUTES:if route in url_route and custom_llm_provider == "gemini":@@ -385,7 +431,11 @@ class PassThroughEndpointLogging:# Check if cost per request is set#########################################################if passthrough_logging_payload.get("cost_per_request") is not None:- kwargs["response_cost"] = passthrough_logging_payload.get("cost_per_request")- logging_obj.model_call_details["response_cost"] = passthrough_logging_payload.get("cost_per_request")+ kwargs["response_cost"] = passthrough_logging_payload.get(+ "cost_per_request"+ )+ logging_obj.model_call_details["response_cost"] = (+ passthrough_logging_payload.get("cost_per_request")+ )return kwargsdiff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 31daaaf24fd..de6a35fd810 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -356,6 +356,8 @@ CallTypesLiteral = Literal["agenerate_content_stream","ocr","aocr",+ "avector_store_search",+ "vector_store_search",]@@ -2069,12 +2071,10 @@ class GuardrailMode(TypedDict, total=False):GuardrailStatus = Literal[- "success",- "guardrail_intervened",- "guardrail_failed_to_respond",- "not_run"+ "success", "guardrail_intervened", "guardrail_failed_to_respond", "not_run"]+class StandardLoggingGuardrailInformation(TypedDict, total=False):guardrail_name: Optional[str]guardrail_provider: Optional[str]@@ -2125,7 +2125,9 @@ class CostBreakdown(TypedDict, total=False):"""input_cost: float # Cost of input/prompt tokens- output_cost: float # Cost of output/completion tokens (includes reasoning if applicable)+ output_cost: (+ float # Cost of output/completion tokens (includes reasoning if applicable)+ )total_cost: float # Total cost (input + output + tool usage)tool_usage_cost: float # Cost of usage of built-in toolsoriginal_cost: float # Cost before discount (optional)@@ -2135,6 +2137,7 @@ class CostBreakdown(TypedDict, total=False):class StandardLoggingPayloadStatusFields(TypedDict, total=False):"""Status fields for easy filtering and analytics"""+llm_api_status: StandardLoggingPayloadStatus"""Status of the LLM API call - 'success' if completed, 'failure' if errored"""guardrail_status: GuardrailStatus@@ -2207,7 +2210,7 @@ class CustomStreamingDecoder:class StandardPassThroughResponseObject(TypedDict):- response: str+ response: Union[str, dict]OPENAI_RESPONSE_HEADERS = [@@ -2256,6 +2259,7 @@ class StandardCallbackDynamicParams(TypedDict, total=False):turn_off_message_logging: Optional[bool] # when true will not log messageslitellm_disabled_callbacks: Optional[List[str]]+class CustomPricingLiteLLMParams(BaseModel):## CUSTOM PRICING ##input_cost_per_token: Optional[float] = None@@ -2264,7 +2268,7 @@ class CustomPricingLiteLLMParams(BaseModel):output_cost_per_second: Optional[float] = Noneinput_cost_per_pixel: Optional[float] = Noneoutput_cost_per_pixel: Optional[float] = None-+# Include all ModelInfoBase fields as optional# This allows any model_info parameter to be set in litellm_paramsinput_cost_per_token_flex: Optional[float] = None@@ -2310,106 +2314,111 @@ class CustomPricingLiteLLMParams(BaseModel):citation_cost_per_token: Optional[float] = Nonetiered_pricing: Optional[List[Dict[str, Any]]] = None-all_litellm_params = [- "metadata",- "litellm_metadata",- "litellm_trace_id",- "litellm_request_debug",- "guardrails",- "tags",- "acompletion",- "aimg_generation",- "atext_completion",- "text_completion",- "caching",- "mock_response",- "mock_timeout",- "disable_add_transform_inline_image_block",- "litellm_proxy_rate_limit_response",- "api_key",- "api_version",- "prompt_id",- "provider_specific_header",- "prompt_variables",- "prompt_version",- "api_base",- "force_timeout",- "logger_fn",- "verbose",- "custom_llm_provider",- "model_file_id_mapping",- "litellm_logging_obj",- "litellm_call_id",- "use_client",- "id",- "fallbacks",- "azure",- "headers",- "model_list",- "num_retries",- "context_window_fallback_dict",- "retry_policy",- "retry_strategy",- "roles",- "final_prompt_value",- "bos_token",- "eos_token",- "request_timeout",- "complete_response",- "self",- "client",- "rpm",- "tpm",- "max_parallel_requests",- "input_cost_per_token",- "output_cost_per_token",- "input_cost_per_second",- "output_cost_per_second",- "hf_model_name",- "model_info",- "proxy_server_request",- "secret_fields",- "preset_cache_key",- "caching_groups",- "ttl",- "cache",- "no-log",- "base_model",- "stream_timeout",- "supports_system_message",- "region_name",- "allowed_model_region",- "model_config",- "fastest_response",- "cooldown_time",- "cache_key",- "max_retries",- "azure_ad_token_provider",- "tenant_id",- "client_id",- "azure_username",- "azure_password",- "azure_scope",- "client_secret",- "user_continue_message",- "configurable_clientside_auth_params",- "weight",- "ensure_alternating_roles",- "assistant_continue_message",- "user_continue_message",- "fallback_depth",- "max_fallbacks",- "max_budget",- "budget_duration",- "use_in_pass_through",- "merge_reasoning_content_in_choices",- "litellm_credential_name",- "allowed_openai_params",- "litellm_session_id",- "use_litellm_proxy",- "prompt_label",- "shared_session",-] + list(StandardCallbackDynamicParams.__annotations__.keys()) + list(CustomPricingLiteLLMParams.model_fields.keys())++all_litellm_params = (+ [+ "metadata",+ "litellm_metadata",+ "litellm_trace_id",+ "litellm_request_debug",+ "guardrails",+ "tags",+ "acompletion",+ "aimg_generation",+ "atext_completion",+ "text_completion",+ "caching",+ "mock_response",+ "mock_timeout",+ "disable_add_transform_inline_image_block",+ "litellm_proxy_rate_limit_response",+ "api_key",+ "api_version",+ "prompt_id",+ "provider_specific_header",+ "prompt_variables",+ "prompt_version",+ "api_base",+ "force_timeout",+ "logger_fn",+ "verbose",+ "custom_llm_provider",+ "model_file_id_mapping",+ "litellm_logging_obj",+ "litellm_call_id",+ "use_client",+ "id",+ "fallbacks",+ "azure",+ "headers",+ "model_list",+ "num_retries",+ "context_window_fallback_dict",+ "retry_policy",+ "retry_strategy",+ "roles",+ "final_prompt_value",+ "bos_token",+ "eos_token",+ "request_timeout",+ "complete_response",+ "self",+ "client",+ "rpm",+ "tpm",+ "max_parallel_requests",+ "input_cost_per_token",+ "output_cost_per_token",+ "input_cost_per_second",+ "output_cost_per_second",+ "hf_model_name",+ "model_info",+ "proxy_server_request",+ "secret_fields",+ "preset_cache_key",+ "caching_groups",+ "ttl",+ "cache",+ "no-log",+ "base_model",+ "stream_timeout",+ "supports_system_message",+ "region_name",+ "allowed_model_region",+ "model_config",+ "fastest_response",+ "cooldown_time",+ "cache_key",+ "max_retries",+ "azure_ad_token_provider",+ "tenant_id",+ "client_id",+ "azure_username",+ "azure_password",+ "azure_scope",+ "client_secret",+ "user_continue_message",+ "configurable_clientside_auth_params",+ "weight",+ "ensure_alternating_roles",+ "assistant_continue_message",+ "user_continue_message",+ "fallback_depth",+ "max_fallbacks",+ "max_budget",+ "budget_duration",+ "use_in_pass_through",+ "merge_reasoning_content_in_choices",+ "litellm_credential_name",+ "allowed_openai_params",+ "litellm_session_id",+ "use_litellm_proxy",+ "prompt_label",+ "shared_session",+ ]+ + list(StandardCallbackDynamicParams.__annotations__.keys())+ + list(CustomPricingLiteLLMParams.model_fields.keys())+)class KeyGenerationConfig(TypedDict, total=False):@@ -2832,10 +2841,10 @@ class PriorityReservationSettings(BaseModel):default=0.25,description="Priority level to assign to API keys without explicit priority metadata. Should match a key in litellm.priority_reservation.",)-+saturation_threshold: float = Field(default=0.50,- description="Saturation threshold (0.0-1.0) at which strict priority enforcement begins. Below this threshold, generous mode allows priority borrowing. Above this threshold, strict mode enforces normalized priority limits."+ description="Saturation threshold (0.0-1.0) at which strict priority enforcement begins. Below this threshold, generous mode allows priority borrowing. Above this threshold, strict mode enforces normalized priority limits.",)model_config = ConfigDict(protected_namespaces=())diff --git a/litellm/vector_stores/main.py b/litellm/vector_stores/main.pyindex 2e121615297..a0d0e338edc 100644--- a/litellm/vector_stores/main.py+++ b/litellm/vector_stores/main.py@@ -436,7 +436,7 @@ def search(# Pre Call logginglitellm_logging_obj.update_environment_variables(- model=None,+ model=api_type,optional_params={"vector_store_id": vector_store_id,"query": query,diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex a1f3a190251..0c9a5349ab3 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -23922,6 +23922,11 @@"supports_vision": true,"supports_web_search": true},+ "vertex_ai/search_api": {+ "input_cost_per_query": 1.5e-03,+ "litellm_provider": "vertex_ai",+ "mode": "vector_store"+ },"openai/sora-2": {"litellm_provider": "openai","mode": "video_generation",diff --git a/setup_vertex_env.sh b/setup_vertex_env.shnew file mode 100644index 00000000000..e66a0e1d858--- /dev/null+++ b/setup_vertex_env.sh@@ -0,0 +1,63 @@+#!/bin/bash+# Setup script for Vertex AI credentials using environment variables+#+# This script helps configure your environment for Vertex AI Discovery passthrough+# without needing to put credentials in the config.yaml file++echo "🔧 Setting up Vertex AI credentials from environment variables"+echo "================================================================"+echo ""++# Prompt for GCP Project ID+read -p "Enter your GCP Project ID: " PROJECT_ID+export DEFAULT_VERTEXAI_PROJECT="$PROJECT_ID"+echo "✓ Set DEFAULT_VERTEXAI_PROJECT=$PROJECT_ID"++# Prompt for Vertex Location+echo ""+echo "Common locations: us-central1, global, us-east1, europe-west1"+read -p "Enter your Vertex AI location (default: global): " LOCATION+LOCATION=${LOCATION:-global}+export DEFAULT_VERTEXAI_LOCATION="$LOCATION"+echo "✓ Set DEFAULT_VERTEXAI_LOCATION=$LOCATION"++# Prompt for credentials file path+echo ""+read -p "Enter the path to your service account JSON file: " CREDS_PATH++# Expand ~ to home directory if needed+CREDS_PATH="${CREDS_PATH/#\~/$HOME}"++# Check if file exists+if [ -f "$CREDS_PATH" ]; then+ export DEFAULT_GOOGLE_APPLICATION_CREDENTIALS="$CREDS_PATH"+ echo "✓ Set DEFAULT_GOOGLE_APPLICATION_CREDENTIALS=$CREDS_PATH"++ # Also set standard GOOGLE_APPLICATION_CREDENTIALS for fallback+ export GOOGLE_APPLICATION_CREDENTIALS="$CREDS_PATH"+ echo "✓ Set GOOGLE_APPLICATION_CREDENTIALS=$CREDS_PATH"+else+ echo "⚠️ Warning: File not found at $CREDS_PATH"+ echo " Please make sure the path is correct"+fi++echo ""+echo "================================================================"+echo "✅ Environment variables configured!"+echo ""+echo "Current settings:"+echo " DEFAULT_VERTEXAI_PROJECT=$DEFAULT_VERTEXAI_PROJECT"+echo " DEFAULT_VERTEXAI_LOCATION=$DEFAULT_VERTEXAI_LOCATION"+echo " DEFAULT_GOOGLE_APPLICATION_CREDENTIALS=$DEFAULT_GOOGLE_APPLICATION_CREDENTIALS"+echo ""+echo "To make these persistent, add the following to your ~/.zshrc or ~/.bashrc:"+echo ""+echo " export DEFAULT_VERTEXAI_PROJECT=\"$PROJECT_ID\""+echo " export DEFAULT_VERTEXAI_LOCATION=\"$LOCATION\""+echo " export DEFAULT_GOOGLE_APPLICATION_CREDENTIALS=\"$CREDS_PATH\""+echo " export GOOGLE_APPLICATION_CREDENTIALS=\"$CREDS_PATH\""+echo ""+echo "You can now start LiteLLM proxy with:"+echo " litellm --config proxy_server_config.yaml"+echo ""+