Arhashmi/Math_Quiz_app
0
1from langchain.prompts import PromptTemplate2from langchain.llms import HuggingFaceHub3from langchain.chains import LLMChain, SequentialChain4from dotenv import load_dotenv5import os6 7# Load environment variables from .env file8load_dotenv()9 10# Hugging Face Hub API token11huggingfacehub_api_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")12 13# Configuration for language model14config = {'max_new_tokens': 512, 'temperature': 0.6}15 16def GetLLMResponse(selected_topic_level, selected_topic, num_quizzes):17 # Ensure that the Hugging Face Hub API token is available18 if huggingfacehub_api_token is None:19 raise ValueError("HUGGINGFACEHUB_API_TOKEN environment variable is not set. Set the API token and try again.")20 21 # Initialize Hugging Face Hub with API token22 llm = HuggingFaceHub(23 repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1",24 model_kwargs=config,25 huggingfacehub_api_token=huggingfacehub_api_token26 )27 28 # Create LLM Chaining for generating questions29 questions_template = "Generate a {selected_topic_level} math quiz on the topic of {selected_topic}. Generate only {num_quizzes} questions not more and without providing answers. The Question should not be in image format/link"30 questions_prompt = PromptTemplate(input_variables=["selected_topic_level", "selected_topic", "num_quizzes"],31 template=questions_template)32 questions_chain = LLMChain(llm=llm, prompt=questions_prompt, output_key="questions")33 34 # Create LLM Chaining for generating answers35 answer_template = "I want you to become a teacher and answer this specific Question:\n{questions}\n\nYou should give me a straightforward and concise explanation and answer to each one of them."36 answer_prompt = PromptTemplate(input_variables=["questions"], template=answer_template)37 answer_chain = LLMChain(llm=llm, prompt=answer_prompt, output_key="answer")38 39 # Create Sequential Chaining40 seq_chain = SequentialChain(chains=[questions_chain, answer_chain],41 input_variables=['selected_topic_level', 'selected_topic', 'num_quizzes'],42 output_variables=['questions', 'answer'])43 44 # Execute the chained prompts45 response = seq_chain({46 'selected_topic_level': selected_topic_level,47 'selected_topic': selected_topic,48 'num_quizzes': num_quizzes49 })50 51 # Print the response for debugging purposes52 print(response)53 54 # Return the response55 return response56 57 