merge: integrate ZSY customer service and profile capabilities
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ForbiddenAgentError
|
||||
from app.infrastructure.milvus_knowledge_adapter import MilvusKnowledgeClient
|
||||
|
||||
|
||||
class FakeMilvus:
|
||||
def __init__(self) -> None:
|
||||
self.kwargs = None
|
||||
|
||||
async def search(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
return [[{
|
||||
"distance": 0.91,
|
||||
"entity": {
|
||||
"knowledge_id": "101",
|
||||
"snippet": "开户说明",
|
||||
"title": "基金开户",
|
||||
"tags": ["开户"],
|
||||
"version": "v1",
|
||||
},
|
||||
}]]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_knowledge_adapter_uses_cosine_and_minimal_public_projection() -> None:
|
||||
client = MilvusKnowledgeClient("http://unused")
|
||||
fake = FakeMilvus()
|
||||
client._client = fake
|
||||
|
||||
hits = await client.search("fin_faq_collection", [0.1] * 1024, 3)
|
||||
|
||||
assert hits[0]["knowledge_id"] == "101"
|
||||
assert hits[0]["snippet"] == "开户说明"
|
||||
assert hits[0]["score"] == 0.91
|
||||
assert fake.kwargs["collection_name"] == "fin_faq_collection"
|
||||
assert fake.kwargs["limit"] == 3
|
||||
assert fake.kwargs["search_params"] == {"metric_type": "COSINE"}
|
||||
assert fake.kwargs["output_fields"] == ["knowledge_id", "title", "snippet", "tags", "version"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_knowledge_adapter_rejects_non_public_collection() -> None:
|
||||
client = MilvusKnowledgeClient("http://unused")
|
||||
|
||||
with pytest.raises(ForbiddenAgentError):
|
||||
await client.search("customer_vectors", [0.1] * 1024, 3)
|
||||
@@ -0,0 +1,96 @@
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import RecoverableAgentError
|
||||
from app.infrastructure.milvus_profile_projection import MilvusProfileProjection
|
||||
|
||||
|
||||
class FakeMilvus:
|
||||
def __init__(self, existing: list[dict[str, object]] | None = None) -> None:
|
||||
self.existing = existing or []
|
||||
self.queries: list[dict[str, object]] = []
|
||||
self.upserts: list[dict[str, object]] = []
|
||||
|
||||
async def query(self, **kwargs: object) -> list[dict[str, object]]:
|
||||
self.queries.append(kwargs)
|
||||
return self.existing
|
||||
|
||||
async def upsert(self, **kwargs: object) -> None:
|
||||
self.upserts.append(kwargs)
|
||||
|
||||
|
||||
def payload() -> dict[str, object]:
|
||||
return {
|
||||
"customer_id": 7,
|
||||
"profile_version": 1,
|
||||
"memory_sources": [{
|
||||
"memory_uuid": str(uuid4()),
|
||||
"memory_key": "preference:risk_level",
|
||||
"content": "稳健型",
|
||||
"memory_type": "preference",
|
||||
"confidence": 0.9,
|
||||
"version": 2,
|
||||
"valid_until": None,
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upsert_writes_schema_fields_and_vector() -> None:
|
||||
client = FakeMilvus()
|
||||
projection = MilvusProfileProjection(client, _embed)
|
||||
|
||||
await projection.upsert(payload())
|
||||
|
||||
assert len(client.upserts) == 1
|
||||
row = client.upserts[0]["data"][0]
|
||||
assert row["customer_id"] == 7
|
||||
assert row["status"] == "active"
|
||||
assert len(row["embedding"]) == 1024
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lower_memory_version_is_not_overwritten() -> None:
|
||||
data = payload()
|
||||
source = data["memory_sources"][0]
|
||||
assert isinstance(source, dict)
|
||||
memory_uuid = source["memory_uuid"]
|
||||
client = FakeMilvus(existing=[{
|
||||
"memory_uuid": memory_uuid, "customer_id": 7, "version": 3,
|
||||
}])
|
||||
|
||||
await MilvusProfileProjection(client, _embed).upsert(data)
|
||||
|
||||
assert client.upserts == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_embedding_dimension_is_enforced() -> None:
|
||||
with pytest.raises(RecoverableAgentError, match="维度"):
|
||||
await MilvusProfileProjection(client=FakeMilvus(), embed=_embed_short).upsert(
|
||||
payload()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_uuid_memory_id_is_rejected() -> None:
|
||||
data = payload()
|
||||
source = data["memory_sources"][0]
|
||||
assert isinstance(source, dict)
|
||||
source["memory_uuid"] = "unsafe\" or true"
|
||||
|
||||
with pytest.raises(ValueError, match="memory_uuid"):
|
||||
await MilvusProfileProjection(FakeMilvus(), _embed).upsert(data)
|
||||
|
||||
|
||||
def _vector(size: int = 1024) -> list[float]:
|
||||
return [0.0] * size
|
||||
|
||||
|
||||
async def _embed(_: str) -> list[float]:
|
||||
return _vector()
|
||||
|
||||
|
||||
async def _embed_short(_: str) -> list[float]:
|
||||
return _vector(3)
|
||||
@@ -0,0 +1,92 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.infrastructure.neo4j_profile_projection import Neo4jProfileProjection
|
||||
|
||||
|
||||
class FakeDriver:
|
||||
def __init__(self, *, applied: bool = True) -> None:
|
||||
self.applied = applied
|
||||
self.calls: list[tuple[str, dict[str, object]]] = []
|
||||
|
||||
async def execute_query(self, query: str, **parameters: object) -> SimpleNamespace:
|
||||
self.calls.append((query, parameters))
|
||||
return SimpleNamespace(records=[{"applied": True}] if self.applied else [])
|
||||
|
||||
|
||||
def payload() -> dict[str, object]:
|
||||
return {
|
||||
"customer_id": 7,
|
||||
"profile_uuid": "profile-7-v1",
|
||||
"profile_version": 1,
|
||||
"memory_sources": [
|
||||
{
|
||||
"memory_uuid": "memory-1",
|
||||
"memory_key": "preference:risk_level",
|
||||
"content": "稳健型",
|
||||
"memory_type": "preference",
|
||||
"confidence": 0.9,
|
||||
"version": 2,
|
||||
"valid_until": None,
|
||||
},
|
||||
{
|
||||
"memory_uuid": "memory-2",
|
||||
"memory_key": "goal:liquidity",
|
||||
"content": "保持流动性",
|
||||
"memory_type": "goal",
|
||||
"confidence": 0.8,
|
||||
"version": 1,
|
||||
"valid_until": None,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_projects_only_fixed_preference_and_goal_queries() -> None:
|
||||
driver = FakeDriver()
|
||||
result = await Neo4jProfileProjection(driver).upsert(payload())
|
||||
|
||||
assert result.applied is True
|
||||
assert len(driver.calls) == 3
|
||||
assert "MERGE (c:Customer" in driver.calls[0][0]
|
||||
assert "PREFERS" in driver.calls[1][0]
|
||||
assert "HAS_GOAL" in driver.calls[2][0]
|
||||
assert driver.calls[1][1]["items"][0]["memory_uuid"] == "memory-1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lower_profile_version_is_skipped_without_writes() -> None:
|
||||
driver = FakeDriver(applied=False)
|
||||
result = await Neo4jProfileProjection(driver).upsert(payload())
|
||||
|
||||
assert result.applied is False
|
||||
assert result.reason == "newer_profile_version_exists"
|
||||
assert len(driver.calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sensitive_memory_content_is_redacted_before_projection() -> None:
|
||||
data = payload()
|
||||
source = data["memory_sources"][0]
|
||||
assert isinstance(source, dict)
|
||||
source["content"] = "我的密码是123456,手机号13800138000"
|
||||
driver = FakeDriver()
|
||||
|
||||
await Neo4jProfileProjection(driver).upsert(data)
|
||||
|
||||
projected = driver.calls[1][1]["items"][0]["content"]
|
||||
assert "123456" not in projected
|
||||
assert "13800138000" not in projected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_memory_key_is_rejected() -> None:
|
||||
data = payload()
|
||||
source = data["memory_sources"][0]
|
||||
assert isinstance(source, dict)
|
||||
source["memory_key"] = "account:balance"
|
||||
|
||||
with pytest.raises(ValueError, match="not projectable"):
|
||||
await Neo4jProfileProjection(FakeDriver()).upsert(data)
|
||||
Reference in New Issue
Block a user