Chains using structured output (with_structured_output)
# Configuration file for managing API keys as environment variablesfrom dotenv import load_dotenv# Load API key informationload_dotenv()
True
# Set up LangSmith tracking. https://smith.langchain.com# !pip install langchain-teddynotefrom langchain_teddynote import logging# Enter a project name.logging.langsmith("Structured-Output-Chain")
Implement a process to generate a 4-option multiple choice quiz on a specific topic.
The Quiz class defines the quiz's question, difficulty, and four choices.
The ChatOpenAI instance performs natural language processing using the GPT-4o model, and the ChatPromptTemplate defines the conversational prompt for quiz generation.
from langchain.chains.openai_functions import create_structured_output_runnable
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
from typing import List
class Quiz(BaseModel):
"""Extract information from a 4-option multiple choice quiz"""
question: str = Field(..., description="The best of the best")
level: str = Field(
..., description="Indicates the difficulty of the quiz (easy, medium, hard)"
)
options: List[str] = Field(..., description="There are four choices in the quiz.")
llm = ChatOpenAI(model="gpt-4o", temperature=0.1)
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You're a world-famous quizzer and generates quizzes in structured formats.",
),
(
"human",
"Please give a 4-option multiple choice quiz related to the content presented in TOPIC.. If there is an actual past exam question, please create a similar question."
"However, do not include any content or information about the TOPIC in the question. \nTOPIC:\n{topic}",
),
("human", "Tip: Make sure to answer in the correct format"),
]
)
# Create a model for structured output
llm_with_structured_output = llm.with_structured_output(Quiz)
# Create a quiz creation chain
chain = prompt | llm_with_structured_output
# Request the creation of a quiz.
generated_quiz = chain.invoke({"topic": "ADSPData Analysis Associate Professional) Qualification Exam"})
# Generated quiz output
print(f"{generated_quiz.question} (Difficulty: {generated_quiz.level})\n")
for i, opt in enumerate(generated_quiz.options):
print(f"{i+1}) {opt}")
Which of the following is the first step in the data analysis process? (Difficulty: Moderate)
1) Data collection
2) Data preprocessing
3) Problem definition
4) Model evaluation