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
Merge remote-tracking branch 'origin/main' into litellm_bedrock_rag_retrieval_filter
mateo-berrif22c7d274a99
diff --cc litellm/rag/main.pyindex eacfffba9ec,1f63152632e..1a5301f0579--- a/litellm/rag/main.py+++ b/litellm/rag/main.py@@@ -223,8 -245,20 +245,25 @@@ async def _execute_query_pipelineraise ValueError("No query found in messages for RAG query")# 2. Search vector store- kwargs_filters: Final = kwargs.pop("filters", None)- filters: Final = retrieval_config.get("retrieval_filter") or retrieval_config.get("filters") or kwargs_filters++ top_level_filters: Final = kwargs.pop("filters", None)++ filters: Final = retrieval_config.get("retrieval_filter") or retrieval_config.get("filters") or top_level_filters++ filter_search_params: Final = MappingProxyType({"filters": filters} if filters else {})+ # Forward allowlisted provider retrieval_config extras (region, embedding+ # model, bucket, credential refs) to the search call; the managed store's+ # params win on conflict.+ provider_search_params: Final = MappingProxyType(+ {k: v for k, v in retrieval_config.items() if k in _FORWARDABLE_RETRIEVAL_CONFIG_KEYS}+ )+ store_search_params: Final = MappingProxyType(+ {+ k: v+ for k, v in (vector_store_params.items() if vector_store_params else ())+ if k not in _SEARCH_ARGS_SET_BY_PIPELINE+ }+ )- forwarded_search_params: Final = MappingProxyType({**provider_search_params, **kwargs, **store_search_params})++ forwarded_search_params: Final = MappingProxyType(++ {**provider_search_params, **kwargs, **filter_search_params, **store_search_params}++ )with _suppressed_sub_call_billing():search_response: Final = await litellm.vector_stores.asearch(vector_store_id=retrieval_config["vector_store_id"],diff --cc tests/test_litellm/rag/test_main.pyindex ab0a9c0f002,264bcd6fb75..54748efb480--- a/tests/test_litellm/rag/test_main.py+++ b/tests/test_litellm/rag/test_main.py@@@ -258,86 -259,201 +263,281 @@@ async def test_aquery_streaming_bills_sassert standard_logging_object["response_cost"] >= 0.003+ ("retrieval_config_json", "top_level_filter_json", "expected_filter_json"),+ (+ (+ '{"vector_store_id":"vs_test_123","custom_llm_provider":"openai","top_k":50,'+ '"retrieval_filter":{"equals":{"key":"tenant","value":"retrieval"}}}',+ None,+ '{"equals":{"key":"tenant","value":"retrieval"}}',+ ),+ (+ '{"vector_store_id":"vs_test_123","custom_llm_provider":"openai","top_k":50,'+ '"filters":{"equals":{"key":"tenant","value":"alias"}}}',+ None,+ '{"equals":{"key":"tenant","value":"alias"}}',+ ),+ (+ '{"vector_store_id":"vs_test_123","custom_llm_provider":"openai","top_k":50}',+ '{"equals":{"key":"tenant","value":"top-level"}}',+ '{"equals":{"key":"tenant","value":"top-level"}}',+ ),+ (+ '{"vector_store_id":"vs_test_123","custom_llm_provider":"openai","top_k":50,'+ '"retrieval_filter":{"equals":{"key":"tenant","value":"retrieval"}},'+ '"filters":{"equals":{"key":"tenant","value":"alias"}}}',+ '{"equals":{"key":"tenant","value":"top-level"}}',+ '{"equals":{"key":"tenant","value":"retrieval"}}',+ ),+ (+ '{"vector_store_id":"vs_test_123","custom_llm_provider":"openai","top_k":50}',+ None,+ None,+ ),+ ),+)+async def test_aquery_forwards_filters_to_vector_store_search(+ retrieval_config_json: str,+ top_level_filter_json: str | None,+ expected_filter_json: str | None,+ monkeypatch,+):+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ retrieval_config: Final = json.loads(retrieval_config_json)+ top_level_filter: Final = json.loads(top_level_filter_json) if top_level_filter_json is not None else None+ expected_filter: Final = json.loads(expected_filter_json) if expected_filter_json is not None else None++ with respx.mock(assert_all_called=True) as respx_mock:+ search_route: Final = respx_mock.post("https://example.com/v1/vector_stores/vs_test_123/search").mock(+ return_value=httpx.Response(+ 200,+ content='{"object":"vector_store.search_results.page","search_query":"q","data":[]}',+ )+ )+ respx_mock.post("https://example.com/v1/chat/completions").mock(+ return_value=httpx.Response(+ 200,+ content=(+ '{"id":"chatcmpl-test","object":"chat.completion","created":1,"model":"gpt-4o-mini",'+ '"choices":[{"index":0,"message":{"role":"assistant","content":"answer"},"finish_reason":"stop"}],'+ '"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}'+ ),+ )+ )+ response: Final = await litellm.aquery(+ model="openai/gpt-4o-mini",+ messages=json.loads('[{"role":"user","content":"most frequent causes of low nicotine"}]'),+ retrieval_config=retrieval_config,+ filters=top_level_filter,+ api_key="sk-test",+ api_base="https://example.com/v1",+ )+ request_body: Final = json.loads(search_route.calls.last.request.content)++ assert isinstance(response, ModelResponse)+ assert response.choices[0].message.content == "answer"+ assert request_body["query"] == "most frequent causes of low nicotine"- assert request_body["filters"] == expected_filter++ assert request_body.get("filters") == expected_filter+ assert request_body["max_num_results"] == 50+++ @pytest.mark.asyncio+ async def test_aquery_forwards_provider_retrieval_config_and_router_to_search():+ """+ Regression: provider-specific retrieval_config keys (aws_region_name,+ embedding_model, vector_bucket_name, ...) and the router must be forwarded+ to the vector store search call. Pre-fix they were silently dropped, so+ /v1/rag/query failed with provider config errors (e.g. S3 Vectors+ "aws_region_name is required") even when the caller supplied them.+ """+ from unittest.mock import AsyncMock++ from litellm.types.vector_stores import VectorStoreSearchResponse++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4o-mini",+ "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "test-key"},+ }+ ]+ )++ fake_search = AsyncMock(+ return_value=VectorStoreSearchResponse(+ object="vector_store.search_results.page", search_query="q", data=[]+ )+ )+ with patch("litellm.vector_stores.asearch", new=fake_search): # test-quality-ok: asearch is the boundary the forwarding contract under test targets+ response = await litellm.aquery(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hello"}],+ retrieval_config={+ "vector_store_id": "bkt:idx",+ "custom_llm_provider": "s3_vectors",+ "top_k": 5,+ "aws_region_name": "eu-west-1",+ "embedding_model": "my-embed",+ "vector_bucket_name": "bkt",+ },+ router=router,+ mock_response="hi",+ )++ assert isinstance(response, ModelResponse)+ fake_search.assert_awaited_once()+ search_kwargs = fake_search.await_args.kwargs+ assert search_kwargs["vector_store_id"] == "bkt:idx"+ assert search_kwargs["custom_llm_provider"] == "s3_vectors"+ assert search_kwargs["max_num_results"] == 5+ assert search_kwargs["router"] is router+ # provider-specific extras forwarded+ assert search_kwargs["aws_region_name"] == "eu-west-1"+ assert search_kwargs["embedding_model"] == "my-embed"+ assert search_kwargs["vector_bucket_name"] == "bkt"+ # consumed keys are not duplicated into the spread+ assert "top_k" not in search_kwargs+++ @pytest.mark.asyncio+ async def test_aquery_minimal_retrieval_config_forwards_no_extras():+ """+ A minimal retrieval_config must not leak consumed keys (or invent extras)+ into the vector store search call.+ """+ from unittest.mock import AsyncMock++ from litellm.types.vector_stores import VectorStoreSearchResponse++ fake_search = AsyncMock(+ return_value=VectorStoreSearchResponse(+ object="vector_store.search_results.page", search_query="q", data=[]+ )+ )+ with patch("litellm.vector_stores.asearch", new=fake_search): # test-quality-ok: asearch is the boundary the forwarding contract under test targets+ await litellm.aquery(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hello"}],+ retrieval_config={"vector_store_id": "vs_test_123", "custom_llm_provider": "openai"},+ mock_response="hi",+ )++ fake_search.assert_awaited_once()+ search_kwargs = fake_search.await_args.kwargs+ assert search_kwargs["vector_store_id"] == "vs_test_123"+ assert search_kwargs["custom_llm_provider"] == "openai"+ assert search_kwargs["router"] is None+ leaked = {"top_k", "filters", "retrieval_filter", "aws_region_name", "embedding_model", "vector_bucket_name"}+ assert not (leaked & set(search_kwargs.keys()))+++ @pytest.mark.asyncio+ async def test_aquery_does_not_forward_connection_override_keys_to_search():+ """+ Only allowlisted retrieval_config keys may reach the vector store search+ call. Caller-controlled connection overrides (api_base, api_key, arbitrary+ extras) must be dropped, otherwise a caller could redirect store+ credentials to an attacker-chosen host.+ """+ from unittest.mock import AsyncMock++ from litellm.types.vector_stores import VectorStoreSearchResponse++ fake_search = AsyncMock(+ return_value=VectorStoreSearchResponse(+ object="vector_store.search_results.page", search_query="q", data=[]+ )+ )+ with patch("litellm.vector_stores.asearch", new=fake_search): # test-quality-ok: asearch is the boundary the forwarding contract under test targets+ await litellm.aquery(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hello"}],+ retrieval_config={+ "vector_store_id": "bkt:idx",+ "custom_llm_provider": "s3_vectors",+ "aws_region_name": "eu-west-1",+ "api_base": "https://attacker.example.com",+ "api_key": "attacker-key",+ "arbitrary_extra": "nope",+ },+ mock_response="hi",+ )++ fake_search.assert_awaited_once()+ search_kwargs = fake_search.await_args.kwargs+ assert search_kwargs["aws_region_name"] == "eu-west-1"+ blocked = {"api_base", "api_key", "arbitrary_extra"}+ assert not (blocked & set(search_kwargs.keys()))+++ @pytest.mark.asyncio+ async def test_aquery_forwards_vector_store_params_to_search_but_not_completion():+ """+ Regression for LIT-6773: the server-trusted vector_store_params (a managed+ store's litellm_params) must reach the search call wholesale, including the+ connection keys the caller allowlist blocks, while the caller's own+ retrieval_config overrides stay blocked, the caller's top-level api_key and+ api_base stay on the completion only, and the completion never inherits the+ store's connection params.+ """+ from unittest.mock import AsyncMock++ from litellm.types.vector_stores import VectorStoreSearchResponse++ fake_search = AsyncMock(+ return_value=VectorStoreSearchResponse(+ object="vector_store.search_results.page", search_query="q", data=[]+ )+ )+ fake_completion = AsyncMock(+ return_value=ModelResponse(+ id="chatcmpl-test",+ choices=[{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],+ model="gpt-4o-mini",+ )+ )+ with (+ patch("litellm.vector_stores.asearch", new=fake_search), # test-quality-ok: the search boundary under test+ patch("litellm.acompletion", new=fake_completion), # test-quality-ok: the completion boundary under test+ ):+ await litellm.aquery(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hello"}],+ api_key="sk-llm-key",+ api_base="https://llm.example.com",+ retrieval_config={+ "vector_store_id": "customer_kb",+ "custom_llm_provider": "milvus",+ "api_base": "https://attacker.example.com",+ "api_key": "attacker-key",+ },+ vector_store_params={+ "vector_store_id": "customer_kb",+ "custom_llm_provider": "milvus",+ "api_base": "http://127.0.0.1:19530",+ "api_key": "root:Milvus",+ "milvus_text_field": "book_intro_text",+ "outputFields": ["book_intro_text"],+ },+ )++ fake_search.assert_awaited_once()+ search_kwargs = fake_search.await_args.kwargs+ assert search_kwargs["vector_store_id"] == "customer_kb"+ assert search_kwargs["custom_llm_provider"] == "milvus"+ assert search_kwargs["api_base"] == "http://127.0.0.1:19530"+ assert search_kwargs["api_key"] == "root:Milvus"+ assert search_kwargs["milvus_text_field"] == "book_intro_text"+ assert search_kwargs["outputFields"] == ["book_intro_text"]+ fake_completion.assert_awaited_once()+ completion_kwargs = fake_completion.await_args.kwargs+ assert completion_kwargs["api_key"] == "sk-llm-key"+ assert completion_kwargs["api_base"] == "https://llm.example.com"+ assert not ({"milvus_text_field", "outputFields"} & set(completion_kwargs))++def test_rag_call_types_are_registered():"""query/aquery/ingest/aingest are @client-decorated entry points, so their