相对第一版 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(含失败关闭反证)。
147 lines
5.9 KiB
Python
147 lines
5.9 KiB
Python
"""统一意图分类出口,业务 Agent 不得自行解析模型分类结果。
|
||
|
||
运行期可选的配置来源是 `agent_intent_config` 中 `status='active'` 的行:装载后只用于
|
||
**增强分类提示与置信度阈值**,不改变任何既有契约——仍然是严格 JSON 输出、格式违约与
|
||
未声明意图一律失败关闭、意图必须落在 `AgentDefinition.supported_intents` 内、
|
||
`needs_clarification = confidence < 阈值`。
|
||
"""
|
||
|
||
import json
|
||
from collections.abc import Awaitable, Callable
|
||
from typing import Any, Protocol
|
||
|
||
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
||
|
||
from app.core.contracts import IntentResult
|
||
from app.core.errors import RecoverableAgentError, ValidationAgentError
|
||
from app.service.model_gateway import ModelGenerationService
|
||
|
||
|
||
class IntentEndpointResolver(Protocol):
|
||
async def resolve(self, *, agent_type: str, task_type: str) -> list[Any]: ...
|
||
|
||
|
||
class IntentConfigEntry(BaseModel):
|
||
"""`agent_intent_config` 生效行在分类链路上的投影(只带分类用得到的字段)。"""
|
||
|
||
model_config = ConfigDict(frozen=True)
|
||
|
||
intent_code: str = Field(min_length=1, max_length=64)
|
||
intent_name: str = Field(default="", max_length=128)
|
||
description: str | None = Field(default=None, max_length=500)
|
||
examples: tuple[str, ...] = ()
|
||
classifier_instruction: str | None = None
|
||
confidence_threshold: float = Field(default=0.6, ge=0, le=1)
|
||
|
||
|
||
# 装载器按 `agent_type` 读取当前生效的意图配置;无配置时返回空元组。
|
||
IntentConfigLoader = Callable[[str], Awaitable[tuple[IntentConfigEntry, ...]]]
|
||
|
||
|
||
class _IntentPayload(BaseModel):
|
||
model_config = ConfigDict(extra="forbid")
|
||
|
||
intent: str = Field(min_length=1, max_length=64)
|
||
confidence: float = Field(ge=0, le=1)
|
||
|
||
|
||
class IntentClassifier:
|
||
"""使用已路由模型输出严格 JSON,并绑定 Agent 声明的意图集合。"""
|
||
|
||
def __init__(
|
||
self,
|
||
model_service: ModelGenerationService,
|
||
*,
|
||
threshold: float = 0.65,
|
||
config_loader: IntentConfigLoader | None = None,
|
||
) -> None:
|
||
if not 0 <= threshold <= 1:
|
||
raise ValueError("intent threshold must be between 0 and 1")
|
||
self.model_service = model_service
|
||
self.threshold = threshold
|
||
self._config_loader = config_loader
|
||
|
||
@property
|
||
def config_loader(self) -> IntentConfigLoader | None:
|
||
"""暴露装载器便于装配自检(生产装配必须注入,测试可缺省)。"""
|
||
return self._config_loader
|
||
|
||
async def classify(
|
||
self,
|
||
*,
|
||
message: str,
|
||
supported_intents: tuple[str, ...],
|
||
endpoints: list[Any],
|
||
agent_type: str | None = None,
|
||
) -> IntentResult:
|
||
if not message.strip():
|
||
raise ValidationAgentError("待分类消息不能为空")
|
||
if not supported_intents:
|
||
raise ValidationAgentError("Agent 未声明支持的意图")
|
||
# 只认 AgentDefinition 声明过的意图:配置里多出来的意图既不进提示,也不放宽校验。
|
||
loaded = await self._load(agent_type)
|
||
configured = tuple(
|
||
entry for entry in loaded if entry.intent_code in supported_intents
|
||
)
|
||
prompt = self._build_prompt(message, supported_intents, configured)
|
||
execution = await self.model_service.generate(endpoints, prompt)
|
||
payload = self._parse(execution.text)
|
||
if payload.intent not in supported_intents:
|
||
raise ValidationAgentError("模型返回了未声明的意图")
|
||
return IntentResult(
|
||
intent=payload.intent,
|
||
confidence=payload.confidence,
|
||
needs_clarification=payload.confidence
|
||
< self._threshold_for(payload.intent, configured),
|
||
)
|
||
|
||
async def _load(self, agent_type: str | None) -> tuple[IntentConfigEntry, ...]:
|
||
if self._config_loader is None or agent_type is None:
|
||
return ()
|
||
return await self._config_loader(agent_type)
|
||
|
||
def _threshold_for(self, intent: str, configured: tuple[IntentConfigEntry, ...]) -> float:
|
||
"""阈值语义不变(confidence < 阈值 → 需澄清),阈值取值优先生效配置。"""
|
||
for entry in configured:
|
||
if entry.intent_code == intent:
|
||
return entry.confidence_threshold
|
||
return self.threshold
|
||
|
||
@staticmethod
|
||
def _build_prompt(
|
||
message: str,
|
||
supported_intents: tuple[str, ...],
|
||
configured: tuple[IntentConfigEntry, ...],
|
||
) -> str:
|
||
lines = [
|
||
"请仅输出 JSON,不要 Markdown。字段必须为 intent 和 confidence。",
|
||
f"intent 只能从 {list(supported_intents)!r} 中选择,confidence 为 0 到 1 的数字。",
|
||
]
|
||
if configured:
|
||
lines.append("平台配置的意图说明:")
|
||
for entry in configured:
|
||
detail = f"- {entry.intent_code}"
|
||
if entry.intent_name:
|
||
detail += f"({entry.intent_name})"
|
||
if entry.description:
|
||
detail += f":{entry.description}"
|
||
if entry.examples:
|
||
detail += f";示例:{' / '.join(entry.examples)}"
|
||
lines.append(detail)
|
||
if entry.classifier_instruction:
|
||
lines.append(f" 分类要求:{entry.classifier_instruction}")
|
||
lines.append(f"用户消息:{message}")
|
||
return "\n".join(lines)
|
||
|
||
@staticmethod
|
||
def _parse(text: str) -> _IntentPayload:
|
||
candidate = text.strip()
|
||
if candidate.startswith("```"):
|
||
candidate = candidate.removeprefix("```")
|
||
candidate = candidate.removeprefix("json").removesuffix("```").strip()
|
||
try:
|
||
value = json.loads(candidate)
|
||
return _IntentPayload.model_validate(value)
|
||
except (json.JSONDecodeError, ValidationError, TypeError) as exc:
|
||
raise RecoverableAgentError("模型意图输出不是有效 JSON") from exc
|