fix(openai): accept valid responses that are falsy at runtime (#35307)

This commit is contained in:
Mattijs Ugen
2026-02-19 03:06:43 +01:00
committed by GitHub
parent 5053436dcf
commit 5c6f8fe0a6
2 changed files with 21 additions and 1 deletions

View File

@@ -3765,7 +3765,7 @@ def _convert_to_openai_response_format(
def _oai_structured_outputs_parser(
ai_msg: AIMessage, schema: type[_BM]
) -> PydanticBaseModel | None:
if parsed := ai_msg.additional_kwargs.get("parsed"):
if (parsed := ai_msg.additional_kwargs.get("parsed")) is not None:
if isinstance(parsed, dict):
return schema(**parsed)
return parsed

View File

@@ -1388,6 +1388,26 @@ def test_structured_outputs_parser() -> None:
assert result == parsed_response
def test_structured_outputs_parser_valid_falsy_response() -> None:
class LunchBox(BaseModel):
sandwiches: list[str]
def __len__(self) -> int:
return len(self.sandwiches)
# prepare a valid *but falsy* response object, an empty LunchBox
parsed_response = LunchBox(sandwiches=[])
assert len(parsed_response) == 0
llm_output = AIMessage(
content='{"sandwiches": []}', additional_kwargs={"parsed": parsed_response}
)
output_parser = RunnableLambda(
partial(_oai_structured_outputs_parser, schema=LunchBox)
)
result = output_parser.invoke(llm_output)
assert result == parsed_response
def test__construct_lc_result_from_responses_api_error_handling() -> None:
"""Test that errors in the response are properly raised."""
response = Response(