File size: 2,944 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
"""Conversation-state service — create conversations, store messages, fetch history."""
from datetime import datetime

from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select

from ..core.logging import get_logger
from ..models.conversation import Conversation, Message

logger = get_logger(__name__)


async def create_conversation(session: AsyncSession, user_id: str) -> Conversation:
    """Insert a new Conversation row and return it."""
    conv = Conversation(user_id=user_id)
    session.add(conv)
    await session.commit()
    await session.refresh(conv)
    logger.info("Conversation created: id=%d user_id=%s", conv.id, user_id)
    return conv


async def get_conversation(
    session: AsyncSession, conversation_id: int, user_id: str
) -> Conversation | None:
    """Fetch a conversation by ID, scoped to the requesting user."""
    logger.debug("Fetching conversation id=%d for user_id=%s", conversation_id, user_id)
    result = await session.execute(
        select(Conversation).where(
            Conversation.id == conversation_id,
            Conversation.user_id == user_id,
        )
    )
    return result.scalar_one_or_none()


async def store_message(
    session: AsyncSession,
    conversation_id: int,
    user_id: str,
    role: str,
    content: str,
) -> Message:
    """Persist a message and bump the parent conversation's updated_at."""
    msg = Message(
        conversation_id=conversation_id,
        user_id=user_id,
        role=role,
        content=content,
    )
    session.add(msg)

    # Bump conversation timestamp
    conv_result = await session.execute(
        select(Conversation).where(Conversation.id == conversation_id)
    )
    conv = conv_result.scalar_one_or_none()
    if conv:
        conv.updated_at = datetime.utcnow()
        session.add(conv)

    await session.commit()
    await session.refresh(msg)
    logger.info("Message stored: role=%s conversation_id=%d", role, conversation_id)
    return msg


async def list_conversations(session: AsyncSession, user_id: str, limit: int = 30) -> list[Conversation]:
    """Return most-recently-updated conversations for a user."""
    result = await session.execute(
        select(Conversation)
        .where(Conversation.user_id == user_id)
        .order_by(Conversation.updated_at.desc())
        .limit(limit)
    )
    return list(result.scalars().all())


async def get_history(session: AsyncSession, conversation_id: int) -> list[Message]:
    """Return all messages in a conversation, oldest first."""
    logger.debug("Fetching history for conversation_id=%d", conversation_id)
    result = await session.execute(
        select(Message)
        .where(Message.conversation_id == conversation_id)
        .order_by(Message.created_at.asc())
    )
    msgs = list(result.scalars().all())
    logger.debug("Fetched %d history messages for conversation_id=%d", len(msgs), conversation_id)
    return msgs