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
fix double-billing issue
Sameer Kankute32ded9b2f8f9
diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.pyindex 12e36fccde9..dc14937d46b 100644--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py@@ -66,23 +66,6 @@ else:PrismaClient = Any-async def get_managed_vector_store_rows_by_uuids(- uuids: List[str],- prisma_client: Any,-) -> List[Any]:- """- Fetch managed vector store rows by their internal UUIDs.-- Standalone helper following the same pattern as get_team_object /- get_key_object so that callers on the hot request path use a named,- importable function rather than an inline prisma_client.db.* call.- """- return await prisma_client.db.litellm_managedvectorstorestable.find_many(- where={"vector_store_id": {"in": uuids}},- take=len(uuids),- )--class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):# Class variables or attributesdef __init__(@@ -773,7 +756,14 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):from litellm.llms.base_llm.managed_resources.utils import (extract_unified_uuid_from_unified_id,)- from litellm.proxy.proxy_server import prisma_client+ from litellm.proxy.auth.auth_checks import (+ get_managed_vector_store_rows_by_uuids,+ )+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ )if not vector_store_ids or prisma_client is None:return@@ -791,6 +781,8 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):rows = await get_managed_vector_store_rows_by_uuids(uuids=list(uuid_to_unified.keys()),prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,)found_uuids = {row.vector_store_id for row in rows}diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex d31a13e8bc6..00f5ea10cf2 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -38,6 +38,7 @@ from litellm.proxy._types import (LiteLLM_EndUserTable,Litellm_EntityType,LiteLLM_JWTAuth,+ LiteLLM_ManagedVectorStoresTable,LiteLLM_ObjectPermissionTable,LiteLLM_OrganizationMembershipTable,LiteLLM_OrganizationTable,@@ -2279,6 +2280,71 @@ async def get_object_permission(return None+@log_db_metrics+async def get_managed_vector_store_rows_by_uuids(+ uuids: List[str],+ prisma_client: Optional[PrismaClient],+ user_api_key_cache: DualCache,+ parent_otel_span: Optional[Span] = None,+ proxy_logging_obj: Optional[ProxyLogging] = None,+) -> List[LiteLLM_ManagedVectorStoresTable]:+ """+ Fetch managed vector store rows by their internal UUIDs.++ Follows the get_team_object / get_key_object / get_object_permission pattern:+ cache-first lookup (in-memory / Redis), DB fallback only on cache miss.+ Critical-path DB access must go through this helper to avoid raw Prisma+ calls on the hot request path.+ """+ if not uuids or prisma_client is None:+ return []++ result: List[LiteLLM_ManagedVectorStoresTable] = []+ cache_misses: List[str] = []++ for uuid in uuids:+ key = "managed_vector_store_id:{}".format(uuid)+ cached = await user_api_key_cache.async_get_cache(key=key)+ if cached is not None:+ if isinstance(cached, dict):+ result.append(LiteLLM_ManagedVectorStoresTable(**cached))+ elif isinstance(cached, LiteLLM_ManagedVectorStoresTable):+ result.append(cached)+ else:+ cache_misses.append(uuid)+ else:+ cache_misses.append(uuid)++ if not cache_misses:+ return result++ rows = await prisma_client.db.litellm_managedvectorstorestable.find_many(+ where={"vector_store_id": {"in": cache_misses}},+ take=len(cache_misses),+ )++ for row in rows:+ row_dict = (+ row.model_dump()+ if hasattr(row, "model_dump")+ else (row.dict() if hasattr(row, "dict") else None)+ )+ if not isinstance(row_dict, dict) or not row_dict:+ row_dict = dict(row) if hasattr(row, "__dict__") else {}+ if not row_dict:+ continue+ cached_obj = LiteLLM_ManagedVectorStoresTable(**row_dict)+ key = "managed_vector_store_id:{}".format(cached_obj.vector_store_id)+ await user_api_key_cache.async_set_cache(+ key=key,+ value=row_dict,+ ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,+ )+ result.append(cached_obj)++ return result++@log_db_metricsasync def get_org_object(org_id: str,diff --git a/litellm/responses/file_search/emulated_handler.py b/litellm/responses/file_search/emulated_handler.pyindex 70f38e63a69..f770648e639 100644--- a/litellm/responses/file_search/emulated_handler.py+++ b/litellm/responses/file_search/emulated_handler.py@@ -406,14 +406,15 @@ async def aresponses_with_emulated_file_search(transformed_tools, all_vs_ids = _replace_file_search_tools(tools)# 2. First provider call — provider will call the file_search function.- # Pass no-log=True so this internal sub-call does not fire its own billing/+ # Mark as an internal sub-call so wrapper_async skips billing callbacks;+ # the parent litellm_logging_obj (propagated via kwargs) fires once at the end.first_response: ResponsesAPIResponse = cast(ResponsesAPIResponse,await _call_aresponses(input=input,model=model,tools=transformed_tools or None,- **{**kwargs, "no-log": True},+ **{**kwargs, "_is_litellm_internal_call": True},),)@@ -516,14 +517,14 @@ async def aresponses_with_emulated_file_search()# 6. Follow-up call — provider writes the final answer given search results.- # Suppress callbacks here too; cost is accumulated into the synthesized+ # Also an internal sub-call; billing is suppressed so the outer call fires once.final_response: ResponsesAPIResponse = cast(ResponsesAPIResponse,await _call_aresponses(input=follow_up_input,model=model,tools=None, # no tools needed for the answer step- **{**kwargs, "no-log": True},+ **{**kwargs, "_is_litellm_internal_call": True},),)diff --git a/litellm/responses/main.py b/litellm/responses/main.pyindex 4404e6b366a..11c9a4168ba 100644--- a/litellm/responses/main.py+++ b/litellm/responses/main.py@@ -732,7 +732,7 @@ def responses(aresponses_with_emulated_file_search,)- _internal_skip = {"litellm_logging_obj", "litellm_call_id", "aresponses"}+ _internal_skip = {"litellm_call_id", "aresponses"}emulated_kwargs = {"include": include,"instructions": instructions,diff --git a/litellm/utils.py b/litellm/utils.pyindex 81d749ab821..6754f82ddde 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -1798,6 +1798,7 @@ def client(original_function): # noqa: PLR0915model: Optional[str] = args[0] if len(args) > 0 else kwargs.get("model", None)is_completion_with_fallbacks = kwargs.get("fallbacks") is not None+ _is_litellm_internal_call = kwargs.pop("_is_litellm_internal_call", False)try:if logging_obj is None:@@ -1944,20 +1945,23 @@ def client(original_function): # noqa: PLR0915)# LOG SUCCESS - handle streaming success logging in the _next_ object- asyncio.create_task(- _client_async_logging_helper(- logging_obj=logging_obj,+ # Internal sub-calls (e.g. emulated file-search steps) share the+ # parent's logging obj; skip here so only the outer call bills once.+ if not _is_litellm_internal_call:+ asyncio.create_task(+ _client_async_logging_helper(+ logging_obj=logging_obj,+ result=result,+ start_time=start_time,+ end_time=end_time,+ is_completion_with_fallbacks=is_completion_with_fallbacks,+ )+ )+ logging_obj.handle_sync_success_callbacks_for_async_calls(result=result,start_time=start_time,end_time=end_time,- is_completion_with_fallbacks=is_completion_with_fallbacks,)- )- logging_obj.handle_sync_success_callbacks_for_async_calls(- result=result,- start_time=start_time,- end_time=end_time,- )# REBUILD EMBEDDING CACHINGif (isinstance(result, EmbeddingResponse)@@ -1985,7 +1989,7 @@ def client(original_function): # noqa: PLR0915except Exception as e:traceback_exception = traceback.format_exc()end_time = datetime.datetime.now()- if logging_obj:+ if logging_obj and not _is_litellm_internal_call:try:logging_obj.failure_handler(e, traceback_exception, start_time, end_timediff --git a/tests/test_litellm/llms/test_file_search_responses.py b/tests/test_litellm/llms/test_file_search_responses.pyindex ebe1466fa6c..1864a296eb6 100644--- a/tests/test_litellm/llms/test_file_search_responses.py+++ b/tests/test_litellm/llms/test_file_search_responses.py@@ -345,6 +345,24 @@ class TestManagedFilesVectorStoreAccess:)assert result == [unified_id]+ def _make_vs_row(self, vector_store_id: str, team_id: Optional[str]) -> Any:+ """Build a row compatible with get_managed_vector_store_rows_by_uuids (Prisma model_dump)."""+ from litellm.proxy._types import LiteLLM_ManagedVectorStoresTable++ return LiteLLM_ManagedVectorStoresTable(+ vector_store_id=vector_store_id,+ custom_llm_provider="openai",+ vector_store_name=None,+ vector_store_description=None,+ vector_store_metadata=None,+ created_at=None,+ updated_at=None,+ litellm_credential_name=None,+ litellm_params=None,+ team_id=team_id,+ user_id=None,+ )+@pytest.mark.asyncioasync def test_F3_wrong_team_raises_403(self):from fastapi import HTTPException@@ -352,18 +370,17 @@ class TestManagedFilesVectorStoreAccess:hook = self._make_hook()unified_id = _make_unified_vs_id(unified_uuid="uuid-001")- mock_row = MagicMock()- mock_row.vector_store_id = "uuid-001"- mock_row.team_id = "team-other"+ mock_row = self._make_vs_row(vector_store_id="uuid-001", team_id="team-other")- mock_db = MagicMock()- mock_db.litellm_managedvectorstorestable.find_many = AsyncMock(- return_value=[mock_row]- )+ async def mock_get_rows(uuids, prisma_client, user_api_key_cache, proxy_logging_obj=None):+ return [mock_row]with patch("litellm.proxy.proxy_server.prisma_client",- MagicMock(db=mock_db),+ MagicMock(),+ ), patch(+ "litellm.proxy.auth.auth_checks.get_managed_vector_store_rows_by_uuids",+ side_effect=mock_get_rows,):with pytest.raises(HTTPException) as exc_info:await hook.check_vector_store_ids_access(@@ -377,20 +394,18 @@ class TestManagedFilesVectorStoreAccess:hook = self._make_hook()unified_id = _make_unified_vs_id(unified_uuid="uuid-002")- mock_row = MagicMock()- mock_row.vector_store_id = "uuid-002"- mock_row.team_id = None # legacy: no team restriction+ mock_row = self._make_vs_row(vector_store_id="uuid-002", team_id=None)- mock_db = MagicMock()- mock_db.litellm_managedvectorstorestable.find_many = AsyncMock(- return_value=[mock_row]- )+ async def mock_get_rows(uuids, prisma_client, user_api_key_cache, proxy_logging_obj=None):+ return [mock_row]with patch("litellm.proxy.proxy_server.prisma_client",- MagicMock(db=mock_db),+ MagicMock(),+ ), patch(+ "litellm.proxy.auth.auth_checks.get_managed_vector_store_rows_by_uuids",+ side_effect=mock_get_rows,):- # Should not raiseawait hook.check_vector_store_ids_access([unified_id], self._make_user(team_id="team-caller"))@@ -404,24 +419,25 @@ class TestManagedFilesVectorStoreAccess:for i in range(3)]- rows = []- for i in range(3):- r = MagicMock()- r.vector_store_id = f"uuid-{i}"- r.team_id = "team-abc"- rows.append(r)+ rows = [+ self._make_vs_row(vector_store_id=f"uuid-{i}", team_id="team-abc")+ for i in range(3)+ ]- mock_db = MagicMock()- find_many_mock = AsyncMock(return_value=rows)- mock_db.litellm_managedvectorstorestable.find_many = find_many_mock+ get_rows_mock = AsyncMock(return_value=rows)with patch("litellm.proxy.proxy_server.prisma_client",- MagicMock(db=mock_db),+ MagicMock(),+ ), patch(+ "litellm.proxy.auth.auth_checks.get_managed_vector_store_rows_by_uuids",+ get_rows_mock,):await hook.check_vector_store_ids_access(ids, self._make_user("team-abc"))- find_many_mock.assert_called_once()+ get_rows_mock.assert_called_once()+ call_args = get_rows_mock.call_args+ assert set(call_args.kwargs["uuids"] or call_args.args[0]) == {"uuid-0", "uuid-1", "uuid-2"}@pytest.mark.asyncioasync def test_F6_non_responses_call_type_skipped(self):@@ -816,3 +832,61 @@ class TestEmulatedFileSearchHandler:tools = [{"type": "file_search", "vector_store_ids": ["vs_abc"]}]assert should_use_emulated_file_search(tools, None) is True++ @pytest.mark.asyncio+ async def test_H15_sub_calls_carry_internal_call_flag(self):+ """Both internal aresponses sub-calls receive _is_litellm_internal_call=True.++ This ensures wrapper_async skips success/failure callbacks for sub-calls so+ billing fires exactly once (on the outer call) with the synthesized result.+ """+ from litellm.responses.file_search.emulated_handler import (+ aresponses_with_emulated_file_search,+ )++ first_resp = self._make_mock_responses_api_response(include_function_call=True)+ final_resp = self._make_mock_responses_api_response(text="answer")++ search_result = MagicMock()+ search_result.file_id = "file-h15"+ search_result.filename = "h15.pdf"+ search_result.score = 0.9+ search_result.content = [{"type": "text", "text": "context"}]+ mock_search_response = MagicMock()+ mock_search_response.data = [search_result]++ captured_kwargs: list = []++ async def _capture(*args, **kwargs):+ captured_kwargs.append(dict(kwargs))+ return captured_kwargs.__len__() == 1 and first_resp or final_resp++ with patch(+ "litellm.responses.file_search.emulated_handler._call_aresponses",+ new=AsyncMock(side_effect=[first_resp, final_resp]),+ ) as mock_call, patch(+ "litellm.vector_stores.main.asearch",+ new=AsyncMock(return_value=mock_search_response),+ ):+ # Intercept kwargs before the mock returns+ original_side_effect = [first_resp, final_resp]+ call_kwargs: list = []++ async def _intercept(**kwargs): # type: ignore[misc]+ call_kwargs.append(dict(kwargs))+ return original_side_effect.pop(0)++ mock_call.side_effect = _intercept++ await aresponses_with_emulated_file_search(+ input="What is H15?",+ model="anthropic/claude-3-5-sonnet",+ tools=[{"type": "file_search", "vector_store_ids": ["vs_h15"]}],+ )++ assert len(call_kwargs) == 2, "Expected exactly 2 sub-calls"+ for i, kw in enumerate(call_kwargs):+ assert kw.get("_is_litellm_internal_call") is True, (+ f"Sub-call {i} must carry _is_litellm_internal_call=True to suppress "+ "billing callbacks in wrapper_async"+ )