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
Add error file ids as managed files
Sameer Kankute9bdb163269be
diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.pyindex 569ea17f6d8..7cbee64b08e 100644--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py@@ -899,40 +899,42 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):batch_id=response.id, model_id=model_id)- if (- response.output_file_id and model_id- ): # return a file id with the model_id and output_file_id- original_output_file_id = response.output_file_id- response.output_file_id = self.get_unified_output_file_id(- output_file_id=response.output_file_id,- model_id=model_id,- model_name=model_name,- )-- # Fetch the actual file object for the output file- file_object = None- try:- # Use litellm to retrieve the file object from the provider- from litellm import afile_retrieve- file_object = await afile_retrieve(- custom_llm_provider=model_name.split("/")[0] if model_name and "/" in model_name else "openai",- file_id=original_output_file_id- )- verbose_logger.debug(- f"Successfully retrieved file object for output_file_id={original_output_file_id}"+ # Handle both output_file_id and error_file_id+ for file_attr in ["output_file_id", "error_file_id"]:+ file_id_value = getattr(response, file_attr, None)+ if file_id_value and model_id:+ original_file_id = file_id_value+ unified_file_id = self.get_unified_output_file_id(+ output_file_id=original_file_id,+ model_id=model_id,+ model_name=model_name,)- except Exception as e:- verbose_logger.warning(- f"Failed to retrieve file object for output_file_id={original_output_file_id}: {str(e)}. Storing with None and will fetch on-demand."+ setattr(response, file_attr, unified_file_id)++ # Fetch the actual file object from the provider+ file_object = None+ try:+ # Use litellm to retrieve the file object from the provider+ from litellm import afile_retrieve+ file_object = await afile_retrieve(+ custom_llm_provider=model_name.split("/")[0] if model_name and "/" in model_name else "openai",+ file_id=original_file_id+ )+ verbose_logger.debug(+ f"Successfully retrieved file object for {file_attr}={original_file_id}"+ )+ except Exception as e:+ verbose_logger.warning(+ f"Failed to retrieve file object for {file_attr}={original_file_id}: {str(e)}. Storing with None and will fetch on-demand."+ )++ await self.store_unified_file_id(+ file_id=unified_file_id,+ file_object=file_object,+ litellm_parent_otel_span=user_api_key_dict.parent_otel_span,+ model_mappings={model_id: original_file_id},+ user_api_key_dict=user_api_key_dict,)-- await self.store_unified_file_id(- file_id=response.output_file_id,- file_object=file_object,- litellm_parent_otel_span=user_api_key_dict.parent_otel_span,- model_mappings={model_id: original_output_file_id},- user_api_key_dict=user_api_key_dict,- )asyncio.create_task(self.store_unified_object_id(unified_object_id=response.id,diff --git a/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.pyindex 946c5ad1729..8a22a43c379 100644--- a/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py+++ b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py@@ -373,6 +373,91 @@ async def test_output_file_id_for_batch_retrieve():assert not cast(LiteLLMBatch, response).output_file_id.startswith("file-")+async def test_error_file_id_for_failed_batch():+ """+ Test that the error_file_id is properly managed when a batch fails+ """+ from typing import cast++ from openai.types.batch import BatchRequestCounts++ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.types.llms.openai import OpenAIFileObject+ from litellm.types.utils import LiteLLMBatch++ batch = LiteLLMBatch(+ id="bGl0ZWxsbV9wcm94eTttb2RlbF9pZDoxMjM0NTY3OTtsbG1fYmF0Y2hfaWQ6YmF0Y2hfYWJjMTIz",+ completion_window="24h",+ created_at=1714508499,+ endpoint="/v1/chat/completions",+ input_file_id="file-abc123",+ object="batch",+ status="failed",+ cancelled_at=None,+ cancelling_at=None,+ completed_at=None,+ error_file_id="error-abc123",+ errors=None,+ expired_at=None,+ expires_at=1714536634,+ failed_at=None,+ finalizing_at=None,+ in_progress_at=None,+ metadata=None,+ output_file_id=None,+ request_counts=BatchRequestCounts(completed=0, failed=0, total=0),+ usage=None,+ )++ batch._hidden_params = {+ "litellm_call_id": "test-call-id",+ "api_base": "https://api.openai.com",+ "model_id": "test-model-id",+ "model_name": "gpt-4o",+ "response_cost": 0.0,+ "additional_headers": {},+ "litellm_model_name": "gpt-4o",+ "unified_batch_id": "litellm_proxy;model_id:test-model-id;llm_batch_id:batch_abc123",+ }++ proxy_managed_files = _PROXY_LiteLLMManagedFiles(+ DualCache(), prisma_client=AsyncMock()+ )++ # Create a proper OpenAIFileObject for the error file+ error_file_object = OpenAIFileObject(+ id="error-abc123",+ object="file",+ bytes=1234,+ created_at=1714508500,+ filename="error.jsonl",+ purpose="batch_output",+ status="processed",+ )++ # Mock the afile_retrieve to simulate retrieving error file metadata+ with patch("litellm.afile_retrieve", new_callable=AsyncMock) as mock_retrieve:+ mock_retrieve.return_value = error_file_object++ user_api_key_dict = UserAPIKeyAuth(+ user_id="test-user-123",+ parent_otel_span=MagicMock()+ )++ response = await proxy_managed_files.async_post_call_success_hook(+ data={},+ user_api_key_dict=user_api_key_dict,+ response=batch,+ )++ # Verify that error_file_id was transformed to a managed file ID+ assert cast(LiteLLMBatch, response).error_file_id is not None+ assert not cast(LiteLLMBatch, response).error_file_id.startswith("error-")+ # Verify it's a base64 encoded managed file ID+ assert _is_base64_encoded_unified_file_id(cast(LiteLLMBatch, response).error_file_id)++@pytest.mark.asyncioasync def test_async_post_call_success_hook_twice_assert_no_unique_violation():import asyncio