File size: 6,792 Bytes
507973e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""POST /chat — stateless AI-chatbot endpoint.

Task Reference: T011, T012, T013 - Extended for multi-provider support
"""
from typing import Annotated

from agents import Runner
from fastapi import APIRouter, Depends, Header, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession

from sqlmodel import select

from ..core.database import get_session
from ..core.better_auth import get_current_user_from_session
from ..core.config import settings
from ..core.logging import get_logger
from ..models.conversation import Message
from ..core.providers import ProviderName
from ..services import chat_service
from ..services.agent_service import todo_agent
from ..services.router import ProviderRouter

logger = get_logger(__name__)

# Initialize router with policy from config
provider_router = ProviderRouter(
    policy=settings.routing_policy,  # type: ignore
    default_provider=settings.default_provider,  # type: ignore
)

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


# ---------------------------------------------------------------------------
# Request / Response DTOs
# ---------------------------------------------------------------------------


class ChatRequest(BaseModel):
    conversation_id: int | None = None
    message: str = Field(..., min_length=1, max_length=4000)
    provider: ProviderName | None = None  # T011: optional provider selection


class ChatResponse(BaseModel):
    conversation_id: int
    response: str
    tool_calls: list[str]
    provider: str  # T012: which provider handled request


# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------


@router.get("/conversations")
async def list_conversations(
    authorization: Annotated[str | None, Header()] = None,
    cookie: Annotated[str | None, Header()] = None,
    session: AsyncSession = Depends(get_session),
):
    """List all conversations for the current user, newest first, with first-message preview."""
    user = await get_current_user_from_session(authorization, cookie, session)
    convs = await chat_service.list_conversations(session, user.id)

    # Fetch first user message per conversation in one query
    conv_ids = [c.id for c in convs]
    first_msg_map: dict[int, str] = {}
    if conv_ids:
        result = await session.execute(
            select(Message)
            .where(Message.conversation_id.in_(conv_ids), Message.role == "user")
            .order_by(Message.conversation_id, Message.created_at.asc())
        )
        for m in result.scalars().all():
            if m.conversation_id not in first_msg_map:
                first_msg_map[m.conversation_id] = m.content

    return [
        {
            "id": c.id,
            "created_at": c.created_at.isoformat(),
            "updated_at": c.updated_at.isoformat(),
            "title": (first_msg_map.get(c.id) or "")[:60] or f"Chat #{c.id}",
        }
        for c in convs
    ]


@router.get("/conversations/{conversation_id}")
async def get_conversation_messages(
    conversation_id: int,
    authorization: Annotated[str | None, Header()] = None,
    cookie: Annotated[str | None, Header()] = None,
    session: AsyncSession = Depends(get_session),
):
    """Fetch all messages for a conversation."""
    user = await get_current_user_from_session(authorization, cookie, session)
    conv = await chat_service.get_conversation(session, conversation_id, user.id)
    if conv is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found")
    messages = await chat_service.get_history(session, conversation_id)
    return {
        "id": conv.id,
        "created_at": conv.created_at.isoformat(),
        "messages": [
            {"id": m.id, "role": m.role, "content": m.content, "created_at": m.created_at.isoformat()}
            for m in messages
        ],
    }


@router.post("", response_model=ChatResponse)
async def send_chat_message(
    data: ChatRequest,
    authorization: Annotated[str | None, Header()] = None,
    cookie: Annotated[str | None, Header()] = None,
    session: AsyncSession = Depends(get_session),
):
    """Stateless 9-step request cycle: auth → conversation → history → agent → persist → return."""
    # 1. Authenticate
    user = await get_current_user_from_session(authorization, cookie, session)
    logger.info("Chat request: user_id=%s conversation_id=%s", user.id, data.conversation_id)

    # 2. Resolve conversation
    if data.conversation_id is None:
        conv = await chat_service.create_conversation(session, user.id)
        cid = conv.id
    else:
        conv = await chat_service.get_conversation(session, data.conversation_id, user.id)
        if conv is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found")
        cid = conv.id

    # 3. Fetch history (for logging / future context injection)
    history = await chat_service.get_history(session, cid)

    # 4. Persist user message
    await chat_service.store_message(session, cid, user.id, "user", data.message)

    # 5. Build agent input with security context
    input_str = f"[Context] Your user_id is {user.id}.\n\n{data.message}"

    # 6. Log pre-run
    logger.debug("Running agent with %d history messages", len(history))

    # 7-8. Run agent with provider router (T013)
    try:
        result, provider_used = await provider_router.run_with_failover(
            agent=todo_agent,
            user_input=input_str,
            preferred_provider=data.provider,
        )
        # _tool_use_tracker_snapshot: dict[agent_name -> [tool_name, ...]]
        tool_calls_used: list[str] = [
            name
            for names in result._tool_use_tracker_snapshot.values()  # noqa: SLF001
            for name in names
        ]
    except HTTPException:
        # Re-raise HTTPException from router (503 when all providers fail)
        raise
    except Exception as exc:
        logger.error("Agent execution failed: %s", exc, exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Agent error: {exc}",
        ) from exc

    # 9. Persist assistant response
    response_text = str(result.final_output)
    await chat_service.store_message(session, cid, user.id, "assistant", response_text)

    # 10. Log post-run
    logger.info("Agent response: %s... provider=%s tool_calls=%s", response_text[:80], provider_used, tool_calls_used)

    # 11. Return (T013)
    return ChatResponse(
        conversation_id=cid,
        response=response_text,
        tool_calls=tool_calls_used,
        provider=provider_used,
    )