Files
group_fqcd_jr/app/service/runtime_config_service.py
lzf_0626 13bab7c3d0 feat: 客服 Agent 端到端跑通(知识直返 + 答不了引导人工客服)
按业务方确定的取向实现:金融场景确定性优先,能溯源到公司资料的才答,答不了就
引导客户拨打客服热线,绝不用模型猜答案。端到端验收 8/8 通过。

新增:
- app/service/knowledge_search_service.py:知识检索。未复用记忆的 VectorMemoryAdapter
  是因为它只返回 (memory_uuid, score),会丢掉知识块的标题与正文,而客服回答必须能把
  原文与出处一起交付。检索失败一律返回 degraded 而不抛异常,由 Agent 走兜底。
- app/service/knowledge_tool.py + app/core/knowledge_contracts.py:只读工具 search_knowledge。
  走 ToolExecutor 而不是让 Agent 直接持有检索服务,是为了让白名单、权限、审计、超时
  都归基座统一管理;工具只读也符合 ToolRegistry 的硬约束。复用既有权限码
  knowledge:reference:read(customer 角色已具备),不新增权限点。
- app/service/agent/implementations/customer_service.py:Agent 本体,刻意保持薄——
  意图分发 + 四条出口(faq/产品/政策直返、闲聊走模型、其余与异常引导人工)。
  直接返回知识原文而不经模型改写,答案的字面内容全部来自公司已发布资料。
- tools/publish_customer_service_config.py:发布意图工具白名单。
- tools/customer_service_check.py:端到端验收(8 个用例,含越界请求与知识库外问题)。

装配:
- bootstrap 新增 get_knowledge_search_service 工厂,注册 search_knowledge 工具与
  customer_service Agent。
- runtime_config_service 新增 load_active_prompt:提示词绑定 release_id,按当前生效
  版本读取,未发布时回落代码默认值。闲聊话术因此可审核、可回滚,不必改代码发版。

过程中发现并处理的三个问题:
1. 自造 source_references 被基座合规闸门拒绝。governance.review_output 只接受
   「本次召回的记忆」与「本次成功调用的工具」两类引用(用于防止伪造来源),
   knowledge 类型会被判非法并使整个 run 失败。处理方式是**不放开那道校验**,
   而把知识出处(文件标题与内部编号)写进正文,source_references 交给基座自动附加。
2. 发布配置是整版本替换语义:新版本会清空旧版本的全部配置项。若只发客服白名单,
   示例 Agent 的 fund_query_demo:fund_quote 会被静默清空。故发布脚本先读取当前生效
   版本的全部配置项并原样继承,再追加新增项。
3. 验收脚本自身两处自伤:打印 emoji 触发 GBK UnicodeEncodeError、以及读错结果字段
   (RunQueryService 返回的答案键是 content 不是 text)。

已知缺口(未修,已记录):
- CoreResult.transfer_required 未持久化:conversation_message 不存该标记,
  API 读不到"本次是否引导了人工"。当前靠正文里的固定话术判断。
- 知识块引用(source_type=knowledge)尚未启用,需先让 ToolExecutor 把工具返回的
  doc_id 登记为本次可引用来源。

验证:ruff 通过、mypy 107 文件无错、unit+contract 447 passed;
tools/customer_service_check.py 8/8 通过(含越界请求、投诉、知识库外问题三类
必须引导人工的场景,以及 7 个零容忍负面词零命中)。
2026-09-10 20:22:42 +08:00

150 lines
6.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)
async def load_active_prompt(
prompt_code: str, task_type: str, agent_type: str
) -> PromptTemplateVersion | None:
"""读取当前生效版本里的提示词;没有 active 版本或没有该提示词时返回 None。
`prompt_template_version` 绑定 `release_id`,所以必须先定位 active 的 `config_release`
——这也正是「提示词变更要经过审核与发布」的落地方式:改话术走发布流程,而不是改代码。
返回 None 是**正常路径**而非异常:调用方(Agent)据此回落到代码内置的默认提示词,
保证即使配置中心还没发布过这条提示词,功能也能工作。
"""
async with SessionFactory() as session:
release = await session.scalar(
select(ConfigRelease).where(ConfigRelease.status == "active")
)
if release is None:
return None
return await RuntimeConfigService(session).prompt(
release.id, prompt_code, task_type, agent_type
)