Spaces:
Sleeping
Sleeping
File size: 24,406 Bytes
bc987d8 |
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 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 |
"""
Contextualized AI Tutoring tools for TutorX.
Provides step-by-step guidance, alternative explanations, and conversational AI tutoring.
"""
import json
import uuid
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from mcp_server.mcp_instance import mcp
from mcp_server.model.gemini_flash import GeminiFlash
MODEL = GeminiFlash()
# Tutoring session storage
tutoring_sessions = {}
def extract_json_from_text(text: str):
"""Extract JSON from text response"""
import re
if not text or not isinstance(text, str):
return None
# Remove code fences
text = re.sub(r'^\s*```(?:json)?\s*', '', text, flags=re.IGNORECASE)
text = re.sub(r'\s*```\s*$', '', text, flags=re.IGNORECASE)
text = text.strip()
# Remove trailing commas
text = re.sub(r',([ \t\r\n]*[}}\]])', r'\1', text)
return json.loads(text)
class TutoringSession:
"""Manages a tutoring session with context and memory"""
def __init__(self, session_id: str, student_id: str, subject: str = "general"):
self.session_id = session_id
self.student_id = student_id
self.subject = subject
self.created_at = datetime.utcnow()
self.last_activity = datetime.utcnow()
self.conversation_history = []
self.current_topic = None
self.learning_objectives = []
self.student_understanding_level = 0.5 # 0.0 to 1.0
self.preferred_explanation_style = "detailed" # detailed, simple, visual, step-by-step
self.difficulty_preference = 0.5 # 0.0 to 1.0
def add_interaction(self, query: str, response: str, interaction_type: str = "question"):
"""Add an interaction to the session history"""
self.conversation_history.append({
"timestamp": datetime.utcnow().isoformat(),
"query": query,
"response": response,
"type": interaction_type,
"understanding_level": self.student_understanding_level
})
self.last_activity = datetime.utcnow()
def get_context_summary(self) -> str:
"""Generate a context summary for the AI tutor"""
recent_interactions = self.conversation_history[-5:] # Last 5 interactions
context = f"""
Session Context:
- Student ID: {self.student_id}
- Subject: {self.subject}
- Current Topic: {self.current_topic or 'Not specified'}
- Understanding Level: {self.student_understanding_level:.2f}/1.0
- Preferred Style: {self.preferred_explanation_style}
- Session Duration: {(datetime.utcnow() - self.created_at).total_seconds() / 60:.1f} minutes
Recent Conversation:
"""
for interaction in recent_interactions:
context += f"\nStudent: {interaction['query']}\nTutor: {interaction['response'][:100]}...\n"
return context
@mcp.tool()
async def start_tutoring_session(student_id: str, subject: str = "general",
learning_objectives: List[str] = None) -> dict:
"""
Start a new AI tutoring session with context management.
Args:
student_id: Student identifier
subject: Subject area for tutoring
learning_objectives: List of learning objectives for the session
Returns:
Dictionary with session information
"""
try:
session_id = str(uuid.uuid4())
session = TutoringSession(session_id, student_id, subject)
if learning_objectives:
session.learning_objectives = learning_objectives
tutoring_sessions[session_id] = session
# Generate welcome message
prompt = f"""
You are an expert AI tutor starting a new tutoring session.
Student ID: {student_id}
Subject: {subject}
Learning Objectives: {learning_objectives or 'To be determined based on student needs'}
Generate a welcoming introduction that:
1. Welcomes the student warmly
2. Explains your role as their AI tutor
3. Asks about their current understanding or what they'd like to learn
4. Sets expectations for the tutoring session
Return a JSON object with:
- "welcome_message": friendly welcome text
- "suggested_topics": list of 3-5 topics they might want to explore
- "session_guidelines": brief explanation of how the tutoring works
"""
response = await MODEL.generate_text(prompt, temperature=0.7)
welcome_data = extract_json_from_text(response)
return {
"success": True,
"session_id": session_id,
"student_id": student_id,
"subject": subject,
"created_at": session.created_at.isoformat(),
**welcome_data
}
except Exception as e:
return {
"success": False,
"error": f"Failed to start tutoring session: {str(e)}"
}
@mcp.tool()
async def ai_tutor_chat(session_id: str, student_query: str,
request_type: str = "explanation") -> dict:
"""
Process student query with contextualized AI tutoring.
Args:
session_id: Active tutoring session ID
student_query: Student's question or request
request_type: Type of request ('explanation', 'step_by_step', 'alternative', 'practice', 'clarification')
Returns:
Dictionary with tutor response and guidance
"""
try:
if session_id not in tutoring_sessions:
return {
"success": False,
"error": "Invalid session ID. Please start a new tutoring session."
}
session = tutoring_sessions[session_id]
context = session.get_context_summary()
# Analyze student query to understand their needs
analysis_prompt = f"""
Analyze this student query in the context of their tutoring session:
{context}
Student Query: "{student_query}"
Request Type: {request_type}
Analyze and return JSON with:
- "topic_identified": main topic/concept the student is asking about
- "difficulty_level": estimated difficulty (0.0 to 1.0)
- "understanding_gaps": potential areas where student might be confused
- "prerequisite_concepts": concepts student should know first
- "confidence_level": how confident the student seems (0.0 to 1.0)
"""
analysis_response = await MODEL.generate_text(analysis_prompt, temperature=0.3)
analysis = extract_json_from_text(analysis_response)
# Update session context based on analysis
if analysis and "topic_identified" in analysis:
session.current_topic = analysis["topic_identified"]
if "difficulty_level" in analysis:
session.difficulty_preference = analysis["difficulty_level"]
# Generate appropriate response based on request type
if request_type == "step_by_step":
response_prompt = f"""
{context}
The student asked: "{student_query}"
Provide a detailed step-by-step explanation that:
1. Breaks down the concept into manageable steps
2. Uses simple, clear language appropriate for their level
3. Includes examples for each step
4. Checks understanding at key points
5. Provides encouragement and support
Return JSON with:
- "step_by_step_explanation": detailed step-by-step guide
- "key_steps": list of main steps with brief descriptions
- "examples": relevant examples for each step
- "check_points": questions to verify understanding
- "encouragement": supportive message
"""
elif request_type == "alternative":
response_prompt = f"""
{context}
The student asked: "{student_query}"
Provide alternative explanations using different approaches:
1. Visual/spatial explanation
2. Analogy-based explanation
3. Real-world application
4. Simplified version
Return JSON with:
- "visual_explanation": explanation using visual/spatial concepts
- "analogy_explanation": explanation using familiar analogies
- "real_world_application": how this applies in real life
- "simplified_version": very simple explanation
- "which_works_best": question asking which explanation resonates
"""
else: # Default explanation
response_prompt = f"""
{context}
The student asked: "{student_query}"
Provide a comprehensive, personalized explanation that:
1. Addresses their specific question directly
2. Builds on their current understanding level
3. Uses their preferred explanation style
4. Includes relevant examples
5. Suggests next steps for learning
Return JSON with:
- "main_explanation": comprehensive answer to their question
- "key_concepts": important concepts to remember
- "examples": relevant examples
- "next_steps": suggested follow-up activities
- "related_topics": topics they might want to explore next
"""
tutor_response = await MODEL.generate_text(response_prompt, temperature=0.7)
response_data = extract_json_from_text(tutor_response)
# Add interaction to session history
session.add_interaction(
student_query,
response_data.get("main_explanation", str(response_data)),
request_type
)
return {
"success": True,
"session_id": session_id,
"request_type": request_type,
"analysis": analysis,
"response": response_data,
"session_stats": {
"interactions_count": len(session.conversation_history),
"current_topic": session.current_topic,
"understanding_level": session.student_understanding_level
}
}
except Exception as e:
return {
"success": False,
"error": f"Failed to process tutoring request: {str(e)}"
}
@mcp.tool()
async def get_step_by_step_guidance(session_id: str, concept: str,
current_step: int = 1) -> dict:
"""
Provide detailed step-by-step guidance for learning a specific concept.
Args:
session_id: Active tutoring session ID
concept: The concept to provide guidance for
current_step: Current step the student is on (1-based)
Returns:
Dictionary with step-by-step guidance
"""
try:
if session_id not in tutoring_sessions:
return {
"success": False,
"error": "Invalid session ID. Please start a new tutoring session."
}
session = tutoring_sessions[session_id]
context = session.get_context_summary()
prompt = f"""
{context}
Provide comprehensive step-by-step guidance for learning: "{concept}"
Current step: {current_step}
Create a structured learning path that:
1. Breaks the concept into logical, sequential steps
2. Provides clear explanations for each step
3. Includes practice exercises for each step
4. Offers multiple ways to understand each step
5. Includes checkpoints to verify understanding
Return JSON with:
- "total_steps": total number of steps needed
- "current_step_details": detailed information about the current step
- "step_explanation": clear explanation of the current step
- "practice_exercises": 2-3 practice problems for this step
- "key_points": important points to remember
- "common_mistakes": common mistakes students make at this step
- "next_step_preview": brief preview of what comes next
- "prerequisite_check": what student should know before this step
- "mastery_indicators": how to know if student has mastered this step
"""
response = await MODEL.generate_text(prompt, temperature=0.6)
guidance_data = extract_json_from_text(response)
return {
"success": True,
"session_id": session_id,
"concept": concept,
"current_step": current_step,
"guidance": guidance_data
}
except Exception as e:
return {
"success": False,
"error": f"Failed to generate step-by-step guidance: {str(e)}"
}
@mcp.tool()
async def get_alternative_explanations(session_id: str, concept: str,
explanation_types: List[str] = None) -> dict:
"""
Generate alternative explanations for a concept using different approaches.
Args:
session_id: Active tutoring session ID
concept: The concept to explain
explanation_types: Types of explanations to generate
Returns:
Dictionary with alternative explanations
"""
try:
if session_id not in tutoring_sessions:
return {
"success": False,
"error": "Invalid session ID. Please start a new tutoring session."
}
session = tutoring_sessions[session_id]
context = session.get_context_summary()
if not explanation_types:
explanation_types = ["visual", "analogy", "real_world", "simplified", "technical"]
prompt = f"""
{context}
Generate multiple alternative explanations for: "{concept}"
Create explanations using these approaches: {explanation_types}
For each explanation type, provide:
1. A complete explanation using that approach
2. Key benefits of this explanation style
3. When this explanation works best
4. Supporting examples or analogies
Return JSON with:
- "visual_explanation": explanation using visual/spatial concepts and imagery
- "analogy_explanation": explanation using familiar analogies and metaphors
- "real_world_explanation": explanation showing real-world applications
- "simplified_explanation": very simple, basic explanation
- "technical_explanation": detailed, technical explanation
- "story_explanation": explanation told as a story or narrative
- "comparison_explanation": explanation comparing to similar concepts
- "recommendation": which explanation might work best for this student
"""
response = await MODEL.generate_text(prompt, temperature=0.7)
explanations_data = extract_json_from_text(response)
return {
"success": True,
"session_id": session_id,
"concept": concept,
"explanation_types": explanation_types,
"explanations": explanations_data
}
except Exception as e:
return {
"success": False,
"error": f"Failed to generate alternative explanations: {str(e)}"
}
@mcp.tool()
async def update_student_understanding(session_id: str, concept: str,
understanding_level: float,
feedback: str = "") -> dict:
"""
Update student's understanding level and adapt tutoring accordingly.
Args:
session_id: Active tutoring session ID
concept: The concept being learned
understanding_level: Student's understanding level (0.0 to 1.0)
feedback: Optional feedback from student
Returns:
Dictionary with updated session information and recommendations
"""
try:
if session_id not in tutoring_sessions:
return {
"success": False,
"error": "Invalid session ID. Please start a new tutoring session."
}
session = tutoring_sessions[session_id]
# Update session understanding level
session.student_understanding_level = understanding_level
session.current_topic = concept
# Generate adaptive recommendations based on understanding level
prompt = f"""
Student understanding update:
- Concept: {concept}
- Understanding Level: {understanding_level:.2f}/1.0
- Student Feedback: {feedback or 'No feedback provided'}
- Session Context: {session.get_context_summary()}
Based on this understanding level, provide adaptive recommendations:
Return JSON with:
- "understanding_assessment": assessment of student's current understanding
- "next_actions": recommended next steps based on understanding level
- "difficulty_adjustment": how to adjust difficulty (easier/harder/same)
- "focus_areas": specific areas that need more attention
- "encouragement": encouraging message appropriate for their level
- "study_strategies": personalized study strategies
- "time_estimate": estimated time to reach mastery
"""
response = await MODEL.generate_text(prompt, temperature=0.6)
recommendations_data = extract_json_from_text(response)
# Add this update to conversation history
session.add_interaction(
f"Understanding update for {concept}: {understanding_level:.2f}",
f"Updated understanding and provided recommendations",
"understanding_update"
)
return {
"success": True,
"session_id": session_id,
"concept": concept,
"updated_understanding_level": understanding_level,
"recommendations": recommendations_data,
"session_stats": {
"interactions_count": len(session.conversation_history),
"current_topic": session.current_topic,
"understanding_level": session.student_understanding_level
}
}
except Exception as e:
return {
"success": False,
"error": f"Failed to update understanding: {str(e)}"
}
@mcp.tool()
async def get_tutoring_session_status(session_id: str) -> dict:
"""
Get the current status and context of a tutoring session.
Args:
session_id: Tutoring session ID
Returns:
Dictionary with session status and statistics
"""
try:
if session_id not in tutoring_sessions:
return {
"success": False,
"error": "Session not found"
}
session = tutoring_sessions[session_id]
return {
"success": True,
"session_id": session_id,
"student_id": session.student_id,
"subject": session.subject,
"current_topic": session.current_topic,
"created_at": session.created_at.isoformat(),
"last_activity": session.last_activity.isoformat(),
"duration_minutes": (datetime.utcnow() - session.created_at).total_seconds() / 60,
"understanding_level": session.student_understanding_level,
"preferred_style": session.preferred_explanation_style,
"learning_objectives": session.learning_objectives,
"interaction_count": len(session.conversation_history),
"recent_topics": list(set([
interaction.get("query", "")[:50]
for interaction in session.conversation_history[-5:]
]))
}
except Exception as e:
return {
"success": False,
"error": f"Failed to get session status: {str(e)}"
}
@mcp.tool()
async def end_tutoring_session(session_id: str, session_summary: str = "") -> dict:
"""
End a tutoring session and generate a summary.
Args:
session_id: Tutoring session ID
session_summary: Optional summary from student
Returns:
Dictionary with session summary and recommendations
"""
try:
if session_id not in tutoring_sessions:
return {
"success": False,
"error": "Session not found"
}
session = tutoring_sessions[session_id]
# Generate session summary
prompt = f"""
Generate a comprehensive summary for this tutoring session:
{session.get_context_summary()}
Session Details:
- Duration: {(datetime.utcnow() - session.created_at).total_seconds() / 60:.1f} minutes
- Interactions: {len(session.conversation_history)}
- Final Understanding Level: {session.student_understanding_level:.2f}/1.0
- Student Summary: {session_summary or 'No summary provided'}
Return JSON with:
- "session_summary": comprehensive summary of what was covered
- "learning_achievements": what the student accomplished
- "areas_covered": topics and concepts discussed
- "understanding_progress": how understanding evolved during session
- "recommendations": recommendations for future study
- "next_session_suggestions": suggestions for next tutoring session
- "study_plan": personalized study plan based on session
- "strengths_identified": student strengths observed
- "areas_for_improvement": areas that need more work
"""
response = await MODEL.generate_text(prompt, temperature=0.6)
summary_data = extract_json_from_text(response)
# Store session summary before removing
session_data = {
"session_id": session_id,
"student_id": session.student_id,
"subject": session.subject,
"duration_minutes": (datetime.utcnow() - session.created_at).total_seconds() / 60,
"interaction_count": len(session.conversation_history),
"final_understanding": session.student_understanding_level,
"summary": summary_data
}
# Remove session from active sessions
del tutoring_sessions[session_id]
return {
"success": True,
"session_ended": True,
**session_data
}
except Exception as e:
return {
"success": False,
"error": f"Failed to end session: {str(e)}"
}
@mcp.tool()
async def list_active_tutoring_sessions(student_id: str = None) -> dict:
"""
List all active tutoring sessions, optionally filtered by student.
Args:
student_id: Optional student ID to filter sessions
Returns:
Dictionary with list of active sessions
"""
try:
active_sessions = []
for session_id, session in tutoring_sessions.items():
if student_id is None or session.student_id == student_id:
active_sessions.append({
"session_id": session_id,
"student_id": session.student_id,
"subject": session.subject,
"current_topic": session.current_topic,
"created_at": session.created_at.isoformat(),
"last_activity": session.last_activity.isoformat(),
"duration_minutes": (datetime.utcnow() - session.created_at).total_seconds() / 60,
"understanding_level": session.student_understanding_level,
"interaction_count": len(session.conversation_history)
})
return {
"success": True,
"active_sessions": active_sessions,
"total_sessions": len(active_sessions),
"filtered_by_student": student_id is not None
}
except Exception as e:
return {
"success": False,
"error": f"Failed to list sessions: {str(e)}"
}
|