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
[QA] Bedrock Vector Stores Integration - Allow using with registry + in OpenAI API spec with tools (#10516)
Ishaan Jaff988e20aa361d
diff --git a/enterprise/proxy/vector_stores/endpoints.py b/enterprise/proxy/vector_stores/endpoints.pyindex 443f4ac3e66..c4198f6a551 100644--- a/enterprise/proxy/vector_stores/endpoints.py+++ b/enterprise/proxy/vector_stores/endpoints.py@@ -1,25 +1,29 @@"""VECTOR STORE MANAGEMENT-All /vector_store management endpoints+All /vector_store management endpoints/vector_store/new/vector_store/delete/vector_store/list"""+import copyfrom typing import List-from litellm.litellm_core_utils.safe_json_dumps import safe_dumps+from fastapi import APIRouter, Depends, HTTPException++import litellmfrom litellm._logging import verbose_proxy_logger+from litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.auth.user_api_key_auth import user_api_key_auth-from litellm.proxy.vector_stores.vector_store_registry import global_vector_store_managerfrom litellm.types.vector_stores import (- LiteLLM_ManagedVectorStoreListResponse,LiteLLM_ManagedVectorStore,+ LiteLLM_ManagedVectorStoreListResponse,VectorStoreDeleteRequest,)+from litellm.vector_stores.vector_store_registry import VectorStoreRegistryrouter = APIRouter()@@ -47,25 +51,37 @@ async def new_vector_store(if prisma_client is None:raise HTTPException(status_code=500, detail="Database not connected")-+try:# Check if vector store already exists- existing_vector_store = await prisma_client.db.litellm_managedvectorstorestable.find_unique(- where={"vector_store_id": vector_store.get("vector_store_id")}+ existing_vector_store = (+ await prisma_client.db.litellm_managedvectorstorestable.find_unique(+ where={"vector_store_id": vector_store.get("vector_store_id")}+ ))if existing_vector_store is not None:raise HTTPException(- status_code=400,- detail=f"Vector store with ID {vector_store.get('vector_store_id')} already exists"+ status_code=400,+ detail=f"Vector store with ID {vector_store.get('vector_store_id')} already exists",)-+if vector_store.get("vector_store_metadata") is not None:- vector_store["vector_store_metadata"] = safe_dumps(vector_store.get("vector_store_metadata"))-- new_vector_store = await prisma_client.db.litellm_managedvectorstorestable.create(- data=vector_store+ vector_store["vector_store_metadata"] = safe_dumps(+ vector_store.get("vector_store_metadata")+ )++ new_vector_store = (+ await prisma_client.db.litellm_managedvectorstorestable.create(+ data=vector_store+ ))-++ # Add vector store to registry+ if litellm.vector_store_registry is not None:+ litellm.vector_store_registry.add_vector_store_to_registry(+ vector_store=new_vector_store+ )+return {"status": "success","message": f"Vector store {vector_store.get('vector_store_id')} created successfully",@@ -76,7 +92,6 @@ async def new_vector_store(raise HTTPException(status_code=500, detail=str(e))-@router.get("/vector_store/list",tags=["vector store management"],@@ -91,36 +106,39 @@ async def list_vector_stores("""List all available vector stores with optional filtering and pagination.Combines both in-memory vector stores and those stored in the database.-+Parameters:- page: int - Page number for pagination (default: 1)- page_size: int - Number of items per page (default: 100)"""from litellm.proxy.proxy_server import prisma_client+ seen_vector_store_ids = set()+try:# Get in-memory vector stores- in_memory_vector_stores: List[LiteLLM_ManagedVectorStore] = copy.deepcopy(global_vector_store_manager.vector_stores)+ in_memory_vector_stores: List[LiteLLM_ManagedVectorStore] = []+ if litellm.vector_store_registry is not None:+ in_memory_vector_stores = copy.deepcopy(+ litellm.vector_store_registry.vector_stores+ )# Get vector stores from database- vector_stores_from_db: List[LiteLLM_ManagedVectorStore] = []- if prisma_client is not None:- _vector_stores_from_db = await prisma_client.db.litellm_managedvectorstorestable.find_many(- order={- "created_at": "desc"- },- )- for vector_store in _vector_stores_from_db:- _dict_vector_store = dict(vector_store)- _litellm_managed_vector_store = LiteLLM_ManagedVectorStore(**_dict_vector_store)- vector_stores_from_db.append(_litellm_managed_vector_store)-+ vector_stores_from_db = await VectorStoreRegistry._get_vector_stores_from_db(+ prisma_client=prisma_client+ )+# Combine in-memory and database vector stores- combined_vector_stores: List[LiteLLM_ManagedVectorStore] = in_memory_vector_stores + vector_stores_from_db-+ combined_vector_stores: List[LiteLLM_ManagedVectorStore] = []+ for vector_store in in_memory_vector_stores + vector_stores_from_db:+ vector_store_id = vector_store.get("vector_store_id", None)+ if vector_store_id not in seen_vector_store_ids:+ combined_vector_stores.append(vector_store)+ seen_vector_store_ids.add(vector_store_id)+total_count = len(combined_vector_stores)total_pages = (total_count + page_size - 1) // page_size-+# Format response using LiteLLM_ManagedVectorStoreListResponseresponse = LiteLLM_ManagedVectorStoreListResponse(object="list",@@ -129,7 +147,7 @@ async def list_vector_stores(current_page=page,total_pages=total_pages,)-+return responseexcept Exception as e:verbose_proxy_logger.exception(f"Error listing vector stores: {str(e)}")@@ -155,26 +173,31 @@ async def delete_vector_store(if prisma_client is None:raise HTTPException(status_code=500, detail="Database not connected")-+try:# Check if vector store exists- existing_vector_store = await prisma_client.db.litellm_managedvectorstorestable.find_unique(- where={"vector_store_id": data.vector_store_id}+ existing_vector_store = (+ await prisma_client.db.litellm_managedvectorstorestable.find_unique(+ where={"vector_store_id": data.vector_store_id}+ ))if existing_vector_store is None:raise HTTPException(- status_code=404,- detail=f"Vector store with ID {data.vector_store_id} not found"+ status_code=404,+ detail=f"Vector store with ID {data.vector_store_id} not found",)-+# Delete vector storeawait prisma_client.db.litellm_managedvectorstorestable.delete(where={"vector_store_id": data.vector_store_id})-++ # Delete vector store from registry+ if litellm.vector_store_registry is not None:+ litellm.vector_store_registry.delete_vector_store_from_registry(+ vector_store_id=data.vector_store_id+ )+return {"message": f"Vector store {data.vector_store_id} deleted successfully"}except Exception as e:raise HTTPException(status_code=500, detail=str(e))---diff --git a/litellm/__init__.py b/litellm/__init__.pyindex a015eceb0ab..b507e52bdbe 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -114,7 +114,7 @@ _custom_logger_compatible_callbacks_literal = Literal["gcs_pubsub","agentops","anthropic_cache_control_hook",- "bedrock_knowledgebase_hook",+ "bedrock_vector_store",]logged_real_time_event_types: Optional[Union[List[str], Literal["*"]]] = None_known_custom_logger_compatible_callbacks: List = list(@@ -1070,6 +1070,11 @@ import litellm.anthropic_interface as anthropicadapters: List[AdapterItem] = []+### Vector Store Registry ###+from .vector_stores.vector_store_registry import VectorStoreRegistry++vector_store_registry: Optional[VectorStoreRegistry] = None+### CUSTOM LLMs ###from .types.llms.custom_llm import CustomLLMItemfrom .types.utils import GenericStreamingChunkdiff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.pyindex 1fe25d76238..17441ba1d0a 100644--- a/litellm/integrations/custom_logger.py+++ b/litellm/integrations/custom_logger.py@@ -5,6 +5,7 @@ from typing import (TYPE_CHECKING,Any,AsyncGenerator,+ Dict,List,Literal,Optional,@@ -84,6 +85,7 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbacprompt_variables: Optional[dict],dynamic_callback_params: StandardCallbackDynamicParams,litellm_logging_obj: LiteLLMLoggingObj,+ tools: Optional[List[Dict]] = None,) -> Tuple[str, List[AllMessageValues], dict]:"""Returns:diff --git a/litellm/integrations/langfuse/langfuse_prompt_management.py b/litellm/integrations/langfuse/langfuse_prompt_management.pyindex 8de38a0154e..b4149d7ad97 100644--- a/litellm/integrations/langfuse/langfuse_prompt_management.py+++ b/litellm/integrations/langfuse/langfuse_prompt_management.py@@ -4,7 +4,7 @@ Call Hook for LiteLLM Proxy which allows Langfuse prompt management.import osfrom functools import lru_cache-from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, Union, cast+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union, castfrom packaging.version import Versionfrom typing_extensions import TypeAlias@@ -175,6 +175,7 @@ class LangfusePromptManagement(LangFuseLogger, PromptManagementBase, CustomLoggeprompt_variables: Optional[dict],dynamic_callback_params: StandardCallbackDynamicParams,litellm_logging_obj: LiteLLMLoggingObj,+ tools: Optional[List[Dict]] = None,) -> Tuple[str,List[AllMessageValues],diff --git a/litellm/integrations/vector_stores/base_vector_store.py b/litellm/integrations/vector_stores/base_vector_store.pynew file mode 100644index 00000000000..38e31f63816--- /dev/null+++ b/litellm/integrations/vector_stores/base_vector_store.py@@ -0,0 +1,5 @@+from litellm.integrations.custom_prompt_management import CustomPromptManagement+++class BaseVectorStore(CustomPromptManagement):+ passdiff --git a/litellm/integrations/rag_hooks/bedrock_knowledgebase.py b/litellm/integrations/vector_stores/bedrock_vector_store.pysimilarity index 87%rename from litellm/integrations/rag_hooks/bedrock_knowledgebase.pyrename to litellm/integrations/vector_stores/bedrock_vector_store.pyindex 28f4e1492e2..e52a90bcdad 100644--- a/litellm/integrations/rag_hooks/bedrock_knowledgebase.py+++ b/litellm/integrations/vector_stores/bedrock_vector_store.py@@ -9,9 +9,10 @@ import jsonfrom datetime import datetimefrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple+import litellmfrom litellm._logging import verbose_logger, verbose_proxy_loggerfrom litellm.integrations.custom_logger import CustomLogger-from litellm.integrations.custom_prompt_management import CustomPromptManagement+from litellm.integrations.vector_stores.base_vector_store import BaseVectorStorefrom litellm.llms.bedrock.base_aws_llm import BaseAWSLLMfrom litellm.llms.custom_httpx.http_handler import (get_async_httpx_client,@@ -33,6 +34,7 @@ from litellm.types.vector_stores import (VectorStoreSearchResult,VectorStorSearchResponse,)+from litellm.utils import load_credentials_from_listif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj@@ -45,7 +47,7 @@ else:StandardCallbackDynamicParams = Any-class BedrockKnowledgeBaseHook(CustomPromptManagement, BaseAWSLLM):+class BedrockVectorStore(BaseVectorStore, BaseAWSLLM):CONTENT_PREFIX_STRING = "Context: \n\n"CUSTOM_LLM_PROVIDER = "bedrock"@@ -72,11 +74,17 @@ class BedrockKnowledgeBaseHook(CustomPromptManagement, BaseAWSLLM):prompt_variables: Optional[dict],dynamic_callback_params: StandardCallbackDynamicParams,litellm_logging_obj: LiteLLMLoggingObj,+ tools: Optional[List[Dict]] = None,) -> Tuple[str, List[AllMessageValues], dict]:"""Retrieves the context from the Bedrock Knowledge Base and appends it to the messages."""- vector_store_ids = non_default_params.pop("vector_store_ids", None)+ if litellm.vector_store_registry is None:+ return model, messages, non_default_params++ vector_store_ids = litellm.vector_store_registry.pop_vector_store_ids_to_run(+ non_default_params=non_default_params, tools=tools+ )vector_store_request_metadata: List[StandardLoggingVectorStoreRequest] = []if vector_store_ids:for vector_store_id in vector_store_ids:@@ -85,6 +93,7 @@ class BedrockKnowledgeBaseHook(CustomPromptManagement, BaseAWSLLM):bedrock_kb_response = await self.make_bedrock_kb_retrieve_request(knowledge_base_id=vector_store_id,query=query,+ non_default_params=non_default_params,)verbose_logger.debug(f"Bedrock Knowledge Base Response: {bedrock_kb_response}"@@ -228,6 +237,7 @@ class BedrockKnowledgeBaseHook(CustomPromptManagement, BaseAWSLLM):guardrail_version: Optional[str] = None,next_token: Optional[str] = None,retrieval_configuration: Optional[BedrockKBRetrievalConfiguration] = None,+ non_default_params: Optional[dict] = None,) -> BedrockKBResponse:"""Make a Bedrock Knowledge Base retrieve request.@@ -245,7 +255,21 @@ class BedrockKnowledgeBaseHook(CustomPromptManagement, BaseAWSLLM):"""from fastapi import HTTPException- credentials = self.get_credentials()+ non_default_params = non_default_params or {}+ load_credentials_from_list(kwargs=non_default_params)+ credentials = self.get_credentials(+ aws_access_key_id=non_default_params.get("aws_access_key_id", None),+ aws_secret_access_key=non_default_params.get("aws_secret_access_key", None),+ aws_session_token=non_default_params.get("aws_session_token", None),+ aws_region_name=non_default_params.get("aws_region_name", None),+ aws_session_name=non_default_params.get("aws_session_name", None),+ aws_profile_name=non_default_params.get("aws_profile_name", None),+ aws_role_name=non_default_params.get("aws_role_name", None),+ aws_web_identity_token=non_default_params.get(+ "aws_web_identity_token", None+ ),+ aws_sts_endpoint=non_default_params.get("aws_sts_endpoint", None),+ )aws_region_name = self._get_aws_region_name(optional_params=self.optional_params)@@ -310,28 +334,16 @@ class BedrockKnowledgeBaseHook(CustomPromptManagement, BaseAWSLLM):)@staticmethod- def should_use_prompt_management_hook(non_default_params: Dict) -> bool:- if non_default_params.get("vector_store_ids", None):- return True- return False-- @staticmethod- def get_initialized_custom_logger(- non_default_params: Dict,- ) -> Optional[CustomLogger]:+ def get_initialized_custom_logger() -> Optional[CustomLogger]:from litellm.litellm_core_utils.litellm_logging import (_init_custom_logger_compatible_class,)- if BedrockKnowledgeBaseHook.should_use_prompt_management_hook(- non_default_params- ):- return _init_custom_logger_compatible_class(- logging_integration="bedrock_knowledgebase_hook",- internal_usage_cache=None,- llm_router=None,- )- return None+ return _init_custom_logger_compatible_class(+ logging_integration="bedrock_vector_store",+ internal_usage_cache=None,+ llm_router=None,+ )@staticmethoddef get_chat_completion_message_from_bedrock_kb_response(@@ -347,7 +359,7 @@ class BedrockKnowledgeBaseHook(CustomPromptManagement, BaseAWSLLM):return None, ""# string to combine the context from the knowledge base- context_string: str = BedrockKnowledgeBaseHook.CONTENT_PREFIX_STRING+ context_string: str = BedrockVectorStore.CONTENT_PREFIX_STRINGfor retrieval_result in retrieval_results:retrieval_result_content: Optional[BedrockKBContent] = (retrieval_result.get("content", None) or {}diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 4f7f43c528e..c6957a4e5d6 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -43,9 +43,7 @@ from litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.mlflow import MlflowLoggerfrom litellm.integrations.pagerduty.pagerduty import PagerDutyAlerting-from litellm.integrations.rag_hooks.bedrock_knowledgebase import (- BedrockKnowledgeBaseHook,-)+from litellm.integrations.vector_stores.bedrock_vector_store import BedrockVectorStorefrom litellm.litellm_core_utils.get_litellm_params import get_litellm_paramsfrom litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import (StandardBuiltInToolCostTracking,@@ -464,6 +462,7 @@ class Logging(LiteLLMLoggingBaseClass):self,non_default_params: Dict,prompt_id: Optional[str] = None,+ tools: Optional[List[Dict]] = None,) -> bool:"""Return True if prompt management hooks should be run@@ -472,7 +471,8 @@ class Logging(LiteLLMLoggingBaseClass):return Trueif self._should_run_prompt_management_hooks_without_prompt_id(- non_default_params=non_default_params+ non_default_params=non_default_params,+ tools=tools,):return True@@ -481,6 +481,7 @@ class Logging(LiteLLMLoggingBaseClass):def _should_run_prompt_management_hooks_without_prompt_id(self,non_default_params: Dict,+ tools: Optional[List[Dict]] = None,) -> bool:"""Certain prompt management hooks don't need a `prompt_id` to be passed in, they are triggered by dynamic params@@ -490,6 +491,15 @@ class Logging(LiteLLMLoggingBaseClass):for param in non_default_params:if param in DynamicPromptManagementParamLiteral.list_all_params():return True++ #############################################################################+ # Check if Vector Store / Knowledge Base hooks should be applied to the prompt+ #############################################################################+ if litellm.vector_store_registry is not None:+ if litellm.vector_store_registry.get_vector_store_to_run(+ non_default_params=non_default_params, tools=tools+ ):+ return Truereturn Falsedef get_chat_completion_prompt(@@ -532,6 +542,7 @@ class Logging(LiteLLMLoggingBaseClass):prompt_id: Optional[str],prompt_variables: Optional[dict],prompt_management_logger: Optional[CustomLogger] = None,+ tools: Optional[List[Dict]] = None,) -> Tuple[str, List[AllMessageValues], dict]:custom_logger = (prompt_management_logger@@ -553,6 +564,7 @@ class Logging(LiteLLMLoggingBaseClass):prompt_variables=prompt_variables,dynamic_callback_params=self.standard_callback_dynamic_params,litellm_logging_obj=self,+ tools=tools,)self.messages = messagesreturn model, messages, non_default_params@@ -601,13 +613,26 @@ class Logging(LiteLLMLoggingBaseClass):)return anthropic_cache_control_logger- if bedrock_knowledgebase_logger := BedrockKnowledgeBaseHook.get_initialized_custom_logger(- non_default_params- ):- self.model_call_details["prompt_integration"] = (- bedrock_knowledgebase_logger.__class__.__name__- )- return bedrock_knowledgebase_logger+ #########################################################+ # Vector Store / Knowledge Base hooks+ #########################################################+ if litellm.vector_store_registry is not None:+ if vector_store_to_run := litellm.vector_store_registry.get_vector_store_to_run(+ non_default_params=non_default_params+ ):+ vector_store_custom_logger = (+ litellm.ProviderConfigManager.get_provider_vector_store_config(+ provider=cast(+ litellm.LlmProviders,+ vector_store_to_run.get("custom_llm_provider"),+ ),+ )+ )+ self.model_call_details["prompt_integration"] = (+ vector_store_custom_logger.__class__.__name__+ )+ return vector_store_custom_logger+return Nonedef get_custom_logger_for_anthropic_cache_control_hook(@@ -3025,13 +3050,13 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915anthropic_cache_control_hook = AnthropicCacheControlHook()_in_memory_loggers.append(anthropic_cache_control_hook)return anthropic_cache_control_hook # type: ignore- elif logging_integration == "bedrock_knowledgebase_hook":+ elif logging_integration == "bedrock_vector_store":for callback in _in_memory_loggers:- if isinstance(callback, BedrockKnowledgeBaseHook):+ if isinstance(callback, BedrockVectorStore):return callback- bedrock_knowledgebase_hook = BedrockKnowledgeBaseHook()- _in_memory_loggers.append(bedrock_knowledgebase_hook)- return bedrock_knowledgebase_hook # type: ignore+ bedrock_vector_store = BedrockVectorStore()+ _in_memory_loggers.append(bedrock_vector_store)+ return bedrock_vector_store # type: ignoreelif logging_integration == "gcs_pubsub":for callback in _in_memory_loggers:if isinstance(callback, GcsPubSubLogger):@@ -3174,9 +3199,9 @@ def get_custom_logger_compatible_class( # noqa: PLR0915for callback in _in_memory_loggers:if isinstance(callback, AnthropicCacheControlHook):return callback- elif logging_integration == "bedrock_knowledgebase_hook":+ elif logging_integration == "bedrock_vector_store":for callback in _in_memory_loggers:- if isinstance(callback, BedrockKnowledgeBaseHook):+ if isinstance(callback, BedrockVectorStore):return callbackelif logging_integration == "gcs_pubsub":for callback in _in_memory_loggers:diff --git a/litellm/main.py b/litellm/main.pyindex 52e6609f37c..9487de5043e 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -412,7 +412,9 @@ async def acompletion(litellm_logging_obj = kwargs.get("litellm_logging_obj", None)if isinstance(litellm_logging_obj, LiteLLMLoggingObj) and (litellm_logging_obj.should_run_prompt_management_hooks(- prompt_id=kwargs.get("prompt_id", None), non_default_params=kwargs+ prompt_id=kwargs.get("prompt_id", None),+ non_default_params=kwargs,+ tools=tools,)):(@@ -425,6 +427,7 @@ async def acompletion(non_default_params=kwargs,prompt_id=kwargs.get("prompt_id", None),prompt_variables=kwargs.get("prompt_variables", None),+ tools=tools,)#########################################################diff --git a/litellm/proxy/_experimental/out/onboarding.html b/litellm/proxy/_experimental/out/onboarding.htmldeleted file mode 100644index bbb3c04c070..00000000000--- a/litellm/proxy/_experimental/out/onboarding.html+++ /dev/null@@ -1 +0,0 @@-<!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/ui/_next/static/chunks/webpack-75a5453f51d60261.js"/><script src="/ui/_next/static/chunks/fd9d1056-205af899b895cbac.js" async=""></script><script src="/ui/_next/static/chunks/117-1c5bfc45bfc4237d.js" async=""></script><script src="/ui/_next/static/chunks/main-app-4f7318ae681a6d94.js" async=""></script><title>LiteLLM Dashboard</title><meta name="description" content="LiteLLM Proxy Admin UI"/><link rel="icon" href="/ui/favicon.ico" type="image/x-icon" sizes="16x16"/><meta name="next-size-adjust"/><script src="/ui/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><script src="/ui/_next/static/chunks/webpack-75a5453f51d60261.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:HL[\"/ui/_next/static/media/a34f9d1faa5f3315-s.p.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n2:HL[\"/ui/_next/static/css/86f6cc749f6b8493.css\",\"style\"]\n3:HL[\"/ui/_next/static/css/513933b5401340d3.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"4:I[12846,[],\"\"]\n6:I[19107,[],\"ClientPageRoot\"]\n7:I[12011,[\"665\",\"static/chunks/3014691f-b7b79b78e27792f3.js\",\"42\",\"static/chunks/42-69f5b4e6a9942a9f.js\",\"899\",\"static/chunks/899-57685cedd1dcbc78.js\",\"250\",\"static/chunks/250-d58eaf99965b85ca.js\",\"461\",\"static/chunks/app/onboarding/page-55bb5a6ed064240c.js\"],\"default\",1]\n8:I[4707,[],\"\"]\n9:I[36423,[],\"\"]\nb:I[61060,[],\"\"]\nc:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L4\",null,{\"buildId\":\"uPn92g-Yq9ZPM_l7ejl_A\",\"assetPrefix\":\"/ui\",\"urlParts\":[\"\",\"onboarding\"],\"initialTree\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{},[[\"$L5\",[\"$\",\"$L6\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$7\"}],null],null],null]},[null,[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"onboarding\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/ui/_next/static/css/86f6cc749f6b8493.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"1\",{\"rel\":\"stylesheet\",\"href\":\"/ui/_next/static/css/513933b5401340d3.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__className_cf7686\",\"children\":[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$La\"],\"globalErrorComponent\":\"$b\",\"missingSlots\":\"$Wc\"}]\n"])</script><script>self.__next_f.push([1,"a:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"LiteLLM Dashboard\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"LiteLLM Proxy Admin UI\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/ui/favicon.ico\",\"type\":\"image/x-icon\",\"sizes\":\"16x16\"}],[\"$\",\"meta\",\"5\",{\"name\":\"next-size-adjust\"}]]\n5:null\n"])</script></body></html>\ No newline at end of filediff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex a3d0653ea9c..2f7604065b5 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -9,14 +9,14 @@ model_list:api_key: os.environ/ANTHROPIC_API_KEYvector_store_ids: ["T37J8R4WTM"]-vector_stores:- - vector_store_name: "bedrock-litellm-website-knowledgebase"- litellm_params:- custom_llm_provider: "bedrock"- vector_store_id: "T37J8R4WTM"- vector_store_description: "Bedrock vector store for the Litellm website knowledgebase"- vector_store_metadata:- source: "https://www.litellm.com/docs"+# vector_stores:+# - vector_store_name: "bedrock-litellm-website-knowledgebase"+# litellm_params:+# custom_llm_provider: "bedrock"+# vector_store_id: "T37J8R4WTM"+# vector_store_description: "Bedrock vector store for the Litellm website knowledgebase"+# vector_store_metadata:+# source: "https://www.litellm.com/docs"general_settings:diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex c289b9d188c..75290ae0958 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -2028,11 +2028,13 @@ class ProxyConfig:## VECTOR STORESvector_stores_config = config.get("vector_stores", None)if vector_stores_config:- from litellm.proxy.vector_stores.vector_store_registry import (- global_vector_store_manager,- )+ from litellm.vector_stores.vector_store_registry import VectorStoreRegistry++ if litellm.vector_store_registry is None:+ litellm.vector_store_registry = VectorStoreRegistry()- global_vector_store_manager.load_vector_stores_from_config(+ # Load vector stores from config+ litellm.vector_store_registry.load_vector_stores_from_config(vector_stores_config)pass@@ -2674,6 +2676,9 @@ class ProxyConfig:db_general_settings=db_general_settings.param_value,)+ # initialize vector stores table in db+ await self._init_vector_stores_in_db(prisma_client=prisma_client)+except Exception as e:verbose_proxy_logger.exception("litellm.proxy.proxy_server.py::ProxyConfig:add_deployment - {}".format(@@ -2681,6 +2686,33 @@ class ProxyConfig:))+ async def _init_vector_stores_in_db(self, prisma_client: PrismaClient):+ from litellm.vector_stores.vector_store_registry import VectorStoreRegistry++ try:+ # read vector stores from db table+ vector_stores = await VectorStoreRegistry._get_vector_stores_from_db(+ prisma_client=prisma_client+ )+ if len(vector_stores) <= 0:+ return++ if litellm.vector_store_registry is None:+ litellm.vector_store_registry = VectorStoreRegistry(+ vector_stores=vector_stores+ )+ else:+ for vector_store in vector_stores:+ litellm.vector_store_registry.add_vector_store_to_registry(+ vector_store=vector_store+ )+ except Exception as e:+ verbose_proxy_logger.exception(+ "litellm.proxy.proxy_server.py::ProxyConfig:_init_vector_stores_in_db - {}".format(+ str(e)+ )+ )+def decrypt_credentials(self, credential: Union[dict, BaseModel]) -> CredentialItem:if isinstance(credential, dict):credential_object = CredentialItem(**credential)diff --git a/litellm/proxy/vector_stores/vector_store_registry.py b/litellm/proxy/vector_stores/vector_store_registry.pydeleted file mode 100644index 3eb337b7724..00000000000--- a/litellm/proxy/vector_stores/vector_store_registry.py+++ /dev/null@@ -1,79 +0,0 @@-# litellm/proxy/vector_stores/vector_store_registry.py-import json-from datetime import datetime, timezone-from typing import Any, Dict, List--from litellm._logging import verbose_logger-from litellm.types.vector_stores import (- LiteLLM_ManagedVectorStore,- LiteLLM_ManagedVectorStoreListResponse,- LiteLLM_VectorStoreConfig,-)---class VectorStoreManager:- def __init__(self):- self.vector_stores: List[LiteLLM_ManagedVectorStore] = []-- def load_vector_stores_from_config(self, vector_stores_config: List[Dict]):- for vector_store_config in vector_stores_config:- # cast to VectorStoreConfig- litellm_vector_store_config = LiteLLM_VectorStoreConfig(- **vector_store_config- )- vector_store_name = litellm_vector_store_config.get("vector_store_name")- vector_store_litellm_params: Dict[str, Any] = (- litellm_vector_store_config.get("litellm_params") or {}- )-- vector_store_id = vector_store_litellm_params.get("vector_store_id")- if vector_store_id is None:- raise ValueError(- f"vector_store_id is required for initializing vector store, got vector_store_id={vector_store_id}"- )- custom_llm_provider = vector_store_litellm_params.get("custom_llm_provider")- if custom_llm_provider is None:- raise ValueError(- f"custom_llm_provider is required for initializing vector store, got custom_llm_provider={custom_llm_provider}"- )-- litellm_managed_vector_store = LiteLLM_ManagedVectorStore(- vector_store_id=vector_store_id,- custom_llm_provider=custom_llm_provider,- vector_store_name=vector_store_name,- vector_store_description=vector_store_litellm_params.get(- "vector_store_description"- ),- vector_store_metadata=vector_store_litellm_params.get(- "vector_store_metadata"- ),- created_at=datetime.now(timezone.utc),- updated_at=datetime.now(timezone.utc),- )- self.vector_stores.append(litellm_managed_vector_store)-- verbose_logger.debug(- "all loaded vector stores = %s",- json.dumps(self.vector_stores, indent=4, default=str),- )-- def list_all_vector_stores(self) -> LiteLLM_ManagedVectorStoreListResponse:- """- List all vector stores in the required format-- Returns:- LiteLLM_ManagedVectorStoreListResponse: A standardized response with vector store data- """- # Prepare the response- response = LiteLLM_ManagedVectorStoreListResponse(- object="list",- data=self.vector_stores,- total_count=len(self.vector_stores),- current_page=1,- total_pages=1,- )-- return response---global_vector_store_manager = VectorStoreManager()diff --git a/litellm/utils.py b/litellm/utils.pyindex d586962ba95..e8f40f72059 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -75,6 +75,7 @@ from litellm.constants import ()from litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.integrations.custom_logger import CustomLogger+from litellm.integrations.vector_stores.base_vector_store import BaseVectorStorefrom litellm.litellm_core_utils.core_helpers import (map_finish_reason,process_response_headers,@@ -523,9 +524,9 @@ def function_setup( # noqa: PLR0915function_id: Optional[str] = kwargs["id"] if "id" in kwargs else None## DYNAMIC CALLBACKS ##- dynamic_callbacks: Optional[- List[Union[str, Callable, CustomLogger]]- ] = kwargs.pop("callbacks", None)+ dynamic_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = (+ kwargs.pop("callbacks", None)+ )all_callbacks = get_dynamic_callbacks(dynamic_callbacks=dynamic_callbacks)if len(all_callbacks) > 0:@@ -1209,9 +1210,9 @@ def client(original_function): # noqa: PLR0915exception=e,retry_policy=kwargs.get("retry_policy"),)- kwargs[- "retry_policy"- ] = reset_retry_policy() # prevent infinite loops+ kwargs["retry_policy"] = (+ reset_retry_policy()+ ) # prevent infinite loopslitellm.num_retries = (None # set retries to None to prevent infinite loops)@@ -2754,16 +2755,16 @@ def get_optional_params( # noqa: PLR0915True # so that main.py adds the function call to the prompt)if "tools" in non_default_params:- optional_params[- "functions_unsupported_model"- ] = non_default_params.pop("tools")+ optional_params["functions_unsupported_model"] = (+ non_default_params.pop("tools")+ )non_default_params.pop("tool_choice", None) # causes ollama requests to hangelif "functions" in non_default_params:- optional_params[- "functions_unsupported_model"- ] = non_default_params.pop("functions")+ optional_params["functions_unsupported_model"] = (+ non_default_params.pop("functions")+ )elif (litellm.add_function_to_prompt): # if user opts to add it to prompt instead@@ -2786,10 +2787,10 @@ def get_optional_params( # noqa: PLR0915if "response_format" in non_default_params:if provider_config is not None:- non_default_params[- "response_format"- ] = provider_config.get_json_schema_from_pydantic_object(- response_format=non_default_params["response_format"]+ non_default_params["response_format"] = (+ provider_config.get_json_schema_from_pydantic_object(+ response_format=non_default_params["response_format"]+ ))else:non_default_params["response_format"] = type_to_response_format_param(@@ -3805,9 +3806,9 @@ def _count_characters(text: str) -> int:def get_response_string(response_obj: Union[ModelResponse, ModelResponseStream]) -> str:- _choices: Union[- List[Union[Choices, StreamingChoices]], List[StreamingChoices]- ] = response_obj.choices+ _choices: Union[List[Union[Choices, StreamingChoices]], List[StreamingChoices]] = (+ response_obj.choices+ )response_str = ""for choice in _choices:@@ -6481,6 +6482,18 @@ class ProviderConfigManager:return VertexAIFilesConfig()return None+ @staticmethod+ def get_provider_vector_store_config(+ provider: LlmProviders,+ ) -> Optional[CustomLogger]:+ from litellm.integrations.vector_stores.bedrock_vector_store import (+ BedrockVectorStore,+ )++ if LlmProviders.BEDROCK == provider:+ return BedrockVectorStore.get_initialized_custom_logger()+ return None+def get_end_user_id_for_cost_tracking(litellm_params: dict,diff --git a/litellm/vector_stores/vector_store_registry.py b/litellm/vector_stores/vector_store_registry.pynew file mode 100644index 00000000000..4f8be0b0e06--- /dev/null+++ b/litellm/vector_stores/vector_store_registry.py@@ -0,0 +1,211 @@+# litellm/proxy/vector_stores/vector_store_registry.py+import json+from datetime import datetime, timezone+from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast++from litellm._logging import verbose_logger+from litellm.types.vector_stores import (+ LiteLLM_ManagedVectorStore,+ LiteLLM_ManagedVectorStoreListResponse,+ LiteLLM_VectorStoreConfig,+)++if TYPE_CHECKING:+ from litellm.proxy.utils import PrismaClient+else:+ PrismaClient = Any+++class VectorStoreRegistry:+ def __init__(self, vector_stores: List[LiteLLM_ManagedVectorStore] = []):+ self.vector_stores: List[LiteLLM_ManagedVectorStore] = vector_stores+ self.vector_store_ids_to_vector_store_map: Dict[+ str, LiteLLM_ManagedVectorStore+ ] = {}++ def get_vector_store_ids_to_run(+ self, non_default_params: Dict, tools: Optional[List[Dict]] = None+ ) -> List[str]:+ """+ Returns the vector store ids to run++ vector_store_ids can be provided in two ways:+ """+ vector_store_ids: List[str] = []++ # 1. check if vector_store_ids is provided in the non_default_params+ vector_store_ids = non_default_params.get("vector_store_ids", None) or []++ # 2. check if vector_store_ids is provided as a tool in the request+ vector_store_ids = self._get_vector_store_ids_from_tool_calls(+ tools=tools, vector_store_ids=vector_store_ids+ )++ return vector_store_ids++ def pop_vector_store_ids_to_run(+ self, non_default_params: Dict, tools: Optional[List[Dict]] = None+ ) -> List[str]:+ """+ Pops the vector store ids from the non_default_params and tools+ """+ vector_store_ids: List[str] = []++ # 1. check if vector_store_ids is provided in the non_default_params+ vector_store_ids = non_default_params.pop("vector_store_ids", None) or []++ # 2. check if vector_store_ids is provided as a tool in the request+ vector_store_ids = self._get_vector_store_ids_from_tool_calls(+ tools=tools, vector_store_ids=vector_store_ids+ )+ return vector_store_ids++ def get_vector_store_to_run(+ self, non_default_params: Dict, tools: Optional[List[Dict]] = None+ ) -> Optional[LiteLLM_ManagedVectorStore]:+ """+ Returns the vector store to run++ vectore_stores can be run in two ways:+ 1. vector_store_ids is provided in the non_default_params+ 2. vector_store_ids is provided as a tool in the request+++ This will return the first vector store found in the registry.+ """+ vector_store_ids = self.get_vector_store_ids_to_run(+ non_default_params=non_default_params, tools=tools+ )++ # check if the vector store ids are in the registry+ if len(vector_store_ids) <= 0:+ return None++ for vector_store_id in vector_store_ids:+ for vector_store in self.vector_stores:+ if vector_store.get("vector_store_id") == vector_store_id:+ return vector_store+ return None++ def _get_vector_store_ids_from_tool_calls(+ self, tools: Optional[List[Dict]] = None, vector_store_ids: List[str] = []+ ) -> List[str]:+ """+ Returns the vector store ids from the tool calls+ """+ if tools:+ for tool in tools:+ if "vector_store_ids" in tool:+ vector_store_ids.extend(tool["vector_store_ids"])+ return vector_store_ids++ def load_vector_stores_from_config(self, vector_stores_config: List[Dict]):+ """+ Loads vector stores from the litellm proxy config.yaml+ """+ for vector_store_config in vector_stores_config:+ # cast to VectorStoreConfig+ litellm_vector_store_config = LiteLLM_VectorStoreConfig(+ **vector_store_config+ )+ vector_store_name = litellm_vector_store_config.get("vector_store_name")+ vector_store_litellm_params: Dict[str, Any] = (+ litellm_vector_store_config.get("litellm_params") or {}+ )++ vector_store_id = vector_store_litellm_params.get("vector_store_id")+ if vector_store_id is None:+ raise ValueError(+ f"vector_store_id is required for initializing vector store, got vector_store_id={vector_store_id}"+ )+ custom_llm_provider = vector_store_litellm_params.get("custom_llm_provider")+ if custom_llm_provider is None:+ raise ValueError(+ f"custom_llm_provider is required for initializing vector store, got custom_llm_provider={custom_llm_provider}"+ )++ litellm_managed_vector_store = LiteLLM_ManagedVectorStore(+ vector_store_id=vector_store_id,+ custom_llm_provider=custom_llm_provider,+ vector_store_name=vector_store_name,+ vector_store_description=vector_store_litellm_params.get(+ "vector_store_description"+ ),+ vector_store_metadata=vector_store_litellm_params.get(+ "vector_store_metadata"+ ),+ created_at=datetime.now(timezone.utc),+ updated_at=datetime.now(timezone.utc),+ )+ self.vector_stores.append(litellm_managed_vector_store)++ verbose_logger.debug(+ "all loaded vector stores = %s",+ json.dumps(self.vector_stores, indent=4, default=str),+ )++ def list_all_vector_stores(self) -> LiteLLM_ManagedVectorStoreListResponse:+ """+ List all vector stores in the required format++ Returns:+ LiteLLM_ManagedVectorStoreListResponse: A standardized response with vector store data+ """+ # Prepare the response+ response = LiteLLM_ManagedVectorStoreListResponse(+ object="list",+ data=self.vector_stores,+ total_count=len(self.vector_stores),+ current_page=1,+ total_pages=1,+ )++ return response++ def add_vector_store_to_registry(self, vector_store: LiteLLM_ManagedVectorStore):+ """+ Add a vector store to the registry++ Only add the vector store if it is not already in the registry+ """+ vector_store_id = vector_store.get("vector_store_id")+ for vector_store in self.vector_stores:+ if vector_store.get("vector_store_id") == vector_store_id:+ return+ self.vector_stores.append(cast(LiteLLM_ManagedVectorStore, vector_store))++ def delete_vector_store_from_registry(self, vector_store_id: str):+ """+ Delete a vector store from the registry+ """+ self.vector_stores = [+ vector_store+ for vector_store in self.vector_stores+ if vector_store.get("vector_store_id") != vector_store_id+ ]++ #########################################################+ ########### DB management helpers for vector stores ###########+ #########################################################++ @staticmethod+ async def _get_vector_stores_from_db(+ prisma_client: Optional[PrismaClient],+ ) -> List[LiteLLM_ManagedVectorStore]:+ """+ Get vector stores from the database+ """+ vector_stores_from_db: List[LiteLLM_ManagedVectorStore] = []+ if prisma_client is not None:+ _vector_stores_from_db = (+ await prisma_client.db.litellm_managedvectorstorestable.find_many(+ order={"created_at": "desc"},+ )+ )+ for vector_store in _vector_stores_from_db:+ _dict_vector_store = dict(vector_store)+ _litellm_managed_vector_store = LiteLLM_ManagedVectorStore(+ **_dict_vector_store+ )+ vector_stores_from_db.append(_litellm_managed_vector_store)+ return vector_stores_from_dbdiff --git a/tests/logging_callback_tests/test_bedrock_knowledgebase_hook.py b/tests/logging_callback_tests/test_bedrock_knowledgebase_hook.pyindex e41c6924a6d..2ec7848f3cd 100644--- a/tests/logging_callback_tests/test_bedrock_knowledgebase_hook.py+++ b/tests/logging_callback_tests/test_bedrock_knowledgebase_hook.py@@ -19,7 +19,7 @@ import pytestimport litellmfrom litellm import completionfrom litellm._logging import verbose_logger-from litellm.integrations.rag_hooks.bedrock_knowledgebase import BedrockKnowledgeBaseHook+from litellm.integrations.vector_stores.bedrock_vector_store import BedrockVectorStorefrom litellm.llms.custom_httpx.http_handler import HTTPHandler, AsyncHTTPHandlerfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.types.utils import StandardLoggingPayload, StandardLoggingVectorStoreRequest@@ -35,10 +35,24 @@ class TestCustomLogger(CustomLogger):pass+def setup_vector_store_registry():+ from litellm.vector_stores.vector_store_registry import VectorStoreRegistry, LiteLLM_ManagedVectorStore+ # Init vector store registry+ litellm.vector_store_registry = VectorStoreRegistry(+ vector_stores=[+ LiteLLM_ManagedVectorStore(+ vector_store_id="T37J8R4WTM",+ custom_llm_provider="bedrock"+ )+ ]+ )++@pytest.mark.asyncio-async def test_basic_bedrock_knowledgebase_retrieval():+async def test_basic_bedrock_knowledgebase_retrieval(setup_vector_store_registry):- bedrock_knowledgebase_hook = BedrockKnowledgeBaseHook()+ bedrock_knowledgebase_hook = BedrockVectorStore()response = await bedrock_knowledgebase_hook.make_bedrock_kb_retrieve_request(knowledge_base_id="T37J8R4WTM",query="what is litellm?",@@ -47,9 +61,10 @@ async def test_basic_bedrock_knowledgebase_retrieval():@pytest.mark.asyncio-async def test_e2e_bedrock_knowledgebase_retrieval_with_completion():+async def test_e2e_bedrock_knowledgebase_retrieval_with_completion(setup_vector_store_registry):litellm._turn_on_debug()client = AsyncHTTPHandler()+ print("value of litellm.vector_store_registry:", litellm.vector_store_registry)with patch.object(client, "post") as mock_post:# Mock the response for the LLM call@@ -88,18 +103,20 @@ async def test_e2e_bedrock_knowledgebase_retrieval_with_completion():# 2. the message with the context should have the bedrock knowledge base prefix string# this helps confirm that the context from the knowledge base was applied to the request- assert BedrockKnowledgeBaseHook.CONTENT_PREFIX_STRING in content[1]["text"]+ assert BedrockVectorStore.CONTENT_PREFIX_STRING in content[1]["text"]@pytest.mark.asyncio-async def test_e2e_bedrock_knowledgebase_retrieval_with_llm_api_call():+async def test_e2e_bedrock_knowledgebase_retrieval_with_llm_api_call(setup_vector_store_registry):"""Test that the Bedrock Knowledge Base Hook works when making a real llm api call"""++ # Init clientlitellm._turn_on_debug()async_client = AsyncHTTPHandler()- litellm.callbacks = [BedrockKnowledgeBaseHook()]+ litellm.callbacks = [BedrockVectorStore()]response = await litellm.acompletion(model="anthropic/claude-3-5-haiku-latest",messages=[{"role": "user", "content": "what is litellm?"}],@@ -112,11 +129,11 @@ async def test_e2e_bedrock_knowledgebase_retrieval_with_llm_api_call():@pytest.mark.asyncio-async def test_openai_with_knowledge_base_mock_openai():+async def test_openai_with_knowledge_base_mock_openai(setup_vector_store_registry):"""Tests that knowledge base content is correctly passed to the OpenAI API call"""- litellm.callbacks = [BedrockKnowledgeBaseHook()]+ litellm.callbacks = [BedrockVectorStore()]litellm.set_verbose = Truefrom openai import AsyncOpenAI@@ -154,16 +171,65 @@ async def test_openai_with_knowledge_base_mock_openai():# assert message[1] is the user message with the knowledge base contextassert messages[1]["role"] == "user"- assert BedrockKnowledgeBaseHook.CONTENT_PREFIX_STRING in messages[1]["content"]+ assert BedrockVectorStore.CONTENT_PREFIX_STRING in messages[1]["content"]+++async def test_openai_with_vector_store_ids_in_tool_call_mock_openai(setup_vector_store_registry):+ """+ Tests that vector store ids can be passed as tools++ This is the OpenAI format+ """+ litellm.callbacks = [BedrockVectorStore()]+ litellm.set_verbose = True+ from openai import AsyncOpenAI++ client = AsyncOpenAI(api_key="fake-api-key")++ with patch.object(+ client.chat.completions.with_raw_response, "create"+ ) as mock_client:+ try:+ await litellm.acompletion(+ model="gpt-4",+ messages=[{"role": "user", "content": "what is litellm?"}],+ tools=[{+ "type": "file_search",+ "vector_store_ids": ["T37J8R4WTM"]+ }],+ client=client,+ )+ except Exception as e:+ print(f"Error: {e}")++ # Verify the API was called+ mock_client.assert_called_once()+ request_body = mock_client.call_args.kwargs++ # Verify the request contains messages with knowledge base context+ assert "messages" in request_body+ messages = request_body["messages"]++ # We expect at least 2 messages:+ # 1. User message with the question+ # 2. User message with the knowledge base context+ assert len(messages) >= 2++ print("request messages:", json.dumps(messages, indent=4, default=str))++ # assert message[1] is the user message with the knowledge base context+ assert messages[1]["role"] == "user"+ assert BedrockVectorStore.CONTENT_PREFIX_STRING in messages[1]["content"]@pytest.mark.asyncio-async def test_logging_with_knowledge_base_hook():+async def test_logging_with_knowledge_base_hook(setup_vector_store_registry):"""Test that the knowledge base request was logged in standard logging payload"""test_custom_logger = TestCustomLogger()- litellm.callbacks = [BedrockKnowledgeBaseHook(), test_custom_logger]+ litellm.callbacks = [BedrockVectorStore(), test_custom_logger]litellm.set_verbose = Trueawait litellm.acompletion(model="gpt-4",@@ -210,3 +276,111 @@ async def test_logging_with_knowledge_base_hook():assert len(text_content) > 0+async def test_logging_with_knowledge_base_hook_no_vector_store_registry(setup_vector_store_registry):+ """+ Test that the knowledge base request was logged in standard logging payload+ """+ test_custom_logger = TestCustomLogger()+ litellm.callbacks = [BedrockVectorStore(), test_custom_logger]+ litellm.vector_store_registry = None+ await litellm.acompletion(+ model="gpt-4",+ messages=[{"role": "user", "content": "what is litellm?"}],+ )++++async def test_e2e_bedrock_knowledgebase_retrieval_without_vector_store_registry(setup_vector_store_registry):+ litellm._turn_on_debug()+ client = AsyncHTTPHandler()+ litellm.vector_store_registry = None++ with patch.object(client, "post") as mock_post:+ # Mock the response for the LLM call+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {"Content-Type": "application/json"}+ mock_response.json = lambda: json.loads(mock_response.text)+ mock_post.return_value = mock_response+ try:+ response = await litellm.acompletion(+ model="anthropic/claude-3.5-sonnet",+ messages=[{"role": "user", "content": "what is litellm?"}],+ vector_store_ids = [+ "T37J8R4WTM"+ ],+ client=client+ )+ except Exception as e:+ print(f"Error: {e}")++ # Verify the LLM request was made+ mock_post.assert_called_once()++ # Verify the request body+ print("call args:", mock_post.call_args)+ request_body = mock_post.call_args.kwargs["json"]+ print("Request body:", json.dumps(request_body, indent=4, default=str))++ # Assert content from the knowedge base was applied to the request++ # 1. we should have 1 content block, the first is the user message+ # There should only be one since there is no initialized vector store registry+ content = request_body["messages"][0]["content"]+ assert len(content) == 1+ assert content[0]["type"] == "text"++++++async def test_e2e_bedrock_knowledgebase_retrieval_with_vector_store_not_in_registry(setup_vector_store_registry):+ """+ No vector store request is made for vector store ids that are not in the registry++ In this test newUnknownVectorStoreId is not in the registry, so no vector store request is made+ """+ litellm._turn_on_debug()+ client = AsyncHTTPHandler()++ print("Registry iniitalized:", litellm.vector_store_registry.vector_stores)+++ with patch.object(client, "post") as mock_post:+ # Mock the response for the LLM call+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {"Content-Type": "application/json"}+ mock_response.json = lambda: json.loads(mock_response.text)+ mock_post.return_value = mock_response+ try:+ response = await litellm.acompletion(+ model="anthropic/claude-3.5-sonnet",+ messages=[{"role": "user", "content": "what is litellm?"}],+ vector_store_ids = [+ "newUnknownVectorStoreId"+ ],+ client=client+ )+ except Exception as e:+ print(f"Error: {e}")++ # Verify the LLM request was made+ mock_post.assert_called_once()++ # Verify the request body+ print("call args:", mock_post.call_args)+ request_body = mock_post.call_args.kwargs["json"]+ print("Request body:", json.dumps(request_body, indent=4, default=str))++ # Assert content from the knowedge base was applied to the request++ # 1. we should have 1 content block, the first is the user message+ # There should only be one since there is no initialized vector store registry+ content = request_body["messages"][0]["content"]+ assert len(content) == 1+ assert content[0]["type"] == "text"+diff --git a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py b/tests/logging_callback_tests/test_unit_tests_init_callbacks.pyindex 025f0008596..0239ab7f51e 100644--- a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py+++ b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py@@ -34,7 +34,7 @@ from litellm.integrations.opentelemetry import OpenTelemetryfrom litellm.integrations.mlflow import MlflowLoggerfrom litellm.integrations.argilla import ArgillaLoggerfrom litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHook-from litellm.integrations.rag_hooks.bedrock_knowledgebase import BedrockKnowledgeBaseHook+from litellm.integrations.vector_stores.bedrock_vector_store import BedrockVectorStorefrom litellm.integrations.langfuse.langfuse_prompt_management import (LangfusePromptManagement,)@@ -78,7 +78,7 @@ callback_class_str_to_classType = {"gcs_pubsub": GcsPubSubLogger,"anthropic_cache_control_hook": AnthropicCacheControlHook,"agentops": AgentOps,- "bedrock_knowledgebase_hook": BedrockKnowledgeBaseHook,+ "bedrock_vector_store": BedrockVectorStore,}expected_env_vars = {diff --git a/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsx b/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsxindex 2db6a30941f..1e9b5024c41 100644--- a/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsx+++ b/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreForm.tsx@@ -53,6 +53,7 @@ const VectorStoreForm: React.FC<VectorStoreFormProps> = ({vector_store_name: formValues.vector_store_name,vector_store_description: formValues.vector_store_description,vector_store_metadata: metadata,+ litellm_credential_name: formValues.litellm_credential_name,});message.success("Vector store created successfully");form.resetFields();