feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持

This commit is contained in:
hugo committed 2026-07-07 11:10:32 +08:00
1 parent ac4262cd75
commit c8ce77199e
183 files changed
+11690 -2300

No files matched your search

@@ -1,60 +0,0 @@
"""
services/file_check_tools/agent_resolver.py
用途:识别具备文件检核进度能力的对话 Agent。
依赖:Agent.extra_config(capabilities + tool_run_progress.schedule_task_id)。
逻辑:chat.py / dify.py / user.py 通过 capabilities 驱动;agent_declares_file_check_progress 用于缺参时快速失败。
"""
from __future__ import annotations
from app.models import Agent
def _resolve_task_id_from_mapping(mapping: dict | None) -> int | None:
if not isinstance(mapping, dict):
return None
raw = mapping.get("schedule_task_id", mapping.get("task_id"))
try:
task_id = int(raw)
except (TypeError, ValueError):
return None
return task_id if task_id > 0 else None
def _extra_dict(agent) -> dict:
extra = getattr(agent, "extra_config", None) or {}
return extra if isinstance(extra, dict) else {}
def agent_declares_file_check_progress(agent) -> bool:
"""
判断 Agent 是否声明了文件检核进度能力(不要求 schedule_task_id 已配齐)。
用途:识别「已声明 tool_run_progress 但未配置 task_id」的 Agent,在调 Dify 前快速报错。
"""
extra = _extra_dict(agent)
caps = extra.get("capabilities") or []
if isinstance(caps, list) and "tool_run_progress" in caps:
return True
return isinstance(extra.get("tool_run_progress"), dict)
def is_file_check_chat_agent(agent) -> bool:
"""
判断 Agent 是否为文件检核对话入口。
核心逻辑:extra_config.capabilities 含 tool_run_progress,且配置了 schedule_task_id。
"""
extra = _extra_dict(agent)
if not agent_declares_file_check_progress(agent):
return False
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict) and _resolve_task_id_from_mapping(tool_cfg):
return True
return bool(_resolve_task_id_from_mapping(extra))
def resolve_chat_agent() -> Agent | None:
"""返回第一个具备文件检核进度能力的活跃 Agent(测试/运维辅助)。"""
rows = Agent.query.filter(Agent.is_active.is_(True)).order_by(Agent.id.asc()).all()
return next((row for row in rows if is_file_check_chat_agent(row)), None)
@@ -0,0 +1,53 @@
"""
backend/app/services/file_check_tools/context_adapter.py
用途:文件检核 Agent 的 Context Adapter,构建 task_id Dify inputs。
依赖:file_check_tools.dify_inputs、agent_runtime_context.registry。
逻辑:agent_code=file_check 时由 build_chat_dify_inputs 分发;缺失 bound_schedule_task_id 时抛 ValidationError。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_runtime_context.registry import register_context_adapter
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
@register_context_adapter('file_check')
def build_file_check_context_adapter(
*,
agent,
session_id: str,
adapter_hints: dict[str, Any] | None = None,
request_id: str | None = None,
trigger_source: str | None = 'frontend_chat',
locale: str | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""
构建文件检核 Chatflow Dify Start inputs。
核心逻辑:从 bound_schedule_task_id 列注入 task_id;
session_id 存在时附带 agent_runtime_context(迭代 5 Dify Start 联调);
required=True 时未配置 bound_schedule_task_id 立即失败,避免 Dify 长连接挂死。
Args:
agent: 当前对话 Agent。
session_id: HXOPS 会话 ID(检核 Tool 链路由 turn 注册表推断,不传入 Dify)。
adapter_hints: 预留;检核当前不消费领域 hints。
Returns:
含 task_id 与可选 agent_runtime_context 的 inputs dict。
Raises:
ValidationError: bound_schedule_task_id 未配置或非法。
"""
return build_file_check_dify_inputs(
agent,
required=True,
session_id=session_id,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
)
@@ -1,93 +1,154 @@
"""
services/file_check_tools/dify_inputs.py
用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。
依赖:task_resolver、agent_resolver、errors.ValidationError。
逻辑:chat.py 在调 Dify 前调用本模块;缺失 schedule_task_id 时抛 ValidationError,避免 Dify 长连接挂死。
"""
from __future__ import annotations
from app.core.errors import ValidationError
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致
FILE_CHECK_TASK_ID_INPUT = "task_id"
FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required"
def _missing_task_id_error(agent) -> ValidationError:
"""
构造 task_id 未配置时的业务异常。
核心逻辑:返回可操作的配置提示,供管理后台与前端直接展示。
"""
return ValidationError(
"文件检核 Agent 未配置有效的 schedule_task_id,无法调用 Dify Chatflow。"
"请在管理后台编辑该 Agent,于 extra_config 中设置 "
"tool_run_progress.schedule_task_id(绑定排程任务 ID)。",
details={
"error_code": FILE_CHECK_TASK_ID_MISSING_CODE,
"agent_id": getattr(agent, "id", None),
"agent_name": getattr(agent, "name", None) or "",
"config_hint": {
"capabilities": ["tool_run_progress"],
"tool_run_progress": {
"type": "file_check",
"schedule_task_id": "<ScheduleTask.id>",
},
},
},
)
def ensure_file_check_task_id_configured(agent) -> int:
"""
解析并校验文件检核 Agent 绑定的 schedule_task_id。
Args:
agent: 当前对话 Agent。
Returns:
有效的 ScheduleTask.id。
Raises:
ValidationError: extra_config 未配置或 schedule_task_id 非法。
"""
task_id = resolve_schedule_task_id_from_agent(agent)
if not task_id:
raise _missing_task_id_error(agent)
return task_id
def build_file_check_dify_inputs(agent, *, required: bool = False) -> dict[str, str]:
"""
构建文件检核 Chatflow 的 Dify chat inputs。
仅注入 task_id。hxops_session_id / hxops_turn_id 由 chat.py 登记 turn 注册表,
Tool API 启动时通过 user_message 推断,无需传入 Dify 画布。
Args:
agent: 当前对话 Agent;task_id 从其 extra_config 解析。
required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。
Returns:
含 task_id 的 inputs 字典;required=False 且未配置时返回空 dict。
Raises:
ValidationError: required=True 且 schedule_task_id 未配置。
"""
task_id = resolve_schedule_task_id_from_agent(agent)
if not task_id:
if required:
raise _missing_task_id_error(agent)
return {}
return {FILE_CHECK_TASK_ID_INPUT: str(task_id)}
__all__ = [
"FILE_CHECK_TASK_ID_INPUT",
"FILE_CHECK_TASK_ID_MISSING_CODE",
"build_file_check_dify_inputs",
"ensure_file_check_task_id_configured",
]
␍
"""
services/file_check_tools/dify_inputs.py
用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。
依赖:task_resolver、agent_runtime_context.builder、errors.ValidationError。
逻辑:Context Adapter 调用本模块;必注入 task_id;session_id 存在时可选附带 agent_runtime_context(迭代 5 Dify Start 联调)。
"""
from __future__ import annotations
from app.core.errors import ValidationError
from app.services.agent_runtime_context.builder import build_agent_runtime_context, serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致
FILE_CHECK_TASK_ID_INPUT = "task_id"
FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required"
def _missing_task_id_error(agent) -> ValidationError:
"""
构造 task_id 未配置时的业务异常。
核心逻辑:返回可操作的配置提示,供管理后台与前端直接展示。
"""
return ValidationError(
"文件检核 Agent 未配置有效的 bound_schedule_task_id,无法调用 Dify Chatflow。"
"请在管理后台编辑该 Agent,设置 bound_schedule_task_id(绑定排程任务 ID)"
"并启用 capabilities.task_progress。",
details={
"error_code": FILE_CHECK_TASK_ID_MISSING_CODE,
"agent_id": getattr(agent, "id", None),
"agent_name": getattr(agent, "name", None) or "",
"config_hint": {
"bound_schedule_task_id": "<ScheduleTask.id>",
"capabilities": {"task_progress": True},
},
},
)
def ensure_file_check_task_id_configured(agent) -> int:
"""
解析并校验文件检核 Agent 绑定的 schedule_task_id。
Args:
agent: 当前对话 Agent。
Returns:
有效的 ScheduleTask.id(来自 bound_schedule_task_id 列)。
Raises:
ValidationError: bound_schedule_task_id 未配置或非法。
"""
task_id = resolve_schedule_task_id_from_agent(agent)
if not task_id:
raise _missing_task_id_error(agent)
return task_id
def _build_file_check_runtime_context(
*,
session_id: str,
schedule_task_id: int,
agent,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
) -> dict[str, str]:
"""
构建 file_check 可选 agent_runtime_context 快照。
核心逻辑:refs 携带 schedule_task_id;domain.state_hint 供 Dify 理解检核任务锚点。
"""
agent_name = str(getattr(agent, 'name', None) or '').strip() or '文件检核'
runtime_context = build_agent_runtime_context(
agent_code='file_check',
scope='chat_turn',
session_id=session_id,
request_id=request_id,
trigger_source=trigger_source or 'frontend_chat',
locale=locale,
refs={'schedule_task_id': str(schedule_task_id)},
domain={
'type': 'file_check',
'summary': agent_name,
'state_hint': {'schedule_task_id': str(schedule_task_id)},
},
)
if not runtime_context:
return {}
return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context)}
def build_file_check_dify_inputs(
agent,
*,
required: bool = False,
session_id: str | None = None,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
include_runtime_context: bool = True,
) -> dict[str, str]:
"""
构建文件检核 Chatflow 的 Dify chat inputs。
核心逻辑:必注入 task_id(Start 节点变量);session_id 存在且 include_runtime_context 时附带 agent_runtime_context。
hxops_turn_id 由 Executor 注册 turn 注册表,不传入 Dify 画布。
Args:
agent: 当前对话 Agent;task_id 从 bound_schedule_task_id 列解析。
required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。
session_id: HXOPS 会话 ID;存在时可生成 agent_runtime_context。
request_id: 请求追踪 ID。
trigger_source: 触发来源。
locale: 用户语言。
include_runtime_context: 是否在 task_id 之外附带 agent_runtime_context。
Returns:
含 task_id(及可选 agent_runtime_context)的 inputs;required=False 且未配置时返回空 dict。
Raises:
ValidationError: required=True 且 bound_schedule_task_id 未配置或非法。
"""
task_id = resolve_schedule_task_id_from_agent(agent)
if not task_id:
if required:
raise _missing_task_id_error(agent)
return {}
inputs: dict[str, str] = {FILE_CHECK_TASK_ID_INPUT: str(task_id)}
normalized_session_id = str(session_id or '').strip()
if include_runtime_context and normalized_session_id:
inputs.update(
_build_file_check_runtime_context(
session_id=normalized_session_id,
schedule_task_id=task_id,
agent=agent,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
)
)
return inputs
__all__ = [
"FILE_CHECK_TASK_ID_INPUT",
"FILE_CHECK_TASK_ID_MISSING_CODE",
"build_file_check_dify_inputs",
"ensure_file_check_task_id_configured",
]
@@ -3,7 +3,7 @@ services/file_check_tools/progress_paths.py
用途:文件检核进度轮询 API 路径常量与展示标题解析。
依赖:ScheduleTask。
逻辑:前端/ enrich 由 schedule_task_id 推导 URL,管理员无需配置 log_progress_url。
逻辑:前端/API 由 bound_schedule_task_id 推导轮询 URL,管理员无需配置 log_progress_url。
"""
from __future__ import annotations
@@ -19,7 +19,7 @@ def resolve_file_check_progress_title(task_id: int | None) -> str:
从 ScheduleTask.name 解析进度卡片标题。
Args:
task_id: Agent extra_config 中的 schedule_task_id。
task_id: Agent.bound_schedule_task_id(ScheduleTask.id)。
Returns:
排程任务名称;不存在时返回空字符串。
@@ -1,30 +1,36 @@
"""
services/file_check_tools/task_resolver.py
用途:解析文件检核 Chatflow 绑定的 ScheduleTask.id 与 Agent 进度配置。
依赖:ScheduleTask、Agent.extra_config、progress_paths、agent_resolver。
逻辑:task_id 来自 Agent extra_config;title 来自 ScheduleTask.name;轮询 URL 由代码推导。
用途:解析文件检核 Chatflow 绑定的 ScheduleTask.id。
依赖:ScheduleTask、Agent.bound_schedule_task_id。
逻辑:只读 agents.bound_schedule_task_id 列;未配置时返回 None。
"""
from __future__ import annotations
from app.models import Agent, ScheduleTask
from app.services.file_check_tools.agent_resolver import _resolve_task_id_from_mapping
from app.services.file_check_tools.progress_paths import resolve_file_check_progress_title
resolve_schedule_task_id_from_mapping = _resolve_task_id_from_mapping
from app.models import ScheduleTask
def resolve_schedule_task_id_from_agent(agent) -> int | None:
"""从 Agent extra_config 解析绑定的检核排程 task_id。"""
extra = getattr(agent, "extra_config", None) or {}
if not isinstance(extra, dict):
"""
解析 Agent 绑定的检核排程 task_id。
核心逻辑:只读 agents.bound_schedule_task_id 列;未注册时返回 None。
Args:
agent: Agent ORM 或等价对象。
Returns:
有效的 ScheduleTask.id;缺失或非法时 None。
"""
bound_task_id = getattr(agent, 'bound_schedule_task_id', None)
if bound_task_id is None:
return None
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict):
task_id = resolve_schedule_task_id_from_mapping(tool_cfg)
if task_id:
return task_id
return resolve_schedule_task_id_from_mapping(extra)
try:
task_id = int(bound_task_id)
except (TypeError, ValueError):
return None
return task_id if task_id > 0 else None
def is_file_check_schedule_task(task: ScheduleTask | None) -> bool:
@@ -32,86 +38,7 @@ def is_file_check_schedule_task(task: ScheduleTask | None) -> bool:
return task is not None and int(getattr(task, "id", 0) or 0) > 0
def _has_tool_run_progress_capability(extra: dict) -> bool:
caps = extra.get("capabilities") or []
if isinstance(caps, list) and "tool_run_progress" in caps:
return True
if isinstance(extra.get("tool_run_progress"), dict):
return True
progress_type = str(extra.get("type") or "").strip().lower()
if progress_type == "file_check":
return True
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict):
nested_type = str(tool_cfg.get("type") or "").strip().lower()
if nested_type == "file_check":
return True
return False
def _apply_schedule_task_metadata(merged: dict) -> None:
"""按 schedule_task_id 写入展示 title(ScheduleTask.name)。"""
task_id = resolve_schedule_task_id_from_mapping(merged)
if not task_id:
return
schedule_title = resolve_file_check_progress_title(task_id)
if schedule_title:
merged["title"] = schedule_title
def enrich_tool_run_progress_extra(extra_config: dict | None, *, agent: Agent | None = None) -> dict:
"""
为文件检核 Agent 的 extra_config 补全 tool_run_progress 能力与轮询参数。
核心逻辑:管理员只需配置 schedule_task_id;进度轮询 URL 由前后端按 task_id 推导,无需 log_progress_url。
Returns:
新的 extra_config 副本。
"""
extra = dict(extra_config or {})
tool_cfg = extra.get("tool_run_progress")
merged = dict(tool_cfg) if isinstance(tool_cfg, dict) else {
"type": "file_check",
"poll_interval_seconds": 2,
"lock_input_when_running": True,
}
merged.setdefault("poll_interval_seconds", 2)
merged.setdefault("type", "file_check")
merged.setdefault("lock_input_when_running", True)
if not resolve_schedule_task_id_from_mapping(merged) and agent is not None:
task_id = resolve_schedule_task_id_from_agent(agent)
if task_id:
merged["schedule_task_id"] = task_id
_apply_schedule_task_metadata(merged)
# 历史字段:若 DB 仍存有 URL,去掉以免误导运维重复维护
merged.pop("log_progress_url", None)
merged.pop("detail_url_template", None)
merged.pop("session_progress_url", None)
extra["tool_run_progress"] = merged
capabilities = list(extra.get("capabilities") or [])
if "tool_run_progress" not in capabilities:
capabilities.append("tool_run_progress")
extra["capabilities"] = capabilities
return extra
def enrich_agent_extra_if_file_check(agent: Agent) -> dict:
"""若 Agent 已声明 tool_run_progress 能力则 enrich extra_config,否则原样返回。"""
extra = dict(agent.extra_config or {}) if isinstance(agent.extra_config, dict) else {}
if _has_tool_run_progress_capability(extra):
return enrich_tool_run_progress_extra(extra, agent=agent)
return extra
__all__ = [
"enrich_agent_extra_if_file_check",
"enrich_tool_run_progress_extra",
"is_file_check_schedule_task",
"resolve_schedule_task_id_from_agent",
"resolve_schedule_task_id_from_mapping",
]