feat: 报告结构支持检索方向/来源与智能新增,并修复协助卡停轮与宿主跳转

为深度研究报告结构增加检索方向与技能来源、对话式智能新增页与详情排版;澄清中间件在 after_model 可靠结束本轮,避免弱模型出卡后继续生成;任务按钮补充 host 跳转与相关深链能力。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-22 17:46:06 +08:00
1 parent a5a9c952e8
commit 51afebb394
67 files changed
+4511 -699

No files matched your search

@@ -9,9 +9,9 @@
收到研究课题后,按以下顺序工作,并把过程自然地讲给用户听:
1. **理解课题**:先用一小段话说明你对课题的理解、打算从哪些方面收集信息(背景、现状、数据、案例、趋势、争议点等)。这段话直接输出,不要调用工具。
2. **拆分检索词**:把课题拆成若干具体的检索词,覆盖不同方面、避免重复。
2. **拆分检索词**:把课题拆成若干具体的检索词,覆盖不同方面、避免重复。**例外**:若用户消息含有 `<retrieval-directions>` 块,则**按这些方向来拆分检索词**——每个方向拆成若干具体、可检索的词(专名、时间、地点、同义/中英对照等),**不要把方向名称本身当检索词**(方向标签往往搜不到结果);不要扩展到未列出的方向。某个检索词没有结果时换更具体或更短的词再试。
3. **按顺序检索**:**一次只检索一个检索词**,检索完看结果,再决定下一个。这样用户能看清每个检索词换回了什么材料。
4. **需要时用技能**:如果某个检索词更适合知识库或某个技能,先读取技能说明(read_file 技能的 SKILL.md),再按说明调用。
4. **需要时用技能**:如果某个检索词更适合知识库或某个技能,先读取技能说明(read_file 技能的 SKILL.md),再按说明调用。**例外**:若用户消息含有 `<retrieval-skills>` 块,则必须按其中列出的技能检索:先 read_file 每个技能的 SKILL.md,再按其说明调用;不要改用未列出的技能,也不要自行改成纯 web_search(除非技能说明要求联网)。
5. **交叉验证与补漏**:发现关键信息缺来源、或多个来源说法矛盾时,补一轮针对性检索。
6. **输出收集小结**:检索完成后,输出一段「收集小结」,包含:
- 覆盖了哪些方面、共收集到多少条材料;
@@ -169,6 +169,7 @@ class FullReportRewriteRequest(BaseModel):
instruction: str = Field(..., min_length=1, max_length=4_000)
operation: Literal["rewrite", "generate"] = "rewrite"
report_outline: str | None = Field(default=None, alias="reportOutline", max_length=20_000)
structure_mode: Literal["fixed", "adaptive"] | None = Field(default=None, alias="structureMode")
style: str | None = Field(default=None, max_length=64)
model_name: str | None = Field(default=None, alias="modelName", max_length=256)
@@ -179,6 +180,7 @@ class CreateReportVariantRequest(BaseModel):
"""Create an independent report before regenerating it with a new structure."""
report_outline: str | None = Field(default=None, alias="reportOutline", max_length=20_000)
structure_mode: Literal["fixed", "adaptive"] | None = Field(default=None, alias="structureMode")
model_config = {"populate_by_name": True}
@@ -322,17 +324,34 @@ def _report_hash(report: str) -> str:
return hashlib.sha256(report.encode("utf-8")).hexdigest()
def _instruction_with_report_outline(instruction: str, report_outline: str) -> str:
def _instruction_with_report_outline(
instruction: str,
report_outline: str,
structure_mode: str | None = None,
) -> str:
"""Make a selected report template an explicit rewrite constraint."""
normalized_instruction = instruction.strip()
normalized_outline = report_outline.strip()
if not normalized_outline:
return normalized_instruction
if structure_mode == "fixed":
constraint = (
"请按以下结构输出全文:文首题名与「日期:」「类型:」「密级:」等版头必须保留并填入真实值"
"(占位符 XXX/xxx/xxxxx 不得照抄或删行;日期用当天中文日期;类型按题名判断;密级无另行规定时写「内部」)。"
"章节标题、编号与层级必须与大纲一致,不得改写、合并、省略或重排任何小节;"
"材料不足的小节保留原标题并写明资料不足,不得为凑结构编造事实。"
)
else:
constraint = (
"请按以下结构输出全文:文首题名与「日期:」「类型:」「密级:」等版头必须保留并填入真实值"
"(占位符 XXX/xxx/xxxxx 不得照抄或删行;日期用当天中文日期;类型按题名判断;密级无另行规定时写「内部」)。"
"章节按大纲展开;仅当某小节完全没有材料时才可合并或省略该小节,不得为套用结构编造事实。"
)
return "\n\n".join(
(
normalized_instruction,
"【报告结构要求】",
"请按以下 Markdown 章节结构重组全文;不适用的章节可以合并或省略,且不得为套用结构编造事实。",
constraint,
normalized_outline,
)
)
@@ -825,6 +844,8 @@ async def create_report_variant(
config_snapshot["parent_session_id"] = session_id
if outline:
config_snapshot["custom_outline"] = outline
if body.structure_mode:
config_snapshot["structure_mode"] = body.structure_mode
parent_title = str(parent.get("title") or parent.get("query") or "研究报告").strip()
variant_id = _new_id("drs")
@@ -895,7 +916,7 @@ async def start_full_report_rewrite_job(
raise HTTPException(status_code=409, detail="A completed report is required before full rewrite")
report_outline = body.report_outline.strip() if body.report_outline else ""
instruction = _instruction_with_report_outline(body.instruction, report_outline)
instruction = _instruction_with_report_outline(body.instruction, report_outline, body.structure_mode)
style = body.style.strip() if body.style else "formal_analysis"
sources = await source_store.list_by_session(
session_id,
@@ -1409,7 +1430,7 @@ async def stream_full_report_rewrite(
base_hash = _report_hash(report)
style = body.style.strip() if body.style else "formal_analysis"
report_outline = body.report_outline.strip() if body.report_outline else ""
instruction = _instruction_with_report_outline(body.instruction, report_outline)
instruction = _instruction_with_report_outline(body.instruction, report_outline, body.structure_mode)
rewrite_target = _make_rewrite_target(report, 0, len(report), "全文")
question = (
"请重写整篇研究报告。"
@@ -6,9 +6,12 @@ row; picking a card applies ``content`` to the research config's
Routes (prefix ``/api/report-structures``):
GET "" list (optional ``enabled`` / ``title`` filters)
POST "" create (title / name / content; enabled forced True)
POST "" create (title / name / content / structure_mode /
retrieval_directions / retrieval_skills;
enabled forced True)
GET "/{id}" get one
PUT "/{id}" update title / name / content
PUT "/{id}" update title / name / content / structure_mode /
retrieval_directions / retrieval_skills
PUT "/{id}/enabled" toggle 启用/停用
DELETE "/{id}" delete
@@ -27,6 +30,13 @@ from pydantic import BaseModel, Field
from app.gateway.deps import get_optional_user_from_request
from deerflow.persistence.report_structures import ReportStructureStore
from deerflow.persistence.report_structures.directions import normalize_retrieval_directions
from deerflow.persistence.report_structures.skills import normalize_retrieval_skills
from deerflow.persistence.report_structures.modes import (
DEFAULT_STRUCTURE_MODE,
StructureMode,
normalize_structure_mode,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/report-structures", tags=["report-structures"])
@@ -40,6 +50,9 @@ class ReportStructureResponse(BaseModel):
title: str
name: str
content: str
structure_mode: StructureMode = DEFAULT_STRUCTURE_MODE
retrieval_directions: list[str] = []
retrieval_skills: list[str] = []
enabled: bool = True
created_by: str | None = None
created_at: str | None = None
@@ -54,12 +67,18 @@ class ReportStructureCreateRequest(BaseModel):
title: str = Field(..., min_length=1, max_length=256)
name: str = Field(default="", max_length=256)
content: str = Field(..., min_length=1, max_length=20_000)
structure_mode: StructureMode = DEFAULT_STRUCTURE_MODE
retrieval_directions: list[str] = Field(default_factory=list)
retrieval_skills: list[str] = Field(default_factory=list)
class ReportStructureUpdateRequest(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=256)
name: str | None = Field(default=None, max_length=256)
content: str | None = Field(default=None, min_length=1, max_length=20_000)
structure_mode: StructureMode | None = None
retrieval_directions: list[str] | None = None
retrieval_skills: list[str] | None = None
class ReportStructureEnabledRequest(BaseModel):
@@ -69,6 +88,14 @@ class ReportStructureEnabledRequest(BaseModel):
# ── helpers ──────────────────────────────────────────────────────────────
def _to_response(row: dict) -> ReportStructureResponse:
data = dict(row)
data["structure_mode"] = normalize_structure_mode(data.get("structure_mode"))
data["retrieval_directions"] = normalize_retrieval_directions(data.get("retrieval_directions"))
data["retrieval_skills"] = normalize_retrieval_skills(data.get("retrieval_skills"))
return ReportStructureResponse(**data)
def _get_store(request: Request) -> ReportStructureStore:
store = getattr(request.app.state, "report_structure_store", None)
if store is None:
@@ -102,7 +129,7 @@ async def list_report_structures(
needle = title.strip().lower()
if needle:
rows = [r for r in rows if needle in str(r.get("title", "")).lower()]
return ReportStructureListResponse(structures=[ReportStructureResponse(**r) for r in rows])
return ReportStructureListResponse(structures=[_to_response(r) for r in rows])
@router.post("", response_model=ReportStructureResponse, status_code=201)
@@ -114,10 +141,13 @@ async def create_report_structure(request: Request, body: ReportStructureCreateR
"title": body.title.strip(),
"name": body.name.strip(),
"content": body.content.strip(),
"structure_mode": normalize_structure_mode(body.structure_mode),
"retrieval_directions": normalize_retrieval_directions(body.retrieval_directions),
"retrieval_skills": normalize_retrieval_skills(body.retrieval_skills),
"created_by": await _current_username(request),
}
)
return ReportStructureResponse(**row)
return _to_response(row)
@router.get("/{structure_id}", response_model=ReportStructureResponse)
@@ -126,7 +156,7 @@ async def get_report_structure(request: Request, structure_id: str) -> ReportStr
row = await store.get_structure(structure_id)
if row is None:
raise HTTPException(status_code=404, detail="报告结构不存在")
return ReportStructureResponse(**row)
return _to_response(row)
@router.put("/{structure_id}", response_model=ReportStructureResponse)
@@ -141,12 +171,18 @@ async def update_report_structure(
data["name"] = body.name.strip()
if body.content is not None:
data["content"] = body.content.strip()
if body.structure_mode is not None:
data["structure_mode"] = normalize_structure_mode(body.structure_mode)
if body.retrieval_directions is not None:
data["retrieval_directions"] = normalize_retrieval_directions(body.retrieval_directions)
if body.retrieval_skills is not None:
data["retrieval_skills"] = normalize_retrieval_skills(body.retrieval_skills)
if not data:
raise HTTPException(status_code=400, detail="没有需要更新的字段")
row = await store.update_structure(structure_id, data)
if row is None:
raise HTTPException(status_code=404, detail="报告结构不存在")
return ReportStructureResponse(**row)
return _to_response(row)
@router.put("/{structure_id}/enabled", response_model=ReportStructureResponse)
@@ -157,7 +193,7 @@ async def set_report_structure_enabled(
row = await store.set_enabled(structure_id, body.enabled)
if row is None:
raise HTTPException(status_code=404, detail="报告结构不存在")
return ReportStructureResponse(**row)
return _to_response(row)
@router.delete("/{structure_id}", status_code=204)
@@ -51,6 +51,7 @@ class TaskButton(BaseModel):
id: str = Field(..., min_length=1, max_length=128)
business: str = Field(..., min_length=1, max_length=32)
label: str = Field(default="", max_length=255)
# url=外链 / business=切换业务 / purpose=目的树弹框 / host=宿主路由(iframe postMessage)。
link_type: str = Field(default="url", max_length=16)
target: str = Field(default="", max_length=1024)
append_task_id: bool = True
@@ -20,7 +20,7 @@ import uuid
from pathlib import Path
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from fastapi import APIRouter, HTTPException, Query, Request
from langgraph.checkpoint.base import empty_checkpoint, uuid6
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
@@ -193,6 +193,18 @@ class ThreadStateResponse(BaseModel):
tasks: list[dict[str, Any]] = Field(default_factory=list, description="Interrupted task details")
class ThreadMessagesResponse(BaseModel):
"""A page of the latest thread message state.
``messages`` deliberately has no narrower response model: LangChain message
fields such as ``additional_kwargs`` and provider-specific tool-call payloads
must reach integration clients unchanged.
"""
total: int = Field(description="Total number of messages in the thread")
messages: list[Any] = Field(default_factory=list, description="Messages in chronological order")
class ThreadPatchRequest(BaseModel):
"""Request body for patching thread metadata."""
@@ -321,6 +333,20 @@ def _message_id(message: Any) -> str | None:
return str(value) if value else None
def _serialize_thread_messages(messages: Any) -> list[Any]:
"""Return checkpoint messages in the same wire form as stream/state APIs.
The latest checkpoint is the canonical conversation transcript. Reusing the
runtime serializer keeps every standard and provider-specific message field
(including ``additional_kwargs``, ``tool_calls`` and hidden context flags)
while converting LangChain message objects into JSON-safe values.
"""
if not isinstance(messages, list):
return []
serialized = serialize_channel_values({"messages": messages}).get("messages", [])
return serialized if isinstance(serialized, list) else []
def _message_content(message: Any) -> Any:
if isinstance(message, dict):
return message.get("content")
@@ -587,6 +613,18 @@ async def delete_thread_data(thread_id: str, request: Request) -> ThreadDeleteRe
except Exception:
logger.debug("Could not delete thread_meta for %s (not critical)", sanitize_log_param(thread_id))
# Conversation deposits are an auxiliary artifact index. Remove their
# records/documents as well so a whole-thread delete cannot leave a stale
# searchable copy behind. The helper is intentionally best-effort (the
# primary thread state is already deleted above).
asyncio.create_task(
delete_conversation_deposit_documents(
request.app,
thread_id=thread_id,
message_ids=None,
)
)
return response
@@ -1204,6 +1242,38 @@ async def get_thread_last_ai_message(thread_id: str, request: Request, max_chars
return {"delivered": full_len > 0, "content": text, "length": full_len}
@router.get("/{thread_id}/messages", response_model=ThreadMessagesResponse)
@require_permission("threads", "read", owner_check=True)
async def get_thread_messages(
thread_id: str,
request: Request,
limit: int = Query(default=200, ge=1, le=1000, description="Maximum messages to return"),
offset: int = Query(default=0, ge=0, description="Number of leading messages to skip"),
) -> ThreadMessagesResponse:
"""Return a chronological, paginated view of a thread's message transcript.
This reads the latest checkpoint rather than a derived display transcript, so
hidden context messages and all original message fields are retained. The
response serialization is shared with ``GET /state`` and streaming events.
"""
checkpointer = get_checkpointer(request)
config = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
try:
checkpoint_tuple = await checkpointer.aget_tuple(config)
except Exception:
logger.exception("Failed to get messages for thread %s", sanitize_log_param(thread_id))
raise HTTPException(status_code=500, detail="Failed to get thread messages")
if checkpoint_tuple is None:
raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found")
checkpoint = getattr(checkpoint_tuple, "checkpoint", {}) or {}
channel_values = checkpoint.get("channel_values", {}) or {}
messages = _serialize_thread_messages(channel_values.get("messages"))
total = len(messages)
return ThreadMessagesResponse(total=total, messages=messages[offset : offset + limit])
@router.delete("/{thread_id}/messages")
@require_permission("threads", "write", owner_check=True, require_existing=True)
async def clear_thread_messages(thread_id: str, request: Request) -> dict[str, Any]:
@@ -1332,6 +1402,12 @@ async def delete_thread_message(thread_id: str, message_id: str, request: Reques
channel_values["messages"] = filtered
checkpoint["channel_values"] = channel_values
checkpoint["id"] = str(uuid6(clock_seq=-2))
checkpoint["ts"] = now_iso()
versions = dict(checkpoint.get("channel_versions", {}))
new_ver = checkpointer.get_next_version(versions.get("messages"), None)
versions["messages"] = new_ver
checkpoint["channel_versions"] = versions
metadata["updated_at"] = now_iso()
write_config: dict[str, Any] = {
@@ -1341,7 +1417,7 @@ async def delete_thread_message(thread_id: str, message_id: str, request: Reques
}
}
try:
await checkpointer.aput(write_config, checkpoint, metadata, {})
await checkpointer.aput(write_config, checkpoint, metadata, {"messages": new_ver})
except Exception:
logger.exception(
"Failed to delete message %s from thread %s",
@@ -183,7 +183,7 @@ def _instruction_with_report_outline(instruction: str, report_outline: str | Non
(
normalized_instruction,
"【报告结构要求】",
"请按以下 Markdown 章节结构重组全文;不适用的章节可以合并或省略,且不得为套用结构编造事实。",
"请按以下结构输出全文:文首题名与「日期:」「类型:」「密级:」等版头必须保留并填入真实值(占位符 XXX/xxx/xxxxx 不得照抄或删行;日期用当天中文日期;类型按题名判断;密级无另行规定时写「内部」)。章节按大纲展开;仅当某小节完全没有材料时才可合并或省略该小节,不得为套用结构编造事实。",
normalized_outline,
)
)