faaizashiq commited on
Commit
62cf0fe
·
verified ·
1 Parent(s): ebd204f

Upload 6 files

Browse files
Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.9-slim
3
+
4
+ # Set the working directory in the container
5
+ WORKDIR /app
6
+
7
+ # Copy the requirements file into the container
8
+ COPY requirements.txt .
9
+
10
+ # Install any needed packages specified in requirements.txt
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Copy the current directory contents into the container at /app
14
+ COPY . .
15
+
16
+ # Make port 7860 available (Hugging Face Default)
17
+ EXPOSE 7860
18
+
19
+ # Define environment variable
20
+ ENV FLASK_APP=backend/main.py
21
+
22
+ # Create a non-root user (Security Best Practice for Spaces)
23
+ RUN useradd -m -u 1000 user
24
+ USER user
25
+ ENV HOME=/home/user \
26
+ PATH=/home/user/.local/bin:$PATH
27
+
28
+ # Run gunicorn
29
+ # Hugging Face expects port 7860
30
+ CMD gunicorn --workers=${WEB_CONCURRENCY:-4} --bind=0.0.0.0:${PORT:-7860} backend.main:app
backend/agents/adaptive_agent.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Any
2
+
3
+ class AdaptiveAgent:
4
+ """
5
+ Agent A: The Coach
6
+ Responsibility: Analyzes user performance history to determine the optimal difficulty level.
7
+ """
8
+
9
+ DIFFICULTIES = ["Easy", "Intermediate", "Expert"]
10
+
11
+ def evaluate_user(self, history: List[Dict[str, Any]]) -> Dict[str, Any]:
12
+ """
13
+ Analyzes a list of past match results to determine new difficulty.
14
+
15
+ Args:
16
+ history: List of dicts, e.g.,
17
+ [{'result': 'success', 'time_taken': 45, 'hints_used': 0}, ...]
18
+
19
+ Returns:
20
+ Dict with 'recommended_difficulty' and 'reasoning'.
21
+ """
22
+ if not history:
23
+ return {"difficulty": "Easy", "reason": "New user"}
24
+
25
+ # Analyze last 5 games
26
+ recent_games = history[-5:]
27
+ success_count = sum(1 for game in recent_games if game.get('result') == 'success')
28
+ avg_time = sum(game.get('time_taken', 0) for game in recent_games) / len(recent_games)
29
+ total_hints = sum(game.get('hints_used', 0) for game in recent_games)
30
+
31
+ current_difficulty = recent_games[-1].get('difficulty', "Easy")
32
+
33
+ # Promotion Logic
34
+ if success_count >= 4 and total_hints <= 2:
35
+ next_diff = self._change_difficulty(current_difficulty, 1)
36
+ return {
37
+ "difficulty": next_diff,
38
+ "reason": "Consistently successful with few hints. Promoting!"
39
+ }
40
+
41
+ # Demotion Logic
42
+ if success_count <= 1:
43
+ next_diff = self._change_difficulty(current_difficulty, -1)
44
+ return {
45
+ "difficulty": next_diff,
46
+ "reason": "Struggling with current tasks. Let's practice basics."
47
+ }
48
+
49
+ # Maintain
50
+ return {
51
+ "difficulty": current_difficulty,
52
+ "reason": "Steady progress. Maintaining current challenge level."
53
+ }
54
+
55
+ def _change_difficulty(self, current: str, step: int) -> str:
56
+ try:
57
+ # Normalize casing just in case
58
+ current = current.capitalize()
59
+ if current not in self.DIFFICULTIES:
60
+ # Fallback if unknown difficulty comes in
61
+ return "Easy"
62
+
63
+ idx = self.DIFFICULTIES.index(current)
64
+ new_idx = max(0, min(len(self.DIFFICULTIES) - 1, idx + step))
65
+ return self.DIFFICULTIES[new_idx]
66
+ except ValueError:
67
+ return "Easy"
68
+
69
+ if __name__ == "__main__":
70
+ # Test logic
71
+ agent = AdaptiveAgent()
72
+ history = [
73
+ {'result': 'success', 'time_taken': 30, 'hints_used': 0, 'difficulty': 'Beginner'},
74
+ {'result': 'success', 'time_taken': 25, 'hints_used': 0, 'difficulty': 'Beginner'},
75
+ {'result': 'success', 'time_taken': 40, 'hints_used': 1, 'difficulty': 'Beginner'},
76
+ {'result': 'success', 'time_taken': 35, 'hints_used': 0, 'difficulty': 'Beginner'}
77
+ ]
78
+ print(agent.evaluate_user(history))
backend/agents/hint_agent.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import os
3
+ from typing import Dict, Any, Optional
4
+
5
+ class HintAgent:
6
+ """
7
+ Agent C: The Mentor
8
+ Responsibility: Provides context-aware help based on user's current code/state.
9
+ """
10
+
11
+ def __init__(self, api_key: Optional[str] = None):
12
+ self.api_key = api_key or os.getenv("GEMINI_API_KEY")
13
+ if not self.api_key:
14
+ # For development, allow initialization without key if just testing logic structure
15
+ # But actual generation will fail
16
+ pass
17
+ else:
18
+ genai.configure(api_key=self.api_key)
19
+ self.model = genai.GenerativeModel('gemini-1.5-flash')
20
+
21
+ def generate_hint(self,
22
+ level_context: Dict[str, Any],
23
+ user_code: str,
24
+ error_message: Optional[str] = None) -> str:
25
+ """
26
+ Generates a hint based on the level and user's current attempt.
27
+ """
28
+ if not hasattr(self, 'model'):
29
+ return "SYSTEM ERROR: API Key missing for Hint Agent."
30
+
31
+ prompt = f"""
32
+ You are a coding tutor. The student is stuck.
33
+
34
+ LEVEL CONTEXT:
35
+ Title: {level_context.get('title')}
36
+ Goal: {level_context.get('goal_description') or level_context.get('problem')}
37
+
38
+ USER'S CURRENT CODE:
39
+ {user_code}
40
+
41
+ ERROR MESSAGE (if any):
42
+ {error_message}
43
+
44
+ TASK:
45
+ Provide a helpful, encouraging hint.
46
+ DO NOT give the full solution immediately unless they are very stuck.
47
+ If there is a syntax error, point it out gently.
48
+ Keep it under 2 sentences.
49
+ """
50
+
51
+ try:
52
+ response = self.model.generate_content(prompt)
53
+ return response.text.strip()
54
+ except Exception as e:
55
+ # Fallback Hint (Generic but helpful)
56
+ return "Try breaking the problem down into smaller steps. Check if your loops and variables are set correctly!"
57
+
58
+ if __name__ == "__main__":
59
+ from dotenv import load_dotenv
60
+ load_dotenv()
61
+ agent = HintAgent()
62
+ context = {"title": "Mars Rover", "goal_description": "Move forward 3 times"}
63
+ code = "move_forward\nturn_left"
64
+ print(agent.generate_hint(context, code))
backend/agents/scenario_agent.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import json
3
+ import os
4
+ import random
5
+ import time
6
+ from typing import Dict, Any, Optional
7
+
8
+ class ScenarioAgent:
9
+ """
10
+ Agent B: The Creator
11
+ Responsibility: Generates unique, creative game levels in JSON format.
12
+ Includes Caching & Fallback for Zero-Lag experience.
13
+ """
14
+
15
+ def __init__(self, api_key: Optional[str] = None):
16
+ self.api_key = api_key or os.getenv("GEMINI_API_KEY")
17
+ if not self.api_key:
18
+ print("WARNING: GEMINI_API_KEY not found. Using fallback mode.")
19
+ self.model = None
20
+ else:
21
+ genai.configure(api_key=self.api_key)
22
+ self.model = genai.GenerativeModel('gemini-1.5-flash')
23
+
24
+ # Simple In-Memory Cache: { "mode_difficulty_topic": { "data": ..., "timestamp": ... } }
25
+ self.cache = {}
26
+ self.cache_duration = 3600 # 1 hour
27
+
28
+
29
+ # STEM Topics to ensure variety
30
+ self.topics = {
31
+ "Space": ["Mars Rover Navigation", "Satellite Repair", "Alien Communication", "Black Hole Trajectory"],
32
+ "Biology": ["DNA Sequencing", "Blood Cell Defense", "Plant Growth Simulation", "Neuronal Network"],
33
+ "Robotics": ["Assembly Line Logic", "Drone Delivery", "Bomb Defusal", "Warehouse Sorting"],
34
+ "Cryptography": ["Spy Message Decoding", "Bank Security", "Password Hashing", "Ancient Runes"],
35
+ "Chemistry": ["Potion Mixing", "Element Bonding", "Acid-Base Neutralization", "Crystal Formation"]
36
+ }
37
+
38
+ # In-Memory "Learning" Storage
39
+ # In a real app, this would be a Database (Postgres/Firebase)
40
+ self.high_rated_levels = []
41
+
42
+ def learn_from_feedback(self, level_data: Dict[str, Any], rating: int):
43
+ """
44
+ Ingests user feedback.
45
+ If a level gets 5 stars, we save it as a 'Gold Standard' example.
46
+ """
47
+ if rating == 5:
48
+ # Keep only the last 50 awesome levels to save memory
49
+ if len(self.high_rated_levels) > 50:
50
+ self.high_rated_levels.pop(0)
51
+ self.high_rated_levels.append(level_data)
52
+ print(f"DEBUG: Agent learned from 5-star level: {level_data.get('title')}")
53
+
54
+ def _get_few_shot_examples(self, mode: str) -> str:
55
+ """Returns verified examples + dynamically learned examples."""
56
+
57
+ # 1. Static base examples (The "Textbook" rules)
58
+ base_examples = ""
59
+ if mode == "maze":
60
+ base_examples = """
61
+ EXAMPLE OUTPUT:
62
+ {
63
+ "type": "maze",
64
+ "level_id": "lvl_mars_01",
65
+ "title": "Mars Rover Jump",
66
+ "story": "A crater blocks the path! Use the jump module.",
67
+ "goal_description": "Reach the solar panel.",
68
+ "grid_layout": [[0,0,1], [2,0,3]],
69
+ "allowed_blocks": ["move_forward", "jump", "turn_left"],
70
+ "optimal_steps": 4,
71
+ "hint_1": "Jumping skips one tile.",
72
+ "hint_2": "Jump over the wall (1)."
73
+ }
74
+ """
75
+ elif mode == "blockly":
76
+ base_examples = """
77
+ EXAMPLE OUTPUT:
78
+ {
79
+ "type": "blockly",
80
+ "level_id": "lvl_crypto_05",
81
+ "title": "Caesar Cipher",
82
+ "story": "The spies sent a shifted message.",
83
+ "problem": "Shift each letter by +1.",
84
+ "toolbox_categories": ["Text", "Loops", "Variables"],
85
+ "initial_code": "message = 'HAL'",
86
+ "validation_rules": {
87
+ "required_concepts": ["loop"],
88
+ "expected_output": "IBM"
89
+ },
90
+ "hint_1": "Loop through each character.",
91
+ "hint_2": "Use charCodeAt() + 1"
92
+ }
93
+ """
94
+
95
+ # 2. Dynamic "Learned" Examples (The "User Favorites")
96
+ learned_example = ""
97
+ # Filter for relevant mode
98
+ relevant_learnings = [l for l in self.high_rated_levels if l.get('type') == mode]
99
+
100
+ if relevant_learnings:
101
+ # Pick one random 5-star level to inspire the AI
102
+ favorite = random.choice(relevant_learnings)
103
+ learned_example = f"""
104
+
105
+ USER FAVORITE EXAMPLE (The user loved this style!):
106
+ {json.dumps(favorite)}
107
+ """
108
+
109
+ return base_examples + learned_example
110
+
111
+ def _get_system_prompt(self, mode: str, difficulty: str) -> str:
112
+ """Constructs the system prompt based on mode and difficulty."""
113
+
114
+ base_prompt = f"""
115
+ You are the Lead Game Designer for 'CodeCracker', an educational coding game for ages 10-14.
116
+ Your task is to generate a UNIQUE Level JSON.
117
+
118
+ CURRENT SETTINGS:
119
+ - Mode: {mode}
120
+ - Difficulty: {difficulty}
121
+
122
+ Refer to these strict examples for the required JSON structure:
123
+ {self._get_few_shot_examples(mode)}
124
+
125
+ OUTPUT FORMAT: RAW JSON ONLY (No Markdown).
126
+ """
127
+
128
+ if mode == "maze":
129
+ base_prompt += """
130
+ JSON STRUCTURE FOR MAZE:
131
+ {
132
+ "type": "maze",
133
+ "level_id": "UUID_STRING",
134
+ "title": "Short Fun Title",
135
+ "story": "Engaging 1-2 sentence scenario.",
136
+ "goal_description": "What needs to be achieved.",
137
+ "grid_layout": [[0,0,1],[2,0,3]], // 0=Path, 1=Wall, 2=Start, 3=Goal, 4=Hazard
138
+ "allowed_blocks": ["move_forward", "turn_left", "turn_right", "repeat_loop"],
139
+ "optimal_steps": 5,
140
+ "hint_1": "Vague hint",
141
+ "hint_2": "Specific hint"
142
+ }
143
+ Constraints:
144
+ - Easy: 5x5 grid, simple path.
145
+ - Intermediate: 8x8 grid, more turns.
146
+ - Expert: 10x10 grid, dead ends, multiple turns.
147
+ """
148
+
149
+ elif mode == "blockly":
150
+ base_prompt += """
151
+ JSON STRUCTURE FOR BLOCKLY (LOGIC PUZZLE):
152
+ {
153
+ "type": "blockly",
154
+ "level_id": "UUID_STRING",
155
+ "title": "Short Fun Title",
156
+ "story": "Real-world problem scenario.",
157
+ "problem": "Clear problem statement.",
158
+ "toolbox_categories": ["Math", "Loops", "Variables"], // What blocks are available
159
+ "initial_code": "", // Optional starter code
160
+ "validation_rules": {
161
+ "required_concepts": ["loop", "variable"],
162
+ "expected_output": "Value or State"
163
+ },
164
+ "hint_1": "Vague hint",
165
+ "hint_2": "Specific hint"
166
+ }
167
+ """
168
+
169
+ elif mode == "time_challenge":
170
+ base_prompt += """
171
+ JSON STRUCTURE FOR TIME CHALLENGE:
172
+ This is a fast-paced mode mixing logic and debugging.
173
+ {
174
+ "type": "time_challenge",
175
+ "level_id": "UUID_STRING",
176
+ "title": "Speed Run Title",
177
+ "story": "Urgent scenario (e.g., 'Reactor Meltdown!').",
178
+ "timer_seconds": 60,
179
+ "buggy_code": "code with syntax or logic error",
180
+ "task": "Fix the bug before time runs out!",
181
+ "solution_patch": "Corrected line or logic"
182
+ }
183
+ """
184
+
185
+ return base_prompt
186
+
187
+ def generate_level(self, mode: str, difficulty: str, specific_topic: Optional[str] = None) -> Dict[str, Any]:
188
+ """Generates a level config with Cache & Fallback."""
189
+
190
+ # 1. Randomize topic if null
191
+ if not specific_topic:
192
+ category = random.choice(list(self.topics.keys()))
193
+ specific_topic = random.choice(self.topics[category])
194
+ else:
195
+ category = "Requested"
196
+
197
+ # 2. Check Cache (to prevent lag on repeated requests)
198
+ cache_key = f"{mode}_{difficulty}_{specific_topic}"
199
+ if cache_key in self.cache:
200
+ entry = self.cache[cache_key]
201
+ if time.time() - entry['timestamp'] < self.cache_duration:
202
+ print(f"DEBUG: Returning cached level for {cache_key}")
203
+ return entry['data']
204
+
205
+ prompt = f"""
206
+ Generate a Level.
207
+ Topic: {specific_topic}
208
+ Domain: {category}
209
+ Ensure the scenario is DIFFERENT from generic coding problems.
210
+ """
211
+
212
+ try:
213
+ if not self.model:
214
+ raise Exception("No API Key or Model available")
215
+
216
+ # 3. Fast Timeout generation (Simulated by simple call here, but ideally async)
217
+ response = self.model.generate_content(
218
+ self._get_system_prompt(mode, difficulty) + "\n\n" + prompt
219
+ )
220
+ text = response.text.strip()
221
+ if text.startswith("```json"):
222
+ text = text[7:]
223
+ if text.endswith("```"):
224
+ text = text[:-3]
225
+
226
+ level_data = json.loads(text)
227
+
228
+ # 4. Save to Cache
229
+ self.cache[cache_key] = {
230
+ "data": level_data,
231
+ "timestamp": time.time()
232
+ }
233
+ return level_data
234
+
235
+ except Exception as e:
236
+ print(f"ERROR: AI Generation failed ({e}). Returning Fallback.")
237
+ return self._get_fallback_level(mode, difficulty)
238
+
239
+ def _get_fallback_level(self, mode, difficulty):
240
+ """Zero-Crash Fallback: Returns a valid local JSON if AI fails."""
241
+ if mode == "maze":
242
+ return {
243
+ "type": "maze",
244
+ "level_id": "fallback_001",
245
+ "title": "Emergency Practice",
246
+ "story": "The AI navigation system is offline. We need manual override!",
247
+ "grid_layout": [[2,0,0],[1,1,0],[0,0,3]],
248
+ "allowed_blocks": ["move", "turn"],
249
+ "tutorial": "Guide the bot manually."
250
+ }
251
+ elif mode == "blockly":
252
+ return {
253
+ "type": "blockly",
254
+ "level_id": "fallback_002",
255
+ "title": "Logic Repair",
256
+ "story": "The automated systems are down. We need manual logic configuration.",
257
+ "problem": "Create a loop that counts to 3.",
258
+ "toolbox_categories": ["Loops", "Math", "Variables"],
259
+ "initial_code": "",
260
+ "validation_rules": {
261
+ "required_concepts": ["loop"],
262
+ "expected_output": "3"
263
+ },
264
+ "hint_1": "Use the 'repeat' block.",
265
+ "hint_2": "Set the number to 3."
266
+ }
267
+ elif mode == "time_challenge":
268
+ return {
269
+ "type": "time_challenge",
270
+ "level_id": "fallback_003",
271
+ "title": "System Reboot",
272
+ "story": "Critical Error! Debug the startup sequence immediately.",
273
+ "timer_seconds": 45,
274
+ "buggy_code": "print('System Ready'\nstart_engine()",
275
+ "task": "Fix the syntax error.",
276
+ "solution_patch": "print('System Ready')\nstart_engine()"
277
+ }
278
+
279
+ return {
280
+ "type": "error",
281
+ "message": "Mode not supported in fallback",
282
+ "level_id": "error_000"
283
+ }
284
+
285
+ if __name__ == "__main__":
286
+ # fast test
287
+ from dotenv import load_dotenv
288
+ load_dotenv()
289
+ agent = ScenarioAgent()
290
+ print("Testing Maze Generation...")
291
+ print(json.dumps(agent.generate_level("maze", "Easy"), indent=2))
backend/main.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from flask_cors import CORS
3
+ import os
4
+ from dotenv import load_dotenv
5
+
6
+ # Import our Agents
7
+ from agents.scenario_agent import ScenarioAgent
8
+ from agents.adaptive_agent import AdaptiveAgent
9
+ from agents.hint_agent import HintAgent
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
+
14
+ app = Flask(__name__)
15
+ CORS(app) # Enable CORS for all routes
16
+
17
+ # Initialize Agents
18
+ scenario_agent = ScenarioAgent()
19
+ adaptive_agent = AdaptiveAgent()
20
+ hint_agent = HintAgent()
21
+
22
+ @app.route('/health', methods=['GET'])
23
+ def health_check():
24
+ return jsonify({"status": "healthy", "service": "CodeCracker AI Backend"})
25
+
26
+ @app.route('/api/level/generate', methods=['POST'])
27
+ def generate_level():
28
+ """
29
+ Generates a new level (Maze, Blockly, or Time Challenge).
30
+ Expected JSON: { "mode": "maze", "difficulty": "Easy", "topic": "Space" (optional) }
31
+ """
32
+ data = request.json
33
+ mode = data.get('mode', 'maze')
34
+ difficulty = data.get('difficulty', 'Easy')
35
+ topic = data.get('topic')
36
+
37
+ try:
38
+ level_data = scenario_agent.generate_level(mode, difficulty, topic)
39
+ if not level_data:
40
+ raise Exception("Empty level data returned")
41
+ return jsonify(level_data)
42
+ except Exception as e:
43
+ print(f"CRITICAL ERROR /api/level/generate: {e}")
44
+ # Final Safety Net: Return a basic Maze fallback if everything else explodes
45
+ fallback = {
46
+ "type": "maze",
47
+ "level_id": "emergency_fallback",
48
+ "title": "System Practice",
49
+ "story": "System offline. Practice mode engaged.",
50
+ "grid_layout": [[2,0,3]],
51
+ "allowed_blocks": ["move_forward"],
52
+ "tutorial_text": "Move to the goal."
53
+ }
54
+ return jsonify(fallback)
55
+
56
+ @app.route('/api/level/feedback', methods=['POST'])
57
+ def level_feedback():
58
+ """
59
+ Receives user feedback (1-5 stars) on a level.
60
+ Expected JSON: { "level_data": {...}, "rating": 5 }
61
+ """
62
+ data = request.json or {}
63
+ level_data = data.get('level_data')
64
+ rating = data.get('rating')
65
+
66
+ if not level_data or not rating:
67
+ return jsonify({"message": "Invalid data ignored"}), 400
68
+
69
+ try:
70
+ # Teach the agent!
71
+ scenario_agent.learn_from_feedback(level_data, int(rating))
72
+ return jsonify({"status": "learned", "message": "Thanks for the feedback!"})
73
+ except Exception as e:
74
+ print(f"Feedback Error: {e}")
75
+ return jsonify({"status": "ignored"}), 200
76
+
77
+ @app.route('/api/player/evaluate', methods=['POST'])
78
+ def evaluate_player():
79
+ """
80
+ Evaluates player history to adjust difficulty.
81
+ Expected JSON: { "history": [ { "result": "success", "time_taken": 30 }, ... ] }
82
+ """
83
+ data = request.json or {}
84
+ history = data.get('history', [])
85
+
86
+ try:
87
+ evaluation = adaptive_agent.evaluate_user(history)
88
+ return jsonify(evaluation)
89
+ except Exception as e:
90
+ print(f"CRITICAL ERROR /api/player/evaluate: {e}")
91
+ # Fallback: Default to current or Easy
92
+ return jsonify({"difficulty": "Easy", "reason": "System requires calibration."})
93
+
94
+ @app.route('/api/hint/generate', methods=['POST'])
95
+ def generate_hint():
96
+ """
97
+ Generates a context-aware hint.
98
+ Expected JSON: { "level_context": {...}, "user_code": "...", "error": "..." }
99
+ """
100
+ data = request.json or {}
101
+ if 'user_code' not in data:
102
+ return jsonify({"error": "Missing user_code"}), 400
103
+
104
+ try:
105
+ hint = hint_agent.generate_hint(
106
+ level_context=data.get('level_context', {}),
107
+ user_code=data.get('user_code'),
108
+ error_message=data.get('error')
109
+ )
110
+ return jsonify({"hint": hint})
111
+ except Exception as e:
112
+ print(f"CRITICAL ERROR /api/hint/generate: {e}")
113
+ return jsonify({"hint": "Try checking your syntax and logic step-by-step."})
114
+
115
+ if __name__ == '__main__':
116
+ port = int(os.environ.get('PORT', 5000))
117
+ app.run(host='0.0.0.0', port=port, debug=True)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ flask>=3.0.0
2
+ flask-cors>=4.0.0
3
+ python-dotenv>=1.0.0
4
+ google-generativeai>=0.3.0
5
+ gunicorn>=21.2.0