Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhanced explain and fixed questions #57

Merged
merged 1 commit into from
Oct 4, 2024
Merged
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: 13 additions & 2 deletions backend/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http"
"os"
"sort"
"strings"
"time"

"github.com/aws/aws-sdk-go/aws"
Expand Down Expand Up @@ -45,10 +46,20 @@ func ExplainHandler(w http.ResponseWriter, r *http.Request) {
// Initialize OpenAI client
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))

// Join the correct answers into a single string
correctAnswersStr := strings.Join(req.CorrectAnswers, ", ")

prompt := fmt.Sprintf(
"Question: %s\nAnswer: %s\nExplanation: Please explain the answer in a simple, intuitive, and easy-to-remember way. Limit your response to %d tokens.",
"Question: %s\nSelected Answer(s): %s\nCorrect Answer(s): %s\n"+
"Explanation: Please provide a comprehensive explanation that covers the following points:\n"+
"1. Why the correct answer(s) is/are correct.\n"+
"2. If the selected answer(s) is/are incorrect, explain why it's/they're wrong.\n"+
"3. Provide any additional context or information that helps understand the concept better.\n"+
"Please explain in a simple, intuitive, and easy-to-remember way. Limit your response to %d words.",
req.Question,
req.SelectedAnswer, maxTokens)
strings.Join(req.SelectedAnswers, ", "),
correctAnswersStr,
maxTokens)

resp, err := client.CreateChatCompletion(r.Context(), openai.ChatCompletionRequest{
Model: openai.GPT4o,
Expand Down
5 changes: 3 additions & 2 deletions backend/types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ type Option struct {
}

type ExplainRequest struct {
Question string `json:"question"`
SelectedAnswer string `json:"selectedAnswer"`
Question string `json:"question"`
SelectedAnswers []string `json:"selectedAnswers"`
CorrectAnswers []string `json:"correctAnswers"`
}

type HintRequest struct {
Expand Down
37 changes: 25 additions & 12 deletions frontend/src/components/QuestionCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,22 @@ import PropTypes from 'prop-types';
import ReactMarkdown from 'react-markdown'; // Import react-markdown
import '../styles/QuestionCard.css';

const QuestionCard = ({ question, selectedAnswers, handleAnswerSelect, handleSubmitAnswer, feedback, handleExplain, loading, explanation, fetchRandomQuestion, handleHint, performanceMetrics, studyMode }) => {
const QuestionCard = ({
question,
selectedAnswers,
handleAnswerSelect,
handleSubmitAnswer,
feedback,
handleExplain,
isExplanationLoading,
explanation,
fetchRandomQuestion,
handleHint,
isHintLoading,
hint,
performanceMetrics,
studyMode
}) => {
if (!question || !question.options) {
return <p>Loading...</p>; // Display a loading message or spinner
}
Expand Down Expand Up @@ -37,15 +52,16 @@ const QuestionCard = ({ question, selectedAnswers, handleAnswerSelect, handleSub
))}
</ul>
<button onClick={handleSubmitAnswer}>Submit Answer</button>
<button onClick={handleExplain} disabled={loading}>
{loading ? 'Loading...' : 'Explain'}
<button onClick={handleExplain} disabled={isExplanationLoading}>
{isExplanationLoading ? 'Loading...' : 'Explain'}
</button>
<button onClick={handleHint} disabled={loading}>
{loading ? 'Loading...' : 'Hint'}
<button onClick={handleHint} disabled={isHintLoading}>
{isHintLoading ? 'Loading...' : 'Hint'}
</button>
<button onClick={fetchRandomQuestion}>Next Question</button>
{feedback && <p className="feedback">{feedback}</p>}
{explanation && <ReactMarkdown className="explanation">{explanation}</ReactMarkdown>} {/* Render explanation as markdown */}
{hint && <ReactMarkdown className="hint">{hint}</ReactMarkdown>}
</div>
);
};
Expand All @@ -57,16 +73,13 @@ QuestionCard.propTypes = {
handleSubmitAnswer: PropTypes.func.isRequired,
feedback: PropTypes.string,
handleExplain: PropTypes.func.isRequired,
loading: PropTypes.bool.isRequired,
isExplanationLoading: PropTypes.bool.isRequired,
explanation: PropTypes.string,
fetchRandomQuestion: PropTypes.func.isRequired,
handleHint: PropTypes.func.isRequired,
performanceMetrics: PropTypes.arrayOf(PropTypes.shape({ // Update prop type for performance metrics
correct: PropTypes.number,
incorrect: PropTypes.number,
questionId: PropTypes.string,
userId: PropTypes.string,
})),
isHintLoading: PropTypes.bool.isRequired,
hint: PropTypes.string,
performanceMetrics: PropTypes.array,
studyMode: PropTypes.string.isRequired, // Add studyMode prop type
};

Expand Down
86 changes: 59 additions & 27 deletions frontend/src/components/QuestionHandler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import QuestionCard from './QuestionCard';
import useFetchRandomQuestion from '../hooks/useFetchRandomQuestion';
Expand All @@ -6,26 +6,29 @@
import useFetchWorstQuestions from '../hooks/useFetchWorstQuestions';
import { handleAnswerSelect, handleSubmitAnswer, handleExplain, handleHint } from '../utils/handlers';

function QuestionHandler({ userId, updateUserMetrics, updatePerformanceData, performanceData }) {

Check failure on line 9 in frontend/src/components/QuestionHandler.js

View workflow job for this annotation

GitHub Actions / lint

'userId' is missing in props validation

Check failure on line 9 in frontend/src/components/QuestionHandler.js

View workflow job for this annotation

GitHub Actions / lint

'updateUserMetrics' is missing in props validation

Check failure on line 9 in frontend/src/components/QuestionHandler.js

View workflow job for this annotation

GitHub Actions / lint

'updatePerformanceData' is missing in props validation

Check failure on line 9 in frontend/src/components/QuestionHandler.js

View workflow job for this annotation

GitHub Actions / lint

'performanceData' is missing in props validation
const location = useLocation();
const studyOption = location.state?.studyMode || 'random'; // Default to 'random' if not provided
const studyOption = location.state?.studyMode || 'random';

const [questions, setQuestions] = useState([]);
const [currentQuestionIndex] = useState(0);
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [selectedAnswers, setSelectedAnswers] = useState([]);
const [feedback, setFeedback] = useState(null);
const [explanation, setExplanation] = useState(null);
const [loading, setLoading] = useState(false);
const [hint, setHint] = useState(null);
const [performanceMetrics, setPerformanceMetrics] = useState({});

// Separate loading states
const [isQuestionLoading, setIsQuestionLoading] = useState(false);
const [isExplanationLoading, setIsExplanationLoading] = useState(false);
const [isHintLoading, setIsHintLoading] = useState(false);

const fetchRandomQuestionCallback = useFetchRandomQuestion(setQuestions);
const fetchPracticeTestQuestionsCallback = useFetchPracticeTestQuestions(setQuestions);
const fetchWorstQuestionsCallback = useFetchWorstQuestions(userId, setQuestions);
console.log('Study option in QuestionHandler:', studyOption);

useEffect(() => {
setPerformanceMetrics(performanceData);
console.log('Performance metrics in QuestionHandler:', performanceMetrics);
const fetchQuestion = useCallback(() => {
setIsQuestionLoading(true);
switch (studyOption) {
case 'random':
fetchRandomQuestionCallback();
Expand All @@ -39,10 +42,18 @@
default:
fetchRandomQuestionCallback();
}
}, [studyOption, fetchRandomQuestionCallback, fetchPracticeTestQuestionsCallback, fetchWorstQuestionsCallback, performanceData, performanceMetrics]);
setIsQuestionLoading(false);
}, [studyOption, fetchRandomQuestionCallback, fetchPracticeTestQuestionsCallback, fetchWorstQuestionsCallback]);

useEffect(() => {
fetchQuestion();
}, [fetchQuestion]);

useEffect(() => {
setPerformanceMetrics(performanceData);
}, [performanceData]);

useEffect(() => {
// Fetch performance metrics for the current question
if (questions.length > 0) {
const currentQuestionId = questions[currentQuestionIndex]?.id;
if (currentQuestionId) {
Expand All @@ -60,34 +71,55 @@
setSelectedAnswers([]);
setFeedback(null);
setExplanation(null);
switch (studyOption) {
case 'random':
fetchRandomQuestionCallback();
break;
case 'practice-test':
fetchPracticeTestQuestionsCallback();
break;
case 'practice-worst':
fetchWorstQuestionsCallback();
break;
default:
fetchRandomQuestionCallback();
setHint(null);
if (currentQuestionIndex < questions.length - 1) {
setCurrentQuestionIndex(prevIndex => prevIndex + 1);
} else {
fetchQuestion();
}
};

const handleSubmitAnswerWrapper = () => {
handleSubmitAnswer(
selectedAnswers,
currentQuestion,
setFeedback,
updateUserMetrics,
updatePerformanceData,
currentQuestion?.id
);
};

const handleExplainWrapper = () => {
setIsExplanationLoading(true);
const correctAnswer = currentQuestion.options.find(option => option.correct).text;
handleExplain(selectedAnswers, currentQuestion, setIsExplanationLoading, setExplanation, correctAnswer);
};

const handleHintWrapper = () => {
setIsHintLoading(true);
handleHint(currentQuestion, setHint, setIsHintLoading);
};

if (isQuestionLoading) {
return <div>Loading question...</div>;
}

return (
<QuestionCard
question={currentQuestion}
selectedAnswers={selectedAnswers}
handleAnswerSelect={(option) => handleAnswerSelect(option, selectedAnswers, setSelectedAnswers)}
handleSubmitAnswer={() => handleSubmitAnswer(selectedAnswers, currentQuestion, setFeedback, updateUserMetrics, updatePerformanceData, currentQuestion?.id)}
handleSubmitAnswer={handleSubmitAnswerWrapper}
feedback={feedback}
handleExplain={() => handleExplain(selectedAnswers, currentQuestion, setLoading, setExplanation)}
loading={loading}
handleExplain={handleExplainWrapper}
isExplanationLoading={isExplanationLoading}
explanation={explanation}
fetchRandomQuestion={fetchNextQuestion}
handleHint={() => handleHint(currentQuestion)}
performanceMetrics={performanceMetrics} // Pass performance metrics to QuestionCard
handleHint={handleHintWrapper}
isHintLoading={isHintLoading}
hint={hint}
performanceMetrics={performanceMetrics}
studyMode={studyOption}
/>
);
Expand Down
1 change: 0 additions & 1 deletion frontend/src/styles/PerformanceMetrics.css
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
max-width: 750px;
width: 100%;
}

.metrics-title {
Expand Down
25 changes: 13 additions & 12 deletions frontend/src/utils/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ export const handleSubmitAnswer = (selectedAnswers, question, setFeedback, updat
}
};

export const handleExplain = (selectedAnswers, question, setLoading, setExplanation) => {
export const handleExplain = (selectedAnswers, question, setIsExplanationLoading, setExplanation, correctAnswer) => {
if (selectedAnswers.length > 0) {
const requestBody = {
question: question.question,
selectedAnswers: selectedAnswers.map(answer => answer.text),
correctAnswer: correctAnswer,
};
setLoading(true);
setIsExplanationLoading(true);
fetch(`${process.env.REACT_APP_API_URL}/api/explain`, {
method: 'POST',
headers: {
Expand All @@ -45,19 +46,19 @@ export const handleExplain = (selectedAnswers, question, setLoading, setExplanat
console.error('Error fetching explanation:', error);
})
.finally(() => {
setLoading(false);
setIsExplanationLoading(false);
});
} else {
console.log('No selected answers to explain');
}
};

export const handleHint = (question, setLoading, setExplanation) => {
const requestBody = {
question: question.question,
}
setLoading(true);
fetch(`${process.env.REACT_APP_API_URL}/api/hint`, {
export const handleHint = (question, setHint, setIsHintLoading) => {
const requestBody = {
question: question.question,
};
setIsHintLoading(true);
fetch(`${process.env.REACT_APP_API_URL}/api/hint`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand All @@ -72,12 +73,12 @@ export const handleHint = (question, setLoading, setExplanation) => {
})
.then(data => {
console.log('Hint:', data.hint);
setExplanation(data.hint);
setHint(data.hint);
})
.catch(error => {
console.error('Error fetching hint:', error);
})
.finally(() => {
setLoading(false);
setIsHintLoading(false);
});
};
};
Loading