feat:新增对话历史列表
This commit is contained in:
@@ -8,7 +8,8 @@ from pymongo import ASCENDING, DESCENDING
|
||||
from pymongo.asynchronous.database import AsyncDatabase
|
||||
|
||||
from app.config import settings
|
||||
from app.schemas.conversation import Turn
|
||||
from app.schemas.conversation import ConversationSummary, Turn
|
||||
from app.services.conversation import make_title
|
||||
|
||||
# 单次清理的空会话上限,避免积压时一次请求扫描过多
|
||||
PURGE_BATCH = 200
|
||||
@@ -119,3 +120,42 @@ class MongoConversationStore:
|
||||
{"$set": data, "$setOnInsert": {"created_at": created_at}},
|
||||
upsert=True,
|
||||
)
|
||||
|
||||
async def list_by_user(
|
||||
self, user_id: int, limit: int, offset: int
|
||||
) -> list[ConversationSummary]:
|
||||
# $unwind 会丢弃没有任何轮次的空会话
|
||||
pipeline = [
|
||||
{"$match": {"user_id": user_id}},
|
||||
{
|
||||
"$lookup": {
|
||||
"from": self._turns.name,
|
||||
"localField": "_id",
|
||||
"foreignField": "conversation_id",
|
||||
"pipeline": [
|
||||
{"$sort": {"created_at": 1, "_id": 1}},
|
||||
{
|
||||
"$group": {
|
||||
"_id": None,
|
||||
"first_prompt": {"$first": "$prompt"},
|
||||
"updated_at": {"$last": "$created_at"},
|
||||
}
|
||||
},
|
||||
],
|
||||
"as": "stats",
|
||||
}
|
||||
},
|
||||
{"$unwind": "$stats"},
|
||||
{"$sort": {"stats.updated_at": -1, "_id": -1}},
|
||||
{"$skip": offset},
|
||||
{"$limit": limit},
|
||||
]
|
||||
cursor = await self._conversations.aggregate(pipeline)
|
||||
return [
|
||||
ConversationSummary(
|
||||
conversation_id=item["_id"],
|
||||
title=make_title(item["stats"]["first_prompt"]),
|
||||
updated_at=item["stats"]["updated_at"],
|
||||
)
|
||||
for item in await cursor.to_list()
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user