mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 01:49:30 +08:00
Question Notebook with bookmarks & categories, Mermaid diagram support in Visualize, embedding mismatch detection refinement, system message merging for Qwen/vLLM, LM Studio & llama.cpp providers, Glass theme, reporting agent retry resilience, and docs migration. Made-with: Cursor
214 lines
7.2 KiB
Python
214 lines
7.2 KiB
Python
"""
|
|
Question Notebook API — persists quiz questions, bookmarks, and categories.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from fastapi import APIRouter, HTTPException, Query
|
|
from pydantic import BaseModel, Field
|
|
|
|
from deeptutor.services.session import get_sqlite_session_store
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
# ── Models ────────────────────────────────────────────────────────
|
|
|
|
class NotebookEntryItem(BaseModel):
|
|
id: int
|
|
session_id: str
|
|
session_title: str = ""
|
|
question_id: str = ""
|
|
question: str
|
|
question_type: str = ""
|
|
options: dict[str, str] = {}
|
|
correct_answer: str = ""
|
|
explanation: str = ""
|
|
difficulty: str = ""
|
|
user_answer: str = ""
|
|
is_correct: bool = False
|
|
bookmarked: bool = False
|
|
followup_session_id: str = ""
|
|
created_at: float
|
|
updated_at: float
|
|
categories: list[CategoryItem] | None = None
|
|
|
|
|
|
class NotebookEntryListResponse(BaseModel):
|
|
items: list[NotebookEntryItem]
|
|
total: int
|
|
|
|
|
|
class EntryUpdateRequest(BaseModel):
|
|
bookmarked: bool | None = None
|
|
followup_session_id: str | None = None
|
|
|
|
|
|
class CategoryItem(BaseModel):
|
|
id: int
|
|
name: str
|
|
created_at: float = 0
|
|
entry_count: int = 0
|
|
|
|
|
|
class CategoryCreateRequest(BaseModel):
|
|
name: str = Field(..., min_length=1, max_length=100)
|
|
|
|
|
|
class CategoryRenameRequest(BaseModel):
|
|
name: str = Field(..., min_length=1, max_length=100)
|
|
|
|
|
|
class CategoryAddRequest(BaseModel):
|
|
category_id: int
|
|
|
|
|
|
class UpsertEntryRequest(BaseModel):
|
|
session_id: str
|
|
question_id: str
|
|
question: str
|
|
question_type: str = ""
|
|
options: dict[str, str] | None = None
|
|
correct_answer: str = ""
|
|
explanation: str = ""
|
|
difficulty: str = ""
|
|
user_answer: str = ""
|
|
is_correct: bool = False
|
|
|
|
|
|
# ── Entry endpoints ──────────────────────────────────────────────
|
|
|
|
@router.post("/entries/upsert")
|
|
async def upsert_single_entry(payload: UpsertEntryRequest):
|
|
store = get_sqlite_session_store()
|
|
try:
|
|
await store.upsert_notebook_entries(payload.session_id, [payload.model_dump()])
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=404, detail=str(e))
|
|
entry = await store.find_notebook_entry(payload.session_id, payload.question_id)
|
|
if entry is None:
|
|
raise HTTPException(status_code=500, detail="Upsert failed")
|
|
return entry
|
|
|
|
@router.get("/entries", response_model=NotebookEntryListResponse)
|
|
async def list_entries(
|
|
category_id: int | None = Query(default=None),
|
|
bookmarked: bool | None = Query(default=None),
|
|
is_correct: bool | None = Query(default=None),
|
|
limit: int = Query(default=50, ge=1, le=200),
|
|
offset: int = Query(default=0, ge=0),
|
|
) -> NotebookEntryListResponse:
|
|
store = get_sqlite_session_store()
|
|
result = await store.list_notebook_entries(
|
|
category_id=category_id,
|
|
bookmarked=bookmarked,
|
|
is_correct=is_correct,
|
|
limit=limit,
|
|
offset=offset,
|
|
)
|
|
return NotebookEntryListResponse(
|
|
items=[NotebookEntryItem(**item) for item in result["items"]],
|
|
total=result["total"],
|
|
)
|
|
|
|
|
|
@router.get("/entries/lookup/by-question")
|
|
async def lookup_entry(session_id: str = Query(...), question_id: str = Query(...)):
|
|
store = get_sqlite_session_store()
|
|
entry = await store.find_notebook_entry(session_id, question_id)
|
|
if entry is None:
|
|
raise HTTPException(status_code=404, detail="Entry not found")
|
|
return entry
|
|
|
|
|
|
@router.get("/entries/{entry_id}", response_model=NotebookEntryItem)
|
|
async def get_entry(entry_id: int) -> NotebookEntryItem:
|
|
store = get_sqlite_session_store()
|
|
entry = await store.get_notebook_entry(entry_id)
|
|
if entry is None:
|
|
raise HTTPException(status_code=404, detail="Entry not found")
|
|
return NotebookEntryItem(**entry)
|
|
|
|
|
|
@router.patch("/entries/{entry_id}")
|
|
async def update_entry(entry_id: int, payload: EntryUpdateRequest):
|
|
store = get_sqlite_session_store()
|
|
updates = payload.model_dump(exclude_none=True)
|
|
if not updates:
|
|
raise HTTPException(status_code=400, detail="No fields to update")
|
|
updated = await store.update_notebook_entry(entry_id, updates)
|
|
if not updated:
|
|
raise HTTPException(status_code=404, detail="Entry not found")
|
|
return {"updated": True, "id": entry_id}
|
|
|
|
|
|
@router.delete("/entries/{entry_id}")
|
|
async def delete_entry(entry_id: int):
|
|
store = get_sqlite_session_store()
|
|
deleted = await store.delete_notebook_entry(entry_id)
|
|
if not deleted:
|
|
raise HTTPException(status_code=404, detail="Entry not found")
|
|
return {"deleted": True, "id": entry_id}
|
|
|
|
|
|
# ── Entry ↔ Category linking ────────────────────────────────────
|
|
|
|
@router.post("/entries/{entry_id}/categories")
|
|
async def add_entry_to_category(entry_id: int, payload: CategoryAddRequest):
|
|
store = get_sqlite_session_store()
|
|
entry = await store.get_notebook_entry(entry_id)
|
|
if entry is None:
|
|
raise HTTPException(status_code=404, detail="Entry not found")
|
|
ok = await store.add_entry_to_category(entry_id, payload.category_id)
|
|
if not ok:
|
|
raise HTTPException(status_code=400, detail="Failed to add to category")
|
|
return {"added": True, "entry_id": entry_id, "category_id": payload.category_id}
|
|
|
|
|
|
@router.delete("/entries/{entry_id}/categories/{category_id}")
|
|
async def remove_entry_from_category(entry_id: int, category_id: int):
|
|
store = get_sqlite_session_store()
|
|
removed = await store.remove_entry_from_category(entry_id, category_id)
|
|
if not removed:
|
|
raise HTTPException(status_code=404, detail="Link not found")
|
|
return {"removed": True, "entry_id": entry_id, "category_id": category_id}
|
|
|
|
|
|
# ── Category CRUD ────────────────────────────────────────────────
|
|
|
|
@router.get("/categories", response_model=list[CategoryItem])
|
|
async def list_categories():
|
|
store = get_sqlite_session_store()
|
|
return await store.list_categories()
|
|
|
|
|
|
@router.post("/categories", response_model=CategoryItem, status_code=201)
|
|
async def create_category(payload: CategoryCreateRequest):
|
|
store = get_sqlite_session_store()
|
|
try:
|
|
return await store.create_category(payload.name)
|
|
except Exception:
|
|
raise HTTPException(status_code=409, detail="Category name already exists")
|
|
|
|
|
|
@router.patch("/categories/{category_id}")
|
|
async def rename_category(category_id: int, payload: CategoryRenameRequest):
|
|
store = get_sqlite_session_store()
|
|
updated = await store.rename_category(category_id, payload.name)
|
|
if not updated:
|
|
raise HTTPException(status_code=404, detail="Category not found")
|
|
return {"updated": True, "id": category_id, "name": payload.name}
|
|
|
|
|
|
@router.delete("/categories/{category_id}")
|
|
async def delete_category(category_id: int):
|
|
store = get_sqlite_session_store()
|
|
deleted = await store.delete_category(category_id)
|
|
if not deleted:
|
|
raise HTTPException(status_code=404, detail="Category not found")
|
|
return {"deleted": True, "id": category_id}
|