codecracker-backend / backend /agents /adaptive_agent.py
faaizashiq's picture
Upload 6 files
62cf0fe verified
from typing import List, Dict, Any
class AdaptiveAgent:
"""
Agent A: The Coach
Responsibility: Analyzes user performance history to determine the optimal difficulty level.
"""
DIFFICULTIES = ["Easy", "Intermediate", "Expert"]
def evaluate_user(self, history: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Analyzes a list of past match results to determine new difficulty.
Args:
history: List of dicts, e.g.,
[{'result': 'success', 'time_taken': 45, 'hints_used': 0}, ...]
Returns:
Dict with 'recommended_difficulty' and 'reasoning'.
"""
if not history:
return {"difficulty": "Easy", "reason": "New user"}
# Analyze last 5 games
recent_games = history[-5:]
success_count = sum(1 for game in recent_games if game.get('result') == 'success')
avg_time = sum(game.get('time_taken', 0) for game in recent_games) / len(recent_games)
total_hints = sum(game.get('hints_used', 0) for game in recent_games)
current_difficulty = recent_games[-1].get('difficulty', "Easy")
# Promotion Logic
if success_count >= 4 and total_hints <= 2:
next_diff = self._change_difficulty(current_difficulty, 1)
return {
"difficulty": next_diff,
"reason": "Consistently successful with few hints. Promoting!"
}
# Demotion Logic
if success_count <= 1:
next_diff = self._change_difficulty(current_difficulty, -1)
return {
"difficulty": next_diff,
"reason": "Struggling with current tasks. Let's practice basics."
}
# Maintain
return {
"difficulty": current_difficulty,
"reason": "Steady progress. Maintaining current challenge level."
}
def _change_difficulty(self, current: str, step: int) -> str:
try:
# Normalize casing just in case
current = current.capitalize()
if current not in self.DIFFICULTIES:
# Fallback if unknown difficulty comes in
return "Easy"
idx = self.DIFFICULTIES.index(current)
new_idx = max(0, min(len(self.DIFFICULTIES) - 1, idx + step))
return self.DIFFICULTIES[new_idx]
except ValueError:
return "Easy"
if __name__ == "__main__":
# Test logic
agent = AdaptiveAgent()
history = [
{'result': 'success', 'time_taken': 30, 'hints_used': 0, 'difficulty': 'Beginner'},
{'result': 'success', 'time_taken': 25, 'hints_used': 0, 'difficulty': 'Beginner'},
{'result': 'success', 'time_taken': 40, 'hints_used': 1, 'difficulty': 'Beginner'},
{'result': 'success', 'time_taken': 35, 'hints_used': 0, 'difficulty': 'Beginner'}
]
print(agent.evaluate_user(history))