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: preserve auto-generated id when provider returns falsy id

Ryan Crabbe9c87484b0748
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 f98158f0124..a4a68255e80 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
@@ -628,7 +628,7 @@ def convert_to_model_response_object( # noqa: PLR0915
)
if "id" in response_object:
- model_response_object.id = response_object["id"]
+ model_response_object.id = response_object["id"] or model_response_object.id
if "system_fingerprint" in response_object:
model_response_object.system_fingerprint = response_object[
diff --git a/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py b/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py
index 6ae3d273e28..e7f87ff7ce6 100644
--- a/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py
+++ b/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py
@@ -1238,3 +1238,31 @@ def test_error_message_includes_function_args():
assert "received_args=" in error_msg
assert "response_object" in error_msg
assert "response_type" in error_msg
+
+
[email protected]("falsy_id", [None, ""])
+def test_convert_to_model_response_object_falsy_id_preserves_auto_generated(falsy_id):
+ """Test that a falsy id in response_object preserves the auto-generated id."""
+ mr = ModelResponse()
+ original_id = mr.id
+ response_object = {
+ "id": falsy_id,
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "Hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
+ "model": "test-model",
+ }
+ result = convert_to_model_response_object(
+ model_response_object=mr,
+ response_object=response_object,
+ stream=False,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+ assert result.id == original_id
+ assert result.id.startswith("chatcmpl-")