Spaces:
Sleeping
Sleeping
File size: 2,799 Bytes
f02c5b9 c880083 f02c5b9 c880083 f02c5b9 c880083 f02c5b9 c880083 f02c5b9 c880083 f02c5b9 c880083 f02c5b9 c880083 | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | """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))
|