Sometimes validation error with with_structured_output(Class)
#26619
-
Im prompting my model with structured outputs:
This sometimes working and sometimes failing with the error:
It seems like the model is not responding with the correct JSON format, even though I thought this is guaranteed when using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @leoniewgnr! I'm here to help you with any bugs, questions, or contributions you have. Let's tackle this issue together! I found a similar solved discussion that might be relevant to your issue: Unexpected string validation error in Pydantic output parser. This discussion addresses validation errors related to the The Here is an example of how to use the from pydantic import BaseModel, Field
from typing import Union, Optional
class Plan(BaseModel):
steps: str
class FinalResponse(BaseModel):
response: str
class Act(BaseModel):
action: Union[Plan, FinalResponse]
planner_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a planner."),
("placeholder", "{messages}"),
]
)
model = ChatOpenAI(model="gpt-4")
structured_model = model.with_structured_output(Act)
chain = planner_prompt | structured_model
output = chain.invoke({"messages": [('user', 'do something')]}) In your case, the validation errors indicate that the model's response does not include the required fields To mitigate this, you can:
Example with structured_model = model.with_structured_output(Act, strict=True) Additionally, you can handle raw outputs and parse them manually if the model struggles with generating outputs that match complex schemas perfectly [2][3][4][5][6]. |
Beta Was this translation helpful? Give feedback.
Hey @leoniewgnr! I'm here to help you with any bugs, questions, or contributions you have. Let's tackle this issue together!
I found a similar solved discussion that might be relevant to your issue: Unexpected string validation error in Pydantic output parser. This discussion addresses validation errors related to the
PydanticOutputParser
expecting a specific format [1].The
with_structured_output(Act)
method sometimes fails with validation errors in theAct
class because the input provided to the model does not conform to the specifiedinput_schema
. Thewith_structured_output
method ensures that the model's output adheres to the specified schema, and if the output does not match, valida…