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]

Convert scientific notation str to int + Bubble up azure content filter results (#11655)

Krish Dholakia369922ef9048
diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
index a44d6c29e01..fb310bf33c7 100644
--- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
+++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
@@ -554,6 +554,13 @@ def convert_to_model_response_object( # noqa: PLR0915
and len(message.tool_calls) > 0
):
finish_reason = "tool_calls"
+
+ ## PROVIDER SPECIFIC FIELDS ##
+ provider_specific_fields = {}
+ for field in choice.keys():
+ if field not in Choices.model_fields.keys():
+ provider_specific_fields[field] = choice[field]
+
logprobs = choice.get("logprobs", None)
enhancements = choice.get("enhancements", None)
choice = Choices(
@@ -562,6 +569,7 @@ def convert_to_model_response_object( # noqa: PLR0915
message=message,
logprobs=logprobs,
enhancements=enhancements,
+ provider_specific_fields=provider_specific_fields,
)
choice_list.append(choice)
model_response_object.choices = choice_list
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 5767618c6e7..8c9a5c1e9f7 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -793,6 +793,13 @@ class Delta(OpenAIObject):
class Choices(OpenAIObject):
+ finish_reason: str
+ index: int
+ message: Message
+ logprobs: Optional[Union[ChoiceLogprobs, Any]] = None
+
+ provider_specific_fields: Optional[Dict[str, Any]] = Field(default=None)
+
def __init__(
self,
finish_reason=None,
@@ -800,31 +807,43 @@ class Choices(OpenAIObject):
message: Optional[Union[Message, dict]] = None,
logprobs: Optional[Union[ChoiceLogprobs, dict, Any]] = None,
enhancements=None,
+ provider_specific_fields: Optional[Dict[str, Any]] = None,
**params,
):
- super(Choices, self).__init__(**params)
if finish_reason is not None:
- self.finish_reason = map_finish_reason(
- finish_reason
- ) # set finish_reason for all responses
+ params["finish_reason"] = map_finish_reason(finish_reason)
else:
- self.finish_reason = "stop"
- self.index = index
+ params["finish_reason"] = "stop"
+ if index is not None:
+ params["index"] = index
+ else:
+ params["index"] = 0
if message is None:
- self.message = Message()
+ params["message"] = Message()
else:
if isinstance(message, Message):
- self.message = message
+ params["message"] = message
elif isinstance(message, dict):
- self.message = Message(**message)
+ params["message"] = Message(**message)
if logprobs is not None:
if isinstance(logprobs, dict):
- self.logprobs = ChoiceLogprobs(**logprobs)
+ params["logprobs"] = ChoiceLogprobs(**logprobs)
else:
- self.logprobs = logprobs
+ params["logprobs"] = logprobs
+ else:
+ params["logprobs"] = None
+ super(Choices, self).__init__(**params)
+
if enhancements is not None:
self.enhancements = enhancements
+ self.provider_specific_fields = provider_specific_fields
+
+ if self.logprobs is None:
+ del self.logprobs
+ if self.provider_specific_fields is None:
+ del self.provider_specific_fields
+
def __contains__(self, key):
# Define custom behavior for the 'in' operator
return hasattr(self, key)
diff --git a/litellm/utils.py b/litellm/utils.py
index 5d4effcf816..bb500181d25 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -532,9 +532,9 @@ def function_setup( # noqa: PLR0915
function_id: Optional[str] = kwargs["id"] if "id" in kwargs else None
## DYNAMIC CALLBACKS ##
- dynamic_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = (
- kwargs.pop("callbacks", None)
- )
+ dynamic_callbacks: Optional[
+ List[Union[str, Callable, CustomLogger]]
+ ] = kwargs.pop("callbacks", None)
all_callbacks = get_dynamic_callbacks(dynamic_callbacks=dynamic_callbacks)
if len(all_callbacks) > 0:
@@ -1240,9 +1240,9 @@ def client(original_function): # noqa: PLR0915
exception=e,
retry_policy=kwargs.get("retry_policy"),
)
- kwargs["retry_policy"] = (
- reset_retry_policy()
- ) # prevent infinite loops
+ kwargs[
+ "retry_policy"
+ ] = reset_retry_policy() # prevent infinite loops
litellm.num_retries = (
None # set retries to None to prevent infinite loops
)
@@ -2131,11 +2131,28 @@ def supports_embedding_image_input(
def _update_dictionary(existing_dict: Dict, new_dict: dict) -> dict:
for k, v in new_dict.items():
if v is not None:
- existing_dict[k] = v
+ # Convert stringified numbers to appropriate numeric types
+ existing_dict[k] = _convert_stringified_numbers(v)
return existing_dict
+def _convert_stringified_numbers(value):
+ """Convert stringified numbers (including scientific notation) to appropriate numeric types."""
+ if isinstance(value, str):
+ try:
+ # Try to convert to float first to handle scientific notation like "3e-07"
+ if "e" in value.lower() or "." in value:
+ return float(value)
+ # Try to convert to int for whole numbers like "8192"
+ else:
+ return int(value)
+ except (ValueError, TypeError):
+ # If conversion fails, return the original string
+ return value
+ return value
+
+
def register_model(model_cost: Union[str, dict]): # noqa: PLR0915
"""
Register new / Override existing models (and their pricing) to specific providers.
@@ -2154,6 +2171,7 @@ def register_model(model_cost: Union[str, dict]): # noqa: PLR0915
loaded_model_cost = {}
if isinstance(model_cost, dict):
+ # Convert stringified numbers to appropriate numeric types
loaded_model_cost = model_cost
elif isinstance(model_cost, str):
loaded_model_cost = litellm.get_model_cost_map(url=model_cost)
@@ -2873,10 +2891,10 @@ def pre_process_non_default_params(
if "response_format" in non_default_params:
if provider_config is not None:
- non_default_params["response_format"] = (
- provider_config.get_json_schema_from_pydantic_object(
- response_format=non_default_params["response_format"]
- )
+ non_default_params[
+ "response_format"
+ ] = provider_config.get_json_schema_from_pydantic_object(
+ response_format=non_default_params["response_format"]
)
else:
non_default_params["response_format"] = type_to_response_format_param(
@@ -3003,16 +3021,16 @@ def pre_process_optional_params(
True # so that main.py adds the function call to the prompt
)
if "tools" in non_default_params:
- optional_params["functions_unsupported_model"] = (
- non_default_params.pop("tools")
- )
+ optional_params[
+ "functions_unsupported_model"
+ ] = non_default_params.pop("tools")
non_default_params.pop(
"tool_choice", None
) # causes ollama requests to hang
elif "functions" in non_default_params:
- optional_params["functions_unsupported_model"] = (
- non_default_params.pop("functions")
- )
+ optional_params[
+ "functions_unsupported_model"
+ ] = non_default_params.pop("functions")
elif (
litellm.add_function_to_prompt
): # if user opts to add it to prompt instead
@@ -4095,9 +4113,9 @@ def _count_characters(text: str) -> int:
def get_response_string(response_obj: Union[ModelResponse, ModelResponseStream]) -> str:
- _choices: Union[List[Union[Choices, StreamingChoices]], List[StreamingChoices]] = (
- response_obj.choices
- )
+ _choices: Union[
+ List[Union[Choices, StreamingChoices]], List[StreamingChoices]
+ ] = response_obj.choices
response_str = ""
for choice in _choices:
diff --git a/tests/llm_translation/test_azure_openai.py b/tests/llm_translation/test_azure_openai.py
index 72ea3ec27e0..039eb434f54 100644
--- a/tests/llm_translation/test_azure_openai.py
+++ b/tests/llm_translation/test_azure_openai.py
@@ -589,3 +589,17 @@ async def test_azure_embedding_max_retries_0(
]
== max_retries
)
+
+
+def test_azure_safety_result():
+ """Bubble up safety result from Azure OpenAI"""
+ from litellm import completion
+ litellm._turn_on_debug()
+
+ response = completion(
+ model="azure/gpt-4o-new-test",
+ messages=[{"role": "user", "content": "Hello world"}],
+ )
+ print(f"response: {response}")
+ assert response.choices[0].message.content is not None
+ assert response.choices[0].provider_specific_fields is not None
\ No newline at end of file
diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py
index 156840d669e..6dfbb8b7e5b 100644
--- a/tests/test_litellm/test_utils.py
+++ b/tests/test_litellm/test_utils.py
@@ -2010,6 +2010,30 @@ class TestProxyFunctionCalling:
print(f"Could not test {model}: {e}")
+def test_register_model_with_scientific_notation():
+ """
+ Test that the register_model function can handle scientific notation in the model name.
+ """
+ model_cost_dict = {
+ "my-custom-model": {
+ "max_tokens": 8192,
+ "input_cost_per_token": "3e-07",
+ "output_cost_per_token": "6e-07",
+ "litellm_provider": "openai",
+ "mode": "chat",
+ },
+ }
+
+ litellm.register_model(model_cost_dict)
+
+ registered_model = litellm.model_cost["my-custom-model"]
+ print(registered_model)
+ assert registered_model["input_cost_per_token"] == 3e-07
+ assert registered_model["output_cost_per_token"] == 6e-07
+ assert registered_model["litellm_provider"] == "openai"
+ assert registered_model["mode"] == "chat"
+
+
if __name__ == "__main__":
# Allow running this test file directly for debugging
pytest.main([__file__, "-v"])
diff --git a/tests/test_litellm/types/test_types_utils.py b/tests/test_litellm/types/test_types_utils.py
index 880616fc883..6bb998b8d1b 100644
--- a/tests/test_litellm/types/test_types_utils.py
+++ b/tests/test_litellm/types/test_types_utils.py
@@ -33,3 +33,9 @@ def test_chat_completion_delta_tool_call():
)
assert "function" in tool
+
+
+def test_empty_choices():
+ from litellm.types.utils import Choices
+
+ Choices()