File size: 2,159 Bytes
481dfe6 | 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 | import logging
from fastapi import APIRouter, HTTPException, Header
from app.retrieval.ingestion import ingest_file, ingest_directory, reset_collection
from app.schemas.ingest import IngestFileRequest, IngestDirectoryRequest, IngestResponse
from app.config import settings
router = APIRouter(prefix="/api/ingest", tags=["ingest"])
logger = logging.getLogger(__name__)
def _verify_ingest_key(x_api_key: str | None) -> None:
"""Protect ingest endpoints with an API key if configured."""
if settings.ingest_api_key and x_api_key != settings.ingest_api_key:
raise HTTPException(status_code=401, detail="Invalid or missing ingest API key.")
@router.post("/file", response_model=IngestResponse)
async def ingest_single_file(
request: IngestFileRequest,
x_api_key: str | None = Header(default=None),
):
_verify_ingest_key(x_api_key)
try:
chunks = ingest_file(request.file_path)
return IngestResponse(success=True, total_documents=1, total_chunks=chunks)
except Exception as e:
logger.error("Ingest file error: %s", e)
raise HTTPException(status_code=500, detail=str(e))
@router.post("/directory", response_model=IngestResponse)
async def ingest_dir(
request: IngestDirectoryRequest,
x_api_key: str | None = Header(default=None),
):
_verify_ingest_key(x_api_key)
try:
result = ingest_directory(request.directory_path, recursive=request.recursive)
return IngestResponse(success=True, **result)
except Exception as e:
logger.error("Ingest directory error: %s", e)
raise HTTPException(status_code=500, detail=str(e))
@router.post("/reset", response_model=IngestResponse)
async def reset(x_api_key: str | None = Header(default=None)):
_verify_ingest_key(x_api_key)
try:
reset_collection()
return IngestResponse(
success=True,
message=f"Collection '{settings.collection_name}' reset successfully.",
)
except Exception as e:
logger.error("Reset error: %s", e)
raise HTTPException(status_code=500, detail=str(e))
|