AI Hints
Home›LangChain Tutorial›Structured Output in Practice
LangChain · Lesson 35 of 120

When Output Goes Wrong

Validation.

⏱ 2 min read▶ Video at 37:49🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Even with structured output, things can go wrong. The model might produce a value outside your limits, or the provider might return something malformed. Your app should handle that calmly.

When Output Goes Wrong
From the video: When Output Goes Wrong
  • Things still go wrong
  • Values out of range
  • Handle it calmly

Catching invalid data

Here we simulate a bad reply, a J SON string with six stars, outside the allowed range. Pydantic's model validate J SON checks it, and raises a validation error. Run it. The error says exactly which field failed and why, so we can retry, or fall back to a default.

validate.pypython
from pydantic import BaseModel, Field, ValidationError

class ReviewTag(BaseModel):
    stars: int = Field(ge=1, le=5)
    mentions_delivery: bool

bad_reply = '{"stars": 6, "mentions_delivery": false}'
try:
    ReviewTag.model_validate_json(bad_reply)
except ValidationError as e:
    err = e.errors()[0]
    print("field:", err["loc"][0], "| problem:", err["msg"])
Output
field: stars | problem: Input should be less than or equal to 5

Including the raw reply

With structured output has a helpful option, include raw. Instead of just the object, it returns a dictionary, with the raw message, the parsed object, and any parsing error. Run it. Parsed holds our object, and parsing error is none, because this reply was fine. When it isn't, you still have the raw reply to inspect.

include_raw.pypython
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class ReviewTag(BaseModel):
    stars: int = Field(ge=1, le=5)
    mentions_delivery: bool

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
tagger = model.with_structured_output(ReviewTag, include_raw=True)

result = tagger.invoke("Great book, quick delivery!")
print(sorted(result.keys()))
print("parsed:", result["parsed"])
print("error:", result["parsing_error"])
Output
['parsed', 'parsing_error', 'raw']
parsed: stars=5 mentions_delivery=True
error: None

Summary

Validation errors tell you exactly what's wrong. Include raw keeps the original reply, so you can retry, fall back, or debug. Next, a quiz on structured output.

Key takeaways
  • ValidationError
  • include_raw=True
  • Retry or fall back
Next up: Structured Output Quiz — test yourself