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(responses): return the first message item as content for structured output on the chat bridge (#46508)

Kerry Lu6d1a3bce2c39
diff --git a/litellm/completion_extras/litellm_responses_transformation/handler.py b/litellm/completion_extras/litellm_responses_transformation/handler.py
index edc32dc487a..3f7017eccc2 100644
--- a/litellm/completion_extras/litellm_responses_transformation/handler.py
+++ b/litellm/completion_extras/litellm_responses_transformation/handler.py
@@ -2,8 +2,14 @@
Handler for transforming /chat/completions api requests to litellm.responses requests
"""
-from collections.abc import AsyncIterable, Coroutine, Iterable
-from typing import TYPE_CHECKING, Any, Final, Union
+from collections.abc import AsyncIterable, Coroutine, Iterable, Mapping
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Final,
+ Union,
+ cast, # noqa: TID251 # optional_params reaches the bridge as an untyped dict
+)
from typing_extensions import TypedDict
@@ -245,10 +251,15 @@ class ResponsesToCompletionBridgeHandler:
else:
if self._is_preformatted_cached_chat_stream(result):
return self._apply_post_stream_processing(result, model, custom_llm_provider)
+ from .transformation import is_structured_output_request
+
completion_stream: Final = self.transformation_handler.get_model_response_iterator(
streaming_response=result,
sync_stream=True,
json_mode=kwargs.get("json_mode"),
+ structured_output=is_structured_output_request(
+ cast("Mapping[str, object]", optional_params) # cast-ok: optional_params is an untyped dict
+ ),
)
streamwrapper: Final = CustomStreamWrapper(
completion_stream=completion_stream,
@@ -343,10 +354,15 @@ class ResponsesToCompletionBridgeHandler:
else:
if self._is_preformatted_cached_chat_stream(result):
return self._apply_post_stream_processing(result, model, custom_llm_provider)
+ from .transformation import is_structured_output_request
+
completion_stream: Final = self.transformation_handler.get_model_response_iterator(
streaming_response=result,
sync_stream=False,
json_mode=kwargs.get("json_mode"),
+ structured_output=is_structured_output_request(
+ cast("Mapping[str, object]", optional_params) # cast-ok: optional_params is an untyped dict
+ ),
)
streamwrapper: Final = CustomStreamWrapper(
completion_stream=completion_stream,
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 2e4bb47654e..638acfe0723 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -20,7 +20,7 @@ from openai.types.responses.response_input_param import (
from openai.types.responses.tool_choice_custom_param import ToolChoiceCustomParam
from openai.types.responses.tool_choice_function_param import ToolChoiceFunctionParam
from openai.types.responses.tool_param import FunctionToolParam
-from pydantic import BaseModel, TypeAdapter, ValidationError
+from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError
import litellm
from litellm import ModelResponse
@@ -346,14 +346,20 @@ def _fold_choices_into_one(
tool_calls: Sequence[Mapping[str, object]],
trailing_reasoning_content: str | None,
trailing_reasoning_item: _BuiltReasoningItem | None,
+ structured_output: bool = False,
) -> "Choices":
- """Clients that only read choices[0] must still see every text and tool call."""
+ """Clients that only read choices[0] must still see every text and tool call.
+
+ Under a structured ``response_format`` each message item is a complete document, so
+ ``content`` is the first one, the same item the openai SDK returns as ``output_parsed``.
+ """
from litellm.types.utils import Choices, Message
messages: Final = tuple(choice.message for choice in choices)
- texts: Final = tuple(str(message.content or "") for message in messages)
+ content_messages: Final = messages[:1] if structured_output else messages
+ texts: Final = tuple(str(message.content or "") for message in content_messages)
offsets: Final = (0, *accumulate(len(text) for text in texts))
- annotations: Final = tuple(_shifted_annotations(messages, offsets))
+ annotations: Final = tuple(_shifted_annotations(content_messages, offsets))
reasoning_contents: Final = (*(_message_reasoning_content(m) for m in messages), trailing_reasoning_content)
reasoning_items: Final = (
*chain.from_iterable(_message_reasoning_items(m) for m in messages),
@@ -373,6 +379,38 @@ def _fold_choices_into_one(
)
+def _responses_event_type(chunk: Mapping[str, object]) -> object:
+ event_type: Final = chunk.get("type")
+ return event_type.value if isinstance(event_type, ResponsesAPIStreamEvents) else event_type
+
+
+class _TypedPayload(BaseModel):
+ """The ``type`` discriminator of a response_format dict or a Responses output item."""
+
+ model_config = ConfigDict(frozen=True, extra="ignore")
+ type: str | None = None
+
+
+_TYPED_PAYLOAD: Final = TypeAdapter(_TypedPayload)
+
+
+def _payload_type(payload: object) -> str | None:
+ try:
+ return _TYPED_PAYLOAD.validate_python(payload).type
+ except ValidationError:
+ return None
+
+
+def _is_message_item_done(chunk: Mapping[str, object]) -> bool:
+ if _responses_event_type(chunk) != ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE.value:
+ return False
+ return _payload_type(chunk.get("item")) == "message"
+
+
+def is_structured_output_request(optional_params: Mapping[str, object]) -> bool:
+ return _payload_type(optional_params.get("response_format")) in ("json_schema", "json_object")
+
+
_ToolChoiceT = TypeVar("_ToolChoiceT")
@@ -897,6 +935,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
def _convert_response_output_to_choices(
output_items: Sequence[object],
handle_raw_dict_callback: Callable[..., tuple["Choices | None", int]] | None = None,
+ structured_output: bool = False,
) -> list["Choices"]:
"""
Convert Responses API output items to chat completion choices.
@@ -904,6 +943,8 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
Args:
output_items: List of items from ResponsesAPIResponse.output
handle_raw_dict_callback: Optional callback for handling raw dict items
+ structured_output: The chat request carried a json response_format, so only the
+ first message item becomes content
Returns:
List of Choices objects
@@ -1027,6 +1068,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
tool_calls=accumulated_tool_calls,
trailing_reasoning_content=reasoning_content,
trailing_reasoning_item=pending_reasoning_item,
+ structured_output=structured_output,
)
]
@@ -1157,6 +1199,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
choices: Final = self._convert_response_output_to_choices(
output_items=output_items,
handle_raw_dict_callback=self._handle_raw_dict_response_item,
+ structured_output=is_structured_output_request(
+ cast("Mapping[str, object]", optional_params) # cast-ok: optional_params is an untyped dict
+ ),
)
response_is_incomplete: Final = raw_response.status == "incomplete" or (
@@ -1219,8 +1264,11 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
streaming_response: Union[Iterator[str], AsyncIterator[str], "ModelResponse", "BaseModel"],
sync_stream: bool,
json_mode: bool | None = False,
+ structured_output: bool = False,
) -> BaseModelResponseIterator:
- return OpenAiResponsesToChatCompletionStreamIterator(streaming_response, sync_stream, json_mode)
+ return OpenAiResponsesToChatCompletionStreamIterator(
+ streaming_response, sync_stream, json_mode, structured_output=structured_output
+ )
def _convert_content_str_to_input_text(self, content: str, role: str) -> dict[str, object]:
if role in ("user", "system", "developer", "tool"):
@@ -1587,11 +1635,14 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator):
streaming_response: Union[Iterator[str], AsyncIterator[str], "ModelResponse", "BaseModel"],
sync_stream: bool,
json_mode: bool | None = False,
+ structured_output: bool = False,
):
super().__init__(streaming_response, sync_stream, json_mode)
self._chat_completion_id: str | None = None
self._served_service_tier: str | None = None
self._tool_call_index_map: dict[int, int] = {} # mutable-ok: per-stream accumulator state
+ self._structured_output: Final = structured_output
+ self._first_message_item_done: bool = False
def _handle_string_chunk(
self, str_line: Union[str, "BaseModel"]
@@ -1903,13 +1954,31 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator):
"""
verbose_logger.debug("Chat provider: transform_streaming_response called with chunk: %s", chunk)
self._remember_served_service_tier(chunk)
- return self._with_served_service_tier(
- self._with_stream_scoped_id(
- OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(
- chunk, tool_call_index_map=self._tool_call_index_map
- )
+ translated: Final = (
+ self._empty_content_chunk()
+ if self._is_text_delta_after_structured_answer(chunk)
+ else OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(
+ chunk, tool_call_index_map=self._tool_call_index_map
)
)
+ if self._structured_output and _is_message_item_done(chunk):
+ self._first_message_item_done = True
+ return self._with_served_service_tier(self._with_stream_scoped_id(translated))
+
+ def _is_text_delta_after_structured_answer(self, chunk: Mapping[str, object]) -> bool:
+ """Under a structured response_format the first message item is the whole answer, so
+ text from any later message item is dropped, matching the non-stream fold."""
+ return (
+ self._structured_output
+ and self._first_message_item_done
+ and _responses_event_type(chunk) == ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA.value
+ )
+
+ @staticmethod
+ def _empty_content_chunk() -> "ModelResponseStream":
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ return ModelResponseStream(choices=[StreamingChoices(index=0, delta=Delta(content=""), finish_reason=None)])
def _remember_served_service_tier(self, chunk: dict[str, object]) -> None:
response_payload: Final = chunk.get("response")
diff --git a/tests/integration/providers/test_responses_bridge_incomplete.py b/tests/integration/providers/test_responses_bridge_incomplete.py
index e970c806330..e3978b4debd 100644
--- a/tests/integration/providers/test_responses_bridge_incomplete.py
+++ b/tests/integration/providers/test_responses_bridge_incomplete.py
@@ -1297,3 +1297,108 @@ def test_chat_stream_over_responses_deployment_folds_message_and_two_function_ca
assert arguments_by_index == {0: '{"city":"Paris"}', 1: '{"city":"Paris","tz":"CET"}'}, choices
assert [choice["finish_reason"] for choice in choices if choice.get("finish_reason")] == ["tool_calls"], choices
assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/responses")]
+
+
+_TWO_FINAL_ANSWERS: Final = (
+ _message_item("msg_final_first", '{"city":"Paris"}', phase="final_answer"),
+ _message_item("msg_final_second", '{"city":"Paris"}', phase="final_answer"),
+)
+
+_CITY_RESPONSE_FORMAT: Final[dict[str, JsonValue]] = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "strict": True,
+ "schema": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ "additionalProperties": False,
+ },
+ },
+}
+
+
+def test_chat_over_responses_deployment_with_json_schema_returns_first_of_two_final_answers(
+ gateway: Gateway,
+) -> None:
+ """gpt-5.4-mini answered a strict json_schema request on /responses with two final_answer items,
+ each the whole document (captured 2026-10-14); a chat client must get one parseable document."""
+ identity: Final = "responses-bridge-json-schema-two-finals-" + uuid.uuid4().hex
+
+ def respond(request: Request) -> Reply:
+ if request.method == "GET" and request.target == "/v1/models":
+ return Reply(body=b'{"object":"list","data":[]}')
+ assert request.method == "POST" and request.target == "/responses", request.target
+ assert json.loads(request.body)["text"]["format"]["type"] == "json_schema", request.body
+ return Reply(body=_responses_body("resp_two_finals", _TWO_FINAL_ANSWERS))
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="openai/responses/gpt-5.4-mini", api_base=wire.url, api_key="synthetic-openai-key"
+ )
+ response: Final = gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "messages": [{"role": "user", "content": f"What is the capital of France? {identity}"}],
+ "response_format": _CITY_RESPONSE_FORMAT,
+ "cache": {"no-cache": True},
+ },
+ )
+ assert response.status_code == 200, response.text
+ body: Final = response.json()
+ assert body["choices"] == [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {"role": "assistant", "content": '{"city":"Paris"}'},
+ }
+ ], response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/responses")]
+
+
+def test_chat_stream_over_responses_deployment_with_json_schema_streams_first_of_two_final_answers(
+ gateway: Gateway,
+) -> None:
+ identity: Final = "responses-bridge-json-schema-two-finals-stream-" + uuid.uuid4().hex
+
+ def respond(request: Request) -> Reply:
+ if request.method == "GET" and request.target == "/v1/models":
+ return Reply(body=b'{"object":"list","data":[]}')
+ assert request.method == "POST" and request.target == "/responses", request.target
+ upstream_body: Final = json.loads(request.body)
+ assert upstream_body["stream"] is True, request.body
+ assert upstream_body["text"]["format"]["type"] == "json_schema", request.body
+ return _stream_reply(
+ "resp_two_finals_stream",
+ _TWO_FINAL_ANSWERS,
+ (
+ *_message_item_frames(0, _TWO_FINAL_ANSWERS[0]),
+ *_message_item_frames(1, _TWO_FINAL_ANSWERS[1]),
+ ),
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="openai/responses/gpt-5.4-mini", api_base=wire.url, api_key="synthetic-openai-key"
+ )
+ response: Final = gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "messages": [{"role": "user", "content": f"What is the capital of France? {identity}"}],
+ "response_format": _CITY_RESPONSE_FORMAT,
+ "stream": True,
+ "cache": {"no-cache": True},
+ },
+ )
+ assert response.status_code == 200, response.text
+ choices: Final = _stream_choices(response)
+ assert [choice["index"] for choice in choices] == [0] * len(choices), choices
+ deltas: Final = [object_value(choice["delta"]) for choice in choices]
+ assert "".join(str(delta["content"]) for delta in deltas if delta.get("content")) == '{"city":"Paris"}', choices
+ assert [choice["finish_reason"] for choice in choices if choice.get("finish_reason")] == ["stop"], choices
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/responses")]
diff --git a/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py b/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
index 8072919ed87..91bfb8d78d6 100644
--- a/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
+++ b/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
@@ -5267,3 +5267,94 @@ def test_convert_response_output_numbers_two_function_calls_zero_and_one() -> No
tool_calls: Final = choices[0].message.tool_calls
assert tool_calls is not None
assert [(call.index, call.function.name) for call in tool_calls] == [(0, "get_weather"), (1, "get_time")]
+
+
+def _final_answer_message(item_id: str, text: str) -> ResponseOutputMessage:
+ return ResponseOutputMessage.model_validate(
+ {
+ "id": item_id,
+ "type": "message",
+ "role": "assistant",
+ "status": "completed",
+ "phase": "final_answer",
+ "content": [{"type": "output_text", "text": text, "annotations": []}],
+ }
+ )
+
+
+ "structured_output, expected_content",
+ [
+ (True, '{"city":"Paris"}'),
+ (False, '{"city":"Paris"}{"city":"Paris"}'),
+ ],
+)
+def test_convert_response_output_structured_output_keeps_first_message_item(
+ structured_output: bool, expected_content: str
+) -> None:
+ """gpt-5.4-mini on /responses with a strict json_schema and a 'say what you will do first'
+ system prompt returned two final_answer items, each the whole document (captured 2026-10-14)."""
+ choices: Final = LiteLLMResponsesTransformationHandler._convert_response_output_to_choices( # pyright: ignore[reportPrivateUsage] # exercises the converter directly
+ (_final_answer_message("msg_1", '{"city":"Paris"}'), _final_answer_message("msg_2", '{"city":"Paris"}')),
+ structured_output=structured_output,
+ )
+
+ assert len(choices) == 1
+ assert choices[0].index == 0
+ assert choices[0].finish_reason == "stop"
+ assert choices[0].message.content == expected_content
+ if structured_output:
+ assert json.loads(expected_content) == {"city": "Paris"}
+
+
+ "optional_params, expected",
+ [
+ ({"response_format": {"type": "json_schema", "json_schema": {"name": "a", "schema": {}}}}, True),
+ ({"response_format": {"type": "json_object"}}, True),
+ ({"response_format": {"type": "text"}}, False),
+ ({}, False),
+ ],
+)
+def test_is_structured_output_request(optional_params: dict[str, object], expected: bool) -> None:
+ from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ is_structured_output_request,
+ )
+
+ assert is_structured_output_request(optional_params) is expected
+
+
+ "structured_output, expected_content",
+ [
+ (True, '{"city":"Paris"}'),
+ (False, '{"city":"Paris"}{"city":"Paris"}'),
+ ],
+)
+def test_stream_structured_output_drops_text_after_first_message_item(
+ structured_output: bool, expected_content: str
+) -> None:
+ from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ OpenAiResponsesToChatCompletionStreamIterator,
+ )
+
+ iterator = OpenAiResponsesToChatCompletionStreamIterator(
+ streaming_response=iter(()), sync_stream=True, structured_output=structured_output
+ )
+ events: Final[tuple[dict[str, object], ...]] = (
+ {"type": "response.output_item.added", "output_index": 0, "item": {"type": "message", "content": []}},
+ {"type": "response.output_text.delta", "output_index": 0, "delta": '{"city":'},
+ {"type": "response.output_text.delta", "output_index": 0, "delta": '"Paris"}'},
+ {"type": "response.output_item.done", "output_index": 0, "item": {"type": "message", "content": []}},
+ {"type": "response.output_item.added", "output_index": 1, "item": {"type": "message", "content": []}},
+ {"type": "response.output_text.delta", "output_index": 1, "delta": '{"city":'},
+ {"type": "response.output_text.delta", "output_index": 1, "delta": '"Paris"}'},
+ {"type": "response.output_item.done", "output_index": 1, "item": {"type": "message", "content": []}},
+ {"type": "response.completed"},
+ )
+
+ chunks: Final = [iterator.chunk_parser(event) for event in events]
+
+ content: Final = "".join(chunk.choices[0].delta.content or "" for chunk in chunks)
+ assert content == expected_content
+ assert chunks[-1].choices[0].finish_reason == "stop"