Files
classquiz-ai/classquiz/routers/ai.py
T
2026-07-28 09:28:57 -04:00

41 lines
1.7 KiB
Python

# SPDX-FileCopyrightText: 2026 LobotomyLabs
# SPDX-License-Identifier: MPL-2.0
import os
import json
import httpx
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from classquiz.auth import get_current_user
from classquiz.db.models import User, QuizInput
router = APIRouter()
class AIGenerateRequest(BaseModel):
topic: str
num_questions: int = 5
@router.post("/generate", response_model=QuizInput)
async def generate_ai_quiz(req: AIGenerateRequest, user: User = Depends(get_current_user)):
api_key = os.getenv("AI_API_KEY", "")
base_url = os.getenv("AI_BASE_URL", "https://api.openai.com/v1")
model = os.getenv("AI_MODEL", "gpt-4o-mini")
prompt = f"Generate a quiz about '{req.topic}' with exactly {req.num_questions} multiple-choice questions (ABCD type). Return ONLY valid JSON with keys: title, description, questions (list of {{question, time: '20', type: 'ABCD', answers: [{{answer, right: bool, color}}]}})."
async with httpx.AsyncClient(timeout=30.0) as client:
res = await client.post(
f"{base_url}/chat/completions",
headers={"Authorization": f"Bearer {api_key}"},
json={"model": model, "messages": [{"role": "user", "content": prompt}], "temperature": 0.7},
)
if res.status_code != 200:
raise HTTPException(status_code=502, detail=f"AI provider error: {res.text}")
content = res.json()["choices"][0]["message"]["content"].strip()
if content.startswith("```"):
content = content.split("```")[1]
if content.startswith("json"):
content = content[4:]
content = content.strip("` \n")
return QuizInput(**json.loads(content))