.get_format_instructions()
method returns a string prompt that tells an LLM how to format its output so that it can be parsed cleanly into a Pydantic model.When using LLMs with a structured output parser like PydanticOutputParser
, you want the model to return a JSON that can be directly validated. .get_format_instructions()
helps you tell the model exactly how to format that output.
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
parser = PydanticOutputParser(pydantic_object=Person)
print(parser.get_format_instructions())
🖨️ Output:
The output should be a JSON object with the following format:
{
"name": string,
"age": integer
}
format_instructions = parser.get_format_instructions()
prompt = f"""
Extract the person's details from the text below.
Text: "My name is Abhi and I am 30 years old."
{format_instructions}
"""
So the full prompt sent to the LLM looks like:
Extract the person's details from the text below.
Text: "My name is Abhi and I am 30 years old."
The output should be a JSON object with the following format:
{
"name": string,
"age": integer
}
💡 Now the LLM is guided to return properly structured JSON!
Method | Purpose |
---|---|
get_format_instructions() |
Tells the LLM how to format its output so it can be parsed as Pydantic |