Add React frontend and Sinbad2IA LLM integration.
Introduce a full Vite/React UI for exams, auth, materials, images, generation, and export. Adapt backend for Sinbad2IA chat API, bcrypt passwords, CORS on port 5173, and schema migrations.
This commit is contained in:
@@ -4,7 +4,7 @@ from typing import Annotated
|
||||
|
||||
from fastapi import Depends
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
import bcrypt
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -18,7 +18,15 @@ from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserLogin, UserRead, UserRegister
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
def _hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def _verify_password(password: str, password_hash: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
class AuthService:
|
||||
@@ -34,7 +42,7 @@ class AuthService:
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
password_hash=pwd_context.hash(payload.password),
|
||||
password_hash=_hash_password(payload.password),
|
||||
full_name=clean_text(payload.full_name, max_length=200) if payload.full_name else None,
|
||||
)
|
||||
self.db.add(user)
|
||||
@@ -47,7 +55,7 @@ class AuthService:
|
||||
user = self.db.scalar(select(User).where(User.email == email))
|
||||
if user is None or user.password_hash is None:
|
||||
raise UnauthorizedError("Invalid email or password")
|
||||
if not pwd_context.verify(payload.password, user.password_hash):
|
||||
if not _verify_password(payload.password, user.password_hash):
|
||||
raise UnauthorizedError("Invalid email or password")
|
||||
return user
|
||||
|
||||
|
||||
@@ -93,6 +93,11 @@ class ExamService:
|
||||
def get_template(self, user_id: uuid.UUID, template_id: uuid.UUID) -> ExamTemplateRead:
|
||||
return self._template_read(self._get_user_template_or_404(user_id, template_id))
|
||||
|
||||
def list_questions(self, user_id: uuid.UUID, template_id: uuid.UUID) -> list[QuestionRead]:
|
||||
template = self._get_user_template_or_404(user_id, template_id)
|
||||
questions = sorted(template.questions, key=lambda q: q.created_at)
|
||||
return [self.to_question_read(question) for question in questions]
|
||||
|
||||
def get_owned_template(self, user_id: uuid.UUID, template_id: uuid.UUID) -> ExamTemplate:
|
||||
return self._get_user_template_or_404(user_id, template_id)
|
||||
|
||||
|
||||
+46
-21
@@ -5,44 +5,69 @@ from app.core.errors import LLMUnavailableError
|
||||
|
||||
|
||||
class LLMClient:
|
||||
"""Cliente para el API de chat de Sinbad2IA (Ollama-compatible en UJA)."""
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self.settings = settings
|
||||
|
||||
async def generate(self, prompt: str) -> str:
|
||||
if not self.settings.llm_api_key:
|
||||
raise LLMUnavailableError("LLM_API_KEY is not configured")
|
||||
def _chat_url(self) -> str:
|
||||
base = self.settings.llm_base_url.rstrip("/")
|
||||
if base.endswith("/api/chat"):
|
||||
return base
|
||||
return f"{base}/api/chat"
|
||||
|
||||
url = f"{self.settings.llm_base_url.rstrip('/')}/chat/completions"
|
||||
async def generate(self, prompt: str) -> str:
|
||||
payload = {
|
||||
"model": self.settings.llm_model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": "You generate safe, valid JSON exam questions for Moodle imports.",
|
||||
"role": "user",
|
||||
"content": (
|
||||
"Genera preguntas de examen en formato JSON válido para importar en Moodle. "
|
||||
"Responde únicamente con el JSON solicitado, sin texto adicional ni bloques markdown.\n\n"
|
||||
f"{prompt}"
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"temperature": 0.2,
|
||||
"response_format": {"type": "json_object"},
|
||||
}
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.settings.llm_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"stream": False,
|
||||
}
|
||||
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.settings.llm_api_key:
|
||||
headers["Authorization"] = f"Bearer {self.settings.llm_api_key}"
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.settings.llm_timeout_seconds) as client:
|
||||
response = await client.post(url, json=payload, headers=headers)
|
||||
response = await client.post(self._chat_url(), json=payload, headers=headers)
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPError as exc:
|
||||
raise LLMUnavailableError("LLM request failed") from exc
|
||||
|
||||
data = response.json()
|
||||
try:
|
||||
content = data["choices"][0]["message"]["content"]
|
||||
except (KeyError, IndexError, TypeError) as exc:
|
||||
raise LLMUnavailableError("LLM response did not include message content") from exc
|
||||
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
content = _extract_assistant_content(response.json())
|
||||
if not content.strip():
|
||||
raise LLMUnavailableError("LLM returned empty content")
|
||||
return content
|
||||
|
||||
|
||||
def _extract_assistant_content(data: object) -> str:
|
||||
"""Soporta respuesta Sinbad2IA/Ollama (`message.content`) y OpenAI (`choices`)."""
|
||||
if not isinstance(data, dict):
|
||||
raise LLMUnavailableError("LLM response is not a JSON object")
|
||||
|
||||
message = data.get("message")
|
||||
if isinstance(message, dict):
|
||||
content = message.get("content")
|
||||
if isinstance(content, str) and content.strip():
|
||||
return content
|
||||
|
||||
choices = data.get("choices")
|
||||
if isinstance(choices, list) and choices:
|
||||
first = choices[0]
|
||||
if isinstance(first, dict):
|
||||
msg = first.get("message")
|
||||
if isinstance(msg, dict):
|
||||
content = msg.get("content")
|
||||
if isinstance(content, str) and content.strip():
|
||||
return content
|
||||
|
||||
raise LLMUnavailableError("LLM response did not include message content")
|
||||
|
||||
Reference in New Issue
Block a user