import asyncio import json from typing import Literal from fastapi import ( APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Query, Request, UploadFile, ) from fastapi.responses import StreamingResponse from loguru import logger from pydantic import BaseModel, Field from src.agent import RagAgent from src.auth import require_admin from src.config import settings from src.books import catalog from src.ingest import ingestor, slugify from src.retriever import indexed_model, model_matches router = APIRouter() class HistoryMessage(BaseModel): role: Literal["user", "assistant"] content: str class SitePage(BaseModel): title: str = "" url: str = "" text: str = Field(min_length=1) class ContentRequest(BaseModel): """Site content for an organisation bot, in place of a PDF.""" book_id: str = Field(min_length=1) pages: list[SitePage] = Field(min_length=1) # Off by default: the usual call is "this one page changed", and wiping the # whole corpus for that would drop every other page. Each source sent is # replaced either way, so a stale copy never survives an edit. replace_all: bool = False class ChatRequest(BaseModel): question: str = Field(min_length=1) book_id: str = Field(min_length=1) history: list[HistoryMessage] = Field(default_factory=list) def get_agent(request: Request, book_id: str) -> RagAgent: agents = getattr(request.app.state, "agents", None) if not agents: raise HTTPException(status_code=503, detail="No books are indexed yet.") agent = agents.get(book_id) if agent is None: raise HTTPException( status_code=404, detail=f"No assistant for '{book_id}'. Available: {', '.join(sorted(agents))}.", ) return agent def _prompt_changed(agent: RagAgent, book: dict) -> bool: """Whether anything baked into the system prompt differs from the record.""" return any( (agent.book.get(key) or "") != (book.get(key) or "") for key in ("kind", "title", "profile") ) async def reload_agents(request: Request) -> None: """Keep the per-book agents in step with what is actually indexed.""" agents = {} for book in await catalog.list_agents(): existing = request.app.state.agents.get(book["book_id"]) # Rebuilt rather than refreshed when the catalogue changed: kind, title # and the org profile are baked into the system prompt at construction, # so refreshing retrieval alone would keep serving the old prompt. if existing and not _prompt_changed(existing, book): await existing.knowledge_base.refresh() agents[book["book_id"]] = existing else: agents[book["book_id"]] = await RagAgent.load(book) request.app.state.agents = agents def require_matching_model() -> None: """Refuse writes that would mix vector spaces — same dimension, so the DB accepts it silently.""" if not model_matches(): raise HTTPException( status_code=409, detail=( f"Store was indexed with '{indexed_model()}' but EMBEDDING_MODEL is " f"'{settings.embedding_model}'. Adding vectors from a different model would " f"silently corrupt retrieval. POST /admin/reindex first." ), ) @router.get("/health") async def health(request: Request) -> dict: agents = getattr(request.app.state, "agents", {}) or {} return { "ready": bool(agents), "books": sorted(agents), "embedding_model": settings.embedding_model, "indexed_with": indexed_model(), "model_matches": model_matches(), } def sse(event: str, data: dict) -> str: return f"event: {event}\ndata: {json.dumps(data)}\n\n" @router.post("/chat") async def chat(request: Request, payload: ChatRequest) -> StreamingResponse: """Streams the answer as server-sent events: `token`, `tool`, `done`, `error`.""" agent = get_agent(request, payload.book_id) require_matching_model() async def events(): try: async for kind, value in agent.stream( payload.question, [m.model_dump() for m in payload.history] ): if await request.is_disconnected(): logger.info("Client disconnected; stopping stream.") return yield sse(kind, {"text": value} if kind == "token" else {"name": value}) yield sse("done", {}) except Exception: logger.exception("Agent stream failed.") yield sse("error", {"message": "Failed to process the request."}) return StreamingResponse( events(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) @router.get("/books", dependencies=[Depends(require_admin)]) async def list_books() -> list[dict]: return await catalog.list_books() @router.post("/books", status_code=202, dependencies=[Depends(require_admin)]) async def upload_book( request: Request, background: BackgroundTasks, file: UploadFile = File(...), book_id: str | None = Form(default=None), replace: bool = Form(default=False), title: str | None = Form(default=None), ) -> dict: if not (file.filename or "").lower().endswith(".pdf"): raise HTTPException(status_code=400, detail="Only PDF uploads are supported.") require_matching_model() busy = ingestor.active() if busy: raise HTTPException( status_code=409, detail=f"'{busy}' is still being indexed. Wait for it to finish before uploading another.", ) resolved = book_id or slugify(file.filename) if ingestor.exists(resolved) and not replace: raise HTTPException( status_code=409, detail=f"'{resolved}' already exists. Re-send with replace=true to overwrite it.", ) path = ingestor.save(file.filename, await file.read()) background.add_task( ingestor.run, path, resolved, replace, lambda: reload_agents(request), # Names the bot in its own system prompt. Without it the name is # whatever banner the PDF happens to print at the top of each page. title, ) return {"book_id": resolved, "state": "running", "status_url": f"/books/{resolved}/status"} @router.post("/content", status_code=202, dependencies=[Depends(require_admin)]) async def upload_content( request: Request, background: BackgroundTasks, payload: ContentRequest, ) -> dict: """ Indexes web pages for a bot -- how the organisation assistant is fed. Same store and same one-at-a-time rule as a PDF upload: embedding is CPU-bound, and two ingests at once make both slow rather than either fast. """ require_matching_model() busy = ingestor.active() if busy: raise HTTPException( status_code=409, detail=f"'{busy}' is still being indexed. Wait for it to finish.", ) pages = [p.model_dump() for p in payload.pages] background.add_task( ingestor.run_pages, pages, payload.book_id, payload.replace_all, lambda: reload_agents(request), ) return { "book_id": payload.book_id, "pages": len(pages), "state": "running", "status_url": f"/books/{payload.book_id}/status", } @router.get("/content/{book_id}/sources", dependencies=[Depends(require_admin)]) async def content_sources(book_id: str) -> dict: """Chunk counts per source document, for the dashboard's content list.""" counts = await asyncio.to_thread(catalog.source_counts, book_id) return {"book_id": book_id, "sources": counts} @router.delete("/content/{book_id}", dependencies=[Depends(require_admin)]) async def delete_content( request: Request, book_id: str, source: str = Query(min_length=1), ) -> dict: """Removes one source document's chunks. The site owns the source text.""" removed = await asyncio.to_thread(catalog.delete_source, book_id, source) await reload_agents(request) return {"book_id": book_id, "source": source, "deleted": removed} @router.delete("/books/{book_id}", dependencies=[Depends(require_admin)]) async def delete_book(request: Request, book_id: str) -> dict: removed = await catalog.delete_book(book_id) if removed == 0: raise HTTPException(status_code=404, detail=f"No chunks found for '{book_id}'.") await reload_agents(request) return {"book_id": book_id, "deleted": removed} @router.get("/books/{book_id}/status", dependencies=[Depends(require_admin)]) async def ingestion_status(book_id: str) -> dict: return ingestor.status.get(book_id, {"state": "unknown"}) @router.get("/books/{book_id}/chunks", dependencies=[Depends(require_admin)]) async def list_chunks( book_id: str, offset: int = Query(default=0, ge=0), limit: int = Query(default=20, ge=1, le=100), ) -> dict: result = await catalog.list_chunks(book_id, offset, limit) if result["total"] == 0: raise HTTPException(status_code=404, detail=f"No chunks found for '{book_id}'.") return result @router.get("/chunks/{chunk_id}", dependencies=[Depends(require_admin)]) async def get_chunk(chunk_id: str) -> dict: chunk = await catalog.get_chunk(chunk_id) if chunk is None: raise HTTPException(status_code=404, detail="Chunk not found.") return chunk @router.post("/admin/reload", dependencies=[Depends(require_admin)]) async def reload(request: Request) -> dict: """ Rebuilds the agents from the catalogue. Needed because a bot's title, kind and org profile are baked into its system prompt when the agent is constructed. Editing a profile in the dashboard writes to `book_bots` and nothing else, so without this the bot keeps answering from the prompt it was born with until the next ingest or a restart. The dashboard calls this after any edit that touches those fields. """ await reload_agents(request) agents = getattr(request.app.state, "agents", {}) or {} return { "reloaded": sorted(agents), "kinds": {book_id: agent.kind for book_id, agent in agents.items()}, } @router.post("/admin/reindex", status_code=202, dependencies=[Depends(require_admin)]) async def reindex(request: Request, background: BackgroundTasks) -> dict: """Re-embed every stored chunk with the configured model. Trigger from the dashboard.""" background.add_task(ingestor.reindex, lambda: reload_agents(request)) return { "state": "running", "model": settings.embedding_model, "was": indexed_model(), "status_url": "/admin/reindex/status", } @router.get("/admin/reindex/status", dependencies=[Depends(require_admin)]) async def reindex_status() -> dict: return ingestor.status.get("__reindex__", {"state": "unknown"})