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
[Feat] Vector Stores - Add Vertex RAG Engine API as a provider (#12595)
Ishaan Jaff5a1746879dd3
diff --git a/docs/my-website/docs/completion/knowledgebase.md b/docs/my-website/docs/completion/knowledgebase.mdindex a1c926274cd..35bd1942b9d 100644--- a/docs/my-website/docs/completion/knowledgebase.md+++ b/docs/my-website/docs/completion/knowledgebase.md@@ -18,7 +18,8 @@ LiteLLM integrates with vector stores, allowing your models to access your organ## Supported Vector Stores- [Bedrock Knowledge Bases](https://aws.amazon.com/bedrock/knowledge-bases/)- [OpenAI Vector Stores](https://platform.openai.com/docs/api-reference/vector-stores/search)-- [Azure Vector Stores](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/file-search?tabs=python#vector-stores+- [Azure Vector Stores](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/file-search?tabs=python#vector-stores)+- [Vertex AI RAG API](https://cloud.google.com/vertex-ai/generative-ai/docs/rag-overview)## Quick Startdiff --git a/litellm/llms/base_llm/vector_store/transformation.py b/litellm/llms/base_llm/vector_store/transformation.pyindex 6ec9d25ae59..95b78ab12b2 100644--- a/litellm/llms/base_llm/vector_store/transformation.py+++ b/litellm/llms/base_llm/vector_store/transformation.py@@ -30,11 +30,12 @@ class BaseVectorStoreConfig:query: Union[str, List[str]],vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,api_base: str,+ litellm_logging_obj: LiteLLMLoggingObj,) -> Tuple[str, Dict]:pass@abstractmethod- def transform_search_vector_store_response(self, response: httpx.Response) -> VectorStoreSearchResponse:+ def transform_search_vector_store_response(self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj) -> VectorStoreSearchResponse:pass@abstractmethoddiff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 1d78be0e97d..2481e93d061 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -2699,6 +2699,7 @@ class BaseLLMHTTPHandler:query=query,vector_store_search_optional_params=vector_store_search_optional_params,api_base=api_base,+ litellm_logging_obj=logging_obj,))@@ -2721,6 +2722,7 @@ class BaseLLMHTTPHandler:return vector_store_provider_config.transform_search_vector_store_response(response=response,+ litellm_logging_obj=logging_obj,)def vector_store_search_handler(@@ -2780,6 +2782,7 @@ class BaseLLMHTTPHandler:query=query,vector_store_search_optional_params=vector_store_search_optional_params,api_base=api_base,+ litellm_logging_obj=logging_obj,))@@ -2802,6 +2805,7 @@ class BaseLLMHTTPHandler:return vector_store_provider_config.transform_search_vector_store_response(response=response,+ litellm_logging_obj=logging_obj,)async def async_vector_store_create_handler(diff --git a/litellm/llms/openai/vector_stores/transformation.py b/litellm/llms/openai/vector_stores/transformation.pyindex 11d76937ab4..8f89f53c639 100644--- a/litellm/llms/openai/vector_stores/transformation.py+++ b/litellm/llms/openai/vector_stores/transformation.py@@ -1,4 +1,4 @@-from typing import Dict, List, Optional, Tuple, Union, cast+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, castimport httpx@@ -15,6 +15,12 @@ from litellm.types.vector_stores import (VectorStoreSearchResponse,)+if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj++ LiteLLMLoggingObj = _LiteLLMLoggingObj+else:+ LiteLLMLoggingObj = Anyclass OpenAIVectorStoreConfig(BaseVectorStoreConfig):ASSISTANTS_HEADER_KEY = "OpenAI-Beta"@@ -76,6 +82,7 @@ class OpenAIVectorStoreConfig(BaseVectorStoreConfig):query: Union[str, List[str]],vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,api_base: str,+ litellm_logging_obj: LiteLLMLoggingObj,) -> Tuple[str, Dict]:url = f"{api_base}/{vector_store_id}/search"typed_request_body = VectorStoreSearchRequest(@@ -91,7 +98,7 @@ class OpenAIVectorStoreConfig(BaseVectorStoreConfig):- def transform_search_vector_store_response(self, response: httpx.Response) -> VectorStoreSearchResponse:+ def transform_search_vector_store_response(self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj) -> VectorStoreSearchResponse:try:response_json = response.json()return VectorStoreSearchResponse(diff --git a/litellm/llms/vertex_ai/vector_stores/__init__.py b/litellm/llms/vertex_ai/vector_stores/__init__.pynew file mode 100644index 00000000000..f3c210a973c--- /dev/null+++ b/litellm/llms/vertex_ai/vector_stores/__init__.py@@ -0,0 +1,3 @@+from .transformation import VertexVectorStoreConfig++__all__ = ["VertexVectorStoreConfig"]\ No newline at end of filediff --git a/litellm/llms/vertex_ai/vector_stores/transformation.py b/litellm/llms/vertex_ai/vector_stores/transformation.pynew file mode 100644index 00000000000..ca374728c03--- /dev/null+++ b/litellm/llms/vertex_ai/vector_stores/transformation.py@@ -0,0 +1,294 @@+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union++import httpx++from litellm.llms.base_llm.vector_store.transformation import BaseVectorStoreConfig+from litellm.llms.vertex_ai.vertex_llm_base import VertexBase+from litellm.secret_managers.main import get_secret_str+from litellm.types.router import GenericLiteLLMParams+from litellm.types.vector_stores import (+ VectorStoreCreateOptionalRequestParams,+ VectorStoreCreateResponse,+ VectorStoreResultContent,+ VectorStoreSearchOptionalRequestParams,+ VectorStoreSearchResponse,+ VectorStoreSearchResult,+)++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj++ LiteLLMLoggingObj = _LiteLLMLoggingObj+else:+ LiteLLMLoggingObj = Any+++class VertexVectorStoreConfig(BaseVectorStoreConfig, VertexBase):+ """+ Configuration for Vertex AI Vector Store RAG API++ This implementation uses the Vertex AI RAG Engine API for vector store operations.+ """++ def __init__(self):+ super().__init__()++ def validate_environment(+ self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]+ ) -> dict:+ """+ Validate and set up authentication for Vertex AI RAG API+ """+ litellm_params = litellm_params or GenericLiteLLMParams()++ # Get credentials and project info+ vertex_credentials = (+ litellm_params.vertex_credentials+ or get_secret_str("VERTEXAI_CREDENTIALS")+ or get_secret_str("VERTEX_AI_CREDENTIALS")+ )+ vertex_project = (+ litellm_params.vertex_project+ or get_secret_str("VERTEXAI_PROJECT")+ or get_secret_str("VERTEX_AI_PROJECT")+ )++ # Get access token using the base class method+ access_token, project_id = self._ensure_access_token(+ credentials=vertex_credentials,+ project_id=vertex_project,+ custom_llm_provider="vertex_ai",+ )++ headers.update({+ "Authorization": f"Bearer {access_token}",+ "Content-Type": "application/json",+ })++ return headers++ def get_complete_url(+ self,+ api_base: Optional[str],+ litellm_params: dict,+ ) -> str:+ """+ Get the Base endpoint for Vertex AI RAG API+ """+ vertex_location = (+ litellm_params.get("vertex_location")+ or get_secret_str("VERTEXAI_LOCATION")+ or get_secret_str("VERTEX_AI_LOCATION")+ or "us-central1"+ )+ vertex_project = (+ litellm_params.get("vertex_project")+ or get_secret_str("VERTEXAI_PROJECT")+ or get_secret_str("VERTEX_AI_PROJECT")+ )++ if api_base:+ return api_base.rstrip("/")++ # Vertex AI RAG API endpoint for retrieveContexts+ return f"https://{vertex_location}-aiplatform.googleapis.com/v1/projects/{vertex_project}/locations/{vertex_location}"++ def transform_search_vector_store_request(+ self,+ vector_store_id: str,+ query: Union[str, List[str]],+ vector_store_search_optional_params: VectorStoreSearchOptionalRequestParams,+ api_base: str,+ litellm_logging_obj: LiteLLMLoggingObj,+ ) -> Tuple[str, Dict[str, Any]]:+ """+ Transform search request for Vertex AI RAG API+ """+ # Convert query to string if it's a list+ if isinstance(query, list):+ query = " ".join(query)++ # Vertex AI RAG API endpoint for retrieving contexts+ url = f"{api_base}:retrieveContexts"++ # Build the request body for Vertex AI RAG API+ request_body: Dict[str, Any] = {+ "vertex_rag_store": {+ "rag_resources": [+ {+ "rag_corpus": vector_store_id+ }+ ]+ },+ "query": {+ "text": query+ }+ }++ #########################################################+ # Update logging object with details of the request+ #########################################################+ litellm_logging_obj.model_call_details["query"] = query++ # Add optional parameters+ max_num_results = vector_store_search_optional_params.get("max_num_results")+ if max_num_results is not None:+ request_body["query"]["rag_retrieval_config"] = {+ "top_k": max_num_results+ }++ # Add filters if provided+ filters = vector_store_search_optional_params.get("filters")+ if filters is not None:+ if "rag_retrieval_config" not in request_body["query"]:+ request_body["query"]["rag_retrieval_config"] = {}+ request_body["query"]["rag_retrieval_config"]["filter"] = filters++ # Add ranking options if provided+ ranking_options = vector_store_search_optional_params.get("ranking_options")+ if ranking_options is not None:+ if "rag_retrieval_config" not in request_body["query"]:+ request_body["query"]["rag_retrieval_config"] = {}+ request_body["query"]["rag_retrieval_config"]["ranking"] = ranking_options++ return url, request_body++ def transform_search_vector_store_response(self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj) -> VectorStoreSearchResponse:+ """+ Transform Vertex AI RAG API response to standard vector store search response+ """+ try:++ response_json = response.json()+ # Extract contexts from Vertex AI response - handle nested structure+ contexts = response_json.get("contexts", {}).get("contexts", [])++ # Transform contexts to standard format+ search_results = []+ for context in contexts:+ content = [+ VectorStoreResultContent(+ text=context.get("text", ""),+ type="text",+ )+ ]++ # Extract file information+ source_uri = context.get("sourceUri", "")+ source_display_name = context.get("sourceDisplayName", "")++ # Generate file_id from source URI or use display name as fallback+ file_id = source_uri if source_uri else source_display_name+ filename = source_display_name if source_display_name else "Unknown Document"++ # Build attributes with available metadata+ attributes = {}+ if source_uri:+ attributes["sourceUri"] = source_uri+ if source_display_name:+ attributes["sourceDisplayName"] = source_display_name++ # Add page span information if available+ page_span = context.get("pageSpan", {})+ if page_span:+ attributes["pageSpan"] = page_span++ result = VectorStoreSearchResult(+ score=context.get("score", 0.0),+ content=content,+ file_id=file_id,+ filename=filename,+ attributes=attributes,+ )+ search_results.append(result)++ return VectorStoreSearchResponse(+ object="vector_store.search_results.page",+ search_query=litellm_logging_obj.model_call_details.get("query", ""),+ data=search_results+ )++ except Exception as e:+ raise self.get_error_class(+ error_message=str(e),+ status_code=response.status_code,+ headers=response.headers+ )++ def transform_create_vector_store_request(+ self,+ vector_store_create_optional_params: VectorStoreCreateOptionalRequestParams,+ api_base: str,+ ) -> Tuple[str, Dict[str, Any]]:+ """+ Transform create request for Vertex AI RAG Corpus+ """+ url = f"{api_base}/ragCorpora" # Base URL for creating RAG corpus++ # Build the request body for Vertex AI RAG Corpus creation+ request_body: Dict[str, Any] = {+ "display_name": vector_store_create_optional_params.get("name", "litellm-vector-store"),+ "description": "Vector store created via LiteLLM"+ }++ # Add metadata if provided+ metadata = vector_store_create_optional_params.get("metadata")+ if metadata is not None:+ request_body["labels"] = metadata++ return url, request_body++ def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse:+ """+ Transform Vertex AI RAG Corpus creation response to standard vector store response+ """+ try:+ response_json = response.json()++ # Extract the corpus ID from the response name+ corpus_name = response_json.get("name", "")+ corpus_id = corpus_name.split("/")[-1] if "/" in corpus_name else corpus_name++ # Handle createTime conversion+ create_time = response_json.get("createTime", 0)+ if isinstance(create_time, str):+ # Convert ISO timestamp to Unix timestamp+ from datetime import datetime+ try:+ dt = datetime.fromisoformat(create_time.replace('Z', '+00:00'))+ create_time = int(dt.timestamp())+ except ValueError:+ create_time = 0+ elif not isinstance(create_time, int):+ create_time = 0++ # Handle labels safely+ labels = response_json.get("labels", {})+ metadata = labels if isinstance(labels, dict) else {}++ return VectorStoreCreateResponse(+ id=corpus_id,+ object="vector_store",+ created_at=create_time,+ name=response_json.get("display_name", ""),+ bytes=0, # Vertex AI doesn't provide byte count in the same way+ file_counts={+ "in_progress": 0,+ "completed": 0,+ "failed": 0,+ "cancelled": 0,+ "total": 0+ },+ status="completed", # Vertex AI corpus creation is typically synchronous+ expires_after=None,+ expires_at=None,+ last_active_at=None,+ metadata=metadata+ )++ except Exception as e:+ raise self.get_error_class(+ error_message=str(e),+ status_code=response.status_code,+ headers=response.headers+ )\ No newline at end of filediff --git a/litellm/types/vector_stores.py b/litellm/types/vector_stores.pyindex 3d7190d7f9b..f0d4a053751 100644--- a/litellm/types/vector_stores.py+++ b/litellm/types/vector_stores.py@@ -72,9 +72,11 @@ class VectorStoreResultContent(TypedDict, total=False):class VectorStoreSearchResult(TypedDict, total=False):"""Result of a vector store search"""-score: Optional[float]content: Optional[List[VectorStoreResultContent]]+ file_id: Optional[str]+ filename: Optional[str]+ attributes: Optional[Dict]class VectorStoreSearchResponse(TypedDict, total=False):diff --git a/litellm/utils.py b/litellm/utils.pyindex 98fe101b946..47653e1ad0b 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -7087,6 +7087,12 @@ class ProviderConfigManager:)return AzureOpenAIVectorStoreConfig()+ elif litellm.LlmProviders.VERTEX_AI == provider:+ from litellm.llms.vertex_ai.vector_stores.transformation import (+ VertexVectorStoreConfig,+ )++ return VertexVectorStoreConfig()return None@staticmethoddiff --git a/tests/vector_store_tests/base_vector_store_test.py b/tests/vector_store_tests/base_vector_store_test.pyindex ac1ec704f36..d3b58d8338d 100644--- a/tests/vector_store_tests/base_vector_store_test.py+++ b/tests/vector_store_tests/base_vector_store_test.py@@ -38,15 +38,16 @@ class BaseVectorStoreTest(ABC):litellm._turn_on_debug()litellm.set_verbose = Truebase_request_args = self.get_base_request_args()+ default_query = base_request_args.pop("query", "Basic ping")try:if sync_mode:response = litellm.vector_stores.search(- query="Basic ping",+ query=default_query,**base_request_args)else:response = await litellm.vector_stores.asearch(- query="Basic ping",+ query=default_query,**base_request_args)except litellm.InternalServerError:@@ -106,7 +107,7 @@ class BaseVectorStoreTest(ABC):f"Expected object to be 'vector_store.search_results.page', got '{response['object']}'"# Validate search_query field- assert isinstance(response['search_query'], list), \+ assert isinstance(response['search_query'], str), \f"search_query should be a list, got {type(response['search_query'])}"assert len(response['search_query']) > 0, "search_query should not be empty"assert all(isinstance(query, str) for query in response['search_query']), \diff --git a/tests/vector_store_tests/test_vertex_ai_vector_store.py b/tests/vector_store_tests/test_vertex_ai_vector_store.pynew file mode 100644index 00000000000..e9dee407917--- /dev/null+++ b/tests/vector_store_tests/test_vertex_ai_vector_store.py@@ -0,0 +1,27 @@+import os+import pytest+from unittest.mock import Mock, patch++from litellm.llms.vertex_ai.vector_stores.transformation import VertexVectorStoreConfig+from litellm.types.vector_stores import (+ VectorStoreCreateResponse,+ VectorStoreSearchResponse,+ VectorStoreSearchResult,+ VectorStoreResultContent,+)+from tests.vector_store_tests.base_vector_store_test import BaseVectorStoreTest+++class TestVertexAIVectorStore(BaseVectorStoreTest):+ def get_base_create_vector_store_args(self) -> dict:+ """Must return the base create vector store args"""+ return {}++ def get_base_request_args(self):+ return {+ "vector_store_id": "projects/reliablekeys/locations/us-central1/ragCorpora/6917529027641081856",+ "custom_llm_provider": "vertex_ai",+ "vertex_project": "reliablekeys",+ "vertex_location": "us-central1",+ "query": "what happens after we add a model"+ }