一、客服 Agent 智能增强(正面回应"不智能、动不动就转人工")
- 决策链由 2 个出口扩到 5 个:E1 澄清 / E2 计算型 / E3 知识直返 / E4 证据约束生成 / E5 分级回退
- 转人工从"默认动作"降为最后一档 E5c,只保留 4 类白名单:
P0 反诈 / P1 账户与个人数据 / P2 写操作与争议 / 用户明确要求人工
- 46 条金标实测(修复前 → 修复后):
转人工率 43.5% → 10.9%;出口准确率 45.7% → 100%;事实正确率 69.6% → 100%
禁忌违反 1 → 0;档位越权 / 无出处数字 / 误拒 四项零容忍全 0
- 安全不变量 INV-1~INV-5;零容忍规则未删,改的是挂载点
(输出侧字面黑名单 → 检索层档位隔离 + 判定层合规词表 + 输出守护)
二、知识库:档位单点化与物理隔离
- 新增 app/core/knowledge_tier.py 作为档位规则唯一落点(G-03),
knowledge_contracts.py 原定义块改为显式再导出(X as X,非副本)
- 档位过滤由 bool 默认值(fail-open)改为 tiers 必填集合(缺参即 TypeError)
- Milvus 侧四集合按 visibility 分区键物理隔离;双 schema 收敛为一套
- 新增 app/core/actor.py:访客三元组与匿名判定的唯一构造/判定点(G-01/G-01b)
- 新增 app/core/fund_fee_rules.py:费率计算纯函数
三、前端入参边界对齐(本轮 W11 新修,4 处"校验宽于存储")
- message 加 max_length=8000(与浮窗 widget.js 的 maxlength 一致)
- session_id 加 1—64;idempotency_key 上限 128 → 64(对齐列宽 String(64))
- feedback_type 加 max_length=32(对齐列宽 String(32))
- 8 条路径参数补 min_length=1 + max_length=64 + 字符集正则
({session_id} / {run_id} / {handover_id})
- 改前超限值会落到 MySQL 才失败(500);改后一律 422 AGENT_INPUT_INVALID + 字段级定位
- 新增 tests/unit/api/test_frontend_boundaries.py(33 例),含"端点表 ↔ OpenAPI 全量对照"
四、投顾模块整体清除(D4.4 / D4.5)
- 删除投顾相关 controller / schema / model / repository / service 及门户页面
- tools/portal_api_check.py 同步作废 AD003/AD005/AD011/A047 四条用例与 advisor_t 登录
(端点与账号均已不存在,此前稳定报 3 条假红)
五、验证(提交前实测)
- pytest -q:1856 passed / 2 skipped / 0 failed
- ruff check app tools tests:19(= 基线);mypy app:2(= 基线)
- 前端接口契约体检 portal_api_check.py:38 项,通过 34,失败 0,跳过 4
- 全链路冒烟 e2e_smoke_test.py --read-only:31/31
- HTTP 全链路探针 http_probe.py:11/11 succeeded
- 跨文档一致性 _consistency.py:GATE PASS
- 真机边界复验 12 条:12/12 符合预期
六、纪律与文档
- 可改文件白名单 A-09(docs/46)与底座会签申请单 A-10(docs/47,组 1—组 4 全部受理)
- 零 DDL:未新增/修改任何表结构,89 张业务表与基线一致
- 证据留痕:docs/evidence/**(含 46 条金标 score、快照、清除与重建记录)
- 未提交(刻意排除,见提交说明):仓库内 客服agent/ 与 开发文档/ 是 2026-09-16 前的
过期副本(Todolist 440 行 vs 权威 D2.1 1167 行),权威正本在仓库外;
_chunks_report.txt 是 tools/build_knowledge_chunks.py 生成的本地产物
151 lines
5.3 KiB
Python
151 lines
5.3 KiB
Python
"""幂等创建长期记忆画像向量集合 `user_long_term_memory_v1`。
|
||
|
||
写入侧是 `app/infrastructure/milvus_profile_projection.py`,字段必须与之一致。
|
||
|
||
用法:
|
||
.\\.venv\\Scripts\\python.exe tools\\setup_milvus_profile_collection.py
|
||
|
||
安全口径(与 `setup_milvus_knowledge_collections.py` 相同:这是**共享** Milvus 实例,
|
||
里面还有别的项目在用的集合):
|
||
- 只碰 `user_long_term_memory_v1` 这一个集合,绝不 list 后批量删除;
|
||
- 集合已存在时**只做结构比对并报告**,不覆盖、不删重建;
|
||
- 结构不一致时明确报错退出,由人决定怎么处理,避免静默丢数据。
|
||
"""
|
||
|
||
import asyncio
|
||
import sys
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
# 与 setup_milvus_knowledge_collections.py 同一条引导:脚本必须能直接在仓库根目录用
|
||
# 项目解释器执行(见模块 docstring 的用法)。缺这一行会在根目录直接报
|
||
# ModuleNotFoundError: No module named app(2026-09-19 S-7 实测)。
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
|
||
COLLECTION = "user_long_term_memory_v1"
|
||
VECTOR_FIELD = "embedding"
|
||
VECTOR_DIM = 1024
|
||
PRIMARY_FIELD = "memory_uuid"
|
||
|
||
#: (字段名, 最大长度)。`memory_uuid` 是主键(UUID 字符串)。
|
||
VARCHAR_FIELDS: tuple[tuple[str, int], ...] = (
|
||
("memory_uuid", 64),
|
||
("content", 2048),
|
||
("memory_type", 32),
|
||
("memory_key", 64),
|
||
("status", 16),
|
||
)
|
||
#: INT64 字段;可空,因为 `valid_until_ts` 对永久记忆为空。
|
||
INT64_FIELDS: tuple[str, ...] = (
|
||
"customer_id",
|
||
"version",
|
||
"valid_until_ts",
|
||
"updated_at_ts",
|
||
)
|
||
FLOAT_FIELDS: tuple[str, ...] = ("confidence",)
|
||
|
||
|
||
def _build_schema() -> Any:
|
||
from pymilvus import DataType, MilvusClient # type: ignore[import-untyped]
|
||
|
||
schema = MilvusClient.create_schema(auto_id=False, enable_dynamic_field=False)
|
||
for name, max_length in VARCHAR_FIELDS:
|
||
schema.add_field(
|
||
field_name=name,
|
||
datatype=DataType.VARCHAR,
|
||
max_length=max_length,
|
||
is_primary=(name == PRIMARY_FIELD),
|
||
nullable=False,
|
||
)
|
||
for name in INT64_FIELDS:
|
||
# 可空:`valid_until_ts` 对永久记忆必须能不写。
|
||
schema.add_field(
|
||
field_name=name, datatype=DataType.INT64, nullable=name != "customer_id"
|
||
)
|
||
for name in FLOAT_FIELDS:
|
||
schema.add_field(field_name=name, datatype=DataType.DOUBLE, nullable=False)
|
||
schema.add_field(
|
||
field_name=VECTOR_FIELD, datatype=DataType.FLOAT_VECTOR, dim=VECTOR_DIM
|
||
)
|
||
return schema
|
||
|
||
|
||
def _build_index_params() -> Any:
|
||
from pymilvus import MilvusClient # type: ignore[import-untyped]
|
||
|
||
index_params = MilvusClient.prepare_index_params()
|
||
index_params.add_index(
|
||
field_name=VECTOR_FIELD,
|
||
index_name="profile_vector_index",
|
||
index_type="AUTOINDEX",
|
||
metric_type="COSINE",
|
||
)
|
||
return index_params
|
||
|
||
|
||
def describe_mismatch(described: dict[str, Any]) -> list[str]:
|
||
"""比对已存在集合与期望结构,返回差异列表(一致时为空)。"""
|
||
problems: list[str] = []
|
||
actual = {field["name"]: field for field in described.get("fields", [])}
|
||
expected_names = (
|
||
[name for name, _ in VARCHAR_FIELDS] + list(INT64_FIELDS)
|
||
+ list(FLOAT_FIELDS) + [VECTOR_FIELD]
|
||
)
|
||
for name in expected_names:
|
||
if name not in actual:
|
||
problems.append(f"缺少字段 {name}")
|
||
for name, _ in VARCHAR_FIELDS:
|
||
if name in actual and not actual[name].get("is_primary") and name == PRIMARY_FIELD:
|
||
problems.append(f"{name} 不是主键")
|
||
vector = actual.get(VECTOR_FIELD)
|
||
if vector is not None:
|
||
params = vector.get("params") or {}
|
||
dim = params.get("dim")
|
||
if dim is not None and int(dim) != VECTOR_DIM:
|
||
problems.append(f"{VECTOR_FIELD} 维度是 {dim},期望 {VECTOR_DIM}")
|
||
return problems
|
||
|
||
|
||
async def ensure_collection(uri: str, token: str = "") -> str:
|
||
"""返回 `created` / `exists` / `conflict:<原因>`。"""
|
||
from pymilvus import AsyncMilvusClient # type: ignore[import-untyped]
|
||
|
||
client = AsyncMilvusClient(uri=uri, token=token or None)
|
||
try:
|
||
if await client.has_collection(COLLECTION):
|
||
described = await client.describe_collection(COLLECTION)
|
||
problems = describe_mismatch(described)
|
||
if problems:
|
||
return "conflict:" + "; ".join(problems)
|
||
return "exists"
|
||
await client.create_collection(
|
||
collection_name=COLLECTION,
|
||
schema=_build_schema(),
|
||
index_params=_build_index_params(),
|
||
)
|
||
return "created"
|
||
finally:
|
||
close = getattr(client, "close", None)
|
||
if close is not None:
|
||
await close()
|
||
|
||
|
||
async def main() -> int:
|
||
from app.core.config import get_settings
|
||
|
||
settings = get_settings()
|
||
uri = settings.milvus_uri
|
||
if not uri:
|
||
print("未配置 milvus_uri,无法创建集合")
|
||
return 1
|
||
outcome = await ensure_collection(uri, settings.milvus_token or "")
|
||
print(f"{COLLECTION}: {outcome}")
|
||
if outcome.startswith("conflict:"):
|
||
print("结构不一致,未做任何修改。请人工确认后再处理。")
|
||
return 2
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(asyncio.run(main()))
|