Skip to content

The agent engineering platform.

fix(openai): raise proper exception `OpenAIRefusalError` on structured output refusal (#34619)

OysterMax92afcaae6033
diff --git a/libs/partners/openai/langchain_openai/chat_models/base.py b/libs/partners/openai/langchain_openai/chat_models/base.py
index 71109d9b4d..6d41c83f33 100644
--- a/libs/partners/openai/langchain_openai/chat_models/base.py
+++ b/libs/partners/openai/langchain_openai/chat_models/base.py
@@ -3590,12 +3590,12 @@ def _oai_structured_outputs_parser(
if any(
isinstance(block, dict)
and block.get("type") == "non_standard"
- and "refusal" in block["value"]
- for block in ai_msg.content
+ and "refusal" in block["value"] # type: ignore[typeddict-item]
+ for block in ai_msg.content_blocks
):
refusal = next(
block["value"]["refusal"]
- for block in ai_msg.content
+ for block in ai_msg.content_blocks
if isinstance(block, dict)
and block["type"] == "non_standard"
and "refusal" in block["value"]
diff --git a/libs/partners/openai/tests/unit_tests/chat_models/test_base.py b/libs/partners/openai/tests/unit_tests/chat_models/test_base.py
index 1bd36e774b..79fbc0222f 100644
--- a/libs/partners/openai/tests/unit_tests/chat_models/test_base.py
+++ b/libs/partners/openai/tests/unit_tests/chat_models/test_base.py
@@ -64,6 +64,7 @@ from langchain_openai.chat_models._compat import (
_convert_to_v03_ai_message,
)
from langchain_openai.chat_models.base import (
+ OpenAIRefusalError,
_construct_lc_result_from_responses_api,
_construct_responses_api_input,
_convert_dict_to_message,
@@ -3191,3 +3192,37 @@ def test_gpt_5_1_temperature_with_reasoning_effort_none(
def test_model_prefers_responses_api() -> None:
assert _model_prefers_responses_api("gpt-5.2-pro")
assert not _model_prefers_responses_api("gpt-5.1")
+
+
+def test_openai_structured_output_refusal_handling_responses_api() -> None:
+ """
+ Test that _oai_structured_outputs_parser raises OpenAIRefusalError
+ when the AIMessage contains a refusal block from OpenAI's Responses API.
+ """
+ ai_msg = AIMessage(
+ content=[
+ {
+ "id": "rs_fake_id",
+ "summary": [],
+ "type": "reasoning",
+ "encrypted_content": "fake_encrypted_content",
+ },
+ {
+ "type": "refusal",
+ "refusal": "refused content in string",
+ "id": "msg_fake_id",
+ },
+ ],
+ )
+
+ # schema does not matter in this issue
+ class MySchema(BaseModel):
+ foo: int
+
+ try:
+ _oai_structured_outputs_parser(ai_msg, MySchema)
+ except OpenAIRefusalError:
+ # OpenAIRefusalError was raised. This is the proper behavior.
+ pass
+ except ValueError as e:
+ pytest.fail(f"This is a wrong behavior. Error details: {e}")