Spaces:
Runtime error
Runtime error
| from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks, File, UploadFile | |
| from typing import Optional, Dict, Any | |
| import uuid | |
| from datetime import datetime | |
| import os | |
| from pathlib import Path | |
| from models.message import Message, MessageCreate, MessageRead | |
| from models.conversation import Conversation | |
| from services.translation_service import translation_service, Language | |
| from services.voice_processing_service import voice_processing_service | |
| from services.chat_service import chat_service | |
| from tools.mcp_server import execute_mcp_tool | |
| from middleware.auth import get_optional_user, get_current_user | |
| from models.user import User | |
| router = APIRouter(prefix="/api", tags=["chat"]) | |
| # Audio endpoint for serving synthesized voice files | |
| async def get_audio_file(filename: str): | |
| """Serve audio files generated by voice synthesis""" | |
| import tempfile | |
| temp_dir = Path(tempfile.gettempdir()) | |
| file_path = temp_dir / filename | |
| if not file_path.exists(): | |
| raise HTTPException(status_code=404, detail="Audio file not found") | |
| from fastapi.responses import FileResponse | |
| return FileResponse( | |
| path=file_path, | |
| media_type="audio/mpeg", | |
| filename=filename | |
| ) | |
| async def process_chat_message( | |
| message: str, | |
| conversation_id: Optional[str] = None, | |
| message_type: str = "text", | |
| language: str = "en", | |
| user_preferences: Optional[Dict[str, Any]] = None, | |
| current_user: User = Depends(get_current_user) | |
| ): | |
| """ | |
| Process chat message and return AI response | |
| Handles both text and voice input, processes through the AI system, and returns appropriate response | |
| """ | |
| try: | |
| # Validate inputs | |
| if not message.strip(): | |
| raise HTTPException(status_code=400, detail="Message cannot be empty") | |
| # Process the message using the chat service | |
| response_obj = await chat_service.process_user_message( | |
| message=message, | |
| conversation_id=conversation_id, | |
| message_type=message_type, | |
| language=language, | |
| user_preferences=user_preferences, | |
| user_id=current_user.id if current_user else None | |
| ) | |
| return response_obj | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error processing chat message: {str(e)}") | |
| # Additional endpoints for conversation management | |
| async def list_conversations(): | |
| """List user's conversations""" | |
| # In a real implementation, this would fetch from database | |
| return {"conversations": []} | |
| async def get_conversation_history(conversation_id: str): | |
| """Get conversation history""" | |
| # In a real implementation, this would fetch from database | |
| return { | |
| "conversation": {"id": conversation_id, "title": "Sample Conversation"}, | |
| "messages": [] | |
| } |