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]

fix(anthropic/chat/transformation.py): include cache creation token count in final prompt token value

Krrish Dholakia1162c526921a
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py
index c851ec06a6b..e338f5104e0 100644
--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py
+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py
@@ -113,20 +113,30 @@ def _generic_cost_per_character(
return prompt_cost, completion_cost
-def _get_token_base_cost(model_info: ModelInfo, usage: Usage) -> Tuple[float, float, float, float]:
+def _get_token_base_cost(
+ model_info: ModelInfo, usage: Usage
+) -> Tuple[float, float, float, float]:
"""
Return prompt cost, completion cost, and cache costs for a given model and usage.
If input_tokens > threshold and `input_cost_per_token_above_[x]k_tokens` or `input_cost_per_token_above_[x]_tokens` is set,
then we use the corresponding threshold cost for all token types.
-
+
Returns:
Tuple[float, float, float, float] - (prompt_cost, completion_cost, cache_creation_cost, cache_read_cost)
"""
- prompt_base_cost = cast(float, _get_cost_per_unit(model_info, "input_cost_per_token"))
- completion_base_cost = cast(float, _get_cost_per_unit(model_info, "output_cost_per_token"))
- cache_creation_cost = cast(float, _get_cost_per_unit(model_info, "cache_creation_input_token_cost"))
- cache_read_cost = cast(float, _get_cost_per_unit(model_info, "cache_read_input_token_cost"))
+ prompt_base_cost = cast(
+ float, _get_cost_per_unit(model_info, "input_cost_per_token")
+ )
+ completion_base_cost = cast(
+ float, _get_cost_per_unit(model_info, "output_cost_per_token")
+ )
+ cache_creation_cost = cast(
+ float, _get_cost_per_unit(model_info, "cache_creation_input_token_cost")
+ )
+ cache_read_cost = cast(
+ float, _get_cost_per_unit(model_info, "cache_read_input_token_cost")
+ )
## CHECK IF ABOVE THRESHOLD
threshold: Optional[float] = None
@@ -140,27 +150,44 @@ def _get_token_base_cost(model_info: ModelInfo, usage: Usage) -> Tuple[float, fl
)
if usage.prompt_tokens > threshold:
- prompt_base_cost = cast(float, _get_cost_per_unit(model_info, key, prompt_base_cost))
- completion_base_cost = cast(float, _get_cost_per_unit(
- model_info,
- f"output_cost_per_token_above_{threshold_str}_tokens",
- completion_base_cost,
- ))
-
+ prompt_base_cost = cast(
+ float, _get_cost_per_unit(model_info, key, prompt_base_cost)
+ )
+ completion_base_cost = cast(
+ float,
+ _get_cost_per_unit(
+ model_info,
+ f"output_cost_per_token_above_{threshold_str}_tokens",
+ completion_base_cost,
+ ),
+ )
+
# Apply tiered pricing to cache costs
- cache_creation_tiered_key = f"cache_creation_input_token_cost_above_{threshold_str}_tokens"
- cache_read_tiered_key = f"cache_read_input_token_cost_above_{threshold_str}_tokens"
-
+ cache_creation_tiered_key = (
+ f"cache_creation_input_token_cost_above_{threshold_str}_tokens"
+ )
+ cache_read_tiered_key = (
+ f"cache_read_input_token_cost_above_{threshold_str}_tokens"
+ )
+
if cache_creation_tiered_key in model_info:
- cache_creation_cost = cast(float, _get_cost_per_unit(
- model_info, cache_creation_tiered_key, cache_creation_cost
- ))
-
+ cache_creation_cost = cast(
+ float,
+ _get_cost_per_unit(
+ model_info,
+ cache_creation_tiered_key,
+ cache_creation_cost,
+ ),
+ )
+
if cache_read_tiered_key in model_info:
- cache_read_cost = cast(float, _get_cost_per_unit(
- model_info, cache_read_tiered_key, cache_read_cost
- ))
-
+ cache_read_cost = cast(
+ float,
+ _get_cost_per_unit(
+ model_info, cache_read_tiered_key, cache_read_cost
+ ),
+ )
+
break
except (IndexError, ValueError):
continue
@@ -195,7 +222,9 @@ def calculate_cost_component(
return 0.0
-def _get_cost_per_unit(model_info: ModelInfo, cost_key: str, default_value: Optional[float] = 0.0) -> Optional[float]:
+def _get_cost_per_unit(
+ model_info: ModelInfo, cost_key: str, default_value: Optional[float] = 0.0
+) -> Optional[float]:
# Sometimes the cost per unit is a string (e.g.: If a value like "3e-7" was read from the config.yaml)
cost_per_unit = model_info.get(cost_key)
if isinstance(cost_per_unit, float):
@@ -210,7 +239,6 @@ def _get_cost_per_unit(model_info: ModelInfo, cost_key: str, default_value: Opti
f"litellm.litellm_core_utils.llm_cost_calc.utils.py::calculate_cost_per_component(): Exception occured - {cost_per_unit}\nDefaulting to 0.0"
)
return default_value
-
def generic_cost_per_token(
@@ -238,6 +266,7 @@ def generic_cost_per_token(
### PROCESSING COST
text_tokens = usage.prompt_tokens
cache_hit_tokens = 0
+ cache_creation_tokens = 0
audio_tokens = 0
character_count = 0
image_count = 0
@@ -278,12 +307,19 @@ def generic_cost_per_token(
or 0
)
+ if getattr(usage, "_cache_creation_input_tokens", 0) is not None:
+ cache_creation_tokens = usage._cache_creation_input_tokens
## EDGE CASE - text tokens not set inside PromptTokensDetails
if text_tokens == 0:
- text_tokens = usage.prompt_tokens - cache_hit_tokens - audio_tokens
+ text_tokens = (
+ usage.prompt_tokens
+ - cache_hit_tokens
+ - audio_tokens
+ - cache_creation_tokens
+ )
- prompt_base_cost, completion_base_cost, cache_creation_cost, cache_read_cost = _get_token_base_cost(
- model_info=model_info, usage=usage
+ prompt_base_cost, completion_base_cost, cache_creation_cost, cache_read_cost = (
+ _get_token_base_cost(model_info=model_info, usage=usage)
)
prompt_cost = float(text_tokens) * prompt_base_cost
@@ -350,8 +386,12 @@ def generic_cost_per_token(
## TEXT COST
completion_cost = float(text_tokens) * completion_base_cost
- _output_cost_per_audio_token = _get_cost_per_unit(model_info, "output_cost_per_audio_token", None)
- _output_cost_per_reasoning_token = _get_cost_per_unit(model_info, "output_cost_per_reasoning_token", None)
+ _output_cost_per_audio_token = _get_cost_per_unit(
+ model_info, "output_cost_per_audio_token", None
+ )
+ _output_cost_per_reasoning_token = _get_cost_per_unit(
+ model_info, "output_cost_per_reasoning_token", None
+ )
## AUDIO COST
if not is_text_tokens_total and audio_tokens is not None and audio_tokens > 0:
@@ -397,7 +437,7 @@ class CostCalculatorUtils:
]:
return True
return False
-
+
@staticmethod
def route_image_generation_cost_calculator(
model: str,
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py
index ce874bfde9a..1a59d677415 100644
--- a/litellm/llms/anthropic/chat/transformation.py
+++ b/litellm/llms/anthropic/chat/transformation.py
@@ -200,8 +200,12 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
)
_allowed_properties = set(AnthropicInputSchema.__annotations__.keys())
- input_schema_filtered = {k: v for k, v in _input_schema.items() if k in _allowed_properties}
- input_anthropic_schema: AnthropicInputSchema = AnthropicInputSchema(**input_schema_filtered)
+ input_schema_filtered = {
+ k: v for k, v in _input_schema.items() if k in _allowed_properties
+ }
+ input_anthropic_schema: AnthropicInputSchema = AnthropicInputSchema(
+ **input_schema_filtered
+ )
_tool = AnthropicMessagesTool(
name=tool["function"]["name"],
@@ -822,6 +826,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
and _usage["cache_creation_input_tokens"] is not None
):
cache_creation_input_tokens = _usage["cache_creation_input_tokens"]
+ prompt_tokens += cache_creation_input_tokens
if (
"cache_read_input_tokens" in _usage
and _usage["cache_read_input_tokens"] is not None
diff --git a/tests/llm_translation/base_llm_unit_tests.py b/tests/llm_translation/base_llm_unit_tests.py
index 3c7d20ac950..019f255430c 100644
--- a/tests/llm_translation/base_llm_unit_tests.py
+++ b/tests/llm_translation/base_llm_unit_tests.py
@@ -25,6 +25,7 @@ from litellm.utils import (
from litellm.main import stream_chunk_builder
from typing import Union
from litellm.types.utils import Usage, ModelResponse
+
# test_example.py
from abc import ABC, abstractmethod
from openai import OpenAI
@@ -119,7 +120,7 @@ class BaseLLMChatTest(ABC):
pytest.skip("Model is overloaded")
assert response.choices[0].message.content is not None
-
+
def test_content_list_handling(self):
"""Check if content list is supported by LLM API"""
base_completion_call_args = self.get_base_completion_call_args()
@@ -141,10 +142,10 @@ class BaseLLMChatTest(ABC):
# for OpenAI the content contains the JSON schema, so we need to assert that the content is not None
assert response.choices[0].message.content is not None
-
def test_tool_call_with_property_type_array(self):
litellm._turn_on_debug()
from litellm.utils import supports_function_calling
+
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
@@ -155,33 +156,33 @@ class BaseLLMChatTest(ABC):
base_completion_call_args = self.get_base_completion_call_args()
response = self.completion_function(
**base_completion_call_args,
- messages = [
+ messages=[
{
- "role": "user",
- "content": "Tell me if the shoe brand Air Jordan has more models than the shoe brand Nike."
+ "role": "user",
+ "content": "Tell me if the shoe brand Air Jordan has more models than the shoe brand Nike.",
}
- ],
- tools = [
+ ],
+ tools=[
{
- "type": "function",
- "function": {
- "name": "shoe_get_id",
- "description": "Get information about a show by its ID or name",
- "parameters": {
- "type": "object",
- "properties": {
- "shoe_id": {
- "type": ["string", "number"],
- "description": "The shoe ID or name"
- }
+ "type": "function",
+ "function": {
+ "name": "shoe_get_id",
+ "description": "Get information about a show by its ID or name",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "shoe_id": {
+ "type": ["string", "number"],
+ "description": "The shoe ID or name",
+ }
+ },
+ "required": ["shoe_id"],
+ "additionalProperties": False,
+ "$schema": "http://json-schema.org/draft-07/schema#",
},
- "required": ["shoe_id"],
- "additionalProperties": False,
- "$schema": "http://json-schema.org/draft-07/schema#"
- }
- }
+ },
},
- ]
+ ],
)
print(response)
print(json.dumps(response, indent=4, default=str))
@@ -189,6 +190,7 @@ class BaseLLMChatTest(ABC):
def test_tool_call_with_empty_enum_property(self):
litellm._turn_on_debug()
from litellm.utils import supports_function_calling
+
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
@@ -199,13 +201,13 @@ class BaseLLMChatTest(ABC):
base_completion_call_args = self.get_base_completion_call_args()
response = self.completion_function(
**base_completion_call_args,
- messages = [
+ messages=[
{
"role": "user",
- "content": "Search for the latest iPhone models and tell me which storage options are available."
+ "content": "Search for the latest iPhone models and tell me which storage options are available.",
}
- ],
- tools = [
+ ],
+ tools=[
{
"type": "function",
"function": {
@@ -225,28 +227,25 @@ class BaseLLMChatTest(ABC):
"product_search_with_aggregation",
],
"title": "Search Mode",
- "type": "string"
+ "type": "string",
},
},
- "required": [
- "search_mode"
- ],
+ "required": ["search_mode"],
"title": "product_search_arguments",
- "type": "object"
- }
- }
+ "type": "object",
+ },
+ },
}
- ]
+ ],
)
print(response)
print(json.dumps(response, indent=4, default=str))
-
-
def test_streaming(self):
"""Check if litellm handles streaming correctly"""
from litellm.types.utils import ModelResponseStream
from typing import Optional
+
base_completion_call_args = self.get_base_completion_call_args()
# litellm.set_verbose = True
messages = [
@@ -294,9 +293,9 @@ class BaseLLMChatTest(ABC):
self.completion_function(**base_completion_call_args, messages=messages)
-
def test_web_search(self):
from litellm.utils import supports_web_search
+
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
@@ -309,7 +308,9 @@ class BaseLLMChatTest(ABC):
response = self.completion_function(
**base_completion_call_args,
- messages=[{"role": "user", "content": "What's the weather like in Boston today?"}],
+ messages=[
+ {"role": "user", "content": "What's the weather like in Boston today?"}
+ ],
web_search_options={},
max_tokens=100,
)
@@ -320,6 +321,7 @@ class BaseLLMChatTest(ABC):
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="")
@@ -332,7 +334,12 @@ class BaseLLMChatTest(ABC):
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": {}}],
)
@@ -343,12 +350,12 @@ class BaseLLMChatTest(ABC):
@pytest.mark.asyncio
async def test_pdf_handling(self, pdf_messages, sync_mode):
from litellm.utils import supports_pdf_input
+
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
litellm._turn_on_debug()
-
image_content = [
{"type": "text", "text": "What's this file about?"},
{
@@ -382,12 +389,12 @@ class BaseLLMChatTest(ABC):
@pytest.mark.asyncio
async def test_async_pdf_handling_with_file_id(self):
from litellm.utils import supports_pdf_input
+
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
litellm._turn_on_debug()
-
image_content = [
{"type": "text", "text": "What's this file about?"},
{
@@ -411,12 +418,13 @@ class BaseLLMChatTest(ABC):
)
assert response is not None
-
-
+
def test_file_data_unit_test(self, pdf_messages):
from litellm.utils import supports_pdf_input, return_raw_request
from litellm.types.utils import CallTypes
- from litellm.litellm_core_utils.prompt_templates.factory import convert_to_anthropic_image_obj
+ from litellm.litellm_core_utils.prompt_templates.factory import (
+ convert_to_anthropic_image_obj,
+ )
media_chunk = convert_to_anthropic_image_obj(
openai_image_url=pdf_messages,
@@ -429,7 +437,7 @@ class BaseLLMChatTest(ABC):
"type": "file",
"file": {
"file_data": pdf_messages,
- }
+ },
},
]
@@ -740,6 +748,7 @@ class BaseLLMChatTest(ABC):
Test that audio input is supported by the LLM API
"""
from litellm.utils import supports_audio_input
+
litellm._turn_on_debug()
base_completion_call_args = self.get_base_completion_call_args()
if not supports_audio_input(base_completion_call_args["model"], None):
@@ -771,8 +780,6 @@ class BaseLLMChatTest(ABC):
print(completion.choices[0].message)
-
-
@pytest.mark.flaky(retries=6, delay=1)
def test_json_response_format_stream(self):
"""
@@ -1010,6 +1017,8 @@ class BaseLLMChatTest(ABC):
max_tokens=10,
)
+ print("response=", response)
+
initial_cost = response._hidden_params["response_cost"]
## call 2
response = self.completion_function(
@@ -1059,7 +1068,7 @@ class BaseLLMChatTest(ABC):
url = f"data:application/pdf;base64,{encoded_file}"
return url
-
+
@pytest.mark.flaky(retries=3, delay=1)
def test_empty_tools(self):
"""
@@ -1079,8 +1088,12 @@ class BaseLLMChatTest(ABC):
if not supports_function_calling(base_completion_call_args["model"], None):
print("Model does not support function calling")
pytest.skip("Model does not support function calling")
-
- response = completion(**base_completion_call_args, messages=[{"role": "user", "content": "Hello, how are you?"}], tools=[]) # just make sure call doesn't fail
+
+ response = completion(
+ **base_completion_call_args,
+ messages=[{"role": "user", "content": "Hello, how are you?"}],
+ tools=[],
+ ) # just make sure call doesn't fail
print("response: ", response)
assert response is not None
except litellm.ContentPolicyViolationError:
@@ -1156,8 +1169,13 @@ class BaseLLMChatTest(ABC):
except Exception as e:
print(f"Error: {e}")
pass
- if "<thinking>" in response.choices[0].message.content and "</thinking>" in response.choices[0].message.content:
- pytest.fail("Thinking block returned in content instead of separate reasoning_content")
+ if (
+ "<thinking>" in response.choices[0].message.content
+ and "</thinking>" in response.choices[0].message.content
+ ):
+ pytest.fail(
+ "Thinking block returned in content instead of separate reasoning_content"
+ )
if response.choices[0].message.tool_calls is None:
return
# Add any assertions here to check the response
@@ -1168,7 +1186,9 @@ class BaseLLMChatTest(ABC):
assert isinstance(
response.choices[0].message.tool_calls[0].function.arguments, str
)
- assert response.choices[0].finish_reason == "tool_calls", f"finish_reason: {response.choices[0].finish_reason}, expected: tool_calls"
+ assert (
+ response.choices[0].finish_reason == "tool_calls"
+ ), f"finish_reason: {response.choices[0].finish_reason}, expected: tool_calls"
messages.append(
response.choices[0].message.model_dump()
) # Add assistant tool invokes
@@ -1232,10 +1252,10 @@ class BaseLLMChatTest(ABC):
def test_supports_audio_input(self, input_type, format_specified):
from litellm.utils import return_raw_request, supports_audio_input
from litellm.types.utils import CallTypes
+
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
-
litellm.drop_params = True
base_completion_call_args = self.get_base_completion_call_args()
if not supports_audio_input(base_completion_call_args["model"], None):
@@ -1249,20 +1269,17 @@ class BaseLLMChatTest(ABC):
audio_format = "wav"
encoded_string = base64.b64encode(wav_data).decode("utf-8")
- audio_content = [
- {
- "type": "text",
- "text": "What is in this recording?"
- }
- ]
+ audio_content = [{"type": "text", "text": "What is in this recording?"}]
test_file_id = "gs://bucket/file.wav"
if input_type == "input_audio":
- audio_content.append({
- "type": "input_audio",
- "input_audio": {"data": encoded_string, "format": audio_format},
- })
+ audio_content.append(
+ {
+ "type": "input_audio",
+ "input_audio": {"data": encoded_string, "format": audio_format},
+ }
+ )
elif input_type == "audio_url":
audio_content.append(
{
@@ -1270,16 +1287,14 @@ class BaseLLMChatTest(ABC):
"file": {
"file_id": test_file_id,
"filename": "my-sample-audio-file",
- }
+ },
}
)
-
-
raw_request = return_raw_request(
endpoint=CallTypes.completion,
kwargs={
- **base_completion_call_args,
+ **base_completion_call_args,
"modalities": ["text", "audio"],
"audio": {"voice": "alloy", "format": audio_format},
"messages": [
@@ -1287,20 +1302,24 @@ class BaseLLMChatTest(ABC):
"role": "user",
"content": audio_content,
},
- ]
- }
+ ],
+ },
)
print("raw_request: ", raw_request)
if input_type == "input_audio":
- assert encoded_string in json.dumps(raw_request), "Audio data not sent to gemini"
+ assert encoded_string in json.dumps(
+ raw_request
+ ), "Audio data not sent to gemini"
elif input_type == "audio_url":
- assert test_file_id in json.dumps(raw_request), "Audio URL not sent to gemini"
-
+ assert test_file_id in json.dumps(
+ raw_request
+ ), "Audio URL not sent to gemini"
def test_function_calling_with_tool_response(self):
from litellm.utils import supports_function_calling
from litellm import completion
+
litellm._turn_on_debug()
try:
@@ -1311,7 +1330,7 @@ class BaseLLMChatTest(ABC):
if not supports_function_calling(base_completion_call_args["model"], None):
print("Model does not support function calling")
pytest.skip("Model does not support function calling")
-
+
def get_weather(city: str):
return f"City: {city}, Weather: Sunny with 34 degree Celcius"
@@ -1339,8 +1358,7 @@ class BaseLLMChatTest(ABC):
}
]
-
- messages = [{ "content": "How is the weather in Mumbai?","role": "user"}]
+ messages = [{"content": "How is the weather in Mumbai?", "role": "user"}]
response, iteration = "", 0
while True:
if response:
@@ -1404,7 +1422,9 @@ class BaseLLMChatTest(ABC):
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
- base_completion_call_args = self.get_base_completion_call_args_with_reasoning_model()
+ base_completion_call_args = (
+ self.get_base_completion_call_args_with_reasoning_model()
+ )
if len(base_completion_call_args) == 0:
print("base_completion_call_args is empty")
pytest.skip("Model does not support reasoning")
@@ -1416,14 +1436,16 @@ class BaseLLMChatTest(ABC):
model=base_completion_call_args["model"]
)
- ## CHECK PARAM MAPPING
+ ## CHECK PARAM MAPPING
optional_params = get_optional_params(
model=base_completion_call_args["model"],
custom_llm_provider=provider,
reasoning_effort="high",
)
# either accepts reasoning effort or thinking budget
- assert "reasoning_effort" in optional_params or "4096" in json.dumps(optional_params)
+ assert "reasoning_effort" in optional_params or "4096" in json.dumps(
+ optional_params
+ )
try:
litellm._turn_on_debug()
@@ -1436,7 +1458,6 @@ class BaseLLMChatTest(ABC):
except Exception as e:
pytest.fail(f"Error: {e}")
-
class BaseOSeriesModelsTest(ABC): # test across azure/openai
@abstractmethod
@@ -1614,8 +1635,14 @@ class BaseAnthropicChatTest(ABC):
**base_completion_call_args, **args, stream=False
)
- print("built_response.choices[0].message.content", built_response.choices[0].message.content)
- print("non_stream_response.choices[0].message.content", non_stream_response.choices[0].message.content)
+ print(
+ "built_response.choices[0].message.content",
+ built_response.choices[0].message.content,
+ )
+ print(
+ "non_stream_response.choices[0].message.content",
+ non_stream_response.choices[0].message.content,
+ )
assert (
json.loads(built_response.choices[0].message.content).keys()
== json.loads(non_stream_response.choices[0].message.content).keys()
@@ -1623,6 +1650,7 @@ class BaseAnthropicChatTest(ABC):
def test_completion_thinking_with_response_format(self):
from pydantic import BaseModel
+
litellm._turn_on_debug()
class RFormat(BaseModel):
@@ -1639,9 +1667,10 @@ class BaseAnthropicChatTest(ABC):
)
print(response)
-
+
def test_completion_thinking_with_max_tokens(self):
from pydantic import BaseModel
+
litellm._turn_on_debug()
base_completion_call_args = self.get_base_completion_call_args_with_thinking()
@@ -1654,10 +1683,10 @@ class BaseAnthropicChatTest(ABC):
)
print(response)
-
-
+
def test_completion_thinking_without_max_tokens(self):
from pydantic import BaseModel
+
litellm._turn_on_debug()
base_completion_call_args = self.get_base_completion_call_args_with_thinking()
@@ -1692,7 +1721,9 @@ class BaseAnthropicChatTest(ABC):
def test_anthropic_thinking_output_stream(self):
# litellm.set_verbose = True
try:
- base_completion_call_args = self.get_base_completion_call_args_with_thinking()
+ base_completion_call_args = (
+ self.get_base_completion_call_args_with_thinking()
+ )
resp = litellm.completion(
**base_completion_call_args,
messages=[{"role": "user", "content": "Tell me a joke."}],
@@ -1748,16 +1779,16 @@ class BaseReasoningLLMTests(ABC):
- test that the responses contain reasoning_content
- test that the usage contains reasoning_tokens
"""
+
@abstractmethod
def get_base_completion_call_args(self) -> dict:
"""Must return the base completion call args"""
pass
-
+
@property
def completion_function(self):
return litellm.completion
-
def test_non_streaming_reasoning_effort(self):
"""
Base test for non-streaming reasoning effort
@@ -1767,15 +1798,16 @@ class BaseReasoningLLMTests(ABC):
"""
litellm._turn_on_debug()
base_completion_call_args = self.get_base_completion_call_args()
- response: ModelResponse = self.completion_function(**base_completion_call_args, reasoning_effort="low")
-
+ response: ModelResponse = self.completion_function(
+ **base_completion_call_args, reasoning_effort="low"
+ )
+
# user gets `reasoning_content` in the response message
assert response.choices[0].message.reasoning_content is not None
assert isinstance(response.choices[0].message.reasoning_content, str)
# user get `reasoning_tokens`
assert response.usage.completion_tokens_details.reasoning_tokens > 0
-
def test_streaming_reasoning_effort(self):
"""
@@ -1784,17 +1816,15 @@ class BaseReasoningLLMTests(ABC):
- Assert that `reasoning_content` is not None from streaming response
- Assert that `reasoning_tokens` is greater than 0 from usage
"""
- #litellm._turn_on_debug()
+ # litellm._turn_on_debug()
base_completion_call_args = self.get_base_completion_call_args()
response: CustomStreamWrapper = self.completion_function(
**base_completion_call_args,
reasoning_effort="low",
stream=True,
- stream_options={
- "include_usage": True
- }
+ stream_options={"include_usage": True},
)
-
+
resoning_content: str = ""
usage: Usage = None
for chunk in response:
@@ -1809,6 +1839,3 @@ class BaseReasoningLLMTests(ABC):
print(f"usage: {usage}")
assert usage.completion_tokens_details.reasoning_tokens > 0
-
-
-
\ No newline at end of file