- Backend: FastAPI + Python-SocketIO + SQLAlchemy - Models for categories, questions, game sessions, events - AI services for answer validation and question generation (Claude) - Room management with Redis - Game logic with stealing mechanics - Admin API for question management - Frontend: React + Vite + TypeScript + Tailwind - 5 visual themes (DRRR, Retro, Minimal, RGB, Anime 90s) - Real-time game with Socket.IO - Achievement system - Replay functionality - Sound effects per theme - Docker Compose for deployment - Design documentation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
98 lines
3.1 KiB
Python
98 lines
3.1 KiB
Python
import json
|
|
from anthropic import Anthropic
|
|
from app.config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
|
|
class AIGenerator:
|
|
def __init__(self):
|
|
self.client = Anthropic(api_key=settings.anthropic_api_key)
|
|
|
|
async def generate_questions(
|
|
self,
|
|
category_name: str,
|
|
difficulty: int,
|
|
count: int = 5
|
|
) -> list[dict]:
|
|
"""
|
|
Generate trivia questions using Claude AI.
|
|
|
|
Args:
|
|
category_name: Name of the category (e.g., "Nintendo", "Anime")
|
|
difficulty: 1-5 (1=very easy, 5=very hard)
|
|
count: Number of questions to generate
|
|
|
|
Returns:
|
|
list[dict]: List of question objects
|
|
"""
|
|
difficulty_descriptions = {
|
|
1: "muy fácil - conocimiento básico que la mayoría conoce",
|
|
2: "fácil - conocimiento común entre fans casuales",
|
|
3: "medio - requiere ser fan de la categoría",
|
|
4: "difícil - conocimiento profundo del tema",
|
|
5: "muy difícil - solo expertos conocerían esto"
|
|
}
|
|
|
|
prompt = f"""Genera {count} preguntas de trivia para la categoría "{category_name}".
|
|
Dificultad: {difficulty} ({difficulty_descriptions.get(difficulty, 'medio')})
|
|
|
|
Requisitos:
|
|
- Las preguntas deben ser verificables y precisas
|
|
- Evitar ambigüedades
|
|
- Las respuestas deben ser específicas y concisas
|
|
- Incluir variaciones comunes de la respuesta
|
|
- Para gaming: referencias a juegos, personajes, mecánicas, fechas de lanzamiento
|
|
- Para anime: personajes, series, estudios, seiyuus
|
|
- Para música: artistas, canciones, álbumes, letras famosas
|
|
- Para películas: actores, directores, frases icónicas, premios
|
|
- Para libros: autores, obras, personajes literarios
|
|
- Para historia-cultura: eventos, fechas, personajes históricos, arte
|
|
|
|
Formato JSON (array de objetos):
|
|
[
|
|
{{
|
|
"question": "texto de la pregunta",
|
|
"correct_answer": "respuesta principal",
|
|
"alt_answers": ["variación1", "variación2"],
|
|
"fun_fact": "dato curioso opcional sobre la respuesta"
|
|
}}
|
|
]
|
|
|
|
Responde SOLO con el JSON, sin texto adicional."""
|
|
|
|
try:
|
|
message = self.client.messages.create(
|
|
model="claude-3-5-sonnet-20241022",
|
|
max_tokens=2000,
|
|
messages=[
|
|
{"role": "user", "content": prompt}
|
|
]
|
|
)
|
|
|
|
response_text = message.content[0].text.strip()
|
|
|
|
# Parse JSON response
|
|
questions = json.loads(response_text)
|
|
|
|
# Add metadata to each question
|
|
for q in questions:
|
|
q["difficulty"] = difficulty
|
|
q["points"] = settings.default_points.get(difficulty, 300)
|
|
q["time_seconds"] = settings.default_times.get(difficulty, 25)
|
|
|
|
return questions
|
|
|
|
except json.JSONDecodeError as e:
|
|
print(f"Error parsing AI response: {e}")
|
|
print(f"Response was: {response_text}")
|
|
return []
|
|
|
|
except Exception as e:
|
|
print(f"Error generating questions: {e}")
|
|
return []
|
|
|
|
|
|
# Singleton instance
|
|
ai_generator = AIGenerator()
|