File size: 11,064 Bytes
3ec7bd3
6580e24
 
 
bd0105d
 
 
 
 
 
 
 
 
 
 
6580e24
 
 
 
 
bd0105d
6580e24
 
 
 
 
 
 
 
 
 
 
 
 
3ec7bd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6580e24
 
a119a22
6580e24
 
 
a119a22
 
 
 
 
 
6580e24
a119a22
 
 
 
6580e24
 
 
3ec7bd3
 
 
 
 
 
 
 
a119a22
 
 
3ec7bd3
a119a22
3ec7bd3
 
 
 
a119a22
 
 
 
 
 
 
6580e24
a119a22
6580e24
 
 
 
 
 
 
 
 
 
 
 
 
a119a22
6580e24
a119a22
 
6580e24
 
 
 
 
 
 
 
 
 
 
 
 
a119a22
6580e24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd0105d
6580e24
 
 
 
bd0105d
6580e24
 
 
 
 
 
3ec7bd3
6580e24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ec7bd3
 
 
 
 
 
 
 
 
 
6580e24
 
 
 
3ec7bd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd0105d
6580e24
 
 
 
a119a22
6580e24
 
 
bd0105d
6580e24
 
 
 
bd0105d
6580e24
 
 
 
 
 
 
 
 
 
 
bd0105d
6580e24
 
 
 
 
 
 
3ec7bd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd0105d
6580e24
 
a119a22
6580e24
 
 
 
 
 
 
 
bd0105d
6580e24
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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"})