Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -25,19 +25,14 @@ embeddings = None
|
|
| 25 |
vectorstore = None
|
| 26 |
retriever = None
|
| 27 |
quiz_chain = None
|
| 28 |
-
grade_chain = None
|
| 29 |
|
| 30 |
-
# Request
|
| 31 |
class QuizRequest(BaseModel):
|
| 32 |
topic: str
|
| 33 |
|
| 34 |
-
class GradeRequest(BaseModel):
|
| 35 |
-
quiz: str
|
| 36 |
-
answers: str # user-provided answers corresponding to quiz questions
|
| 37 |
-
|
| 38 |
@app.on_event("startup")
|
| 39 |
def load_components():
|
| 40 |
-
global llm, embeddings, vectorstore, retriever, quiz_chain
|
| 41 |
try:
|
| 42 |
api_key = os.getenv("API_KEY")
|
| 43 |
if not api_key:
|
|
@@ -45,7 +40,7 @@ def load_components():
|
|
| 45 |
raise RuntimeError("API_KEY environment variable is not set or empty.")
|
| 46 |
logger.info("API_KEY is set.")
|
| 47 |
|
| 48 |
-
#
|
| 49 |
llm = ChatGroq(
|
| 50 |
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 51 |
temperature=0,
|
|
@@ -58,7 +53,7 @@ def load_components():
|
|
| 58 |
encode_kwargs={"normalize_embeddings": True},
|
| 59 |
)
|
| 60 |
|
| 61 |
-
#
|
| 62 |
for zip_name, dir_name in [("faiss_index.zip", "faiss_index"), ("faiss_index(1).zip", "faiss_index_extra")]:
|
| 63 |
if not os.path.exists(dir_name):
|
| 64 |
with zipfile.ZipFile(zip_name, 'r') as z:
|
|
@@ -78,11 +73,11 @@ def load_components():
|
|
| 78 |
|
| 79 |
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 80 |
|
| 81 |
-
# Quiz generation chain (
|
| 82 |
quiz_prompt = PromptTemplate(
|
| 83 |
template="""
|
| 84 |
Generate a quiz on the topic "{topic}" using **only** the information in the "Retrieved context".
|
| 85 |
-
Include clear questions
|
| 86 |
If context is insufficient, reply with "I don't know".
|
| 87 |
|
| 88 |
Retrieved context:
|
|
@@ -91,7 +86,7 @@ Retrieved context:
|
|
| 91 |
Quiz topic:
|
| 92 |
{topic}
|
| 93 |
|
| 94 |
-
Quiz
|
| 95 |
""",
|
| 96 |
input_variables=["context", "topic"],
|
| 97 |
)
|
|
@@ -104,33 +99,13 @@ Quiz questions:
|
|
| 104 |
)
|
| 105 |
logger.info("Quiz chain ready.")
|
| 106 |
|
| 107 |
-
# Grade quiz chain (combines quiz and answers into single question)
|
| 108 |
-
grade_prompt = PromptTemplate(
|
| 109 |
-
template="""
|
| 110 |
-
Grade the following quiz based on the "Retrieved context":
|
| 111 |
-
|
| 112 |
-
{question}
|
| 113 |
-
|
| 114 |
-
Provide a score and brief feedback for each question. If context is insufficient to grade, reply "I don't know" for that question.
|
| 115 |
-
""",
|
| 116 |
-
input_variables=["context", "question"],
|
| 117 |
-
)
|
| 118 |
-
grade_chain = RetrievalQA.from_chain_type(
|
| 119 |
-
llm=llm,
|
| 120 |
-
chain_type="stuff",
|
| 121 |
-
retriever=retriever,
|
| 122 |
-
return_source_documents=False,
|
| 123 |
-
chain_type_kwargs={"prompt": grade_prompt},
|
| 124 |
-
)
|
| 125 |
-
logger.info("Grading chain ready.")
|
| 126 |
-
|
| 127 |
except Exception as e:
|
| 128 |
logger.error("Error loading components", exc_info=True)
|
| 129 |
raise
|
| 130 |
|
| 131 |
@app.get("/")
|
| 132 |
def root():
|
| 133 |
-
return {"message": "API is up and running!"}
|
| 134 |
|
| 135 |
@app.post("/quiz")
|
| 136 |
def create_quiz(request: QuizRequest):
|
|
@@ -142,16 +117,3 @@ def create_quiz(request: QuizRequest):
|
|
| 142 |
except Exception as e:
|
| 143 |
logger.error("Error generating quiz", exc_info=True)
|
| 144 |
raise HTTPException(status_code=500, detail=str(e))
|
| 145 |
-
|
| 146 |
-
@app.post("/grade")
|
| 147 |
-
def grade_quiz(request: GradeRequest):
|
| 148 |
-
try:
|
| 149 |
-
# Combine quiz questions and answers into one input
|
| 150 |
-
combined = f"Quiz questions:\n{request.quiz}\n\nUser answers:\n{request.answers}"
|
| 151 |
-
logger.info("Grading quiz. Combined input: %s", combined)
|
| 152 |
-
result = grade_chain.invoke({"question": combined})
|
| 153 |
-
logger.info("Quiz graded successfully.")
|
| 154 |
-
return {"grading": result.get("result")}
|
| 155 |
-
except Exception as e:
|
| 156 |
-
logger.error("Error grading quiz", exc_info=True)
|
| 157 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 25 |
vectorstore = None
|
| 26 |
retriever = None
|
| 27 |
quiz_chain = None
|
|
|
|
| 28 |
|
| 29 |
+
# Request schema
|
| 30 |
class QuizRequest(BaseModel):
|
| 31 |
topic: str
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
@app.on_event("startup")
|
| 34 |
def load_components():
|
| 35 |
+
global llm, embeddings, vectorstore, retriever, quiz_chain
|
| 36 |
try:
|
| 37 |
api_key = os.getenv("API_KEY")
|
| 38 |
if not api_key:
|
|
|
|
| 40 |
raise RuntimeError("API_KEY environment variable is not set or empty.")
|
| 41 |
logger.info("API_KEY is set.")
|
| 42 |
|
| 43 |
+
# Initialize LLM & Embeddings
|
| 44 |
llm = ChatGroq(
|
| 45 |
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 46 |
temperature=0,
|
|
|
|
| 53 |
encode_kwargs={"normalize_embeddings": True},
|
| 54 |
)
|
| 55 |
|
| 56 |
+
# Load FAISS indexes
|
| 57 |
for zip_name, dir_name in [("faiss_index.zip", "faiss_index"), ("faiss_index(1).zip", "faiss_index_extra")]:
|
| 58 |
if not os.path.exists(dir_name):
|
| 59 |
with zipfile.ZipFile(zip_name, 'r') as z:
|
|
|
|
| 73 |
|
| 74 |
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 75 |
|
| 76 |
+
# Quiz generation chain (with answers)
|
| 77 |
quiz_prompt = PromptTemplate(
|
| 78 |
template="""
|
| 79 |
Generate a quiz on the topic "{topic}" using **only** the information in the "Retrieved context".
|
| 80 |
+
Include clear questions, multiple-choice options (A, B, C, D), and **provide the correct answers** for each question.
|
| 81 |
If context is insufficient, reply with "I don't know".
|
| 82 |
|
| 83 |
Retrieved context:
|
|
|
|
| 86 |
Quiz topic:
|
| 87 |
{topic}
|
| 88 |
|
| 89 |
+
Quiz with answers:
|
| 90 |
""",
|
| 91 |
input_variables=["context", "topic"],
|
| 92 |
)
|
|
|
|
| 99 |
)
|
| 100 |
logger.info("Quiz chain ready.")
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
except Exception as e:
|
| 103 |
logger.error("Error loading components", exc_info=True)
|
| 104 |
raise
|
| 105 |
|
| 106 |
@app.get("/")
|
| 107 |
def root():
|
| 108 |
+
return {"message": "Quiz API is up and running!"}
|
| 109 |
|
| 110 |
@app.post("/quiz")
|
| 111 |
def create_quiz(request: QuizRequest):
|
|
|
|
| 117 |
except Exception as e:
|
| 118 |
logger.error("Error generating quiz", exc_info=True)
|
| 119 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|