Teddy Xinyuan Chen commited on
Commit
99cd51c
·
1 Parent(s): 977aa4a

2024-10-08T20-16-02Z

Browse files
Files changed (2) hide show
  1. src/quizzes/models.py +6 -1
  2. src/quizzes/views.py +22 -0
src/quizzes/models.py CHANGED
@@ -2,6 +2,7 @@ import os
2
  import typing
3
 
4
  import openai
 
5
  from django.contrib.postgres import fields
6
  from django.db import models
7
 
@@ -69,6 +70,10 @@ class LLMGradedAnswer(Answer):
69
  dict: The result of the grading.
70
  """
71
  try:
 
 
 
 
72
  openai.api_key = os.getenv("OPENAI_API_KEY")
73
  prompt = f"Grade the following answer based on the rubric:\nRubric: {self.question.rubrics}\nAnswer: {user_answer}"
74
 
@@ -82,7 +87,7 @@ class LLMGradedAnswer(Answer):
82
 
83
  return {"result": "success", "message": response.choices[0].message["content"]}
84
 
85
- except openai.error.OpenAIError as e:
86
  print(f"An error occurred: {e}")
87
  return {"result": "error", "message": str(e)}
88
 
 
2
  import typing
3
 
4
  import openai
5
+
6
  from django.contrib.postgres import fields
7
  from django.db import models
8
 
 
70
  dict: The result of the grading.
71
  """
72
  try:
73
+ # use dotenv to load env
74
+ from dotenv import load_dotenv
75
+
76
+ load_dotenv()
77
  openai.api_key = os.getenv("OPENAI_API_KEY")
78
  prompt = f"Grade the following answer based on the rubric:\nRubric: {self.question.rubrics}\nAnswer: {user_answer}"
79
 
 
87
 
88
  return {"result": "success", "message": response.choices[0].message["content"]}
89
 
90
+ except Exception as e:
91
  print(f"An error occurred: {e}")
92
  return {"result": "error", "message": str(e)}
93
 
src/quizzes/views.py CHANGED
@@ -45,3 +45,25 @@ def grade_question(request, question_id):
45
  "quizzes/partial.html",
46
  {"is_correct": is_correct, "correct_answer": answer.correct_answer},
47
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  "quizzes/partial.html",
46
  {"is_correct": is_correct, "correct_answer": answer.correct_answer},
47
  )
48
+
49
+
50
+ def grade_question(request, question_id):
51
+ question = get_object_or_404(Question, pk=question_id)
52
+ answer = question.get_answer()
53
+ if answer is None:
54
+ return render(request, "quizzes/partial.html", {"error": "Question must have an answer"}, status=422)
55
+
56
+ user_answer = request.POST.get("answer")
57
+ if hasattr(answer, "grade"):
58
+ result = answer.grade(user_answer)
59
+ is_correct = result.get("result") == "success"
60
+ correct_answer = result.get("message")
61
+ else:
62
+ is_correct = answer.is_correct(user_answer)
63
+ correct_answer = answer.correct_answer
64
+
65
+ return render(
66
+ request,
67
+ "quizzes/partial.html",
68
+ {"is_correct": is_correct, "correct_answer": correct_answer},
69
+ )