feat(roundtable): 圆桌 Step2 分层 DAG 编排(并行/沙箱双模式 + 流程图 + 按需取全文)
数据模型/编辑器:链条加 stages 分层(前后端 + alembic 20260607_03);BusinessChainEditorPage 竖列 Stage 编辑 + 底部只读流程图预览;lib/dag-types + chain-stages 纯逻辑(含单测)。 调度(runDagOrchestration,方案 A 总控驱动):每个 stage 由总控经 agent_orchestration 派活给计划钉死的席位,批内 Promise.all 并行、批间 barrier 串行;末尾交回 runOrchestration 收口。抑制 leader 预广播 + 干净席位任务,根治『席位模仿派活』。 执行子模式:快速(双列·产物走正文·禁写文件 seat_parallel)/ 沙箱(单列·写 .md·沙箱跟随预览 seat);统一禁 bash(防 .py 脚本),提示词禁 .py。 显示:头像条 + 两列/单列 + ref 全量累积 + 节流 flush(仅选中渲染);DAG 流程图弹窗(按 stage 分列,节点随执行点亮,只到共识);沙箱跟随当前席位(防错位 + 修第一个席位自动开沙箱)。 按需取全文:新增 harness 只读工具 read_peer_delivery(从 run context 取网关注入的前序席位完整交付),席位默认看摘要、需要时取全文。 修:宽表溢出、并行自动下滑、data-lov-id Fragment 警告等。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5164fd362c
commit
7b8c11852e
26 files changed
+3719
-216
No files matched your search
@@ -18,13 +18,25 @@
|
||||
总控的唯一职责是「派活 / 澄清 / 收口呈现」,没有任何理由动文件系统或执行命令。
|
||||
并配合 ``SkillStopMiddleware`` 在 ``agent_orchestration`` 调用后停图,便于网关从
|
||||
AIMessage.tool_calls 解析派活列表。
|
||||
- ``seat`` —— 子智能体交付:开 thinking + medium reasoning;禁派活 /
|
||||
澄清 / 展示文件 / 看图 / 联网搜索(与前端 ``_special_run`` 一致)。
|
||||
- ``report`` —— Step3 报告绘制:在 ``seat`` 基础上**额外禁 ``bash`` /
|
||||
- ``seat`` —— 子智能体交付:开 thinking + medium reasoning;**可写文件**
|
||||
(``write_file`` / ``str_replace`` 产出 md 等成品文档),但禁派活 / 澄清 /
|
||||
展示文件 / 看图 / 联网搜索 / **``bash``**。禁 ``bash`` 的原因:圆桌席位是
|
||||
「文档产出者」,弱模型爱写 ``.py`` 脚本再跑出产物(乱且抓不到预览),与
|
||||
``report`` 角色禁 ``bash`` 同理;让它**直接 write_file 写成品文档**。
|
||||
- ``seat_parallel`` —— **DAG 快速(fast)模式的并行席位(方案 A,2026-06)**:**禁写文件**
|
||||
(``write_file`` / ``str_replace``,产物走正文)+ 禁 ``bash`` + 禁「打断 / 越权」类,
|
||||
**放开 ``web_search`` 与技能**(搜索不碰 sandbox;技能靠 ``read_file`` SKILL.md)——
|
||||
否则并行席位几乎调不动工具、产生不了步骤(步骤条不显示)。
|
||||
「写文件产出 md」归 **沙箱(sandbox)模式**(走 ``seat`` policy,单列 + 沙箱跟随预览);
|
||||
fast 模式快、双列、产物走正文 —— 用户明确要求 fast 不生成文件。详见
|
||||
``docs/roundtable-dag-orchestration.md`` §4 / §12.1 / §12.8 / §12.10。
|
||||
与 ``seat`` 的差异:``seat`` 禁 ``web_search``(旧「圆桌一律禁搜索」),
|
||||
``seat_parallel`` **放开搜索**(本期诉求)。
|
||||
- ``report`` —— Step3 报告绘制:在 ``seat``(已禁 ``bash``)基础上**额外禁
|
||||
``str_replace``**:
|
||||
* 禁 ``bash`` → 杜绝它写 Python 脚本再跑出 HTML(脚本产物落在 outputs,
|
||||
但前端虚拟预览只抓 ``write_file`` 的 ``args.content``,抓不到脚本产物 →
|
||||
预览停在半截 ``write_file``,正是「没写完就去生成 py 文件」的现象);
|
||||
* ``bash`` 已在 ``seat`` 禁 → 杜绝写 Python 脚本再跑出 HTML(脚本产物落在
|
||||
outputs,但前端虚拟预览只抓 ``write_file`` 的 ``args.content``,抓不到脚本
|
||||
产物 → 预览停在半截 ``write_file``,正是「没写完就去生成 py 文件」的现象);
|
||||
* 禁 ``str_replace`` → 强制返工用整文件 ``write_file`` 重写
|
||||
(``str_replace`` 没有 ``content`` 字段,会让前端虚拟预览读到 undefined
|
||||
而清空沙箱)。
|
||||
@@ -58,9 +70,36 @@ _LEADER_EXCLUDED: list[str] = [
|
||||
"hindsight_recall",
|
||||
"hindsight_reflect",
|
||||
"hindsight_retain",
|
||||
"read_peer_delivery", # 总控靠 _collect_delivery_status 直读各席位,不需要这个席位侧工具
|
||||
]
|
||||
_SEAT_EXCLUDED: list[str] = ["web_search", "ask_clarification", "present_files", "view_image", "agent_orchestration"]
|
||||
_REPORT_EXCLUDED: list[str] = [*_SEAT_EXCLUDED, "bash", "str_replace"]
|
||||
# seat:席位**可以写文件**(write_file / str_replace)产出 md 等成品文档,但**禁 bash** ——
|
||||
# 圆桌席位是「文档产出者」,不该跑 shell/python 脚本(弱模型爱写 .py 脚本再跑生成产物,既乱又
|
||||
# 抓不到产物预览,与 report 角色禁 bash 同理)。禁 web_search(圆桌串行一律禁搜索,旧决策)。
|
||||
_SEAT_EXCLUDED: list[str] = [
|
||||
"web_search",
|
||||
"ask_clarification",
|
||||
"present_files",
|
||||
"view_image",
|
||||
"agent_orchestration",
|
||||
"bash",
|
||||
]
|
||||
# 并行席位 = **快速(fast)模式**(双列):**禁写文件**(产物走正文)+ 禁跑命令 +「打断/越权」类,
|
||||
# **放开 web_search / 技能**(搜索不碰 sandbox;技能靠 read_file;注意不继承 seat 的 web_search
|
||||
# 禁用,故意显式列举,以便并行席位能联网搜索、产生工具步骤步骤条)。
|
||||
# 「写文件」归 **沙箱(sandbox)模式**(seat policy,单列 + 沙箱跟随预览);fast 模式快、双列、
|
||||
# 产物走正文 —— 用户明确要求 fast 不生成文件(2026-06 §12.10)。
|
||||
_SEAT_PARALLEL_EXCLUDED: list[str] = [
|
||||
"ask_clarification", # 并行批次不打断问澄清
|
||||
"present_files", # 产物走正文,不呈现文件
|
||||
"view_image",
|
||||
"agent_orchestration", # 席位不派活
|
||||
"bash", # 禁跑脚本(防 .py 脚本生成产物)
|
||||
"write_file", # fast 模式产物走正文,不写文件(写文件归 sandbox 模式)
|
||||
"str_replace",
|
||||
]
|
||||
# report:在 seat 基础上额外禁 str_replace(bash 已在 seat 禁)——强制整文件 write_file 重写,
|
||||
# 让前端虚拟预览能拿到完整 args.content。report 是 Step3 单独绘制,不读前序席位 → 禁 read_peer_delivery。
|
||||
_REPORT_EXCLUDED: list[str] = [*_SEAT_EXCLUDED, "str_replace", "read_peer_delivery"]
|
||||
|
||||
# leader 内禀的 skill_stop:``agent_orchestration`` 调用后停图。调用方可在此基础上
|
||||
# 再叠加自己的 skill_stop(见 ``merge_skill_stop_names``)。
|
||||
@@ -82,7 +121,7 @@ class RoundtableRunPolicy:
|
||||
|
||||
|
||||
def roundtable_run_policy(role: str) -> RoundtableRunPolicy:
|
||||
"""返回某角色(``leader`` / ``seat`` / ``report``)的单轮 run 参数。
|
||||
"""返回某角色(``leader`` / ``seat`` / ``seat_parallel`` / ``report``)的单轮 run 参数。
|
||||
|
||||
返回值里的列表是**新副本**,调用方可安全地再 append/merge 而不污染本模块常量。
|
||||
未知角色抛 ``ValueError``(早失败,避免悄悄退化到错误的工具面)。
|
||||
@@ -101,6 +140,14 @@ def roundtable_run_policy(role: str) -> RoundtableRunPolicy:
|
||||
thinking_enabled=True,
|
||||
reasoning_effort="medium",
|
||||
)
|
||||
if role == "seat_parallel":
|
||||
# 同 seat(thinking + medium),但额外禁写文件 / 跑命令(防并行沙箱打架)。
|
||||
return RoundtableRunPolicy(
|
||||
excluded_tools=list(_SEAT_PARALLEL_EXCLUDED),
|
||||
skill_stop_names=[],
|
||||
thinking_enabled=True,
|
||||
reasoning_effort="medium",
|
||||
)
|
||||
if role == "report":
|
||||
return RoundtableRunPolicy(
|
||||
excluded_tools=list(_REPORT_EXCLUDED),
|
||||
@@ -108,7 +155,7 @@ def roundtable_run_policy(role: str) -> RoundtableRunPolicy:
|
||||
thinking_enabled=True,
|
||||
reasoning_effort="medium",
|
||||
)
|
||||
raise ValueError(f"unknown roundtable role: {role!r} (expected leader/seat/report)")
|
||||
raise ValueError(f"unknown roundtable role: {role!r} (expected leader/seat/seat_parallel/report)")
|
||||
|
||||
|
||||
def merge_skill_stop_names(policy_names: list[str], caller_names: list[str] | None) -> list[str]:
|
||||
|
||||
@@ -637,6 +637,7 @@ def _run_payload(
|
||||
thinking_enabled: bool = True,
|
||||
reasoning_effort: str = "medium",
|
||||
multitask_strategy: str = "reject",
|
||||
extra_context: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造 ``POST /api/threads/{thread_id}/runs/stream`` 的请求体。
|
||||
|
||||
@@ -649,7 +650,7 @@ def _run_payload(
|
||||
应传 ``thinking_enabled=False`` + ``reasoning_effort="low"``,省掉模型先吐
|
||||
reasoning tokens 才开口的时间,显著降低前端"调度中"首字节延迟。
|
||||
"""
|
||||
return {
|
||||
payload: dict[str, Any] = {
|
||||
"input": {
|
||||
"messages": [
|
||||
{
|
||||
@@ -697,6 +698,11 @@ def _run_payload(
|
||||
"excluded_tools": excluded_tools,
|
||||
"skill_stop_names": skill_stop_names,
|
||||
}
|
||||
# 额外注入 run context(如圆桌席位的 roundtable_peer_deliveries:前序席位完整交付,
|
||||
# 供 read_peer_delivery 工具按需读取)。只进 context dict,不进 prompt → 不调工具就不耗 token。
|
||||
if extra_context:
|
||||
payload["context"].update(extra_context)
|
||||
return payload
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1251,6 +1257,7 @@ async def _leader_run(
|
||||
model_name: str,
|
||||
seat_meta: dict[str, dict[str, Any]] | None = None,
|
||||
synthesis_mode: bool = False,
|
||||
suppress_pre_broadcast: bool = False,
|
||||
) -> AsyncIterator[str | dict[str, Any]]:
|
||||
"""总控(leader)单轮:透传上游 SSE + 末尾 yield 一个 dict 状态帧(由路由层 ``json.dumps``)。
|
||||
|
||||
@@ -1319,8 +1326,19 @@ async def _leader_run(
|
||||
)
|
||||
|
||||
# 与上游 LLM 并行,减少「总控已开始想但席位 thread 里还没有用户消息」的窗口。
|
||||
pre_broadcast_task = asyncio.create_task(
|
||||
_broadcast(client, base, headers, "总控智能体收到用户消息:" + new_message, agent_threads, [agent_name])
|
||||
#
|
||||
# ``suppress_pre_broadcast``:DAG「每 stage 派活轮」(方案 A)置真——此时 ``new_message`` 是
|
||||
# 「请你作为总控…通过 agent_orchestration 派活给席位…」的**派活 prompt**,若广播进各席位
|
||||
# thread,弱模型(deepseek)会从历史里捡到「派活」意图,**席位跟着模仿派活 / 绕道 bash 调
|
||||
# 内部接口**(已观测 bug-1~4)。DAG 下席位的任务由前端 ``pickDagSeatTask`` 直接、干净地下发
|
||||
# (含任务背景),此处不需要、也不应把总控的派活 prompt 播给席位。recommend/chain 不传该 flag,
|
||||
# 行为不变。
|
||||
pre_broadcast_task = (
|
||||
None
|
||||
if suppress_pre_broadcast
|
||||
else asyncio.create_task(
|
||||
_broadcast(client, base, headers, "总控智能体收到用户消息:" + new_message, agent_threads, [agent_name])
|
||||
)
|
||||
)
|
||||
thread_id = agent_threads[agent_name]
|
||||
# 角色参数取自单一数据源 roundtable_run_policy(leader:禁 web_search、停
|
||||
@@ -1399,15 +1417,16 @@ async def _leader_run(
|
||||
"(expected on rollback preemption; otherwise check the upstream run's server-side error)",
|
||||
agent_name,
|
||||
)
|
||||
with contextlib.suppress(Exception):
|
||||
await pre_broadcast_task
|
||||
if pre_broadcast_task is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
await pre_broadcast_task
|
||||
return
|
||||
|
||||
# Pre-broadcast must finish before we yield the final status frame on any
|
||||
# branch — the seats that get dispatched next rely on having seen the
|
||||
# original user message. Only await it once (first attempt); the rare
|
||||
# self-correction retry reuses the same already-awaited broadcast.
|
||||
if attempt == 0:
|
||||
if attempt == 0 and pre_broadcast_task is not None:
|
||||
t_before_broadcast_await = time.perf_counter()
|
||||
try:
|
||||
await pre_broadcast_task
|
||||
@@ -1485,14 +1504,18 @@ async def _leader_run(
|
||||
# 其它席位"总控给 X 派了什么活")改成 detached 后台任务,不再 await 阻塞 —— 否则广播
|
||||
# 读写各席位巨大 thread 状态会卡几十秒,白白拖慢席位启动(见 _spawn_detached_broadcast)。
|
||||
yield {"status": dispatched, "content": leader_text, "agent_name": agent_name}
|
||||
for sub_name, task_text in valid_dispatch:
|
||||
_spawn_detached_broadcast(
|
||||
base,
|
||||
headers,
|
||||
f"总控智能体给{sub_name}派活,内容为:" + task_text,
|
||||
agent_threads,
|
||||
[agent_name, sub_name],
|
||||
)
|
||||
# DAG 派活轮(suppress_pre_broadcast)同样**不**把「总控给 X 派活」广播给兄弟席位 ——
|
||||
# 否则弱模型从历史里看到派活语句又会模仿派活(席位任务由前端 pickDagSeatTask 干净下发,
|
||||
# 跨席位承上靠各 special run 的"完成交付"后广播,不需要这条派活广播)。recommend/chain 照旧。
|
||||
if not suppress_pre_broadcast:
|
||||
for sub_name, task_text in valid_dispatch:
|
||||
_spawn_detached_broadcast(
|
||||
base,
|
||||
headers,
|
||||
f"总控智能体给{sub_name}派活,内容为:" + task_text,
|
||||
agent_threads,
|
||||
[agent_name, sub_name],
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
@@ -1507,6 +1530,8 @@ async def _special_run(
|
||||
model_name: str,
|
||||
*,
|
||||
display_name: str = "",
|
||||
no_file: bool = False,
|
||||
peer_deliveries: list[dict[str, Any]] | None = None,
|
||||
) -> AsyncIterator[str | dict[str, Any]]:
|
||||
"""子智能体(special)单轮:执行总控下发的 task 文本,交付 content。
|
||||
|
||||
@@ -1514,13 +1539,26 @@ async def _special_run(
|
||||
- 终态 ``status`` 为描述性字符串(非数组),``content`` 为交付正文;
|
||||
- **后广播**在 yield 终态帧之后 await,保证其它席位 state 里有完成摘要,
|
||||
同时尽量让前端先收到结果关闭 loading。
|
||||
|
||||
``no_file``:DAG 并行批次里的席位置真 —— 用 ``seat_parallel`` policy 额外禁
|
||||
write_file / bash / str_replace,避免并行席位同时写沙箱打架(§4)。
|
||||
|
||||
``peer_deliveries``:前序席位的**完整交付** ``[{name, content}, ...]``。注入到
|
||||
run context 的 ``roundtable_peer_deliveries``,供席位用 ``read_peer_delivery`` 工具
|
||||
**按需**取全文(平时只看广播摘要,§12.9 传摘要按需传全文)。不进 prompt,不耗 token。
|
||||
"""
|
||||
t0 = time.perf_counter()
|
||||
thread_id = agent_threads[agent_name]
|
||||
# 角色参数取自单一数据源 roundtable_run_policy(seat / report)。report 在 seat
|
||||
# 基础上额外禁 bash / str_replace(理由见 roundtable_run_policy 模块注释)。
|
||||
# 角色参数取自单一数据源 roundtable_run_policy(seat / seat_parallel / report)。
|
||||
# report 在 seat 基础上额外禁 bash / str_replace;seat_parallel 额外禁
|
||||
# write_file / bash / str_replace(理由见 roundtable_run_policy 模块注释)。
|
||||
# 后台进程内网关用同一份 policy,保证「后台挂起」与「前端手动调用」传参一致。
|
||||
role = "report" if agent_name == REPORT_AGENT_ID else "seat"
|
||||
if agent_name == REPORT_AGENT_ID:
|
||||
role = "report"
|
||||
elif no_file:
|
||||
role = "seat_parallel"
|
||||
else:
|
||||
role = "seat"
|
||||
policy = roundtable_run_policy(role)
|
||||
body = _run_payload(
|
||||
agent_name=agent_name,
|
||||
@@ -1533,6 +1571,10 @@ async def _special_run(
|
||||
reasoning_effort=policy.reasoning_effort,
|
||||
# 干预/重新派活会把同一席位 thread 再跑一次;抢占掉没结束的旧 run,避免 409。
|
||||
multitask_strategy="rollback",
|
||||
# 前序席位完整交付 → run context,供 read_peer_delivery 工具按需取全文(§12.9)。
|
||||
extra_context=(
|
||||
{"roundtable_peer_deliveries": peer_deliveries} if peer_deliveries else None
|
||||
),
|
||||
)
|
||||
t_payload_built = time.perf_counter()
|
||||
logger.info(
|
||||
@@ -1639,6 +1681,25 @@ async def run_multi_agent_stream(request: Request, payload: dict = Body(...)) ->
|
||||
# 额外把各已交付席位的完整交付正文注入总控输入,供其写最终方案。缺省 False(派活决策轮
|
||||
# 只给摘要,保持上下文精简)。旧前端不传 → False,行为安全退化。
|
||||
synthesis_mode: bool = bool(payload.get("synthesis_mode") or False)
|
||||
# 并行禁写文件标记(仅 special 用):前端 runDagOrchestration 在真并行 stage(≥2 席位)
|
||||
# 置真,网关据此用 seat_parallel policy 额外禁 write_file/bash/str_replace(§4)。
|
||||
# 兼容 no_file 别名;缺省 False → 普通 seat,旧前端不传也不破坏。
|
||||
no_file: bool = bool(payload.get("parallel_no_file") or payload.get("no_file") or False)
|
||||
# 抑制 leader 预广播(仅 leader 用):DAG「每 stage 派活轮」置真,避免把总控的派活 prompt
|
||||
# 广播进席位 thread 让弱模型模仿派活(详见 _leader_run 的 suppress_pre_broadcast 注释)。
|
||||
# 缺省 False,recommend/chain 行为不变。
|
||||
suppress_pre_broadcast: bool = bool(payload.get("suppress_pre_broadcast") or False)
|
||||
# 前序席位完整交付(仅 special 用):前端 DAG stage>0 席位带上此前各阶段的全文,网关注入
|
||||
# run context,供 read_peer_delivery 工具按需取全文(平时只看广播摘要,§12.9)。规整成
|
||||
# [{name, content}] 且过滤空项;缺省 None。
|
||||
peer_deliveries: list[dict[str, Any]] | None = None
|
||||
_pd_raw = payload.get("peer_deliveries")
|
||||
if isinstance(_pd_raw, list):
|
||||
peer_deliveries = [
|
||||
{"name": str(p.get("name") or ""), "content": str(p.get("content") or "")}
|
||||
for p in _pd_raw
|
||||
if isinstance(p, dict) and str(p.get("name") or "").strip() and str(p.get("content") or "").strip()
|
||||
] or None
|
||||
# 不写死任何默认模型;空串会让 lead_agent._resolve_model_name() 回退到
|
||||
# config.yaml 的 models[0],与 /api/ai-writing 等其它路由一致。
|
||||
model_name: str = str(payload.get("model") or "")
|
||||
@@ -1679,11 +1740,14 @@ async def run_multi_agent_stream(request: Request, payload: dict = Body(...)) ->
|
||||
client, base, headers, agent_threads, agent_name, new_message, skill_stop_names, model_name,
|
||||
seat_meta=seat_meta,
|
||||
synthesis_mode=synthesis_mode,
|
||||
suppress_pre_broadcast=suppress_pre_broadcast,
|
||||
)
|
||||
else:
|
||||
gen = _special_run(
|
||||
client, base, headers, agent_threads, agent_name, new_message, skill_stop_names, model_name,
|
||||
display_name=display_name,
|
||||
no_file=no_file,
|
||||
peer_deliveries=peer_deliveries,
|
||||
)
|
||||
async for chunk in gen:
|
||||
if isinstance(chunk, dict):
|
||||
|
||||
@@ -46,6 +46,9 @@ class ChainResponse(BaseModel):
|
||||
title: str = ""
|
||||
description: str | None = None
|
||||
seats: list[ChainSeatSchema] = []
|
||||
# Optional layered orchestration: list of stages, each a list of agent_ids
|
||||
# run in parallel (stages run serially). None/absent = linear chain.
|
||||
stages: list[list[str]] | None = None
|
||||
created_at: datetime | str | None = None
|
||||
updated_at: datetime | str | None = None
|
||||
|
||||
@@ -61,6 +64,7 @@ class ChainCreateRequest(BaseModel):
|
||||
title: str = Field(default="", max_length=512)
|
||||
description: str | None = Field(default=None, max_length=2048)
|
||||
seats: list[ChainSeatSchema] = []
|
||||
stages: list[list[str]] | None = None
|
||||
|
||||
|
||||
class ChainUpdateRequest(BaseModel):
|
||||
@@ -68,6 +72,7 @@ class ChainUpdateRequest(BaseModel):
|
||||
title: str | None = Field(default=None, max_length=512)
|
||||
description: str | None = Field(default=None, max_length=2048)
|
||||
seats: list[ChainSeatSchema] | None = None
|
||||
stages: list[list[str]] | None = None
|
||||
|
||||
|
||||
# ── helpers ──────────────────────────────────────────────────────────────
|
||||
@@ -101,6 +106,45 @@ def _validate_seats(seats: list[ChainSeatSchema]) -> None:
|
||||
seen.add(s.agent_id)
|
||||
|
||||
|
||||
def _validate_stages(seats: list[ChainSeatSchema], stages: list[list[str]] | None) -> None:
|
||||
"""Validate the optional layering. ``stages`` must partition the seats.
|
||||
|
||||
Rules (None = linear chain, always valid):
|
||||
- at least one stage, no empty stage;
|
||||
- every agent_id in a stage must be one of the chain's seats;
|
||||
- no agent_id appears twice (within or across stages);
|
||||
- every seat must appear in exactly one stage (full coverage), so the
|
||||
stored layering and the seat list never drift apart.
|
||||
"""
|
||||
if stages is None:
|
||||
return
|
||||
if len(stages) == 0:
|
||||
raise HTTPException(status_code=400, detail="编排分层不能为空(至少一个阶段)")
|
||||
seat_ids = {s.agent_id for s in seats}
|
||||
seen: set[str] = set()
|
||||
for idx, stage in enumerate(stages):
|
||||
if not stage:
|
||||
raise HTTPException(status_code=400, detail=f"第 {idx + 1} 阶段为空,请删除或放入席位")
|
||||
for agent_id in stage:
|
||||
if agent_id not in seat_ids:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"编排分层包含不在席位列表中的智能体: {agent_id}",
|
||||
)
|
||||
if agent_id in seen:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"智能体 {agent_id} 在编排分层中重复出现,每个席位只能跑一次",
|
||||
)
|
||||
seen.add(agent_id)
|
||||
if seen != seat_ids:
|
||||
missing = seat_ids - seen
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"编排分层未覆盖全部席位,缺少: {', '.join(sorted(missing))}",
|
||||
)
|
||||
|
||||
|
||||
# ── routes ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -115,6 +159,7 @@ async def list_chains(request: Request) -> ChainListResponse:
|
||||
@router.post("", response_model=ChainResponse, status_code=201)
|
||||
async def create_chain(request: Request, body: ChainCreateRequest) -> ChainResponse:
|
||||
_validate_seats(body.seats)
|
||||
_validate_stages(body.seats, body.stages)
|
||||
store = _get_store(request)
|
||||
user_id = _current_user_id(request)
|
||||
row = await store.create_chain(
|
||||
@@ -124,6 +169,7 @@ async def create_chain(request: Request, body: ChainCreateRequest) -> ChainRespo
|
||||
"title": body.title.strip(),
|
||||
"description": body.description,
|
||||
"seats": [s.model_dump() for s in body.seats],
|
||||
"stages": body.stages,
|
||||
},
|
||||
)
|
||||
return ChainResponse(**row)
|
||||
@@ -143,6 +189,12 @@ async def get_chain(request: Request, chain_id: str) -> ChainResponse:
|
||||
async def update_chain(request: Request, chain_id: str, body: ChainUpdateRequest) -> ChainResponse:
|
||||
if body.seats is not None:
|
||||
_validate_seats(body.seats)
|
||||
# A non-null stages layering can only be validated against seats; the editor
|
||||
# always saves both together. Reject a layering update that omits seats.
|
||||
if body.stages is not None:
|
||||
if body.seats is None:
|
||||
raise HTTPException(status_code=400, detail="更新编排分层时必须同时提交席位列表")
|
||||
_validate_stages(body.seats, body.stages)
|
||||
store = _get_store(request)
|
||||
user_id = _current_user_id(request)
|
||||
# Distinguish "omitted" from "explicitly sent"; only forward provided fields.
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
"""Add stages column to roundtable_chains.
|
||||
|
||||
Layered orchestration (分层编排) for business chains: an optional list-of-lists of
|
||||
agent_ids grouping the chain's seats into parallel stages (stages run serially).
|
||||
NULL = linear chain. The column is LONGTEXT on MySQL (mirrors ``seats`` headroom)
|
||||
and plain TEXT elsewhere — matching ``PortableLongText`` on
|
||||
``RoundtableChainRow.stages``. ``create_all`` adds the column for brand-new DBs;
|
||||
this revision patches DBs that already have the table.
|
||||
|
||||
Revision ID: 20260607_03
|
||||
Revises: 20260607_02
|
||||
Create Date: 2026-06-07
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.dialects.mysql import LONGTEXT
|
||||
|
||||
|
||||
revision = "20260607_03"
|
||||
down_revision = "20260607_02"
|
||||
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_chains") and not _has_column("roundtable_chains", "stages"):
|
||||
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
|
||||
op.add_column("roundtable_chains", sa.Column("stages", col_type, nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _has_column("roundtable_chains", "stages"):
|
||||
op.drop_column("roundtable_chains", "stages")
|
||||
+6
@@ -33,6 +33,12 @@ class RoundtableChainRow(Base):
|
||||
# JSON: ordered [{"agent_id": str, "name": str, "description": str}, ...].
|
||||
# seats[0] is the first seat to speak. Stored as LONGTEXT-backed JSON string.
|
||||
seats: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
|
||||
# Optional JSON: layered orchestration grouping over ``seats`` — a list of
|
||||
# stages, each a list of agent_ids run in parallel; stages run serially in
|
||||
# order. e.g. [["a","b"],["c"]] = (a‖b) → c. NULL/absent = linear chain
|
||||
# (each seat its own stage). Drives Step 2 dag-mode orchestration; see
|
||||
# frontend ``lib/dag-types.ts``. Stored as LONGTEXT-backed JSON string.
|
||||
stages: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC)
|
||||
)
|
||||
|
||||
+6
@@ -50,6 +50,8 @@ class RoundtableChainRepository:
|
||||
"title": row.title,
|
||||
"description": row.description,
|
||||
"seats": _loads(row.seats) or [],
|
||||
# None when absent → frontend reads it as "linear chain" (no layering).
|
||||
"stages": _loads(row.stages),
|
||||
"created_at": row.created_at.isoformat() if isinstance(row.created_at, datetime) else row.created_at,
|
||||
"updated_at": row.updated_at.isoformat() if isinstance(row.updated_at, datetime) else row.updated_at,
|
||||
}
|
||||
@@ -80,6 +82,7 @@ class RoundtableChainRepository:
|
||||
title=(data.get("title") or "").strip(),
|
||||
description=(data.get("description") or None),
|
||||
seats=_dumps(data.get("seats") or []),
|
||||
stages=_dumps(data.get("stages")),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
@@ -97,6 +100,7 @@ class RoundtableChainRepository:
|
||||
title=_UNSET,
|
||||
description=_UNSET,
|
||||
seats=_UNSET,
|
||||
stages=_UNSET,
|
||||
) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(RoundtableChainRow, chain_id)
|
||||
@@ -108,6 +112,8 @@ class RoundtableChainRepository:
|
||||
row.description = description or None
|
||||
if seats is not _UNSET:
|
||||
row.seats = _dumps(seats)
|
||||
if stages is not _UNSET:
|
||||
row.stages = _dumps(stages)
|
||||
row.updated_at = datetime.now(UTC)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
"""read_peer_delivery —— 圆桌席位「按需读取前序席位**完整交付**」的只读工具。
|
||||
|
||||
背景:圆桌每个席位是独立 thread(独立 sandbox),彼此隔离。默认情况下,一个席位只能
|
||||
从跨席位广播里看到前序席位的**截断摘要**(≤1500 字)。当席位识别到自己需要某个前序
|
||||
席位的**全文**时,调用本工具按席位名取回完整交付。
|
||||
|
||||
数据来源:全文由**网关层**(``app.gateway``)在发起本席位 run 时,注入到
|
||||
``runtime.context["roundtable_peer_deliveries"]`` —— 一个
|
||||
``[{"name": <席位显示名>, "content": <完整交付正文>}, ...]`` 列表。本工具**只读该上下文
|
||||
dict**,不跨 thread、不碰 sandbox、不发网络请求,因此完全在 ``deerflow.*`` 内(不违反
|
||||
harness→app 导入防火墙)。非圆桌场景下该上下文为空,工具返回「无」。
|
||||
|
||||
「传摘要按需传全文」:完整交付**只在席位真正调用本工具时**才进入它的 LLM 上下文,平时
|
||||
只有摘要,既省 token 又满足「需要时能拿全文」。详见
|
||||
``frontend-web/docs/roundtable-dag-orchestration.md`` §12.9。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from langchain.tools import ToolRuntime, tool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CTX_KEY = "roundtable_peer_deliveries"
|
||||
|
||||
|
||||
def _peer_deliveries(runtime: ToolRuntime | None) -> list[dict]:
|
||||
"""从 runtime.context 取出网关注入的前序席位完整交付列表(缺失/非法时返回 [])。"""
|
||||
if runtime is None:
|
||||
return []
|
||||
ctx = getattr(runtime, "context", None)
|
||||
if not ctx:
|
||||
return []
|
||||
try:
|
||||
peers = ctx.get(_CTX_KEY)
|
||||
except Exception:
|
||||
return []
|
||||
if not isinstance(peers, list):
|
||||
return []
|
||||
return [p for p in peers if isinstance(p, dict)]
|
||||
|
||||
|
||||
@tool("read_peer_delivery", parse_docstring=True)
|
||||
def read_peer_delivery_tool(runtime: ToolRuntime, seat_name: str = "") -> str:
|
||||
"""Read another roundtable seat's FULL deliverable on demand.
|
||||
|
||||
In a multi-agent roundtable you (a seat) normally only see **truncated
|
||||
summaries** of earlier seats' deliverables. When you decide you genuinely
|
||||
need the **complete text** of a specific earlier seat (e.g. to build on its
|
||||
detailed data/conclusions), call this tool with that seat's name to fetch
|
||||
its full deliverable. Prefer the summaries you already have; only call this
|
||||
when the summary is insufficient.
|
||||
|
||||
Args:
|
||||
seat_name: The earlier seat's display name (the Chinese name shown in
|
||||
the summaries, e.g. "情报收集"). Leave empty to list which peers'
|
||||
full deliverables are available to read.
|
||||
"""
|
||||
peers = _peer_deliveries(runtime)
|
||||
if not peers:
|
||||
return "(当前没有可读取的前序席位完整交付。请直接基于你已有的上下文与摘要完成交付。)"
|
||||
|
||||
names = [str(p.get("name") or "") for p in peers if p.get("name")]
|
||||
query = (seat_name or "").strip()
|
||||
if not query:
|
||||
return (
|
||||
"可读取**完整交付**的前序席位:" + "、".join(names) + "。\n"
|
||||
"需要哪个席位的全文,就再次调用 read_peer_delivery 并把它的名称传给 seat_name。"
|
||||
)
|
||||
|
||||
ql = query.lower()
|
||||
# 精确匹配(忽略大小写)优先,其次子串互含(容忍模型给「情报收集席位」这类带后缀的名)。
|
||||
for p in peers:
|
||||
if str(p.get("name") or "").lower() == ql:
|
||||
return str(p.get("content") or "(该席位交付为空。)")
|
||||
for p in peers:
|
||||
nm = str(p.get("name") or "")
|
||||
if nm and (ql in nm.lower() or nm.lower() in ql):
|
||||
return str(p.get("content") or "(该席位交付为空。)")
|
||||
return f"未找到名为「{query}」的前序席位。可读取的有:" + "、".join(names) + "。"
|
||||
@@ -114,6 +114,13 @@ def get_available_tools(
|
||||
|
||||
builtin_tools.extend([skill_list_tool, skill_view_tool])
|
||||
|
||||
# read_peer_delivery —— 圆桌席位「按需读取前序席位完整交付」的只读工具(从 run context
|
||||
# 取网关注入的全文,非圆桌场景为空 → 工具自述「无」)。始终提供(只读、无副作用);圆桌
|
||||
# 总控/报告角色由 run policy 显式排除,避免干扰它们。
|
||||
from deerflow.tools.builtins.roundtable_peers_tool import read_peer_delivery_tool
|
||||
|
||||
builtin_tools.append(read_peer_delivery_tool)
|
||||
|
||||
# skill_manage 能创建/修改/删除技能,属于"自我进化"写能力,按 skill_evolution.enabled
|
||||
# 门控。该开关用户可在 per-user 配置里覆盖,所以按"生效配置(含 per-user 覆盖)"判断 ——
|
||||
# Gateway 每次 run 重建 agent,用户改了配置下次 run 即生效;解析失败退回全局 config.yaml。
|
||||
|
||||
Reference in new issue
Block a user