feat(deep-research): 强化任务链路可靠性并接入 agentfx 报告助手种子

功能说明:\n- 重构 Deep Research 调度与执行链,补齐 dispatcher、executor、live hub 与依赖注入入口,提升任务下发、执行、回调的稳定性\n- 增强运行时持久化与恢复能力,接入业务映射、任务来源与任务事件日志模型,覆盖持久化与执行可靠性关键路径测试\n- 新增 agentfx 报告助手 seed 与任务报告导入脚本配置,支持离线环境快速初始化与任务流模板回填\n- 完善 deep-research 与 thread_runs 路由参数编排,兼容不同业务映射与运行入口的前后端联动\n- 补充前端 agentfx deep-link 解析,保证 deep-research 场景下的登录跳转与任务上下文一致
This commit is contained in:
董宏凯 committed 2026-09-04 23:18:52 +08:00
1 parent 438772f0b7
commit 5c75e1af16
36 files changed
+3163 -312

No files matched your search

@@ -1389,17 +1389,40 @@ class ScheduledTaskService:
}
@staticmethod
def _build_conversion_prompt(skeleton_json: str, source: str, embedded_json: Any | None = None) -> str:
def _build_conversion_prompt(
skeleton_json: str,
source: str,
embedded_json: Any | None = None,
instructions: str | None = None,
) -> str:
parts = [
"请把下面的【源数据】转换为【目标结构】要求的 JSON。",
"请把下面的【源数据】转换成【目标结构】要求的 JSON,用于填充一个 HTML 展示模板。",
"模板只是一层**样式外壳**:它的字段名固定(页面脚本按字段名读取,绝不能改),"
"但每个字段的**含义要按源数据的主题重新解释**——把主题内容语义映射进各分区,"
"例如:总览指标填主题的核心数字;分组/区域类列表填主题的分区、品类或阵营;"
"组织/单位类列表填主题的机构、厂商或层级体系;装备/条目类列表填主题的产品、"
"技术或关键要素;事件/项目类列表填主题的时间线事项。内容必须全部来自【源数据】"
"的主题,不要被模板原有示例的领域限制住。",
"源数据可能是一段 JSON、一段纯文本、或包含 JSON 的文本——"
"其中若有结构化 JSON 以 JSON 内容为准;若是纯文本请理解其语义后据实填充;"
"源里没有对应内容的字段按其类型留空(\"\" / [] / null),不要臆造。",
"若下面的【任务要求】里带有对页面的明确修改指示(如“标题改为…”“只更新某部分”),"
"优先满足这些指示,其余字段可留空(页面将沿用模板现有内容);"
"没有指示到的部分按源数据自由发挥,尽量把各分区填满。",
"字段名必须与【目标结构】逐字一致(包括中文键名,原样复制),"
"严禁自造、翻译或改写字段名;数组元素的字段集合必须与样例元素相同,"
"源里没有的字段按类型留空即可,绝不能用自造的字段名顶替,也不要照抄任何示例值。",
"另外请在输出的 JSON 里额外携带两个顶层字符串字段:「页面标题」(按主题拟一个"
"页面大标题;若任务要求里明确给了标题,就用它)和「页面副标题」(一句话副标题)。",
"",
"【目标结构】(展示了完整字段与类型,其中数组只示意 1 个样例元素,实际请按源数据填充全部元素):",
"【目标结构】(字段与类型的空占位骨架,数组只示意 1 个样例元素,实际按源数据填充全部元素):",
"```json\n" + skeleton_json + "\n```",
"",
]
if instructions and instructions.strip():
parts.append("【任务要求】(用户对本次页面的要求/修改指示,优先级最高):")
parts.append(instructions.strip())
parts.append("")
if embedded_json is not None:
# 已从源数据里识别出结构化 JSON,单独标注帮助(尤其弱)模型对齐。
parts.append("【从源数据中识别到的结构化数据】(优先以此为准):")
@@ -1410,14 +1433,14 @@ class ScheduledTaskService:
parts.append("【源数据】:")
parts.append(source)
parts.append("")
parts.append("只输出一个 ```json 代码块,内含填充好的完整目标 JSON,不要任何解释文字。")
parts.append("只输出一个 ```json 代码块,内含填充好的完整目标 JSON(含「页面标题」「页面副标题」),不要任何解释文字。")
return "\n".join(parts)
@staticmethod
def _build_retry_prompt(base_prompt: str, errors: list[str], gaps: list[str]) -> str:
def _build_retry_prompt(base_prompt: str, problems: list[str], gaps: list[str]) -> str:
lines = [base_prompt, "\n\n上一轮转换结果未通过校验,请严格修正后重新输出**完整**的目标 JSON:"]
if errors:
lines.append("- 结构错误:" + ";".join(errors[:12]))
if problems:
lines.append("- " + ";".join(problems[:12]))
if gaps:
lines.append("- 字段缺失(请补齐):" + "、".join(gaps[:30]))
return "\n".join(lines)
@@ -1474,36 +1497,51 @@ class ScheduledTaskService:
model_name: str | None,
soul: str | None,
run_id: str,
instructions: str | None = None,
) -> dict[str, Any]:
"""把源数据(JSON/文本/含JSON文本)转换成模板的 DATA 结构,校验+回喂重试。
成功返回校验通过的对象;全部尝试失败抛 :class:`TemplateFillError`。
通过(结构+字段对齐)返回校验过的对象;重试耗尽时**尽力而为**——只要解析
出过 JSON 对象就返回最后一个(缺顶层键/字段错位的分支由随后的
``merge_with_reference`` 回退模板默认数据,抽多少用多少);只有全程没解析
出 JSON 才抛 :class:`TemplateFillError`(由调用方兜底为默认数据,不让
run 失败)。
"""
skeleton = template_fill.schema_skeleton_json(template_id)
# 源数据可能是纯 JSON / 纯文本 / 含 JSON 的文本:先尽力抽出内嵌 JSON 单独标注。
embedded_json = template_fill.extract_embedded_json(source)
base_prompt = self._build_conversion_prompt(skeleton, source, embedded_json)
last_errors: list[str] = []
base_prompt = self._build_conversion_prompt(skeleton, source, embedded_json, instructions=instructions)
last_problems: list[str] = []
prompt = base_prompt
candidate: dict[str, Any] | None = None
for attempt in range(_MAX_TEMPLATE_FILL_RETRIES + 1):
raw = await self._invoke_conversion_model(model_name, soul, prompt)
candidate = html_page_utils.extract_json_object(raw)
if candidate is None:
last_errors = ["模型未返回可解析的 JSON 对象"]
parsed = html_page_utils.extract_json_object(raw)
if parsed is None:
last_problems = ["模型未返回可解析的 JSON 对象"]
else:
errors = template_fill.validate_data(template_id, candidate)
if not errors:
candidate = parsed # 记住最后一个可解析结果,供重试耗尽时尽力返回
errors = [f"结构错误:{e}" for e in template_fill.validate_data(template_id, candidate)]
mismatches = [f"字段错位:{m}" for m in template_fill.shape_mismatches(template_id, candidate)]
if not errors and not mismatches:
return candidate
last_errors = errors
last_problems = errors + mismatches
gaps = template_fill.field_coverage_gaps(template_id, candidate)
prompt = self._build_retry_prompt(base_prompt, errors, gaps)
prompt = self._build_retry_prompt(base_prompt, last_problems, gaps)
logger.info(
"模板填充[run=%s]第 %d 次校验未通过:%s",
run_id,
attempt + 1,
";".join(last_errors[:5]),
";".join(last_problems[:5]),
)
raise TemplateFillError("转换结果未通过结构校验:" + ";".join(last_errors[:8]))
if candidate is not None:
logger.warning(
"模板填充[run=%s]重试耗尽仍未通过校验,尽力返回待兜底:%s",
run_id,
";".join(last_problems[:5]),
)
return candidate
raise TemplateFillError("转换结果未通过结构校验:" + ";".join(last_problems[:8]))
async def _finalize_template_html(
self,
@@ -1647,14 +1685,21 @@ class ScheduledTaskService:
# HTML 数据来源:抽取(开关开 + 有数据)→ 转换填充;否则用模板默认数据(子页面齐全)。
source = (data_text or "").strip()
used_default = True
page_title: str | None = None
page_subtitle: str | None = None
if do_extract and source:
# 转换阶段同样带上任务所选智能体:SOUL 提供领域口径,未显式选模型时
# 兜底用该智能体配置的模型(与模板填充模式一致)。
soul, conv_model = await self._agent_soul_and_model(task, model_name)
# 任务的描述/prompt 作为「任务要求」注入:用户对页面的修改指示(如
# "标题改为…"、"只更新某部分")优先级最高,没指示就按检索内容自由发挥。
instructions = "\n".join(part for part in (description, prompt) if part)
try:
converted = await self._convert_to_template_data(
tpl_id, source, model_name=conv_model, soul=soul, run_id=run_id
tpl_id, source, model_name=conv_model, soul=soul, run_id=run_id, instructions=instructions or None
)
# 页面标题/副标题是额外键,摘出来替换页头,不进 DATA。
page_title, page_subtitle = template_fill.pop_page_titles(converted)
# 子页面没抽到有效内容的,回退模板原有数据,避免子页面空白。
data_obj = template_fill.merge_with_reference(tpl_id, converted)
content = f"已检索数据并套用模板「{spec.name}」(空子页面回退原数据,含全部子页面)"
@@ -1672,7 +1717,9 @@ class ScheduledTaskService:
)
try:
html = template_fill.fill_template(tpl_id, data_obj, update_date=local_time.date())
html = template_fill.fill_template(
tpl_id, data_obj, update_date=local_time.date(), title=page_title, subtitle=page_subtitle
)
except template_fill.TemplateError as exc:
raise HtmlGenerationError(f"模板填充失败:{exc}") from exc
return await self._finalize_template_html(
@@ -1701,8 +1748,9 @@ class ScheduledTaskService:
Pipeline: 取源 JSON(任务 prompt) → 用内置「模板数据转换器」agent 的 SOUL +
模型把它映射成目标结构 → 结构校验(不过则回喂错误重试) → 填充模板 → 归档
``index.html`` + 持久化 ``scheduled_html_pages`` → 返回 ``format: "html"``
结果(复用现有 HTML 预览)。任一步彻底失败抛 :class:`TemplateFillError`,
run 记为 failed。
结果(复用现有 HTML 预览)。转换质量问题一律**不失败**:抽不到/抽错的分支由
``merge_with_reference`` 回退模板原有数据,转换彻底失败则整页用模板默认数据;
只有模板文件本身缺失/损坏才抛 :class:`TemplateFillError` 让 run 失败。
"""
template_id = _task_template_id(task)
spec = template_fill.get_template(template_id) if template_id else None
@@ -1726,6 +1774,8 @@ class ScheduledTaskService:
used_default=True,
)
page_title: str | None = None
page_subtitle: str | None = None
if not source:
# 未提供源数据 → 用模板自带默认数据(不调模型、不校验)。
data_obj = template_fill.reference_data(template_id)
@@ -1740,18 +1790,33 @@ class ScheduledTaskService:
model_name = str(tcfg.get("model_name") or "").strip() or None
soul, model_name = await self._agent_soul_and_model(task, model_name)
converted = await self._convert_to_template_data(
template_id, source, model_name=model_name, soul=soul, run_id=run_id
)
# 子页面没抽到有效内容的,回退模板原有数据,避免子页面空白。
data_obj = template_fill.merge_with_reference(template_id, converted)
content = f"已根据源数据填充模板「{spec.name}」生成页面"
used_default = False
try:
converted = await self._convert_to_template_data(
template_id, source, model_name=model_name, soul=soul, run_id=run_id
)
except TemplateFillError:
# 转换彻底失败(全程没解析出 JSON)→ 也不让 run 失败:用模板默认
# 数据出页,与 require_html 模板参考路径的兜底一致。
logger.warning(
"模板填充转换失败,回退默认数据 run=%s tpl=%s", run_id, template_id, exc_info=True
)
data_obj = template_fill.reference_data(template_id)
content = f"数据转换未通过,已用模板「{spec.name}」的默认数据生成页面(含全部子页面)"
used_default = True
else:
# 页面标题/副标题是额外键,摘出来替换页头,不进 DATA。
page_title, page_subtitle = template_fill.pop_page_titles(converted)
# 抽不到/抽错的子页面与字段回退模板原有数据,避免子页面空白或 undefined。
data_obj = template_fill.merge_with_reference(template_id, converted)
content = f"已根据源数据填充模板「{spec.name}」生成页面(抽取不到的部分沿用模板原有数据)"
used_default = False
task_tz = ZoneInfo(task.get("timezone") or "UTC")
local_time = scheduled_for.astimezone(task_tz)
try:
html = template_fill.fill_template(template_id, data_obj, update_date=local_time.date())
html = template_fill.fill_template(
template_id, data_obj, update_date=local_time.date(), title=page_title, subtitle=page_subtitle
)
except template_fill.TemplateError as exc:
raise TemplateFillError(f"模板填充失败:{exc}") from exc
return await self._finalize_template_html(