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]

Non-anthropic (gemini/openai/etc.) models token usage returned when calling `/v1/messages` (#12184)

Krish Dholakia9582c88eab6b
diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py
index ffa0def9ce2..23175c9f2fa 100644
--- a/litellm/llms/anthropic/chat/handler.py
+++ b/litellm/llms/anthropic/chat/handler.py
@@ -515,9 +515,7 @@ class ModelResponseIterator:
usage_object=cast(dict, anthropic_usage_chunk), reasoning_content=None
)
- def _content_block_delta_helper(
- self, chunk: dict
- ) -> Tuple[
+ def _content_block_delta_helper(self, chunk: dict) -> Tuple[
str,
Optional[ChatCompletionToolCallChunk],
List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]],
@@ -600,6 +598,19 @@ class ModelResponseIterator:
return thinking_blocks, provider_specific_fields
+ def get_content_block_start(self, chunk: dict) -> ContentBlockStart:
+ from litellm.types.llms.anthropic import (
+ ContentBlockStartText,
+ ContentBlockStartToolUse,
+ )
+
+ if chunk.get("content_block", {}).get("type") == "tool_use":
+ content_block_start = ContentBlockStartToolUse(**chunk) # type: ignore
+ else:
+ content_block_start = ContentBlockStartText(**chunk) # type: ignore
+
+ return content_block_start
+
def chunk_parser(self, chunk: dict) -> ModelResponseStream:
try:
type_chunk = chunk.get("type", "") or ""
@@ -639,7 +650,8 @@ class ModelResponseIterator:
event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01T1x1fJ34qAmk2tNTrN7Up6","name":"get_weather","input":{}}}
"""
- content_block_start = ContentBlockStart(**chunk) # type: ignore
+
+ content_block_start = self.get_content_block_start(chunk=chunk)
self.content_blocks = [] # reset content blocks when new block starts
if content_block_start["content_block"]["type"] == "text":
text = content_block_start["content_block"]["text"]
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
index fad895a6253..5e0dfa9238a 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
@@ -88,6 +88,9 @@ class LiteLLMMessagesToCompletionTransformationHandler:
if stream:
completion_kwargs["stream"] = stream
+ completion_kwargs["stream_options"] = {
+ "include_usage": True,
+ }
excluded_keys = {"anthropic_messages"}
extra_kwargs = extra_kwargs or {}
@@ -100,6 +103,9 @@ class LiteLLMMessagesToCompletionTransformationHandler:
from litellm.types.utils import CallTypes
setattr(value, "call_type", CallTypes.completion.value)
+ setattr(
+ value, "stream_options", completion_kwargs.get("stream_options")
+ )
if (
key not in excluded_keys
and key not in completion_kwargs
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
index 662c42f0d7e..51007b12035 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
@@ -3,12 +3,16 @@
import json
import traceback
import uuid
-from typing import Any, AsyncIterator, Iterator, Optional
+from collections import deque
+from typing import TYPE_CHECKING, Any, AsyncIterator, Iterator, Literal, Optional
from litellm import verbose_logger
from litellm.types.llms.anthropic import UsageDelta
from litellm.types.utils import AdapterCompletionStreamWrapper
+if TYPE_CHECKING:
+ from litellm.types.utils import ModelResponseStream
+
class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
"""
@@ -17,6 +21,13 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
- finish_reason must map exactly to anthropic reason, else anthropic client won't be able to parse it.
"""
+ from litellm.types.llms.anthropic import (
+ ContentBlockContentBlockDict,
+ ContentBlockStart,
+ ContentBlockStartText,
+ TextBlock,
+ )
+
def __init__(self, completion_stream: Any, model: str):
super().__init__(completion_stream)
self.model = model
@@ -24,8 +35,17 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
sent_first_chunk: bool = False
sent_content_block_start: bool = False
sent_content_block_finish: bool = False
+ current_content_block_type: Literal["text", "tool_use"] = "text"
sent_last_message: bool = False
holding_chunk: Optional[Any] = None
+ holding_stop_reason_chunk: Optional[Any] = None
+ current_content_block_index: int = 0
+ current_content_block_start: ContentBlockContentBlockDict = TextBlock(
+ type="text",
+ text="",
+ )
+ pending_new_content_block: bool = False
+ chunk_queue: deque = deque() # Queue for buffering multiple chunks
def __next__(self):
from .transformation import LiteLLMAnthropicMessagesAdapter
@@ -50,17 +70,47 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
self.sent_content_block_start = True
return {
"type": "content_block_start",
- "index": 0,
+ "index": self.current_content_block_index,
"content_block": {"type": "text", "text": ""},
}
+ # Handle pending new content block start
+ if self.pending_new_content_block:
+ self.pending_new_content_block = False
+ self.sent_content_block_finish = False # Reset for new block
+ return {
+ "type": "content_block_start",
+ "index": self.current_content_block_index,
+ "content_block": self.current_content_block_start,
+ }
+
for chunk in self.completion_stream:
if chunk == "None" or chunk is None:
raise Exception
+ should_start_new_block = self._should_start_new_content_block(chunk)
+ if should_start_new_block:
+ self._increment_content_block_index()
+
processed_chunk = LiteLLMAnthropicMessagesAdapter().translate_streaming_openai_response_to_anthropic(
- response=chunk
+ response=chunk,
+ current_content_block_index=self.current_content_block_index,
)
+
+ # Check if we need to start a new content block
+ # This is where you'd add your logic to detect when a new content block should start
+ # For example, if the chunk indicates a tool call or different content type
+
+ if should_start_new_block and not self.sent_content_block_finish:
+ # End current content block and prepare for new one
+ self.holding_chunk = processed_chunk
+ self.sent_content_block_finish = True
+ self.pending_new_content_block = True
+ return {
+ "type": "content_block_stop",
+ "index": max(self.current_content_block_index - 1, 0),
+ }
+
if (
processed_chunk["type"] == "message_delta"
and self.sent_content_block_finish is False
@@ -69,7 +119,7 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
self.sent_content_block_finish = True
return {
"type": "content_block_stop",
- "index": 0,
+ "index": self.current_content_block_index,
}
elif self.holding_chunk is not None:
return_chunk = self.holding_chunk
@@ -96,64 +146,169 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
)
raise StopAsyncIteration
- async def __anext__(self):
+ async def __anext__(self): # noqa: PLR0915
from .transformation import LiteLLMAnthropicMessagesAdapter
try:
+ # Always return queued chunks first
+ if self.chunk_queue:
+ return self.chunk_queue.popleft()
+
+ # Queue initial chunks if not sent yet
if self.sent_first_chunk is False:
self.sent_first_chunk = True
- return {
- "type": "message_start",
- "message": {
- "id": "msg_{}".format(uuid.uuid4()),
- "type": "message",
- "role": "assistant",
- "content": [],
- "model": self.model,
- "stop_reason": None,
- "stop_sequence": None,
- "usage": UsageDelta(input_tokens=0, output_tokens=0),
- },
- }
+ self.chunk_queue.append(
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_{}".format(uuid.uuid4()),
+ "type": "message",
+ "role": "assistant",
+ "content": [],
+ "model": self.model,
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": UsageDelta(input_tokens=0, output_tokens=0),
+ },
+ }
+ )
+ return self.chunk_queue.popleft()
+
if self.sent_content_block_start is False:
self.sent_content_block_start = True
- return {
- "type": "content_block_start",
- "index": 0,
- "content_block": {"type": "text", "text": ""},
- }
+ self.chunk_queue.append(
+ {
+ "type": "content_block_start",
+ "index": self.current_content_block_index,
+ "content_block": {"type": "text", "text": ""},
+ }
+ )
+ return self.chunk_queue.popleft()
+
async for chunk in self.completion_stream:
if chunk == "None" or chunk is None:
raise Exception
+
+ # Check if we need to start a new content block
+ should_start_new_block = self._should_start_new_content_block(chunk)
+ if should_start_new_block:
+ self._increment_content_block_index()
+
processed_chunk = LiteLLMAnthropicMessagesAdapter().translate_streaming_openai_response_to_anthropic(
- response=chunk
+ response=chunk,
+ current_content_block_index=self.current_content_block_index,
)
+
+ # Check if this is a usage chunk and we have a held stop_reason chunk
+ if (
+ self.holding_stop_reason_chunk is not None
+ and getattr(chunk, "usage", None) is not None
+ ):
+ # Merge usage into the held stop_reason chunk
+ merged_chunk = self.holding_stop_reason_chunk.copy()
+ if "delta" not in merged_chunk:
+ merged_chunk["delta"] = {}
+
+ # Add usage to the held chunk
+ merged_chunk["usage"] = {
+ "input_tokens": chunk.usage.prompt_tokens or 0,
+ "output_tokens": chunk.usage.completion_tokens or 0,
+ }
+
+ # Queue the merged chunk and reset
+ self.chunk_queue.append(merged_chunk)
+ self.holding_stop_reason_chunk = None
+ 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 usage
+
+ if should_start_new_block and not self.sent_content_block_finish:
+ # Queue the sequence: content_block_stop -> content_block_start -> current_chunk
+
+ # 1. Stop current content block
+ self.chunk_queue.append(
+ {
+ "type": "content_block_stop",
+ "index": max(self.current_content_block_index - 1, 0),
+ }
+ )
+
+ # 2. Start new content block
+ self.chunk_queue.append(
+ {
+ "type": "content_block_start",
+ "index": self.current_content_block_index,
+ "content_block": self.current_content_block_start,
+ }
+ )
+
+ # 3. Queue the current chunk (don't lose it!)
+ 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 (
processed_chunk["type"] == "message_delta"
and self.sent_content_block_finish is False
):
- self.holding_chunk = processed_chunk
+ # Queue both the content_block_stop and the holding chunk
+ self.chunk_queue.append(
+ {
+ "type": "content_block_stop",
+ "index": self.current_content_block_index,
+ }
+ )
+ self.chunk_queue.append(processed_chunk)
self.sent_content_block_finish = True
- return {
- "type": "content_block_stop",
- "index": 0,
- }
+ return self.chunk_queue.popleft()
elif self.holding_chunk is not None:
- return_chunk = self.holding_chunk
- self.holding_chunk = processed_chunk
- return return_chunk
+ # Queue both chunks
+ self.chunk_queue.append(self.holding_chunk)
+ self.chunk_queue.append(processed_chunk)
+ self.holding_chunk = None
+ return self.chunk_queue.popleft()
else:
- return processed_chunk
+ # Queue the current chunk
+ self.chunk_queue.append(processed_chunk)
+ return self.chunk_queue.popleft()
+
+ # Handle any remaining held chunks after stream ends
+ if self.holding_stop_reason_chunk is not None:
+ self.chunk_queue.append(self.holding_stop_reason_chunk)
+ self.holding_stop_reason_chunk = None
+
if self.holding_chunk is not None:
- return_chunk = self.holding_chunk
+ self.chunk_queue.append(self.holding_chunk)
self.holding_chunk = None
- return return_chunk
- if self.sent_last_message is False:
+
+ if not self.sent_last_message:
self.sent_last_message = True
- return {"type": "message_stop"}
+ self.chunk_queue.append({"type": "message_stop"})
+
+ # Return queued items if any
+ if self.chunk_queue:
+ return self.chunk_queue.popleft()
+
raise StopIteration
+
except StopIteration:
- if self.sent_last_message is False:
+ # Handle any remaining queued chunks before stopping
+ if self.chunk_queue:
+ return self.chunk_queue.popleft()
+ # Handle any held stop_reason chunk
+ if self.holding_stop_reason_chunk is not None:
+ return self.holding_stop_reason_chunk
+ if not self.sent_last_message:
self.sent_last_message = True
return {"type": "message_stop"}
raise StopAsyncIteration
@@ -187,3 +342,34 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
else:
# For non-dict chunks, forward the original value unchanged
yield chunk
+
+ def _increment_content_block_index(self):
+ self.current_content_block_index += 1
+
+ def _should_start_new_content_block(self, chunk: "ModelResponseStream") -> bool:
+ """
+ Determine if we should start a new content block based on the processed chunk.
+ Override this method with your specific logic for detecting new content blocks.
+
+ Examples of when you might want to start a new content block:
+ - Switching from text to tool calls
+ - Different content types in the response
+ - Specific markers in the content
+ """
+ from .transformation import LiteLLMAnthropicMessagesAdapter
+
+ # Example logic - customize based on your needs:
+ # If chunk indicates a tool call
+ (
+ block_type,
+ content_block_start,
+ ) = LiteLLMAnthropicMessagesAdapter()._translate_streaming_openai_chunk_to_anthropic_content_block(
+ choices=chunk.choices # type: ignore
+ )
+
+ if block_type != self.current_content_block_type:
+ self.current_content_block_type = block_type
+ self.current_content_block_start = content_block_start
+ return True
+
+ return False
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index 369c668234f..5cf36a63f00 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@ -1,5 +1,15 @@
import json
-from typing import Any, AsyncIterator, List, Literal, Optional, Tuple, Union, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ List,
+ Literal,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
from openai.types.chat.chat_completion_chunk import Choice as OpenAIStreamingChoice
@@ -45,6 +55,9 @@ from litellm.types.utils import Choices, ModelResponse, Usage
from .streaming_iterator import AnthropicStreamWrapper
+if TYPE_CHECKING:
+ from litellm.types.llms.anthropic import ContentBlockContentBlockDict
+
class AnthropicAdapter:
def __init__(self) -> None:
@@ -439,12 +452,40 @@ class LiteLLMAnthropicMessagesAdapter:
return translated_obj
+ def _translate_streaming_openai_chunk_to_anthropic_content_block(
+ self, choices: List[OpenAIStreamingChoice]
+ ) -> Tuple[
+ Literal["text", "tool_use"],
+ "ContentBlockContentBlockDict",
+ ]:
+ import uuid
+
+ from litellm.types.llms.anthropic import TextBlock, ToolUseBlock
+
+ for choice in choices:
+ if choice.delta.content is not None and len(choice.delta.content) > 0:
+ return "text", TextBlock(type="text", text="")
+ elif (
+ choice.delta.tool_calls is not None
+ and len(choice.delta.tool_calls) > 0
+ and choice.delta.tool_calls[0].function is not None
+ ):
+ return "tool_use", ToolUseBlock(
+ type="tool_use",
+ id=choice.delta.tool_calls[0].id or str(uuid.uuid4()),
+ name=choice.delta.tool_calls[0].function.name or "",
+ input={},
+ )
+
+ return "text", TextBlock(type="text", text="")
+
def _translate_streaming_openai_chunk_to_anthropic(
self, choices: List[OpenAIStreamingChoice]
) -> Tuple[
Literal["text_delta", "input_json_delta"],
Union[ContentTextBlockDelta, ContentJsonBlockDelta],
]:
+
text: str = ""
partial_json: Optional[str] = None
for choice in choices:
@@ -467,7 +508,7 @@ class LiteLLMAnthropicMessagesAdapter:
return "text_delta", ContentTextBlockDelta(type="text_delta", text=text)
def translate_streaming_openai_response_to_anthropic(
- self, response: ModelResponse
+ self, response: ModelResponse, current_content_block_index: int
) -> Union[ContentBlockDelta, MessageBlockDelta]:
## base case - final chunk w/ finish reason
if response.choices[0].finish_reason is not None:
@@ -503,6 +544,6 @@ class LiteLLMAnthropicMessagesAdapter:
)
return ContentBlockDelta(
type="content_block_delta",
- index=response.choices[0].index,
+ index=current_content_block_index,
delta=content_block_delta,
)
diff --git a/litellm/types/llms/anthropic.py b/litellm/types/llms/anthropic.py
index 457e3b658ba..da94408202f 100644
--- a/litellm/types/llms/anthropic.py
+++ b/litellm/types/llms/anthropic.py
@@ -294,15 +294,23 @@ class TextBlock(TypedDict):
type: Literal["text"]
-class ContentBlockStart(TypedDict):
- """
- event: content_block_start
- data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01T1x1fJ34qAmk2tNTrN7Up6","name":"get_weather","input":{}}}
- """
+class ContentBlockStartToolUse(TypedDict):
+ type: Literal["content_block_start"]
+ id: str
+ name: str
+ input: dict
+ content_block: ToolUseBlock
- type: str
+
+class ContentBlockStartText(TypedDict):
+ type: Literal["content_block_start"]
index: int
- content_block: Union[ToolUseBlock, TextBlock]
+ content_block: TextBlock
+
+
+ContentBlockContentBlockDict = Union[ToolUseBlock, TextBlock]
+
+ContentBlockStart = Union[ContentBlockStartToolUse, ContentBlockStartText]
class MessageDelta(TypedDict, total=False):
diff --git a/litellm/utils.py b/litellm/utils.py
index 5d952aaa8f6..0f59870d1aa 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -800,6 +800,7 @@ def function_setup( # noqa: PLR0915
litellm_params: Dict[str, Any] = {"api_base": ""}
if "metadata" in kwargs:
litellm_params["metadata"] = kwargs["metadata"]
+
logging_obj.update_environment_variables(
model=model,
user="",
@@ -6612,7 +6613,7 @@ def validate_chat_completion_tool_choice(
and "function" not in tool_choice
):
return tool_choice
-
+
# Standard OpenAI format: {"type": "function", "function": {...}}
if tool_choice.get("type") is None or tool_choice.get("function") is None:
raise Exception(
@@ -6911,6 +6912,7 @@ class ProviderConfigManager:
from litellm.llms.elevenlabs.audio_transcription.transformation import (
ElevenLabsAudioTranscriptionConfig,
)
+
return ElevenLabsAudioTranscriptionConfig()
elif litellm.LlmProviders.OPENAI == provider:
if "gpt-4o" in model:
diff --git a/tests/llm_translation/test_gemini.py b/tests/llm_translation/test_gemini.py
index 0f094552820..5a7f15af2d9 100644
--- a/tests/llm_translation/test_gemini.py
+++ b/tests/llm_translation/test_gemini.py
@@ -15,11 +15,13 @@ from litellm.llms.vertex_ai.context_caching.transformation import (
)
import litellm
from litellm import completion
+import json
+
class TestGoogleAIStudioGemini(BaseLLMChatTest):
def get_base_completion_call_args(self) -> dict:
return {"model": "gemini/gemini-2.0-flash"}
-
+
def get_base_completion_call_args_with_reasoning_model(self) -> dict:
return {"model": "gemini/gemini-2.5-flash-preview-04-17"}
@@ -34,6 +36,7 @@ class TestGoogleAIStudioGemini(BaseLLMChatTest):
def test_url_context(self):
from litellm.utils import supports_url_context
+
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
@@ -46,14 +49,22 @@ class TestGoogleAIStudioGemini(BaseLLMChatTest):
response = self.completion_function(
**base_completion_call_args,
- messages=[{"role": "user", "content": "Summarize the content of this URL: https://en.wikipedia.org/wiki/Artificial_intelligence"}],
+ messages=[
+ {
+ "role": "user",
+ "content": "Summarize the content of this URL: https://en.wikipedia.org/wiki/Artificial_intelligence",
+ }
+ ],
tools=[{"urlContext": {}}],
)
assert response is not None
- assert response.model_extra['vertex_ai_url_context_metadata'] is not None, "URL context metadata should be present"
+ assert (
+ response.model_extra["vertex_ai_url_context_metadata"] is not None
+ ), "URL context metadata should be present"
print(f"response={response}")
+
def test_gemini_context_caching_separate_messages():
messages = [
# System Message
@@ -111,7 +122,6 @@ def test_gemini_image_generation():
assert response.choices[0].message.content is not None
-
def test_gemini_thinking():
litellm._turn_on_debug()
from litellm.types.utils import Message, CallTypes
@@ -119,10 +129,20 @@ def test_gemini_thinking():
import json
messages = [
- {"role": "user", "content": "Explain the concept of Occam's Razor and provide a simple, everyday example"}
+ {
+ "role": "user",
+ "content": "Explain the concept of Occam's Razor and provide a simple, everyday example",
+ }
]
reasoning_content = "I'm thinking about Occam's Razor."
- assistant_message = Message(content='Okay, let\'s break down Occam\'s Razor.', reasoning_content=reasoning_content, role='assistant', tool_calls=None, function_call=None, provider_specific_fields=None)
+ assistant_message = Message(
+ content="Okay, let's break down Occam's Razor.",
+ reasoning_content=reasoning_content,
+ role="assistant",
+ tool_calls=None,
+ function_call=None,
+ provider_specific_fields=None,
+ )
messages.append(assistant_message)
@@ -131,12 +151,12 @@ def test_gemini_thinking():
kwargs={
"model": "gemini/gemini-2.5-flash-preview-04-17",
"messages": messages,
- }
+ },
)
assert reasoning_content in json.dumps(raw_request)
response = completion(
model="gemini/gemini-2.5-flash-preview-04-17",
- messages=messages, # make sure call works
+ messages=messages, # make sure call works
)
print(response.choices[0].message)
assert response.choices[0].message.content is not None
@@ -152,9 +172,14 @@ def test_gemini_thinking_budget_0():
endpoint=CallTypes.completion,
kwargs={
"model": "gemini/gemini-2.5-flash-preview-04-17",
- "messages": [{"role": "user", "content": "Explain the concept of Occam's Razor and provide a simple, everyday example"}],
- "thinking": {"type": "enabled", "budget_tokens": 0}
- }
+ "messages": [
+ {
+ "role": "user",
+ "content": "Explain the concept of Occam's Razor and provide a simple, everyday example",
+ }
+ ],
+ "thinking": {"type": "enabled", "budget_tokens": 0},
+ },
)
print(raw_request)
assert "0" in json.dumps(raw_request["raw_request_body"])
@@ -163,8 +188,13 @@ def test_gemini_thinking_budget_0():
def test_gemini_finish_reason():
import os
from litellm import completion
+
litellm._turn_on_debug()
- response = completion(model="gemini/gemini-1.5-pro", messages=[{"role": "user", "content": "give me 3 random words"}], max_tokens=2)
+ response = completion(
+ model="gemini/gemini-1.5-pro",
+ messages=[{"role": "user", "content": "give me 3 random words"}],
+ max_tokens=2,
+ )
print(response)
assert response.choices[0].finish_reason is not None
assert response.choices[0].finish_reason == "length"
@@ -172,6 +202,7 @@ def test_gemini_finish_reason():
def test_gemini_url_context():
from litellm import completion
+
litellm._turn_on_debug()
url = "https://ai.google.dev/gemini-api/docs/models"
@@ -180,23 +211,24 @@ def test_gemini_url_context():
{url}
"""
response = completion(
- model="gemini/gemini-2.0-flash",
- messages=[{"role": "user", "content": prompt}],
- tools=[{"urlContext": {}}],
- )
+ model="gemini/gemini-2.0-flash",
+ messages=[{"role": "user", "content": prompt}],
+ tools=[{"urlContext": {}}],
+ )
print(response)
message = response.choices[0].message.content
assert message is not None
- url_context_metadata = response.model_extra['vertex_ai_url_context_metadata']
+ url_context_metadata = response.model_extra["vertex_ai_url_context_metadata"]
assert url_context_metadata is not None
- urlMetadata = url_context_metadata[0]['urlMetadata'][0]
- assert urlMetadata['retrievedUrl'] == url
- assert urlMetadata['urlRetrievalStatus'] == 'URL_RETRIEVAL_STATUS_SUCCESS'
+ urlMetadata = url_context_metadata[0]["urlMetadata"][0]
+ assert urlMetadata["retrievedUrl"] == url
+ assert urlMetadata["urlRetrievalStatus"] == "URL_RETRIEVAL_STATUS_SUCCESS"
@pytest.mark.flaky(retries=3, delay=2)
def test_gemini_with_grounding():
from litellm import completion, Usage, stream_chunk_builder
+
litellm._turn_on_debug()
litellm.set_verbose = True
tools = [{"googleSearch": {}}]
@@ -207,10 +239,15 @@ def test_gemini_with_grounding():
# assert usage.prompt_tokens_details.web_search_requests is not None
# assert usage.prompt_tokens_details.web_search_requests > 0
-
## Check streaming
- response = completion(model="gemini/gemini-2.0-flash", messages=[{"role": "user", "content": "What is the capital of France?"}], tools=tools, stream=True, stream_options={"include_usage": True})
+ response = completion(
+ model="gemini/gemini-2.0-flash",
+ messages=[{"role": "user", "content": "What is the capital of France?"}],
+ tools=tools,
+ stream=True,
+ stream_options={"include_usage": True},
+ )
chunks = []
for chunk in response:
chunks.append(chunk)
@@ -226,6 +263,7 @@ def test_gemini_with_grounding():
def test_gemini_with_empty_function_call_arguments():
from litellm import completion
+
litellm._turn_on_debug()
tools = [
{
@@ -236,6 +274,100 @@ def test_gemini_with_empty_function_call_arguments():
},
}
]
- response = completion(model="gemini/gemini-2.0-flash", messages=[{"role": "user", "content": "What is the capital of France?"}], tools=tools)
+ response = completion(
+ model="gemini/gemini-2.0-flash",
+ messages=[{"role": "user", "content": "What is the capital of France?"}],
+ tools=tools,
+ )
print(response)
- assert response.choices[0].message.content is not None
\ No newline at end of file
+ assert response.choices[0].message.content is not None
+
+
+async def test_claude_tool_use_with_gemini():
+ response = await litellm.anthropic.messages.acreate(
+ messages=[
+ {"role": "user", "content": "Hello, can you tell me the weather in Boston?"}
+ ],
+ model="gemini/gemini-2.5-flash",
+ stream=True,
+ max_tokens=100,
+ tools=[
+ {
+ "name": "get_weather",
+ "description": "Get current weather information for a specific location",
+ "input_schema": {
+ "type": "object",
+ "properties": {"location": {"type": "string"}},
+ },
+ }
+ ],
+ )
+
+ is_content_block_tool_use = False
+ is_partial_json = False
+ has_usage_in_message_delta = False
+
+ async for chunk in response:
+ print(chunk)
+
+ # Handle bytes chunks (SSE format)
+ if isinstance(chunk, bytes):
+ chunk_str = chunk.decode("utf-8")
+
+ # Parse SSE format: event: <type>\ndata: <json>\n\n
+ if "data: " in chunk_str:
+ try:
+ # Extract JSON from data line
+ data_line = [
+ line
+ for line in chunk_str.split("\n")
+ if line.startswith("data: ")
+ ][0]
+ json_str = data_line[6:] # Remove 'data: ' prefix
+ chunk_data = json.loads(json_str)
+
+ # Check for tool_use
+ if "tool_use" in json_str:
+ is_content_block_tool_use = True
+ if "partial_json" in json_str:
+ is_partial_json = True
+
+ # Check for usage in message_delta with stop_reason
+ if (
+ chunk_data.get("type") == "message_delta"
+ and chunk_data.get("delta", {}).get("stop_reason") is not None
+ and "usage" in chunk_data
+ ):
+ has_usage_in_message_delta = True
+ # Verify usage has the expected structure
+ usage = chunk_data["usage"]
+ assert (
+ "input_tokens" in usage
+ ), "input_tokens should be present in usage"
+ assert (
+ "output_tokens" in usage
+ ), "output_tokens should be present in usage"
+ assert isinstance(
+ usage["input_tokens"], int
+ ), "input_tokens should be an integer"
+ assert isinstance(
+ usage["output_tokens"], int
+ ), "output_tokens should be an integer"
+ print(f"Found usage in message_delta: {usage}")
+
+ except (json.JSONDecodeError, IndexError) as e:
+ # Skip chunks that aren't valid JSON
+ pass
+ else:
+ # Handle dict chunks (fallback)
+ if "tool_use" in str(chunk):
+ is_content_block_tool_use = True
+ if "partial_json" in str(chunk):
+ is_partial_json = True
+
+ assert 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"
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
new file mode 100644
index 00000000000..55cfb171e5b
--- /dev/null
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
@@ -0,0 +1,64 @@
+import os
+import sys
+
+import pytest
+from fastapi.testclient import TestClient
+
+sys.path.insert(0, os.path.abspath("../../../../.."))
+
+from unittest.mock import MagicMock, patch
+
+from litellm.llms.anthropic.experimental_pass_through.adapters.transformation import (
+ LiteLLMAnthropicMessagesAdapter,
+)
+from litellm.types.utils import (
+ ChatCompletionDeltaToolCall,
+ Delta,
+ Function,
+ ModelResponse,
+ StreamingChoices,
+)
+
+
+def test_translate_streaming_openai_chunk_to_anthropic_content_block():
+ choices = [
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ provider_specific_fields=None,
+ content=None,
+ role="assistant",
+ function_call=None,
+ tool_calls=[
+ ChatCompletionDeltaToolCall(
+ id="call_d581d130-e234-4315-94e8-27e7ff7c4e55",
+ function=Function(
+ arguments='{"location": "Boston"}', name="get_weather"
+ ),
+ type="function",
+ index=0,
+ )
+ ],
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ]
+
+ (
+ block_type,
+ content_block_start,
+ ) = LiteLLMAnthropicMessagesAdapter()._translate_streaming_openai_chunk_to_anthropic_content_block(
+ choices=choices
+ )
+
+ print(content_block_start)
+
+ assert block_type == "tool_use"
+ assert content_block_start == {
+ "type": "tool_use",
+ "id": "call_d581d130-e234-4315-94e8-27e7ff7c4e55",
+ "name": "get_weather",
+ "input": {},
+ }