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
Batches - support batch retrieve with target model Query Param + Anthropic - completion bridge, yield content_block_stop chunk (#12228)
Krish Dholakia22d28f58530e
diff --git a/docs/my-website/docs/proxy/managed_batches.md b/docs/my-website/docs/proxy/managed_batches.mdindex 1b9b71c1779..431d313fc18 100644--- a/docs/my-website/docs/proxy/managed_batches.md+++ b/docs/my-website/docs/proxy/managed_batches.md@@ -147,7 +147,7 @@ print(file_response.text)```python showLineNumbers title="create_batch.py"...-client.batches.list(limit=10, extra_body={"target_model_names": "gpt-4o-batch"})+client.batches.list(limit=10, extra_query={"target_model_names": "gpt-4o-batch"})```### [Coming Soon] Cancel a batchdiff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.pyindex 51007b12035..aa95183bb6c 100644--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py@@ -221,12 +221,6 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):return self.chunk_queue.popleft()# Check if this processed chunk has a stop_reason - hold it for next chunk- if (- processed_chunk.get("type") == "message_delta"- and processed_chunk.get("delta", {}).get("stop_reason") is not None- ):- self.holding_stop_reason_chunk = processed_chunk- continue # Don't process this chunk yet, wait for usageif should_start_new_block and not self.sent_content_block_finish:# Queue the sequence: content_block_stop -> content_block_start -> current_chunk@@ -268,8 +262,12 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):"index": self.current_content_block_index,})- self.chunk_queue.append(processed_chunk)self.sent_content_block_finish = True+ if processed_chunk.get("delta", {}).get("stop_reason") is not None:++ self.holding_stop_reason_chunk = processed_chunk+ else:+ self.chunk_queue.append(processed_chunk)return self.chunk_queue.popleft()elif self.holding_chunk is not None:# Queue both chunks@@ -360,6 +358,9 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):# Example logic - customize based on your needs:# If chunk indicates a tool call+ if chunk.choices[0].finish_reason is not None:+ return False+(block_type,content_block_start,diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex a854922f4ca..9630cf3eef1 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -1,7 +1,5 @@model_list:- - model_name: "gemini/*"+ - model_name: "gpt-4o"litellm_params:- model: "gemini/*"- api_key: os.environ/GEMINI_API_KEY-litellm_settings:- check_provider_endpoint: true\ No newline at end of file+ model: "gpt-4o"+ api_key: os.environ/OPENAI_API_KEYdiff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.pyindex 66ba0800dac..f8e3a9109bc 100644--- a/litellm/proxy/batches_endpoints/endpoints.py+++ b/litellm/proxy/batches_endpoints/endpoints.py@@ -354,6 +354,7 @@ async def list_batches(limit: Optional[int] = None,after: Optional[str] = None,user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+ target_model_names: Optional[str] = None,):"""Lists@@ -380,7 +381,7 @@ async def list_batches(## check for target model namesdata = await _read_request_body(request=request)- target_model_names = data.get("target_model_names", None)+ target_model_names = target_model_names or data.get("target_model_names", None)if target_model_names:model = target_model_names.split(",")[0]response = await llm_router.alist_batches(diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.pyindex ad82ee7dcaa..98ec274380f 100644--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py@@ -545,8 +545,12 @@ def _get_response_for_spend_logs_payload(def _should_store_prompts_and_responses_in_spend_logs() -> bool:from litellm.proxy.proxy_server import general_settings+ from litellm.secret_managers.main import get_secret_bool- return general_settings.get("store_prompts_in_spend_logs") is True+ return (+ general_settings.get("store_prompts_in_spend_logs") is True+ or get_secret_bool("STORE_PROMPTS_IN_SPEND_LOGS") is True+ )def _get_status_for_spend_log(diff --git a/tests/llm_translation/test_gemini.py b/tests/llm_translation/test_gemini.pyindex 5a7f15af2d9..a42c12cafea 100644--- a/tests/llm_translation/test_gemini.py+++ b/tests/llm_translation/test_gemini.py@@ -307,9 +307,12 @@ async def test_claude_tool_use_with_gemini():is_content_block_tool_use = Falseis_partial_json = Falsehas_usage_in_message_delta = False+ is_content_block_stop = Falseasync for chunk in response:print(chunk)+ if "content_block_stop" in str(chunk):+ is_content_block_stop = True# Handle bytes chunks (SSE format)if isinstance(chunk, bytes):@@ -332,6 +335,8 @@ async def test_claude_tool_use_with_gemini():is_content_block_tool_use = Trueif "partial_json" in json_str:is_partial_json = True+ if "content_block_stop" in json_str:+ is_content_block_stop = True# Check for usage in message_delta with stop_reasonif (@@ -365,9 +370,12 @@ async def test_claude_tool_use_with_gemini():is_content_block_tool_use = Trueif "partial_json" in str(chunk):is_partial_json = True+ if "content_block_stop" in str(chunk):+ is_content_block_stop = Trueassert is_content_block_tool_use, "content_block_tool_use should be present"assert is_partial_json, "partial_json should be present"assert (has_usage_in_message_delta), "Usage should be present in message_delta with stop_reason"+ assert is_content_block_stop, "is_content_block_stop should be present"diff --git a/tests/openai_endpoints_tests/test_openai_batches_endpoint.py b/tests/openai_endpoints_tests/test_openai_batches_endpoint.pyindex 3b6527a11b6..dc6c85fb723 100644--- a/tests/openai_endpoints_tests/test_openai_batches_endpoint.py+++ b/tests/openai_endpoints_tests/test_openai_batches_endpoint.py@@ -9,6 +9,7 @@ from test_openai_files_endpoints import upload_file, delete_fileimport osimport sysimport time+from unittest.mock import patch, MagicMock, AsyncMockBASE_URL = "http://localhost:4000" # Replace with your actual base URL@@ -126,14 +127,14 @@ def write_content_to_file(content.write_to_file(output_path)-import jsonlines--def read_jsonl(filepath: str):+ import json+results = []- with jsonlines.open(filepath) as f:+ with open(filepath, "r") as f:for line in f:- results.append(line)+ if line.strip():+ results.append(json.loads(line))for item in results:print(item)@@ -219,3 +220,75 @@ def test_vertex_batches_endpoint():)print("response from create batch", create_batch_response)pass++[email protected](reason="Local only test to verify if things work well")+async def test_list_batches_with_target_model_names():+ """+ Unit test to verify that target_model_names query parameter is properly handled+ in the list_batches endpoint+ """++ # Test data+ target_model_names = "gpt-4,gpt-3.5-turbo"+ expected_model = "gpt-4" # Should use the first model from the comma-separated list++ # Mock response for list_batches+ mock_batch_response = {+ "object": "list",+ "data": [+ {+ "id": "batch_abc123",+ "object": "batch",+ "endpoint": "/v1/chat/completions",+ "status": "validating",+ "input_file_id": "file-abc123",+ "completion_window": "24h",+ "created_at": 1711471533,+ "metadata": {},+ }+ ],+ "first_id": "batch_abc123",+ "last_id": "batch_abc123",+ "has_more": False,+ }++ # Mock the request and FastAPI dependencies+ mock_request = MagicMock()+ mock_request.method = "GET"+ mock_request.url.query = f"target_model_names={target_model_names}&limit=10"++ mock_fastapi_response = MagicMock()+ mock_user_api_key_dict = MagicMock()++ # Mock _read_request_body to return our target_model_names+ with patch(+ "litellm.proxy.batches_endpoints.endpoints._read_request_body"+ ) as mock_read_body, patch("litellm.proxy.proxy_server.llm_router") as mock_router:++ mock_read_body.return_value = {"target_model_names": target_model_names}+ mock_router.alist_batches = AsyncMock(return_value=mock_batch_response)++ # Import and call the function directly+ from litellm.proxy.batches_endpoints.endpoints import list_batches++ response = await list_batches(+ request=mock_request,+ fastapi_response=mock_fastapi_response,+ target_model_names=target_model_names,+ limit=10,+ user_api_key_dict=mock_user_api_key_dict,+ )++ # Verify that router.alist_batches was called with the correct model+ mock_router.alist_batches.assert_called_once()+ call_args = mock_router.alist_batches.call_args++ # Check that the model parameter was set to the first model in the list+ assert call_args.kwargs["model"] == expected_model+ assert call_args.kwargs["limit"] == 10++ # Verify the response structure+ assert response["object"] == "list"+ assert len(response["data"]) > 0