openai: fix json_schema mode in AzureChatOpenAI.with_structured_output #26086
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR fixes an issue with
json_schema
mode inAzureChatOpenAI.with_structured_output
.Following the release of structured output support in Azure OpenAI, I was able to test #25591 where the main proposed change is to use
BaseChatOpenAI.with_structured_output
and not override it inAzureChatOpenAI.with_structured_output
like currently implemented. When testingjson_schema
mode with those proposed changes, I was gettingValueError: Structured Output response does not have a 'parsed' field nor a 'refusal' field.
.After some investigation, here is an analysis of the issue:
BaseChatOpenAI._create_chat_result
, theparsed
andrefusal
properties of the completion generated byBaseChatOpenAI._generate
are correctly added asadditional_kwargs
to the generation.BaseChatOpenAI._create_chat_result
is called with the argumentresponse
of typeopenai.BaseModel
.AzureChatOpenAI._create_chat_result
overridesBaseChatOpenAI._create_chat_result
like solangchain/libs/partners/openai/langchain_openai/chat_models/azure.py
Lines 985 to 993 in de97d50
BaseChatOpenAI._create_chat_result
is thus called with the argumentresponse
of typedict
(followingresponse.model_dump()
).BaseChatOpenAI._create_chat_result
is not satisfied and thusparsed
andrefusal
are not added to the generation.langchain/libs/partners/openai/langchain_openai/chat_models/base.py
Lines 719 to 726 in de97d50
I propose to change the implementation of that check so that it works on the
response_dict
that is created anyways inBaseChatOpenAI._create_chat_result
so that theparsed
andrefusal
properties of the completion are correctly added asadditional_kwargs
to the generation whatever the type ofresponse
.@baskaryan I believe it would be valuable for you to review to avoid any regression and confirm that this PR should be merged at the same time as #25591 to avoid introducing a bug.