mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 23:49:19 +08:00
247 lines
8.3 KiB
Python
247 lines
8.3 KiB
Python
"""会话 / 消息 / 用户记忆 Mongo 实现。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from bson import ObjectId
|
|
from motor.motor_asyncio import AsyncIOMotorDatabase
|
|
|
|
from domain.models import (
|
|
ChatMessage,
|
|
MemoryKind,
|
|
MemoryStatus,
|
|
MessageRole,
|
|
Session,
|
|
SessionStatus,
|
|
UserMemory,
|
|
)
|
|
from domain.ports import MemoryRepository, MessageRepository, SessionRepository
|
|
|
|
|
|
def _dt(v: Any) -> datetime:
|
|
if isinstance(v, datetime):
|
|
return v
|
|
return datetime.utcnow()
|
|
|
|
|
|
class MongoSessionRepository(SessionRepository):
|
|
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
|
self._col = db.agent_sessions
|
|
|
|
async def create(self, session: Session) -> Session:
|
|
doc = {
|
|
"thread_id": session.thread_id,
|
|
"company_id": session.company_id,
|
|
"user_id": session.user_id,
|
|
"title": session.title,
|
|
"status": session.status.value,
|
|
"summary": session.summary,
|
|
"created_at": session.created_at,
|
|
"updated_at": session.updated_at,
|
|
"last_message_at": session.last_message_at,
|
|
}
|
|
await self._col.insert_one(doc)
|
|
return session
|
|
|
|
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
|
|
doc = await self._col.find_one(
|
|
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
|
|
)
|
|
return None if doc is None else self._to_session(doc)
|
|
|
|
async def list_active(self, company_id: int, user_id: str, limit: int = 50) -> list[Session]:
|
|
cursor = (
|
|
self._col.find(
|
|
{
|
|
"company_id": company_id,
|
|
"user_id": user_id,
|
|
"status": SessionStatus.ACTIVE.value,
|
|
}
|
|
)
|
|
.sort("updated_at", -1)
|
|
.limit(limit)
|
|
)
|
|
return [self._to_session(d) async for d in cursor]
|
|
|
|
async def update(self, session: Session) -> Session:
|
|
session.updated_at = datetime.utcnow()
|
|
await self._col.update_one(
|
|
{
|
|
"company_id": session.company_id,
|
|
"user_id": session.user_id,
|
|
"thread_id": session.thread_id,
|
|
},
|
|
{
|
|
"$set": {
|
|
"title": session.title,
|
|
"status": session.status.value,
|
|
"summary": session.summary,
|
|
"updated_at": session.updated_at,
|
|
"last_message_at": session.last_message_at,
|
|
}
|
|
},
|
|
)
|
|
return session
|
|
|
|
@staticmethod
|
|
def _to_session(doc: dict[str, Any]) -> Session:
|
|
return Session(
|
|
thread_id=doc["thread_id"],
|
|
company_id=int(doc["company_id"]),
|
|
user_id=str(doc["user_id"]),
|
|
title=doc.get("title") or "新对话",
|
|
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
|
|
summary=doc.get("summary"),
|
|
created_at=_dt(doc.get("created_at")),
|
|
updated_at=_dt(doc.get("updated_at")),
|
|
last_message_at=doc.get("last_message_at"),
|
|
)
|
|
|
|
|
|
class MongoMessageRepository(MessageRepository):
|
|
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
|
self._col = db.agent_messages
|
|
|
|
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int:
|
|
doc = await self._col.find_one(
|
|
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id},
|
|
sort=[("seq", -1)],
|
|
projection={"seq": 1},
|
|
)
|
|
return 1 if doc is None else int(doc["seq"]) + 1
|
|
|
|
async def append(self, message: ChatMessage) -> ChatMessage:
|
|
doc = {
|
|
"company_id": message.company_id,
|
|
"user_id": message.user_id,
|
|
"thread_id": message.thread_id,
|
|
"seq": message.seq,
|
|
"role": message.role.value,
|
|
"content": message.content,
|
|
"tool_name": message.tool_name,
|
|
"tool_call_id": message.tool_call_id,
|
|
"created_at": message.created_at,
|
|
}
|
|
result = await self._col.insert_one(doc)
|
|
message.id = str(result.inserted_id)
|
|
return message
|
|
|
|
async def list_recent(
|
|
self, company_id: int, user_id: str, thread_id: str, limit: int
|
|
) -> list[ChatMessage]:
|
|
cursor = (
|
|
self._col.find(
|
|
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
|
|
)
|
|
.sort("seq", -1)
|
|
.limit(limit)
|
|
)
|
|
rows = [self._to_msg(d) async for d in cursor]
|
|
rows.reverse()
|
|
return rows
|
|
|
|
@staticmethod
|
|
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
|
return ChatMessage(
|
|
id=str(doc.get("_id")),
|
|
company_id=int(doc["company_id"]),
|
|
user_id=str(doc["user_id"]),
|
|
thread_id=doc["thread_id"],
|
|
seq=int(doc["seq"]),
|
|
role=MessageRole(doc["role"]),
|
|
content=doc.get("content") or "",
|
|
tool_name=doc.get("tool_name"),
|
|
tool_call_id=doc.get("tool_call_id"),
|
|
created_at=_dt(doc.get("created_at")),
|
|
)
|
|
|
|
|
|
class MongoMemoryRepository(MemoryRepository):
|
|
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
|
self._col = db.agent_user_memory
|
|
|
|
async def list_active(
|
|
self, company_id: int, user_id: str, limit: int
|
|
) -> list[UserMemory]:
|
|
cursor = (
|
|
self._col.find(
|
|
{
|
|
"company_id": company_id,
|
|
"user_id": user_id,
|
|
"status": MemoryStatus.ACTIVE.value,
|
|
}
|
|
)
|
|
.sort("updated_at", -1)
|
|
.limit(limit)
|
|
)
|
|
return [self._to_mem(d) async for d in cursor]
|
|
|
|
async def upsert(self, memory: UserMemory) -> UserMemory:
|
|
memory.updated_at = datetime.utcnow()
|
|
payload = {
|
|
"company_id": memory.company_id,
|
|
"user_id": memory.user_id,
|
|
"kind": memory.kind.value,
|
|
"key": memory.key,
|
|
"text": memory.text,
|
|
"value": memory.value,
|
|
"source_thread_id": memory.source_thread_id,
|
|
"status": memory.status.value,
|
|
"confidence": memory.confidence,
|
|
"updated_at": memory.updated_at,
|
|
}
|
|
if memory.key:
|
|
existing = await self._col.find_one(
|
|
{
|
|
"company_id": memory.company_id,
|
|
"user_id": memory.user_id,
|
|
"key": memory.key,
|
|
"status": {"$ne": MemoryStatus.DELETED.value},
|
|
}
|
|
)
|
|
if existing:
|
|
await self._col.update_one({"_id": existing["_id"]}, {"$set": payload})
|
|
memory.id = str(existing["_id"])
|
|
memory.created_at = _dt(existing.get("created_at"))
|
|
return memory
|
|
|
|
payload["created_at"] = memory.created_at
|
|
result = await self._col.insert_one(payload)
|
|
memory.id = str(result.inserted_id)
|
|
return memory
|
|
|
|
async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool:
|
|
try:
|
|
oid = ObjectId(memory_id)
|
|
except Exception:
|
|
return False
|
|
result = await self._col.update_one(
|
|
{"_id": oid, "company_id": company_id, "user_id": user_id},
|
|
{
|
|
"$set": {
|
|
"status": MemoryStatus.DELETED.value,
|
|
"updated_at": datetime.utcnow(),
|
|
}
|
|
},
|
|
)
|
|
return result.modified_count > 0
|
|
|
|
@staticmethod
|
|
def _to_mem(doc: dict[str, Any]) -> UserMemory:
|
|
return UserMemory(
|
|
id=str(doc.get("_id")),
|
|
company_id=int(doc["company_id"]),
|
|
user_id=str(doc["user_id"]),
|
|
kind=MemoryKind(doc.get("kind") or MemoryKind.FACT.value),
|
|
key=doc.get("key"),
|
|
text=doc.get("text") or "",
|
|
value=doc.get("value") or {},
|
|
source_thread_id=doc.get("source_thread_id"),
|
|
status=MemoryStatus(doc.get("status") or MemoryStatus.ACTIVE.value),
|
|
confidence=float(doc.get("confidence") or 0.8),
|
|
created_at=_dt(doc.get("created_at")),
|
|
updated_at=_dt(doc.get("updated_at")),
|
|
)
|