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]

Resolve remaining merge conflicts with upstream/main

Chesarsf82ba6ca6b4f
diff --cc litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
index 806513f36ff,799e8ab9a0a..c65dfb22730
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
@@@ -332,7 -358,11 +356,9 @@@ class AnthropicStreamWrapper(AdapterCom
and processed_chunk["delta"].get("partial_json")
):
self.chunk_queue.append(processed_chunk)
+
+ # Reset state for new block
self.sent_content_block_finish = False
-
- # Return the first queued item
return self.chunk_queue.popleft()
if (
diff --cc litellm/model_prices_and_context_window_backup.json
index 657f395328f,2000e4e3064..da3035379fe
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@@ -13756,11 -13740,7 +13760,12 @@@
"supports_url_context": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini-2.5-flash-image": {
"cache_read_input_token_cost": 3e-08,
@@@ -13844,12 -13825,7 +13850,13 @@@
"supports_system_messages": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"gemini-3.1-flash-image-preview": {
"input_cost_per_image": 0.00056,
@@@ -13939,12 -13909,7 +13946,13 @@@
"supports_vision": true,
"supports_web_search": true,
"supports_native_streaming": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"deep-research-pro-preview-12-2025": {
"input_cost_per_image": 0.0011,
@@@ -14024,11 -13989,7 +14032,12 @@@
"supports_url_context": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini-2.5-flash-lite-preview-09-2025": {
"cache_read_input_token_cost": 1e-08,
@@@ -14325,11 -14261,7 +14334,12 @@@
"supports_video_input": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini-3-pro-preview": {
"deprecation_date": "2026-03-26",
@@@ -15176,11 -15044,7 +15186,12 @@@
"supports_vision": true,
"supports_web_search": true,
"tpm": 8000000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini/gemini-2.5-flash-image": {
"cache_read_input_token_cost": 3e-08,
@@@ -15231,11 -15095,7 +15242,12 @@@
"supports_vision": true,
"supports_web_search": true,
"tpm": 8000000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini/gemini-3-pro-image-preview": {
"input_cost_per_image": 0.0011,
@@@ -15272,12 -15132,7 +15284,13 @@@
"supports_system_messages": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"gemini/gemini-3.1-flash-image-preview": {
"input_cost_per_token": 2.5e-07,
@@@ -15408,11 -15252,7 +15421,12 @@@
"supports_vision": true,
"supports_web_search": true,
"tpm": 250000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini/gemini-2.5-flash-lite-preview-09-2025": {
"cache_read_input_token_cost": 1e-08,
@@@ -15889,12 -15693,7 +15903,13 @@@
"supports_web_search": true,
"supports_native_streaming": true,
"tpm": 250000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"gemini/gemini-3-flash-preview": {
"cache_read_input_token_cost": 5e-08,
diff --cc model_prices_and_context_window.json
index 5650f05056b,c624736d6bf..c13e44c872b
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@@ -13756,11 -13740,7 +13760,12 @@@
"supports_url_context": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini-2.5-flash-image": {
"cache_read_input_token_cost": 3e-08,
@@@ -13844,12 -13825,7 +13850,13 @@@
"supports_system_messages": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"gemini-3.1-flash-image-preview": {
"input_cost_per_image": 0.00056,
@@@ -13939,12 -13909,7 +13946,13 @@@
"supports_vision": true,
"supports_web_search": true,
"supports_native_streaming": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"deep-research-pro-preview-12-2025": {
"input_cost_per_image": 0.0011,
@@@ -14024,11 -13989,7 +14032,12 @@@
"supports_url_context": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini-2.5-flash-lite-preview-09-2025": {
"cache_read_input_token_cost": 1e-08,
@@@ -14325,11 -14261,7 +14334,12 @@@
"supports_video_input": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini-3-pro-preview": {
"deprecation_date": "2026-03-26",
@@@ -15176,11 -15044,7 +15186,12 @@@
"supports_vision": true,
"supports_web_search": true,
"tpm": 8000000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini/gemini-2.5-flash-image": {
"cache_read_input_token_cost": 3e-08,
@@@ -15231,11 -15095,7 +15242,12 @@@
"supports_vision": true,
"supports_web_search": true,
"tpm": 8000000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini/gemini-3-pro-image-preview": {
"input_cost_per_image": 0.0011,
@@@ -15272,12 -15132,7 +15284,13 @@@
"supports_system_messages": true,
"supports_vision": true,
"supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"gemini/gemini-3.1-flash-image-preview": {
"input_cost_per_token": 2.5e-07,
@@@ -15408,11 -15252,7 +15421,12 @@@
"supports_vision": true,
"supports_web_search": true,
"tpm": 250000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.035,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.035
- }
++ },
+ "supports_service_tier": true
},
"gemini/gemini-2.5-flash-lite-preview-09-2025": {
"cache_read_input_token_cost": 1e-08,
@@@ -15889,12 -15693,7 +15903,13 @@@
"supports_web_search": true,
"supports_native_streaming": true,
"tpm": 250000,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.014,
+ "search_context_size_medium": 0.014,
+ "search_context_size_high": 0.014
+ },
- "web_search_billing_unit": "per_query"
++ "web_search_billing_unit": "per_query",
+ "supports_service_tier": true
},
"gemini/gemini-3-flash-preview": {
"cache_read_input_token_cost": 5e-08,
diff --cc tests/litellm/llms/vertex_ai/test_gemini_batch_embeddings.py
index 5f4c7b564cd,d814f8ec97f..2569a33f11e
--- a/tests/litellm/llms/vertex_ai/test_gemini_batch_embeddings.py
+++ b/tests/litellm/llms/vertex_ai/test_gemini_batch_embeddings.py
@@@ -565,49 -565,31 +566,78 @@@ def test_vertex_ai_text_only_embedding_
assert len(response.data) == 1
+# ---------------------------------------------------------------------------
+# Unsupported params filtering tests (#24293)
+# ---------------------------------------------------------------------------
+
+
+def test_filter_embed_params_drops_unsupported():
+ """Unsupported params like max_tokens should be filtered out."""
+ result = _filter_embed_params({"dimensions": 768, "max_tokens": 256, "temperature": 0.5})
+ assert result == {"outputDimensionality": 768}
+
+
+def test_filter_embed_params_keeps_supported():
+ """All supported Gemini embedding params should pass through."""
+ result = _filter_embed_params({
+ "dimensions": 768,
+ "task_type": "RETRIEVAL_DOCUMENT",
+ "title": "My doc",
+ })
+ assert result == {
+ "outputDimensionality": 768,
+ "taskType": "RETRIEVAL_DOCUMENT",
+ "title": "My doc",
+ }
+
+
+def test_batch_embed_content_drops_max_tokens():
+ """max_tokens in optional_params should not appear in the batch request."""
+ result = transform_openai_input_gemini_content(
+ input="test text",
+ model="text-embedding-004",
+ optional_params={"max_tokens": 256},
+ )
+ for request in result["requests"]:
+ assert "max_tokens" not in request
+
+
+def test_embed_content_drops_max_tokens():
+ """max_tokens in optional_params should not appear in the embedContent request."""
+ result = transform_openai_input_gemini_embed_content(
+ input=["test text"],
+ model="gemini-embedding-001",
+ optional_params={"max_tokens": 256},
+ resolved_files=None,
+ )
+ assert "max_tokens" not in result
+
++
+ def test_batch_embeddings_response_has_correct_indices_and_order():
+ """Test that process_response assigns sequential indices and preserves order."""
+ response_json = {
+ "embeddings": [
+ {"values": [0.1, 0.2, 0.3]},
+ {"values": [0.4, 0.5, 0.6]},
+ {"values": [0.7, 0.8, 0.9]},
+ ]
+ }
+ expected_values = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]
+
+ model_response = EmbeddingResponse()
+ result = process_response(
+ input=["first", "second", "third"],
+ model_response=model_response,
+ model="text-embedding-004",
+ _predictions=response_json,
+ )
+
+ assert len(result.data) == 3
+ for i, embedding in enumerate(result.data):
+ assert (
+ embedding.index == i
+ ), f"embedding {i} has index={embedding.index}, expected {i}"
+ assert (
+ embedding.embedding == expected_values[i]
+ ), f"embedding {i} has wrong values: {embedding.embedding}"
+
diff --cc tests/test_litellm/litellm_core_utils/test_streaming_handler.py
index 6340b5e75c9,47a77c110b0..6b1ad5c4f20
--- a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
@@@ -1828,145 -1878,71 +1878,215 @@@ async def test_custom_stream_wrapper_an
pytest.fail(f"PEP 479 regression: StopIteration leaked as RuntimeError: {e}")
+# Azure streaming chunks that reproduce issue #24221:
+# Azure sends an initial chunk with prompt_filter_results and choices=[],
+# then a chunk with role='assistant' and content='', then content chunks.
+# With stream_options.include_usage=True, the empty-choices chunk was
+# forwarded with an inflated default choice, consuming the sent_first_chunk
+# flag and causing strip_role_from_delta to strip the role from the real
+# first chunk.
+_AZURE_CHUNKS_WITH_PROMPT_FILTER = [
+ # Chunk 1: prompt_filter_results, no choices (Azure-specific)
+ ModelResponseStream(
+ id="chatcmpl-abc123",
+ created=1742056047,
+ model=None,
+ object="chat.completion.chunk",
+ choices=[],
+ usage=None,
+ ),
+ # Chunk 2: first real chunk with role='assistant' and empty content
+ ModelResponseStream(
+ id="chatcmpl-abc123",
+ created=1742056047,
+ model=None,
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(content="", role="assistant"),
+ )
+ ],
+ usage=None,
+ ),
+ # Chunk 3: content
+ ModelResponseStream(
+ id="chatcmpl-abc123",
+ created=1742056047,
+ model=None,
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(content="Hello!"),
+ )
+ ],
+ usage=None,
+ ),
+ # Chunk 4: finish_reason
+ ModelResponseStream(
+ id="chatcmpl-abc123",
+ created=1742056047,
+ model=None,
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ finish_reason="stop",
+ index=0,
+ delta=Delta(),
+ )
+ ],
+ usage=None,
+ ),
+ # Chunk 5: final usage chunk, no choices
+ ModelResponseStream(
+ id="chatcmpl-abc123",
+ created=1742056047,
+ model=None,
+ object="chat.completion.chunk",
+ choices=[],
+ usage=Usage(
+ completion_tokens=10,
+ prompt_tokens=20,
+ total_tokens=30,
+ ),
+ ),
+]
+
+
[email protected]("sync_mode", [True, False], ids=["sync", "async"])
+async def test_azure_streaming_role_preserved_with_include_usage(sync_mode: bool):
+ """
+ Regression test for https://github.com/BerriAI/litellm/issues/24221
+
+ Azure sends an initial chunk with choices=[] (prompt_filter_results)
+ before the first content chunk. With stream_options.include_usage=True,
+ this chunk was forwarded with an inflated default choice, which:
+ 1. Consumed the sent_first_chunk flag
+ 2. Caused strip_role_from_delta to strip role from the real first chunk
+
+ The fix ensures:
+ - Chunks with choices=[] are forwarded faithfully (no inflated choices)
+ - sent_first_chunk is only marked for chunks with real choices
+ - Chunks with role in delta are not discarded as empty
+ """
+ completion_stream = ModelResponseListIterator(
+ model_responses=_AZURE_CHUNKS_WITH_PROMPT_FILTER
+ )
+
+ response = CustomStreamWrapper(
+ completion_stream=completion_stream,
+ model="azure/gpt-5-nano",
+ custom_llm_provider="azure",
+ logging_obj=Logging(
+ model="azure/gpt-5-nano",
+ messages=[{"role": "user", "content": "Hey"}],
+ stream=True,
+ call_type="completion",
+ start_time=time.time(),
+ litellm_call_id="12345",
+ function_id="1245",
+ ),
+ stream_options={"include_usage": True},
+ )
+
+ chunks = []
+ if sync_mode:
+ for chunk in response:
+ chunks.append(chunk)
+ else:
+ async for chunk in response:
+ chunks.append(chunk)
+
+ # The prompt_filter chunk should be forwarded with choices=[]
+ assert len(chunks[0].choices) == 0, (
+ f"Expected prompt_filter chunk with choices=[], got {len(chunks[0].choices)} choices"
+ )
+
+ # At least one chunk must have role='assistant' in its delta
+ has_role = any(
+ len(c.choices) > 0
+ and getattr(c.choices[0].delta, "role", None) == "assistant"
+ for c in chunks
+ )
+ assert has_role, (
+ "No chunk contained role='assistant' in delta (issue #24221). "
+ "Chunk deltas: "
+ + str([
+ c.choices[0].delta if c.choices else "no choices"
+ for c in chunks
+ ])
+ )
++
++
+ def test_gemini_legacy_vertex_stop_finish_reason_normalised():
+ """
+ The legacy vertex_ai SDK streaming path sets finish_reason from a proto enum
+ whose .name attribute is an uppercase string (e.g. "STOP", "MAX_TOKENS").
+ Before the fix, received_finish_reason was stored as "STOP" which never
+ matched "stop" in finish_reason_handler, silently breaking the tool_calls
+ override. After the fix, map_finish_reason() is applied so the value is
+ always an OpenAI-normalised lowercase string.
+ """
+ wrapper = CustomStreamWrapper(
+ completion_stream=None,
+ model="gemini-1.5-pro",
+ logging_obj=MagicMock(),
+ custom_llm_provider="vertex_ai",
+ )
+
+ # Simulate a proto-like chunk: .candidates[0].finish_reason.name == "STOP"
+ mock_finish_reason = MagicMock()
+ mock_finish_reason.name = "STOP"
+ mock_candidate = MagicMock()
+ mock_candidate.finish_reason = mock_finish_reason
+ mock_chunk = MagicMock()
+ mock_chunk.candidates = [mock_candidate]
+ # Ensure the chunk is not treated as a ModelResponseStream
+ mock_chunk.__class__ = type("FakeProtoChunk", (), {})
+
+ with patch("litellm.litellm_core_utils.streaming_handler.proto", create=True):
+ wrapper.chunk_creator(chunk=mock_chunk)
+
+ assert wrapper.received_finish_reason == "stop", (
+ f"Expected 'stop' but got {wrapper.received_finish_reason!r}. "
+ "map_finish_reason() was not applied to the Gemini enum name."
+ )
+
+
+ def test_gemini_legacy_vertex_tool_calls_finish_reason_with_stop_enum():
+ """
+ When Gemini emits finish_reason STOP alongside tool-call content, the final
+ chunk must report finish_reason='tool_calls'. This requires that the raw
+ "STOP" enum name is first normalised to lowercase "stop" by map_finish_reason()
+ so that finish_reason_handler's equality check fires correctly.
+ """
+ wrapper = CustomStreamWrapper(
+ completion_stream=None,
+ model="gemini-1.5-pro",
+ logging_obj=MagicMock(),
+ custom_llm_provider="vertex_ai",
+ )
+
+ mock_finish_reason = MagicMock()
+ mock_finish_reason.name = "STOP"
+ mock_candidate = MagicMock()
+ mock_candidate.finish_reason = mock_finish_reason
+ mock_chunk = MagicMock()
+ mock_chunk.candidates = [mock_candidate]
+ mock_chunk.__class__ = type("FakeProtoChunk", (), {})
+
+ with patch("litellm.litellm_core_utils.streaming_handler.proto", create=True):
+ wrapper.chunk_creator(chunk=mock_chunk)
+
+ # Signal that tool_calls were present in the stream
+ wrapper.tool_call = True
+
+ final = wrapper.finish_reason_handler()
+ assert final.choices[0].finish_reason == "tool_calls", (
+ f"Expected 'tool_calls' but got {final.choices[0].finish_reason!r}. "
+ "STOP enum was not normalised through map_finish_reason()."
+ )