1. What Is Structured Output?
Structured output means the reply follows a schema you define: exact fields and types, checked for you. The JsonOutputParser from the last tab gives a dict too, but it has no rules.
JsonOutputParserThe model decides
{'name': 'Aman', 'age': 21, 'occupation': 'college student', 'skills': ['Python', 'FastAPI']}Fieldswhatever the model chooses
Typesnot checked
A missing fieldyou will not know
Structured outputYou decide
UserProfile(name='Aman', age=21, is_student=True, skills=['Python', 'FastAPI'])Fieldsexactly name, age, is_student, skills
Typeschecked: age must be an int
A missing fieldyou get an error
2. You Define the Schema
DefinitionPydantic lets you write the schema as a class. The result is an object with exactly these fields and types.
class UserProfile(BaseModel): name: str = Field(description="Full name of the user") age: int = Field(description="Age in years as an integer") is_student: bool = Field(description="True if the person is studying, else False") skills: list[str] = Field(description="List of technical skills")
Text in
Aman is a 21 year old college student who knows Python and FastAPI.
You get
UserProfile(name='Aman', age=21, is_student=True, skills=['Python', 'FastAPI'])3. Two Ways to Get It
Both give you a checked UserProfile. The difference is where the schema goes.
from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import PydanticOutputParser from pydantic import BaseModel, Field class UserProfile(BaseModel): name: str = Field(description="Full name of the user") age: int = Field(description="Age in years as an integer") is_student: bool = Field(description="True if the person is studying, else False") skills: list[str] = Field(description="List of technical skills") parser = PydanticOutputParser(pydantic_object=UserProfile) print(parser.get_format_instructions()) template = ChatPromptTemplate.from_template( "Extract the user profile from this text: {bio}\n{format_instructions}" ) prompt = template.invoke({ "bio": "Aman is a 21 year old college student who knows Python and FastAPI.", "format_instructions": parser.get_format_instructions(), }) res1 = model.invoke(prompt) profile = parser.invoke(res1)from pydantic import BaseModel, Field class UserProfile(BaseModel): name: str = Field(description="Full name of the user") age: int = Field(description="Age in years as an integer") is_student: bool = Field(description="True if the person is studying, else False") skills: list[str] = Field(description="List of technical skills") structured_model = model.with_structured_output(UserProfile) res2 = structured_model.invoke( "Priya is a 28 year old software engineer skilled in React, Node and Docker." ) print(res2)
Format instructions: text added to your prompt
The output should be formatted as a JSON instance that conforms to the JSON schema below. As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]} the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted. Here is the output schema: ``` {"properties": {"name": {"description": "Full name of the user", "title": "Name", "type": "string"}, "age": {"description": "Age in years as an integer", "title": "Age", "type": "integer"}, "is_student": {"description": "True if the person is studying, else False", "title": "Is Student", "type": "boolean"}, "skills": {"description": "List of technical skills", "items": {"type": "string"}, "title": "Skills", "type": "array"}}, "required": ["name", "age", "is_student", "skills"]} ```None. The schema goes to the API with the request, not into your prompt.
The model replied
```json { "name": "Aman", "age": 21, "is_student": true, "skills": ["Python", "FastAPI"] } ```(nothing to read: you get the object directly)
You get
UserProfile(name='Aman', age=21, is_student=True, skills=['Python', 'FastAPI'])UserProfile(name='Priya', age=28, is_student=False, skills=['React', 'Node', 'Docker'])
The parser turns the reply into a UserProfile and checks the types.Best way. No parser and no format instructions.
Code
Pydantic and structured output02_pydantic.py · 47 linesShow code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | from dotenv import load_dotenv from langchain.chat_models import init_chat_model from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import PydanticOutputParser from pydantic import BaseModel, Field load_dotenv() model = init_chat_model("mistralai:open-mistral-nemo", temperature=0) """BaseModel: we decide the fields and types""" class UserProfile(BaseModel): name: str = Field(description="Full name of the user") age: int = Field(description="Age in years as an integer") is_student: bool = Field(description="True if the person is studying, else False") skills: list[str] = Field(description="List of technical skills") """1. PydanticOutputParser: schema in the prompt, then JSON -> object (checks types)""" parser = PydanticOutputParser(pydantic_object=UserProfile) print(parser.get_format_instructions()) template = ChatPromptTemplate.from_template( "Extract the user profile from this text: {bio}\n{format_instructions}" ) prompt = template.invoke({ "bio": "Aman is a 21 year old college student who knows Python and FastAPI.", "format_instructions": parser.get_format_instructions(), }) res1 = model.invoke(prompt) profile = parser.invoke(res1) print(profile) print(type(profile)) print(profile.name, profile.age, profile.skills) """2. with_structured_output: schema sent to the API, not the prompt (best way)""" structured_model = model.with_structured_output(UserProfile) res2 = structured_model.invoke( "Priya is a 28 year old software engineer skilled in React, Node and Docker." ) print(res2) print(type(res2)) print(res2.name, res2.is_student, res2.skills) |