Skip to content

Commit 2019bf5

Browse files
ccurmesergioperezchecoHermes Agent
authored
fix(openai): raise clear error on unexpected response type in _create_chat_result (#39731)
Co-authored-by: Sergio Perez <[email protected]> Co-authored-by: Hermes Agent <[email protected]>
1 parent e92c6db commit 2019bf5

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

  • libs/partners/openai

‎libs/partners/openai/langchain_openai/chat_models/base.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1881,6 +1881,19 @@ def _create_chat_result(
18811881
) -> ChatResult:
18821882
generations = []
18831883

1884+
if not isinstance(response, dict | openai.BaseModel):
1885+
# `parse()` yields a `str` when the endpoint returns a non-JSON body,
1886+
# e.g. an HTML error page served after a redirect.
1887+
preview = repr(response)
1888+
if len(preview) > 200:
1889+
preview = f"{preview[:200]}..."
1890+
msg = (
1891+
"Unexpected response type from OpenAI-compatible endpoint. "
1892+
"Expected a dict or openai.BaseModel, got "
1893+
f"{type(response).__name__}: {preview}"
1894+
)
1895+
raise ValueError(msg)
1896+
18841897
response_dict = (
18851898
response
18861899
if isinstance(response, dict)

‎libs/partners/openai/tests/unit_tests/chat_models/test_base.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2100,6 +2100,30 @@ class ModelOutput(BaseModel):
21002100
)
21012101

21022102

2103+
def test_create_chat_result_raises_on_unexpected_response_type() -> None:
2104+
"""A non-JSON response body must surface a clear error, not an `AttributeError`."""
2105+
llm = ChatOpenAI(model=OPENAI_TEST_MODEL)
2106+
2107+
with pytest.raises(ValueError, match="got str") as exc_info:
2108+
llm._create_chat_result("<html><body>Moved</body></html>") # type: ignore[arg-type]
2109+
assert "Moved" in str(exc_info.value)
2110+
2111+
with pytest.raises(ValueError, match="got object"):
2112+
llm._create_chat_result(object()) # type: ignore[arg-type]
2113+
2114+
2115+
def test_create_chat_result_truncates_unexpected_response_body() -> None:
2116+
"""A large response body must not be echoed in full in the error message."""
2117+
llm = ChatOpenAI(model=OPENAI_TEST_MODEL)
2118+
body = "<html>" + "x" * 5000 + "</html>"
2119+
2120+
with pytest.raises(ValueError, match="got str") as exc_info:
2121+
llm._create_chat_result(body) # type: ignore[arg-type]
2122+
message = str(exc_info.value)
2123+
assert len(message) < len(body)
2124+
assert message.endswith("...")
2125+
2126+
21032127
@pytest.mark.skipif(
21042128
(PYDANTIC_VERSION.major, PYDANTIC_VERSION.minor) < (2, 8),
21052129
reason=(

0 commit comments

Comments
 (0)