fix: writing mode uses chat search then pipeline write only
Keep deep_research_report as a write-only deliverable from conversation materials, block post-success rewrite loops with a summary nudge, fill thin/empty pools from model knowledge, and open the sandbox only on real report.md content. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
9afb9750e5
commit
49c01cb72b
20 files changed
+1449
-381
No files matched your search
+468
@@ -0,0 +1,468 @@
|
||||
"""Redirect writing-mode Markdown deliverables onto ``deep_research_report``.
|
||||
|
||||
Writing mode still allows normal chat, search, and clarification. The pipeline
|
||||
starts only when the model begins writing the report file (``write_file`` /
|
||||
``str_replace`` of ``report.md`` or any Markdown under
|
||||
``/mnt/user-data/outputs/``): those calls are rewritten to
|
||||
``deep_research_report``. Sibling ``present_files`` of the same report are
|
||||
dropped because the pipeline presents the file itself.
|
||||
|
||||
After the pipeline has succeeded once in this thread, further
|
||||
``deep_research_report`` / hand-written report writes / ``read_file`` of the
|
||||
report are dropped. The first time that happens, a hidden summary nudge is
|
||||
injected and the graph jumps back to the model so it can write the 2–3
|
||||
sentence wrap-up. If it still tries to loop after that nudge, the turn ends.
|
||||
Ending immediately on the first rewrite attempt left the model's
|
||||
"I will rewrite this" text as the visible summary.
|
||||
|
||||
This middleware never sets ``tool_choice``. Thinking-mode providers (Aliyun
|
||||
compatible-mode) reject ``required`` / object ``tool_choice`` with HTTP 400.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Awaitable, Callable
|
||||
from copy import deepcopy
|
||||
from typing import Any, override
|
||||
|
||||
from langchain.agents import AgentState
|
||||
from langchain.agents.middleware import AgentMiddleware, hook_config
|
||||
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
|
||||
|
||||
from deerflow.tools.builtins.deep_research_report_tool import is_writing_mode_report_path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOOL_NAME = "deep_research_report"
|
||||
_WRITE_TOOLS = frozenset({"write_file", "str_replace"})
|
||||
_READ_TOOLS = frozenset({"read_file", "read_multiple_files"})
|
||||
_PRESENT_TOOL = "present_files"
|
||||
_OUTPUTS_PREFIX = "/mnt/user-data/outputs"
|
||||
_MAX_TOPIC_CHARS = 500
|
||||
_NUDGE_KWARG = "writing_mode_summary_nudge"
|
||||
_REJECT_HANDWRITTEN = (
|
||||
"写作模式的报告文件必须由 `deep_research_report` 生成,禁止用 write_file / "
|
||||
"str_replace 手写报告。请立即调用 `deep_research_report`(topic=用户课题原文)。"
|
||||
)
|
||||
_REJECT_AFTER_SUCCESS = (
|
||||
"写作管线已经完成,报告已写入 /mnt/user-data/outputs/report.md 并展示给用户。"
|
||||
"禁止再次调用 deep_research_report,也禁止用 write_file / str_replace / "
|
||||
"read_file 读写该报告。请只用 2-3 句话总结核心结论后结束本轮,不要再调用任何文件或写作工具。"
|
||||
)
|
||||
_SUMMARY_NUDGE = (
|
||||
"<system_reminder>\n"
|
||||
"写作管线已经完成,报告已写入 /mnt/user-data/outputs/report.md 并展示给用户。\n"
|
||||
"请只用 2-3 句话总结核心结论,不要再调用任何工具,不要阅读或重写该文件。\n"
|
||||
"不要评价材料是否不足,不要计划重写。\n"
|
||||
"</system_reminder>"
|
||||
)
|
||||
|
||||
|
||||
def _is_visible_human(message: Any) -> bool:
|
||||
if not isinstance(message, HumanMessage):
|
||||
return False
|
||||
kwargs = getattr(message, "additional_kwargs", None) or {}
|
||||
return not kwargs.get("hide_from_ui")
|
||||
|
||||
|
||||
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 _tool_name(tool_call: object) -> str:
|
||||
return str(_tool_field(tool_call, "name", "") or "")
|
||||
|
||||
|
||||
def _tool_path(tool_call: object) -> str:
|
||||
args = _normalize_args(_tool_field(tool_call, "args", {}))
|
||||
path = args.get("path")
|
||||
if path is None:
|
||||
files = args.get("files") or args.get("filepaths") or args.get("paths")
|
||||
if isinstance(files, list) and files:
|
||||
path = files[0]
|
||||
return str(path or "").strip().replace("\\", "/")
|
||||
|
||||
|
||||
def _is_outputs_markdown_path(path: str) -> bool:
|
||||
if is_writing_mode_report_path(path):
|
||||
return True
|
||||
if not path:
|
||||
return False
|
||||
lowered = path.lower()
|
||||
if not (lowered.endswith(".md") or lowered.endswith(".markdown")):
|
||||
return False
|
||||
if path == _OUTPUTS_PREFIX or path.startswith(f"{_OUTPUTS_PREFIX}/"):
|
||||
return True
|
||||
relative = path.lstrip("./")
|
||||
return relative == "outputs" or relative.startswith("outputs/")
|
||||
|
||||
|
||||
def is_handwritten_report_call(tool_call: object) -> bool:
|
||||
"""True when the model is about to hand-write the writing-mode Markdown file."""
|
||||
if _tool_name(tool_call) not in _WRITE_TOOLS:
|
||||
return False
|
||||
return _is_outputs_markdown_path(_tool_path(tool_call))
|
||||
|
||||
|
||||
def is_report_present_call(tool_call: object) -> bool:
|
||||
if _tool_name(tool_call) != _PRESENT_TOOL:
|
||||
return False
|
||||
path = _tool_path(tool_call)
|
||||
if path:
|
||||
return _is_outputs_markdown_path(path)
|
||||
args = _normalize_args(_tool_field(tool_call, "args", {}))
|
||||
files = args.get("files") or args.get("filepaths") or args.get("paths") or []
|
||||
if isinstance(files, list):
|
||||
return any(_is_outputs_markdown_path(str(item or "").strip().replace("\\", "/")) for item in files)
|
||||
return False
|
||||
|
||||
|
||||
def is_pipeline_call(tool_call: object) -> bool:
|
||||
return _tool_name(tool_call) == TOOL_NAME
|
||||
|
||||
|
||||
def is_report_reread_call(tool_call: object) -> bool:
|
||||
"""True when the model is about to re-read the writing-mode Markdown file."""
|
||||
if _tool_name(tool_call) not in _READ_TOOLS:
|
||||
return False
|
||||
path = _tool_path(tool_call)
|
||||
if path:
|
||||
return _is_outputs_markdown_path(path)
|
||||
args = _normalize_args(_tool_field(tool_call, "args", {}))
|
||||
files = args.get("files") or args.get("filepaths") or args.get("paths") or []
|
||||
if isinstance(files, list):
|
||||
return any(_is_outputs_markdown_path(str(item or "").strip().replace("\\", "/")) for item in files)
|
||||
return False
|
||||
|
||||
|
||||
def is_deliverable_loop_call(tool_call: object) -> bool:
|
||||
"""Pipeline, hand-written report, or presenting the report — all loop fuel."""
|
||||
return is_pipeline_call(tool_call) or is_handwritten_report_call(tool_call) or is_report_present_call(tool_call)
|
||||
|
||||
|
||||
def is_post_success_loop_call(tool_call: object) -> bool:
|
||||
"""After a successful pipeline, re-reading the report is also a loop."""
|
||||
return is_deliverable_loop_call(tool_call) or is_report_reread_call(tool_call)
|
||||
|
||||
|
||||
def _already_nudged_summary(messages: list[Any]) -> bool:
|
||||
for message in messages:
|
||||
if not isinstance(message, HumanMessage):
|
||||
continue
|
||||
kwargs = getattr(message, "additional_kwargs", None) or {}
|
||||
if kwargs.get(_NUDGE_KWARG):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _summary_nudge_message() -> HumanMessage:
|
||||
return HumanMessage(
|
||||
content=_SUMMARY_NUDGE,
|
||||
additional_kwargs={"hide_from_ui": True, _NUDGE_KWARG: True},
|
||||
)
|
||||
|
||||
|
||||
def is_post_success_loop_call(tool_call: object) -> bool:
|
||||
"""After a successful pipeline, re-reading the report is also a loop."""
|
||||
return is_deliverable_loop_call(tool_call) or is_report_reread_call(tool_call)
|
||||
|
||||
|
||||
def _already_nudged_summary(messages: list[Any]) -> bool:
|
||||
for message in messages:
|
||||
if not isinstance(message, HumanMessage):
|
||||
continue
|
||||
kwargs = getattr(message, "additional_kwargs", None) or {}
|
||||
if kwargs.get(_NUDGE_KWARG):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _summary_nudge_message() -> HumanMessage:
|
||||
return HumanMessage(
|
||||
content=_SUMMARY_NUDGE,
|
||||
additional_kwargs={"hide_from_ui": True, _NUDGE_KWARG: True},
|
||||
)
|
||||
|
||||
|
||||
def _report_tool_succeeded(message: ToolMessage) -> bool:
|
||||
if str(getattr(message, "name", "") or "") != TOOL_NAME:
|
||||
return False
|
||||
status = str(getattr(message, "status", "") or "").lower()
|
||||
if status == "error":
|
||||
return False
|
||||
content = str(getattr(message, "content", "") or "").strip()
|
||||
if not content:
|
||||
return False
|
||||
return not content.lower().startswith("error")
|
||||
|
||||
|
||||
def pipeline_already_succeeded(messages: list[Any]) -> bool:
|
||||
"""True after any successful ``deep_research_report`` in this thread."""
|
||||
return any(isinstance(message, ToolMessage) and _report_tool_succeeded(message) for message in messages)
|
||||
|
||||
|
||||
def _message_text(message: Any) -> str:
|
||||
content = getattr(message, "content", "")
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for part in content:
|
||||
if isinstance(part, str):
|
||||
parts.append(part)
|
||||
elif isinstance(part, dict):
|
||||
text = part.get("text")
|
||||
if isinstance(text, str):
|
||||
parts.append(text)
|
||||
return " ".join(parts).strip()
|
||||
return str(content or "").strip()
|
||||
|
||||
|
||||
def extract_report_topic(messages: list[Any]) -> str:
|
||||
"""Use the latest visible user text as ``deep_research_report.topic``."""
|
||||
for message in reversed(messages):
|
||||
if _is_visible_human(message):
|
||||
text = " ".join(_message_text(message).split())
|
||||
if text:
|
||||
return text[:_MAX_TOPIC_CHARS]
|
||||
return "当前课题"
|
||||
|
||||
|
||||
def _as_report_call(tool_call: object, topic: str) -> dict[str, Any]:
|
||||
call_id = str(_tool_field(tool_call, "id") or "")
|
||||
return {
|
||||
"name": TOOL_NAME,
|
||||
"args": {"topic": topic},
|
||||
"id": call_id,
|
||||
"type": "tool_call",
|
||||
}
|
||||
|
||||
|
||||
def _kept_call_ids(calls: list[Any]) -> set[str]:
|
||||
return {str(_tool_field(call, "id") or "") for call in calls if _tool_field(call, "id")}
|
||||
|
||||
|
||||
def _sync_raw_tool_calls(last: AIMessage, kept: list[Any]) -> dict[str, Any]:
|
||||
update: dict[str, Any] = {"tool_calls": kept}
|
||||
additional_kwargs = dict(getattr(last, "additional_kwargs", {}) or {})
|
||||
raw_calls = additional_kwargs.get("tool_calls")
|
||||
kept_ids = _kept_call_ids(kept)
|
||||
rewritten_by_id = {
|
||||
str(_tool_field(call, "id") or ""): call
|
||||
for call in kept
|
||||
if _tool_field(call, "id")
|
||||
}
|
||||
if isinstance(raw_calls, list) and raw_calls:
|
||||
synced: list[Any] = []
|
||||
for item in raw_calls:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
item_id = str(item.get("id") or "")
|
||||
if item_id not in kept_ids:
|
||||
continue
|
||||
replacement = rewritten_by_id.get(item_id)
|
||||
if replacement is not None and _tool_name(replacement) == TOOL_NAME:
|
||||
function = dict(item.get("function") or {})
|
||||
function["name"] = TOOL_NAME
|
||||
function["arguments"] = json.dumps(
|
||||
_normalize_args(_tool_field(replacement, "args", {})),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
synced.append({**item, "function": function})
|
||||
else:
|
||||
synced.append(item)
|
||||
if synced:
|
||||
additional_kwargs["tool_calls"] = synced
|
||||
else:
|
||||
additional_kwargs.pop("tool_calls", None)
|
||||
additional_kwargs.pop("function_call", None)
|
||||
elif not kept:
|
||||
additional_kwargs.pop("tool_calls", None)
|
||||
additional_kwargs.pop("function_call", None)
|
||||
update["additional_kwargs"] = additional_kwargs
|
||||
if not kept:
|
||||
response_metadata = deepcopy(getattr(last, "response_metadata", {}) or {})
|
||||
if response_metadata.get("finish_reason") == "tool_calls":
|
||||
response_metadata["finish_reason"] = "stop"
|
||||
update["response_metadata"] = response_metadata
|
||||
return update
|
||||
|
||||
|
||||
def rewrite_handwritten_report_calls(
|
||||
last: AIMessage,
|
||||
*,
|
||||
topic: str,
|
||||
pipeline_already_done: bool = False,
|
||||
) -> AIMessage | None:
|
||||
"""Rewrite or drop report deliverable tool calls.
|
||||
|
||||
Before the pipeline has succeeded: rewrite the first hand-written report
|
||||
write to ``deep_research_report`` and drop sibling presents.
|
||||
|
||||
After it has succeeded: drop every pipeline / hand-written / present /
|
||||
report-reread call so the model cannot start another writing loop.
|
||||
"""
|
||||
tool_calls = list(getattr(last, "tool_calls", None) or [])
|
||||
if not tool_calls:
|
||||
return None
|
||||
|
||||
if pipeline_already_done:
|
||||
kept = [call for call in tool_calls if not is_post_success_loop_call(call)]
|
||||
if len(kept) == len(tool_calls):
|
||||
return None
|
||||
update = _sync_raw_tool_calls(last, kept)
|
||||
if not kept:
|
||||
update["content"] = ""
|
||||
return last.model_copy(update=update)
|
||||
|
||||
has_pipeline = any(is_pipeline_call(call) for call in tool_calls)
|
||||
rewritten: list[Any] = []
|
||||
changed = False
|
||||
redirected = has_pipeline
|
||||
for call in tool_calls:
|
||||
if is_pipeline_call(call):
|
||||
rewritten.append(call)
|
||||
continue
|
||||
if is_handwritten_report_call(call):
|
||||
changed = True
|
||||
if redirected:
|
||||
continue
|
||||
rewritten.append(_as_report_call(call, topic))
|
||||
redirected = True
|
||||
continue
|
||||
if is_report_present_call(call) and (
|
||||
has_pipeline or redirected or any(is_handwritten_report_call(item) for item in tool_calls)
|
||||
):
|
||||
changed = True
|
||||
continue
|
||||
rewritten.append(call)
|
||||
|
||||
if not changed:
|
||||
return None
|
||||
return last.model_copy(update=_sync_raw_tool_calls(last, rewritten))
|
||||
|
||||
|
||||
def _messages_from_tool_request(request: ToolCallRequest) -> list[Any]:
|
||||
state = getattr(request, "state", None) or {}
|
||||
if isinstance(state, dict):
|
||||
return list(state.get("messages") or [])
|
||||
messages = getattr(state, "messages", None)
|
||||
return list(messages or [])
|
||||
|
||||
|
||||
class WritingModeReportMiddleware(AgentMiddleware[AgentState]):
|
||||
"""Start the writing pipeline only when the model begins writing the Markdown file."""
|
||||
|
||||
state_schema = AgentState
|
||||
|
||||
def _redirect_or_stop(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):
|
||||
return None
|
||||
already_done = pipeline_already_succeeded(messages)
|
||||
patched = rewrite_handwritten_report_calls(
|
||||
last,
|
||||
topic=extract_report_topic(messages),
|
||||
pipeline_already_done=already_done,
|
||||
)
|
||||
if patched is None:
|
||||
return None
|
||||
result: dict[str, Any] = {"messages": [patched]}
|
||||
if already_done and not (patched.tool_calls or []):
|
||||
if _already_nudged_summary(messages):
|
||||
logger.info(
|
||||
"Writing-mode pipeline already succeeded; summary nudge ignored, ending turn"
|
||||
)
|
||||
result["jump_to"] = "end"
|
||||
return result
|
||||
logger.info(
|
||||
"Writing-mode pipeline already succeeded; dropping deliverable tools and nudging summary"
|
||||
)
|
||||
result["messages"] = [patched, _summary_nudge_message()]
|
||||
result["jump_to"] = "model"
|
||||
return result
|
||||
|
||||
def _reject_loop_tool(self, request: ToolCallRequest) -> ToolMessage | None:
|
||||
tool_call = getattr(request, "tool_call", None) or {}
|
||||
already_done = pipeline_already_succeeded(_messages_from_tool_request(request))
|
||||
if already_done and is_post_success_loop_call(tool_call):
|
||||
return ToolMessage(
|
||||
content=f"Error: {_REJECT_AFTER_SUCCESS}",
|
||||
tool_call_id=str(_tool_field(tool_call, "id") or ""),
|
||||
name=str(_tool_name(tool_call) or TOOL_NAME),
|
||||
)
|
||||
if not already_done and is_handwritten_report_call(tool_call):
|
||||
return ToolMessage(
|
||||
content=f"Error: {_REJECT_HANDWRITTEN}",
|
||||
tool_call_id=str(_tool_field(tool_call, "id") or ""),
|
||||
name=str(_tool_name(tool_call) or "write_file"),
|
||||
)
|
||||
return None
|
||||
|
||||
@hook_config(can_jump_to=["end", "model"])
|
||||
@override
|
||||
def after_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
|
||||
return self._redirect_or_stop(state)
|
||||
|
||||
@hook_config(can_jump_to=["end", "model"])
|
||||
@override
|
||||
async def aafter_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
|
||||
return self._redirect_or_stop(state)
|
||||
|
||||
@override
|
||||
def wrap_tool_call(
|
||||
self,
|
||||
request: ToolCallRequest,
|
||||
handler: Callable[[ToolCallRequest], ToolMessage | Command],
|
||||
) -> ToolMessage | Command:
|
||||
rejected = self._reject_loop_tool(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_loop_tool(request)
|
||||
if rejected is not None:
|
||||
return rejected
|
||||
return await handler(request)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"TOOL_NAME",
|
||||
"WritingModeReportMiddleware",
|
||||
"extract_report_topic",
|
||||
"is_handwritten_report_call",
|
||||
"is_post_success_loop_call",
|
||||
"is_report_present_call",
|
||||
"is_report_reread_call",
|
||||
"pipeline_already_succeeded",
|
||||
"rewrite_handwritten_report_calls",
|
||||
]
|
||||
Reference in new issue
Block a user