File size: 1,589 Bytes
582520a | 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 | """Knowledge base ingestion API."""
from pathlib import Path
from fastapi import APIRouter, Depends, File, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.db import get_db
from app.models import KnowledgeDoc
from app.schemas import KnowledgeIngestResponse
from app.services.rag import get_knowledge_store, ingest_path
router = APIRouter(prefix="/api/knowledge", tags=["knowledge"])
@router.get("/status")
async def knowledge_status() -> dict:
"""Return current knowledge chunk count."""
store = get_knowledge_store()
return {"chunk_count": store.chunk_count}
@router.post(
"/ingest",
response_model=KnowledgeIngestResponse,
)
async def ingest_upload(
file: UploadFile = File(...),
db: AsyncSession = Depends(get_db),
) -> KnowledgeIngestResponse:
"""Upload and ingest a knowledge document."""
settings = get_settings()
target_dir = Path(settings.knowledge_path)
target_dir.mkdir(parents=True, exist_ok=True)
filename = Path(file.filename or "upload.txt").name
dest = target_dir / filename
content = await file.read()
dest.write_bytes(content)
source = dest.suffix.lower().lstrip(".") or "text"
count = await ingest_path(dest, source)
db.add(
KnowledgeDoc(
filename=filename,
source_type=source,
chunk_count=count,
)
)
await db.commit()
return KnowledgeIngestResponse(
filename=filename,
chunk_count=count,
message=f"Ingested {count} chunks from {filename}",
)
|