Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -25,22 +25,25 @@ embeddings = None
|
|
| 25 |
vectorstore = None
|
| 26 |
retriever = None
|
| 27 |
quiz_chain = None
|
|
|
|
| 28 |
|
| 29 |
-
# Request schema
|
| 30 |
class QuizRequest(BaseModel):
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
| 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("
|
| 38 |
if not api_key:
|
| 39 |
logger.error("API_KEY environment variable is not set or empty.")
|
| 40 |
raise RuntimeError("API_KEY environment variable is not set or empty.")
|
| 41 |
logger.info("API_KEY is set.")
|
| 42 |
|
| 43 |
-
#
|
| 44 |
llm = ChatGroq(
|
| 45 |
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 46 |
temperature=0,
|
|
@@ -53,7 +56,7 @@ def load_components():
|
|
| 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:
|
|
@@ -71,24 +74,24 @@ def load_components():
|
|
| 71 |
vectorstore = vs1
|
| 72 |
logger.info("Merged FAISS indexes into a single vectorstore.")
|
| 73 |
|
| 74 |
-
retriever = vectorstore.as_retriever(search_kwargs={"k":
|
| 75 |
|
| 76 |
-
# Quiz generation chain
|
| 77 |
quiz_prompt = PromptTemplate(
|
| 78 |
template="""
|
| 79 |
-
Generate a quiz on the topic "{
|
| 80 |
-
Include clear questions
|
| 81 |
If context is insufficient, reply with "I don't know".
|
| 82 |
|
| 83 |
Retrieved context:
|
| 84 |
{context}
|
| 85 |
|
| 86 |
Quiz topic:
|
| 87 |
-
{
|
| 88 |
|
| 89 |
-
Quiz
|
| 90 |
""",
|
| 91 |
-
input_variables=["context", "
|
| 92 |
)
|
| 93 |
quiz_chain = RetrievalQA.from_chain_type(
|
| 94 |
llm=llm,
|
|
@@ -99,21 +102,23 @@ Quiz with answers:
|
|
| 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": "
|
| 109 |
|
| 110 |
@app.post("/quiz")
|
| 111 |
def create_quiz(request: QuizRequest):
|
| 112 |
try:
|
| 113 |
-
logger.info("Generating quiz for topic: %s", request.
|
| 114 |
-
result = quiz_chain.invoke({"
|
| 115 |
logger.info("Quiz generated successfully.")
|
| 116 |
return {"quiz": result.get("result")}
|
| 117 |
except Exception as e:
|
| 118 |
logger.error("Error generating quiz", exc_info=True)
|
| 119 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
| 25 |
vectorstore = None
|
| 26 |
retriever = None
|
| 27 |
quiz_chain = None
|
| 28 |
+
grade_chain = None
|
| 29 |
|
|
|
|
| 30 |
class QuizRequest(BaseModel):
|
| 31 |
+
question: str
|
| 32 |
+
|
| 33 |
+
class GradeRequest(BaseModel):
|
| 34 |
+
question: str # string of Q/A pairs
|
| 35 |
|
| 36 |
@app.on_event("startup")
|
| 37 |
def load_components():
|
| 38 |
+
global llm, embeddings, vectorstore, retriever, quiz_chain, grade_chain
|
| 39 |
try:
|
| 40 |
+
api_key = os.getenv("api_key")
|
| 41 |
if not api_key:
|
| 42 |
logger.error("API_KEY environment variable is not set or empty.")
|
| 43 |
raise RuntimeError("API_KEY environment variable is not set or empty.")
|
| 44 |
logger.info("API_KEY is set.")
|
| 45 |
|
| 46 |
+
# 1) Init LLM & Embeddings
|
| 47 |
llm = ChatGroq(
|
| 48 |
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 49 |
temperature=0,
|
|
|
|
| 56 |
encode_kwargs={"normalize_embeddings": True},
|
| 57 |
)
|
| 58 |
|
| 59 |
+
# 2) Load FAISS indexes
|
| 60 |
for zip_name, dir_name in [("faiss_index.zip", "faiss_index"), ("faiss_index(1).zip", "faiss_index_extra")]:
|
| 61 |
if not os.path.exists(dir_name):
|
| 62 |
with zipfile.ZipFile(zip_name, 'r') as z:
|
|
|
|
| 74 |
vectorstore = vs1
|
| 75 |
logger.info("Merged FAISS indexes into a single vectorstore.")
|
| 76 |
|
| 77 |
+
retriever = vectorstore.as_retriever(search_kwargs={"k": 10})
|
| 78 |
|
| 79 |
+
# Quiz generation chain
|
| 80 |
quiz_prompt = PromptTemplate(
|
| 81 |
template="""
|
| 82 |
+
Generate a quiz on the topic "{question}" using **only** the information in the "Retrieved context".
|
| 83 |
+
Include clear questions and multiple-choice options (A, B, C, D). Also provide the answers of the questions with them.
|
| 84 |
If context is insufficient, reply with "I don't know".
|
| 85 |
|
| 86 |
Retrieved context:
|
| 87 |
{context}
|
| 88 |
|
| 89 |
Quiz topic:
|
| 90 |
+
{question}
|
| 91 |
|
| 92 |
+
Quiz:
|
| 93 |
""",
|
| 94 |
+
input_variables=["context", "question"],
|
| 95 |
)
|
| 96 |
quiz_chain = RetrievalQA.from_chain_type(
|
| 97 |
llm=llm,
|
|
|
|
| 102 |
)
|
| 103 |
logger.info("Quiz chain ready.")
|
| 104 |
|
| 105 |
+
|
| 106 |
except Exception as e:
|
| 107 |
logger.error("Error loading components", exc_info=True)
|
| 108 |
raise
|
| 109 |
|
| 110 |
@app.get("/")
|
| 111 |
def root():
|
| 112 |
+
return {"message": "API is up and running!"}
|
| 113 |
|
| 114 |
@app.post("/quiz")
|
| 115 |
def create_quiz(request: QuizRequest):
|
| 116 |
try:
|
| 117 |
+
logger.info("Generating quiz for topic: %s", request.question)
|
| 118 |
+
result = quiz_chain.invoke({"query": request.question})
|
| 119 |
logger.info("Quiz generated successfully.")
|
| 120 |
return {"quiz": result.get("result")}
|
| 121 |
except Exception as e:
|
| 122 |
logger.error("Error generating quiz", exc_info=True)
|
| 123 |
raise HTTPException(status_code=500, detail=str(e))
|
| 124 |
+
|