Coverage for src / lilbee / server / routes / documents.py: 100%

31 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-04-29 19:16 +0000

1"""Document management route handlers: add, list, remove, sync.""" 

2 

3from __future__ import annotations 

4 

5from litestar import get, post 

6from litestar.exceptions import ValidationException 

7from litestar.params import Parameter 

8from litestar.response import Stream 

9from pydantic import BaseModel, Field 

10 

11from lilbee.server import handlers 

12from lilbee.server.auth import read_only 

13from lilbee.server.models import ( 

14 AddRequest, 

15 DocumentListResponse, 

16 DocumentRemoveResponse, 

17 SyncRequest, 

18) 

19 

20 

21class RemoveRequest(BaseModel): 

22 """Request body for /api/documents/remove.""" 

23 

24 names: list[str] = Field(max_length=100) 

25 delete_files: bool = False 

26 

27 

28@post("/api/sync") 

29async def sync_route(data: SyncRequest | None = None) -> Stream: 

30 """Re-index changed documents with streaming SSE progress events. 

31 

32 Pass ``{"force_rebuild": true}`` to wipe the store and re-ingest every file 

33 under the current ``cfg.embedding_model``. This is the recovery path after 

34 a ``PUT /api/models/embedding`` that returned ``reindex_required=true``. 

35 """ 

36 enable_ocr = data.enable_ocr if data else None 

37 force_rebuild = data.force_rebuild if data else False 

38 return Stream( 

39 handlers.sync_stream(enable_ocr=enable_ocr, force_rebuild=force_rebuild), 

40 media_type="text/event-stream", 

41 ) 

42 

43 

44@post("/api/add") 

45async def add_route(data: AddRequest) -> Stream: 

46 """Add files to the knowledge base with streaming SSE progress.""" 

47 try: 

48 handlers.validate_add_paths(data.model_dump()) 

49 except ValueError as exc: 

50 raise ValidationException(str(exc)) from exc 

51 return Stream( 

52 handlers.add_files_stream(data.model_dump()), 

53 media_type="text/event-stream", 

54 status_code=201, 

55 ) 

56 

57 

58@get("/api/documents") 

59@read_only 

60async def documents_list_route( 

61 search: str = Parameter(query="search", default=""), 

62 limit: int = Parameter(query="limit", default=50, le=1000), 

63 offset: int = Parameter(query="offset", default=0, ge=0), 

64) -> DocumentListResponse: 

65 """List indexed documents with metadata, paginated and searchable.""" 

66 return await handlers.list_documents(search=search, limit=limit, offset=offset) 

67 

68 

69@post("/api/documents/remove") 

70async def documents_remove_route(data: RemoveRequest) -> DocumentRemoveResponse: 

71 """Remove documents from the knowledge base by source name.""" 

72 return await handlers.delete_documents(data.names, delete_files=data.delete_files)