代码提交
This commit is contained in:
1 parent
007ed5a7de
commit
babc5e95c6
21 files changed
+1170
-145
No files matched your search
+22
-8
@@ -5,7 +5,12 @@ from langchain.agents.middleware import AgentMiddleware
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
|
||||
from deerflow.agents.lead_agent.prompt import apply_prompt_template
|
||||
from deerflow.agents.middlewares.clarification_middleware import ClarificationMiddleware
|
||||
from deerflow.agents.middlewares.clarification_middleware import ClarificationMiddleware
|
||||
from deerflow.agents.middlewares.forced_research_middleware import (
|
||||
FORCED_RESEARCH_AGENT_ID,
|
||||
ForcedResearchMiddleware,
|
||||
filter_forced_research_tools,
|
||||
)
|
||||
from deerflow.agents.middlewares.loop_detection_middleware import LoopDetectionMiddleware
|
||||
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
|
||||
from deerflow.agents.middlewares.prompt_prefix_middleware import PromptPrefixMiddleware
|
||||
@@ -368,14 +373,21 @@ def _build_middlewares(
|
||||
|
||||
middlewares.append(SkillReviewMiddleware())
|
||||
|
||||
# PositionArtifactCapMiddleware — position-roundtable seats (and summary)
|
||||
# PositionArtifactCapMiddleware — position-roundtable seats (and summary)
|
||||
# may only emit N outputs write_file calls per user turn. Action-plan skips
|
||||
# the context flag so it can still write report + JSON.
|
||||
from deerflow.agents.middlewares.position_artifact_cap_middleware import PositionArtifactCapMiddleware
|
||||
|
||||
middlewares.append(PositionArtifactCapMiddleware())
|
||||
|
||||
# LoopDetectionMiddleware — detect and break repetitive tool call loops
|
||||
middlewares.append(PositionArtifactCapMiddleware())
|
||||
|
||||
# The built-in forced-research responder has a hard per-turn collection
|
||||
# gate plus temporary-Python-only sandbox IO. This is runtime enforcement,
|
||||
# not merely SOUL prompt steering, so weak models cannot answer before a
|
||||
# successful retrieval/skill-script result exists.
|
||||
if agent_name == FORCED_RESEARCH_AGENT_ID:
|
||||
middlewares.append(ForcedResearchMiddleware())
|
||||
|
||||
# LoopDetectionMiddleware — detect and break repetitive tool call loops
|
||||
middlewares.append(LoopDetectionMiddleware())
|
||||
|
||||
# Inject custom middlewares before ClarificationMiddleware
|
||||
@@ -626,14 +638,16 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
|
||||
# Default lead agent (unchanged behavior)
|
||||
is_notebook_mode = bool(cfg.get("notebook_search_space_id"))
|
||||
notebook_source_ids: list[int] = cfg.get("notebook_source_ids") or []
|
||||
default_tools = get_available_tools(
|
||||
default_tools = get_available_tools(
|
||||
model_name=model_name,
|
||||
groups=agent_config.tool_groups if agent_config else None,
|
||||
subagent_enabled=subagent_enabled,
|
||||
is_scheduled_run=cfg.get("is_scheduled_run", False),
|
||||
excluded_tools=requested_excluded_tools,
|
||||
app_config=resolved_app_config,
|
||||
)
|
||||
app_config=resolved_app_config,
|
||||
)
|
||||
if agent_id == FORCED_RESEARCH_AGENT_ID:
|
||||
default_tools = filter_forced_research_tools(default_tools)
|
||||
if is_notebook_mode:
|
||||
from deerflow.tools.builtins.notebook_search_tool import notebook_search_tool
|
||||
|
||||
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
"""Hard runtime policy for the built-in forced-research responder.
|
||||
|
||||
The ordinary custom-agent skill allowlist only makes skills visible to the
|
||||
model; it does not guarantee that a model will use one before answering. This
|
||||
middleware turns that behavioural preference into a per-user-turn runtime
|
||||
contract:
|
||||
|
||||
* before a successful information-gathering tool result exists, every model
|
||||
call is made with ``tool_choice=required``;
|
||||
* a provider that ignores ``tool_choice`` and emits text is sent back to the
|
||||
model node (with the premature text hidden);
|
||||
* after a bounded number of failed attempts the model may only report the
|
||||
collection failure instead of looping forever;
|
||||
* ``write_file`` / ``str_replace`` are restricted to temporary ``.py`` files
|
||||
under ``/mnt/user-data/workspace`` and ``bash`` may only execute Python
|
||||
scripts. Markdown/document deliverables and ``present_files`` are denied.
|
||||
|
||||
The policy is mounted only for :data:`FORCED_RESEARCH_AGENT_ID`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Awaitable, Callable
|
||||
from copy import deepcopy
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Any, override
|
||||
|
||||
from langchain.agents import AgentState
|
||||
from langchain.agents.middleware import AgentMiddleware, hook_config
|
||||
from langchain.agents.middleware.types import ModelCallResult, ModelRequest, ModelResponse
|
||||
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
||||
from langgraph.prebuilt.tool_node import ToolCallRequest
|
||||
from langgraph.runtime import Runtime
|
||||
from langgraph.types import Command
|
||||
|
||||
FORCED_RESEARCH_AGENT_ID = "forced-research-responder"
|
||||
|
||||
_WORKSPACE_PREFIX = "/mnt/user-data/workspace"
|
||||
_MAX_COLLECTION_ATTEMPTS = 8
|
||||
|
||||
# These tools prepare/discover capabilities but do not themselves return the
|
||||
# information requested by the user. Unknown tools (not in this set) are
|
||||
# intentionally accepted so configured MCP/skill-specific retrieval tools work.
|
||||
_NON_EVIDENCE_TOOLS = {
|
||||
"agent_orchestration",
|
||||
"ask_clarification",
|
||||
"bash",
|
||||
"glob",
|
||||
"grep",
|
||||
"ls",
|
||||
"memory",
|
||||
"present_files",
|
||||
"read_file",
|
||||
"scheduled_task",
|
||||
"search_skills",
|
||||
"skill_list",
|
||||
"skill_manage",
|
||||
"skill_view",
|
||||
"str_replace",
|
||||
"task",
|
||||
"tool_search",
|
||||
"write_file",
|
||||
"write_todos",
|
||||
}
|
||||
|
||||
_TOOLS_REMOVED_FROM_FORCED_RESEARCH = {
|
||||
"agent_orchestration",
|
||||
"ask_clarification",
|
||||
"memory",
|
||||
"present_files",
|
||||
"scheduled_task",
|
||||
"skill_manage",
|
||||
"task",
|
||||
}
|
||||
|
||||
_FAILED_RESULT_MARKERS = (
|
||||
"error:",
|
||||
"no results found",
|
||||
"no result found",
|
||||
"success\": false",
|
||||
"success': false",
|
||||
"未找到",
|
||||
"没有找到",
|
||||
"检索失败",
|
||||
"查询失败",
|
||||
)
|
||||
|
||||
_FORCE_COLLECTION_TEXT = """<forced_research_gate>
|
||||
【运行时强制】本轮尚未取得任何有效的信息采集结果,禁止直接回答用户。
|
||||
请先分析用户意图,拆分检索方向和具体检索词,然后立即调用已配置技能所需的工具、检索工具、知识库工具或技能 Python 脚本。
|
||||
读取 SKILL.md、搜索技能、编写临时 Python 脚本都只是准备步骤,不能替代实际信息采集。
|
||||
至少取得一次有效工具结果后,才能按照用户指定的格式直接在聊天中回答。
|
||||
</forced_research_gate>"""
|
||||
|
||||
_COLLECTION_FAILED_TEXT = """<forced_research_gate>
|
||||
【运行时强制】本轮已经多次尝试调用工具,但仍未取得有效的信息采集结果。
|
||||
现在不要继续循环,也不得凭模型记忆补写事实。请直接用用户要求的格式如实说明本轮检索失败、已经尝试的方向以及仍缺少的信息。
|
||||
禁止生成或呈现任何文件。
|
||||
</forced_research_gate>"""
|
||||
|
||||
|
||||
def filter_forced_research_tools(tools: list[Any]) -> list[Any]:
|
||||
"""Remove unrelated/write-capable built-ins while retaining skill tools.
|
||||
|
||||
``write_file`` and ``str_replace`` stay available because the policy below
|
||||
narrows them to temporary Python source files. ``bash`` stays available so
|
||||
script-backed skills can execute their own or those temporary scripts.
|
||||
"""
|
||||
|
||||
return [tool for tool in tools if getattr(tool, "name", "") not in _TOOLS_REMOVED_FROM_FORCED_RESEARCH]
|
||||
|
||||
|
||||
def _normalize_args(raw: object) -> dict[str, Any]:
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
return {}
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
return {}
|
||||
|
||||
|
||||
def _tool_field(tool_call: object, key: str, default: Any = None) -> Any:
|
||||
if isinstance(tool_call, dict):
|
||||
return tool_call.get(key, default)
|
||||
getter = getattr(tool_call, "get", None)
|
||||
if callable(getter):
|
||||
return getter(key, default)
|
||||
return getattr(tool_call, key, default)
|
||||
|
||||
|
||||
def _normalized_container_path(value: object) -> str:
|
||||
text = str(value or "").strip().replace("\\", "/")
|
||||
if not text:
|
||||
return ""
|
||||
try:
|
||||
return str(PurePosixPath(text))
|
||||
except Exception: # noqa: BLE001 - invalid model-provided path is denied
|
||||
return ""
|
||||
|
||||
|
||||
def _is_workspace_python_path(value: object) -> bool:
|
||||
path = _normalized_container_path(value)
|
||||
return path.startswith(f"{_WORKSPACE_PREFIX}/") and path.lower().endswith(".py")
|
||||
|
||||
|
||||
_PYTHON_EXECUTABLE_RE = re.compile(r"(?:^|[\s;&|])(?:python(?:3(?:\.\d+)?)?|py)(?:\.exe)?(?:\s|$)", re.IGNORECASE)
|
||||
_PYTHON_FILE_RE = re.compile(r"(?:^|[\s\"'])([^\s\"']+\.py)(?=$|[\s\"'])", re.IGNORECASE)
|
||||
_SHELL_WRITE_RE = re.compile(r"(?:>|\b(?:tee|touch|cp|mv|rm|del|erase|out-file|set-content|add-content)\b)", re.IGNORECASE)
|
||||
_FORBIDDEN_DELIVERABLE_RE = re.compile(r"(?:/mnt/user-data/outputs|\.(?:md|markdown|docx?|pdf|xlsx?|pptx?|html?)(?:\s|$|[\"']))", re.IGNORECASE)
|
||||
|
||||
|
||||
def _validate_python_command(command: object) -> str | None:
|
||||
text = str(command or "").strip()
|
||||
if not text:
|
||||
return "bash 仅允许执行技能所需的 Python 脚本,command 不能为空。"
|
||||
if _FORBIDDEN_DELIVERABLE_RE.search(text):
|
||||
return "禁止通过 bash 创建、修改或处理 Markdown/文档交付物及 outputs 目录。"
|
||||
if _SHELL_WRITE_RE.search(text):
|
||||
return "bash 仅允许执行 Python 脚本,禁止使用 shell 重定向或文件管理命令。"
|
||||
if not _PYTHON_EXECUTABLE_RE.search(text) or not _PYTHON_FILE_RE.search(text):
|
||||
return "bash 仅允许执行 .py 脚本(例如 cd <技能目录> && python scripts/search.py ...)。"
|
||||
return None
|
||||
|
||||
|
||||
def validate_forced_research_tool_call(tool_call: object) -> str | None:
|
||||
"""Return a rejection reason, or ``None`` when the call is permitted."""
|
||||
|
||||
name = str(_tool_field(tool_call, "name", "") or "")
|
||||
args = _normalize_args(_tool_field(tool_call, "args", {}))
|
||||
if name == "present_files":
|
||||
return "本智能体只在聊天中输出,禁止呈现沙箱文件。"
|
||||
if name in {"write_file", "str_replace"}:
|
||||
if not _is_workspace_python_path(args.get("path")):
|
||||
return "只允许在 /mnt/user-data/workspace/ 下创建或修改临时 .py 文件。"
|
||||
if name == "bash":
|
||||
return _validate_python_command(args.get("command"))
|
||||
return None
|
||||
|
||||
|
||||
def _is_visible_human(message: Any) -> bool:
|
||||
if not isinstance(message, HumanMessage):
|
||||
return False
|
||||
kwargs = getattr(message, "additional_kwargs", None) or {}
|
||||
if kwargs.get("hide_from_ui"):
|
||||
return False
|
||||
return getattr(message, "name", None) != "forced_research_gate"
|
||||
|
||||
|
||||
def _turn_start(messages: list[Any]) -> int:
|
||||
for index in range(len(messages) - 1, -1, -1):
|
||||
if _is_visible_human(messages[index]):
|
||||
return index
|
||||
return 0
|
||||
|
||||
|
||||
def _call_map(messages: list[Any], start: int) -> dict[str, tuple[str, dict[str, Any]]]:
|
||||
calls: dict[str, tuple[str, dict[str, Any]]] = {}
|
||||
for message in messages[start:]:
|
||||
if not isinstance(message, AIMessage):
|
||||
continue
|
||||
for call in message.tool_calls or []:
|
||||
call_id = str(_tool_field(call, "id", "") or "")
|
||||
if call_id:
|
||||
calls[call_id] = (
|
||||
str(_tool_field(call, "name", "") or ""),
|
||||
_normalize_args(_tool_field(call, "args", {})),
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _tool_result_succeeded(message: ToolMessage) -> bool:
|
||||
status = str(getattr(message, "status", "") or "").lower()
|
||||
if status == "error":
|
||||
return False
|
||||
content = str(getattr(message, "content", "") or "").strip()
|
||||
if not content:
|
||||
return False
|
||||
lowered = content.lower()
|
||||
return not any(marker in lowered for marker in _FAILED_RESULT_MARKERS)
|
||||
|
||||
|
||||
def _is_information_result(name: str, args: dict[str, Any], message: ToolMessage) -> bool:
|
||||
if name in _NON_EVIDENCE_TOOLS:
|
||||
if name == "read_file":
|
||||
path = str(args.get("path") or "").replace("\\", "/").lower()
|
||||
if path.endswith("/skill.md") or path.endswith(".py"):
|
||||
return False
|
||||
elif name == "bash":
|
||||
# bash is evidence only when it actually executed a Python skill
|
||||
# script; policy validation has already rejected other commands.
|
||||
if _validate_python_command(args.get("command")) is not None:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
return _tool_result_succeeded(message)
|
||||
|
||||
|
||||
def _turn_collection_state(messages: list[Any]) -> tuple[bool, int]:
|
||||
start = _turn_start(messages)
|
||||
calls = _call_map(messages, start)
|
||||
attempts = 0
|
||||
for message in messages[start:]:
|
||||
if not isinstance(message, ToolMessage):
|
||||
continue
|
||||
call_id = str(getattr(message, "tool_call_id", "") or "")
|
||||
call = calls.get(call_id)
|
||||
if call is None:
|
||||
continue
|
||||
attempts += 1
|
||||
if _is_information_result(call[0], call[1], message):
|
||||
return True, attempts
|
||||
return False, attempts
|
||||
|
||||
|
||||
def _hidden_reminder(text: str) -> HumanMessage:
|
||||
return HumanMessage(
|
||||
name="forced_research_gate",
|
||||
content=text,
|
||||
additional_kwargs={"hide_from_ui": True, "lc_source": "forced_research_gate"},
|
||||
)
|
||||
|
||||
|
||||
class ForcedResearchMiddleware(AgentMiddleware[AgentState]):
|
||||
"""Require information collection and enforce temporary-Python-only IO."""
|
||||
|
||||
state_schema = AgentState
|
||||
|
||||
def _patch_model_request(self, request: ModelRequest) -> ModelRequest:
|
||||
messages = list(request.messages or [])
|
||||
collected, attempts = _turn_collection_state(messages)
|
||||
if collected:
|
||||
return request
|
||||
if attempts >= _MAX_COLLECTION_ATTEMPTS:
|
||||
return request.override(messages=[*messages, _hidden_reminder(_COLLECTION_FAILED_TEXT)])
|
||||
return request.override(
|
||||
messages=[*messages, _hidden_reminder(_FORCE_COLLECTION_TEXT)],
|
||||
tool_choice="required",
|
||||
)
|
||||
|
||||
def _prevent_premature_exit(self, state: AgentState) -> dict[str, Any] | None:
|
||||
messages = list(state.get("messages") or [])
|
||||
if not messages:
|
||||
return None
|
||||
last = messages[-1]
|
||||
if not isinstance(last, AIMessage) or last.tool_calls:
|
||||
return None
|
||||
collected, attempts = _turn_collection_state(messages)
|
||||
if collected or attempts >= _MAX_COLLECTION_ATTEMPTS:
|
||||
return None
|
||||
|
||||
# Some OpenAI-compatible gateways ignore ``tool_choice=required``.
|
||||
# Hide/blank that premature answer and explicitly jump back to model.
|
||||
additional_kwargs = dict(last.additional_kwargs or {})
|
||||
additional_kwargs["hide_from_ui"] = True
|
||||
additional_kwargs["lc_source"] = "forced_research_suppressed_answer"
|
||||
response_metadata = deepcopy(last.response_metadata or {})
|
||||
if response_metadata.get("finish_reason") == "stop":
|
||||
response_metadata["finish_reason"] = "tool_calls"
|
||||
suppressed = last.model_copy(
|
||||
update={
|
||||
"content": "",
|
||||
"additional_kwargs": additional_kwargs,
|
||||
"response_metadata": response_metadata,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"jump_to": "model",
|
||||
"messages": [suppressed, _hidden_reminder(_FORCE_COLLECTION_TEXT)],
|
||||
}
|
||||
|
||||
def _reject_tool_call(self, request: ToolCallRequest) -> ToolMessage | None:
|
||||
tool_call = getattr(request, "tool_call", None) or {}
|
||||
reason = validate_forced_research_tool_call(tool_call)
|
||||
if reason is None:
|
||||
return None
|
||||
return ToolMessage(
|
||||
content=f"Error: {reason}",
|
||||
tool_call_id=str(_tool_field(tool_call, "id", "") or ""),
|
||||
name=str(_tool_field(tool_call, "name", "") or ""),
|
||||
status="error",
|
||||
)
|
||||
|
||||
@override
|
||||
def wrap_model_call(
|
||||
self,
|
||||
request: ModelRequest,
|
||||
handler: Callable[[ModelRequest], ModelResponse],
|
||||
) -> ModelCallResult:
|
||||
return handler(self._patch_model_request(request))
|
||||
|
||||
@override
|
||||
async def awrap_model_call(
|
||||
self,
|
||||
request: ModelRequest,
|
||||
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
||||
) -> ModelCallResult:
|
||||
return await handler(self._patch_model_request(request))
|
||||
|
||||
@hook_config(can_jump_to=["model"])
|
||||
@override
|
||||
def after_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
|
||||
return self._prevent_premature_exit(state)
|
||||
|
||||
@hook_config(can_jump_to=["model"])
|
||||
@override
|
||||
async def aafter_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
|
||||
return self._prevent_premature_exit(state)
|
||||
|
||||
@override
|
||||
def wrap_tool_call(
|
||||
self,
|
||||
request: ToolCallRequest,
|
||||
handler: Callable[[ToolCallRequest], ToolMessage | Command],
|
||||
) -> ToolMessage | Command:
|
||||
rejected = self._reject_tool_call(request)
|
||||
if rejected is not None:
|
||||
return rejected
|
||||
return handler(request)
|
||||
|
||||
@override
|
||||
async def awrap_tool_call(
|
||||
self,
|
||||
request: ToolCallRequest,
|
||||
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
|
||||
) -> ToolMessage | Command:
|
||||
rejected = self._reject_tool_call(request)
|
||||
if rejected is not None:
|
||||
return rejected
|
||||
return await handler(request)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FORCED_RESEARCH_AGENT_ID",
|
||||
"ForcedResearchMiddleware",
|
||||
"filter_forced_research_tools",
|
||||
"validate_forced_research_tool_call",
|
||||
]
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
"""席位「有效交付」判定 —— 只认可见正文,不要求 md / 落盘文件。
|
||||
|
||||
经典会商席位的契约是消息正文(分析结论、检索转述、要点清单都可以)。思考过程
|
||||
(``<think>`` / 未闭合 think / 模板只吐 ``</think>``)和空串都不算交付。与前端
|
||||
``splitInlineReasoning`` / ``stripReasoning`` 口径对齐,供前台网关、last-ai-message
|
||||
核对、后台编排引擎共用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_THINK_TAG_RE = re.compile(r"<think>\s*([\s\S]*?)\s*</think>", re.IGNORECASE)
|
||||
_ANY_THINK_TAG_RE = re.compile(r"</?think>", re.IGNORECASE)
|
||||
_OPEN_TAG = "<think>"
|
||||
_CLOSE_TAG = "</think>"
|
||||
|
||||
# 续轮硬约束:这些席位本轮没有可见正文,总控必须以系统核对为准重新派活。
|
||||
_INVALID_CONTINUE_PROMPT = (
|
||||
"以下席位本轮未产出有效正文(仅思考或中断,思考过程不算交付):{names}。"
|
||||
"这些席位**不算已交付**。请通过 agent_orchestration **重新派活**给它们,"
|
||||
"拿到可见正文后再判断是否收口;严禁声称它们已交付,也不得现在输出最终方案。"
|
||||
)
|
||||
|
||||
CONTINUE_PROMPT_ALL_VALID = (
|
||||
"各子智能体已就上一轮派活完成交付,请你结合最新结论判断是否仍需继续派活;"
|
||||
"若信息已足够,请直接输出最终方案并停止派活。"
|
||||
)
|
||||
|
||||
|
||||
def visible_seat_text(content: str | None) -> str:
|
||||
"""剥掉内联思考后剩下的可见正文。无正文时返回空串。"""
|
||||
if not content:
|
||||
return ""
|
||||
|
||||
working = content
|
||||
first_close = working.lower().find(_CLOSE_TAG)
|
||||
first_open = working.lower().find(_OPEN_TAG)
|
||||
# 形态 4:模板只吐闭合标签,闭合之前整段算思考。
|
||||
if first_close >= 0 and (first_open < 0 or first_close < first_open):
|
||||
working = working[first_close + len(_CLOSE_TAG) :]
|
||||
|
||||
closed = _THINK_TAG_RE.sub("", working)
|
||||
open_idx = closed.lower().rfind(_OPEN_TAG)
|
||||
if open_idx >= 0:
|
||||
closed = closed[:open_idx]
|
||||
return _ANY_THINK_TAG_RE.sub("", closed).strip()
|
||||
|
||||
|
||||
def classify_seat_delivery(content: str | None) -> str:
|
||||
"""``valid`` / ``thinking_only`` / ``empty``。"""
|
||||
raw = content or ""
|
||||
if visible_seat_text(raw):
|
||||
return "valid"
|
||||
if raw.strip():
|
||||
return "thinking_only"
|
||||
return "empty"
|
||||
|
||||
|
||||
def is_valid_seat_delivery(content: str | None) -> bool:
|
||||
return classify_seat_delivery(content) == "valid"
|
||||
|
||||
|
||||
def build_continue_prompt(
|
||||
*,
|
||||
invalid_names: list[str],
|
||||
delivered_block: str = "",
|
||||
) -> str:
|
||||
"""总控续轮 prompt:有无效席位时强制重派,否则沿用「已完成交付」口径。"""
|
||||
names = [n for n in invalid_names if n]
|
||||
if names:
|
||||
head = _INVALID_CONTINUE_PROMPT.format(names="、".join(names))
|
||||
if delivered_block.strip():
|
||||
return f"{head}\n\n其它席位已有的有效交付如下:\n{delivered_block}"
|
||||
return head
|
||||
if delivered_block.strip():
|
||||
return f"{CONTINUE_PROMPT_ALL_VALID}\n\n各席位最新交付如下:\n{delivered_block}"
|
||||
return CONTINUE_PROMPT_ALL_VALID
|
||||
+58
-32
@@ -23,11 +23,11 @@ import logging
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from .delivery import build_continue_prompt, visible_seat_text
|
||||
from .extraction_spec import build_summary_directive
|
||||
from .progress import JobProgressWriter
|
||||
from .types import (
|
||||
CHAIN_CLOSEOUT_PROMPT,
|
||||
CONTINUE_PROMPT,
|
||||
MAX_CYCLES,
|
||||
DagPlan,
|
||||
ReportResult,
|
||||
@@ -44,6 +44,30 @@ from .types import (
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _accept_seat_delivery(
|
||||
progress: JobProgressWriter,
|
||||
*,
|
||||
agent_id: str,
|
||||
name: str,
|
||||
cycle: int,
|
||||
raw: str | None,
|
||||
) -> str:
|
||||
"""只把剥掉思考后的可见正文记入 deliveries;思考-only / 空串记诊断并返回空串。"""
|
||||
vis = visible_seat_text(raw)
|
||||
if vis:
|
||||
return vis
|
||||
await progress.diag(
|
||||
stage="step2_seat",
|
||||
level="warning",
|
||||
event="seat_empty_delivery",
|
||||
message=f"席位「{name}」本轮无有效正文(仅思考、中断或空串,不算交付)",
|
||||
agent_id=agent_id,
|
||||
agent_name=name,
|
||||
cycle=cycle,
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class OrchestrationResult:
|
||||
"""引擎一次运行的终态。"""
|
||||
@@ -313,7 +337,7 @@ async def _run_gather_phase(
|
||||
await progress.seat_done(seat.agent_id, 0)
|
||||
return
|
||||
await _emit_switches(progress, seat_turn.switches, agent_name=name_by_id.get(seat.agent_id, seat.agent_id), agent_id=seat.agent_id)
|
||||
text = (seat_turn.final_text or "").strip()
|
||||
text = visible_seat_text(seat_turn.final_text)
|
||||
if text:
|
||||
gathered[seat.agent_id] = text
|
||||
await progress.add_seat_dialogue(
|
||||
@@ -396,15 +420,12 @@ async def _run_recommend(
|
||||
await progress.seat_done(agent_id, cyc)
|
||||
return
|
||||
await _emit_switches(progress, seat.switches, agent_name=name, cycle=cyc, agent_id=agent_id)
|
||||
batch[agent_id] = seat.final_text
|
||||
if not (seat.final_text or "").strip():
|
||||
await progress.diag(
|
||||
stage="step2_seat", level="warning", event="seat_empty_delivery",
|
||||
message=f"席位「{name}」本轮交付为空(可能模型未产出或被截断)",
|
||||
agent_id=agent_id, agent_name=name, cycle=cyc,
|
||||
)
|
||||
accepted = await _accept_seat_delivery(
|
||||
progress, agent_id=agent_id, name=name, cycle=cyc, raw=seat.final_text,
|
||||
)
|
||||
batch[agent_id] = accepted
|
||||
await progress.add_seat_dialogue(
|
||||
agent_id, name, seat.final_text, cyc,
|
||||
agent_id, name, accepted or seat.final_text, cyc,
|
||||
tool_calls=seat.tool_calls, thread_id=thread_ids.get(agent_id),
|
||||
)
|
||||
await progress.seat_done(agent_id, cyc)
|
||||
@@ -413,9 +434,12 @@ async def _run_recommend(
|
||||
deliveries.update(batch)
|
||||
|
||||
await progress.bump_consensus()
|
||||
# 续轮:把各席位本轮交付喂给总控,让它据实判断(总控 SOUL 依赖看到交付)
|
||||
# 续轮:无效席位强制重派;全部有效才用「已完成交付」口径。
|
||||
invalid_names = [
|
||||
name_by_id.get(aid, aid) for aid, text in batch.items() if not (text or "").strip()
|
||||
]
|
||||
block = _deliveries_block(deliveries, name_by_id)
|
||||
message = CONTINUE_PROMPT + (f"\n\n各席位最新交付如下:\n{block}" if block else "")
|
||||
message = build_continue_prompt(invalid_names=invalid_names, delivered_block=block)
|
||||
|
||||
# 达到最大轮次:强制收口(对齐前端 toast「已达到最大研讨轮次」)
|
||||
logger.info("roundtable recommend loop hit MAX_CYCLES=%d, forcing consensus", MAX_CYCLES)
|
||||
@@ -493,15 +517,12 @@ async def _run_chain(
|
||||
await progress.set_consensus_pct(round((i + 1) / total * 90))
|
||||
continue
|
||||
await _emit_switches(progress, seat_turn.switches, agent_name=seat.name, cycle=i + 1, agent_id=seat.agent_id)
|
||||
deliveries[seat.agent_id] = seat_turn.final_text
|
||||
if not (seat_turn.final_text or "").strip():
|
||||
await progress.diag(
|
||||
stage="step2_seat", level="warning", event="seat_empty_delivery",
|
||||
message=f"席位「{seat.name}」本轮交付为空(可能模型未产出或被截断)",
|
||||
agent_id=seat.agent_id, agent_name=seat.name, cycle=i + 1,
|
||||
)
|
||||
accepted = await _accept_seat_delivery(
|
||||
progress, agent_id=seat.agent_id, name=seat.name, cycle=i + 1, raw=seat_turn.final_text,
|
||||
)
|
||||
deliveries[seat.agent_id] = accepted
|
||||
await progress.add_seat_dialogue(
|
||||
seat.agent_id, seat.name, seat_turn.final_text, i + 1,
|
||||
seat.agent_id, seat.name, accepted or 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)
|
||||
@@ -509,11 +530,15 @@ async def _run_chain(
|
||||
if total > 0:
|
||||
await progress.set_consensus_pct(round((i + 1) / total * 90))
|
||||
|
||||
# (c) 总控收口:综合全链交付,产出最终结论(带上全部席位交付)
|
||||
# (c) 总控收口:仍有无效席位时禁止「已完成发言」口径,强制重派。
|
||||
if 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 "")
|
||||
invalid_names = [a.name for a in agents if not (deliveries.get(a.agent_id) or "").strip()]
|
||||
if invalid_names:
|
||||
closeout_msg = build_continue_prompt(invalid_names=invalid_names, delivered_block=block)
|
||||
else:
|
||||
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,
|
||||
@@ -616,15 +641,12 @@ async def _run_dag(
|
||||
await progress.seat_done(seat.agent_id, _cyc)
|
||||
return
|
||||
await _emit_switches(progress, seat_turn.switches, agent_name=seat.name, cycle=_cyc, agent_id=seat.agent_id)
|
||||
deliveries[seat.agent_id] = seat_turn.final_text
|
||||
if not (seat_turn.final_text or "").strip():
|
||||
await progress.diag(
|
||||
stage="step2_seat", level="warning", event="seat_empty_delivery",
|
||||
message=f"席位「{seat.name}」本轮交付为空(可能模型未产出或被截断)",
|
||||
agent_id=seat.agent_id, agent_name=seat.name, cycle=_cyc,
|
||||
)
|
||||
accepted = await _accept_seat_delivery(
|
||||
progress, agent_id=seat.agent_id, name=seat.name, cycle=_cyc, raw=seat_turn.final_text,
|
||||
)
|
||||
deliveries[seat.agent_id] = accepted
|
||||
await progress.add_seat_dialogue(
|
||||
seat.agent_id, seat.name, seat_turn.final_text, _cyc,
|
||||
seat.agent_id, seat.name, accepted or seat_turn.final_text, _cyc,
|
||||
tool_calls=seat_turn.tool_calls, thread_id=thread_ids.get(seat.agent_id),
|
||||
)
|
||||
await progress.seat_done(seat.agent_id, _cyc)
|
||||
@@ -634,11 +656,15 @@ async def _run_dag(
|
||||
if total > 0:
|
||||
await progress.set_consensus_pct(round((i + 1) / total * 90))
|
||||
|
||||
# (c) 收口:finalSynthesis 时总控综合全部 stage 交付,产出最终结论。
|
||||
# (c) 收口:仍有无效席位时禁止「已完成发言」口径,强制重派。
|
||||
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 "")
|
||||
invalid_names = [a.name for a in agents if not (deliveries.get(a.agent_id) or "").strip()]
|
||||
if invalid_names:
|
||||
closeout_msg = build_continue_prompt(invalid_names=invalid_names, delivered_block=block)
|
||||
else:
|
||||
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,
|
||||
|
||||
+5
-5
@@ -16,14 +16,14 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
from .delivery import CONTINUE_PROMPT_ALL_VALID
|
||||
|
||||
# 编排循环最大轮次,与前端 roundtable-constants.ts MAX_CYCLES 对齐。
|
||||
MAX_CYCLES = 8
|
||||
|
||||
# recommend 模式每轮派活后、回到 leader 的「续轮」prompt(逐字对齐前端)。
|
||||
CONTINUE_PROMPT = (
|
||||
"各子智能体已就上一轮派活完成交付,请你结合最新结论判断是否仍需继续派活;"
|
||||
"若信息已足够,请直接输出最终方案并停止派活。"
|
||||
)
|
||||
# recommend 模式全部席位均有可见正文时的「续轮」prompt。有无效席位时请用
|
||||
# ``delivery.build_continue_prompt``,不要无条件使用本常量。
|
||||
CONTINUE_PROMPT = CONTINUE_PROMPT_ALL_VALID
|
||||
|
||||
# chain 模式全链走完后、总控收口的 prompt(逐字对齐前端)。
|
||||
CHAIN_CLOSEOUT_PROMPT = (
|
||||
|
||||
Reference in new issue
Block a user