Ragora-Server / app /api /chat.py
Peterase's picture
feat: folder management, document move/drag-drop, per-document chat scoping
c880083
"""Chat API endpoints."""
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.database import get_db
from app.auth import get_current_user
from app.models import User
from app.application.chat_service import ChatService
from app.dependencies import get_chat_service
from typing import Optional, List
import logging
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/chat", tags=["chat"])
class ChatRequest(BaseModel):
message: str
chat_id: Optional[str] = None
# Scope the search to specific documents or a folder
document_ids: Optional[List[str]] = None # Ask about specific files
folder_id: Optional[str] = None # Ask about all files in a folder
@router.post("/")
async def send_message(
request: ChatRequest,
chat_service: ChatService = Depends(get_chat_service),
current_user: User = Depends(get_current_user)
):
"""Send a chat message, optionally scoped to specific documents or a folder."""
try:
result = await chat_service.send_message(
message=request.message,
user=current_user,
chat_id=request.chat_id,
document_ids=request.document_ids,
folder_id=request.folder_id
)
return result
except ValueError as e:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
except Exception as e:
logger.error(f"Chat error: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to generate response: {str(e)}"
)
@router.get("/history")
async def get_chat_history(
chat_service: ChatService = Depends(get_chat_service),
current_user: User = Depends(get_current_user)
):
"""Get all chat sessions."""
return await chat_service.get_chat_history(current_user)
@router.get("/{chat_id}")
async def get_chat_messages(
chat_id: str,
chat_service: ChatService = Depends(get_chat_service),
current_user: User = Depends(get_current_user)
):
"""Get all messages in a chat."""
try:
return await chat_service.get_chat_messages(chat_id, current_user)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
@router.delete("/{chat_id}")
async def delete_chat(
chat_id: str,
chat_service: ChatService = Depends(get_chat_service),
current_user: User = Depends(get_current_user)
):
"""Delete a chat."""
try:
await chat_service.delete_chat(chat_id, current_user)
return {"message": "Chat deleted successfully"}
except ValueError as e:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))