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
[Bug Fix] QA - Use PG Vector Vector Store with LiteLLM (#12716)
Ishaan Jaff3051a9c68a43
diff --git a/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.py b/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.pyindex 8e7db45d756..8e3343c1a98 100644--- a/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.py+++ b/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.py@@ -9,7 +9,7 @@ All /vector_store management endpoints"""import copy-from typing import List+from typing import List, Optionalfrom fastapi import APIRouter, Depends, HTTPException, Request, Response@@ -50,6 +50,7 @@ async def new_vector_store(- vector_store_metadata: Optional[Dict] - Additional metadata for the vector store"""from litellm.proxy.proxy_server import prisma_client+ from litellm.types.router import GenericLiteLLMParamsif prisma_client is None:raise HTTPException(status_code=500, detail="Database not connected")@@ -72,9 +73,20 @@ async def new_vector_store(vector_store.get("vector_store_metadata"))+ # Safely handle JSON serialization of litellm_params+ litellm_params_json: Optional[str] = None+ _input_litellm_params: dict = vector_store.get("litellm_params", {}) or {}+ if _input_litellm_params is not None:+ litellm_params_dict = GenericLiteLLMParams(**_input_litellm_params).model_dump(exclude_none=True)+ litellm_params_json = safe_dumps(litellm_params_dict)+ del vector_store["litellm_params"]+_new_vector_store = (await prisma_client.db.litellm_managedvectorstorestable.create(- data=vector_store+ data={+ **vector_store,+ "litellm_params": litellm_params_json,+ }))diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex b92f4af3844..28cb1a60437 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -502,6 +502,7 @@ model LiteLLM_ManagedVectorStoresTable {created_at DateTime @default(now())updated_at DateTime @updatedAtlitellm_credential_name String?+ litellm_params Json?}// Guardrails table for storing guardrail configurationsdiff --git a/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py b/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.pyindex 630cab4402e..59c378f8204 100644--- a/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py+++ b/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py@@ -92,12 +92,13 @@ class VectorStorePreCallHook(CustomLogger):# Get vector store id from the vector store configvector_store_id = vector_store_to_run.get("vector_store_id", "")custom_llm_provider = vector_store_to_run.get("custom_llm_provider")-+ litellm_params_for_vector_store = vector_store_to_run.get("litellm_params", {}) or {}# Call litellm.vector_stores.search() with the required parameterssearch_response = await litellm.vector_stores.asearch(vector_store_id=vector_store_id,query=query,custom_llm_provider=custom_llm_provider,+ **litellm_params_for_vector_store)verbose_logger.debug(f"search_response: {search_response}")diff --git a/litellm/llms/pg_vector/vector_stores/transformation.py b/litellm/llms/pg_vector/vector_stores/transformation.pyindex 1bc03a6f2f8..6553a85ad9b 100644--- a/litellm/llms/pg_vector/vector_stores/transformation.py+++ b/litellm/llms/pg_vector/vector_stores/transformation.py@@ -1,9 +1,14 @@-from typing import Optional+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Unionfrom litellm.llms.openai.vector_stores.transformation import OpenAIVectorStoreConfigfrom litellm.secret_managers.main import get_secret_strfrom litellm.types.router import GenericLiteLLMParams+from litellm.types.vector_stores import VectorStoreSearchOptionalRequestParams+if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+else:+ LiteLLMLoggingObj = Anyclass PGVectorStoreConfig(OpenAIVectorStoreConfig):"""@@ -66,4 +71,23 @@ class PGVectorStoreConfig(OpenAIVectorStoreConfig):# Remove trailing slashesapi_base = api_base.rstrip("/")- return f"{api_base}/vector_stores"\ No newline at end of file+ return f"{api_base}/v1/vector_stores"+++ 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]:+ url = f"{api_base}/{vector_store_id}/search"+ _, request_body = super().transform_search_vector_store_request(+ vector_store_id=vector_store_id,+ query=query,+ vector_store_search_optional_params=vector_store_search_optional_params,+ api_base=api_base,+ litellm_logging_obj=litellm_logging_obj,+ )+ return url, request_body\ No newline at end of filediff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex bebb4630ec7..8a8fd6794e7 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -6,18 +6,3 @@ model_list:litellm_params:model: openai/*--guardrails:- - guardrail_name: "bedrock-post-guard"- litellm_params:- guardrail: bedrock # supported values: "aporia", "bedrock", "lakera"- mode: "post_call"- guardrailIdentifier: ff6ujrregl1q- guardrailVersion: "DRAFT"- disable_exception_on_block: true- default_on: true--litellm_settings:- callbacks: ["datadog_llm_observability"]- cache: true-diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 03aba679f01..e4d87cf24ea 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -207,9 +207,6 @@ from litellm.proxy.common_utils.openai_endpoint_utils import (from litellm.proxy.common_utils.proxy_state import ProxyStatefrom litellm.proxy.common_utils.reset_budget_job import ResetBudgetJobfrom litellm.proxy.common_utils.swagger_utils import ERROR_RESPONSES-from litellm.proxy.common_utils.vector_store_endpoints.endpoints import (- router as vector_store_router,-)from litellm.proxy.credential_endpoints.endpoints import router as credential_routerfrom litellm.proxy.db.db_transaction_queue.spend_log_cleanup import SpendLogCleanupfrom litellm.proxy.db.exception_handler import PrismaDBExceptionHandler@@ -332,6 +329,7 @@ from litellm.proxy.utils import (hash_token,update_spend,)+from litellm.proxy.vector_store_endpoints.endpoints import router as vector_store_routerfrom litellm.proxy.vertex_ai_endpoints.langfuse_endpoints import (router as langfuse_router,)diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex b92f4af3844..28cb1a60437 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -502,6 +502,7 @@ model LiteLLM_ManagedVectorStoresTable {created_at DateTime @default(now())updated_at DateTime @updatedAtlitellm_credential_name String?+ litellm_params Json?}// Guardrails table for storing guardrail configurationsdiff --git a/litellm/proxy/common_utils/vector_store_endpoints/endpoints.py b/litellm/proxy/vector_store_endpoints/endpoints.pysimilarity index 100%rename from litellm/proxy/common_utils/vector_store_endpoints/endpoints.pyrename to litellm/proxy/vector_store_endpoints/endpoints.pydiff --git a/litellm/types/vector_stores.py b/litellm/types/vector_stores.pyindex f0d4a053751..58a2e7f9006 100644--- a/litellm/types/vector_stores.py+++ b/litellm/types/vector_stores.py@@ -2,10 +2,11 @@ from datetime import datetimefrom enum import Enumfrom typing import Any, Dict, List, Literal, Optional, Union+from annotated_types import Gefrom pydantic import BaseModelfrom typing_extensions import TypedDict-from litellm.types.router import CredentialLiteLLMParams+from litellm.types.router import CredentialLiteLLMParams, GenericLiteLLMParamsclass SupportedVectorStoreIntegrations(str, Enum):@@ -36,6 +37,9 @@ class LiteLLM_ManagedVectorStore(TypedDict, total=False):# credential fieldslitellm_credential_name: Optional[str]+ # litellm_params+ litellm_params: Optional[Dict[str, Any]]+class LiteLLM_ManagedVectorStoreListResponse(TypedDict, total=False):"""Response format for listing vector stores"""diff --git a/schema.prisma b/schema.prismaindex b92f4af3844..28cb1a60437 100644--- a/schema.prisma+++ b/schema.prisma@@ -502,6 +502,7 @@ model LiteLLM_ManagedVectorStoresTable {created_at DateTime @default(now())updated_at DateTime @updatedAtlitellm_credential_name String?+ litellm_params Json?}// Guardrails table for storing guardrail configurationsdiff --git a/tests/test_litellm/llms/pg_vector/vector_stores/test_pg_vector_transformation.py b/tests/test_litellm/llms/pg_vector/vector_stores/test_pg_vector_transformation.pyindex 644980928ae..4c2295b268b 100644--- a/tests/test_litellm/llms/pg_vector/vector_stores/test_pg_vector_transformation.py+++ b/tests/test_litellm/llms/pg_vector/vector_stores/test_pg_vector_transformation.py@@ -5,7 +5,7 @@ This test file mirrors litellm/llms/pg_vector/vector_stores/transformation.pyand contains mocked tests for the PGVectorStoreConfig class."""-from unittest.mock import Mock+from unittest.mock import MagicMock, Mock, patchimport pytest@@ -59,7 +59,7 @@ class TestPGVectorStoreConfig:result_url = config.get_complete_url(api_base, litellm_params)- assert result_url == "https://my-pg-vector-service.example.com/vector_stores"+ assert result_url == "https://my-pg-vector-service.example.com/v1/vector_stores"def test_get_complete_url_removes_trailing_slashes(self):"""@@ -73,7 +73,7 @@ class TestPGVectorStoreConfig:result_url = config.get_complete_url(api_base, litellm_params)- assert result_url == "https://my-pg-vector-service.example.com/vector_stores"+ assert result_url == "https://my-pg-vector-service.example.com/v1/vector_stores"def test_get_complete_url_missing_api_base(self):"""@@ -139,9 +139,8 @@ class TestPGVectorStoreConfig:# Verify resultsassert headers["Authorization"] == "Bearer test_key"- assert url == "https://example.com/vector_stores"+ assert url == "https://example.com/v1/vector_stores"- @pytest.mark.serialdef test_environment_variable_support(self):"""Test that environment variables are supported for configuration.@@ -166,7 +165,7 @@ class TestPGVectorStoreConfig:with patch.dict(os.environ, {'PG_VECTOR_API_BASE': 'https://env-pg-vector.example.com'}):url = config.get_complete_url(None, {})- assert url == "https://env-pg-vector.example.com/vector_stores"+ assert url == "https://env-pg-vector.example.com/v1/vector_stores"# Test that params take precedence over environment variableswith patch.dict(os.environ, {'PG_VECTOR_API_KEY': 'env_key'}):@@ -176,4 +175,109 @@ class TestPGVectorStoreConfig:# Param key should take precedence over environment variableassert headers["Authorization"] == "Bearer param_key"- assert headers["Content-Type"] == "application/json"\ No newline at end of file+ assert headers["Content-Type"] == "application/json"++ @patch('litellm.llms.custom_httpx.http_handler.HTTPHandler.post')+ def test_pg_vector_search_request_construction(self, mock_post):+ """+ Test that PG Vector search constructs the correct URL and request body.++ This test validates the complete request construction for PG Vector search+ operations, including URL, headers, and request body.+ """+ import litellm++ # Clear any existing vector store registry to prevent interference with test data+ original_registry = getattr(litellm, 'vector_store_registry', None)+ litellm.vector_store_registry = None++ try:+ # Mock successful response+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "object": "vector_store.search_results.page",+ "search_query": ["what are remote working hours for BerriAI"],+ "data": [+ {+ "file_id": "file_123",+ "filename": "remote_work_policy.txt",+ "score": 0.95,+ "attributes": {"department": "HR"},+ "content": [+ {+ "type": "text",+ "text": "Remote working hours are flexible from 9 AM to 5 PM"+ }+ ]+ }+ ]+ }+ mock_post.return_value = mock_response++ # Test parameters - use a different vector store ID than test registry+ api_base = "http://localhost:8001"+ api_key = "sk-1234"+ vector_store_id = "pg-vector-test-store-123" # Different from test registry IDs+ query = "what are remote working hours for BerriAI"++ # Call litellm vector store search+ exception_raised = None+ response = None+ try:+ response = litellm.vector_stores.search(+ query=query,+ vector_store_id=vector_store_id,+ api_base=api_base,+ api_key=api_key,+ custom_llm_provider="pg_vector",+ mock_response=None # Explicitly disable LiteLLM's automatic mocking+ )+ print(f"✅ Search completed successfully: {response}")+ except Exception as e:+ exception_raised = e+ print(f"❌ Exception raised during search: {type(e).__name__}: {e}")+ import traceback+ traceback.print_exc()++ # Print debug information+ print(f"🔍 Mock post called: {mock_post.called}")+ print(f"🔍 Mock post call count: {mock_post.call_count}")+ if mock_post.call_args:+ print(f"🔍 Mock post call args: {mock_post.call_args}")++ # For now, let's check if there was an exception that prevented the call+ if exception_raised:+ print(f"🔍 Exception details: {exception_raised}")+ # If there's a specific exception we expect during testing, we might allow it+ # but we should still verify the mock was called before the exception++ # Validate that the mock was called correctly+ assert mock_post.called, f"HTTPHandler.post should have been called. Exception: {exception_raised}"++ # Get the call arguments+ call_args, call_kwargs = mock_post.call_args++ # Validate URL+ expected_url = f"{api_base}/v1/vector_stores/{vector_store_id}/search"+ actual_url = call_kwargs.get('url')+ assert actual_url == expected_url, f"Expected URL {expected_url}, got {actual_url}"++ # Validate headers+ headers = call_kwargs.get('headers', {})+ assert headers.get("Authorization") == f"Bearer {api_key}"+ assert headers.get("Content-Type") == "application/json"++ # Validate request body - it should be in 'data' parameter as JSON string+ json_data_str = call_kwargs.get('data', '{}')+ import json+ json_data = json.loads(json_data_str) if isinstance(json_data_str, str) else json_data_str+ assert json_data.get("query") == query++ print("✅ PG Vector search request validation passed:")+ print(f" URL: {actual_url}")+ print(f" Headers: {headers}")+ print(f" Body: {json_data}")+ finally:+ # Restore original registry+ litellm.vector_store_registry = original_registry\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsx b/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsxindex 6c6db2a954e..c36cc4ed6cd 100644--- a/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsx+++ b/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsx@@ -59,13 +59,14 @@ const VectorStoreForm: React.FC<VectorStoreFormProps> = ({litellm_credential_name: formValues.litellm_credential_name,};- // Add provider-specific fields dynamically+ // pass all provider fields as litellm params dictconst providerFields = getProviderSpecificFields(formValues.custom_llm_provider);- providerFields.forEach(field => {- if (formValues[field.name]) {- payload[field.name] = formValues[field.name];- }- });+ const litellmParams = providerFields.reduce((acc, field) => {+ acc[field.name] = formValues[field.name];+ return acc;+ }, {} as Record<string, any>);++ payload["litellm_params"] = litellmParams;await vectorStoreCreateCall(accessToken, payload);message.success("Vector store created successfully");