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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
"""

Proactive Learning Assistance Module (Phase 1)

Implements intelligent prompting suggestions, context-aware follow-up questions, and critical knowledge gap identification

"""

import json
from typing import Dict, List, Optional, Tuple
from datetime import datetime
from openai import OpenAI


class KnowledgeGapAnalyzer:
    """Analyzes user knowledge gaps, especially critical safety-related gaps"""
    
    # Safety-critical ADAS features that require high knowledge levels
    SAFETY_CRITICAL_FEATURES = [
        "Function of Active Distance Assist DISTRONIC",
        "Function of Active Stop-and-Go Assist",
        "Function of Active Steering Assist"
    ]
    
    # Knowledge level thresholds
    CRITICAL_GAP_THRESHOLD = 0.5  # Below this is considered a critical gap for safety features
    WEAK_AREA_THRESHOLD = 0.6  # Below this is considered a weak area
    
    def __init__(self, available_topics: List[str]):
        self.available_topics = available_topics
    
    def identify_critical_gaps(self, user_profile) -> List[str]:
        """

        Identify critical knowledge gaps that could impact safety

        

        Returns:

            List of topics with critical knowledge gaps

        """
        critical_gaps = []
        knowledge_level = user_profile.knowledge_level if hasattr(user_profile, 'knowledge_level') else {}
        
        for topic in self.available_topics:
            level = knowledge_level.get(topic, 0.0)
            
            # Check if it's a safety-critical feature with low knowledge
            if topic in self.SAFETY_CRITICAL_FEATURES and level < self.CRITICAL_GAP_THRESHOLD:
                critical_gaps.append(topic)
        
        return critical_gaps
    
    def identify_weak_areas(self, user_profile) -> List[str]:
        """

        Identify all weak areas (not just critical)

        

        Returns:

            List of topics with weak knowledge levels

        """
        weak_areas = []
        knowledge_level = user_profile.knowledge_level if hasattr(user_profile, 'knowledge_level') else {}
        
        for topic in self.available_topics:
            level = knowledge_level.get(topic, 0.0)
            if level < self.WEAK_AREA_THRESHOLD:
                weak_areas.append(topic)
        
        return weak_areas
    
    def get_gap_priority(self, user_profile) -> List[Tuple[str, float]]:
        """

        Get knowledge gaps with priority scores

        

        Returns:

            List of (topic, priority_score) tuples, sorted by priority

        """
        gaps = []
        knowledge_level = user_profile.knowledge_level if hasattr(user_profile, 'knowledge_level') else {}
        
        for topic in self.available_topics:
            level = knowledge_level.get(topic, 0.0)
            
            # Calculate priority score
            priority = 0.0
            
            # Safety-critical features get higher priority
            if topic in self.SAFETY_CRITICAL_FEATURES:
                priority += 2.0
            
            # Lower knowledge level = higher priority
            priority += (1.0 - level) * 1.5
            
            # Check if it's in weak areas
            if hasattr(user_profile, 'weak_areas') and topic in user_profile.weak_areas:
                priority += 0.5
            
            gaps.append((topic, priority))
        
        # Sort by priority (descending)
        gaps.sort(key=lambda x: x[1], reverse=True)
        return gaps


class PromptSuggestionGenerator:
    """Generates intelligent prompt suggestions based on user profile and learning history"""
    
    def __init__(self, client: OpenAI, rag_engine, knowledge_gap_analyzer: KnowledgeGapAnalyzer, 

                 available_topics: List[str]):
        self.client = client
        self.rag_engine = rag_engine
        self.gap_analyzer = knowledge_gap_analyzer
        self.available_topics = available_topics
    
    def generate_suggestions(self, user_id: str, user_profile, learning_path=None, 

                            context: Optional[str] = None, max_suggestions: int = 5) -> List[Dict[str, str]]:
        """

        Generate prompt suggestions based on multiple criteria

        

        Args:

            user_id: User ID

            user_profile: UserProfile object

            learning_path: Optional LearningPath object

            context: Optional context (e.g., recent question)

            max_suggestions: Maximum number of suggestions to return

            

        Returns:

            List of suggestion dictionaries with 'question' and 'reason' keys

        """
        suggestions = []
        
        # 1. Based on critical knowledge gaps
        critical_gaps = self.gap_analyzer.identify_critical_gaps(user_profile)
        for topic in critical_gaps[:2]:  # Top 2 critical gaps
            question = self._generate_question_for_topic(topic, "beginner")
            if question:
                suggestions.append({
                    "question": question,
                    "reason": f"Critical Safety Feature: Your understanding of {topic.replace('Function of ', '')} needs improvement",
                    "priority": "high",
                    "type": "critical_gap"
                })
        
        # 2. Based on learning path
        if learning_path and hasattr(learning_path, 'nodes') and learning_path.nodes:
            current_node = None
            if learning_path.current_node_index < len(learning_path.nodes):
                current_node = learning_path.nodes[learning_path.current_node_index]
            
            if current_node and current_node.status != "completed":
                question = self._generate_question_for_topic(current_node.topic, current_node.bloom_level)
                if question:
                    suggestions.append({
                        "question": question,
                        "reason": f"Learning Path: Current learning node - {current_node.topic}",
                        "priority": "medium",
                        "type": "learning_path"
                    })
        
        # 3. Based on weak areas
        weak_areas = self.gap_analyzer.identify_weak_areas(user_profile)
        for topic in weak_areas[:2]:  # Top 2 weak areas
            if topic not in critical_gaps:  # Avoid duplicates
                question = self._generate_question_for_topic(topic, "understand")
                if question:
                    suggestions.append({
                        "question": question,
                        "reason": f"Weak Area: Recommend strengthening understanding of {topic.replace('Function of ', '')}",
                        "priority": "medium",
                        "type": "weak_area"
                    })
        
        # 4. Based on recent questions (if context provided)
        if context:
            related_questions = self._generate_related_questions(context)
            for q in related_questions[:2]:
                suggestions.append({
                    "question": q,
                    "reason": "Related Question: Explore deeper into the topic you just asked about",
                    "priority": "low",
                    "type": "related"
                })
        
        # 5. Based on unlearned topics
        knowledge_level = user_profile.knowledge_level if hasattr(user_profile, 'knowledge_level') else {}
        unlearned_topics = [t for t in self.available_topics if t not in knowledge_level]
        for topic in unlearned_topics[:1]:  # Top 1 unlearned topic
            question = self._generate_question_for_topic(topic, "remember")
            if question:
                suggestions.append({
                    "question": question,
                    "reason": f"New Topic: Start learning {topic.replace('Function of ', '')}",
                    "priority": "low",
                    "type": "new_topic"
                })
        
        # Rank and filter suggestions
        suggestions = self._rank_suggestions(suggestions)
        return suggestions[:max_suggestions]
    
    def _generate_question_for_topic(self, topic: str, level: str = "understand") -> Optional[str]:
        """Generate a question for a specific topic"""
        try:
            # Use RAG to get topic information
            query = f"What are the key points about {topic}?"
            answer, _ = self.rag_engine.query(query)
            
            # Generate question using LLM
            prompt = f"""Based on the following information about {topic}, generate a single, clear question that a user might ask to learn about this topic.



The question should be at a {level} level (from Bloom's taxonomy).



Information:

{answer[:500]}  # Limit context to avoid token limits



Generate only the question text, nothing else. The question should be:

- Clear and specific

- Appropriate for someone learning about ADAS systems

- In Chinese or English (match the user's language preference)



Question:"""
            
            response = self.client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant that generates educational questions."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_tokens=100
            )
            
            question = response.choices[0].message.content.strip()
            # Remove quotes if present
            question = question.strip('"').strip("'")
            return question
        except Exception as e:
            print(f"Error generating question for topic {topic}: {e}")
            # Fallback to simple question
            topic_clean = topic.replace("Function of ", "").replace(" Assist", "")
            return f"What is {topic_clean} and how does it work?"
    
    def _generate_related_questions(self, context: str) -> List[str]:
        """Generate related questions based on context"""
        try:
            prompt = f"""Based on the following question or context, generate 2-3 related follow-up questions that would help deepen understanding.



Context: {context[:300]}



Generate 2-3 questions, one per line. Questions should:

- Build upon the context

- Help explore related concepts

- Be clear and specific



Questions:"""
            
            response = self.client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant that generates educational follow-up questions."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_tokens=200
            )
            
            questions_text = response.choices[0].message.content.strip()
            questions = [q.strip().strip('-').strip() for q in questions_text.split('\n') if q.strip()]
            return questions[:3]
        except Exception as e:
            print(f"Error generating related questions: {e}")
            return []
    
    def _rank_suggestions(self, suggestions: List[Dict]) -> List[Dict]:
        """Rank suggestions by priority"""
        priority_weights = {"high": 3, "medium": 2, "low": 1}
        suggestions.sort(key=lambda x: priority_weights.get(x.get("priority", "low"), 1), reverse=True)
        return suggestions


class FollowUpQuestionGenerator:
    """Generates context-aware follow-up questions based on RAG answers"""
    
    def __init__(self, client: OpenAI, rag_engine):
        self.client = client
        self.rag_engine = rag_engine
        
        self.bloom_levels = ["remember", "understand", "apply", "analyze", "evaluate", "create"]
    
    def generate_follow_up_questions(self, answer: str, user_profile, 

                                     max_questions: int = 5) -> List[Dict[str, str]]:
        """

        Generate follow-up questions based on the answer provided

        

        Args:

            answer: The RAG answer text

            user_profile: UserProfile object

            max_questions: Maximum number of questions to generate

            

        Returns:

            List of question dictionaries with 'question' and 'bloom_level' keys

        """
        questions = []
        
        # Determine user's current Bloom level (default to understand)
        current_bloom = self._infer_user_bloom_level(user_profile)
        current_index = self.bloom_levels.index(current_bloom) if current_bloom in self.bloom_levels else 1
        
        # Generate questions for next 2-3 Bloom levels
        target_levels = self.bloom_levels[current_index:current_index + 3]
        
        for level in target_levels[:2]:  # Limit to 2 levels
            level_questions = self._generate_questions_by_bloom(answer, level)
            questions.extend(level_questions[:2])  # 2 questions per level
        
        # Also generate related concept questions
        related_questions = self._generate_related_concept_questions(answer)
        questions.extend(related_questions[:1])
        
        return questions[:max_questions]
    
    def _infer_user_bloom_level(self, user_profile) -> str:
        """Infer user's current Bloom taxonomy level based on profile"""
        # Check recent test performance
        if hasattr(user_profile, 'bloom_level_performance') and user_profile.bloom_level_performance:
            # Find the highest level where user has good performance
            for level in reversed(self.bloom_levels):
                for topic_perf in user_profile.bloom_level_performance.values():
                    if level in topic_perf and topic_perf[level] >= 0.7:
                        return level
        
        # Default based on overall progress
        if hasattr(user_profile, 'knowledge_level') and user_profile.knowledge_level:
            avg_level = sum(user_profile.knowledge_level.values()) / len(user_profile.knowledge_level.values())
            if avg_level < 0.3:
                return "remember"
            elif avg_level < 0.6:
                return "understand"
            else:
                return "apply"
        
        return "understand"  # Default
    
    def _generate_questions_by_bloom(self, answer: str, bloom_level: str) -> List[Dict[str, str]]:
        """Generate questions at a specific Bloom taxonomy level"""
        try:
            bloom_descriptions = {
                "remember": "test basic recall of facts and information",
                "understand": "test explanation and interpretation of concepts",
                "apply": "test application of knowledge in practical situations",
                "analyze": "test analysis of relationships and structure",
                "evaluate": "test evaluation and judgment based on criteria",
                "create": "test creation of new ideas or solutions"
            }
            
            prompt = f"""Based on the following answer about ADAS systems, generate 2 follow-up questions at the {bloom_level} level of Bloom's taxonomy.



Bloom level description: {bloom_descriptions.get(bloom_level, '')}



Answer text:

{answer[:800]}  # Limit context



Generate 2 questions that:

- Build upon the information in the answer

- Are at the {bloom_level} level

- Help deepen understanding

- Are clear and specific



Output format: One question per line, no numbering or bullets.



Questions:"""
            
            response = self.client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {"role": "system", "content": "You are an educational assistant that generates follow-up questions."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_tokens=200
            )
            
            questions_text = response.choices[0].message.content.strip()
            question_list = [q.strip().strip('-').strip() for q in questions_text.split('\n') if q.strip()]
            
            return [{"question": q, "bloom_level": bloom_level} for q in question_list[:2]]
        except Exception as e:
            print(f"Error generating questions by Bloom level: {e}")
            return []
    
    def _generate_related_concept_questions(self, answer: str) -> List[Dict[str, str]]:
        """Generate questions about related concepts"""
        try:
            prompt = f"""Based on the following answer, generate 1 question about a related ADAS concept that would help the user understand the broader context.



Answer:

{answer[:500]}



Generate 1 question about a related concept or feature that connects to the information provided.



Question:"""
            
            response = self.client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {"role": "system", "content": "You are an educational assistant."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_tokens=100
            )
            
            question = response.choices[0].message.content.strip().strip('"').strip("'")
            return [{"question": question, "bloom_level": "understand"}]
        except Exception as e:
            print(f"Error generating related concept question: {e}")
            return []


class ProactiveLearningEngine:
    """Main engine for proactive learning assistance"""
    
    def __init__(self, client: OpenAI, rag_engine, user_profiling, adaptive_engine=None, 

                 available_topics: List[str] = None):
        self.client = client
        self.rag_engine = rag_engine
        self.user_profiling = user_profiling
        self.adaptive_engine = adaptive_engine
        self.available_topics = available_topics or []
        
        # Initialize components
        self.gap_analyzer = KnowledgeGapAnalyzer(self.available_topics)
        self.suggestion_generator = PromptSuggestionGenerator(
            client, rag_engine, self.gap_analyzer, self.available_topics
        )
        self.followup_generator = FollowUpQuestionGenerator(client, rag_engine)
    
    def get_prompt_suggestions(self, user_id: str, context: Optional[str] = None, 

                              max_suggestions: int = 5) -> List[Dict[str, str]]:
        """

        Get prompt suggestions for a user

        

        Args:

            user_id: User ID

            context: Optional context (e.g., recent question)

            max_suggestions: Maximum number of suggestions

            

        Returns:

            List of suggestion dictionaries

        """
        if not self.user_profiling:
            return []
        
        user_profile = self.user_profiling.get_or_create_profile(user_id)
        
        # Get learning path if available
        learning_path = None
        if self.adaptive_engine:
            learning_path = self.adaptive_engine.get_active_path(user_id)
        
        return self.suggestion_generator.generate_suggestions(
            user_id, user_profile, learning_path, context, max_suggestions
        )
    
    def get_follow_up_questions(self, user_id: str, answer: str, 

                                max_questions: int = 5) -> List[Dict[str, str]]:
        """

        Get follow-up questions based on an answer

        

        Args:

            user_id: User ID

            answer: The RAG answer text

            max_questions: Maximum number of questions

            

        Returns:

            List of question dictionaries

        """
        if not self.user_profiling:
            return []
        
        user_profile = self.user_profiling.get_or_create_profile(user_id)
        return self.followup_generator.generate_follow_up_questions(
            answer, user_profile, max_questions
        )
    
    def get_critical_gaps(self, user_id: str) -> List[str]:
        """

        Get critical knowledge gaps for a user

        

        Args:

            user_id: User ID

            

        Returns:

            List of topics with critical gaps

        """
        if not self.user_profiling:
            return []
        
        user_profile = self.user_profiling.get_or_create_profile(user_id)
        return self.gap_analyzer.identify_critical_gaps(user_profile)
    
    def analyze_user_state(self, user_id: str) -> Dict:
        """

        Analyze user's current learning state

        

        Args:

            user_id: User ID

            

        Returns:

            Dictionary with analysis results

        """
        if not self.user_profiling:
            return {}
        
        user_profile = self.user_profiling.get_or_create_profile(user_id)
        
        critical_gaps = self.gap_analyzer.identify_critical_gaps(user_profile)
        weak_areas = self.gap_analyzer.identify_weak_areas(user_profile)
        gap_priorities = self.gap_analyzer.get_gap_priority(user_profile)
        
        return {
            "critical_gaps": critical_gaps,
            "weak_areas": weak_areas,
            "gap_priorities": gap_priorities[:5],  # Top 5
            "total_gaps": len(weak_areas),
            "critical_gaps_count": len(critical_gaps)
        }