feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持
This commit is contained in:
1 parent
ac4262cd75
commit
c8ce77199e
183 files changed
+11690
-2300
No files matched your search
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/__init__.py
|
||||
|
||||
用途:Agent 注册表包入口,导出 Catalog 与 Resolver 公共 API。
|
||||
依赖:agent_registry.catalog、agent_registry.resolver、agent_registry.backfill_mapping。
|
||||
逻辑:Admin type-catalog、聊天分发、回填脚本均通过本包访问归一化能力。
|
||||
"""
|
||||
|
||||
from app.services.agent_registry.backfill_mapping import infer_registry_fields_from_legacy
|
||||
from app.services.agent_registry.catalog import (
|
||||
AGENT_TYPE_CATALOG,
|
||||
get_catalog_entry,
|
||||
list_type_catalog,
|
||||
)
|
||||
from app.services.agent_registry.resolver import (
|
||||
DEFAULT_CAPABILITIES,
|
||||
normalize_capabilities,
|
||||
resolve_agent_code,
|
||||
resolve_conversation_mode,
|
||||
resolve_capabilities,
|
||||
resolve_handler,
|
||||
resolve_handler_for_agent_code,
|
||||
resolve_handler_key,
|
||||
resolve_runtime_provider,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'AGENT_TYPE_CATALOG',
|
||||
'DEFAULT_CAPABILITIES',
|
||||
'get_catalog_entry',
|
||||
'infer_registry_fields_from_legacy',
|
||||
'list_type_catalog',
|
||||
'normalize_capabilities',
|
||||
'resolve_agent_code',
|
||||
'resolve_conversation_mode',
|
||||
'resolve_capabilities',
|
||||
'resolve_handler',
|
||||
'resolve_handler_for_agent_code',
|
||||
'resolve_handler_key',
|
||||
'resolve_runtime_provider',
|
||||
]
|
||||
@@ -0,0 +1,302 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/admin_payload.py
|
||||
|
||||
用途:Admin Agent CRUD 载荷校验、列写入与 extra_config 已迁移键清理。
|
||||
依赖:agent_registry.catalog、agent_registry.resolver.normalize_capabilities。
|
||||
逻辑:agent_service.create/update 调用;校验 agent_code Catalog 与 provider 枚举。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent
|
||||
from app.services.agent_registry.catalog import get_catalog_entry, list_agent_type_codes
|
||||
from app.services.agent_registry.catalog_loader import (
|
||||
coerce_manifest_boolean,
|
||||
get_dify_required_providers,
|
||||
get_platform_enum_set,
|
||||
)
|
||||
from app.services.agent_registry.catalog_validation import (
|
||||
apply_catalog_capabilities,
|
||||
default_capabilities_copy,
|
||||
normalize_handler_config,
|
||||
validate_required_fields,
|
||||
)
|
||||
from app.services.agent_registry.content_profiles import VALID_CONTENT_PROFILES
|
||||
from app.services.agent_registry.intent_routes import validate_intent_routes
|
||||
from app.services.agent_registry.resolver import normalize_capabilities
|
||||
|
||||
# 曾 mirror 到 extra_config 的 Registry 键;Admin save 时清理(保留 training_* 等实验字段)。
|
||||
MIGRATED_EXTRA_REGISTRY_KEYS = frozenset({
|
||||
'agent_code',
|
||||
'runtime_provider',
|
||||
'conversation_mode',
|
||||
'dify_app_type',
|
||||
'iframe_url',
|
||||
'category',
|
||||
'sub_category',
|
||||
'sort_order',
|
||||
'welcome_message',
|
||||
'suggested_questions_style',
|
||||
'suggested_questions',
|
||||
'capabilities',
|
||||
'tool_run_progress',
|
||||
})
|
||||
|
||||
|
||||
def _strip(value: Any) -> str:
|
||||
return str(value or '').strip()
|
||||
|
||||
|
||||
def _legacy_type_from_provider(runtime_provider: str) -> str:
|
||||
return 'iframe' if runtime_provider == 'iframe' else 'api'
|
||||
|
||||
|
||||
def _parse_capabilities(raw: Any) -> dict[str, bool]:
|
||||
if isinstance(raw, dict):
|
||||
return normalize_capabilities(raw, strict=True)
|
||||
return normalize_capabilities(None, strict=True)
|
||||
|
||||
|
||||
def _parse_is_active(raw: Any, *, default: bool) -> bool:
|
||||
"""Admin is_active 布尔归一化;支持字符串 false/true。"""
|
||||
if raw is None:
|
||||
return default
|
||||
return coerce_manifest_boolean(raw, context='is_active')
|
||||
|
||||
|
||||
def _parse_bound_schedule_task_id(raw: Any) -> int | None:
|
||||
if raw is None or raw == '':
|
||||
return None
|
||||
try:
|
||||
task_id = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('bound_schedule_task_id 必须为有效整数')
|
||||
return task_id if task_id > 0 else None
|
||||
|
||||
|
||||
def _parse_handler_config(
|
||||
raw: Any,
|
||||
*,
|
||||
agent_code: str,
|
||||
existing: dict | None = None,
|
||||
explicit: bool = False,
|
||||
) -> dict | None:
|
||||
"""
|
||||
归一化 handler_config。
|
||||
|
||||
Args:
|
||||
raw: 请求值;None 且 explicit=True 表示显式清空。
|
||||
explicit: True 表示请求体包含 handler_config 键(含 null)。
|
||||
"""
|
||||
if raw is None:
|
||||
if explicit:
|
||||
return normalize_handler_config(agent_code, None)
|
||||
return existing if isinstance(existing, dict) else None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('handler_config 必须为 JSON 对象')
|
||||
if explicit:
|
||||
merged = dict(raw)
|
||||
else:
|
||||
merged = dict(existing or {})
|
||||
merged.update(raw)
|
||||
if 'intent_routes' in raw:
|
||||
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
|
||||
|
||||
ensure_intent_routes_loaded()
|
||||
merged['intent_routes'] = validate_intent_routes(raw.get('intent_routes'))
|
||||
if 'content_profile' in raw:
|
||||
profile = _strip(raw.get('content_profile'))
|
||||
if profile and profile not in VALID_CONTENT_PROFILES:
|
||||
raise ValidationError(f'无效的 handler_config.content_profile: {profile}')
|
||||
merged['content_profile'] = profile or None
|
||||
return normalize_handler_config(agent_code, merged)
|
||||
|
||||
|
||||
def validate_agent_payload(
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
agent: Agent | None = None,
|
||||
provided_fields: frozenset[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
校验并归一化 Admin Agent 创建/更新载荷。
|
||||
|
||||
Args:
|
||||
data: 请求 JSON(update 时为 merged 载荷)。
|
||||
agent: 更新时的现有 Agent;创建时为 None。
|
||||
provided_fields: 更新时原始请求体包含的键;用于区分未传字段与显式 null。
|
||||
|
||||
Returns:
|
||||
归一化后的字段 dict,供 apply_agent_payload 写入 ORM。
|
||||
|
||||
Raises:
|
||||
ValidationError: agent_code / provider / file_check 绑定等校验失败。
|
||||
"""
|
||||
if not _strip(data.get('name')):
|
||||
raise ValidationError('Name is required')
|
||||
|
||||
valid_runtime_providers = get_platform_enum_set('runtime_providers')
|
||||
valid_conversation_modes = get_platform_enum_set('conversation_modes')
|
||||
valid_dify_app_types = get_platform_enum_set('dify_app_types')
|
||||
valid_suggested_styles = get_platform_enum_set('suggested_questions_styles')
|
||||
dify_required_providers = get_dify_required_providers()
|
||||
|
||||
agent_code = _strip(data.get('agent_code')) or (agent.agent_code if agent else 'generic')
|
||||
if agent_code not in list_agent_type_codes():
|
||||
raise ValidationError(f'无效的应用类型 agent_code: {agent_code}')
|
||||
|
||||
runtime_provider = _strip(data.get('runtime_provider')) or (agent.runtime_provider if agent else '')
|
||||
if not runtime_provider:
|
||||
catalog = get_catalog_entry(agent_code) or {}
|
||||
runtime_provider = _strip(catalog.get('runtime_provider_default')) or 'dify'
|
||||
if runtime_provider not in valid_runtime_providers:
|
||||
raise ValidationError(f'无效的 runtime_provider: {runtime_provider}')
|
||||
|
||||
conversation_mode = _strip(data.get('conversation_mode')) or (agent.conversation_mode if agent else '')
|
||||
if not conversation_mode:
|
||||
catalog = get_catalog_entry(agent_code) or {}
|
||||
conversation_mode = _strip(catalog.get('conversation_mode_default')) or 'chat'
|
||||
if conversation_mode not in valid_conversation_modes:
|
||||
raise ValidationError(f'无效的 conversation_mode: {conversation_mode}')
|
||||
|
||||
dify_app_type = _strip(data.get('dify_app_type')) or (getattr(agent, 'dify_app_type', None) if agent else 'chatflow') or 'chatflow'
|
||||
if dify_app_type not in valid_dify_app_types:
|
||||
dify_app_type = 'chatflow'
|
||||
|
||||
dify_app_id = _strip(data.get('dify_app_id')) or (agent.dify_app_id if agent else '')
|
||||
if runtime_provider in dify_required_providers and not dify_app_id:
|
||||
raise ValidationError('runtime_provider 含 dify 时 dify_app_id 必填')
|
||||
|
||||
iframe_url = _strip(data.get('iframe_url')) or (getattr(agent, 'iframe_url', None) if agent else None)
|
||||
if runtime_provider == 'iframe' and not iframe_url:
|
||||
raise ValidationError('runtime_provider=iframe 时 iframe_url 必填')
|
||||
|
||||
bound_schedule_task_id = data.get('bound_schedule_task_id', getattr(agent, 'bound_schedule_task_id', None) if agent else None)
|
||||
bound_schedule_task_id = _parse_bound_schedule_task_id(bound_schedule_task_id)
|
||||
|
||||
capabilities = _parse_capabilities(data.get('capabilities', getattr(agent, 'capabilities', None) if agent else None))
|
||||
capabilities = apply_catalog_capabilities(agent_code, capabilities)
|
||||
validate_required_fields(agent_code, bound_schedule_task_id=bound_schedule_task_id)
|
||||
|
||||
handler_explicit = (
|
||||
'handler_config' in provided_fields
|
||||
if provided_fields is not None
|
||||
else 'handler_config' in data
|
||||
)
|
||||
existing_handler = (
|
||||
getattr(agent, 'handler_config', None)
|
||||
if agent and isinstance(getattr(agent, 'handler_config', None), dict)
|
||||
else None
|
||||
)
|
||||
handler_config = _parse_handler_config(
|
||||
data.get('handler_config') if handler_explicit else None,
|
||||
agent_code=agent_code,
|
||||
existing=existing_handler,
|
||||
explicit=handler_explicit,
|
||||
)
|
||||
if handler_config is not None and not isinstance(handler_config, dict):
|
||||
raise ValidationError('handler_config 必须为 JSON 对象')
|
||||
|
||||
suggested_style = _strip(data.get('suggested_questions_style')) or (
|
||||
getattr(agent, 'suggested_questions_style', None) if agent else 'plain'
|
||||
) or 'plain'
|
||||
if suggested_style not in valid_suggested_styles:
|
||||
suggested_style = 'plain'
|
||||
|
||||
suggested_questions = data.get('suggested_questions', getattr(agent, 'suggested_questions', None) if agent else None)
|
||||
if suggested_questions is not None and not isinstance(suggested_questions, list):
|
||||
raise ValidationError('suggested_questions 必须为数组')
|
||||
|
||||
sort_raw = data.get('sort_order', getattr(agent, 'sort_order', 0) if agent else 0)
|
||||
try:
|
||||
sort_order = int(sort_raw)
|
||||
except (TypeError, ValueError):
|
||||
sort_order = 0
|
||||
if sort_order < 0:
|
||||
sort_order = 0
|
||||
|
||||
file_upload_policy = data.get('file_upload_policy', getattr(agent, 'file_upload_policy', None) if agent else None)
|
||||
if file_upload_policy is not None and not isinstance(file_upload_policy, dict):
|
||||
raise ValidationError('file_upload_policy 必须为 JSON 对象')
|
||||
|
||||
is_active_default = agent.is_active if agent else True
|
||||
is_active = (
|
||||
_parse_is_active(data.get('is_active'), default=is_active_default)
|
||||
if 'is_active' in data
|
||||
else is_active_default
|
||||
)
|
||||
|
||||
return {
|
||||
'name': _strip(data.get('name')),
|
||||
'description': data.get('description'),
|
||||
'icon_url': data.get('icon_url'),
|
||||
'is_active': is_active,
|
||||
'dify_app_id': dify_app_id or None,
|
||||
'dify_api_key': _strip(data.get('dify_api_key')) or None,
|
||||
'api_base_url': _strip(data.get('api_base_url')) or None,
|
||||
'type': _legacy_type_from_provider(runtime_provider),
|
||||
'agent_code': agent_code,
|
||||
'runtime_provider': runtime_provider,
|
||||
'conversation_mode': conversation_mode,
|
||||
'dify_app_type': dify_app_type,
|
||||
'iframe_url': iframe_url or None,
|
||||
'category': _strip(data.get('category')) or None,
|
||||
'sub_category': _strip(data.get('sub_category')) or None,
|
||||
'sort_order': sort_order,
|
||||
'welcome_message': data.get('welcome_message'),
|
||||
'suggested_questions_style': suggested_style,
|
||||
'suggested_questions': suggested_questions,
|
||||
'capabilities': capabilities,
|
||||
'file_upload_policy': file_upload_policy,
|
||||
'bound_schedule_task_id': bound_schedule_task_id,
|
||||
'handler_config': handler_config,
|
||||
'extra_config': data.get('extra_config') if isinstance(data.get('extra_config'), dict) else None,
|
||||
}
|
||||
|
||||
|
||||
def apply_agent_payload(agent: Agent, normalized: dict[str, Any]) -> None:
|
||||
"""
|
||||
将归一化载荷写入 Agent ORM,并清理 extra_config 中已迁移 Registry 键。
|
||||
|
||||
Args:
|
||||
agent: 目标 Agent 实例。
|
||||
normalized: validate_agent_payload 的返回值。
|
||||
"""
|
||||
column_fields = (
|
||||
'name', 'description', 'icon_url', 'is_active', 'dify_app_id', 'api_base_url', 'type',
|
||||
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url',
|
||||
'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style',
|
||||
'suggested_questions', 'capabilities', 'file_upload_policy', 'bound_schedule_task_id',
|
||||
'handler_config',
|
||||
)
|
||||
for key in column_fields:
|
||||
if key in normalized:
|
||||
setattr(agent, key, normalized[key])
|
||||
|
||||
if normalized.get('dify_api_key'):
|
||||
agent.dify_api_key = normalized['dify_api_key']
|
||||
|
||||
if normalized.get('extra_config') is not None:
|
||||
agent.extra_config = normalized['extra_config']
|
||||
|
||||
strip_migrated_extra_registry_keys(agent)
|
||||
|
||||
|
||||
def strip_migrated_extra_registry_keys(agent: Agent) -> None:
|
||||
"""
|
||||
从 extra_config 移除已迁移至结构化列的 mirror 键。
|
||||
|
||||
保留 training_* 等未结构化实验字段;不再向 extra 写入 Registry 列。
|
||||
"""
|
||||
extra = dict(agent.extra_config or {}) if isinstance(agent.extra_config, dict) else {}
|
||||
for key in MIGRATED_EXTRA_REGISTRY_KEYS:
|
||||
extra.pop(key, None)
|
||||
agent.extra_config = extra or None
|
||||
|
||||
|
||||
def default_capabilities() -> dict[str, bool]:
|
||||
"""返回 capabilities 默认 schema 副本。"""
|
||||
return default_capabilities_copy()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/admin_schema.py
|
||||
|
||||
用途:组装 Admin Agent Registry 完整 schema(平台枚举 + Catalog + handler_config schema)。
|
||||
依赖:catalog_loader、content_profiles。
|
||||
逻辑:GET /api/admin/agents/schema 返回本模块 build_agent_registry_schema()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_registry.catalog_loader import (
|
||||
build_agent_type_catalog,
|
||||
get_default_capabilities,
|
||||
get_platform_config,
|
||||
get_tool_run_progress_defaults,
|
||||
list_type_catalog,
|
||||
)
|
||||
from app.services.agent_registry.content_profiles import list_content_profiles
|
||||
|
||||
|
||||
def build_agent_registry_schema() -> dict[str, Any]:
|
||||
"""
|
||||
构建 Admin 表单权威 schema。
|
||||
|
||||
Returns:
|
||||
platform、agent_types、handler_config_schemas、content_profiles 预览键。
|
||||
"""
|
||||
platform = get_platform_config()
|
||||
catalog = build_agent_type_catalog()
|
||||
handler_config_schemas = {
|
||||
code: deepcopy_schema(entry.get('handler_config_schema'))
|
||||
for code, entry in catalog.items()
|
||||
if isinstance(entry.get('handler_config_schema'), dict)
|
||||
}
|
||||
agent_types = []
|
||||
for item in list_type_catalog():
|
||||
code = item.get('agent_code')
|
||||
entry = catalog.get(str(code or '')) or {}
|
||||
agent_types.append({
|
||||
**item,
|
||||
'required_fields': list(entry.get('required_fields') or []),
|
||||
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
|
||||
})
|
||||
|
||||
return {
|
||||
'platform': {
|
||||
'runtime_providers': list(platform.get('runtime_providers') or []),
|
||||
'conversation_modes': list(platform.get('conversation_modes') or []),
|
||||
'dify_app_types': list(platform.get('dify_app_types') or []),
|
||||
'suggested_questions_styles': list(platform.get('suggested_questions_styles') or []),
|
||||
'default_capabilities': get_default_capabilities(),
|
||||
'tool_run_progress_defaults': get_tool_run_progress_defaults(),
|
||||
},
|
||||
'agent_types': agent_types,
|
||||
'handler_config_schemas': handler_config_schemas,
|
||||
'content_profile_keys': [item['key'] for item in list_content_profiles()],
|
||||
}
|
||||
|
||||
|
||||
def deepcopy_schema(value: Any) -> Any:
|
||||
import copy
|
||||
return copy.deepcopy(value) if value is not None else {}
|
||||
@@ -0,0 +1,211 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/backfill_mapping.py
|
||||
|
||||
用途:存量 Agent 一次性回填映射(extra_config / type / 名称 → Registry 结构化列)。
|
||||
依赖:agent_registry.catalog、agent_registry.resolver.normalize_capabilities。
|
||||
逻辑:仅 backfill_agent_registry.py 调用;运行时 resolver 不做名称/能力启发式。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
# 回填专用:历史 Agent 名称 → handler_config.intent_routes key(迁移映射,非运行时 dispatch)。
|
||||
LEGACY_INTENT_ROUTE_KEYS = {
|
||||
'hr_leave': 'hr_leave_sql',
|
||||
'plm': 'plm_oracle',
|
||||
'maintenance': 'maintenance_chat',
|
||||
'text2sql': 'text2sql',
|
||||
}
|
||||
from app.services.agent_registry.content_profiles import (
|
||||
infer_content_profile_from_intent_routes,
|
||||
merge_profile_defaults_into_fields,
|
||||
)
|
||||
from app.services.agent_registry.resolver import normalize_capabilities
|
||||
|
||||
TRAINING_CONTENT_PROFILE = 'training'
|
||||
|
||||
|
||||
def _extra_dict(agent) -> dict[str, Any]:
|
||||
extra = getattr(agent, 'extra_config', None)
|
||||
return extra if isinstance(extra, dict) else {}
|
||||
|
||||
|
||||
def _strip_str(value: Any) -> str:
|
||||
return str(value or '').strip()
|
||||
|
||||
|
||||
def _legacy_capabilities_list(extra: dict[str, Any]) -> list[str]:
|
||||
caps = extra.get('capabilities')
|
||||
if isinstance(caps, list):
|
||||
return [str(item).strip() for item in caps if str(item).strip()]
|
||||
return []
|
||||
|
||||
|
||||
def _declares_tool_run_progress(extra: dict[str, Any]) -> bool:
|
||||
if 'tool_run_progress' in _legacy_capabilities_list(extra):
|
||||
return True
|
||||
return isinstance(extra.get('tool_run_progress'), dict)
|
||||
|
||||
|
||||
def _name_implies_shipping_notice(agent) -> bool:
|
||||
"""回填专用:历史货代 Agent 名称 → agent_code=shipping_notice。"""
|
||||
agent_name = _strip_str(getattr(agent, 'name', None))
|
||||
if agent_name == '货代发货通知 Agent':
|
||||
return True
|
||||
normalized_name = agent_name.replace(' ', '')
|
||||
return '发货通知' in normalized_name and 'Agent' in normalized_name
|
||||
|
||||
|
||||
def _name_implies_maintenance_chat(agent) -> bool:
|
||||
agent_name = _strip_str(getattr(agent, 'name', None))
|
||||
return agent_name == '设备维保助手' or ('设备维保' in agent_name and '助手' in agent_name)
|
||||
|
||||
|
||||
def _infer_intent_routes_from_name(agent) -> list[str]:
|
||||
"""回填专用:历史 Agent 名称 → handler_config.intent_routes。"""
|
||||
name = _strip_str(getattr(agent, 'name', None))
|
||||
routes: list[str] = []
|
||||
if name == '通用入口':
|
||||
routes.extend([LEGACY_INTENT_ROUTE_KEYS['hr_leave'], LEGACY_INTENT_ROUTE_KEYS['plm']])
|
||||
elif name == '人事规章':
|
||||
routes.append(LEGACY_INTENT_ROUTE_KEYS['hr_leave'])
|
||||
elif name == '生产sop':
|
||||
routes.append(LEGACY_INTENT_ROUTE_KEYS['plm'])
|
||||
elif _name_implies_maintenance_chat(agent):
|
||||
routes.append(LEGACY_INTENT_ROUTE_KEYS['maintenance'])
|
||||
elif name == '固资管理':
|
||||
routes.append(LEGACY_INTENT_ROUTE_KEYS['text2sql'])
|
||||
from app.services.agent_registry.intent_routes import normalize_intent_routes_list
|
||||
|
||||
return normalize_intent_routes_list(routes)
|
||||
|
||||
|
||||
def _infer_content_profile_from_name(agent) -> str | None:
|
||||
"""回填专用:历史培训 Agent 名称 / extra 开关 → handler_config.content_profile。"""
|
||||
extra = _extra_dict(agent)
|
||||
if extra.get('training_workspace_enabled') in (True, 'true', 'True', 1):
|
||||
return TRAINING_CONTENT_PROFILE
|
||||
name = _strip_str(getattr(agent, 'name', None))
|
||||
if name and re.search(r'(培训|考试|入职)', name):
|
||||
return TRAINING_CONTENT_PROFILE
|
||||
return None
|
||||
|
||||
|
||||
def _capabilities_from_legacy(extra: dict[str, Any], agent_code: str | None = None) -> dict[str, bool]:
|
||||
caps = normalize_capabilities(extra.get('capabilities') if isinstance(extra.get('capabilities'), dict) else None)
|
||||
if _declares_tool_run_progress(extra) or agent_code == 'file_check':
|
||||
caps['task_progress'] = True
|
||||
if isinstance(extra.get('file_upload'), bool):
|
||||
caps['file_upload'] = extra['file_upload']
|
||||
return caps
|
||||
|
||||
|
||||
def _apply_name_based_capabilities(agent, caps: dict[str, bool]) -> dict[str, bool]:
|
||||
"""回填专用:固资管理 Agent 启用 erp_kb capability。"""
|
||||
if _strip_str(getattr(agent, 'name', None)) == '固资管理':
|
||||
caps['erp_kb'] = True
|
||||
return caps
|
||||
|
||||
|
||||
def infer_registry_fields_from_legacy(agent) -> dict[str, Any]:
|
||||
"""
|
||||
按旧字段与运维映射规则推断 Registry 结构化值(仅回填脚本使用)。
|
||||
|
||||
核心逻辑:type=iframe → generic/iframe/embedded;名称含发货通知 → shipping_notice;
|
||||
capabilities 含 tool_run_progress → file_check;其余 type=api → generic/dify/chat。
|
||||
|
||||
Returns:
|
||||
含 agent_code、runtime_provider、conversation_mode、capabilities、bound_schedule_task_id 等键的字典。
|
||||
"""
|
||||
extra = _extra_dict(agent)
|
||||
agent_type = _strip_str(getattr(agent, 'type', None)).lower()
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
|
||||
if agent_type == 'iframe':
|
||||
result['agent_code'] = 'generic'
|
||||
result['runtime_provider'] = 'iframe'
|
||||
result['conversation_mode'] = 'embedded'
|
||||
elif _name_implies_shipping_notice(agent):
|
||||
result['agent_code'] = 'shipping_notice'
|
||||
result['runtime_provider'] = 'hybrid'
|
||||
result['conversation_mode'] = 'task_chat'
|
||||
elif _declares_tool_run_progress(extra):
|
||||
result['agent_code'] = 'file_check'
|
||||
result['runtime_provider'] = 'dify'
|
||||
result['conversation_mode'] = 'task_chat'
|
||||
else:
|
||||
extra_code = _strip_str(extra.get('agent_code'))
|
||||
result['agent_code'] = extra_code or 'generic'
|
||||
result['runtime_provider'] = 'iframe' if agent_type == 'iframe' else 'dify'
|
||||
result['conversation_mode'] = 'embedded' if agent_type == 'iframe' else 'chat'
|
||||
|
||||
extra_code = _strip_str(extra.get('agent_code'))
|
||||
if extra_code and result.get('agent_code') == 'generic':
|
||||
result['agent_code'] = extra_code
|
||||
|
||||
extra_provider = _strip_str(extra.get('runtime_provider'))
|
||||
if extra_provider:
|
||||
result['runtime_provider'] = extra_provider
|
||||
|
||||
extra_mode = _strip_str(extra.get('conversation_mode'))
|
||||
if extra_mode:
|
||||
result['conversation_mode'] = extra_mode
|
||||
|
||||
if _strip_str(extra.get('dify_app_type')):
|
||||
result['dify_app_type'] = _strip_str(extra.get('dify_app_type'))
|
||||
if _strip_str(extra.get('iframe_url')):
|
||||
result['iframe_url'] = _strip_str(extra.get('iframe_url'))
|
||||
if _strip_str(extra.get('category')):
|
||||
result['category'] = _strip_str(extra.get('category'))
|
||||
if _strip_str(extra.get('sub_category')):
|
||||
result['sub_category'] = _strip_str(extra.get('sub_category'))
|
||||
if extra.get('sort_order') is not None:
|
||||
try:
|
||||
result['sort_order'] = int(extra.get('sort_order'))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if _strip_str(extra.get('welcome_message')):
|
||||
result['welcome_message'] = _strip_str(extra.get('welcome_message'))
|
||||
if _strip_str(extra.get('suggested_questions_style')):
|
||||
result['suggested_questions_style'] = _strip_str(extra.get('suggested_questions_style'))
|
||||
if isinstance(extra.get('suggested_questions'), list):
|
||||
result['suggested_questions'] = extra.get('suggested_questions')
|
||||
|
||||
tool_cfg = extra.get('tool_run_progress')
|
||||
if isinstance(tool_cfg, dict):
|
||||
raw_task_id = tool_cfg.get('schedule_task_id', tool_cfg.get('task_id'))
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
if task_id > 0:
|
||||
result['bound_schedule_task_id'] = task_id
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
result['handler_config'] = {
|
||||
key: tool_cfg[key]
|
||||
for key in ('poll_interval_seconds', 'lock_input_when_running', 'type')
|
||||
if key in tool_cfg
|
||||
}
|
||||
|
||||
result['capabilities'] = _apply_name_based_capabilities(
|
||||
agent,
|
||||
_capabilities_from_legacy(extra, result.get('agent_code')),
|
||||
)
|
||||
|
||||
intent_routes = _infer_intent_routes_from_name(agent)
|
||||
content_profile = _infer_content_profile_from_name(agent)
|
||||
if not content_profile and intent_routes:
|
||||
content_profile = infer_content_profile_from_intent_routes(intent_routes)
|
||||
if intent_routes or content_profile:
|
||||
handler_config = dict(result.get('handler_config') or {})
|
||||
if intent_routes:
|
||||
handler_config['intent_routes'] = intent_routes
|
||||
if content_profile:
|
||||
handler_config['content_profile'] = content_profile
|
||||
result['handler_config'] = handler_config
|
||||
if content_profile:
|
||||
merge_profile_defaults_into_fields(result, content_profile)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,56 @@
|
||||
"""␍
|
||||
backend/app/services/agent_registry/catalog.py␍
|
||||
␍
|
||||
用途:Agent 应用类型 Catalog 对外入口(数据来自 catalog_manifest.yaml + 代码 handler 绑定)。␍
|
||||
依赖:catalog_loader、catalog_bindings。␍
|
||||
逻辑:Admin type-catalog / schema API、Resolver、admin_payload 校验均读取本模块。␍
|
||||
"""␍
|
||||
␍
|
||||
from __future__ import annotations␍
|
||||
␍
|
||||
from collections.abc import Iterator, Mapping␍
|
||||
from typing import Any␍
|
||||
␍
|
||||
from app.services.agent_registry.catalog_loader import (␍
|
||||
build_agent_type_catalog,␍
|
||||
clear_catalog_cache,␍
|
||||
get_catalog_entry,␍
|
||||
list_agent_type_codes,␍
|
||||
list_type_catalog,␍
|
||||
)␍
|
||||
␍
|
||||
␍
|
||||
class _AgentTypeCatalogMapping(Mapping[str, dict[str, Any]]):␍
|
||||
"""␍
|
||||
兼容既有 AGENT_TYPE_CATALOG 访问方式;底层统一走 build_agent_type_catalog() 缓存。␍
|
||||
"""␍
|
||||
␍
|
||||
def __getitem__(self, key: str) -> dict[str, Any]:␍
|
||||
catalog = build_agent_type_catalog()␍
|
||||
if key not in catalog:␍
|
||||
raise KeyError(key)␍
|
||||
return catalog[key]␍
|
||||
␍
|
||||
def __contains__(self, key: object) -> bool:␍
|
||||
return key in build_agent_type_catalog()␍
|
||||
␍
|
||||
def __iter__(self) -> Iterator[str]:␍
|
||||
return iter(build_agent_type_catalog())␍
|
||||
␍
|
||||
def __len__(self) -> int:␍
|
||||
return len(build_agent_type_catalog())␍
|
||||
␍
|
||||
def get(self, key: str, default: Any = None) -> Any:␍
|
||||
return build_agent_type_catalog().get(key, default)␍
|
||||
␍
|
||||
␍
|
||||
# 兼容测试与既有 import:非 import 时静态快照,每次访问读同一缓存源。␍
|
||||
AGENT_TYPE_CATALOG: Mapping[str, dict[str, Any]] = _AgentTypeCatalogMapping()␍
|
||||
␍
|
||||
__all__ = [␍
|
||||
'AGENT_TYPE_CATALOG',␍
|
||||
'clear_catalog_cache',␍
|
||||
'get_catalog_entry',␍
|
||||
'list_agent_type_codes',␍
|
||||
'list_type_catalog',␍
|
||||
]␍
|
||||
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/catalog_bindings.py
|
||||
|
||||
用途:agent_code → runtime_handler 代码绑定(须与 HANDLER_REGISTRY 注册一致)。
|
||||
依赖:handlers.registry。
|
||||
逻辑:catalog_loader 合并 manifest 与本文;禁止写入 YAML。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# agent_code → HANDLER_REGISTRY key;纯 Dify 类型不在此声明。
|
||||
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
|
||||
'shipping_notice': 'shipping_notice',
|
||||
'file_check': 'file_check',
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/catalog_loader.py
|
||||
|
||||
用途:加载 catalog_manifest.yaml 并与 runtime_handler 代码绑定合并。
|
||||
依赖:catalog_bindings、PyYAML。
|
||||
逻辑:catalog.py、admin_schema、resolver、admin_payload 校验均经本模块读取权威配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.agent_registry.catalog_bindings import RUNTIME_HANDLER_BINDINGS
|
||||
|
||||
_MANIFEST_PATH = Path(__file__).resolve().parent / 'data' / 'catalog_manifest.yaml'
|
||||
|
||||
|
||||
def coerce_manifest_boolean(value: Any, *, context: str = 'manifest') -> bool:
|
||||
"""
|
||||
归一化 manifest / Catalog 布尔值。
|
||||
|
||||
核心逻辑:显式支持 true/false/1/0 字符串;非法字符串抛 ValidationError。
|
||||
"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
if value in (0, 1):
|
||||
return bool(value)
|
||||
raise ValidationError(f'{context} 布尔字段取值无效')
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in ('true', '1', 'yes', 'on'):
|
||||
return True
|
||||
if normalized in ('false', '0', 'no', 'off', ''):
|
||||
return False
|
||||
raise ValidationError(f'{context} 布尔字段取值无效: {value}')
|
||||
if value is None:
|
||||
return False
|
||||
raise ValidationError(f'{context} 布尔字段取值无效')
|
||||
|
||||
|
||||
def coerce_payload_boolean(value: Any, *, context: str = 'payload', strict: bool = True) -> bool:
|
||||
"""
|
||||
Admin / ORM 载荷布尔归一化。
|
||||
|
||||
Args:
|
||||
value: 原始值。
|
||||
context: 错误上下文。
|
||||
strict: 为 False 时非法值回落 False(读库容错);为 True 时抛 ValidationError。
|
||||
"""
|
||||
try:
|
||||
return coerce_manifest_boolean(value, context=context)
|
||||
except ValidationError:
|
||||
if strict:
|
||||
raise
|
||||
return False
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def load_catalog_manifest() -> dict[str, Any]:
|
||||
"""
|
||||
读取并缓存 YAML manifest。
|
||||
|
||||
Returns:
|
||||
含 platform、agent_types 的 dict。
|
||||
"""
|
||||
raw = yaml.safe_load(_MANIFEST_PATH.read_text(encoding='utf-8'))
|
||||
if not isinstance(raw, dict):
|
||||
raise RuntimeError('catalog_manifest.yaml 格式无效')
|
||||
return raw
|
||||
|
||||
|
||||
def clear_catalog_cache() -> None:
|
||||
"""
|
||||
清空 manifest / catalog 进程内缓存。
|
||||
|
||||
用途:单测隔离、未来 dev 热加载;生产仍建议重启 worker。
|
||||
"""
|
||||
load_catalog_manifest.cache_clear()
|
||||
build_agent_type_catalog.cache_clear()
|
||||
|
||||
|
||||
def get_platform_config() -> dict[str, Any]:
|
||||
"""平台级枚举与默认值(runtime_provider、capabilities 等)。"""
|
||||
platform = load_catalog_manifest().get('platform') or {}
|
||||
return deepcopy(platform) if isinstance(platform, dict) else {}
|
||||
|
||||
|
||||
def get_platform_enum_set(key: str) -> frozenset[str]:
|
||||
"""
|
||||
读取 platform 段 list 枚举为 frozenset。
|
||||
|
||||
Args:
|
||||
key: 如 runtime_providers、conversation_modes。
|
||||
"""
|
||||
platform = get_platform_config()
|
||||
values = platform.get(key) or []
|
||||
if not isinstance(values, list):
|
||||
return frozenset()
|
||||
return frozenset(str(item).strip() for item in values if str(item).strip())
|
||||
|
||||
|
||||
def get_dify_required_providers() -> frozenset[str]:
|
||||
"""需要 dify_app_id 的 runtime_provider 集合(manifest 权威)。"""
|
||||
providers = get_platform_enum_set('dify_required_providers')
|
||||
if providers:
|
||||
return providers
|
||||
return frozenset({'dify', 'hybrid'})
|
||||
|
||||
|
||||
def get_default_capabilities() -> dict[str, bool]:
|
||||
"""capabilities 默认 schema(与 resolver.DEFAULT_CAPABILITIES 对齐)。"""
|
||||
platform = get_platform_config()
|
||||
defaults = platform.get('default_capabilities') or {}
|
||||
result: dict[str, bool] = {}
|
||||
if isinstance(defaults, dict):
|
||||
for key, value in defaults.items():
|
||||
result[str(key)] = coerce_manifest_boolean(
|
||||
value,
|
||||
context=f'platform.default_capabilities.{key}',
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def get_tool_run_progress_defaults() -> dict[str, Any]:
|
||||
"""task_progress 视图默认值(含 progress_type);布尔/整数字段经 coercion。"""
|
||||
platform = get_platform_config()
|
||||
raw = platform.get('tool_run_progress_defaults') or {}
|
||||
if not isinstance(raw, dict):
|
||||
raw = {}
|
||||
progress_type = str(raw.get('progress_type') or 'file_check').strip() or 'file_check'
|
||||
try:
|
||||
poll_interval = int(raw.get('poll_interval_seconds', 2))
|
||||
except (TypeError, ValueError):
|
||||
poll_interval = 2
|
||||
poll_interval = max(1, min(poll_interval, 30))
|
||||
lock_input = coerce_manifest_boolean(
|
||||
raw.get('lock_input_when_running', True),
|
||||
context='tool_run_progress_defaults.lock_input_when_running',
|
||||
)
|
||||
return {
|
||||
'progress_type': progress_type,
|
||||
'poll_interval_seconds': poll_interval,
|
||||
'lock_input_when_running': lock_input,
|
||||
}
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
合并 manifest agent_types 与 RUNTIME_HANDLER_BINDINGS(进程内缓存)。
|
||||
|
||||
Returns:
|
||||
agent_code → Catalog 条目(含 runtime_handler)。
|
||||
"""
|
||||
manifest = load_catalog_manifest()
|
||||
raw_types = manifest.get('agent_types') or {}
|
||||
if not isinstance(raw_types, dict):
|
||||
return {}
|
||||
catalog: dict[str, dict[str, Any]] = {}
|
||||
for code, entry in raw_types.items():
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
merged = deepcopy(entry)
|
||||
merged['runtime_handler'] = RUNTIME_HANDLER_BINDINGS.get(str(code)) or None
|
||||
if isinstance(merged.get('forced_capabilities'), dict):
|
||||
merged['forced_capabilities'] = {
|
||||
str(cap_key): coerce_manifest_boolean(
|
||||
cap_value,
|
||||
context=f'agent_types.{code}.forced_capabilities.{cap_key}',
|
||||
)
|
||||
for cap_key, cap_value in merged['forced_capabilities'].items()
|
||||
}
|
||||
catalog[str(code)] = merged
|
||||
return catalog
|
||||
|
||||
|
||||
def get_catalog_entry(agent_code: str) -> dict[str, Any] | None:
|
||||
"""按 agent_code 获取 Catalog 条目。"""
|
||||
code = str(agent_code or '').strip()
|
||||
if not code:
|
||||
return None
|
||||
entry = build_agent_type_catalog().get(code)
|
||||
return deepcopy(entry) if entry else None
|
||||
|
||||
|
||||
def list_type_catalog() -> list[dict[str, Any]]:
|
||||
"""Admin 应用类型下拉列表。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
return [
|
||||
{'agent_code': code, **deepcopy(entry)}
|
||||
for code, entry in catalog.items()
|
||||
]
|
||||
|
||||
|
||||
def list_agent_type_codes() -> frozenset[str]:
|
||||
"""已知 agent_code 集合。"""
|
||||
return frozenset(build_agent_type_catalog().keys())
|
||||
@@ -0,0 +1,160 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/catalog_validation.py
|
||||
|
||||
用途:按 Catalog manifest 校验 Agent 载荷(required_fields、forced_capabilities、handler_config)。
|
||||
依赖:catalog_loader、ValidationError。
|
||||
逻辑:admin_payload.validate_agent_payload 委托本模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.agent_registry.catalog_loader import (
|
||||
coerce_manifest_boolean,
|
||||
coerce_payload_boolean,
|
||||
get_catalog_entry,
|
||||
get_default_capabilities,
|
||||
)
|
||||
|
||||
|
||||
def apply_catalog_capabilities(agent_code: str, capabilities: dict[str, bool]) -> dict[str, bool]:
|
||||
"""
|
||||
合并 Catalog forced_capabilities 到 capabilities dict。
|
||||
|
||||
Args:
|
||||
agent_code: 应用类型。
|
||||
capabilities: 归一化后的 capabilities。
|
||||
|
||||
Returns:
|
||||
应用 forced_capabilities 后的副本。
|
||||
"""
|
||||
entry = get_catalog_entry(agent_code) or {}
|
||||
forced = entry.get('forced_capabilities') or {}
|
||||
merged = dict(capabilities)
|
||||
if isinstance(forced, dict):
|
||||
for key, value in forced.items():
|
||||
merged[str(key)] = coerce_manifest_boolean(
|
||||
value,
|
||||
context=f'forced_capabilities.{key}',
|
||||
)
|
||||
return merged
|
||||
|
||||
|
||||
def validate_required_fields(
|
||||
agent_code: str,
|
||||
*,
|
||||
bound_schedule_task_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
校验 Catalog 声明的 required_fields。
|
||||
|
||||
Raises:
|
||||
ValidationError: 必填列缺失。
|
||||
"""
|
||||
entry = get_catalog_entry(agent_code) or {}
|
||||
required = entry.get('required_fields') or []
|
||||
if not isinstance(required, list):
|
||||
return
|
||||
if 'bound_schedule_task_id' in required and not bound_schedule_task_id:
|
||||
raise ValidationError(f'agent_code={agent_code} 时 bound_schedule_task_id 必填')
|
||||
|
||||
|
||||
def _coerce_handler_value(field_schema: dict[str, Any], value: Any) -> Any:
|
||||
field_type = str(field_schema.get('type') or '').strip()
|
||||
if field_type == 'integer':
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('handler_config 字段必须为整数')
|
||||
minimum = field_schema.get('minimum')
|
||||
maximum = field_schema.get('maximum')
|
||||
if minimum is not None and parsed < int(minimum):
|
||||
raise ValidationError(f'handler_config 字段不得小于 {minimum}')
|
||||
if maximum is not None and parsed > int(maximum):
|
||||
raise ValidationError(f'handler_config 字段不得大于 {maximum}')
|
||||
return parsed
|
||||
if field_type == 'boolean':
|
||||
return coerce_manifest_boolean(value, context='handler_config')
|
||||
if field_type == 'string':
|
||||
text = str(value or '').strip()
|
||||
enum = field_schema.get('enum')
|
||||
if isinstance(enum, list) and enum and text and text not in enum:
|
||||
raise ValidationError(f'handler_config 字段取值无效: {text}')
|
||||
return text or None
|
||||
if field_type == 'array':
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError('handler_config 数组字段格式无效')
|
||||
items_schema = field_schema.get('items')
|
||||
item_type = None
|
||||
if isinstance(items_schema, dict):
|
||||
item_type = items_schema.get('type')
|
||||
elif isinstance(items_schema, str):
|
||||
item_type = items_schema
|
||||
if item_type == 'string':
|
||||
return [str(item or '').strip() for item in value if str(item or '').strip()]
|
||||
return list(value)
|
||||
return value
|
||||
|
||||
|
||||
def normalize_handler_config(agent_code: str, raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
按 agent_code 的 handler_config_schema 归一化 handler_config。
|
||||
|
||||
核心逻辑:仅保留 schema 声明字段;空 schema 表示不允许任何 handler_config 字段。
|
||||
"""
|
||||
if raw is None:
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('handler_config 必须为 JSON 对象')
|
||||
|
||||
entry = get_catalog_entry(agent_code) or {}
|
||||
schema = entry.get('handler_config_schema')
|
||||
if not isinstance(schema, dict):
|
||||
schema = {}
|
||||
|
||||
if not schema:
|
||||
if raw:
|
||||
unknown = ', '.join(sorted(str(key) for key in raw.keys()))
|
||||
raise ValidationError(
|
||||
f'agent_code={agent_code} 不允许配置 handler_config 字段: {unknown}',
|
||||
)
|
||||
return None
|
||||
|
||||
normalized: dict[str, Any] = {}
|
||||
for key, field_schema in schema.items():
|
||||
if not isinstance(field_schema, dict):
|
||||
continue
|
||||
if key in raw:
|
||||
normalized[key] = _coerce_handler_value(field_schema, raw.get(key))
|
||||
elif 'default' in field_schema:
|
||||
normalized[key] = _coerce_handler_value(field_schema, field_schema.get('default'))
|
||||
|
||||
return normalized or None
|
||||
|
||||
|
||||
def deepcopy_default(value: Any) -> Any:
|
||||
"""保留供非 schema 场景使用的标量/容器拷贝。"""
|
||||
if isinstance(value, (dict, list)):
|
||||
import copy
|
||||
return copy.deepcopy(value)
|
||||
return value
|
||||
|
||||
|
||||
def default_capabilities_copy() -> dict[str, bool]:
|
||||
"""返回 capabilities 默认 schema 副本。"""
|
||||
defaults = get_default_capabilities()
|
||||
if defaults:
|
||||
return dict(defaults)
|
||||
return {
|
||||
'streaming': True,
|
||||
'file_upload': False,
|
||||
'task_progress': False,
|
||||
'human_confirm': False,
|
||||
'source_citation': True,
|
||||
'guide': True,
|
||||
'erp_kb': False,
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/content_profiles.py
|
||||
|
||||
用途:Agent 聊天内容 profile 目录(默认欢迎语/推荐问题模板 + Admin 校验白名单)。
|
||||
依赖:无。
|
||||
逻辑:Admin 保存 content_profile、backfill 回填默认文案、前端模板应用均读取本模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
VALID_CONTENT_PROFILES = frozenset({'generic_entrance', 'hr_policy', 'training'})
|
||||
|
||||
CONTENT_PROFILE_CATALOG: dict[str, dict[str, Any]] = {
|
||||
'generic_entrance': {
|
||||
'key': 'generic_entrance',
|
||||
'label': '通用入口',
|
||||
'description': 'HR + PLM 双 Intent 通用入口 Agent 的默认欢迎语与推荐问题',
|
||||
'welcome_message': (
|
||||
'我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,'
|
||||
'我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。'
|
||||
),
|
||||
'suggested_questions_style': 'plain',
|
||||
'suggested_questions': [
|
||||
{'question': '新员工入职须知', 'group': ''},
|
||||
{'question': '查询我有多少假期?', 'group': ''},
|
||||
{'question': '如何进行请假?', 'group': ''},
|
||||
{'question': '查公司法定节假日?', 'group': ''},
|
||||
{'question': '查公司薪酬及福利待遇怎么样?', 'group': ''},
|
||||
],
|
||||
},
|
||||
'hr_policy': {
|
||||
'key': 'hr_policy',
|
||||
'label': '人事规章专岗',
|
||||
'description': '仅 HR SQL Intent 的人事规章 Agent 默认欢迎语与推荐问题',
|
||||
'welcome_message': (
|
||||
'我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,'
|
||||
'我能从公司最新、最全的规章制度中,为你精准提取并总结答案。'
|
||||
),
|
||||
'suggested_questions_style': 'styled',
|
||||
'suggested_questions': [
|
||||
{'question': '查询我有多少假期?', 'group': '考勤与休假'},
|
||||
{'question': '如何进行请假?', 'group': '考勤与休假'},
|
||||
{'question': '查公司法定节假日?', 'group': '考勤与休假'},
|
||||
{'question': '新员工入职须知', 'group': '规章与日常'},
|
||||
{'question': '怎么开具在职证明?', 'group': '规章与日常'},
|
||||
{'question': '查公司薪酬及福利待遇怎么样?', 'group': '规章与日常'},
|
||||
],
|
||||
},
|
||||
'training': {
|
||||
'key': 'training',
|
||||
'label': '员工培训',
|
||||
'description': '培训工作区 Agent;详细题库仍存 extra_config.training_*',
|
||||
'welcome_message': (
|
||||
'我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。'
|
||||
),
|
||||
'suggested_questions_style': 'styled',
|
||||
'suggested_questions': [
|
||||
{'question': '开始新人培训', 'group': '培训流程'},
|
||||
{'question': '我已看完视频,请总结知识点', 'group': '培训流程'},
|
||||
{'question': '开始考试', 'group': '培训流程'},
|
||||
{'question': '导出本月培训成绩', 'group': 'HR 管理'},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def list_content_profiles(*, include_training: bool = True) -> list[dict[str, Any]]:
|
||||
"""返回 Admin 可选 content_profile 列表(含默认文案预览字段)。"""
|
||||
items = []
|
||||
for key in ('generic_entrance', 'hr_policy', 'training'):
|
||||
if key == 'training' and not include_training:
|
||||
continue
|
||||
entry = CONTENT_PROFILE_CATALOG.get(key)
|
||||
if entry:
|
||||
items.append(deepcopy(entry))
|
||||
return items
|
||||
|
||||
|
||||
def get_content_profile_definition(key: str) -> dict[str, Any] | None:
|
||||
"""按 key 读取 profile 定义;未知 key 返回 None。"""
|
||||
normalized = str(key or '').strip()
|
||||
entry = CONTENT_PROFILE_CATALOG.get(normalized)
|
||||
return deepcopy(entry) if entry else None
|
||||
|
||||
|
||||
def infer_content_profile_from_intent_routes(routes: list[str] | None) -> str | None:
|
||||
"""
|
||||
根据 intent_routes 推断 content_profile(与 intent_route_registry 聚合逻辑一致)。
|
||||
|
||||
Returns:
|
||||
generic_entrance | hr_policy | None
|
||||
"""
|
||||
if not routes:
|
||||
return None
|
||||
route_set = {str(item or '').strip() for item in routes if str(item or '').strip()}
|
||||
has_hr = 'hr_leave_sql' in route_set
|
||||
has_plm = 'plm_oracle' in route_set
|
||||
if has_hr and has_plm:
|
||||
return 'generic_entrance'
|
||||
if has_hr and not has_plm:
|
||||
return 'hr_policy'
|
||||
return None
|
||||
|
||||
|
||||
def merge_profile_defaults_into_fields(fields: dict[str, Any], profile_key: str) -> None:
|
||||
"""
|
||||
将 profile 默认 welcome_message / suggested_questions 写入回填字段 dict(仅填空)。
|
||||
|
||||
Args:
|
||||
fields: infer_registry_fields_from_legacy 等构建的 ORM 更新 dict(原地修改)。
|
||||
profile_key: content_profile key。
|
||||
"""
|
||||
definition = get_content_profile_definition(profile_key)
|
||||
if not definition:
|
||||
return
|
||||
if not str(fields.get('welcome_message') or '').strip():
|
||||
fields['welcome_message'] = definition['welcome_message']
|
||||
if not fields.get('suggested_questions'):
|
||||
fields['suggested_questions'] = deepcopy(definition['suggested_questions'])
|
||||
if not str(fields.get('suggested_questions_style') or '').strip():
|
||||
fields['suggested_questions_style'] = definition['suggested_questions_style']
|
||||
@@ -0,0 +1,80 @@
|
||||
# Agent Registry Catalog manifest(展示名、默认值、校验规则、handler_config schema)
|
||||
# runtime_handler 由 catalog_bindings.py 代码绑定,不在此文件维护。
|
||||
|
||||
platform:
|
||||
runtime_providers:
|
||||
- dify
|
||||
- builtin
|
||||
- hybrid
|
||||
- iframe
|
||||
conversation_modes:
|
||||
- chat
|
||||
- task_chat
|
||||
- embedded
|
||||
dify_app_types:
|
||||
- chatflow
|
||||
- workflow
|
||||
suggested_questions_styles:
|
||||
- plain
|
||||
- styled
|
||||
default_capabilities:
|
||||
streaming: true
|
||||
file_upload: false
|
||||
task_progress: false
|
||||
human_confirm: false
|
||||
source_citation: true
|
||||
guide: true
|
||||
erp_kb: false
|
||||
tool_run_progress_defaults:
|
||||
progress_type: file_check
|
||||
poll_interval_seconds: 2
|
||||
lock_input_when_running: true
|
||||
dify_required_providers:
|
||||
- dify
|
||||
- hybrid
|
||||
|
||||
agent_types:
|
||||
generic:
|
||||
label: 通用问答 / 知识库
|
||||
conversation_mode_default: chat
|
||||
runtime_provider_default: dify
|
||||
models: []
|
||||
required_fields: []
|
||||
forced_capabilities: {}
|
||||
handler_config_schema:
|
||||
intent_routes:
|
||||
type: array
|
||||
items: string
|
||||
content_profile:
|
||||
type: string
|
||||
enum: [generic_entrance, hr_policy, training]
|
||||
shipping_notice:
|
||||
label: 货代发货通知
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: hybrid
|
||||
models:
|
||||
- ShippingBatch
|
||||
- ShippingTask
|
||||
- ShippingTaskEvent
|
||||
required_fields: []
|
||||
forced_capabilities: {}
|
||||
handler_config_schema: {}
|
||||
file_check:
|
||||
label: 文件检核
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: dify
|
||||
models:
|
||||
- ScheduleTask
|
||||
required_fields:
|
||||
- bound_schedule_task_id
|
||||
forced_capabilities:
|
||||
task_progress: true
|
||||
handler_config_schema:
|
||||
poll_interval_seconds:
|
||||
type: integer
|
||||
default: 2
|
||||
minimum: 1
|
||||
maximum: 30
|
||||
lock_input_when_running:
|
||||
type: boolean
|
||||
default: true
|
||||
@@ -0,0 +1,21 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/__init__.py
|
||||
|
||||
用途:Agent Handler Registry 包入口。
|
||||
依赖:handlers.registry、handlers.bootstrap。
|
||||
逻辑:Executor 与 chat relay 通过本包访问 HANDLER_REGISTRY。
|
||||
"""
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY, get_handler, register_handler
|
||||
|
||||
__all__ = [
|
||||
'AgentHandler',
|
||||
'ChatStreamContext',
|
||||
'HANDLER_REGISTRY',
|
||||
'get_handler',
|
||||
'load_handlers',
|
||||
'register_handler',
|
||||
'reset_handlers_for_tests',
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/base.py
|
||||
|
||||
用途:Agent 业务 Handler 基类与聊天流上下文。
|
||||
依赖:无。
|
||||
逻辑:Hybrid/Builtin Executor 与 SSE relay 通过 Handler 钩子扩展领域行为。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterator
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatStreamContext:
|
||||
"""
|
||||
/api/chat/completions 单次流式请求上下文。
|
||||
|
||||
核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id/batch_no)。
|
||||
"""
|
||||
|
||||
query: str
|
||||
display_query: str
|
||||
user: Any
|
||||
agent: Any
|
||||
session: Any
|
||||
external_conversation_id: str | None
|
||||
request_id: str
|
||||
normalized_files: list[dict] | None = None
|
||||
adapter_hints: dict[str, Any] | None = None
|
||||
shipping_task_id: str = ''
|
||||
shipping_batch_no: str = ''
|
||||
kb_type: str = '企业知识库'
|
||||
hxops_turn_id: str | None = None
|
||||
|
||||
|
||||
class AgentHandler:
|
||||
"""
|
||||
业务 Handler 基类;子类通过 @register_handler 注册到 HANDLER_REGISTRY。
|
||||
|
||||
核心逻辑:prepare_stream 在 Dify 调用前注册 turn/校验;build_ui_state_event 供 SSE relay 下发领域 UI State。
|
||||
"""
|
||||
|
||||
handler_key: str = ''
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""Dify/Builtin 流开始前准备上下文(注册 turn、补充字段等)。"""
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
"""构造领域 UI State SSE 事件 dict;无则返回 None。"""
|
||||
return None
|
||||
|
||||
def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
为 UI State 事件生成去重键;None 表示不参与 dedupe。
|
||||
|
||||
Args:
|
||||
event: build_ui_state_event 返回的事件 dict。
|
||||
"""
|
||||
return None
|
||||
|
||||
def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
"""上游流开始前额外下发的 SSE 行(`data: {...}\\n\\n` 格式)。"""
|
||||
return iter(())
|
||||
|
||||
def on_upstream_terminal_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
) -> Iterator[str]:
|
||||
"""上游 message_end/workflow_finished 后追加的 SSE 行。"""
|
||||
return iter(())
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/bootstrap.py
|
||||
|
||||
用途:应用启动时加载 HANDLER_REGISTRY。
|
||||
依赖:handlers.shipping_notice 等领域 handler 模块。
|
||||
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_handlers_loaded = False
|
||||
|
||||
|
||||
def load_handlers() -> None:
|
||||
"""
|
||||
导入各领域 handler 模块以触发 @register_handler 注册。
|
||||
|
||||
核心逻辑:副作用 import;测试 reset 后通过 importlib.reload 重新注册。
|
||||
"""
|
||||
global _handlers_loaded
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
if _handlers_loaded and HANDLER_REGISTRY:
|
||||
return
|
||||
|
||||
import importlib
|
||||
|
||||
import app.services.agent_registry.handlers.file_check as file_check_mod
|
||||
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
|
||||
|
||||
importlib.reload(file_check_mod)
|
||||
importlib.reload(shipping_mod)
|
||||
|
||||
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
|
||||
_handlers_loaded = True
|
||||
|
||||
|
||||
def reset_handlers_for_tests() -> None:
|
||||
"""测试专用:清空 Registry 并重置 loaded 标记。"""
|
||||
global _handlers_loaded
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
_handlers_loaded = False
|
||||
HANDLER_REGISTRY.clear()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/file_check.py
|
||||
|
||||
用途:文件检核 Agent Handler — 聊天流 turn 注册与 Dify 进度绑定。
|
||||
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry。
|
||||
逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
|
||||
from app.services.agent_registry.handlers.registry import register_handler
|
||||
from app.services.agent_registry.resolver import agent_declares_task_progress
|
||||
|
||||
|
||||
@register_handler('file_check')
|
||||
class FileCheckHandler(AgentHandler):
|
||||
"""
|
||||
文件检核业务 Handler。
|
||||
|
||||
核心逻辑:capabilities.task_progress === true 时在 Dify 流开始前注册 hxops_turn_id,
|
||||
供检核进度轮询绑定 chat_log;capabilities 本身仅控制前端是否展示进度 UI。
|
||||
"""
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
if not agent_declares_task_progress(ctx.agent):
|
||||
return ctx
|
||||
|
||||
turn_id = uuid.uuid4().hex
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_file_check_chat_turn(
|
||||
turn_id=turn_id,
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
agent_id=int(getattr(ctx.agent, 'id', 0) or 0),
|
||||
query=ctx.query,
|
||||
)
|
||||
ctx.hxops_turn_id = turn_id
|
||||
return ctx
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/registry.py
|
||||
|
||||
用途:HANDLER_REGISTRY 与 register_handler 装饰器。
|
||||
依赖:handlers.base.AgentHandler。
|
||||
逻辑:bootstrap 导入各领域 handler 模块完成注册;resolver/Executor 按 key 查找。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable, TypeVar
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
|
||||
HANDLER_REGISTRY: dict[str, AgentHandler] = {}
|
||||
|
||||
HandlerT = TypeVar('HandlerT', bound=AgentHandler)
|
||||
|
||||
|
||||
def register_handler(handler_key: str) -> Callable[[type[HandlerT]], type[HandlerT]]:
|
||||
"""
|
||||
注册业务 Handler 到 HANDLER_REGISTRY。
|
||||
|
||||
Args:
|
||||
handler_key: 与 AGENT_TYPE_CATALOG.runtime_handler 对齐的 key。
|
||||
"""
|
||||
|
||||
def decorator(cls: type[HandlerT]) -> type[HandlerT]:
|
||||
instance = cls()
|
||||
instance.handler_key = handler_key
|
||||
HANDLER_REGISTRY[handler_key] = instance
|
||||
return cls
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_handler(handler_key: str) -> AgentHandler | None:
|
||||
"""按 key 获取 Handler 实例;未注册时返回 None。"""
|
||||
key = str(handler_key or '').strip()
|
||||
if not key:
|
||||
return None
|
||||
return HANDLER_REGISTRY.get(key)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/shipping_notice.py
|
||||
|
||||
用途:货代发货通知 Hybrid Handler — 聊天流 UI State 与上下文准备。
|
||||
依赖:shipping_notice.query_service、ui_state、agent_registry.handlers.registry。
|
||||
逻辑:SSE relay 调用 build_ui_state_event;不替代 Dify 正文生成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Iterator
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
|
||||
from app.services.agent_registry.handlers.registry import register_handler
|
||||
|
||||
|
||||
@register_handler('shipping_notice')
|
||||
class ShippingNoticeHandler(AgentHandler):
|
||||
"""
|
||||
货代发货通知业务 Handler。
|
||||
|
||||
核心逻辑:按 adapter_hints / 请求 task_id、batch_no 构造 shipping_ui_state 事件供前端渲染步骤与按钮。
|
||||
"""
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 shipping_ui_state SSE 事件。
|
||||
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
|
||||
"""
|
||||
task_id = str(ctx.shipping_task_id or '').strip()
|
||||
batch_no = str(ctx.shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {}
|
||||
shipping_hints = hints.get('shipping_notice') if isinstance(hints.get('shipping_notice'), dict) else {}
|
||||
task_id = str(shipping_hints.get('task_id') or '').strip()
|
||||
batch_no = str(shipping_hints.get('batch_no') or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
task = get_task_by_ref(task_id) if task_id else None
|
||||
batch = get_batch_by_no(batch_no) if batch_no else None
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
candidate = get_task_by_ref(focus_task_no)
|
||||
if candidate is not None and candidate.batch_id == batch.id:
|
||||
task = candidate
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'task_no': task.task_no,
|
||||
'batch_no': task.batch.batch_no if task.batch is not None else None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
}
|
||||
if batch is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'batch_ui_state': build_batch_ui_state(batch),
|
||||
}
|
||||
except Exception:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] build_ui_state failed request_id=%s task_id=%s batch_no=%s',
|
||||
ctx.request_id,
|
||||
task_id,
|
||||
batch_no,
|
||||
)
|
||||
return None
|
||||
|
||||
def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None:
|
||||
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
|
||||
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
|
||||
focus_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else {}
|
||||
)
|
||||
checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint')
|
||||
return json.dumps({
|
||||
'task_no': event.get('task_no'),
|
||||
'batch_no': event.get('batch_no'),
|
||||
'checkpoint': checkpoint,
|
||||
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
|
||||
}, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
def _format_sse(self, event: dict[str, Any]) -> str:
|
||||
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
|
||||
def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
event = self.build_ui_state_event(ctx)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
|
||||
def on_upstream_terminal_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
) -> Iterator[str]:
|
||||
event_name = str(event_data.get('event') or '').strip()
|
||||
if event_name not in {'message_end', 'workflow_finished'}:
|
||||
return iter(())
|
||||
event = self.build_ui_state_event(ctx)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
@@ -0,0 +1,139 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/intent_routes.py
|
||||
|
||||
用途:Intent Router 快路径 route 纯注册表(定义/注册/查询/校验,不含具体业务)。
|
||||
依赖:app.core.errors.ValidationError。
|
||||
逻辑:chat.intent_route_registry 注册 handler 时同步写入本模块;Admin 选项同源。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IntentRouteDefinition:
|
||||
"""Intent 快路径 Admin/校验用元数据。"""
|
||||
|
||||
key: str
|
||||
label: str
|
||||
description: str
|
||||
category: str = 'business'
|
||||
enabled: bool = True
|
||||
sort_order: int = 0
|
||||
ui_profile: str | None = None
|
||||
|
||||
|
||||
_INTENT_ROUTE_REGISTRY: dict[str, IntentRouteDefinition] = {}
|
||||
|
||||
|
||||
def register_intent_route(definition: IntentRouteDefinition) -> IntentRouteDefinition:
|
||||
"""
|
||||
注册 Intent route 定义。
|
||||
|
||||
Raises:
|
||||
ValidationError: key 为空或重复注册。
|
||||
"""
|
||||
key = str(definition.key or '').strip()
|
||||
if not key:
|
||||
raise ValidationError('intent_route key 不能为空')
|
||||
if key in _INTENT_ROUTE_REGISTRY:
|
||||
raise ValidationError(f'重复的 intent_route: {key}')
|
||||
_INTENT_ROUTE_REGISTRY[key] = definition
|
||||
return definition
|
||||
|
||||
|
||||
def get_intent_route_definition(key: str) -> IntentRouteDefinition | None:
|
||||
"""按 key 读取已注册 route 定义;未知 key 返回 None。"""
|
||||
normalized = str(key or '').strip()
|
||||
return _INTENT_ROUTE_REGISTRY.get(normalized)
|
||||
|
||||
|
||||
def list_intent_routes(*, include_disabled: bool = False) -> list[dict[str, Any]]:
|
||||
"""返回 Admin 可选 Intent route 列表(默认仅 enabled)。"""
|
||||
items = sorted(_INTENT_ROUTE_REGISTRY.values(), key=lambda item: item.sort_order)
|
||||
if not include_disabled:
|
||||
items = [item for item in items if item.enabled]
|
||||
return [
|
||||
{
|
||||
'key': item.key,
|
||||
'label': item.label,
|
||||
'description': item.description,
|
||||
'category': item.category,
|
||||
'enabled': item.enabled,
|
||||
'sort_order': item.sort_order,
|
||||
'ui_profile': item.ui_profile,
|
||||
}
|
||||
for item in items
|
||||
]
|
||||
|
||||
|
||||
def get_intent_route_keys() -> frozenset[str]:
|
||||
"""返回已注册 route key 集合。"""
|
||||
return frozenset(_INTENT_ROUTE_REGISTRY.keys())
|
||||
|
||||
|
||||
def is_known_intent_route(route: str) -> bool:
|
||||
"""判断 route key 是否已在注册表中。"""
|
||||
return str(route or '').strip() in _INTENT_ROUTE_REGISTRY
|
||||
|
||||
|
||||
def normalize_intent_routes_list(raw: list[Any] | None) -> list[str]:
|
||||
"""将 intent_routes 归一化为去重合法 route 名;非法项静默跳过(回填场景)。"""
|
||||
if not isinstance(raw, list):
|
||||
return []
|
||||
seen: set[str] = set()
|
||||
result: list[str] = []
|
||||
for item in raw:
|
||||
route = str(item or '').strip()
|
||||
if not route or not is_known_intent_route(route) or route in seen:
|
||||
continue
|
||||
seen.add(route)
|
||||
result.append(route)
|
||||
return result
|
||||
|
||||
|
||||
def validate_intent_routes(raw: Any) -> list[str]:
|
||||
"""
|
||||
Admin 写入时校验 intent_routes。
|
||||
|
||||
Raises:
|
||||
ValidationError: 非数组或含未知 route。
|
||||
"""
|
||||
if raw is None:
|
||||
return []
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('handler_config.intent_routes 必须为数组')
|
||||
result: list[str] = []
|
||||
for item in raw:
|
||||
route = str(item or '').strip()
|
||||
if not route:
|
||||
continue
|
||||
if not is_known_intent_route(route):
|
||||
raise ValidationError(f'无效的 intent_route: {route}')
|
||||
if route not in result:
|
||||
result.append(route)
|
||||
return result
|
||||
|
||||
|
||||
def parse_intent_routes(raw: Any) -> frozenset[str]:
|
||||
"""从 handler_config.intent_routes 解析为 frozenset。"""
|
||||
if isinstance(raw, (list, tuple, set, frozenset)):
|
||||
return frozenset(normalize_intent_routes_list(list(raw)))
|
||||
return frozenset()
|
||||
|
||||
|
||||
__all__ = [
|
||||
'IntentRouteDefinition',
|
||||
'get_intent_route_definition',
|
||||
'get_intent_route_keys',
|
||||
'is_known_intent_route',
|
||||
'list_intent_routes',
|
||||
'normalize_intent_routes_list',
|
||||
'parse_intent_routes',
|
||||
'register_intent_route',
|
||||
'validate_intent_routes',
|
||||
]
|
||||
@@ -0,0 +1,319 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/resolver.py
|
||||
|
||||
用途:Agent 注册表 Resolver — 运行时只读 agents 表结构化列。
|
||||
依赖:agent_registry.catalog(resolve_handler_key)。
|
||||
|
||||
部署前置(强制):
|
||||
执行 ``flask db upgrade`` 后必须先跑回填,将存量 extra_config / type / 名称
|
||||
等语义写入结构化列::
|
||||
|
||||
python scripts/backfill_agent_registry.py --apply
|
||||
|
||||
未回填的 Agent 将按列缺省值运行(如 agent_code=generic、runtime_provider=dify),
|
||||
行为可能与改造前不一致。
|
||||
|
||||
约束(禁止在本模块实现):
|
||||
- 不双读 extra_config(agent_code、capabilities、tool_run_progress 等)
|
||||
- 不根据 agents.type / agents.name 做运行时启发式
|
||||
- 名称/能力/type→列 映射仅存在于 backfill_mapping.py(一次性回填脚本)
|
||||
|
||||
逻辑:Admin 序列化、Context Adapter 分发、task_resolver、Executor(迭代 4)
|
||||
均通过本模块读取 agent_code / runtime_provider / conversation_mode / capabilities。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_registry.catalog import get_catalog_entry
|
||||
|
||||
from app.services.agent_registry.catalog_loader import get_default_capabilities, coerce_payload_boolean
|
||||
|
||||
DEFAULT_CAPABILITIES: dict[str, bool] = get_default_capabilities() or {
|
||||
'streaming': True,
|
||||
'file_upload': False,
|
||||
'task_progress': False,
|
||||
'human_confirm': False,
|
||||
'source_citation': True,
|
||||
'guide': True,
|
||||
'erp_kb': False,
|
||||
}
|
||||
|
||||
_BUILTIN_PROVIDERS = frozenset({'builtin', 'hybrid'})
|
||||
|
||||
# 列缺失或为 NULL 时的 ORM 缺省,与 models.Agent 列 default 对齐;非 extra_config 兜底。
|
||||
_COLUMN_DEFAULTS: dict[str, str] = {
|
||||
'agent_code': 'generic',
|
||||
'runtime_provider': 'dify',
|
||||
'conversation_mode': 'chat',
|
||||
}
|
||||
|
||||
|
||||
def _strip_str(value: Any) -> str:
|
||||
return str(value or '').strip()
|
||||
|
||||
|
||||
def _read_string_column(agent, column: str, *, default: str) -> str:
|
||||
"""
|
||||
读取 Registry 字符串列;列属性缺失或值为 NULL/空串时返回 default。
|
||||
|
||||
核心逻辑:只读 ORM 列,不访问 extra_config、agents.type 或名称字段。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或具备同名属性的代理对象。
|
||||
column: agents 表列名(如 agent_code、runtime_provider)。
|
||||
default: 列不可用时的缺省值(须与 models.Agent 列 default 一致)。
|
||||
|
||||
Returns:
|
||||
归一化后的非空字符串。
|
||||
"""
|
||||
if not hasattr(agent, column):
|
||||
return default
|
||||
value = getattr(agent, column, None)
|
||||
if value is None:
|
||||
return default
|
||||
normalized = _strip_str(value)
|
||||
return normalized or default
|
||||
|
||||
|
||||
def normalize_capabilities(raw: dict[str, Any] | None, *, strict: bool = False) -> dict[str, bool]:
|
||||
"""
|
||||
将 capabilities 归一化为固定 schema 布尔 dict。
|
||||
|
||||
Args:
|
||||
raw: agents.capabilities 列;None 时使用默认值。
|
||||
strict: True 时对非法布尔字符串抛 ValidationError(Admin 写入路径)。
|
||||
|
||||
Returns:
|
||||
含 streaming/file_upload/task_progress 等键的 dict。
|
||||
"""
|
||||
defaults = get_default_capabilities() or DEFAULT_CAPABILITIES
|
||||
result = dict(defaults)
|
||||
if isinstance(raw, dict):
|
||||
for key in defaults:
|
||||
if key in raw:
|
||||
result[key] = coerce_payload_boolean(
|
||||
raw[key],
|
||||
context=f'capabilities.{key}',
|
||||
strict=strict,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def resolve_agent_code(agent) -> str:
|
||||
"""
|
||||
解析 Agent 应用类型 code。
|
||||
|
||||
核心逻辑:只读 agents.agent_code 列;缺省 generic。
|
||||
不读 extra_config.agent_code,也不按名称推断 shipping_notice / file_check。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或具备 agent_code 属性的代理对象。
|
||||
|
||||
Returns:
|
||||
agent_code 字符串。
|
||||
|
||||
Note:
|
||||
存量 Agent 须先经 backfill_agent_registry.py 写入列,否则一律视为 generic。
|
||||
"""
|
||||
return _read_string_column(agent, 'agent_code', default=_COLUMN_DEFAULTS['agent_code'])
|
||||
|
||||
|
||||
def resolve_runtime_provider(agent) -> str:
|
||||
"""
|
||||
解析 Agent 运行时 provider。
|
||||
|
||||
核心逻辑:只读 agents.runtime_provider 列;缺省 dify。
|
||||
不读 agents.type(api/iframe)或 extra_config。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或代理对象。
|
||||
|
||||
Returns:
|
||||
runtime_provider 字符串(dify / builtin / hybrid / iframe)。
|
||||
"""
|
||||
return _read_string_column(agent, 'runtime_provider', default=_COLUMN_DEFAULTS['runtime_provider'])
|
||||
|
||||
|
||||
def resolve_conversation_mode(agent) -> str:
|
||||
"""
|
||||
解析 Agent 对话形态。
|
||||
|
||||
核心逻辑:只读 agents.conversation_mode 列;缺省 chat。
|
||||
不根据 runtime_provider=iframe 在运行时推断 embedded。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或代理对象。
|
||||
|
||||
Returns:
|
||||
conversation_mode 字符串(chat / task_chat / embedded)。
|
||||
"""
|
||||
return _read_string_column(agent, 'conversation_mode', default=_COLUMN_DEFAULTS['conversation_mode'])
|
||||
|
||||
|
||||
def resolve_capabilities(agent) -> dict[str, bool]:
|
||||
"""
|
||||
解析 Agent 平台能力声明。
|
||||
|
||||
核心逻辑:只读 agents.capabilities JSON 列;NULL 或非 dict 时返回 DEFAULT_CAPABILITIES。
|
||||
不解析 extra_config.capabilities 列表或 tool_run_progress 块。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或具备 capabilities 属性的代理对象。
|
||||
|
||||
Returns:
|
||||
含 streaming / file_upload / task_progress 等键的归一化 bool dict。
|
||||
"""
|
||||
if hasattr(agent, 'capabilities'):
|
||||
column_caps = getattr(agent, 'capabilities', None)
|
||||
return normalize_capabilities(column_caps if isinstance(column_caps, dict) else None)
|
||||
return normalize_capabilities(None)
|
||||
|
||||
|
||||
def resolve_handler_key(agent_code: str) -> str | None:
|
||||
"""
|
||||
按 agent_code 从 Catalog 解析 runtime_handler key。
|
||||
|
||||
Args:
|
||||
agent_code: 应用类型标识。
|
||||
|
||||
Returns:
|
||||
HANDLER_REGISTRY 键;纯 Dify 类型为 None。
|
||||
"""
|
||||
entry = get_catalog_entry(agent_code)
|
||||
if not entry:
|
||||
return None
|
||||
handler = entry.get('runtime_handler')
|
||||
return _strip_str(handler) or None
|
||||
|
||||
|
||||
def resolve_handler(agent):
|
||||
"""
|
||||
解析 builtin/hybrid 运行时 Handler 实例。
|
||||
|
||||
核心逻辑:runtime_provider ∈ {builtin, hybrid} 时查 Catalog → HANDLER_REGISTRY;
|
||||
hybrid 且 Catalog 有 handler_key 但未注册实现时抛出 AgentHandlerNotConfiguredError。
|
||||
|
||||
Returns:
|
||||
Handler 实例;provider 为 dify/iframe 或 Catalog 无 handler 时返回 None。
|
||||
|
||||
Raises:
|
||||
AgentHandlerNotConfiguredError: hybrid/builtin 需要 handler 但未注册。
|
||||
"""
|
||||
provider = resolve_runtime_provider(agent)
|
||||
if provider not in _BUILTIN_PROVIDERS:
|
||||
return None
|
||||
|
||||
handler_key = resolve_handler_key(resolve_agent_code(agent))
|
||||
if not handler_key:
|
||||
if provider == 'builtin':
|
||||
from app.core.errors import AgentHandlerNotConfiguredError
|
||||
raise AgentHandlerNotConfiguredError(
|
||||
message='runtime_provider=builtin 时 Catalog 必须声明 runtime_handler',
|
||||
agent_code=resolve_agent_code(agent),
|
||||
runtime_provider=provider,
|
||||
)
|
||||
return None
|
||||
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
handler = HANDLER_REGISTRY.get(handler_key)
|
||||
if handler is None:
|
||||
from app.core.errors import AgentHandlerNotConfiguredError
|
||||
raise AgentHandlerNotConfiguredError(
|
||||
message=f'Handler 未注册: {handler_key}',
|
||||
agent_code=resolve_agent_code(agent),
|
||||
handler_key=handler_key,
|
||||
runtime_provider=provider,
|
||||
)
|
||||
return handler
|
||||
|
||||
|
||||
def resolve_intent_routes(agent) -> frozenset[str]:
|
||||
"""
|
||||
解析 Agent Intent Router 快路径声明。
|
||||
|
||||
核心逻辑:只读 agents.handler_config.intent_routes 列;不根据名称推断。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或具备 handler_config 属性的代理对象。
|
||||
|
||||
Returns:
|
||||
合法 intent route 名的 frozenset;未配置时为空集。
|
||||
"""
|
||||
from app.services.agent_registry.intent_routes import parse_intent_routes
|
||||
|
||||
handler_config = getattr(agent, 'handler_config', None) if hasattr(agent, 'handler_config') else None
|
||||
if not isinstance(handler_config, dict):
|
||||
return frozenset()
|
||||
return parse_intent_routes(handler_config.get('intent_routes'))
|
||||
|
||||
|
||||
def agent_has_intent_route(agent, route: str) -> bool:
|
||||
"""
|
||||
判断 Agent 是否声明指定 Intent 快路径。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或代理对象。
|
||||
route: intent_routes 中的 route 名(如 hr_leave_sql)。
|
||||
|
||||
Returns:
|
||||
已声明该 route 时返回 True。
|
||||
"""
|
||||
normalized_route = str(route or '').strip()
|
||||
if not normalized_route:
|
||||
return False
|
||||
return normalized_route in resolve_intent_routes(agent)
|
||||
|
||||
|
||||
def agent_has_erp_kb(agent) -> bool:
|
||||
"""判断 Agent 是否启用 ERP 固资知识库特化(capabilities.erp_kb)。"""
|
||||
return bool(resolve_capabilities(agent).get('erp_kb'))
|
||||
|
||||
|
||||
def agent_declares_task_progress(agent) -> bool:
|
||||
"""
|
||||
判断 Agent 是否声明文件检核/异步任务进度能力(不要求 bound_schedule_task_id)。
|
||||
|
||||
核心逻辑:只读 capabilities.task_progress === true;不读 extra_config、不按 agent_code 旁路。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或代理对象。
|
||||
|
||||
Returns:
|
||||
capabilities.task_progress 为 True 时返回 True。
|
||||
"""
|
||||
return resolve_capabilities(agent).get('task_progress') is True
|
||||
|
||||
|
||||
def is_file_check_runtime_ready(agent) -> bool:
|
||||
"""
|
||||
判断 file_check 对话入口是否已完整配置(可注入 task_id、绑定 chat_log.run_id)。
|
||||
|
||||
核心逻辑:agent_declares_task_progress 且 agents.bound_schedule_task_id 已注册。
|
||||
|
||||
Args:
|
||||
agent: Agent ORM 或代理对象。
|
||||
|
||||
Returns:
|
||||
能力声明且 task_id 列已配置时返回 True。
|
||||
"""
|
||||
if not agent_declares_task_progress(agent):
|
||||
return False
|
||||
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
|
||||
|
||||
return bool(resolve_schedule_task_id_from_agent(agent))
|
||||
|
||||
|
||||
def resolve_handler_for_agent_code(agent) -> 'AgentHandler | None':
|
||||
"""
|
||||
按 agent_code 查找已注册 Handler(不校验 runtime_provider)。
|
||||
|
||||
用途:SSE relay 等领域 UI 增强;纯 dify 的 shipping_notice 实例也可下发 UI State。
|
||||
"""
|
||||
handler_key = resolve_handler_key(resolve_agent_code(agent))
|
||||
if not handler_key:
|
||||
return None
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
return HANDLER_REGISTRY.get(handler_key)
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/serialization.py
|
||||
|
||||
用途:Agent Registry 字段序列化,供 Admin / 用户侧 API 输出。
|
||||
依赖:agent_registry.resolver、agent_registry.catalog。
|
||||
逻辑:api/admin/agents、api/user、api/agents、agent_category 调用本模块合并结构化列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import Agent
|
||||
from app.services.agent_registry.resolver import (
|
||||
normalize_capabilities,
|
||||
resolve_agent_code,
|
||||
resolve_capabilities,
|
||||
resolve_conversation_mode,
|
||||
resolve_runtime_provider,
|
||||
)
|
||||
|
||||
|
||||
def mask_dify_api_key(value: str | None) -> str:
|
||||
"""管理端列表脱敏 Dify API Key。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
return ''
|
||||
if len(text) <= 8:
|
||||
return '****'
|
||||
return f'{text[:4]}****{text[-4:]}'
|
||||
|
||||
|
||||
def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
|
||||
"""
|
||||
输出 Agent Registry 结构化字段(列 + resolver 归一化 capabilities)。
|
||||
|
||||
Returns:
|
||||
agent_code、runtime_provider、conversation_mode、capabilities 等 API 公共字段。
|
||||
"""
|
||||
from app.services.chat.intent_route_registry import resolve_agent_intent_metadata
|
||||
|
||||
capabilities = resolve_capabilities(agent)
|
||||
handler_config = getattr(agent, 'handler_config', None)
|
||||
intent_meta = resolve_agent_intent_metadata(agent)
|
||||
tool_run_progress = build_tool_run_progress_view(agent)
|
||||
return {
|
||||
'agent_code': resolve_agent_code(agent),
|
||||
'runtime_provider': resolve_runtime_provider(agent),
|
||||
'conversation_mode': resolve_conversation_mode(agent),
|
||||
'dify_app_type': getattr(agent, 'dify_app_type', None) or 'chatflow',
|
||||
'iframe_url': getattr(agent, 'iframe_url', None),
|
||||
'category': getattr(agent, 'category', None) or None,
|
||||
'sub_category': getattr(agent, 'sub_category', None) or None,
|
||||
'sort_order': int(getattr(agent, 'sort_order', 0) or 0),
|
||||
'welcome_message': getattr(agent, 'welcome_message', None),
|
||||
'suggested_questions_style': getattr(agent, 'suggested_questions_style', None) or 'plain',
|
||||
'suggested_questions': getattr(agent, 'suggested_questions', None) or [],
|
||||
'capabilities': capabilities,
|
||||
'file_upload_policy': getattr(agent, 'file_upload_policy', None),
|
||||
'bound_schedule_task_id': getattr(agent, 'bound_schedule_task_id', None),
|
||||
'handler_config': handler_config if isinstance(handler_config, dict) else None,
|
||||
'tool_run_progress': tool_run_progress,
|
||||
**intent_meta,
|
||||
}
|
||||
|
||||
|
||||
def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
|
||||
"""Agent ORM → 管理端列表/详情 JSON(API Key 仅返回脱敏值,明文不可读)。"""
|
||||
registry = serialize_registry_fields(agent)
|
||||
return {
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'icon_url': agent.icon_url,
|
||||
'is_active': agent.is_active,
|
||||
'type': agent.type,
|
||||
'dify_app_id': agent.dify_app_id,
|
||||
'dify_api_key_masked': mask_dify_api_key(agent.dify_api_key),
|
||||
'api_base_url': agent.api_base_url,
|
||||
'extra_config': agent.extra_config if isinstance(agent.extra_config, dict) else {},
|
||||
**registry,
|
||||
}
|
||||
|
||||
|
||||
def serialize_agent_for_user_list(agent: Agent | Any) -> dict[str, Any]:
|
||||
"""用户可见 Agent 列表项(聊天侧栏、工作台)。"""
|
||||
name = agent.name if hasattr(agent, 'name') else agent.get('name')
|
||||
description = agent.description if hasattr(agent, 'description') else agent.get('description')
|
||||
icon_url = agent.icon_url if hasattr(agent, 'icon_url') else agent.get('icon_url')
|
||||
agent_id = int(agent.id if hasattr(agent, 'id') else agent.get('id') or 0)
|
||||
registry = serialize_registry_fields(agent)
|
||||
return {
|
||||
'id': agent_id,
|
||||
'name': name,
|
||||
'description': description,
|
||||
'icon_url': icon_url,
|
||||
**registry,
|
||||
}
|
||||
|
||||
|
||||
def serialize_agent_for_user_detail(
|
||||
agent: Agent,
|
||||
*,
|
||||
dify_parameters: dict[str, Any] | None = None,
|
||||
extra_config: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""用户 Agent 详情(不含 dify_api_key)。"""
|
||||
registry = serialize_registry_fields(agent)
|
||||
extra = extra_config if isinstance(extra_config, dict) else (
|
||||
agent.extra_config if isinstance(agent.extra_config, dict) else {}
|
||||
)
|
||||
return {
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'type': agent.type,
|
||||
'icon_url': agent.icon_url,
|
||||
'extra_config': extra,
|
||||
'dify_parameters': dify_parameters,
|
||||
**registry,
|
||||
}
|
||||
|
||||
|
||||
def build_tool_run_progress_view(agent: Agent) -> dict[str, Any] | None:
|
||||
"""
|
||||
从 Registry 列构建前端 tool_run_progress 视图(迁移期兼容 extra 读者)。
|
||||
|
||||
核心逻辑:capabilities.task_progress 为 true 且 bound_schedule_task_id 已注册时返回配置 dict。
|
||||
"""
|
||||
caps = resolve_capabilities(agent)
|
||||
if not caps.get('task_progress'):
|
||||
return None
|
||||
task_id = getattr(agent, 'bound_schedule_task_id', None)
|
||||
try:
|
||||
schedule_task_id = int(task_id)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if schedule_task_id <= 0:
|
||||
return None
|
||||
|
||||
handler_config = getattr(agent, 'handler_config', None)
|
||||
from app.services.agent_registry.catalog_loader import get_tool_run_progress_defaults
|
||||
from app.services.agent_registry.resolver import resolve_agent_code
|
||||
|
||||
defaults = get_tool_run_progress_defaults()
|
||||
cfg: dict[str, Any] = {
|
||||
'type': str(defaults.get('progress_type') or resolve_agent_code(agent) or 'file_check'),
|
||||
'schedule_task_id': schedule_task_id,
|
||||
}
|
||||
cfg['poll_interval_seconds'] = defaults.get('poll_interval_seconds', 2)
|
||||
cfg['lock_input_when_running'] = defaults.get('lock_input_when_running', True)
|
||||
if isinstance(handler_config, dict):
|
||||
if handler_config.get('poll_interval_seconds') is not None:
|
||||
cfg['poll_interval_seconds'] = handler_config['poll_interval_seconds']
|
||||
if handler_config.get('lock_input_when_running') is not None:
|
||||
cfg['lock_input_when_running'] = handler_config['lock_input_when_running']
|
||||
return cfg
|
||||
Reference in new issue
Block a user