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(types): normalize null top_logprobs to [] in ChatCompletionTokenLogprob (#22245)

Shivaangd524b795743e
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 1b7089d7f10..f54a7ae71a1 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -32,7 +32,14 @@ from openai.types.moderation_create_response import Moderation as Moderation
from openai.types.moderation_create_response import (
ModerationCreateResponse as ModerationCreateResponse,
)
-from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_validator
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ PrivateAttr,
+ field_validator,
+ model_validator,
+)
from typing_extensions import Required, TypedDict
from litellm._uuid import uuid
@@ -856,6 +863,21 @@ class ChatCompletionTokenLogprob(OpenAIObject):
returned.
"""
+ # Some OpenAI-compatible providers return null for top_logprobs when
+ # omitted; normalize to [] to preserve the typed List[TopLogprob] contract.
+ @field_validator("top_logprobs", mode="before")
+ @classmethod
+ def ensure_top_logprobs_is_list(cls, v):
+ """Normalize null top_logprobs to empty list.
+
+ Some providers return null instead of [] when logprobs=true but
+ top_logprobs is unset. The OpenAI spec requires an array.
+ Fixes https://github.com/BerriAI/litellm/issues/21932
+ """
+ if v is None:
+ return []
+ return v
+
def __contains__(self, key):
# Define custom behavior for the 'in' operator
return hasattr(self, key)
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 a722aec7eb4..34e58deee28 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
@@ -1497,3 +1497,95 @@ def test_convert_to_model_response_object_default_usage_overwritten():
assert result.usage.prompt_tokens == 15
assert result.usage.completion_tokens == 7
assert result.usage.total_tokens == 22
+
+
+def test_convert_to_model_response_object_with_null_top_logprobs():
+ """
+ Test that convert_to_model_response_object handles null top_logprobs
+ without raising a Pydantic validation error.
+
+ Some providers return null for top_logprobs when logprobs=true but
+ top_logprobs is unset/0. The OpenAI spec requires top_logprobs to be
+ an array, so litellm should normalize null to [].
+
+ Regression test for https://github.com/BerriAI/litellm/issues/21932
+ """
+ response_object = {
+ "id": "chatcmpl-a21e454401074fd8814736d84dcbb1e4",
+ "object": "chat.completion",
+ "created": 1771632698,
+ "model": "my-model",
+ "choices": [
+ {
+ "index": 0,
+ "message": {
+ "role": "assistant",
+ "content": "Silent light above.",
+ },
+ "finish_reason": "stop",
+ "logprobs": {
+ "content": [
+ {
+ "token": "Sil",
+ "bytes": [83, 105, 108],
+ "logprob": -2.1518118381500244,
+ "top_logprobs": None,
+ },
+ {
+ "token": "ent",
+ "bytes": [101, 110, 116],
+ "logprob": -0.13957086205482483,
+ "top_logprobs": None,
+ },
+ {
+ "token": " light",
+ "bytes": [32, 108, 105, 103, 104, 116],
+ "logprob": -1.3923776149749756,
+ "top_logprobs": None,
+ },
+ {
+ "token": " above",
+ "bytes": [32, 97, 98, 111, 118, 101],
+ "logprob": -1.137486219406128,
+ "top_logprobs": None,
+ },
+ {
+ "token": ".",
+ "bytes": [46],
+ "logprob": -0.1709611415863037,
+ "top_logprobs": None,
+ },
+ ],
+ "refusal": None,
+ },
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 73,
+ "completion_tokens": 5,
+ "total_tokens": 78,
+ },
+ }
+
+ result = convert_to_model_response_object(
+ model_response_object=ModelResponse(),
+ response_object=response_object,
+ stream=False,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ hidden_params=None,
+ _response_headers=None,
+ convert_tool_call_to_json_mode=False,
+ )
+
+ assert isinstance(result, ModelResponse)
+ assert len(result.choices) == 1
+
+ choice = result.choices[0]
+ assert choice.logprobs is not None
+ assert len(choice.logprobs.content) == 5
+
+ # Verify all null top_logprobs were normalized to empty lists
+ for token_logprob in choice.logprobs.content:
+ assert token_logprob.top_logprobs == []
+ assert isinstance(token_logprob.top_logprobs, list)
diff --git a/tests/test_litellm/types/test_types_utils.py b/tests/test_litellm/types/test_types_utils.py
index a2dfb5268e3..70344950d3e 100644
--- a/tests/test_litellm/types/test_types_utils.py
+++ b/tests/test_litellm/types/test_types_utils.py
@@ -127,3 +127,98 @@ def test_usage_completion_tokens_details_text_tokens():
# Verify round-trip serialization works
new_usage = Usage(**dump_result)
assert new_usage.completion_tokens_details.text_tokens == 12
+
+
+def test_chat_completion_token_logprob_null_top_logprobs():
+ """
+ Test that ChatCompletionTokenLogprob normalizes null top_logprobs to [].
+
+ Some providers return null for top_logprobs when logprobs=true but
+ top_logprobs is unset. The OpenAI spec requires top_logprobs to be an array.
+
+ Regression test for https://github.com/BerriAI/litellm/issues/21932
+ """
+ from litellm.types.utils import ChatCompletionTokenLogprob
+
+ logprob = ChatCompletionTokenLogprob(
+ token="Hello",
+ bytes=[72, 101, 108, 108, 111],
+ logprob=-0.31725305,
+ top_logprobs=None,
+ )
+ assert logprob.top_logprobs == []
+ assert isinstance(logprob.top_logprobs, list)
+
+
+def test_chat_completion_token_logprob_valid_top_logprobs():
+ """
+ Test that ChatCompletionTokenLogprob still accepts valid top_logprobs arrays.
+ """
+ from litellm.types.utils import ChatCompletionTokenLogprob, TopLogprob
+
+ logprob = ChatCompletionTokenLogprob(
+ token="Hello",
+ bytes=[72, 101, 108, 108, 111],
+ logprob=-0.31725305,
+ top_logprobs=[
+ TopLogprob(
+ token="Hello", logprob=-0.31725305, bytes=[72, 101, 108, 108, 111]
+ ),
+ TopLogprob(token="Hi", logprob=-1.3190403, bytes=[72, 105]),
+ ],
+ )
+ assert len(logprob.top_logprobs) == 2
+ assert logprob.top_logprobs[0].token == "Hello"
+
+
+def test_choice_logprobs_with_null_top_logprobs():
+ """
+ Test that ChoiceLogprobs correctly parses content tokens that have
+ null top_logprobs (the full nested parsing path).
+
+ Regression test for https://github.com/BerriAI/litellm/issues/21932
+ """
+ from litellm.types.utils import ChoiceLogprobs
+
+ logprobs_dict = {
+ "content": [
+ {
+ "token": "Sil",
+ "bytes": [83, 105, 108],
+ "logprob": -2.1518118381500244,
+ "top_logprobs": None,
+ },
+ {
+ "token": "ent",
+ "bytes": [101, 110, 116],
+ "logprob": -0.13957086205482483,
+ "top_logprobs": None,
+ },
+ ]
+ }
+
+ result = ChoiceLogprobs(**logprobs_dict)
+ assert result.content is not None
+ assert len(result.content) == 2
+ for token_logprob in result.content:
+ assert token_logprob.top_logprobs == []
+ assert isinstance(token_logprob.top_logprobs, list)
+
+
+def test_chat_completion_token_logprob_invalid_top_logprobs_rejected():
+ """
+ Test that invalid (non-list, non-null) top_logprobs values are still
+ rejected by Pydantic validation. The validator only normalizes null,
+ it does not coerce other invalid types.
+ """
+ from pydantic import ValidationError
+
+ from litellm.types.utils import ChatCompletionTokenLogprob
+
+ with pytest.raises(ValidationError):
+ ChatCompletionTokenLogprob(
+ token="Hello",
+ bytes=[72, 101, 108, 108, 111],
+ logprob=-0.31725305,
+ top_logprobs="invalid_string",
+ )