Spaces:
Runtime error
Runtime error
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlalchemy.orm import Session | |
| from typing import Optional | |
| from app.database.connection import get_db | |
| from app.database.models import User | |
| from app.schemas.chat import ChatRequest, ChatResponse, MessageResponse | |
| from app.services.chat_service import ChatService | |
| from app.middleware.auth import get_current_user_optional | |
| router = APIRouter(prefix="/api/chat", tags=["chat"]) | |
| async def send_message( | |
| request: ChatRequest, | |
| db: Session = Depends(get_db), | |
| current_user: Optional[User] = Depends(get_current_user_optional) | |
| ): | |
| """ | |
| Send a chat message and get response. | |
| Args: | |
| request: Chat request with message and optional session_id | |
| db: Database session | |
| current_user: Optional current user (None for guests) | |
| Returns: | |
| Chat response with message and metadata | |
| Raises: | |
| HTTPException: If processing fails | |
| """ | |
| user_id = current_user.id if current_user else None | |
| try: | |
| result = ChatService.process_message( | |
| db=db, | |
| message=request.message, | |
| session_id=request.session_id, | |
| user_id=user_id, | |
| policy_ids=request.policy_ids | |
| ) | |
| # Parse metadata | |
| import json | |
| meta = json.loads(result["message"].meta) if result["message"].meta else {} | |
| return ChatResponse( | |
| message=MessageResponse( | |
| id=result["message"].id, | |
| session_id=result["message"].session_id, | |
| role=result["message"].role, | |
| content=result["message"].content, | |
| meta=meta, | |
| created_at=result["message"].created_at | |
| ), | |
| session_id=result["session_id"], | |
| agent=result.get("agent") | |
| ) | |
| except ValueError as e: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail=str(e) | |
| ) | |
| except Exception as e: | |
| print(f"Error processing message: {e}") | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="Error processing message" | |
| ) | |
| async def get_chat_history( | |
| session_id: str, | |
| db: Session = Depends(get_db), | |
| current_user: Optional[User] = Depends(get_current_user_optional) | |
| ): | |
| """ | |
| Get chat history for a session. | |
| Args: | |
| session_id: Session ID | |
| db: Database session | |
| current_user: Optional current user | |
| Returns: | |
| List of messages | |
| """ | |
| try: | |
| messages = ChatService.get_chat_history(db, session_id) | |
| return {"messages": messages} | |
| except Exception as e: | |
| print(f"Error getting chat history: {e}") | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="Error retrieving chat history" | |
| ) | |