File size: 3,051 Bytes
dd1b74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
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
@router.get("/audio/{filename}")
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
    )


@router.post("/chat", response_model=Dict[str, Any])
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
@router.get("/conversations", response_model=Dict[str, Any])
async def list_conversations():
    """List user's conversations"""
    # In a real implementation, this would fetch from database
    return {"conversations": []}


@router.get("/conversations/{conversation_id}", response_model=Dict[str, Any])
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": []
    }