tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Generative AI > LangChain > LangChain Structured Output with Pydantic

LangChain Structured Output with Pydantic

Author: Venkata Sudhakar

LangChain's with_structured_output method binds a Pydantic model to an LLM, forcing it to return a validated Python object instead of raw text. This is the cleanest way to extract structured data from LLM responses in LangChain applications - you get type safety, automatic validation, and IDE autocomplete on the returned object without writing any JSON parsing code.

Pydantic models define the schema with type annotations and optional field descriptions that guide the LLM. Under the hood, LangChain uses function calling or JSON mode to constrain the output. If the LLM returns an invalid response, Pydantic raises a ValidationError before the data reaches your application code, preventing silent data quality issues in production.

The below example extracts structured product order information from ShopMax India customer messages using LangChain with_structured_output and Pydantic.


It gives the following output,

Input: I want to buy a Samsung Galaxy S24 in Hyderabad....
  Action: BUY | Urgency: LOW
  Summary: Customer wants to purchase Samsung Galaxy S24 in Hyderabad.

Input: My order SM-45821 has not arrived in 8 days and I nee...
  Action: TRACK | Urgency: HIGH
  Summary: Customer needs urgent status update on delayed order SM-45821.

Input: What is the return process for headphones purchased la...
  Action: RETURN | Urgency: LOW
  Summary: Customer asking about return process for recently purchased headphones.

Each response is a validated OrderIntent object with typed fields - no JSON parsing, no KeyError exceptions, no missing fields. The Field descriptions guide the LLM to fill each field correctly. Use with_structured_output for any ShopMax workflow that feeds LLM output into downstream code: routing customer tickets, updating CRM records, triggering order management workflows, or classifying support requests for team assignment.


 
  


  
bl  br