mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-25 00:29:20 +08:00
init
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
"""Mongo 连接与索引。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
|
||||
|
||||
from config.settings import Settings
|
||||
|
||||
_client: AsyncIOMotorClient | None = None
|
||||
|
||||
|
||||
async def get_db(settings: Settings) -> AsyncIOMotorDatabase:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = AsyncIOMotorClient(settings.mongo_uri)
|
||||
return _client[settings.mongo_db]
|
||||
|
||||
|
||||
async def ensure_indexes(db: AsyncIOMotorDatabase) -> None:
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("thread_id", 1)], unique=True
|
||||
)
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("status", 1), ("scene", 1), ("updated_at", -1)]
|
||||
)
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("scene", 1), ("scene_ref", 1), ("status", 1)]
|
||||
)
|
||||
await db.agent_messages.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("thread_id", 1), ("seq", 1)]
|
||||
)
|
||||
await db.agent_user_memory.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("status", 1), ("kind", 1), ("updated_at", -1)]
|
||||
)
|
||||
await db.agent_user_memory.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("key", 1)],
|
||||
unique=True,
|
||||
partialFilterExpression={"key": {"$type": "string"}},
|
||||
)
|
||||
|
||||
|
||||
async def close_mongo() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
_client.close()
|
||||
_client = None
|
||||
@@ -0,0 +1,449 @@
|
||||
"""会话 / 消息 / 用户记忆 Mongo 实现。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
import re
|
||||
|
||||
from bson import ObjectId
|
||||
from motor.motor_asyncio import AsyncIOMotorDatabase
|
||||
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmResponseChain,
|
||||
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()
|
||||
|
||||
|
||||
def _optional_int(v: Any) -> int | None:
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _chain_to_doc(chain: LlmResponseChain | None) -> dict[str, Any] | None:
|
||||
if chain is None or not (chain.previous_response_id or "").strip():
|
||||
return None
|
||||
return {
|
||||
"provider_id": chain.provider_id,
|
||||
"model": chain.model,
|
||||
"previous_response_id": chain.previous_response_id.strip(),
|
||||
}
|
||||
|
||||
|
||||
def _chain_from_doc(raw: Any) -> LlmResponseChain | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
rid = str(raw.get("previous_response_id") or "").strip()
|
||||
model = str(raw.get("model") or "").strip()
|
||||
if not rid or not model:
|
||||
return None
|
||||
return LlmResponseChain(
|
||||
provider_id=_optional_int(raw.get("provider_id")),
|
||||
model=model,
|
||||
previous_response_id=rid,
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
"scene": session.scene or "general",
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||
"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,
|
||||
*,
|
||||
scene: str | None = None,
|
||||
) -> list[Session]:
|
||||
query: dict[str, Any] = {
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": SessionStatus.ACTIVE.value,
|
||||
}
|
||||
# 缺省只列经营助手;旧文档无 scene 字段视为 general
|
||||
want = (scene or "general").strip() or "general"
|
||||
if want == "general":
|
||||
query["$or"] = [
|
||||
{"scene": "general"},
|
||||
{"scene": {"$exists": False}},
|
||||
{"scene": None},
|
||||
]
|
||||
else:
|
||||
query["scene"] = want
|
||||
cursor = (
|
||||
self._col.find(query)
|
||||
.sort("updated_at", -1)
|
||||
.limit(limit)
|
||||
)
|
||||
return [self._to_session(d) async for d in cursor]
|
||||
|
||||
async def find_active_by_scene_ref(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
*,
|
||||
scene: str,
|
||||
scene_ref: str,
|
||||
) -> Session | None:
|
||||
ref = (scene_ref or "").strip()
|
||||
if not ref:
|
||||
return None
|
||||
doc = await self._col.find_one(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": SessionStatus.ACTIVE.value,
|
||||
"scene": (scene or "").strip() or "general",
|
||||
"scene_ref": ref,
|
||||
},
|
||||
sort=[("updated_at", -1)],
|
||||
)
|
||||
return self._to_session(doc) if doc else None
|
||||
|
||||
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,
|
||||
"scene": session.scene or "general",
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||
"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"),
|
||||
scene=(doc.get("scene") or "general"),
|
||||
scene_ref=doc.get("scene_ref"),
|
||||
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
||||
llm_model=doc.get("llm_model"),
|
||||
llm_response_chain=_chain_from_doc(doc.get("llm_response_chain")),
|
||||
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,
|
||||
# 兼容旧文档无 status;软删后 status=deleted
|
||||
"$or": [
|
||||
{"status": {"$exists": False}},
|
||||
{"status": None},
|
||||
{"status": {"$ne": "deleted"}},
|
||||
],
|
||||
}
|
||||
)
|
||||
.sort("seq", -1)
|
||||
.limit(limit)
|
||||
)
|
||||
rows = [self._to_msg(d) async for d in cursor]
|
||||
rows.reverse()
|
||||
return rows
|
||||
|
||||
async def soft_delete_by_thread(
|
||||
self, company_id: int, user_id: str, thread_id: str
|
||||
) -> int:
|
||||
result = await self._col.update_many(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"thread_id": thread_id,
|
||||
"$or": [
|
||||
{"status": {"$exists": False}},
|
||||
{"status": None},
|
||||
{"status": {"$ne": "deleted"}},
|
||||
],
|
||||
},
|
||||
{"$set": {"status": "deleted", "deleted_at": datetime.utcnow()}},
|
||||
)
|
||||
return int(result.modified_count or 0)
|
||||
|
||||
@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 count_active(self, company_id: int, user_id: str) -> int:
|
||||
return int(
|
||||
await self._col.count_documents(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": MemoryStatus.ACTIVE.value,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
async def search(
|
||||
self, company_id: int, user_id: str, query: str, limit: int
|
||||
) -> list[UserMemory]:
|
||||
"""按摘要/正文关键词匹配(非向量);无关键词时退化为最近更新列表。"""
|
||||
tokens = _keyword_tokens(query)
|
||||
filt: dict[str, Any] = {
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": MemoryStatus.ACTIVE.value,
|
||||
}
|
||||
if tokens:
|
||||
token_clauses = []
|
||||
for t in tokens:
|
||||
escaped = re.escape(t)
|
||||
token_clauses.append(
|
||||
{
|
||||
"$or": [
|
||||
{"summary": {"$regex": escaped, "$options": "i"}},
|
||||
{"text": {"$regex": escaped, "$options": "i"}},
|
||||
]
|
||||
}
|
||||
)
|
||||
filt["$and"] = token_clauses
|
||||
cursor = self._col.find(filt).sort("updated_at", -1).limit(max(1, min(limit, 20)))
|
||||
return [self._to_mem(d) async for d in cursor]
|
||||
|
||||
async def get_by_ids(
|
||||
self, company_id: int, user_id: str, memory_ids: list[str]
|
||||
) -> list[UserMemory]:
|
||||
oids: list[ObjectId] = []
|
||||
for mid in memory_ids:
|
||||
try:
|
||||
oids.append(ObjectId(mid))
|
||||
except Exception:
|
||||
continue
|
||||
if not oids:
|
||||
return []
|
||||
cursor = self._col.find(
|
||||
{
|
||||
"_id": {"$in": oids},
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": MemoryStatus.ACTIVE.value,
|
||||
}
|
||||
)
|
||||
by_id: dict[str, UserMemory] = {}
|
||||
async for d in cursor:
|
||||
by_id[str(d["_id"])] = self._to_mem(d)
|
||||
# 保持调用方 id 顺序
|
||||
return [by_id[mid] for mid in memory_ids if mid in by_id]
|
||||
|
||||
async def upsert(self, memory: UserMemory) -> UserMemory:
|
||||
memory.updated_at = datetime.utcnow()
|
||||
if not (memory.summary or "").strip():
|
||||
memory.summary = _fallback_summary(memory.text)
|
||||
payload = {
|
||||
"company_id": memory.company_id,
|
||||
"user_id": memory.user_id,
|
||||
"kind": memory.kind.value,
|
||||
"key": memory.key,
|
||||
"text": memory.text,
|
||||
"summary": memory.summary,
|
||||
"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:
|
||||
text = doc.get("text") or ""
|
||||
summary = (doc.get("summary") or "").strip() or _fallback_summary(text)
|
||||
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=text,
|
||||
summary=summary,
|
||||
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")),
|
||||
)
|
||||
|
||||
|
||||
def _fallback_summary(text: str, max_len: int = 80) -> str:
|
||||
s = (text or "").strip().replace("\n", " ")
|
||||
if len(s) <= max_len:
|
||||
return s
|
||||
return s[: max_len - 1] + "…"
|
||||
|
||||
|
||||
def _keyword_tokens(query: str) -> list[str]:
|
||||
"""按空白与常见标点切词;过短 token 丢弃。"""
|
||||
parts = re.split(r"[\s,,。.!!??;;::、/\\|]+", (query or "").strip())
|
||||
out: list[str] = []
|
||||
for p in parts:
|
||||
t = p.strip()
|
||||
if len(t) >= 1 and t not in out:
|
||||
out.append(t)
|
||||
return out[:8]
|
||||
Reference in New Issue
Block a user