Structured Output Parser
import os
from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.output_parsers import StructuredOutputParser
from langchain_core.prompts import PromptTemplate
load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", api_key=api_key)
# Step 1: Define structured schema
schema = {
"name": "string",
"age": "integer",
"hobbies": "list[string]"
}
parser = StructuredOutputParser(schema=schema)
# Step 2: Prepare prompt
prompt = PromptTemplate(
template="Provide a person’s info in the structured format:\n{name, age, hobbies}",
input_variables=[]
)
# Step 3: Run LLM and parse output
response = llm.invoke(prompt.format())
parsed_output = parser.parse(response.content)
print(parsed_output)
# Example: {'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'hiking']}Last updated