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
+48
-140
@@ -7,19 +7,12 @@
|
||||
``outputs/`` 目录——前端画布 / 编辑 / 下载 / 续写全部沿用既有 artifacts 通道。
|
||||
除「写 md」这一动作换成管线外,agent 的对话 / 检索 / 澄清行为一切照旧。
|
||||
|
||||
资料来源三分支(收割池先按**当前主题**做词面相关度强过滤——旧课题的检索
|
||||
结果既不计入门槛,也不进报告):
|
||||
资料来源(收割池先按**当前主题**做词面相关度强过滤——旧课题的检索
|
||||
结果不进报告):
|
||||
|
||||
- 主题相关池足够(≥ :data:`_MIN_HARVESTED_MATERIALS`)→ 直接用对话资料写;
|
||||
- 不足且用户已答复 → ``retrieve=True`` 自检索(对话资料合并去重)、
|
||||
``retrieve=False`` 只用现有资料(哪怕为空——basic runner 有优雅兜底);
|
||||
- 不足且未询问 → 返回指令 ToolMessage,让模型用 ``ask_clarification``
|
||||
询问用户是否补充检索,用户答复后带 ``retrieve`` 重调本工具。
|
||||
|
||||
``retrieve=True`` 不只是提示词约束:工具会核验消息史里存在
|
||||
「本工具的资料不足答复 → ask_clarification → 用户回复」完整链
|
||||
(:func:`_retrieval_confirmed_by_user`),模型擅自传 ``retrieve=True``
|
||||
会被拒绝并打回询问流程。
|
||||
- 一律用对话里已经产生的资料写(哪怕为空——basic runner 有领域知识兜底),
|
||||
**不再**因条数不足打断用户,也**不再**在管线内部补检索。
|
||||
需要检索时由 lead agent 用对话工具先搜,再调用本工具写文件。
|
||||
|
||||
报告管线继承聊天里选择的模型与思考开关(``context.model_name`` /
|
||||
``thinking_enabled`` / ``thinking_force_disabled``,经 run config 白名单透
|
||||
@@ -60,12 +53,11 @@ from deerflow.agents.deep_research.events import DeepResearchEvent, EventType, R
|
||||
from deerflow.agents.deep_research.types import AdapterBundle, DeepResearchRequest, ResearchMaterial
|
||||
from deerflow.agents.thread_state import ThreadState
|
||||
from deerflow.persistence.report_structures.defaults import GENERAL_OUTLINE
|
||||
from deerflow.runtime.references import _message_name, _message_type
|
||||
from deerflow.runtime.thread_paths import resolve_path_user_id
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 收割池低于该条数视为「资料不足」,需要先征询用户是否补充检索。
|
||||
# 收割池低于该条数视为「资料偏少」,仅记日志,不再打断用户。
|
||||
_MIN_HARVESTED_MATERIALS = 3
|
||||
|
||||
# 引擎事件中值得转发到聊天的子集(model_usage / heartbeat / job_* 只对持久
|
||||
@@ -96,6 +88,17 @@ _FORWARDABLE_LIVE_EVENTS: frozenset[str] = frozenset({"report_delta", "report_th
|
||||
REPORT_VIRTUAL_PATH = "/mnt/user-data/outputs/report.md"
|
||||
|
||||
|
||||
def is_writing_mode_report_path(path: str | None) -> bool:
|
||||
"""Only ``report.md`` counts as the writing-mode deliverable for follow-up edits.
|
||||
|
||||
Leftover notes / skill Markdown must not skip the first-report pipeline.
|
||||
"""
|
||||
if not path or not isinstance(path, str):
|
||||
return False
|
||||
normalized = path.replace("\\", "/").split("?", 1)[0].split("#", 1)[0].rstrip("/")
|
||||
return normalized.lower().endswith("/report.md") or normalized.lower() == "report.md"
|
||||
|
||||
|
||||
class StreamWriterEventSink:
|
||||
"""把引擎事件经 LangGraph custom 通道转发到聊天前端。
|
||||
|
||||
@@ -211,6 +214,15 @@ class HarvestPlusSearchMaterialProvider:
|
||||
return dedupe_materials(combined)
|
||||
|
||||
|
||||
# 写作模式常在「不用搜索 / 对话资料很少」时开写。工作台默认的「材料不足就
|
||||
# 写明资料不足」会把报告写成元分析;这里强制用领域知识补全正文。
|
||||
_KNOWLEDGE_WRITE_INSTRUCTION = (
|
||||
"对话材料很少或用户要求直接开写时:必须基于模型自身的领域知识写成完整、有实质内容的研究报告"
|
||||
"(含架构说明;用户要求流程图时用 Mermaid)。禁止把「材料不足/未提供文献/现有材料高度浓缩」"
|
||||
"写成报告主线或用其填充多个章节。参考文献可标为基于公开领域知识,不要用「材料未提供」占整节。"
|
||||
)
|
||||
|
||||
|
||||
def build_writing_research_config(
|
||||
*,
|
||||
focus: str | None = None,
|
||||
@@ -224,7 +236,10 @@ def build_writing_research_config(
|
||||
覆盖 fast/smart/strategic 三个角色,使报告管线与对话用同一个模型和思考
|
||||
开关(缺省回落系统默认模型)。
|
||||
"""
|
||||
instruction = focus.strip() if focus and focus.strip() else None
|
||||
parts: list[str] = []
|
||||
if focus and focus.strip():
|
||||
parts.append(focus.strip())
|
||||
parts.append(_KNOWLEDGE_WRITE_INSTRUCTION)
|
||||
return DeepResearchConfig(
|
||||
mode="basic",
|
||||
collection_mode="legacy",
|
||||
@@ -235,7 +250,7 @@ def build_writing_research_config(
|
||||
fast_model=model_name,
|
||||
smart_model=model_name,
|
||||
strategic_model=model_name,
|
||||
**({"report_instruction": instruction} if instruction else {}),
|
||||
report_instruction="\n".join(parts),
|
||||
).clamp()
|
||||
|
||||
|
||||
@@ -325,33 +340,6 @@ def _filter_relevant_materials(
|
||||
return relevant, len(materials) - len(relevant)
|
||||
|
||||
|
||||
# ── retrieve=True 的用户确认核验(P1:不靠提示词,消息史里找证据链) ──────────
|
||||
|
||||
|
||||
def _retrieval_confirmed_by_user(messages: list[Any]) -> bool:
|
||||
"""核验消息史存在「本工具资料不足答复 → ask_clarification → 用户回复」。
|
||||
|
||||
模型无法伪造 ToolMessage / HumanMessage(分别由工具执行与真实用户输入
|
||||
产生),因此该链成立 ⇔ 用户确实被问过并答过。跨 run 依然有效——消息
|
||||
历史就是 LangGraph 的持久状态。
|
||||
"""
|
||||
last_report_reply = -1
|
||||
for index, message in enumerate(messages):
|
||||
if _message_type(message) == "tool" and str(_message_name(message) or "") == "deep_research_report":
|
||||
last_report_reply = index
|
||||
if last_report_reply < 0:
|
||||
return False
|
||||
asked = False
|
||||
for message in messages[last_report_reply + 1 :]:
|
||||
if _message_type(message) != "tool":
|
||||
if asked and _message_type(message) == "human":
|
||||
return True
|
||||
continue
|
||||
if str(_message_name(message) or "") == "ask_clarification":
|
||||
asked = True
|
||||
return False
|
||||
|
||||
|
||||
def _safe_stream_writer() -> Any:
|
||||
"""获取当前 run 的 custom 事件写入器;非流式上下文返回 None。"""
|
||||
try:
|
||||
@@ -362,45 +350,6 @@ def _safe_stream_writer() -> Any:
|
||||
return None
|
||||
|
||||
|
||||
def _insufficient_materials_message(
|
||||
relevant_count: int,
|
||||
minimum: int,
|
||||
*,
|
||||
topic: str,
|
||||
total_count: int,
|
||||
dropped_count: int,
|
||||
) -> str:
|
||||
detail = (
|
||||
f"对话中共整理出 {total_count} 条资料,其中与当前主题「{topic}」相关的仅 {relevant_count} 条"
|
||||
if dropped_count > 0
|
||||
else f"对话中仅整理出 {relevant_count} 条与主题「{topic}」相关的资料"
|
||||
)
|
||||
return (
|
||||
f"[需要用户确认] {detail}(低于 {minimum} 条的最低参考线)。"
|
||||
"在生成报告前,请立即调用 `ask_clarification` 询问用户:\n"
|
||||
'question: "对话中已有的资料较少,是否自动检索更多资料来写报告?"\n'
|
||||
'clarification_type: "missing_info"\n'
|
||||
f'context: "当前对话仅整理出 {relevant_count} 条与主题相关的资料;补充检索可让报告更充实,但会多花一些时间。"\n'
|
||||
'options: ["检索更多资料,再写报告", "不用检索,直接用现有资料写"]\n'
|
||||
"用户选择检索 → 携带 retrieve=true 重新调用本工具(参数 topic/focus 保持不变);"
|
||||
"用户选择不检索 → 携带 retrieve=false 重新调用本工具。"
|
||||
"在得到用户答复前,不要自行检索,也不要用 write_file 手工撰写报告。"
|
||||
"注意:未经上述询问并获得用户答复,本工具会拒绝 retrieve=true。"
|
||||
)
|
||||
|
||||
|
||||
def _retrieve_without_confirmation_message() -> str:
|
||||
return (
|
||||
"[参数被拒绝] retrieve=true 只允许在用户通过 ask_clarification 明确同意补充检索之后使用;"
|
||||
"本次调用未检测到「询问用户 → 用户答复」的记录,已按资料不足处理。"
|
||||
"请立即调用 `ask_clarification` 询问用户是否检索更多资料"
|
||||
'(question: "对话中已有的资料较少,是否自动检索更多资料来写报告?",'
|
||||
'clarification_type: "missing_info",options: ["检索更多资料,再写报告", "不用检索,直接用现有资料写"]),'
|
||||
"用户答复后再按其选择重新调用本工具(retrieve=true / false)。"
|
||||
"不要不经询问直接传 retrieve=true,也不要用 write_file 手工撰写报告。"
|
||||
)
|
||||
|
||||
|
||||
@tool("deep_research_report", parse_docstring=True)
|
||||
async def deep_research_report_tool(
|
||||
runtime: ToolRuntime[ContextT, ThreadState],
|
||||
@@ -423,20 +372,18 @@ async def deep_research_report_tool(
|
||||
automatically; do NOT write the report body yourself with write_file.
|
||||
|
||||
If the harvested pool is thin (or little of it matches the current topic), the
|
||||
tool returns instructions to ask the user whether to search for more materials
|
||||
(via ask_clarification); after the user answers, re-call this tool with
|
||||
`retrieve` set accordingly (same topic/focus). `retrieve=true` is REJECTED
|
||||
unless the conversation shows that ask_clarification exchange — never pass it
|
||||
speculatively.
|
||||
tool still starts the writing pipeline immediately with whatever relevant
|
||||
materials exist — do NOT ask the user whether to search for more, and do NOT
|
||||
call ask_clarification for that reason. Search in the conversation first with
|
||||
your normal tools; this tool only writes the file.
|
||||
|
||||
Args:
|
||||
topic: The research topic / thesis to investigate. Copy the user's subject faithfully;
|
||||
do not paraphrase it into something narrower unless the user asked for that scope.
|
||||
focus: Optional extra write-time requirements from the user (length, tone, must-cover
|
||||
points, language preferences). Omit when the user gave none.
|
||||
retrieve: Only set on a re-call after the user answered the insufficient-materials
|
||||
question. True = search more materials (combined with the conversation pool);
|
||||
False = write directly with existing materials only. Omit on the first call.
|
||||
retrieve: Ignored. Kept for older callers; the writing-mode pipeline never
|
||||
searches. False / omitted / True all write from conversation materials only.
|
||||
tool_call_id: Injected tool call id.
|
||||
"""
|
||||
# 与 present_file_tool 相同的解析顺序:runtime.context → runtime.config。
|
||||
@@ -473,63 +420,22 @@ async def deep_research_report_tool(
|
||||
dropped_count,
|
||||
)
|
||||
|
||||
if retrieve is True and not _retrieval_confirmed_by_user(conversation_messages):
|
||||
# P1:retrieve=true 只认「已询问且用户已答复」,提示词约束之外在工具层强制。
|
||||
logger.warning(
|
||||
"[deep_research_report] thread=%s rejected retrieve=true without user confirmation",
|
||||
thread_id,
|
||||
)
|
||||
return Command(
|
||||
update={
|
||||
"messages": [
|
||||
ToolMessage(
|
||||
content=_retrieve_without_confirmation_message(),
|
||||
tool_call_id=tool_call_id,
|
||||
name="deep_research_report",
|
||||
)
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
if harvested_count < _MIN_HARVESTED_MATERIALS and retrieve is None:
|
||||
# 资料不足且未征询过用户:不静默自检索,交给模型发起用户协助。
|
||||
if harvested_count < _MIN_HARVESTED_MATERIALS:
|
||||
logger.info(
|
||||
"[deep_research_report] thread=%s insufficient materials (%d < %d); asking user",
|
||||
"[deep_research_report] thread=%s thin materials (%d < %d); writing immediately",
|
||||
thread_id,
|
||||
harvested_count,
|
||||
_MIN_HARVESTED_MATERIALS,
|
||||
)
|
||||
return Command(
|
||||
update={
|
||||
"messages": [
|
||||
ToolMessage(
|
||||
content=_insufficient_materials_message(
|
||||
harvested_count,
|
||||
_MIN_HARVESTED_MATERIALS,
|
||||
topic=query,
|
||||
total_count=len(harvested),
|
||||
dropped_count=dropped_count,
|
||||
),
|
||||
tool_call_id=tool_call_id,
|
||||
name="deep_research_report",
|
||||
)
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
if harvested_count >= _MIN_HARVESTED_MATERIALS or retrieve is False:
|
||||
materials_provider: Any = StaticHarvestMaterialProvider(materials)
|
||||
material_source = "对话资料"
|
||||
else: # retrieve is True 且已核验用户同意补充检索
|
||||
materials_provider = HarvestPlusSearchMaterialProvider(
|
||||
materials,
|
||||
DeerFlowMaterialProvider(
|
||||
user_id=resolve_path_user_id(str(thread_id)),
|
||||
session_id=f"chat-{thread_id}",
|
||||
runtime_thread_id=str(thread_id),
|
||||
),
|
||||
if retrieve is True:
|
||||
logger.info(
|
||||
"[deep_research_report] thread=%s ignoring retrieve=true; "
|
||||
"writing-mode pipeline writes from conversation materials only",
|
||||
thread_id,
|
||||
)
|
||||
material_source = "对话资料+补充检索"
|
||||
materials_provider: Any = StaticHarvestMaterialProvider(materials)
|
||||
material_source = "对话资料"
|
||||
|
||||
user_id = resolve_path_user_id(str(thread_id))
|
||||
session_id = f"chat-{thread_id}"
|
||||
@@ -635,7 +541,9 @@ async def deep_research_report_tool(
|
||||
|
||||
__all__ = [
|
||||
"HarvestPlusSearchMaterialProvider",
|
||||
"REPORT_VIRTUAL_PATH",
|
||||
"StreamWriterEventSink",
|
||||
"build_writing_research_config",
|
||||
"deep_research_report_tool",
|
||||
"is_writing_mode_report_path",
|
||||
]
|
||||
Reference in new issue
Block a user