|
| 1 | +"""API routes for chat-related endpoints.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from uuid import UUID |
| 5 | + |
| 6 | +from fastapi import APIRouter, Depends, HTTPException |
| 7 | +from sqlalchemy.orm import Session |
| 8 | + |
| 9 | +from app.core.database_connection import get_db |
| 10 | +from app.schemas.chat import ChatHistoryResponse, ChatMessageResponse |
| 11 | +from app.services.chat import get_chat_history |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +router = APIRouter(prefix="/chat", tags=["chat"]) |
| 16 | + |
| 17 | + |
| 18 | +@router.get("/history/{chat_session_id}", response_model=ChatHistoryResponse) |
| 19 | +async def get_chat_history_endpoint( |
| 20 | + chat_session_id: UUID, |
| 21 | + db: Session = Depends(get_db), |
| 22 | +) -> ChatHistoryResponse: |
| 23 | + """ |
| 24 | + Retrieve the last 10 messages from a chat session. |
| 25 | +
|
| 26 | + This endpoint returns the most recent 10 messages from the specified chat session, |
| 27 | + ordered by creation time (most recent first). |
| 28 | +
|
| 29 | + Args: |
| 30 | + chat_session_id: UUID of the chat session |
| 31 | + db: Database session dependency |
| 32 | +
|
| 33 | + Returns: |
| 34 | + ChatHistoryResponse containing the session_id, list of messages, and count |
| 35 | +
|
| 36 | + Raises: |
| 37 | + HTTPException: 404 if chat session doesn't exist |
| 38 | + HTTPException: 400 if invalid UUID format |
| 39 | + HTTPException: 500 for database errors |
| 40 | + """ |
| 41 | + logger.info(f"Received chat history request for session: {chat_session_id}") |
| 42 | + |
| 43 | + try: |
| 44 | + # Get chat history from service |
| 45 | + messages = get_chat_history(db, chat_session_id) |
| 46 | + |
| 47 | + # Convert SQLAlchemy models to Pydantic models |
| 48 | + message_responses = [ |
| 49 | + ChatMessageResponse( |
| 50 | + id=msg.id, |
| 51 | + session_id=msg.session_id, |
| 52 | + sender=msg.sender, |
| 53 | + message=msg.message, |
| 54 | + created_at=msg.created_at, |
| 55 | + ) |
| 56 | + for msg in messages |
| 57 | + ] |
| 58 | + |
| 59 | + return ChatHistoryResponse( |
| 60 | + session_id=chat_session_id, |
| 61 | + messages=message_responses, |
| 62 | + count=len(message_responses), |
| 63 | + ) |
| 64 | + |
| 65 | + except ValueError as e: |
| 66 | + logger.warning(f"Chat session not found: {e}") |
| 67 | + raise HTTPException(status_code=404, detail=str(e)) |
| 68 | + except Exception as e: |
| 69 | + logger.error(f"Error retrieving chat history: {e}") |
| 70 | + raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}") |
0 commit comments