Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

[Refactor] Use Existing config structure for bedrock vector stores (#12672)

Ishaan Jaff37b681440071
diff --git a/litellm/llms/base_llm/vector_store/transformation.py b/litellm/llms/base_llm/vector_store/transformation.py
index 95b78ab12b2..e2edc75013f 100644
--- a/litellm/llms/base_llm/vector_store/transformation.py
+++ b/litellm/llms/base_llm/vector_store/transformation.py
@@ -85,3 +85,19 @@ class BaseVectorStoreConfig:
headers=headers,
)
+ def sign_request(
+ self,
+ headers: dict,
+ optional_params: Dict,
+ request_data: Dict,
+ api_base: str,
+ api_key: Optional[str] = None,
+ ) -> Tuple[dict, Optional[bytes]]:
+ """Optionally sign or modify the request before sending.
+
+ Providers like AWS Bedrock require SigV4 signing. Providers that don't
+ require any signing can simply return the headers unchanged and ``None``
+ for the signed body.
+ """
+ return headers, None
+
diff --git a/litellm/llms/bedrock/vector_stores/transformation.py b/litellm/llms/bedrock/vector_stores/transformation.py
new file mode 100644
index 00000000000..a0519bd4da2
--- /dev/null
+++ b/litellm/llms/bedrock/vector_stores/transformation.py
@@ -0,0 +1,198 @@
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+from urllib.parse import urlparse
+
+import httpx
+
+from litellm.llms.base_llm.vector_store.transformation import BaseVectorStoreConfig
+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
+from litellm.types.integrations.rag.bedrock_knowledgebase import (
+ BedrockKBContent,
+ BedrockKBResponse,
+ BedrockKBRetrievalConfiguration,
+ BedrockKBRetrievalQuery,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.vector_stores import (
+ VectorStoreResultContent,
+ VectorStoreSearchOptionalRequestParams,
+ VectorStoreSearchResponse,
+ VectorStoreSearchResult,
+)
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+
+
+class BedrockVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM):
+ """Vector store configuration for AWS Bedrock Knowledge Bases."""
+
+ def __init__(self) -> None:
+ BaseVectorStoreConfig.__init__(self)
+ BaseAWSLLM.__init__(self)
+
+ def validate_environment(
+ self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]
+ ) -> dict:
+ headers = headers or {}
+ headers.setdefault("Content-Type", "application/json")
+ return headers
+
+ def get_complete_url(
+ self, api_base: Optional[str], litellm_params: dict
+ ) -> str:
+ aws_region_name = litellm_params.get("aws_region_name")
+ endpoint_url, _ = self.get_runtime_endpoint(
+ api_base=api_base,
+ aws_bedrock_runtime_endpoint=litellm_params.get("aws_bedrock_runtime_endpoint"),
+ aws_region_name=self.get_aws_region_name_for_non_llm_api_calls(
+ aws_region_name=aws_region_name
+ ),
+ endpoint_type="agent",
+ )
+ return f"{endpoint_url}/knowledgebases"
+
+ 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]:
+ if isinstance(query, list):
+ query = " ".join(query)
+
+ url = f"{api_base}/{vector_store_id}/retrieve"
+
+ request_body: Dict[str, Any] = {
+ "retrievalQuery": BedrockKBRetrievalQuery(text=query),
+ }
+
+ retrieval_config: Dict[str, Any] = {}
+ max_results = vector_store_search_optional_params.get("max_num_results")
+ if max_results is not None:
+ retrieval_config.setdefault("vectorSearchConfiguration", {})[
+ "numberOfResults"
+ ] = max_results
+ filters = vector_store_search_optional_params.get("filters")
+ if filters is not None:
+ retrieval_config.setdefault("vectorSearchConfiguration", {})[
+ "filter"
+ ] = filters
+ if retrieval_config:
+ request_body["retrievalConfiguration"] = BedrockKBRetrievalConfiguration(
+ **retrieval_config
+ )
+
+ litellm_logging_obj.model_call_details["query"] = query
+ return url, request_body
+
+ def sign_request(
+ self,
+ headers: dict,
+ optional_params: Dict,
+ request_data: Dict,
+ api_base: str,
+ api_key: Optional[str] = None,
+ ) -> Tuple[dict, Optional[bytes]]:
+ return self._sign_request(
+ service_name="bedrock",
+ headers=headers,
+ optional_params=optional_params,
+ request_data=request_data,
+ api_base=api_base,
+ api_key=api_key,
+ )
+
+ def _get_file_id_from_metadata(self, metadata: Dict[str, Any]) -> str:
+ """
+ Extract file_id from Bedrock KB metadata.
+ Uses source URI if available, otherwise generates a fallback ID.
+ """
+ source_uri = metadata.get("x-amz-bedrock-kb-source-uri", "") if metadata else ""
+ if source_uri:
+ return source_uri
+
+ chunk_id = metadata.get("x-amz-bedrock-kb-chunk-id", "unknown") if metadata else "unknown"
+ return f"bedrock-kb-{chunk_id}"
+
+ def _get_filename_from_metadata(self, metadata: Dict[str, Any]) -> str:
+ """
+ Extract filename from Bedrock KB metadata.
+ Tries to extract filename from source URI, falls back to domain name or data source ID.
+ """
+ source_uri = metadata.get("x-amz-bedrock-kb-source-uri", "") if metadata else ""
+
+ if source_uri:
+ try:
+ parsed_uri = urlparse(source_uri)
+ filename = parsed_uri.path.split('/')[-1] if parsed_uri.path and parsed_uri.path != '/' else parsed_uri.netloc
+ if not filename or filename == '/':
+ filename = parsed_uri.netloc
+ return filename
+ except Exception:
+ return source_uri
+
+ data_source_id = metadata.get("x-amz-bedrock-kb-data-source-id", "unknown") if metadata else "unknown"
+ return f"bedrock-kb-document-{data_source_id}"
+
+ def _get_attributes_from_metadata(self, metadata: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Extract all attributes from Bedrock KB metadata.
+ Returns a copy of the metadata dictionary.
+ """
+ if not metadata:
+ return {}
+ return dict(metadata)
+
+ def transform_search_vector_store_response(
+ self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj
+ ) -> VectorStoreSearchResponse:
+ try:
+ response_data = BedrockKBResponse(**response.json())
+ results: List[VectorStoreSearchResult] = []
+ for item in response_data.get("retrievalResults", []) or []:
+ content: Optional[BedrockKBContent] = item.get("content")
+ text = content.get("text") if content else None
+ if text is None:
+ continue
+
+ # Extract metadata and use helper functions
+ metadata = item.get("metadata", {}) or {}
+ file_id = self._get_file_id_from_metadata(metadata)
+ filename = self._get_filename_from_metadata(metadata)
+ attributes = self._get_attributes_from_metadata(metadata)
+
+ results.append(
+ VectorStoreSearchResult(
+ score=item.get("score"),
+ content=[VectorStoreResultContent(text=text, type="text")],
+ file_id=file_id,
+ filename=filename,
+ attributes=attributes,
+ )
+ )
+ return VectorStoreSearchResponse(
+ object="vector_store.search_results.page",
+ search_query=litellm_logging_obj.model_call_details.get("query", ""),
+ data=results,
+ )
+ except Exception as e:
+ raise self.get_error_class(
+ error_message=str(e),
+ status_code=response.status_code,
+ headers=response.headers,
+ )
+
+ # Vector store creation is not yet implemented
+ def transform_create_vector_store_request(
+ self,
+ vector_store_create_optional_params,
+ api_base: str,
+ ) -> Tuple[str, Dict]:
+ raise NotImplementedError
+
+ def transform_create_vector_store_response(self, response: httpx.Response):
+ raise NotImplementedError
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 2481e93d061..a6ed6513c17 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -2702,6 +2702,14 @@ class BaseLLMHTTPHandler:
litellm_logging_obj=logging_obj,
)
)
+ all_optional_params: Dict[str, Any] = dict(litellm_params)
+ all_optional_params.update(vector_store_search_optional_params or {})
+ headers, signed_json_body = vector_store_provider_config.sign_request(
+ headers=headers,
+ optional_params=all_optional_params,
+ request_data=request_body,
+ api_base=url,
+ )
logging_obj.pre_call(
input="",
@@ -2713,9 +2721,14 @@ class BaseLLMHTTPHandler:
},
)
+ request_body = json.dumps(request_body) if signed_json_body is None else signed_json_body
+
try:
response = await async_httpx_client.post(
- url=url, headers=headers, json=request_body, timeout=timeout
+ url=url,
+ headers=headers,
+ data=request_body,
+ timeout=timeout,
)
except Exception as e:
raise self._handle_error(e=e, provider_config=vector_store_provider_config)
@@ -2786,6 +2799,16 @@ class BaseLLMHTTPHandler:
)
)
+ all_optional_params: Dict[str, Any] = dict(litellm_params)
+ all_optional_params.update(vector_store_search_optional_params or {})
+
+ headers, signed_json_body = vector_store_provider_config.sign_request(
+ headers=headers,
+ optional_params=all_optional_params,
+ request_data=request_body,
+ api_base=url,
+ )
+
logging_obj.pre_call(
input="",
api_key="",
@@ -2796,9 +2819,13 @@ class BaseLLMHTTPHandler:
},
)
+ request_body = json.dumps(request_body) if signed_json_body is None else signed_json_body
+
try:
response = sync_httpx_client.post(
- url=url, headers=headers, json=request_body
+ url=url,
+ headers=headers,
+ data=request_body,
)
except Exception as e:
raise self._handle_error(e=e, provider_config=vector_store_provider_config)
diff --git a/litellm/utils.py b/litellm/utils.py
index f92d14b5dd7..3a26c3f0713 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -7101,6 +7101,12 @@ class ProviderConfigManager:
)
return VertexVectorStoreConfig()
+ elif litellm.LlmProviders.BEDROCK == provider:
+ from litellm.llms.bedrock.vector_stores.transformation import (
+ BedrockVectorStoreConfig,
+ )
+
+ return BedrockVectorStoreConfig()
elif litellm.LlmProviders.PG_VECTOR == provider:
from litellm.llms.pg_vector.vector_stores.transformation import (
PGVectorStoreConfig,
diff --git a/tests/test_litellm/llms/bedrock/vector_stores/test_bedrock_vector_store_transformation.py b/tests/test_litellm/llms/bedrock/vector_stores/test_bedrock_vector_store_transformation.py
new file mode 100644
index 00000000000..e924fe83bb8
--- /dev/null
+++ b/tests/test_litellm/llms/bedrock/vector_stores/test_bedrock_vector_store_transformation.py
@@ -0,0 +1,26 @@
+from unittest.mock import MagicMock
+
+from litellm.llms.bedrock.vector_stores.transformation import BedrockVectorStoreConfig
+
+
+def test_transform_search_request():
+ """
+ Test that BedrockVectorStoreConfig correctly transforms search vector store requests.
+
+ Verifies that the transformation creates the proper URL endpoint and request body
+ with the expected retrievalQuery structure.
+ """
+ config = BedrockVectorStoreConfig()
+ mock_log = MagicMock()
+ mock_log.model_call_details = {}
+
+ url, body = config.transform_search_vector_store_request(
+ vector_store_id="kb123",
+ query="hello",
+ vector_store_search_optional_params={},
+ api_base="https://bedrock-agent-runtime.us-west-2.amazonaws.com/knowledgebases",
+ litellm_logging_obj=mock_log,
+ )
+
+ assert url.endswith("/kb123/retrieve")
+ assert body["retrievalQuery"].get("text") == "hello"
\ No newline at end of file
diff --git a/tests/vector_store_tests/test_bedrock_vector_store.py b/tests/vector_store_tests/test_bedrock_vector_store.py
new file mode 100644
index 00000000000..98ea070667c
--- /dev/null
+++ b/tests/vector_store_tests/test_bedrock_vector_store.py
@@ -0,0 +1,101 @@
+"""
+Test Bedrock Vector Store helper functions and transformation.
+"""
+import pytest
+from unittest.mock import Mock
+import httpx
+
+from tests.vector_store_tests.base_vector_store_test import BaseVectorStoreTest
+from litellm.llms.bedrock.vector_stores.transformation import BedrockVectorStoreConfig
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+
+
+class TestBedrockVectorStore(BaseVectorStoreTest):
+ """
+ Test the Bedrock vector store transformation functionality.
+ """
+
+ 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": "T37J8R4WTM",
+ "custom_llm_provider": "bedrock",
+ "query": "what happens after we add a model"
+ }
+
+ def test_get_file_id_from_metadata(self):
+ """Test that file_id is correctly extracted from metadata."""
+ config = BedrockVectorStoreConfig()
+
+ # Test with source URI
+ metadata_with_uri = {
+ "x-amz-bedrock-kb-source-uri": "https://www.litellm.ai",
+ "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co"
+ }
+ file_id = config._get_file_id_from_metadata(metadata_with_uri)
+ assert file_id == "https://www.litellm.ai"
+
+ # Test without source URI but with chunk ID
+ metadata_without_uri = {
+ "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co"
+ }
+ file_id = config._get_file_id_from_metadata(metadata_without_uri)
+ assert file_id == "bedrock-kb-1%3A0%3AjNYPg5YByRuP5PdK96co"
+
+ # Test with empty metadata
+ file_id = config._get_file_id_from_metadata({})
+ assert file_id == "bedrock-kb-unknown"
+
+ def test_get_filename_from_metadata(self):
+ """Test that filename is correctly extracted from metadata."""
+ config = BedrockVectorStoreConfig()
+
+ # Test with source URI containing path
+ metadata_with_path = {
+ "x-amz-bedrock-kb-source-uri": "https://docs.litellm.ai/tutorial/setup.html"
+ }
+ filename = config._get_filename_from_metadata(metadata_with_path)
+ assert filename == "setup.html"
+
+ # Test with source URI without path (domain only)
+ metadata_domain_only = {
+ "x-amz-bedrock-kb-source-uri": "https://www.litellm.ai"
+ }
+ filename = config._get_filename_from_metadata(metadata_domain_only)
+ assert filename == "www.litellm.ai"
+
+ # Test without source URI but with data source ID
+ metadata_without_uri = {
+ "x-amz-bedrock-kb-data-source-id": "CCEJIRXXFI"
+ }
+ filename = config._get_filename_from_metadata(metadata_without_uri)
+ assert filename == "bedrock-kb-document-CCEJIRXXFI"
+
+ # Test with empty metadata
+ filename = config._get_filename_from_metadata({})
+ assert filename == "bedrock-kb-document-unknown"
+
+ def test_get_attributes_from_metadata(self):
+ """Test that attributes are correctly extracted from metadata."""
+ config = BedrockVectorStoreConfig()
+
+ # Test with full metadata
+ metadata = {
+ "x-amz-bedrock-kb-source-uri": "https://www.litellm.ai",
+ "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co",
+ "x-amz-bedrock-kb-data-source-id": "CCEJIRXXFI"
+ }
+ attributes = config._get_attributes_from_metadata(metadata)
+ assert attributes == metadata
+ assert attributes is not metadata # Should be a copy
+
+ # Test with empty metadata
+ attributes = config._get_attributes_from_metadata({})
+ assert attributes == {}
+
+ # Test with None
+ attributes = config._get_attributes_from_metadata(None)
+ assert attributes == {}
\ No newline at end of file