File size: 8,120 Bytes
0ff2e07 | 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 | """Learning progress tracker tool for agents."""
import json
from datetime import datetime
from uuid import UUID
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from agents import function_tool
from backend.database import get_session
from backend.models.concept import Concept
from backend.services.spaced_repetition import (
calculate_next_review,
mastery_to_quality,
is_due_for_review,
days_until_review,
)
async def _get_db_session() -> AsyncSession:
"""Get a database session."""
async for session in get_session():
return session
raise RuntimeError("Could not get database session")
@function_tool
async def update_concept_mastery(
user_id: str,
concept_name: str,
quality: int,
session_id: str = "",
) -> str:
"""
Update mastery level for a concept based on review quality.
Args:
user_id: The user's ID (UUID)
concept_name: Name of the concept
quality: Review quality (0-5, where 0=blackout, 5=perfect)
session_id: Optional learning session ID
Returns:
JSON string with updated mastery info
"""
try:
user_uuid = UUID(user_id)
session_uuid = UUID(session_id) if session_id else None
except ValueError:
return json.dumps({"error": "Invalid UUID format"})
try:
db = await _get_db_session()
stmt = select(Concept).where(
Concept.user_id == user_uuid,
Concept.name == concept_name,
)
result = await db.execute(stmt)
concept = result.scalar_one_or_none()
if concept is None:
concept = Concept(
user_id=user_uuid,
session_id=session_uuid,
name=concept_name,
mastery_level=0.0,
)
db.add(concept)
old_mastery = concept.mastery_level
review_result = calculate_next_review(
quality=quality,
current_mastery=concept.mastery_level,
review_count=concept.review_count,
)
concept.mastery_level = review_result.new_mastery
concept.next_review = review_result.next_review
concept.last_reviewed = datetime.utcnow()
concept.review_count += 1
await db.commit()
await db.refresh(concept)
return json.dumps({
"success": True,
"concept": concept_name,
"previous_mastery": old_mastery,
"new_mastery": concept.mastery_level,
"next_review": concept.next_review.isoformat() if concept.next_review else None,
"days_until_review": review_result.interval_days,
"review_count": concept.review_count,
}, indent=2)
except Exception as e:
return json.dumps({"error": f"Failed to update mastery: {str(e)}"})
@function_tool
async def get_concept_progress(
user_id: str,
concept_name: str = "",
) -> str:
"""
Get progress for a concept or all concepts.
Args:
user_id: The user's ID (UUID)
concept_name: Optional specific concept name
Returns:
JSON string with progress information
"""
try:
user_uuid = UUID(user_id)
except ValueError:
return json.dumps({"error": "Invalid UUID format"})
try:
db = await _get_db_session()
if concept_name:
stmt = select(Concept).where(
Concept.user_id == user_uuid,
Concept.name == concept_name,
)
result = await db.execute(stmt)
concept = result.scalar_one_or_none()
if concept is None:
return json.dumps({"error": f"Concept '{concept_name}' not found"})
return json.dumps({
"concept": concept.name,
"mastery_level": concept.mastery_level,
"next_review": concept.next_review.isoformat() if concept.next_review else None,
"is_due": is_due_for_review(concept.next_review),
"days_until_review": days_until_review(concept.next_review),
"review_count": concept.review_count,
"last_reviewed": concept.last_reviewed.isoformat() if concept.last_reviewed else None,
}, indent=2)
else:
stmt = select(Concept).where(Concept.user_id == user_uuid)
result = await db.execute(stmt)
concepts = result.scalars().all()
return json.dumps({
"total_concepts": len(concepts),
"concepts": [
{
"name": c.name,
"mastery_level": c.mastery_level,
"is_due": is_due_for_review(c.next_review),
"days_until_review": days_until_review(c.next_review),
}
for c in concepts
],
"average_mastery": (
sum(c.mastery_level for c in concepts) / len(concepts)
if concepts
else 0.0
),
"due_for_review": sum(
1 for c in concepts if is_due_for_review(c.next_review)
),
}, indent=2)
except Exception as e:
return json.dumps({"error": f"Failed to get progress: {str(e)}"})
@function_tool
async def get_due_concepts(
user_id: str,
limit: int = 10,
) -> str:
"""
Get concepts that are due for review.
Args:
user_id: The user's ID (UUID)
limit: Maximum number of concepts to return
Returns:
JSON string with due concepts
"""
try:
user_uuid = UUID(user_id)
except ValueError:
return json.dumps({"error": "Invalid UUID format"})
try:
db = await _get_db_session()
stmt = select(Concept).where(Concept.user_id == user_uuid)
result = await db.execute(stmt)
concepts = result.scalars().all()
due_concepts = [
c for c in concepts
if is_due_for_review(c.next_review)
]
due_concepts.sort(key=lambda c: (c.mastery_level, c.next_review or datetime.min))
return json.dumps({
"total_due": len(due_concepts),
"concepts": [
{
"id": str(c.id),
"name": c.name,
"mastery_level": c.mastery_level,
"last_reviewed": c.last_reviewed.isoformat() if c.last_reviewed else None,
"review_count": c.review_count,
}
for c in due_concepts[:limit]
],
}, indent=2)
except Exception as e:
return json.dumps({"error": f"Failed to get due concepts: {str(e)}"})
@function_tool
async def record_quiz_performance(
user_id: str,
concept_name: str,
is_correct: bool,
session_id: str = "",
) -> str:
"""
Record quiz performance and update mastery.
Args:
user_id: The user's ID (UUID)
concept_name: The concept being tested
is_correct: Whether the answer was correct
session_id: Optional learning session ID
Returns:
JSON string with updated progress
"""
try:
user_uuid = UUID(user_id)
except ValueError:
return json.dumps({"error": "Invalid UUID format"})
try:
db = await _get_db_session()
stmt = select(Concept).where(
Concept.user_id == user_uuid,
Concept.name == concept_name,
)
result = await db.execute(stmt)
concept = result.scalar_one_or_none()
current_mastery = concept.mastery_level if concept else 0.0
quality = mastery_to_quality(current_mastery, is_correct)
return await update_concept_mastery(
user_id=user_id,
concept_name=concept_name,
quality=quality,
session_id=session_id,
)
except Exception as e:
return json.dumps({"error": f"Failed to record performance: {str(e)}"})
|