pythonintermediate
LangChain Pydantic Output Parser
Use LangChain's PydanticOutputParser to reliably parse structured data from LLM text responses.
pythonPress ⌘/Ctrl + Shift + C to copy
from langchain_openai import ChatOpenAI
from langchain.output_parsers import PydanticOutputParser
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field
from typing import Optional
class JobListing(BaseModel):
title: str = Field(description='Job title')
company: str = Field(description='Company name')
location: str = Field(description='City or Remote')
salary_min: Optional[int] = Field(description='Minimum salary USD')
salary_max: Optional[int] = Field(description='Maximum salary USD')
skills: list[str] = Field(description='Required skills')
parser = PydanticOutputParser(pydantic_object=JobListing)
prompt = ChatPromptTemplate.from_template(
'Extract job details from:\n{text}\n\n{format_instructions}'
).partial(format_instructions=parser.get_format_instructions())
chain = prompt | ChatOpenAI(model='gpt-4o-mini') | parser
job_text = 'Senior Data Engineer at Acme Corp in New York. $130k-$160k. Requires Python, Spark, dbt.'
result = chain.invoke({'text': job_text})
print(result.model_dump_json(indent=2))Use Cases
- information extraction
- job parsing
- structured NLP
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Structured LLM Output with Pydantic
Parse LLM responses into validated Pydantic models using LangChain's structured output binding.
Best for: structured extraction
#langchain#pydantic
pythonintermediate
Structured AI Extraction with Instructor
Use the Instructor library to extract validated Pydantic models from LLM responses reliably.
Best for: information extraction
#instructor#pydantic
pythonintermediate
LangChain Output Parser for Code
Parse AI-generated code blocks with LangChain's custom output parsers to extract clean code.
Best for: code extraction
#langchain#output-parser
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
#langchain#openai