fix:记忆架构优化

This commit is contained in:
2026-09-13 21:22:54 +08:00
parent dd281b3361
commit 41284f0bb1
8 changed files with 354 additions and 11 deletions
+32 -2
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
from typing import Any
from pymilvus import AsyncMilvusClient, DataType
from config.database.milvus import client as configured_client
@@ -87,15 +89,43 @@ class MilvusMemoryStore:
return memory_id
async def search(self, vector: list[float], customer_id: int, *, limit: int = 10) -> list[dict]:
"""按客户 ID 过滤向量查询结果。"""
"""按客户 ID 过滤向量查询,返回归一化的命中列表。"""
await self.ensure_collection()
return await self.client.search(
raw = await self.client.search(
collection_name=self.collection_name,
data=[vector],
limit=limit,
filter=f"customer_id == {int(customer_id)}",
output_fields=["memory_id", "customer_id", "memory_type", "tag", "content", "status"],
)
return self._normalize_hits(raw)
@staticmethod
def _normalize_hits(raw: Any) -> list[dict]:
"""将 pymilvus 返回结构收敛为 memory_id + distance 的扁平列表。"""
hits: list[dict] = []
for batch in raw or []:
for hit in batch or []:
if not isinstance(hit, dict):
continue
entity = hit.get("entity") or {}
memory_id = entity.get("memory_id") or hit.get("id")
if memory_id is None:
continue
try:
distance = float(hit.get("distance", 0.0))
except (TypeError, ValueError):
distance = 0.0
hits.append(
{
"memory_id": str(memory_id),
"distance": max(0.0, min(1.0, distance)),
"tag": entity.get("tag"),
"content": entity.get("content"),
"status": entity.get("status"),
}
)
return hits
async def delete(self, memory_id: int | str) -> None:
"""删除一条客户记忆向量。"""