|
| 1 | +from typing import List, Optional |
| 2 | +from datetime import datetime |
| 3 | +from app.database import client |
| 4 | +from .schemas import ChatLog, ChatLogResponse, ChatThreadInfo |
| 5 | + |
| 6 | +# Initialize MongoDB collection |
| 7 | +collection = client["chatbot"]["state"] |
| 8 | + |
| 9 | + |
| 10 | +async def list_chatlogs( |
| 11 | + page: int = 1, |
| 12 | + limit: int = 10, |
| 13 | + start_date: Optional[datetime] = None, |
| 14 | + end_date: Optional[datetime] = None, |
| 15 | +) -> ChatLogResponse: |
| 16 | + skip = (page - 1) * limit |
| 17 | + |
| 18 | + # Build query filter |
| 19 | + query = {} |
| 20 | + if start_date or end_date: |
| 21 | + query["date"] = {} |
| 22 | + if start_date: |
| 23 | + query["date"]["$gte"] = start_date |
| 24 | + if end_date: |
| 25 | + query["date"]["$lte"] = end_date |
| 26 | + |
| 27 | + # Get total count of unique threads for pagination |
| 28 | + pipeline = [ |
| 29 | + {"$match": query}, |
| 30 | + {"$group": {"_id": "$thread_id"}}, |
| 31 | + {"$count": "total"}, |
| 32 | + ] |
| 33 | + result = await collection.aggregate(pipeline).to_list(1) |
| 34 | + total = result[0]["total"] if result else 0 |
| 35 | + |
| 36 | + # Get paginated results grouped by thread_id with latest date |
| 37 | + pipeline = [ |
| 38 | + {"$match": query}, |
| 39 | + {"$sort": {"date": -1}}, |
| 40 | + { |
| 41 | + "$group": { |
| 42 | + "_id": "$thread_id", |
| 43 | + "thread_id": {"$first": "$thread_id"}, |
| 44 | + "date": {"$first": "$date"}, |
| 45 | + } |
| 46 | + }, |
| 47 | + {"$sort": {"date": -1}}, |
| 48 | + {"$skip": skip}, |
| 49 | + {"$limit": limit}, |
| 50 | + ] |
| 51 | + |
| 52 | + conversations = [] |
| 53 | + async for doc in collection.aggregate(pipeline): |
| 54 | + conversations.append( |
| 55 | + ChatThreadInfo(thread_id=doc["thread_id"], date=doc["date"]) |
| 56 | + ) |
| 57 | + |
| 58 | + return ChatLogResponse( |
| 59 | + total=total, page=page, limit=limit, conversations=conversations |
| 60 | + ) |
| 61 | + |
| 62 | + |
| 63 | +async def get_chat_thread(thread_id: str) -> List[ChatLog]: |
| 64 | + """Get complete conversation history for a specific thread""" |
| 65 | + |
| 66 | + cursor = collection.find({"thread_id": thread_id}).sort("date", 1) |
| 67 | + messages = await cursor.to_list(length=None) |
| 68 | + |
| 69 | + if not messages: |
| 70 | + return None |
| 71 | + |
| 72 | + chat_logs = [] |
| 73 | + for msg in messages: |
| 74 | + chat_logs.append( |
| 75 | + ChatLog( |
| 76 | + user_message=msg["user_message"], |
| 77 | + bot_message=msg["bot_message"], |
| 78 | + date=msg["date"], |
| 79 | + context=msg.get("context", {}), |
| 80 | + ) |
| 81 | + ) |
| 82 | + |
| 83 | + return chat_logs |
0 commit comments