Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions routes/openai_route.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from fastapi import APIRouter, Response, HTTPException
from data_access_layer.topics_db_functions import get_topics
from globals import globals
from data_access_layer import users_db_functions
from services.openai_service import get_question_and_answer, evaluate_answer
Expand All @@ -16,10 +17,14 @@ async def gen_question(body: GenBody, response: Response):
max_attempts = 5
attempts = 0

allowed_topics = get_topics()
if body.topic not in allowed_topics:
raise HTTPException(status_code=400, detail=f"Invalid topic: {body.topic}. Must be one of {allowed_topics}.")

try:
while attempts < max_attempts:
answer = get_question_and_answer(topic, difficulty, answers_num)
if answers_num == len(answer['Answer']):
if (answers_num and answers_num == len(answer['Answer'])) or (not answers_num and len(answer['Answer']) == 1):
return answer
attempts += 1

Expand All @@ -30,7 +35,6 @@ async def gen_question(body: GenBody, response: Response):
response.status_code = 400
return {"error": str(e)}


@router.post('/evaluate')
async def evaluate_question(body: QARequest,ai_answer:str, response: Response):
try:
Expand All @@ -41,9 +45,10 @@ async def evaluate_question(body: QARequest,ai_answer:str, response: Response):
answer = body.answer
evaluation_score = evaluate_answer(question=question_text, answer=answer,ai_answer=ai_answer)
users_db_functions.add_user_stats(user_id=user_id, question_text=question_text, answer=answer, topic=topic,
difficulty=difficulty,
score=evaluation_score["Score"], answer_correct=(evaluation_score["Score"] >= 5),
client=globals.mongo_client)
difficulty=difficulty,
score=evaluation_score["Score"],
answer_correct=(evaluation_score["Score"] >= 5),
client=globals.mongo_client)
evaluation_score["question"] = question_text
evaluation_score["user_answer"] = answer
return evaluation_score
Expand Down
7 changes: 7 additions & 0 deletions tests/test_openai_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ def test_question_generation_wrong_difficulty():
response = requests.post(url, json={"topic": "python", "difficulty": "HARD"})
assert response.status_code == 422

def test_question_generation_invalid_topic():
server_url = os.getenv("SERVER_URL")
assert server_url is not None
url = f"{server_url}/question/generate"
response = requests.post(url, json={"topic": "invalid_topic"})
assert response.status_code == 400
assert "Invalid topic: invalid_topic. Must be one of" in response.json()['detail']

def test_gen_question_answers_num():
server_url = os.getenv("SERVER_URL")
Expand Down