File size: 1,367 Bytes
582520a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Chat API routes."""

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.db import get_db
from app.schemas import (
    ChatMessageRequest,
    ChatMessageResponse,
    ChatStartResponse,
)
from app.services.chat import handle_user_message, start_conversation
from app.services.language import normalize_ui_language

router = APIRouter(prefix="/api/chat", tags=["chat"])


@router.post("/start", response_model=ChatStartResponse)
async def chat_start(
    ui_language: str = "en",
    db: AsyncSession = Depends(get_db),
) -> ChatStartResponse:
    """Start a new web conversation."""
    lang = normalize_ui_language(ui_language)
    conv, greeting = await start_conversation(
        db, channel="web", ui_language=lang
    )
    return ChatStartResponse(
        conversation_id=conv.id,
        greeting=greeting,
        language=lang,
    )


@router.post("/message", response_model=ChatMessageResponse)
async def chat_message(
    body: ChatMessageRequest,
    db: AsyncSession = Depends(get_db),
) -> ChatMessageResponse:
    """Send a user message and receive the bot reply."""
    data = await handle_user_message(
        db,
        conversation_id=body.conversation_id,
        message=body.message,
        ui_language=normalize_ui_language(body.ui_language),
    )
    return ChatMessageResponse(**data)