aakashbansal commited on
Commit
7b19fb1
·
1 Parent(s): f3e9b82

currently what's happening is, for the first question, I see a message s

Browse files
Files changed (1) hide show
  1. src/components/chatbot/chatbot.tsx +29 -26
src/components/chatbot/chatbot.tsx CHANGED
@@ -29,6 +29,7 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
29
  const scrollAreaRef = useRef<HTMLDivElement>(null);
30
  const { toast } = useToast();
31
  const messageIdCounter = useRef(0);
 
32
 
33
  const addMessage = (message: Omit<ChatMessageType, 'id' | 'timestamp'>) => {
34
  messageIdCounter.current += 1;
@@ -39,6 +40,7 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
39
  const fetchNewMCQ = async () => {
40
  if (!imageDataUri) {
41
  addMessage({ sender: 'ai', type: 'error', text: "Image data is not available to generate questions." });
 
42
  return;
43
  }
44
  setIsLoading(true);
@@ -48,9 +50,17 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
48
  setIncorrectAttempts([]);
49
 
50
  try {
51
- const mcqData = await generateMCQ({ imageDataUri });
52
- setCurrentMCQ(mcqData);
53
- addMessage({ sender: 'ai', type: 'mcq', mcq: mcqData });
 
 
 
 
 
 
 
 
54
  setIsAwaitingAnswer(true);
55
  } catch (error) {
56
  console.error("Error generating MCQ:", error);
@@ -67,12 +77,9 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
67
  };
68
 
69
  useEffect(() => {
70
- setMessages([]);
71
- addMessage({
72
- sender: 'ai',
73
- type: 'text',
74
- text: `Okay let's start with ${journeyTitle}!`,
75
- });
76
  if (imageDataUri) {
77
  fetchNewMCQ();
78
  } else {
@@ -82,7 +89,8 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
82
  }, [imageDataUri, journeyTitle]);
83
 
84
  useEffect(() => {
85
- if (imageDataUri && messages.length > 0 && messages[messages.length-1].text === "Preparing your journey...") {
 
86
  fetchNewMCQ();
87
  }
88
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -98,7 +106,7 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
98
  const handleOptionSelect = async (option: string, isCorrect: boolean) => {
99
  if (!currentMCQ) return;
100
 
101
- setIsAwaitingAnswer(false); // User has submitted an answer
102
 
103
  addMessage({
104
  sender: 'user',
@@ -107,8 +115,8 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
107
  });
108
 
109
  if (isCorrect) {
110
- addMessage({ sender: 'ai', type: 'feedback', text: "That's correct! Well done.", isCorrect: true });
111
  setIsLoading(true);
 
112
  try {
113
  const explanationResult = await explainCorrectAnswer({
114
  question: currentMCQ.mcq,
@@ -122,7 +130,7 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
122
  addMessage({ sender: 'ai', type: 'error', text: `Sorry, I couldn't provide an explanation for that. ${errorMsg}` });
123
  }
124
  setHasAnsweredCorrectly(true);
125
- setIncorrectAttempts([]); // Clear attempts on correct answer
126
  setIsLoading(false);
127
  } else {
128
  const updatedIncorrectAttempts = [...incorrectAttempts, option];
@@ -130,12 +138,11 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
130
  setIsLoading(true);
131
 
132
  if (updatedIncorrectAttempts.length >= currentMCQ.options.length - 1) {
133
- // All incorrect options have been tried
134
  addMessage({
135
  sender: 'ai',
136
  type: 'feedback',
137
  text: `It looks like you've tried the other options. The correct answer is "${currentMCQ.correctAnswer}".`,
138
- isCorrect: true, // Marking as 'correct' flow for styling purposes of feedback
139
  });
140
  try {
141
  const explanationResult = await explainCorrectAnswer({
@@ -150,9 +157,8 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
150
  addMessage({ sender: 'ai', type: 'error', text: `Sorry, I couldn't provide an explanation for that. ${errorMsg}` });
151
  }
152
  setHasAnsweredCorrectly(true);
153
- setIncorrectAttempts([]); // Clear attempts as the question is resolved
154
  } else {
155
- // Still more options to try
156
  try {
157
  const explanationResult = await explainIncorrectAnswer({
158
  question: currentMCQ.mcq,
@@ -161,15 +167,15 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
161
  correctAnswer: currentMCQ.correctAnswer,
162
  });
163
  addMessage({ sender: 'ai', type: 'feedback', text: explanationResult.explanation, isCorrect: false });
164
- addMessage({ sender: 'ai', type: 'mcq', mcq: currentMCQ }); // Re-post the same MCQ for another attempt
165
  } catch (error) {
166
  console.error("Error fetching explanation for incorrect answer:", error);
167
  const errorMsg = error instanceof Error ? error.message : "An unknown error occurred";
168
  addMessage({ sender: 'ai', type: 'error', text: `Sorry, I couldn't explain that. ${errorMsg}` });
169
  addMessage({ sender: 'ai', type: 'feedback', text: "That's not quite right. Try again!", isCorrect: false });
170
- addMessage({ sender: 'ai', type: 'mcq', mcq: currentMCQ }); // If explanation fetch fails, still re-post MCQ
171
  }
172
- setIsAwaitingAnswer(true); // Allow another answer on the re-posted MCQ
173
  }
174
  setIsLoading(false);
175
  }
@@ -190,7 +196,6 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
190
  msg.mcq.mcq === currentMCQ.mcq &&
191
  JSON.stringify(msg.mcq.options) === JSON.stringify(currentMCQ.options);
192
 
193
- // Find the index of the last message that is the current active MCQ
194
  const lastInstanceOfCurrentMCQIndex = messages.findLastIndex(
195
  (m) =>
196
  m.type === 'mcq' &&
@@ -200,9 +205,6 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
200
  JSON.stringify(m.mcq.options) === JSON.stringify(currentMCQ.options)
201
  );
202
 
203
- // This specific message should be interactive if it's the current MCQ,
204
- // it's the *last* instance of that MCQ in the chat,
205
- // and we are awaiting an answer for it and it hasn't been correctly answered yet.
206
  const shouldThisMessageBeInteractive =
207
  isThisMessageTheCurrentMCQ &&
208
  index === lastInstanceOfCurrentMCQIndex &&
@@ -213,11 +215,11 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
213
  <ChatMessage
214
  key={msg.id}
215
  message={msg}
216
- activeMCQ={currentMCQ} // Pass currentMCQ to know its structure
217
  isAwaitingActiveMCQAnswer={shouldThisMessageBeInteractive}
218
  onOptionSelectActiveMCQ={handleOptionSelect}
219
  incorrectAttemptsForMCQ={
220
- isThisMessageTheCurrentMCQ && // Only pass attempts for the current, active MCQ instance
221
  index === lastInstanceOfCurrentMCQIndex
222
  ? incorrectAttempts
223
  : []
@@ -261,3 +263,4 @@ export function Chatbot({ imageDataUri, journeyTitle }: ChatbotProps) {
261
  </div>
262
  );
263
  }
 
 
29
  const scrollAreaRef = useRef<HTMLDivElement>(null);
30
  const { toast } = useToast();
31
  const messageIdCounter = useRef(0);
32
+ const isInitialQuestionRef = useRef(true);
33
 
34
  const addMessage = (message: Omit<ChatMessageType, 'id' | 'timestamp'>) => {
35
  messageIdCounter.current += 1;
 
40
  const fetchNewMCQ = async () => {
41
  if (!imageDataUri) {
42
  addMessage({ sender: 'ai', type: 'error', text: "Image data is not available to generate questions." });
43
+ setIsLoading(false);
44
  return;
45
  }
46
  setIsLoading(true);
 
50
  setIncorrectAttempts([]);
51
 
52
  try {
53
+ const mcqResult = await generateMCQ({ imageDataUri });
54
+
55
+ let questionText = mcqResult.mcq;
56
+ if (isInitialQuestionRef.current) {
57
+ questionText = `Okay, let's start with ${journeyTitle}! ${mcqResult.mcq}`;
58
+ isInitialQuestionRef.current = false;
59
+ }
60
+
61
+ const mcqDataForMessage = { ...mcqResult, mcq: questionText };
62
+ setCurrentMCQ(mcqDataForMessage);
63
+ addMessage({ sender: 'ai', type: 'mcq', mcq: mcqDataForMessage });
64
  setIsAwaitingAnswer(true);
65
  } catch (error) {
66
  console.error("Error generating MCQ:", error);
 
77
  };
78
 
79
  useEffect(() => {
80
+ setMessages([]);
81
+ isInitialQuestionRef.current = true;
82
+
 
 
 
83
  if (imageDataUri) {
84
  fetchNewMCQ();
85
  } else {
 
89
  }, [imageDataUri, journeyTitle]);
90
 
91
  useEffect(() => {
92
+ if (imageDataUri && messages.length === 1 && messages[0].type === 'text' && messages[0].text === "Preparing your journey...") {
93
+ setMessages([]);
94
  fetchNewMCQ();
95
  }
96
  // eslint-disable-next-line react-hooks/exhaustive-deps
 
106
  const handleOptionSelect = async (option: string, isCorrect: boolean) => {
107
  if (!currentMCQ) return;
108
 
109
+ setIsAwaitingAnswer(false);
110
 
111
  addMessage({
112
  sender: 'user',
 
115
  });
116
 
117
  if (isCorrect) {
 
118
  setIsLoading(true);
119
+ addMessage({ sender: 'ai', type: 'feedback', text: "That's correct! Well done.", isCorrect: true });
120
  try {
121
  const explanationResult = await explainCorrectAnswer({
122
  question: currentMCQ.mcq,
 
130
  addMessage({ sender: 'ai', type: 'error', text: `Sorry, I couldn't provide an explanation for that. ${errorMsg}` });
131
  }
132
  setHasAnsweredCorrectly(true);
133
+ setIncorrectAttempts([]);
134
  setIsLoading(false);
135
  } else {
136
  const updatedIncorrectAttempts = [...incorrectAttempts, option];
 
138
  setIsLoading(true);
139
 
140
  if (updatedIncorrectAttempts.length >= currentMCQ.options.length - 1) {
 
141
  addMessage({
142
  sender: 'ai',
143
  type: 'feedback',
144
  text: `It looks like you've tried the other options. The correct answer is "${currentMCQ.correctAnswer}".`,
145
+ isCorrect: true,
146
  });
147
  try {
148
  const explanationResult = await explainCorrectAnswer({
 
157
  addMessage({ sender: 'ai', type: 'error', text: `Sorry, I couldn't provide an explanation for that. ${errorMsg}` });
158
  }
159
  setHasAnsweredCorrectly(true);
160
+ setIncorrectAttempts([]);
161
  } else {
 
162
  try {
163
  const explanationResult = await explainIncorrectAnswer({
164
  question: currentMCQ.mcq,
 
167
  correctAnswer: currentMCQ.correctAnswer,
168
  });
169
  addMessage({ sender: 'ai', type: 'feedback', text: explanationResult.explanation, isCorrect: false });
170
+ addMessage({ sender: 'ai', type: 'mcq', mcq: currentMCQ });
171
  } catch (error) {
172
  console.error("Error fetching explanation for incorrect answer:", error);
173
  const errorMsg = error instanceof Error ? error.message : "An unknown error occurred";
174
  addMessage({ sender: 'ai', type: 'error', text: `Sorry, I couldn't explain that. ${errorMsg}` });
175
  addMessage({ sender: 'ai', type: 'feedback', text: "That's not quite right. Try again!", isCorrect: false });
176
+ addMessage({ sender: 'ai', type: 'mcq', mcq: currentMCQ });
177
  }
178
+ setIsAwaitingAnswer(true);
179
  }
180
  setIsLoading(false);
181
  }
 
196
  msg.mcq.mcq === currentMCQ.mcq &&
197
  JSON.stringify(msg.mcq.options) === JSON.stringify(currentMCQ.options);
198
 
 
199
  const lastInstanceOfCurrentMCQIndex = messages.findLastIndex(
200
  (m) =>
201
  m.type === 'mcq' &&
 
205
  JSON.stringify(m.mcq.options) === JSON.stringify(currentMCQ.options)
206
  );
207
 
 
 
 
208
  const shouldThisMessageBeInteractive =
209
  isThisMessageTheCurrentMCQ &&
210
  index === lastInstanceOfCurrentMCQIndex &&
 
215
  <ChatMessage
216
  key={msg.id}
217
  message={msg}
218
+ activeMCQ={currentMCQ}
219
  isAwaitingActiveMCQAnswer={shouldThisMessageBeInteractive}
220
  onOptionSelectActiveMCQ={handleOptionSelect}
221
  incorrectAttemptsForMCQ={
222
+ isThisMessageTheCurrentMCQ &&
223
  index === lastInstanceOfCurrentMCQIndex
224
  ? incorrectAttempts
225
  : []
 
263
  </div>
264
  );
265
  }
266
+