代码提交

This commit is contained in:
董宏凯 committed 2026-08-24 20:47:31 +08:00
1 parent 007ed5a7de
commit babc5e95c6
21 files changed
+1170 -145

No files matched your search

@@ -34,6 +34,7 @@ Leader 终态帧(前端 ``isFinalStatusFrame``)
- ``status: []`` — 无 tool_calls,视为共识,可进 Step 3;
- ``status: "clarification"`` — 总控 ``ask_clarification``,前端暂停编排展示澄清条;
- ``status: "子智能体 X 完成..."`` — special 完成(字符串状态);
- ``status: "invalid_delivery"`` — 席位本轮无可见正文(仅思考 / 断流 / 空串),不算交付;
- ``status: "error"`` — 失败。
共享导出
@@ -77,6 +78,7 @@ from app.gateway.routers._roundtable_seed import (
SUMMARY_AGENT_ID,
ensure_roundtable_functional_agents,
)
from deerflow.agents.roundtable_orchestrator.delivery import classify_seat_delivery, visible_seat_text
from deerflow.agents.roundtable_orchestrator.extraction_spec import build_summary_directive
from deerflow.config import get_app_config
from deerflow.runtime.user_context import get_effective_user_id
@@ -679,6 +681,36 @@ def _flatten_content(content: Any) -> str:
return str(content)
def _last_ai_raw_text(messages: list[Any]) -> str:
"""最后一条有原文的 AI 消息(含思考标签),用于区分 thinking_only 与 empty。"""
for msg in reversed(messages or []):
if not isinstance(msg, dict):
continue
if (msg.get("type") or "").lower() not in ("ai", "aimessage", "aimessagechunk"):
continue
raw = _flatten_content(msg.get("content", ""))
if raw.strip():
return raw
return ""
def _visible_delivery_from_messages(messages: list[Any]) -> str:
"""本轮可见正文:最后一条 human 之后、剥掉思考仍非空的 AI 文本。"""
last_human = -1
for i, msg in enumerate(messages or []):
if isinstance(msg, dict) and (msg.get("type") or "").lower() in ("human", "user"):
last_human = i
for msg in reversed((messages or [])[last_human + 1 :]):
if not isinstance(msg, dict):
continue
if (msg.get("type") or "").lower() not in ("ai", "aimessage", "aimessagechunk"):
continue
visible = visible_seat_text(_flatten_content(msg.get("content", "")))
if visible:
return visible
return ""
def _run_payload(
*,
agent_name: str,
@@ -1389,13 +1421,13 @@ async def _collect_delivery_status(
seat_threads: dict[str, str],
*,
max_chars: int = 0,
) -> dict[str, tuple[bool, str, int]]:
) -> dict[str, tuple[bool, str, int, str]]:
"""读各席位 thread 的真实状态,客观判定「是否已交付 + 交付摘要」。
返回 ``{seat_id: (delivered, text, full_len)}``。``text`` 是该席位**最后一条 AI 交付**(按
``max_chars`` 截断:派活轮取 600 字摘要、综合轮 ``max_chars<=0`` 取全文);``full_len`` 是交付
全文长度(供调用方判断 text 是否被截断、要不要加省略号)。判定依据:席位 thread 是否存在非空
AI 交付,只有 broadcast 进来的 human 消息不算。
返回 ``{seat_id: (delivered, text, full_len, invalid_reason)}``。``text`` 是该席位**可见正文**
(按 ``max_chars`` 截断:派活轮取 600 字摘要、综合轮 ``max_chars<=0`` 取全文);``full_len`` 是
可见正文全文长度。判定依据:剥掉思考后是否有可见正文(不要求 md 文件);思考-only / 空串 /
断流都不算已交付。
走**轻量读**接口(``GET /last-ai-message?max_chars=N``):服务端只回最后一条 AI 消息(可截断),
不把整份 state 序列化经 loopback 传回 —— 派活轮每席位只取 600 字,大幅压低原先 ~11s 的
@@ -1404,7 +1436,7 @@ async def _collect_delivery_status(
这是「确定性双保险」的数据源:总控弱模型会臆造「三方已交付」,这里由网关**客观核对**每个席位
thread 的实际产出,再把结论喂回总控输入,总控以系统核对为准,不靠自己读历史猜。
"""
async def _one(sid: str, tid: str) -> tuple[str, tuple[bool, str, int]]:
async def _one(sid: str, tid: str) -> tuple[str, tuple[bool, str, int, str]]:
try:
resp = await client.get(
f"{base}/api/threads/{tid}/last-ai-message",
@@ -1412,13 +1444,14 @@ async def _collect_delivery_status(
headers=headers,
)
if resp.status_code != 200:
return sid, (False, "", 0)
return sid, (False, "", 0, "empty")
data = resp.json()
content = str(data.get("content") or "")
full_len = int(data.get("length") or len(content))
return sid, (bool(data.get("delivered")), content, full_len)
reason = str(data.get("invalid_reason") or "")
return sid, (bool(data.get("delivered")), content, full_len, reason)
except Exception:
return sid, (False, "", 0)
return sid, (False, "", 0, "empty")
results = await asyncio.gather(*(_one(sid, tid) for sid, tid in seat_threads.items()))
return dict(results)
@@ -1431,7 +1464,7 @@ _STATUS_EXCERPT_CHARS = 600
def _build_seat_status_block(
seats: list[tuple[str, dict[str, Any]]],
delivery: dict[str, tuple[bool, str, int]],
delivery: dict[str, tuple[bool, str, int, str]] | dict[str, tuple[bool, str, int]],
*,
undelivered_count: int = 0,
) -> str:
@@ -1448,19 +1481,25 @@ def _build_seat_status_block(
lines: list[str] = []
for sid, meta in seats:
name = str((meta or {}).get("name") or sid)
delivered, text, full_len = delivery.get(sid, (False, "", 0))
item = delivery.get(sid, (False, "", 0, ""))
delivered, text, full_len = item[0], item[1], item[2]
reason = item[3] if len(item) > 3 else ""
if delivered:
# text 已是服务端按 max_chars 截好的摘要;full_len > len(text) 说明被截断,加省略号。
ellipsis = "…" if full_len > len(text) else ""
tail = f" —— 交付摘要:{text}{ellipsis}" if text else ""
lines.append(f"- {sid}({name}):✅ 已交付{tail}")
elif reason == "thinking_only":
lines.append(f"- {sid}({name}):⚠️ 无有效正文(仅思考或中断,不算交付)")
else:
lines.append(f"- {sid}({name}):⬜ 未交付")
roster = "\n".join(lines)
pending_rule = (
(
f"\n⚠️ 当前还有 {undelivered_count} 个 ⬜ 未交付席位。**信息尚未集齐,严禁现在收口/输出最终方案**,"
"也不得声称「各席位均已发言」。请**优先继续派活**给这些 ⬜ 席位,把它们的真实交付拿到手再说综合。"
f"\n⚠️ 当前还有 {undelivered_count} 个未交付席位(⬜ 未交付或 ⚠️ 仅思考/中断)。"
"**信息尚未集齐,严禁现在收口/输出最终方案**,"
"也不得声称「各席位均已发言」。请**优先继续派活**给这些席位,把它们的真实可见正文拿到手再说综合。"
"思考过程、半截输出都不算交付。"
)
if undelivered_count > 0
else ""
@@ -1468,9 +1507,9 @@ def _build_seat_status_block(
return (
"【本次圆桌席位与真实交付状态(系统客观核对,以此为准,严禁臆造)】\n"
"派活时 agent_orchestration 的 agent_name 必须从下面逐字符复制一个 id;"
"只有标 ✅ 的才算已交付,标 ⬜ 的就是还没交付——\n"
"若用户想要的席位是 ⬜,你**必须**派活给它拿到真实交付,**不得**跳过它直接收口或代答;"
"也**不得**声称任何 ⬜ 席位已交付。下面只是**摘要**,做最终综合时以系统额外提供的"
"只有标 ✅ 的才算已交付(可见正文,不要求 md 文件);标 ⬜ / ⚠️ 的都还没交付——\n"
"若用户想要的席位是 ⬜ 或 ⚠️,你**必须**派活给它拿到真实可见正文,**不得**跳过它直接收口或代答;"
"也**不得**声称任何 ⬜ / ⚠️ 席位已交付。下面只是**摘要**,做最终综合时以系统额外提供的"
"「完整交付」为准:\n"
f"{roster}"
f"{pending_rule}"
@@ -1479,7 +1518,7 @@ def _build_seat_status_block(
def _build_full_deliverables_block(
seats: list[tuple[str, dict[str, Any]]],
delivery: dict[str, tuple[bool, str, int]],
delivery: dict[str, tuple[bool, str, int, str]] | dict[str, tuple[bool, str, int]],
) -> str:
"""综合轮专用:把各已交付席位的**完整交付正文**拼成一块,供总控写最终方案。
@@ -1488,7 +1527,8 @@ def _build_full_deliverables_block(
"""
sections: list[str] = []
for sid, meta in seats:
delivered, full_text, _ = delivery.get(sid, (False, "", 0))
item = delivery.get(sid, (False, "", 0, ""))
delivered, full_text = item[0], item[1]
if not delivered or not full_text:
continue
name = str((meta or {}).get("name") or sid)
@@ -1976,26 +2016,38 @@ async def _special_run(
messages = _parse_last_messages(captured)
if messages is None:
# 与 _leader_run 同理:席位 run 被抢占/断开导致流截断,不抛 502,静默收尾。
# 这不是模型错误(多半 rollback 抢占),不触发换模型。
# 流被截断(网断 / rollback 抢占)。不抛 502,但席位路径要明确告诉前端:本轮不算交付,
# 避免总控把 checkpoint 里残留的思考/半截当成已完成。
logger.warning(
"[special-timing] %s upstream truncated (no values frame) — ending quietly "
"[special-timing] %s upstream truncated (no values frame) — ending as invalid_delivery "
"(expected on rollback preemption; otherwise check the upstream run's server-side error)",
agent_name,
)
if empty_is_failure:
yield {
"status": "invalid_delivery",
"reason": "truncated",
"content": "",
"agent_name": agent_name,
"model_used": candidate,
}
return
# Sub-agent's final deliverable is the latest AIMessage's text content.
# Sub-agent's final deliverable is visible body after the last human (this turn).
last_msg: dict[str, Any] = {}
for msg in reversed(messages):
if isinstance(msg, dict) and (msg.get("type") or "").lower() in ("ai", "aimessage", "aimessagechunk"):
last_msg = msg
break
content = _flatten_content(last_msg.get("content", ""))
visible = visible_seat_text(content)
if not visible:
visible = _visible_delivery_from_messages(messages)
delivery_kind = classify_seat_delivery(content) if content.strip() else ("valid" if visible else "empty")
# 模型失败检测:兜底错误文案;研讨席位再加「交付为空」。还有备选模型则换。
# 模型失败检测:兜底错误文案;研讨席位再加「无可见正文」(思考不算)。还有备选模型则换。
fail_reason = is_llm_error_message(last_msg)
if fail_reason is None and empty_is_failure and not content.strip():
fail_reason = "empty"
if fail_reason is None and empty_is_failure and delivery_kind != "valid":
fail_reason = "thinking_only" if delivery_kind == "thinking_only" else "empty"
if fail_reason and idx + 1 < len(model_chain):
next_model = model_chain[idx + 1]
logger.warning("[special-fallback] %s 模型 %s 失败(%s),切换到 %s", agent_name, candidate, fail_reason, next_model)
@@ -2009,17 +2061,23 @@ async def _special_run(
}
continue
# 成功(或已用尽备选):发交付终态帧 + detached 后广播。
if empty_is_failure and delivery_kind != "valid":
logger.warning("[special-fallback] %s 所有模型均未产出可见正文(%s)", agent_name, delivery_kind)
yield {
"status": "invalid_delivery",
"reason": delivery_kind,
"content": "",
"agent_name": agent_name,
"model_used": candidate,
}
return
# 成功:发交付终态帧 + detached 后广播(只广播可见正文,不含思考)。
_prefix = f"子智能体{speaker_label}完成{new_message}工作,交付内容为:"
# 广播给**所有**席位(含总控)的都只是**截断摘要** —— 总控 thread 不再囤积各席位全文,
# 每轮 leader 的上下文因此保持小、响应快。总控做最终综合需要全文时,由 _leader_run 在
# 「综合轮」按需现读各席位 thread 注入(见 _build_full_deliverables_block),不靠历史囤积。
brief_msg = _truncate_broadcast_content(_prefix, content)
# 先 yield 交付结果让前端立即收口本席位;后广播改 detached,不再 await 阻塞 ——
# 否则它读写各席位大状态会让 SSE 多挂十几秒,把下一轮 leader 的启动也一起拖慢。
brief_msg = _truncate_broadcast_content(_prefix, visible or content)
yield {
"status": f"子智能体{speaker_label}完成{new_message}工作",
"content": content,
"content": visible or content,
"agent_name": agent_name,
"model_used": candidate,
}