from hopx_ai import Sandbox
import os
from typing import Dict, List, Any
class TutorialStep:
def __init__(self, step_id: str, instructions: str, solution: str, hints: List[str]):
self.step_id = step_id
self.instructions = instructions
self.solution = solution
self.hints = hints
class InteractiveTutorial:
def __init__(self, api_key: str):
self.api_key = api_key
self.sandbox = None
self.current_step = 0
self.steps = []
def initialize(self):
"""Initialize tutorial session"""
self.sandbox = Sandbox.create(
template="code-interpreter",
api_key=self.api_key,
timeout_seconds=3600
)
def add_step(self, step: TutorialStep):
"""Add tutorial step"""
self.steps.append(step)
def validate_step(self, step_index: int, student_code: str) -> Dict[str, Any]:
"""Validate student code for a step"""
step = self.steps[step_index]
# Execute student code
result = self.sandbox.run_code(student_code, timeout=10)
# Check if solution matches
solution_result = self.sandbox.run_code(step.solution, timeout=10)
# Compare outputs
student_output = result.stdout.strip() if result.success else ""
solution_output = solution_result.stdout.strip() if solution_result.success else ""
passed = student_output == solution_output and result.success
return {
"passed": passed,
"student_output": student_output,
"expected_output": solution_output,
"hint": step.hints[0] if not passed and step.hints else None,
"success": result.success
}
def get_next_hint(self, step_index: int, hint_index: int) -> str:
"""Get hint for current step"""
step = self.steps[step_index]
if hint_index < len(step.hints):
return step.hints[hint_index]
return "No more hints available"
def cleanup(self):
"""Clean up tutorial session"""
if self.sandbox:
self.sandbox.kill()
self.sandbox = None
# Usage
tutorial = InteractiveTutorial(api_key=os.getenv("HOPX_API_KEY"))
tutorial.initialize()
# Add steps
tutorial.add_step(TutorialStep(
step_id="step_1",
instructions="Print 'Hello, World!'",
solution="print('Hello, World!')",
hints=["Use the print() function", "Remember to use quotes around the text"]
))
# Validate student code
result = tutorial.validate_step(0, "print('Hello, World!')")
print(f"Passed: {result['passed']}")
tutorial.cleanup()