Files
MobilityOps/backend/app/api/routers/knowledge.py
T
NuklearRabbit b511ba2dbc M5: implement RAGcore knowledge integration
KnowledgeProvider protocol with a deterministic TF-IDF-weighted extractive demo provider (never generative, always cites real excerpts) and a RAGcore HTTP adapter that degrades cleanly to unavailable. Knowledge nav + chat-style Q&A UI with source cards and honest grounded/insufficient/unavailable states. 57 backend tests passing, ruff clean. Fixed a real relevance bug (generic terms like "vehicle" crowding out distinctive matches) via IDF weighting, found by testing the actual S6 scenario. Verified end-to-end in the browser: grounded damage question cites both expected procedures; unrelated question honestly returns insufficient evidence with no fabrication.
2026-08-01 22:57:06 +02:00

52 lines
1.6 KiB
Python

from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.api.deps import get_current_user, get_db
from app.schemas import CurrentUser
from app.services.audit import record_audit_event
from app.services.knowledge import GroundedAnswer, KnowledgeHealth, get_knowledge_provider
router = APIRouter(prefix="/api/v1/knowledge", tags=["knowledge"])
class AskQuestionRequest(BaseModel):
question: str = Field(min_length=3, max_length=1000)
@router.post("/questions", response_model=GroundedAnswer)
def ask_question(
body: AskQuestionRequest,
db: Session = Depends(get_db),
user: CurrentUser = Depends(get_current_user),
) -> GroundedAnswer:
correlation_id = str(uuid.uuid4())
provider = get_knowledge_provider()
answer = provider.ask(body.question, correlation_id)
record_audit_event(
db,
actor_type="user",
actor_label=user.display_name,
action="knowledge_question_asked",
entity_type="knowledge",
correlation_id=uuid.UUID(correlation_id),
metadata={
"evidence_state": answer.evidence_state,
"provider": answer.provider,
"source_ids": [s.document_id for s in answer.sources],
"question_length": len(body.question),
},
)
db.commit()
return answer
@router.get("/status", response_model=KnowledgeHealth)
def knowledge_status(_user: CurrentUser = Depends(get_current_user)) -> KnowledgeHealth:
return get_knowledge_provider().health()