- Defining a Pydantic model for the expected response.
- Creating a
PydanticOutputParser. - Embedding parser format instructions in the prompt so the LLM returns JSON matching the schema.
- Invoking the model and parsing the output into a typed Python object.
Complete example
Below is a concise, runnable example showing the full workflow: define a model, create a parser, add format instructions to the prompt, call the model, and parse the response.This example shows how the parser provides
format_instructions (a JSON Schema-like specification). Including these instructions in your prompt guides the LLM to emit well-formed JSON that the parser can validate and load into a Pydantic model.Notes on imports and model invocation
Import paths and how you call the model can differ between LangChain versions and wrappers. Common variations:from langchain import OpenAIvsfrom langchain_openai import OpenAIBaseModelandFieldmay come directly frompydantic- Model invocation can use
model.invoke(...),model.predict(...), ormodel(...)depending on the wrapper
Build the final prompt
Supply a movie name (for example,Interstellar) and render the prompt. The format_instructions partial will contain the JSON Schema-like instructions the model should follow.
Invoke the model and parse the response
Call the model with the formatted prompt string and capture the output:PydanticOutputParser to convert it into a typed Ticket instance:
Field reference
Why this pattern is useful
- You get strong guarantees about the shape and types of the data your application receives from an LLM.
- Parsing into a Pydantic model makes downstream processing, validation, and IDE/autocomplete support straightforward.
- Embedding
parser.get_format_instructions()in the prompt aligns the LLM output to the schema, reducing parsing errors.
The parser validates and converts JSON to an instance of the
Ticket model. If the model’s output does not conform to the schema, the parser will raise a validation error—so including format_instructions in the prompt is important to guide the LLM toward valid output.Summary
Steps to follow:- Define a Pydantic model (subclass of
BaseModel) describing the expected fields and types. - Create a
PydanticOutputParserusing that Pydantic model. - Include
parser.get_format_instructions()as a partial variable in your prompt template. - Invoke the LLM with the formatted prompt.
- Use
parser.parse(...)to convert the model output into a typed Python object.
Links and references
- LangChain Output Parsers: https://langchain.readthedocs.io/
- Pydantic: https://pydantic-docs.helpmanual.io/
- OpenAI API / SDK docs: https://platform.openai.com/docs