圆桌第三步流程图模式 + 后台 DAG 任务编排

- 方案总结报告:用户要求结构化输出/流程图时跳过 md 直出 flow-json 流程图,
  报告用文字展示;报告与流程图均可多轮修改、互相切换(detectFlowIntent 识别意图)
- 流程图画布放右侧沙箱位(sidePanel 插槽)不覆盖消息列表,可与 md 预览切换;
  节点随容器宽度自适应缩放并 fitView 居中
- 后台挂起支持真 DAG 编排(分层并行/阶段目标/总控提示词),新增
  orchestration_plan 持久化列 + 迁移;大弹窗流程图按 DAG 分层渲染

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
董宏凯andClaude Fable 5 committed 2026-06-12 13:52:17 +08:00
1 parent b33426416b
commit 086c280e5d
25 files changed
+880 -149

No files matched your search

@@ -20,13 +20,18 @@ from .types import (
CHAIN_CLOSEOUT_PROMPT,
CONTINUE_PROMPT,
MAX_CYCLES,
DagPlan,
DagStage,
LeaderTurn,
ReportResult,
RoundtableGateway,
SeatRef,
SeatTurn,
build_chain_leader_task,
build_dag_stage_leader_task,
parse_dag_plan,
pick_chain_task,
pick_dag_seat_task,
)
__all__ = [
@@ -40,9 +45,14 @@ __all__ = [
"SeatTurn",
"ReportResult",
"SeatRef",
"DagStage",
"DagPlan",
"MAX_CYCLES",
"CONTINUE_PROMPT",
"CHAIN_CLOSEOUT_PROMPT",
"build_chain_leader_task",
"pick_chain_task",
"build_dag_stage_leader_task",
"parse_dag_plan",
"pick_dag_seat_task",
]
@@ -18,6 +18,7 @@
from __future__ import annotations
import asyncio
import logging
from dataclasses import dataclass, field
from datetime import UTC, datetime
@@ -27,11 +28,15 @@ from .types import (
CHAIN_CLOSEOUT_PROMPT,
CONTINUE_PROMPT,
MAX_CYCLES,
DagPlan,
ReportResult,
RoundtableGateway,
SeatRef,
build_chain_leader_task,
build_dag_stage_leader_task,
parse_dag_plan,
pick_chain_task,
pick_dag_seat_task,
)
logger = logging.getLogger(__name__)
@@ -73,6 +78,7 @@ async def run_orchestration(
mode: str = "recommend",
intent_text: str = "",
enable_report: bool = True,
plan: dict | None = None,
) -> OrchestrationResult:
"""运行一次完整编排(循环 → 共识 → 报告绘制)。
@@ -84,8 +90,10 @@ async def run_orchestration(
coordinator_name: 总控 agent_id(如 "roundtable-coordinator")。
model: 选定模型(None/"" 走后端默认)。
seed_message: 第一轮 leader 的 prompt(启动=初始意图;resume=用户答案续轮)。
mode: "recommend" | "chain"。
mode: "recommend" | "chain" | "dag"。
intent_text: 任务意图,用于报告 prompt(缺省退回 seed_message)。
plan: dag 模式的分层编排计划(前端 ``OrchestrationPlan`` dict)。mode=="dag" 且
可解析出非空 stages 时走 ``_run_dag``;否则(dag 但 plan 缺失/为空)回退 recommend。
enable_report: 是否在收口后执行 Step3 报告绘制。False 时只跑完 Step2 研讨即收尾、
不生成报告(step3=None)。当前「后台挂起」临时禁用报告(进程内驱动报告 agent
在真模型下仍无法稳定写出 HTML,详见 multi-agent-background-run-遗留问题与下次继续.md)。
@@ -93,9 +101,13 @@ async def run_orchestration(
intent = (intent_text or seed_message or "").strip()
try:
await progress.begin()
if mode == "chain":
dag_plan = parse_dag_plan(plan) if mode == "dag" else None
if mode == "dag" and dag_plan is not None:
outcome = await _run_dag(gateway, progress, agents, thread_ids, coordinator_name, model, seed_message, intent, dag_plan)
elif mode == "chain":
outcome = await _run_chain(gateway, progress, agents, thread_ids, coordinator_name, model, seed_message, intent)
else:
# recommend,或 dag 但 plan 缺失/为空 → 回退总控自由派活(绝不静默跑错语义)。
outcome = await _run_recommend(gateway, progress, agents, thread_ids, coordinator_name, model, seed_message, intent)
if outcome.kind == "clarification":
@@ -314,6 +326,108 @@ async def _run_chain(
return _LoopOutcome("consensus", last_leader_content=last_leader, deliveries=deliveries)
# ── dag 模式(分层 DAG:stage 间串行、stage 内并行)──────────────────────────────
async def _run_dag(
gateway: RoundtableGateway,
progress: JobProgressWriter,
agents: list[SeatRef],
thread_ids: dict[str, str],
coordinator_name: str,
model: str | None,
seed_message: str,
intent_text: str,
plan: DagPlan,
) -> _LoopOutcome:
"""分层 DAG 编排:每个 stage 一轮总控派活(钉死本批席位)→ 批内席位**并行**执行
(``asyncio.gather``)→ 下一 stage 总控再派;全部 stage 完成后由总控收口综合。
与前端 ``runDagOrchestration``「总控驱动每 stage 派活」同构(§12.4)。并行席位各自独立
thread(``run_seat`` 内 ``thread_ids[agent_id]``),故进程内 gather 安全、无沙箱串台。
"""
deliveries: dict[str, str] = {}
last_leader = ""
total = len(plan.stages)
name_by_id = {a.agent_id: a.name for a in agents}
def _seat_ref(agent_id: str) -> SeatRef:
return SeatRef(agent_id, name_by_id.get(agent_id, agent_id))
for i, stage in enumerate(plan.stages):
stage_seats = [_seat_ref(aid) for aid in stage.agent_ids]
if not stage_seats:
continue
# (a) 总控「派活轮」:钉死本 stage 席位,带任务背景 / 本阶段目标 / 总控编排指引 + 此前交付。
await progress.leader_thinking(i + 1)
leader_task = build_dag_stage_leader_task(
seed_message=seed_message,
stage_index=i,
total_stages=total,
seats=stage_seats,
is_first=(i == 0),
goal=stage.goal,
coordinator_prompt=plan.coordinator_prompt,
)
block = _deliveries_block(deliveries, name_by_id)
if block:
leader_task += f"\n\n此前各阶段席位已完成的交付如下(供你承上启下、为本批席位派活):\n{block}"
turn = await gateway.run_leader(
thread_ids=thread_ids,
coordinator_name=coordinator_name,
message=leader_task,
model=model,
)
if turn.final_text:
last_leader = turn.final_text
await progress.add_leader_dialogue(
turn.final_text, i + 1, tool_calls=turn.tool_calls, thread_id=thread_ids.get(coordinator_name)
)
if turn.is_clarification:
return _LoopOutcome("clarification", question=turn.clarification, last_leader_content=last_leader, deliveries=deliveries)
# (b) 批内并行:每个钉死席位拿到总控派给它的 task(漏派则给干净本职任务),并行执行。
await progress.dispatching(i + 1)
for seat in stage_seats:
await progress.seat_active(seat.agent_id)
async def _run_one(seat: SeatRef) -> None:
task = pick_dag_seat_task(turn.dispatched, seat.agent_id, seat.name, goal=stage.goal)
seat_msg = _seat_message(intent_text, deliveries, name_by_id, task)
seat_turn = await gateway.run_seat(thread_ids=thread_ids, agent_id=seat.agent_id, task=seat_msg, model=model)
deliveries[seat.agent_id] = seat_turn.final_text
await progress.add_seat_dialogue(
seat.agent_id, seat.name, seat_turn.final_text, i + 1,
tool_calls=seat_turn.tool_calls, thread_id=thread_ids.get(seat.agent_id),
)
await progress.seat_done(seat.agent_id, i + 1)
await asyncio.gather(*(_run_one(seat) for seat in stage_seats))
if total > 0:
await progress.set_consensus_pct(round((i + 1) / total * 90))
# (c) 收口:finalSynthesis 时总控综合全部 stage 交付,产出最终结论。
if plan.final_synthesis and total > 0:
await progress.leader_thinking(total + 1)
block = _deliveries_block(deliveries, name_by_id)
closeout_msg = CHAIN_CLOSEOUT_PROMPT + (f"\n\n各阶段席位完整交付如下:\n{block}" if block else "")
closeout = await gateway.run_leader(
thread_ids=thread_ids,
coordinator_name=coordinator_name,
message=closeout_msg,
model=model,
)
if closeout.final_text:
last_leader = closeout.final_text
await progress.add_leader_dialogue(
closeout.final_text, total + 1, tool_calls=closeout.tool_calls, thread_id=thread_ids.get(coordinator_name)
)
return _LoopOutcome("consensus", last_leader_content=last_leader, deliveries=deliveries)
# ── 报告阶段 ─────────────────────────────────────────────────────────────────
@@ -37,9 +37,10 @@ class SimulatedRoundtableGateway:
async def run_leader(self, *, thread_ids, coordinator_name, message, model) -> LeaderTurn:
await self._tick()
self._leader_calls += 1
if self._mode == "chain":
# chain 模式由引擎按链条顺序强制跑席位,leader 只给说明、不派活。
return LeaderTurn(final_text="(模拟)总控:请当前席位按职责给出分析。", dispatched=[])
if self._mode in ("chain", "dag"):
# chain / dag 模式由引擎按计划钉死席位强制执行,leader 只给说明、不显式派活
# (引擎的 pick_*_task 会回退给席位干净本职任务)。
return LeaderTurn(final_text="(模拟)总控:请本阶段席位按职责给出分析。", dispatched=[])
# recommend:首轮派活全部席位,次轮共识。
if self._leader_calls == 1:
return LeaderTurn(
@@ -14,7 +14,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Protocol, runtime_checkable
from typing import Any, Protocol, runtime_checkable
# 编排循环最大轮次,与前端 roundtable-constants.ts MAX_CYCLES 对齐。
MAX_CYCLES = 8
@@ -195,3 +195,137 @@ def pick_chain_task(
f"请你作为「{seat_name}」,基于任务背景与此前各席位的交付,"
"从你的专业职责出发给出你的分析与交付。"
)
# ── dag 模式:分层编排计划 + prompt 构造(移植自前端 dag-types.ts)─────────────────
#
# DAG = 有序的 stage 列表:stage 间串行、stage 内并行。线性链是其特例(每层 1 席位)。
# 与前端 `runDagOrchestration`「总控驱动每 stage 派活」同构(§3.2 方案 A + 批内并行):
# 每个 stage 一轮总控派活(钉死本批席位)→ 批内席位并行执行 → 下一 stage 总控再派。
@dataclass(frozen=True)
class DagStage:
"""一个并行批次:``agent_ids`` 内的席位并行执行;``goal`` = 用户写的本阶段目标(可空)。"""
agent_ids: list[str]
goal: str | None = None
@property
def is_parallel(self) -> bool:
return len(self.agent_ids) > 1
@dataclass(frozen=True)
class DagPlan:
"""用户编排出的执行计划。``stages`` 顺序即串行顺序。"""
stages: list[DagStage]
final_synthesis: bool = True
coordinator_prompt: str | None = None
def parse_dag_plan(raw: Any) -> DagPlan | None:
"""把前端 ``OrchestrationPlan`` 形状的 dict 解析成 ``DagPlan``(容错)。
无 stages / 全空 stage → 返回 None(调用方据此回退 recommend)。只保留有 agentId 的 stage。
"""
if not isinstance(raw, dict):
return None
stages_raw = raw.get("stages")
if not isinstance(stages_raw, list):
return None
stages: list[DagStage] = []
for s in stages_raw:
if not isinstance(s, dict):
continue
ids_raw = s.get("agentIds") or s.get("agent_ids") or []
ids = [str(a) for a in ids_raw if str(a or "").strip()]
if not ids:
continue
goal = s.get("goal")
goal_text = str(goal).strip() if isinstance(goal, str) and goal.strip() else None
stages.append(DagStage(agent_ids=ids, goal=goal_text))
if not stages:
return None
final_synthesis = raw.get("finalSynthesis")
if final_synthesis is None:
final_synthesis = raw.get("final_synthesis", True)
cp = raw.get("coordinatorPrompt") or raw.get("coordinator_prompt")
cp_text = str(cp).strip() if isinstance(cp, str) and cp.strip() else None
return DagPlan(stages=stages, final_synthesis=bool(final_synthesis), coordinator_prompt=cp_text)
def build_dag_stage_leader_task(
*,
seed_message: str,
stage_index: int,
total_stages: int,
seats: list[SeatRef],
is_first: bool,
goal: str | None = None,
coordinator_prompt: str | None = None,
) -> str:
"""构造 dag「每 stage 派活轮」leader prompt:约束总控只对本 stage 钉死席位派活。
对齐前端 ``buildDagStageLeaderTask``:首 stage 带任务背景,后续 stage 靠后端注入的此前
交付摘要承上;带「本阶段目标」与「总控编排指引(用户预设,最高优先)」。
"""
ordinal = f"{stage_index + 1}/{total_stages}"
seat_list = "、".join(f"「{s.name}」(agent_name: {s.agent_id})" for s in seats)
is_parallel = len(seats) > 1
goal_text = (goal or "").strip()
coord_text = (coordinator_prompt or "").strip()
lines: list[str] = []
if is_first:
lines += ["这是一次【分层 DAG 编排】的多智能体圆桌研讨。任务背景如下:", seed_message, ""]
else:
lines += ["分层研讨继续。系统已把此前各阶段席位的交付摘要注入到你本轮输入里,请据此承上启下。", ""]
if coord_text:
lines += [
"【总控编排指引(用户预设,最高优先)】以下是本次业务链条为你(总控)预设的整体派活原则,请在每一阶段派活时都严格遵循:",
coord_text,
"",
]
lines += [
f"本研讨严格按预设分层顺序进行,共 {total_stages} 个阶段,现在是第 {ordinal} 个阶段。",
f"本阶段需要执行的席位(已由编排计划钉死)是:{seat_list}。",
]
if goal_text:
lines += [
f"【本阶段目标】{goal_text}",
"请据此目标为每个席位拆解任务,并要求他们显式承接上一阶段的产出来完成本阶段目标。",
]
lines += [
f"请你作为总控,通过 agent_orchestration 技能**分别**向上述{'这些席位' if is_parallel else '席位'}派活,"
f"结合任务背景{'、本阶段目标' if goal_text else ''}与此前交付,为每个席位分配聚焦其职责的本阶段任务。",
"只派给上述席位、且每个都必须派到;不要派给清单外的任何席位,也不要自己直接作答或给出最终结论。",
]
if is_parallel:
lines.append(f"注意:本阶段这 {len(seats)} 个席位会并行执行,请确保给每个席位的 task 都能独立完成,不要让它们互相等待。")
return "\n".join(lines)
def pick_dag_seat_task(
dispatched: list[tuple[str, str]],
seat_agent_id: str,
seat_name: str,
*,
goal: str | None = None,
) -> str:
"""从总控「每 stage 派活轮」终态取派给某钉死席位的 task(移植自前端 pickDagSeatTask)。
1) 命中 agent_name 完全一致的派活 → 用它的 task;
2) 未命中 / 总控只写文字没派活 → **不**把总控派活叙述喂给席位(防席位模仿派活),改给干净
本职任务(任务背景 + 此前交付由 ``_seat_message`` 另行注入)。
两条分支都带「本阶段目标」兜底。
"""
goal_rule = f"\n【本阶段目标】{goal.strip()}\n请确保你的交付服务于该目标,并显式承接上一阶段的产出。" if (goal or "").strip() else ""
wanted = seat_agent_id.lower()
for name, task in dispatched:
if name.lower() == wanted and (task or "").strip():
return f"请你作为「{seat_name}」,完成总控派给你的本阶段任务:\n{task.strip()}{goal_rule}"
return (
f"请你作为「{seat_name}」,从你的专业职责出发,独立完成本阶段属于你的分析与交付。"
f"此前各阶段席位的交付已在上下文里,请据此承接。{goal_rule}"
)
@@ -0,0 +1,47 @@
"""Add orchestration_plan column to roundtable_jobs.
后台挂起支持分层 DAG 编排(业务链并行):把前端 ``OrchestrationPlan``(stages /
阶段目标 / 总控提示词 / finalSynthesis)整份存进 job 行,驱动后端 ``_run_dag``
(stage 串行、stage 内并行)+ 前端大弹窗按 stage 分层画流程图 + resume 时重建计划。
LONGTEXT(计划 JSON 可超 64 KB)。
Revision ID: 20260612_01
Revises: 20260611_01
Create Date: 2026-06-12
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260612_01"
down_revision = "20260611_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_jobs") and not _has_column("roundtable_jobs", "orchestration_plan"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_jobs", sa.Column("orchestration_plan", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_jobs", "orchestration_plan"):
op.drop_column("roundtable_jobs", "orchestration_plan")
@@ -51,10 +51,14 @@ class RoundtableJobRow(Base):
# ThreadIdMap: JSON object { "<agent_id>": "<thread_id>", ... }.
thread_ids: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
coordinator_name: Mapped[str | None] = mapped_column(String(128), nullable=True)
# "recommend"(总控自由派活)| "chain"(按业务链条顺序派活).
# "recommend"(总控自由派活)| "chain"(按业务链条顺序派活)| "dag"(分层 DAG:stage 间串行、stage 内并行).
orchestration_mode: Mapped[str] = mapped_column(String(16), nullable=False, default="recommend")
# chain 模式来源链条快照:JSON object { id, title }(recommend 模式为 null).
chain: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
# dag 模式分层编排计划:JSON object { mode, stages:[{id,agentIds,goal?}], finalSynthesis,
# coordinatorPrompt? }(对齐前端 OrchestrationPlan)。仅 dag 模式有值;驱动后端 _run_dag
# (stage 串行 / stage 内并行)+ 前端大弹窗按 stage 分层画流程图 + resume 时重建计划。
orchestration_plan: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
# 研讨对话记录:JSON array of { id, role('leader'|'seat'), agentId, name, content, cycle }。
# 让用户跑完 / 进行中都能看到真实研讨内容(leader 说明 + 各席位交付),而非只有流程图。
dialogues: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
@@ -55,7 +55,7 @@ class RoundtableJobRepository:
for k in ("created_at", "updated_at"):
if isinstance(d.get(k), datetime):
d[k] = d[k].isoformat()
for k in ("dispatch_chain", "thread_ids", "chain", "dialogues", "step3"):
for k in ("dispatch_chain", "thread_ids", "chain", "orchestration_plan", "dialogues", "step3"):
d[k] = _loads(d.get(k))
return d
@@ -71,6 +71,7 @@ class RoundtableJobRepository:
coordinator_name: str | None = None,
thread_ids: dict[str, str] | None = None,
chain: dict[str, Any] | None = None,
orchestration_plan: dict[str, Any] | None = None,
dispatch_chain: list[dict[str, Any]] | None = None,
status: str = "queued",
phase: str = "initializing",
@@ -92,6 +93,7 @@ class RoundtableJobRepository:
coordinator_name=coordinator_name,
orchestration_mode=orchestration_mode,
chain=_dumps(chain),
orchestration_plan=_dumps(orchestration_plan),
error=None,
created_at=now,
updated_at=now,