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
+68
-20
@@ -43,6 +43,41 @@ if TYPE_CHECKING:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _parent_isolated_run_config(run_name: str) -> dict[str, Any]:
|
||||
"""Keep LangGraph runtime, drop only inherited LLM streaming callbacks.
|
||||
|
||||
``StreamWriter`` reads ``get_config()[configurable]`` at emit time. Replacing
|
||||
the child config with a blank dict makes ``report_delta`` / ``report_thinking``
|
||||
raise and get swallowed, so the sandbox only appears after the file lands.
|
||||
"""
|
||||
parent: dict[str, Any] = {}
|
||||
try:
|
||||
from langchain_core.runnables.config import var_child_runnable_config
|
||||
|
||||
current = var_child_runnable_config.get()
|
||||
if isinstance(current, dict):
|
||||
parent = dict(current)
|
||||
except Exception: # noqa: BLE001 — isolation must never fail the completion
|
||||
parent = {}
|
||||
tags = [tag for tag in (parent.get("tags") or []) if tag != "nostream"]
|
||||
tags.append("nostream")
|
||||
parent["callbacks"] = []
|
||||
parent["tags"] = tags
|
||||
parent["run_name"] = run_name
|
||||
return parent
|
||||
|
||||
|
||||
def _clear_inherited_runnable_config(isolated: dict[str, Any]) -> Callable[[], None]:
|
||||
"""Install the isolated config for the duration of ``astream``."""
|
||||
try:
|
||||
from langchain_core.runnables.config import var_child_runnable_config
|
||||
except ImportError:
|
||||
return lambda: None
|
||||
|
||||
token = var_child_runnable_config.set(isolated)
|
||||
return lambda: var_child_runnable_config.reset(token)
|
||||
|
||||
|
||||
# ── message conversion ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -347,26 +382,39 @@ class DeerFlowCompletionBackend:
|
||||
text_parts: list[str] = []
|
||||
usage: dict[str, Any] = {}
|
||||
inline_think_filter = InlineThinkTagFilter()
|
||||
async for chunk in model.astream(to_langchain_messages(messages), **kwargs):
|
||||
if self._cancel is not None:
|
||||
self._cancel.raise_if_cancelled()
|
||||
reasoning = _reasoning_delta(chunk)
|
||||
if reasoning and on_reasoning is not None:
|
||||
await on_reasoning(reasoning)
|
||||
# A few OpenAI-compatible models put their reasoning in the
|
||||
# ordinary content channel instead of ``reasoning_content``.
|
||||
# Split it from Markdown even when tags span tokens: callers may
|
||||
# display a live thought trace, but it never joins ``text``.
|
||||
delta, inline_reasoning = inline_think_filter.push_parts(_content_to_text(chunk))
|
||||
if inline_reasoning and on_reasoning is not None:
|
||||
await on_reasoning(inline_reasoning)
|
||||
if delta:
|
||||
text_parts.append(delta)
|
||||
if on_delta is not None:
|
||||
await on_delta(delta)
|
||||
chunk_usage = _extract_usage(chunk)
|
||||
if any(chunk_usage.values()):
|
||||
usage = chunk_usage
|
||||
# Isolate from the parent LangGraph run: inherited callbacks would
|
||||
# replay every report token into the chat ``messages`` stream, so the
|
||||
# left-hand bubble and the sandbox would write the same prose at once.
|
||||
# Custom ``report_delta`` events remain the only live preview channel.
|
||||
isolated_config = _parent_isolated_run_config(f"deep_research:{operation}")
|
||||
reset_parent_config = _clear_inherited_runnable_config(isolated_config)
|
||||
try:
|
||||
async for chunk in model.astream(
|
||||
to_langchain_messages(messages),
|
||||
config=isolated_config,
|
||||
**kwargs,
|
||||
):
|
||||
if self._cancel is not None:
|
||||
self._cancel.raise_if_cancelled()
|
||||
reasoning = _reasoning_delta(chunk)
|
||||
if reasoning and on_reasoning is not None:
|
||||
await on_reasoning(reasoning)
|
||||
# A few OpenAI-compatible models put their reasoning in the
|
||||
# ordinary content channel instead of ``reasoning_content``.
|
||||
# Split it from Markdown even when tags span tokens: callers may
|
||||
# display a live thought trace, but it never joins ``text``.
|
||||
delta, inline_reasoning = inline_think_filter.push_parts(_content_to_text(chunk))
|
||||
if inline_reasoning and on_reasoning is not None:
|
||||
await on_reasoning(inline_reasoning)
|
||||
if delta:
|
||||
text_parts.append(delta)
|
||||
if on_delta is not None:
|
||||
await on_delta(delta)
|
||||
chunk_usage = _extract_usage(chunk)
|
||||
if any(chunk_usage.values()):
|
||||
usage = chunk_usage
|
||||
finally:
|
||||
reset_parent_config()
|
||||
|
||||
tail, inline_reasoning_tail = inline_think_filter.finish_parts()
|
||||
if inline_reasoning_tail and on_reasoning is not None:
|
||||
|
||||
+78
-22
@@ -198,35 +198,63 @@ class BasicRunner:
|
||||
cancellation.raise_if_cancelled()
|
||||
|
||||
if not all_materials:
|
||||
knowledge_fill = _allows_knowledge_fill(request.config.report_instruction)
|
||||
await events.emit(
|
||||
"warning",
|
||||
phase="curating",
|
||||
payload={"code": "no_materials", "message": "未收集到任何研究材料", "recoverable": False},
|
||||
payload={
|
||||
"code": "no_materials",
|
||||
"message": (
|
||||
"未收集到外部研究材料,改用领域知识撰写"
|
||||
if knowledge_fill
|
||||
else "未收集到任何研究材料"
|
||||
),
|
||||
"recoverable": knowledge_fill,
|
||||
},
|
||||
)
|
||||
report_md = f"# {request.query}\n\n未能收集到与研究课题「{request.query}」相关的材料,无法生成报告。"
|
||||
await adapters.artifacts.write_text("report.md", report_md)
|
||||
await events.emit("report_completed", phase="writing", payload={"reportVersion": 1, "sourceCount": 0})
|
||||
return DeepResearchResult(report_markdown=report_md, source_ids=[], plan=plan)
|
||||
if not knowledge_fill:
|
||||
report_md = (
|
||||
f"# {request.query}\n\n"
|
||||
f"未能收集到与研究课题「{request.query}」相关的材料,无法生成报告。"
|
||||
)
|
||||
await adapters.artifacts.write_text("report.md", report_md)
|
||||
await events.emit(
|
||||
"report_completed",
|
||||
phase="writing",
|
||||
payload={"reportVersion": 1, "sourceCount": 0},
|
||||
)
|
||||
return DeepResearchResult(report_markdown=report_md, source_ids=[], plan=plan)
|
||||
deduped: list[ResearchMaterial] = []
|
||||
selected_ids: list[str] = []
|
||||
context_list: list[dict[str, Any]] = []
|
||||
context_text = _KNOWLEDGE_FILL_EMPTY_CONTEXT
|
||||
else:
|
||||
from deerflow.agents.deep_research.adapters.material import dedupe_materials
|
||||
|
||||
from deerflow.agents.deep_research.adapters.material import dedupe_materials
|
||||
deduped = dedupe_materials(all_materials)
|
||||
context_comp.set_materials(deduped)
|
||||
|
||||
deduped = dedupe_materials(all_materials)
|
||||
context_comp.set_materials(deduped)
|
||||
selected_ids = [m.id for m in deduped]
|
||||
await events.emit(
|
||||
"sources_curated",
|
||||
phase="curating",
|
||||
payload={"selectedIds": selected_ids, "removedIds": [], "reason": "deduped"},
|
||||
)
|
||||
|
||||
selected_ids = [m.id for m in deduped]
|
||||
await events.emit(
|
||||
"sources_curated",
|
||||
phase="curating",
|
||||
payload={"selectedIds": selected_ids, "removedIds": [], "reason": "deduped"},
|
||||
)
|
||||
# ── 4. compress context ────────────────────────────────────────
|
||||
await events.emit(
|
||||
"phase_changed",
|
||||
phase="compressing",
|
||||
payload={"from": "curating", "to": "compressing"},
|
||||
)
|
||||
if cancellation:
|
||||
cancellation.raise_if_cancelled()
|
||||
|
||||
# ── 4. compress context ────────────────────────────────────────
|
||||
await events.emit("phase_changed", phase="compressing", payload={"from": "curating", "to": "compressing"})
|
||||
if cancellation:
|
||||
cancellation.raise_if_cancelled()
|
||||
|
||||
context_list = await context_comp.async_get_context(request.query, max_results=min(len(deduped), config.max_search_results_per_query * 2))
|
||||
context_text = _format_context(context_list, deduped)
|
||||
context_list = await context_comp.async_get_context(
|
||||
request.query,
|
||||
max_results=min(len(deduped), config.max_search_results_per_query * 2),
|
||||
)
|
||||
context_text = _format_context(context_list, deduped)
|
||||
|
||||
# ── 5. writing: generate report ────────────────────────────────
|
||||
await events.emit("phase_changed", phase="writing", payload={"from": "compressing", "to": "writing"})
|
||||
@@ -403,6 +431,13 @@ class BasicRunner:
|
||||
)
|
||||
outline_block = _report_outline_instruction(outline)
|
||||
requirements_block = _report_requirements_instruction(request.config.report_instruction)
|
||||
if _allows_knowledge_fill(request.config.report_instruction):
|
||||
system_extra = (
|
||||
"用户已要求在材料不足时用模型自身的公开领域知识写成完整报告。"
|
||||
"禁止把「材料不足/未提供文献」写成章节主线;参考文献可标注为基于公开领域知识。"
|
||||
)
|
||||
else:
|
||||
system_extra = ""
|
||||
if request.config.structure_mode == "fixed":
|
||||
# Recency bias: keep the skeleton immediately before "请撰写报告".
|
||||
context_block = (
|
||||
@@ -427,6 +462,8 @@ class BasicRunner:
|
||||
if filled_preamble:
|
||||
await emitter.add(filled_preamble + "\n\n")
|
||||
system = _SYSTEM
|
||||
if system_extra:
|
||||
system += system_extra
|
||||
if request.config.structure_mode == "fixed" and (outline or "").strip():
|
||||
system += "撰写时必须原样沿用用户大纲中的章节标题与层级,不得改写成通用报告套式。"
|
||||
result = await llm.stream_complete(
|
||||
@@ -624,12 +661,31 @@ def ensure_markdown_standalone_lines(text: str) -> str:
|
||||
return "\n".join(output)
|
||||
|
||||
|
||||
_KNOWLEDGE_FILL_EMPTY_CONTEXT = (
|
||||
"(本次未收集到外部研究材料。请基于模型自身的公开领域知识撰写完整、有实质内容的研究报告,"
|
||||
"含架构说明;用户要求流程图时输出 Mermaid。"
|
||||
"禁止只写「无法生成报告」或把「材料不足」写成全文。)"
|
||||
)
|
||||
_KNOWLEDGE_FILL_MARKERS = ("必须基于模型自身的领域知识", "基于模型自身的领域知识")
|
||||
|
||||
|
||||
def _allows_knowledge_fill(report_instruction: str | None) -> bool:
|
||||
text = report_instruction or ""
|
||||
return any(marker in text for marker in _KNOWLEDGE_FILL_MARKERS)
|
||||
|
||||
|
||||
def _report_requirements_instruction(report_instruction: str | None) -> str:
|
||||
"""Render confirmed generation requirements as bounded, untrusted content."""
|
||||
if not report_instruction:
|
||||
return "User generation requirements: none provided."
|
||||
evidence_note = (
|
||||
"these requirements override the default 'do not go beyond materials' rule "
|
||||
"when they ask to write from model knowledge"
|
||||
if _allows_knowledge_fill(report_instruction)
|
||||
else "content only; system and evidence rules still win"
|
||||
)
|
||||
return (
|
||||
"User generation requirements (content only; system and evidence rules still win):\n"
|
||||
f"User generation requirements ({evidence_note}):\n"
|
||||
f"<user-report-requirements>\n{report_instruction}\n</user-report-requirements>"
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user