相对第一版 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(含失败关闭反证)。
128 lines
5.4 KiB
Python
128 lines
5.4 KiB
Python
from datetime import UTC, datetime
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.infrastructure.db import SessionFactory
|
|
from app.model.configuration import (
|
|
AgentIntentConfig,
|
|
ConfigRelease,
|
|
PlatformConfigItem,
|
|
PromptTemplateVersion,
|
|
)
|
|
from app.service.intent_classifier import IntentConfigEntry
|
|
|
|
|
|
class RuntimeConfigService:
|
|
"""Reads only configuration rows bound to the caller's released version."""
|
|
|
|
def __init__(self, session: AsyncSession) -> None:
|
|
self.session = session
|
|
|
|
async def prompt(
|
|
self, release_id: int, prompt_code: str, task_type: str, agent_type: str | None
|
|
) -> PromptTemplateVersion | None:
|
|
result = await self.session.scalar(
|
|
select(PromptTemplateVersion).where(
|
|
PromptTemplateVersion.release_id == release_id,
|
|
PromptTemplateVersion.prompt_code == prompt_code,
|
|
PromptTemplateVersion.task_type == task_type,
|
|
(PromptTemplateVersion.agent_type == agent_type)
|
|
| PromptTemplateVersion.agent_type.is_(None),
|
|
)
|
|
)
|
|
return result
|
|
|
|
async def intent(self, agent_type: str, intent_code: str) -> AgentIntentConfig | None:
|
|
result = await self.session.scalar(
|
|
select(AgentIntentConfig).where(
|
|
AgentIntentConfig.agent_type == agent_type,
|
|
AgentIntentConfig.intent_code == intent_code,
|
|
AgentIntentConfig.status == "active",
|
|
)
|
|
)
|
|
return result
|
|
|
|
async def active_intents(self, agent_type: str) -> tuple[IntentConfigEntry, ...]:
|
|
"""读取某 Agent 当前生效的意图配置,供意图分类链路使用。
|
|
|
|
生效判定与 `intent()` 一致:`status='active'`;另外尊重 `effective_at/expire_at`
|
|
的有效期窗口(未填写视为立即生效、不过期)。该表通过生成列唯一键
|
|
`uk_intent_config_active_one` 保证同一 `agent_type:intent_code` 最多一个 active
|
|
版本,因此按 intent_code 匹配不会歧义;仍按 `priority` 排序以保证结果稳定。
|
|
"""
|
|
now = datetime.now(UTC).replace(tzinfo=None)
|
|
rows = await self.session.scalars(
|
|
select(AgentIntentConfig)
|
|
.where(
|
|
AgentIntentConfig.agent_type == agent_type,
|
|
AgentIntentConfig.status == "active",
|
|
(AgentIntentConfig.effective_at.is_(None))
|
|
| (AgentIntentConfig.effective_at <= now),
|
|
(AgentIntentConfig.expire_at.is_(None)) | (AgentIntentConfig.expire_at > now),
|
|
)
|
|
.order_by(AgentIntentConfig.priority, AgentIntentConfig.intent_code)
|
|
)
|
|
return tuple(self._entry(row) for row in rows)
|
|
|
|
@staticmethod
|
|
def _entry(row: AgentIntentConfig) -> IntentConfigEntry:
|
|
return IntentConfigEntry(
|
|
intent_code=row.intent_code,
|
|
intent_name=row.intent_name or "",
|
|
description=row.description,
|
|
examples=tuple(str(item) for item in (row.examples or ())),
|
|
classifier_instruction=row.classifier_instruction,
|
|
confidence_threshold=float(row.confidence_threshold),
|
|
)
|
|
|
|
async def allowed_tools(
|
|
self, release_id: int, agent_type: str, intent_code: str
|
|
) -> tuple[str, ...]:
|
|
config_key = f"{agent_type}:{intent_code}"
|
|
item = await self.session.scalar(
|
|
select(PlatformConfigItem).where(
|
|
PlatformConfigItem.release_id == release_id,
|
|
PlatformConfigItem.namespace == "agent_tools",
|
|
PlatformConfigItem.config_key == config_key,
|
|
)
|
|
)
|
|
if item is None:
|
|
return ()
|
|
raw_tools = item.value_json.get("allowed_tools", [])
|
|
if not isinstance(raw_tools, list) or not all(isinstance(tool, str) for tool in raw_tools):
|
|
raise ValueError("invalid tool whitelist configuration")
|
|
return tuple(raw_tools)
|
|
|
|
async def fund_quote(self, release_id: int) -> dict[str, object]:
|
|
"""读取已发布行情配置;缺失时返回空映射,由 Service 使用安全默认值。"""
|
|
item = await self.session.scalar(
|
|
select(PlatformConfigItem).where(
|
|
PlatformConfigItem.release_id == release_id,
|
|
PlatformConfigItem.namespace == "fund_market",
|
|
PlatformConfigItem.config_key == "default",
|
|
)
|
|
)
|
|
return item.value_json if item is not None else {}
|
|
|
|
|
|
async def load_fund_quote_config() -> dict[str, object]:
|
|
"""读取当前激活行情配置;配置中心不可用时交给调用方使用默认值。"""
|
|
async with SessionFactory() as session:
|
|
release = await session.scalar(
|
|
select(ConfigRelease).where(ConfigRelease.status == "active")
|
|
)
|
|
if release is None:
|
|
return {}
|
|
return await RuntimeConfigService(session).fund_quote(release.id)
|
|
|
|
|
|
async def load_active_intent_configs(agent_type: str) -> tuple[IntentConfigEntry, ...]:
|
|
"""意图分类链路的运行期配置装载器:只读 `agent_intent_config` 的 active 行。
|
|
|
|
该表不绑定 `config_release`(没有 `release_id` 外键),因此这里按 Agent 直接读取;
|
|
没有配置时返回空元组,分类退化为代码声明的意图清单——**行为与接入前一致**。
|
|
"""
|
|
async with SessionFactory() as session:
|
|
return await RuntimeConfigService(session).active_intents(agent_type)
|