M1: FastAPI 分层后端(judge.engine hydro/judge0 + AI 多厂商) + 前端工作台(真实API/速查表/公式小课堂)
这个提交包含在:
@@ -0,0 +1,52 @@
|
||||
"""AI 对话与讲解 API。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.db import get_session
|
||||
from app.repositories.problem_repo import ProblemRepo
|
||||
from app.repositories.submission_repo import SubmissionRepo
|
||||
from app.services.ai_service import AIService
|
||||
|
||||
router = APIRouter(prefix="/chat", tags=["chat"])
|
||||
|
||||
|
||||
class ChatBody(BaseModel):
|
||||
messages: list[dict] # [{role, content}]
|
||||
mode: str = "learning"
|
||||
problem_id: int | None = None
|
||||
|
||||
|
||||
class ExplainBody(BaseModel):
|
||||
rid: str
|
||||
mode: str = "learning"
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def chat(body: ChatBody, session: Session = Depends(get_session)):
|
||||
svc = AIService()
|
||||
context_md = ""
|
||||
if body.problem_id:
|
||||
prob = ProblemRepo(session).get(body.problem_id)
|
||||
if prob:
|
||||
context_md = prob.statement_md
|
||||
try:
|
||||
return {"reply": await svc.chat(body.messages, mode=body.mode, context_md=context_md)}
|
||||
except RuntimeError as e:
|
||||
raise HTTPException(502, str(e))
|
||||
|
||||
|
||||
@router.post("/explain")
|
||||
async def explain(body: ExplainBody, session: Session = Depends(get_session)):
|
||||
sub = SubmissionRepo(session).get(body.rid)
|
||||
if not sub:
|
||||
raise HTTPException(404, "提交记录不存在")
|
||||
prob = ProblemRepo(session).get_by_hydro_pid(sub.hydro_pid)
|
||||
statement = prob.statement_md if prob else ""
|
||||
svc = AIService()
|
||||
try:
|
||||
return {"reply": await svc.explain_submission(sub, statement, mode=body.mode)}
|
||||
except RuntimeError as e:
|
||||
raise HTTPException(502, str(e))
|
||||
在新工单中引用
屏蔽一个用户