相对第一版 46fc976 的完整变更。组员迁移对照表见 docs/20。
一、对外契约对齐 docs/05(破坏性,共 4 处,组员需按 docs/20 调整)
1) 配置发布端点改为文档规定的复数资源名:submit→validations、
approve→reviews(需 body decision)、activate→activations、
rollback→rollbacks;第一版这 4 个动词式路径 docs/05 从未定义过。
2) 错误码由 8 个笼统码改为 15 个具体语义码(FORBIDDEN→AGENT_PERMISSION_DENIED、
UNAUTHORIZED→AUTHENTICATION_REQUIRED、CONFLICT→RESOURCE_VERSION_CONFLICT、
RESOURCE_NOT_FOUND→RUN_NOT_FOUND/SESSION_NOT_FOUND 等),
输入类错误状态码 400→422。
3) POST /api/v1/agent-runs 与 GET /api/v1/agent-runs/{run_id} 统一为
{data, meta} 信封(data 内字段名与语义未变)。
4) 错误响应体统一为 {error:{code,message,retryable,field_errors}, meta:{trace_id}},
不再返回 FastAPI 默认的 {"detail": ...}。
二、数据库基线与约束
新增 39 张表的基线迁移(链根)与联合唯一键纠偏(4 张表、删 8 增 4,幂等收敛);
撤下 config_release 的双人复核 CHECK(应用层已允许自审,审核节点保留,
自审如实写入 reviewer_id);记忆 active key 生成列与唯一键;
activate 开始记录 supersedes_release_id 使版本链可追溯。
docs/00 基线未修改,未重命名或删除任何表与字段。
三、修复会静默出错或无报错的缺陷
- 跑完集成测试后平台会静默失去生效配置:清理只删自己创建的版本,却没有恢复被它
顶成 superseded 的原生效版本,且审计一并删除因而完全无痕,表现为所有工具被拒
但没有任何报错。已修清理逻辑并加恢复。
- Worker 单轮异常导致进程退出;记忆抽取调用方的“事务已开始”异常;
召回缓存丢失 degraded 标记;连接时区未生效导致 created_at/updated_at 差 8 小时;
.env 与 os.getenv 密钥来源分裂导致“没有可用的已批准模型端点”。
- 记忆信号识别漏判与跨键误命中;SSE 未带 Accept 的协商行为。
四、功能补齐
记忆链路 P1/P2/P3(抽取、受控词表、召回与缓存、生命周期级联及投影事件)、
fin_* 场内交易只读 ORM 层、agent_intent_config 状态流转并在运行期真正生效、
限流(Redis 固定窗口、故障一律放行)、游标校验、trace_id 中间件、
示例业务 Agent fund_query_demo 与一键端到端验证脚本,以及审计/指纹/迁移状态工具。
五、文档与验证
新增 docs/19(业务 Agent 接入实操)、docs/20(第一版迁移指南)与 docs/evidence 证据;
docs/01/02/06/08/09/17 同步实现现状。
验证结果:ruff 通过、mypy 103 文件无错、unit+contract 447 passed、
integration 29 passed、acceptance_check --production 7 PASS、
demo_agent_e2e 9/9 PASS(含失败关闭反证)。
148 lines
6.7 KiB
Python
148 lines
6.7 KiB
Python
import logging
|
|
import re
|
|
from collections.abc import Callable
|
|
from typing import Protocol
|
|
|
|
from sqlalchemy import select, text
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.contracts import (
|
|
AgentDefinition,
|
|
AgentResult,
|
|
RecalledMemory,
|
|
RequestContext,
|
|
ResolvedAgentConfig,
|
|
)
|
|
from app.core.errors import ForbiddenAgentError, RecoverableAgentError
|
|
from app.infrastructure.db import SessionFactory
|
|
from app.model.configuration import ConfigRelease
|
|
from app.service.memory_recall_service import MemoryRecallService
|
|
from app.service.runtime_config_service import RuntimeConfigService
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# 组装层注入的召回服务工厂:允许带 Redis 缓存与向量库,缺省退化为纯结构化召回。
|
|
RecallServiceFactory = Callable[[AsyncSession], MemoryRecallService]
|
|
|
|
|
|
class AgentGovernance(Protocol):
|
|
async def resolve(
|
|
self, definition: AgentDefinition, context: RequestContext
|
|
) -> ResolvedAgentConfig: ...
|
|
|
|
async def recall(self, context: RequestContext) -> tuple[RecalledMemory, ...]: ...
|
|
|
|
async def review(
|
|
self, result: AgentResult, context: RequestContext, config: ResolvedAgentConfig,
|
|
memories: tuple[RecalledMemory, ...],
|
|
) -> AgentResult: ...
|
|
|
|
|
|
class PlatformGovernance:
|
|
"""Request-scoped snapshots; no AsyncSession or customer state retained on the singleton."""
|
|
|
|
def __init__(self, recall_factory: RecallServiceFactory | None = None) -> None:
|
|
# 组装层可注入带缓存/向量库的召回服务;缺省退化为纯结构化召回,
|
|
# 依赖缺失或故障只降级,不让记忆功能整体不可用。
|
|
self._recall_factory = recall_factory
|
|
|
|
async def resolve(
|
|
self, definition: AgentDefinition, context: RequestContext
|
|
) -> ResolvedAgentConfig:
|
|
async with SessionFactory() as session:
|
|
release = await session.scalar(select(ConfigRelease).where(
|
|
ConfigRelease.status == "active"))
|
|
tools: dict[str, tuple[str, ...]] = {}
|
|
if release is not None:
|
|
service = RuntimeConfigService(session)
|
|
for intent in definition.supported_intents:
|
|
configured = await service.allowed_tools(
|
|
release.id, definition.agent_type, intent)
|
|
tools[intent] = tuple(sorted(set(configured) & set(definition.allowed_tools)))
|
|
rows = (await session.execute(text("""
|
|
SELECT match_type, word_pattern, applicable_agents FROM agent_negative_word
|
|
WHERE status='active' AND reviewer_id IS NOT NULL AND reviewed_at IS NOT NULL
|
|
"""))).mappings().all()
|
|
rules: list[tuple[str, str]] = []
|
|
import json
|
|
|
|
for row in rows:
|
|
agents = row["applicable_agents"]
|
|
if isinstance(agents, str):
|
|
agents = json.loads(agents)
|
|
if agents and definition.agent_type not in agents:
|
|
continue
|
|
if row["match_type"] not in {"exact", "contains"}:
|
|
# Python re has no execution timeout: never run unchecked admin regex.
|
|
raise RecoverableAgentError("禁止表达正则规则需要受限匹配器")
|
|
rules.append((str(row["match_type"]), str(row["word_pattern"])))
|
|
return ResolvedAgentConfig(
|
|
config_version=release.release_no if release else f"code:{definition.version}",
|
|
release_id=release.id if release else None,
|
|
prompt_version="none", model_endpoint="", allowed_tools=(),
|
|
allowed_tools_by_intent=tools, negative_rules=tuple(rules),
|
|
)
|
|
|
|
async def recall(self, context: RequestContext) -> tuple[RecalledMemory, ...]:
|
|
async with SessionFactory() as session:
|
|
service = (
|
|
self._recall_factory(session)
|
|
if self._recall_factory is not None
|
|
else MemoryRecallService(session)
|
|
)
|
|
customer_id = int(context.user_id)
|
|
result = await service.recall(customer_id)
|
|
if result.degraded:
|
|
logger.warning("memory recall degraded customer_id=%s reasons=%s",
|
|
customer_id, ",".join(result.degraded_reasons))
|
|
return tuple(
|
|
RecalledMemory(memory_uuid=item.memory_uuid, customer_id=str(customer_id),
|
|
content=item.content)
|
|
for item in result.items
|
|
)
|
|
|
|
async def review(
|
|
self, result: AgentResult, context: RequestContext, config: ResolvedAgentConfig,
|
|
memories: tuple[RecalledMemory, ...],
|
|
) -> AgentResult:
|
|
return review_output(result, context, config, memories)
|
|
|
|
|
|
def review_output(
|
|
result: AgentResult, context: RequestContext, config: ResolvedAgentConfig,
|
|
memories: tuple[RecalledMemory, ...],
|
|
) -> AgentResult:
|
|
content = result.result
|
|
issued_tools = {f"{context.trace_id}:{record.tool_name}" for record in content.tool_calls
|
|
if record.status == "succeeded"}
|
|
known = {memory.memory_uuid for memory in memories if memory.customer_id == context.user_id}
|
|
for reference in content.source_references:
|
|
valid = ((reference.source_type == "memory" and reference.source_id in known)
|
|
or (reference.source_type == "tool" and reference.source_id in issued_tools))
|
|
if not valid:
|
|
raise ForbiddenAgentError("引用未来自本次已授权召回结果")
|
|
output = content.text
|
|
hard_patterns = ("保证收益", "稳赚不赔", "保本保收益", "已为您下单", "已替您交易")
|
|
blocked = any(word in output for word in hard_patterns)
|
|
for kind, pattern in config.negative_rules:
|
|
blocked |= (output == pattern if kind == "exact" else pattern in output)
|
|
if blocked:
|
|
content = content.model_copy(update={
|
|
"text": "该内容需要人工核实。基金投资存在风险,本系统不代客交易。",
|
|
"source_references": (), "transfer_required": True,
|
|
"transfer_reason": "compliance_review_required",
|
|
})
|
|
else:
|
|
# Apply to text and citation titles, not only to the displayed answer.
|
|
def redact(value: str) -> str:
|
|
value = re.sub(r"(?<!\d)1[3-9]\d{9}(?!\d)", "[手机号已脱敏]", value)
|
|
return re.sub(r"(?<!\d)\d{15,19}[Xx]?(?!\d)", "[敏感号码已脱敏]", value)
|
|
|
|
content = content.model_copy(update={
|
|
"text": redact(output),
|
|
"source_references": tuple(ref.model_copy(update={
|
|
"title": redact(ref.title) if ref.title else None,
|
|
}) for ref in content.source_references),
|
|
})
|
|
return result.model_copy(update={"result": content})
|