File size: 6,217 Bytes
b93a6a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""
Chat endpoint for AI-powered conversational task management.

This module provides the REST API endpoint for the AI chatbot,
implementing stateless conversation management with MCP tool execution.
"""

from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional
from sqlmodel import Session
import logging

from src.database import get_session
from src.middleware.jwt_auth import get_current_user
from src.services.conversation_service import conversation_service
from src.agents.orchestrator import orchestrator

logger = logging.getLogger(__name__)

router = APIRouter()


# Request/Response Models

class ChatRequest(BaseModel):
    """Request model for chat endpoint."""
    message: str = Field(
        ...,
        min_length=1,
        max_length=10000,
        description="User's message to the AI chatbot"
    )


class ChatResponse(BaseModel):
    """Response model for chat endpoint."""
    conversation_id: int = Field(description="ID of the conversation")
    message_id: int = Field(description="ID of the assistant's message")
    response: str = Field(description="AI assistant's response")
    timestamp: str = Field(description="ISO 8601 timestamp of the response")


class ConversationHistoryResponse(BaseModel):
    """Response model for conversation history."""
    conversation_id: int
    messages: List[Dict[str, Any]]
    total_count: int
    has_more: bool = False


# Endpoints

@router.post("/chat", response_model=ChatResponse)
async def chat(
    request: ChatRequest,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_session)
):
    """
    Send a message to the AI chatbot.

    The chatbot will:
    - Understand user intent (add task, list tasks, complete task, etc.)
    - Execute appropriate MCP tool operations
    - Return conversational response with operation results

    All conversation history is automatically persisted and loaded for context.

    Requires authentication.
    """
    try:
        user_id = current_user["user_id"]
        logger.info(f"Chat request from user {user_id}: {request.message[:50]}...")

        # 1. Get or create conversation
        conversation = await conversation_service.get_or_create_conversation(db, user_id)

        # 2. Store user message
        user_message = await conversation_service.store_message(
            db=db,
            conversation_id=conversation.id,
            user_id=user_id,
            role="user",
            content=request.message
        )

        # 3. Load conversation history
        history = await conversation_service.load_conversation_history(
            db=db,
            conversation_id=conversation.id,
            limit=50
        )

        # 4. Build message array for AI
        messages = conversation_service.build_message_array(history)

        # 5. Run agent orchestrator
        result = await orchestrator.run(messages=messages, user_id=user_id, db=db)

        # 6. Store assistant response
        assistant_message = await conversation_service.store_message(
            db=db,
            conversation_id=conversation.id,
            user_id=user_id,
            role="assistant",
            content=result["response"]
        )

        # 7. Return structured response
        return ChatResponse(
            conversation_id=conversation.id,
            message_id=assistant_message.id,
            response=result["response"],
            timestamp=assistant_message.created_at.isoformat()
        )

    except ValueError as e:
        logger.error(f"Validation error in chat endpoint: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Error in chat endpoint: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail="An error occurred while processing your message. Please try again."
        )


@router.get("/chat/history", response_model=ConversationHistoryResponse)
async def get_chat_history(
    limit: int = 50,
    offset: int = 0,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_session)
):
    """
    Retrieve conversation history for the authenticated user.

    Returns messages in chronological order.

    Requires authentication.
    """
    try:
        user_id = current_user["user_id"]

        # Get user's conversation
        conversation = await conversation_service.get_or_create_conversation(db, user_id)

        # Load messages
        messages = await conversation_service.load_conversation_history(
            db=db,
            conversation_id=conversation.id,
            limit=limit
        )

        # Format messages
        formatted_messages = [
            {
                "id": msg.id,
                "role": msg.role,
                "content": msg.content,
                "timestamp": msg.created_at.isoformat()
            }
            for msg in messages
        ]

        return ConversationHistoryResponse(
            conversation_id=conversation.id,
            messages=formatted_messages,
            total_count=len(formatted_messages),
            has_more=len(formatted_messages) >= limit
        )

    except Exception as e:
        logger.error(f"Error retrieving chat history: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail="An error occurred while retrieving chat history."
        )


@router.get("/chat/health")
async def chat_health_check():
    """
    Check if chat service is properly configured.

    Does not require authentication.
    """
    try:
        import os
        cohere_key = os.getenv("COHERE_API_KEY")

        if not cohere_key:
            return {
                "status": "error",
                "message": "COHERE_API_KEY not configured"
            }

        return {
            "status": "healthy",
            "message": "Chat service is configured and ready",
            "provider": "Cohere",
            "architecture": "Stateless with MCP tools"
        }

    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }