🎯 By the end of this module, you will:
with_structured_output() to bind schemas to any LangChain modelStructured Outputs with Pydantic
Free-form LLM text is useless downstream. Pydantic + with_structured_output turns any model into a typed data extractor — no regex, no brittle JSON parsing.
# Step 1: Define output schema as a Pydantic model
from pydantic import BaseModel, Field
from typing import Literal
class SentimentAnalysis(BaseModel):
sentiment: Literal["positive", "negative", "neutral"]
confidence: float = Field(ge=0.0, le=1.0)
issue_type: str = Field(description="Category of the user's issue")
requires_escalation: bool📋 Mental Model: Unstructured vs Structured
"The sentiment is negative and confidence around 90%. The issue seems to be latency."
Cannot write to DB. Cannot trigger API. Requires brittle regex.
{"sentiment": "negative",
"confidence": 0.90,
"requires_escalation": true}Directly writable to PostgreSQL. Zero parsing code.
🔬 Schema Builder Visualizer
Pydantic & JSON Schema VisualizerType Safety
Configure schema fields and observe how Python type hints convert into enforceable JSON Schema for LLMs
A one-sentence summary of the text.
One of: positive, negative, neutral.
Confidence score between 0.0 and 1.0.
Key actionable takeaways.
from pydantic import BaseModel, Field
from typing import Optional, List
class IncidentReport(BaseModel):
summary: str = Field(
description="A one-sentence summary of the text."
)
sentiment: str = Field(
description="One of: positive, negative, neutral."
)
confidence: float = Field(
description="Confidence score between 0.0 and 1.0."
)
action_items: Optional[list[str]] = Field(
description="Key actionable takeaways."
)Structured Output Traps
A field named score: float with no description will cause the model to guess what to put there. Always include a Field() description that specifies the exact meaning, range, and expected values.
Complex nested schemas with many Optional fields confuse smaller models. Flatten your schema to 1-2 levels. For complex extractions, break into multiple sequential structured calls.
Key Takeaways
- 1.Schema-First Design: Define your Pydantic model before writing the prompt. The schema IS the interface contract between your LLM and your application code.
- 2.Field() Descriptions are LLM Instructions: Write field descriptions as if explaining to the LLM exactly what value to put there — with examples and boundary conditions.
- 3.Catch ValidationError Early: Wrap every structured output call in try/except. Log the field-level Pydantic errors and implement an automatic retry with a clarifying prompt.
Integrating External Tools into an Agent
Connect Tavily Search, calculator tools, and external APIs to give your agent real-world access — and learn the golden rules of tool selection.