增强文档改写配图与深度研究流式稳定性,并完善 8BF/会商工作区。
全文改写支持可选配图与思考过程展示,深度研究接入 DashScope 原生出图并剥离内联 think 标签;8BF 会商补齐第一步工作区与任务卡回退,同时限制热重载扫描范围。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
819e537aa3
commit
15a46b903a
48 files changed
+3724
-616
No files matched your search
@@ -1269,8 +1269,13 @@ the terminal `lastJobId` in `usage_snapshot` so a refreshed conversation page
|
||||
can replay its trace from the event log. Detailed mode uses stable targets (`introduction`,
|
||||
`section:N`, `conclusion`) because section writers are concurrent;
|
||||
multi-agent revisions must emit `report_reset` before their next report
|
||||
version. Do not emit raw model reasoning or one persisted event per provider
|
||||
token. The Vite page owns Word export through
|
||||
version. Do not persist raw model reasoning or one persisted event per provider
|
||||
token. Models that expose thinking inside ordinary `<think>...</think>` text
|
||||
must be split statefully before a report delta, checkpoint, or Markdown
|
||||
projection is created; an optional live-only `report_thinking` frame can drive
|
||||
the message-list thought trace, while the sandbox receives answer Markdown
|
||||
only. The Vite
|
||||
page owns Word export through
|
||||
`frontend-web/src/core/scheduled-tasks/markdown-docx.ts`; do not add Python
|
||||
document-conversion dependencies merely to export text.
|
||||
All non-streaming Deep Research control-plane calls (`complete()` for query /
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
install:
|
||||
uv sync
|
||||
|
||||
dev:
|
||||
PYTHONPATH=. uv run uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001 --reload
|
||||
dev:
|
||||
PYTHONPATH=. uv run uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001 --reload --reload-exclude ".deer-flow/*" --reload-exclude ".runtime/*"
|
||||
|
||||
gateway:
|
||||
PYTHONPATH=. uv run uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001
|
||||
|
||||
@@ -180,6 +180,11 @@ the right-side `report.md` sandbox can write smoothly, while bounded,
|
||||
persisted `report_chunk` events remain reconnect checkpoints. The durable log
|
||||
is still authoritative: a browser reconnect, slow consumer, or another worker
|
||||
falls back to `?after=<seq>` replay rather than starting a second model call.
|
||||
Reasoning exposed by providers either through structured reasoning fields or
|
||||
inline `<think>...</think>` text is separated from report deltas, checkpoints,
|
||||
and the persisted Markdown projection. It may be forwarded as an ephemeral
|
||||
live `report_thinking` frame for the message-list thought trace, but is never
|
||||
persisted or written to the sandbox; only answer Markdown reaches the sandbox.
|
||||
The short non-streaming control-plane calls used to plan queries, sections, and
|
||||
reviews are independently capped at 45 seconds (maximum 120 seconds). If query
|
||||
or section planning times out, the runner emits a visible recoverable warning
|
||||
@@ -231,12 +236,16 @@ only applies to sessions with a `running` or `awaiting_input` durable job.
|
||||
DeerFlow's stock configuration includes image recognition but no image-generation
|
||||
provider. Deep Research therefore keeps illustrations disabled until an operator
|
||||
fills `config.yaml -> deep_research.image_generation` with an
|
||||
OpenAI-compatible image endpoint, API key, and model. When configured, the
|
||||
capabilities endpoint enables the page's “生成报告配图” switch. A selected job
|
||||
requests at most four base64 image results, writes them as protected
|
||||
`research-image-*.png|jpg|webp` artifacts, injects `deep-research://` links into
|
||||
the Markdown report, and emits image SSE events. A failed/unconfigured image
|
||||
provider only emits a recoverable warning; the text report still completes.
|
||||
image endpoint, API key, and model. `provider: openai_compatible` uses the
|
||||
standard `/images/generations` protocol and requires `b64_json`; `provider:
|
||||
dashscope_native` supports Qwen Image 3.0 and Wan 2.7 on DashScope / Token Plan
|
||||
with the native multimodal-generation protocol. Native provider image URLs are
|
||||
downloaded immediately, so both providers produce protected local artifacts.
|
||||
When configured, the capabilities endpoint enables the page's “生成报告配图” switch.
|
||||
A selected job writes at most four `research-image-*.png|jpg|webp` artifacts,
|
||||
injects `deep-research://` links into the Markdown report, and emits image SSE
|
||||
events. A failed/unconfigured image provider only emits a recoverable warning;
|
||||
the text report still completes.
|
||||
|
||||
Completed reports also expose `GET /api/deep-research/sessions/{id}/messages`
|
||||
and `POST /api/deep-research/sessions/{id}/chat`. Follow-up answers are grounded
|
||||
|
||||
@@ -44,6 +44,7 @@ from deerflow.agents.deep_research.types import (
|
||||
DeepResearchResult,
|
||||
)
|
||||
from deerflow.runtime.user_context import reset_current_user, set_current_user
|
||||
from deerflow.utils.stream_text import InlineThinkTagFilter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from deerflow.config.app_config import AppConfig
|
||||
@@ -157,9 +158,7 @@ class RecordingEventSink:
|
||||
elif type == "sources_curated" and self._source_store is not None:
|
||||
for sid in (payload or {}).get("selectedIds", []):
|
||||
try:
|
||||
await self._source_store.set_selected(
|
||||
sid, selected=True, reason="curated", user_id=self._user_id
|
||||
)
|
||||
await self._source_store.set_selected(sid, selected=True, reason="curated", user_id=self._user_id)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
@@ -265,14 +264,8 @@ class DeepResearchJobExecutor:
|
||||
cancel_token = CancellationToken()
|
||||
|
||||
main_task = asyncio.current_task()
|
||||
heartbeat = (
|
||||
asyncio.create_task(self._heartbeat(job_id, lease_owner, main_task))
|
||||
if lease_owner
|
||||
else None
|
||||
)
|
||||
watcher = asyncio.create_task(
|
||||
self._watch_cancellation(job_id, main_task, lease_owner, cancel_token)
|
||||
)
|
||||
heartbeat = asyncio.create_task(self._heartbeat(job_id, lease_owner, main_task)) if lease_owner else None
|
||||
watcher = asyncio.create_task(self._watch_cancellation(job_id, main_task, lease_owner, cancel_token))
|
||||
|
||||
try:
|
||||
# Normal sandbox Markdown rewrites share the same durable lease,
|
||||
@@ -390,9 +383,7 @@ class DeepResearchJobExecutor:
|
||||
session_for_model.setdefault("config_snapshot", snapshot.get("config") or {})
|
||||
|
||||
if not report.strip() or not instruction:
|
||||
await self._mark_document_rewrite_failed(
|
||||
job_id, session_id, lease_owner, "INVALID_SNAPSHOT", "改写任务快照不完整,无法继续执行。"
|
||||
)
|
||||
await self._mark_document_rewrite_failed(job_id, session_id, lease_owner, "INVALID_SNAPSHOT", "改写任务快照不完整,无法继续执行。")
|
||||
return
|
||||
|
||||
events = PersistingEventSink(
|
||||
@@ -421,9 +412,7 @@ class DeepResearchJobExecutor:
|
||||
phase="planning",
|
||||
payload={"type": "requirements_started"},
|
||||
)
|
||||
await self._job_store.update_progress(
|
||||
job_id, lease_owner=lease_owner, phase="planning", progress=20
|
||||
)
|
||||
await self._job_store.update_progress(job_id, lease_owner=lease_owner, phase="planning", progress=20)
|
||||
requirement_parts: list[str] = []
|
||||
# Persist the first fragment too: the HTTP client opens its SSE stream
|
||||
# just after queuing the job, so this closes the tiny subscribe race
|
||||
@@ -449,6 +438,14 @@ class DeepResearchJobExecutor:
|
||||
)
|
||||
last_requirements_checkpoint = time.monotonic()
|
||||
|
||||
async def on_requirement_thinking(delta: str) -> None:
|
||||
if delta:
|
||||
await events.publish_live(
|
||||
"document_rewrite",
|
||||
phase="planning",
|
||||
payload={"type": "thinking", "chunk": delta},
|
||||
)
|
||||
|
||||
requirements_fallback = False
|
||||
try:
|
||||
requirements_plan = await stream_full_report_rewrite_requirements(
|
||||
@@ -458,6 +455,7 @@ class DeepResearchJobExecutor:
|
||||
style=style_instruction,
|
||||
model_name=model_name,
|
||||
on_delta=on_requirement_delta,
|
||||
on_reasoning=on_requirement_thinking,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
@@ -492,9 +490,7 @@ class DeepResearchJobExecutor:
|
||||
"plan": requirements_plan,
|
||||
},
|
||||
)
|
||||
await self._job_store.update_progress(
|
||||
job_id, lease_owner=lease_owner, phase="writing", progress=50
|
||||
)
|
||||
await self._job_store.update_progress(job_id, lease_owner=lease_owner, phase="writing", progress=50)
|
||||
|
||||
draft_parts: list[str] = []
|
||||
last_checkpoint = time.monotonic()
|
||||
@@ -529,6 +525,14 @@ class DeepResearchJobExecutor:
|
||||
)
|
||||
last_checkpoint = time.monotonic()
|
||||
|
||||
async def on_thinking(delta: str) -> None:
|
||||
if delta:
|
||||
await events.publish_live(
|
||||
"document_rewrite",
|
||||
phase="writing",
|
||||
payload={"type": "thinking", "chunk": delta},
|
||||
)
|
||||
|
||||
try:
|
||||
rewritten, citation_ids, _usage = await stream_full_report_rewrite(
|
||||
session=session_for_model,
|
||||
@@ -538,6 +542,7 @@ class DeepResearchJobExecutor:
|
||||
style=style,
|
||||
model_name=model_name,
|
||||
on_delta=on_delta,
|
||||
on_reasoning=on_thinking,
|
||||
requirements_plan=requirements_plan,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
@@ -560,9 +565,7 @@ class DeepResearchJobExecutor:
|
||||
await events.emit("document_rewrite", phase="reviewing", payload={"type": "validation_started"})
|
||||
validation_error = validate_markdown(rewritten)
|
||||
if validation_error:
|
||||
await self._mark_document_rewrite_failed(
|
||||
job_id, session_id, lease_owner, "VALIDATION_FAILED", validation_error, events=events, stage="validation"
|
||||
)
|
||||
await self._mark_document_rewrite_failed(job_id, session_id, lease_owner, "VALIDATION_FAILED", validation_error, events=events, stage="validation")
|
||||
return
|
||||
|
||||
before_headings = heading_count(report)
|
||||
@@ -582,13 +585,9 @@ class DeepResearchJobExecutor:
|
||||
validation_warnings=warnings,
|
||||
)
|
||||
summary["citationCount"] = len(citation_ids)
|
||||
await events.emit(
|
||||
"document_rewrite", phase="reviewing", payload={"type": "comparison_ready", **summary}
|
||||
)
|
||||
await events.emit("document_rewrite", phase="reviewing", payload={"type": "comparison_ready", **summary})
|
||||
await events.emit("document_rewrite", phase="exporting", payload={"type": "commit_started"})
|
||||
await self._job_store.update_progress(
|
||||
job_id, lease_owner=lease_owner, phase="exporting", progress=90
|
||||
)
|
||||
await self._job_store.update_progress(job_id, lease_owner=lease_owner, phase="exporting", progress=90)
|
||||
|
||||
committed_hash = __import__("hashlib").sha256(rewritten.encode("utf-8")).hexdigest()
|
||||
updated = await self._session_store.replace_report_if_unchanged(
|
||||
@@ -643,9 +642,7 @@ class DeepResearchJobExecutor:
|
||||
expected_report=rewritten,
|
||||
report_markdown=report,
|
||||
)
|
||||
message = "保存改写版本失败,报告已恢复原文。" if rolled_back is not None else (
|
||||
"保存改写版本失败,且报告随后被修改,未再覆盖。"
|
||||
)
|
||||
message = "保存改写版本失败,报告已恢复原文。" if rolled_back is not None else ("保存改写版本失败,且报告随后被修改,未再覆盖。")
|
||||
await self._mark_document_rewrite_failed(
|
||||
job_id,
|
||||
session_id,
|
||||
@@ -749,6 +746,11 @@ class DeepResearchJobExecutor:
|
||||
instruction = str(snapshot.get("instruction") or "").strip()
|
||||
style = str(snapshot.get("style") or "professional").strip()
|
||||
model_name = str(snapshot.get("model_name") or "").strip() or None
|
||||
generate_images = bool(snapshot.get("generate_images"))
|
||||
try:
|
||||
max_generated_images = min(max(int(snapshot.get("max_generated_images") or 2), 1), 4)
|
||||
except (TypeError, ValueError):
|
||||
max_generated_images = 2
|
||||
|
||||
async def fail(code: str, message: str, *, stage: str = "generation") -> None:
|
||||
await events.emit(
|
||||
@@ -808,13 +810,20 @@ class DeepResearchJobExecutor:
|
||||
)
|
||||
return
|
||||
|
||||
rewrite_source = original
|
||||
if generate_images:
|
||||
# Do not ask the writer to preserve a previous run's managed image
|
||||
# blocks. A new illustration pass will create a fresh, local set;
|
||||
# user-authored image links remain untouched.
|
||||
from app.gateway.document_rewrite_illustrations import strip_managed_document_illustrations
|
||||
|
||||
rewrite_source = strip_managed_document_illustrations(original)
|
||||
|
||||
style_instruction = DOCUMENT_STYLE_INSTRUCTIONS.get(
|
||||
style,
|
||||
DOCUMENT_STYLE_INSTRUCTIONS["professional"],
|
||||
)
|
||||
resolved_name = model_name or (
|
||||
self._app_config.models[0].name if self._app_config.models else None
|
||||
)
|
||||
resolved_name = model_name or (self._app_config.models[0].name if self._app_config.models else None)
|
||||
model_cfg = self._app_config.get_model_config(resolved_name) if resolved_name else None
|
||||
thinking_enabled = bool(model_cfg and getattr(model_cfg, "supports_thinking", False))
|
||||
try:
|
||||
@@ -849,12 +858,21 @@ class DeepResearchJobExecutor:
|
||||
last_requirements_checkpoint = 0.0
|
||||
requirements_fallback = False
|
||||
try:
|
||||
async def on_requirement_thinking(delta: str) -> None:
|
||||
if delta:
|
||||
await events.publish_live(
|
||||
"document_rewrite",
|
||||
phase="planning",
|
||||
payload={"type": "thinking", "chunk": delta},
|
||||
)
|
||||
|
||||
async for delta in astream_rewrite_requirements(
|
||||
model,
|
||||
file_name=actual_path.name,
|
||||
instruction=instruction,
|
||||
style_instruction=style_instruction,
|
||||
original=original,
|
||||
original=rewrite_source,
|
||||
on_thinking=on_requirement_thinking,
|
||||
):
|
||||
requirement_parts.append(delta)
|
||||
requirement_draft = "".join(requirement_parts)
|
||||
@@ -909,7 +927,7 @@ class DeepResearchJobExecutor:
|
||||
f"{requirements_plan}\n"
|
||||
"【已确认的改写执行计划结束】\n\n"
|
||||
"【原始 Markdown 开始】\n"
|
||||
f"{original}\n"
|
||||
f"{rewrite_source}\n"
|
||||
"【原始 Markdown 结束】"
|
||||
)
|
||||
),
|
||||
@@ -934,6 +952,7 @@ class DeepResearchJobExecutor:
|
||||
|
||||
draft_parts: list[str] = []
|
||||
last_checkpoint = time.monotonic()
|
||||
inline_think_filter = InlineThinkTagFilter()
|
||||
try:
|
||||
async for chunk in model.astream(messages, config={"run_name": "document_rewrite"}):
|
||||
thinking_delta, text_delta = extract_stream_chunk_parts(chunk)
|
||||
@@ -943,6 +962,13 @@ class DeepResearchJobExecutor:
|
||||
phase="writing",
|
||||
payload={"type": "thinking", "chunk": thinking_delta},
|
||||
)
|
||||
text_delta, inline_thinking = inline_think_filter.push_parts(text_delta)
|
||||
if inline_thinking:
|
||||
await events.publish_live(
|
||||
"document_rewrite",
|
||||
phase="writing",
|
||||
payload={"type": "thinking", "chunk": inline_thinking},
|
||||
)
|
||||
if not text_delta:
|
||||
continue
|
||||
draft_parts.append(text_delta)
|
||||
@@ -974,6 +1000,26 @@ class DeepResearchJobExecutor:
|
||||
await fail(type(exc).__name__, str(exc))
|
||||
return
|
||||
|
||||
tail, inline_thinking_tail = inline_think_filter.finish_parts()
|
||||
if inline_thinking_tail:
|
||||
await events.publish_live(
|
||||
"document_rewrite",
|
||||
phase="writing",
|
||||
payload={"type": "thinking", "chunk": inline_thinking_tail},
|
||||
)
|
||||
if tail:
|
||||
draft_parts.append(tail)
|
||||
draft = "".join(draft_parts)
|
||||
await events.publish_live(
|
||||
"document_rewrite",
|
||||
phase="writing",
|
||||
payload={
|
||||
"type": "rewrite_delta",
|
||||
"delta": tail,
|
||||
"charCount": visible_document_char_count(draft),
|
||||
},
|
||||
)
|
||||
|
||||
rewritten = "".join(draft_parts).strip()
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
@@ -984,6 +1030,148 @@ class DeepResearchJobExecutor:
|
||||
"charCount": visible_document_char_count(rewritten),
|
||||
},
|
||||
)
|
||||
|
||||
# Reject an invalid text draft before spending image-generation quota.
|
||||
validation_error = validate_markdown_document(rewritten)
|
||||
if validation_error:
|
||||
await fail("VALIDATION_FAILED", validation_error, stage="validation")
|
||||
return
|
||||
|
||||
generated_illustrations = []
|
||||
persisted_illustrations = []
|
||||
illustration_warnings: list[str] = []
|
||||
if generate_images:
|
||||
from app.gateway.document_rewrite_illustrations import generate_document_illustrations
|
||||
from deerflow.agents.deep_research.adapters.image import ImageGenerationSettings, build_image_provider
|
||||
|
||||
await self._job_store.update_progress(
|
||||
job_id,
|
||||
lease_owner=lease_owner,
|
||||
phase="illustrating",
|
||||
progress=88,
|
||||
)
|
||||
# Make the phase visible even when the configured provider is
|
||||
# unavailable or every provider request fails before a result.
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
phase="illustrating",
|
||||
payload={
|
||||
"type": "illustration_started",
|
||||
"section": "准备生成文档配图",
|
||||
"position": 0,
|
||||
"total": max_generated_images,
|
||||
},
|
||||
)
|
||||
image_settings = ImageGenerationSettings.from_app_config()
|
||||
if not image_settings.is_configured:
|
||||
illustration_warnings.append("当前部署未配置图片生成服务,已跳过文档配图。")
|
||||
else:
|
||||
provider = build_image_provider()
|
||||
|
||||
async def on_image_started(section: str, position: int, total: int) -> None:
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
phase="illustrating",
|
||||
payload={
|
||||
"type": "illustration_started",
|
||||
"section": section,
|
||||
"position": position,
|
||||
"total": total,
|
||||
},
|
||||
)
|
||||
|
||||
async def on_image_generated(image, total: int, generated_count: int) -> None:
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
phase="illustrating",
|
||||
payload={
|
||||
"type": "illustration_generated",
|
||||
"section": image.section,
|
||||
"position": image.position,
|
||||
"total": total,
|
||||
"generatedCount": generated_count,
|
||||
},
|
||||
)
|
||||
|
||||
generated_illustrations, generated_warnings = await generate_document_illustrations(
|
||||
provider,
|
||||
markdown=rewritten,
|
||||
document_name=actual_path.name,
|
||||
maximum=max_generated_images,
|
||||
on_started=on_image_started,
|
||||
on_generated=on_image_generated,
|
||||
)
|
||||
illustration_warnings.extend(generated_warnings)
|
||||
|
||||
# Do not save images if a manual edit has invalidated the frozen
|
||||
# source version while image calls were in flight.
|
||||
current_before_images = await asyncio.to_thread(actual_path.read_text, encoding="utf-8")
|
||||
if content_hash(current_before_images) != base_hash:
|
||||
message = "文件在生成配图期间已被修改,已保留原文件。"
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
phase="done",
|
||||
payload={"type": "conflict", "message": message},
|
||||
)
|
||||
await self._job_store.update_progress(
|
||||
job_id,
|
||||
lease_owner=lease_owner,
|
||||
status="completed",
|
||||
phase="done",
|
||||
progress=100,
|
||||
result_snapshot={
|
||||
"kind": "artifact_document_rewrite",
|
||||
"status": "conflict",
|
||||
"content": rewritten,
|
||||
"originalContent": original,
|
||||
"requirementsPlan": requirements_plan,
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
if generated_illustrations:
|
||||
from app.gateway.document_rewrite_illustrations import (
|
||||
insert_document_illustrations,
|
||||
persist_document_illustrations,
|
||||
)
|
||||
|
||||
try:
|
||||
persisted_illustrations, persistence_warnings = await asyncio.to_thread(
|
||||
persist_document_illustrations,
|
||||
generated_illustrations,
|
||||
markdown_path=actual_path,
|
||||
virtual_markdown_path=virtual_path,
|
||||
job_id=job_id,
|
||||
)
|
||||
illustration_warnings.extend(persistence_warnings)
|
||||
rewritten = insert_document_illustrations(rewritten, persisted_illustrations)
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
phase="illustrating",
|
||||
payload={
|
||||
"type": "rewrite_checkpoint",
|
||||
"content": rewritten,
|
||||
"charCount": visible_document_char_count(rewritten),
|
||||
},
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("could not save artifact rewrite illustrations for %s", job_id)
|
||||
illustration_warnings.append("配图保存失败,已完成文字改写但未插入图片。")
|
||||
persisted_illustrations = []
|
||||
else:
|
||||
persisted_illustrations = []
|
||||
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
phase="illustrating",
|
||||
payload={
|
||||
"type": "illustration_completed",
|
||||
"generatedCount": len(persisted_illustrations),
|
||||
"requestedCount": max_generated_images,
|
||||
"warnings": illustration_warnings,
|
||||
},
|
||||
)
|
||||
|
||||
await events.emit("document_rewrite", phase="reviewing", payload={"type": "validation_started"})
|
||||
validation_error = validate_markdown_document(rewritten)
|
||||
if validation_error:
|
||||
@@ -993,6 +1181,7 @@ class DeepResearchJobExecutor:
|
||||
heading_count_before = sum(1 for line in original.splitlines() if line.lstrip().startswith("#"))
|
||||
heading_count_after = sum(1 for line in rewritten.splitlines() if line.lstrip().startswith("#"))
|
||||
warnings = ["标题数量发生变化,请在前后对比中确认结构。"] if heading_count_before != heading_count_after else []
|
||||
warnings.extend(illustration_warnings)
|
||||
summary = build_document_rewrite_summary(
|
||||
source_display_name=actual_path.name,
|
||||
instruction=instruction,
|
||||
@@ -1001,6 +1190,8 @@ class DeepResearchJobExecutor:
|
||||
rewritten=rewritten,
|
||||
validation_warnings=warnings,
|
||||
)
|
||||
summary["generatedImageCount"] = len(persisted_illustrations)
|
||||
summary["requestedImageCount"] = max_generated_images if generate_images else 0
|
||||
await events.emit(
|
||||
"document_rewrite",
|
||||
phase="reviewing",
|
||||
@@ -1126,9 +1317,7 @@ class DeepResearchJobExecutor:
|
||||
job_id=job_id,
|
||||
on_event=self._live_publisher,
|
||||
)
|
||||
await events.emit(
|
||||
"document_rewrite", phase="done", payload={"type": "error", "message": message, "stage": stage}
|
||||
)
|
||||
await events.emit("document_rewrite", phase="done", payload={"type": "error", "message": message, "stage": stage})
|
||||
await self._job_store.update_progress(
|
||||
job_id,
|
||||
lease_owner=lease_owner,
|
||||
@@ -1334,11 +1523,7 @@ class DeepResearchJobExecutor:
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
"请为以下研究报告写一段 150-250 字的摘要,使用"
|
||||
f"{lang_note},一段纯文本,不要标题、不要列表、不要 Markdown 格式:\n\n"
|
||||
f"{report_markdown[:24_000]}"
|
||||
),
|
||||
"content": (f"请为以下研究报告写一段 150-250 字的摘要,使用{lang_note},一段纯文本,不要标题、不要列表、不要 Markdown 格式:\n\n{report_markdown[:24_000]}"),
|
||||
},
|
||||
],
|
||||
on_delta=on_delta,
|
||||
@@ -1371,9 +1556,7 @@ class DeepResearchJobExecutor:
|
||||
|
||||
# ── terminal-state writers ──────────────────────────────────────────────
|
||||
|
||||
async def _mark_completed(
|
||||
self, job_id: str, session_id: str, lease_owner: str | None, result: DeepResearchResult
|
||||
) -> None:
|
||||
async def _mark_completed(self, job_id: str, session_id: str, lease_owner: str | None, result: DeepResearchResult) -> None:
|
||||
# Persist the report projection before exposing a terminal completed
|
||||
# job. The session row is the durable report itself; marking the job
|
||||
# complete first and suppressing a session-write failure can otherwise
|
||||
@@ -1449,13 +1632,9 @@ class DeepResearchJobExecutor:
|
||||
)
|
||||
await asyncio.sleep(_REPORT_PROJECTION_RETRY_DELAY_SECONDS * attempt)
|
||||
|
||||
raise RuntimeError(
|
||||
f"研究报告未能保存到会话 {session_id},任务不会标记为完成"
|
||||
) from last_error
|
||||
raise RuntimeError(f"研究报告未能保存到会话 {session_id},任务不会标记为完成") from last_error
|
||||
|
||||
async def _mark_awaiting(
|
||||
self, job_id: str, session_id: str, pause: ResearchAwaitingInput
|
||||
) -> None:
|
||||
async def _mark_awaiting(self, job_id: str, session_id: str, pause: ResearchAwaitingInput) -> None:
|
||||
"""Project a persisted plan-review interrupt onto the owning session."""
|
||||
with suppress(Exception): # noqa: BLE001
|
||||
await self._session_store.update(
|
||||
@@ -1465,9 +1644,7 @@ class DeepResearchJobExecutor:
|
||||
active_job_id=job_id,
|
||||
)
|
||||
|
||||
async def _mark_failed(
|
||||
self, job_id: str, session_id: str, lease_owner: str | None, code: str, message: str
|
||||
) -> None:
|
||||
async def _mark_failed(self, job_id: str, session_id: str, lease_owner: str | None, code: str, message: str) -> None:
|
||||
await self._job_store.update_progress(
|
||||
job_id,
|
||||
lease_owner=lease_owner,
|
||||
|
||||
@@ -85,6 +85,7 @@ async def stream_full_report_rewrite(
|
||||
style: str,
|
||||
model_name: str | None,
|
||||
on_delta: Callable[[str], Awaitable[None]],
|
||||
on_reasoning: Callable[[str], Awaitable[None]] | None = None,
|
||||
requirements_plan: str | None = None,
|
||||
) -> tuple[str, list[str], dict[str, Any]]:
|
||||
"""Generate a complete Markdown replacement without starting new research."""
|
||||
@@ -126,6 +127,7 @@ async def stream_full_report_rewrite(
|
||||
messages=messages,
|
||||
operation="full_report_rewrite",
|
||||
on_delta=on_delta,
|
||||
on_reasoning=on_reasoning,
|
||||
)
|
||||
answer = result.text.strip() or report
|
||||
answer, cited = _normalise_citations(answer, source_ids)
|
||||
@@ -140,6 +142,7 @@ async def stream_full_report_rewrite_requirements(
|
||||
style: str,
|
||||
model_name: str | None,
|
||||
on_delta: Callable[[str], Awaitable[None]],
|
||||
on_reasoning: Callable[[str], Awaitable[None]] | None = None,
|
||||
) -> str:
|
||||
"""Stream a compact plan before rewriting a research report.
|
||||
|
||||
@@ -169,6 +172,7 @@ async def stream_full_report_rewrite_requirements(
|
||||
],
|
||||
operation="full_report_rewrite_requirements",
|
||||
on_delta=on_delta,
|
||||
on_reasoning=on_reasoning,
|
||||
)
|
||||
return result.text.strip()
|
||||
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
"""Safe, optional illustrations for a sandbox Markdown full rewrite.
|
||||
|
||||
The writer streams prose first. When requested, this module derives a small
|
||||
set of heading-scoped illustration prompts, persists the returned bytes inside
|
||||
the same user-owned artifact tree, then adds only local ``/mnt`` references to
|
||||
the Markdown. Provider URLs never reach the browser or the saved document.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
from deerflow.agents.deep_research.adapters.image import ImageGenerationError, ImageProvider
|
||||
|
||||
_HEADING_RE = re.compile(r"^##[ \t]+([^\r\n]+?)[ \t]*$", re.MULTILINE)
|
||||
_TITLE_RE = re.compile(r"^#[ \t]+([^\r\n]+?)[ \t]*$", re.MULTILINE)
|
||||
_START_MARKER = "<!-- deerflow:ai-rewrite-image:start -->"
|
||||
_END_MARKER = "<!-- deerflow:ai-rewrite-image:end -->"
|
||||
_MANAGED_IMAGE_BLOCK_RE = re.compile(
|
||||
rf"\n?{re.escape(_START_MARKER)}.*?{re.escape(_END_MARKER)}\n?",
|
||||
re.DOTALL,
|
||||
)
|
||||
_MIME_EXTENSIONS = {
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpg",
|
||||
"image/webp": "webp",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DocumentIllustration:
|
||||
"""A provider result that has not been exposed or persisted yet."""
|
||||
|
||||
section: str
|
||||
position: int
|
||||
data: bytes
|
||||
mime_type: str
|
||||
alt: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PersistedDocumentIllustration:
|
||||
"""A generated image with a virtual artifact path safe for Markdown."""
|
||||
|
||||
section: str
|
||||
position: int
|
||||
virtual_path: str
|
||||
alt: str
|
||||
|
||||
|
||||
def strip_managed_document_illustrations(markdown: str) -> str:
|
||||
"""Remove only DeerFlow-generated image blocks before a fresh image pass."""
|
||||
|
||||
return _MANAGED_IMAGE_BLOCK_RE.sub("\n", markdown).strip()
|
||||
|
||||
|
||||
def select_illustration_sections(markdown: str, maximum: int) -> list[str]:
|
||||
"""Pick distinct H2 sections; fall back to the title for short documents."""
|
||||
|
||||
limit = max(0, min(maximum, 4))
|
||||
if not limit:
|
||||
return []
|
||||
sections: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for match in _HEADING_RE.finditer(markdown):
|
||||
section = _clean_heading(match.group(1))
|
||||
if section and section not in seen:
|
||||
seen.add(section)
|
||||
sections.append(section)
|
||||
if len(sections) >= limit:
|
||||
return sections
|
||||
if sections:
|
||||
return sections
|
||||
title_match = _TITLE_RE.search(markdown)
|
||||
title = _clean_heading(title_match.group(1)) if title_match else "文档主题"
|
||||
return [title or "文档主题"]
|
||||
|
||||
|
||||
async def generate_document_illustrations(
|
||||
provider: ImageProvider,
|
||||
*,
|
||||
markdown: str,
|
||||
document_name: str,
|
||||
maximum: int,
|
||||
on_started=None,
|
||||
on_generated=None,
|
||||
) -> tuple[list[DocumentIllustration], list[str]]:
|
||||
"""Generate a bounded, sequential image set and keep failures recoverable."""
|
||||
|
||||
sections = select_illustration_sections(markdown, maximum)
|
||||
title_match = _TITLE_RE.search(markdown)
|
||||
document_title = _clean_heading(title_match.group(1)) if title_match else Path(document_name).stem
|
||||
generated: list[DocumentIllustration] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
for position, section in enumerate(sections, 1):
|
||||
if on_started is not None:
|
||||
await on_started(section, position, len(sections))
|
||||
try:
|
||||
result = await provider.generate(
|
||||
_illustration_prompt(document_title, section),
|
||||
section_id=section,
|
||||
)
|
||||
data = result.get("data") if isinstance(result, dict) else None
|
||||
if not isinstance(data, bytes) or not data:
|
||||
raise ImageGenerationError("图片生成服务未返回可保存的图片数据")
|
||||
mime_type = str(result.get("mime_type") or "image/png").lower()
|
||||
if mime_type not in _MIME_EXTENSIONS:
|
||||
mime_type = "image/png"
|
||||
illustration = DocumentIllustration(
|
||||
section=section,
|
||||
position=position,
|
||||
data=data,
|
||||
mime_type=mime_type,
|
||||
alt=_clean_alt(str(result.get("alt") or f"{section}配图")),
|
||||
)
|
||||
generated.append(illustration)
|
||||
if on_generated is not None:
|
||||
await on_generated(illustration, len(sections), len(generated))
|
||||
except ImageGenerationError as exc:
|
||||
warnings.append(f"“{section}”配图未生成:{exc}")
|
||||
except Exception: # noqa: BLE001
|
||||
# Generation remains best effort: an unavailable image provider
|
||||
# must never discard an otherwise complete document rewrite.
|
||||
warnings.append(f"“{section}”配图生成失败,已保留文字改写结果。")
|
||||
return generated, warnings
|
||||
|
||||
|
||||
def persist_document_illustrations(
|
||||
illustrations: list[DocumentIllustration],
|
||||
*,
|
||||
markdown_path: Path,
|
||||
virtual_markdown_path: str,
|
||||
job_id: str,
|
||||
) -> tuple[list[PersistedDocumentIllustration], list[str]]:
|
||||
"""Best-effort persist each asset beside the rewritten Markdown file.
|
||||
|
||||
A single failed local write must not discard earlier successful images. In
|
||||
particular, Windows development reloaders can briefly recreate an output
|
||||
directory while a report is being written. The caller receives warnings
|
||||
for the timeline, while any persisted image remains usable in the final
|
||||
Markdown.
|
||||
"""
|
||||
|
||||
if not illustrations:
|
||||
return [], []
|
||||
# Keep this name intentionally short. On Windows the local sandbox path
|
||||
# already contains user/thread UUIDs; including a long report title plus a
|
||||
# UUID-based temporary filename exceeded MAX_PATH (and surfaced as a
|
||||
# misleading FileNotFoundError). Job ids make names unique across files,
|
||||
# so a single short hidden directory per outputs folder is sufficient.
|
||||
asset_directory_name = ".ai-images"
|
||||
asset_directory = markdown_path.parent / asset_directory_name
|
||||
virtual_parent = PurePosixPath(virtual_markdown_path).parent.as_posix().rstrip("/")
|
||||
persisted: list[PersistedDocumentIllustration] = []
|
||||
warnings: list[str] = []
|
||||
for image in illustrations:
|
||||
try:
|
||||
extension = _MIME_EXTENSIONS[image.mime_type]
|
||||
file_name = f"{job_id}-{image.position:02d}.{extension}"
|
||||
_atomic_write_bytes(asset_directory / file_name, image.data)
|
||||
persisted.append(
|
||||
PersistedDocumentIllustration(
|
||||
section=image.section,
|
||||
position=image.position,
|
||||
virtual_path=f"{virtual_parent}/{asset_directory_name}/{file_name}",
|
||||
alt=image.alt,
|
||||
)
|
||||
)
|
||||
except OSError:
|
||||
warnings.append(f"“{image.section}”配图保存失败,已继续保留其他成功配图。")
|
||||
return persisted, warnings
|
||||
|
||||
|
||||
def insert_document_illustrations(
|
||||
markdown: str,
|
||||
illustrations: list[PersistedDocumentIllustration],
|
||||
) -> str:
|
||||
"""Insert fenced local-image blocks directly below their selected sections."""
|
||||
|
||||
amended = strip_managed_document_illustrations(markdown)
|
||||
for image in illustrations:
|
||||
marker = f"## {image.section}"
|
||||
block = (
|
||||
f"\n\n{_START_MARKER}\n"
|
||||
f"\n"
|
||||
f"{_END_MARKER}\n"
|
||||
)
|
||||
if marker in amended:
|
||||
amended = amended.replace(marker, f"{marker}{block}", 1)
|
||||
else:
|
||||
amended = f"{amended.rstrip()}{block}"
|
||||
return amended.strip()
|
||||
|
||||
|
||||
def _atomic_write_bytes(path: Path, content: bytes) -> None:
|
||||
"""Write one image atomically with Windows-safe temporary path lengths."""
|
||||
|
||||
last_error: FileNotFoundError | None = None
|
||||
for _attempt in range(3):
|
||||
temporary: Path | None = None
|
||||
try:
|
||||
# A runtime cleanup can remove a freshly-created asset folder
|
||||
# between image calls. Recreate it immediately before writing and
|
||||
# retry this small local operation. NamedTemporaryFile deliberately
|
||||
# keeps the temporary basename short: appending a report title,
|
||||
# job id, and UUID can exceed Windows MAX_PATH before os.replace.
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="wb",
|
||||
dir=path.parent,
|
||||
prefix=".w-",
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as file:
|
||||
temporary = Path(file.name)
|
||||
file.write(content)
|
||||
file.flush()
|
||||
os.fsync(file.fileno())
|
||||
os.replace(temporary, path)
|
||||
return
|
||||
except FileNotFoundError as exc:
|
||||
last_error = exc
|
||||
finally:
|
||||
try:
|
||||
if temporary is not None and temporary.exists():
|
||||
temporary.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
if last_error is not None:
|
||||
raise last_error
|
||||
|
||||
|
||||
def _illustration_prompt(document_title: str, section: str) -> str:
|
||||
return (
|
||||
"为一份专业 Markdown 文档生成一张可嵌入的章节配图。"
|
||||
f"文档主题:{_clean_heading(document_title)}。章节:{section}。"
|
||||
"画面应信息性、简洁、与正文内容一致,可使用抽象示意、数据可视化风格或场景插画。"
|
||||
"不要在图片中放置可读文字、品牌标志、水印或人物肖像;不得虚构具体数据或事实。"
|
||||
)
|
||||
|
||||
|
||||
def _clean_heading(value: str) -> str:
|
||||
return " ".join(value.replace("\r", " ").replace("\n", " ").split())[:160]
|
||||
|
||||
|
||||
def _clean_alt(value: str) -> str:
|
||||
return _clean_heading(value).replace("[", "").replace("]", "") or "文档配图"
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DocumentIllustration",
|
||||
"PersistedDocumentIllustration",
|
||||
"generate_document_illustrations",
|
||||
"insert_document_illustrations",
|
||||
"persist_document_illustrations",
|
||||
"select_illustration_sections",
|
||||
"strip_managed_document_illustrations",
|
||||
]
|
||||
@@ -14,10 +14,12 @@ import logging
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from collections.abc import AsyncIterator
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from deerflow.utils.stream_text import InlineThinkTagFilter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_DOCUMENT_REWRITE_CHARS = 120_000
|
||||
@@ -89,9 +91,7 @@ def build_rewrite_requirements_context(content: str) -> str:
|
||||
if len(headings) >= 30:
|
||||
break
|
||||
|
||||
heading_count = sum(
|
||||
1 for line in content.splitlines() if re.match(r"^\s{0,3}#{1,6}\s+", line)
|
||||
)
|
||||
heading_count = sum(1 for line in content.splitlines() if re.match(r"^\s{0,3}#{1,6}\s+", line))
|
||||
link_count = len(re.findall(r"!?(?:\[[^\]]*\]\([^)]*\))", content))
|
||||
table_rows = sum(1 for line in content.splitlines() if line.lstrip().startswith("|"))
|
||||
return "\n".join(
|
||||
@@ -136,16 +136,7 @@ def build_rewrite_requirements_messages(
|
||||
|
||||
return [
|
||||
SystemMessage(content=DOCUMENT_REWRITE_REQUIREMENTS_SYSTEM_PROMPT),
|
||||
HumanMessage(
|
||||
content=(
|
||||
f"文件名:{file_name}\n"
|
||||
f"用户改写要求:{instruction}\n"
|
||||
f"选定风格:{style_instruction}\n\n"
|
||||
"【文档结构信息开始】\n"
|
||||
f"{build_rewrite_requirements_context(original)}\n"
|
||||
"【文档结构信息结束】"
|
||||
)
|
||||
),
|
||||
HumanMessage(content=(f"文件名:{file_name}\n用户改写要求:{instruction}\n选定风格:{style_instruction}\n\n【文档结构信息开始】\n{build_rewrite_requirements_context(original)}\n【文档结构信息结束】")),
|
||||
]
|
||||
|
||||
|
||||
@@ -156,18 +147,30 @@ async def astream_rewrite_requirements(
|
||||
instruction: str,
|
||||
style_instruction: str,
|
||||
original: str,
|
||||
on_thinking: Callable[[str], Awaitable[None]] | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Yield only visible plan text from the short requirements-planning call."""
|
||||
"""Yield visible plan text and optionally forward live model reasoning."""
|
||||
messages = build_rewrite_requirements_messages(
|
||||
file_name=file_name,
|
||||
instruction=instruction,
|
||||
style_instruction=style_instruction,
|
||||
original=original,
|
||||
)
|
||||
inline_think_filter = InlineThinkTagFilter()
|
||||
async for chunk in model.astream(messages, config={"run_name": "document_rewrite_requirements"}):
|
||||
_, text = extract_stream_chunk_parts(chunk)
|
||||
if text:
|
||||
yield text
|
||||
structured_thinking, text = extract_stream_chunk_parts(chunk)
|
||||
if structured_thinking and on_thinking is not None:
|
||||
await on_thinking(structured_thinking)
|
||||
visible_text, inline_thinking = inline_think_filter.push_parts(text)
|
||||
if inline_thinking and on_thinking is not None:
|
||||
await on_thinking(inline_thinking)
|
||||
if visible_text:
|
||||
yield visible_text
|
||||
tail, inline_thinking_tail = inline_think_filter.finish_parts()
|
||||
if inline_thinking_tail and on_thinking is not None:
|
||||
await on_thinking(inline_thinking_tail)
|
||||
if tail:
|
||||
yield tail
|
||||
|
||||
|
||||
def atomic_write_text(path: Path, content: str) -> None:
|
||||
|
||||
@@ -21,6 +21,7 @@ from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.deps import get_agent_store
|
||||
from deerflow.runtime.user_context import get_effective_user_id
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -125,6 +126,37 @@ async def _validate_public_chain_mapping(
|
||||
status_code=400,
|
||||
detail="Global business mappings require a public business chain",
|
||||
)
|
||||
|
||||
# 公共业务映射会被任意账号启动,链条中的席位也必须对任意账号可见。
|
||||
# 仅把链条本身发布、却把其中某个自定义智能体保留为未发布/私有,会导致
|
||||
# 前端只能解析到不足两个席位,最终被误判为“没有可用业务链”。
|
||||
seats = chain.get("seats")
|
||||
if isinstance(seats, list):
|
||||
agent_store = get_agent_store(request)
|
||||
unavailable_names: list[str] = []
|
||||
for raw_seat in seats:
|
||||
if not isinstance(raw_seat, dict):
|
||||
continue
|
||||
agent_id = str(raw_seat.get("agent_id") or "").strip()
|
||||
if not agent_id:
|
||||
continue
|
||||
agent = await agent_store.get_any(agent_id)
|
||||
is_builtin = agent is not None and agent.get("user_id") is None
|
||||
is_public_agent = bool(agent and agent.get("published")) and not bool(
|
||||
agent and agent.get("is_private")
|
||||
)
|
||||
if is_builtin or is_public_agent:
|
||||
continue
|
||||
name = str(raw_seat.get("name") or agent_id).strip()
|
||||
unavailable_names.append(name)
|
||||
if unavailable_names:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Global business mappings require every seat to be published and public; "
|
||||
f"unavailable agents: {', '.join(unavailable_names)}"
|
||||
),
|
||||
)
|
||||
fields["chain_id"] = chain_id
|
||||
fields["chain_title"] = str(chain.get("title") or "") or None
|
||||
|
||||
|
||||
@@ -158,20 +158,19 @@ def _clarification_blocks_ready(
|
||||
*,
|
||||
is_fresh: bool,
|
||||
) -> bool:
|
||||
"""Position intent must wait for a fresh clarification answer.
|
||||
"""A fresh clarification always pauses intent resolution.
|
||||
|
||||
The generic Step-1 route intentionally preserves READY-first behavior for
|
||||
stale tool calls in historical snapshots. Position roundtable instead has
|
||||
a four-part hand-off whose missing context is requested interactively, so
|
||||
a newly dispatched clarification is a strict terminal pause. A historical
|
||||
tool call from the preceding user-assistance turn must not block the next
|
||||
user answer from reaching READY.
|
||||
A tool call and a premature ``[INTENT_READY]`` block may coexist in the
|
||||
same upstream run. The tool call is an explicit request for user input,
|
||||
so it wins for every Step-1 workspace (including 8BF): do not consume the
|
||||
assistance card before the user can answer it. Stale calls from earlier
|
||||
turns remain harmless because only a fresh call blocks READY.
|
||||
|
||||
``intent_agent_id`` stays in the signature for route-call compatibility
|
||||
and to keep the policy extensible per agent if a future flow needs one.
|
||||
"""
|
||||
return (
|
||||
intent_agent_id == POSITION_INTENT_AGENT_ID
|
||||
and bool(clarification_calls)
|
||||
and is_fresh
|
||||
)
|
||||
del intent_agent_id
|
||||
return bool(clarification_calls) and is_fresh
|
||||
|
||||
|
||||
def _intent_thread_metadata(
|
||||
@@ -696,11 +695,10 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
)
|
||||
clarification_is_fresh = current_rounds > past_rounds
|
||||
|
||||
# A position-roundtable clarification is an explicit pause.
|
||||
# Some models emit a premature [INTENT_READY] text after the
|
||||
# tool call in the same upstream run. For this dedicated flow
|
||||
# the fresh clarification must win so the user can answer it;
|
||||
# generic roundtable keeps its historical READY-first order.
|
||||
# A fresh clarification is an explicit pause. Some models emit
|
||||
# a premature [INTENT_READY] block after its tool call in the
|
||||
# same upstream run; the user-assistance card must win so the
|
||||
# user can answer it before any summary is accepted.
|
||||
dispatch_msg = _find_dispatch_message(messages)
|
||||
tool_calls = dispatch_msg.get("tool_calls") or []
|
||||
clarification_calls = [
|
||||
@@ -710,10 +708,10 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
and (tc.get("name") or "").lower() == "ask_clarification"
|
||||
]
|
||||
|
||||
# --- 终态分支 1:结构化意图已就绪(最高优先级)---
|
||||
# --- 终态分支 1:结构化意图已就绪(无新追问时)---
|
||||
# 模型可能在较早的 AIMessage 里已输出 [INTENT_READY],而最后一轮
|
||||
# 仍残留 ask_clarification 的 tool_calls;必须先扫 READY,否则前端
|
||||
# 会错误展示澄清卡片且 intentReady 无法解锁 Step 2。
|
||||
# 仍残留 ask_clarification 的 tool_calls;若它是本轮新产生的追问,
|
||||
# 必须先等待用户回答,不能让 READY 覆盖可交互的协助卡。
|
||||
summary: dict[str, Any] | None = None
|
||||
ready_text: str = ""
|
||||
for msg in reversed(messages):
|
||||
|
||||
@@ -59,6 +59,7 @@ from app.gateway.document_rewrite_summary import build_document_rewrite_summary
|
||||
from app.gateway.path_utils import aresolve_thread_virtual_path
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.models import create_chat_model
|
||||
from deerflow.utils.stream_text import InlineThinkTagFilter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -143,6 +144,8 @@ class DocumentRewriteRequest(BaseModel):
|
||||
instruction: str = Field(..., min_length=1, max_length=4_000)
|
||||
style: str | None = Field(default=None)
|
||||
model_name: str | None = Field(default=None, alias="modelName")
|
||||
generate_images: bool = Field(default=False, alias="generateImages")
|
||||
max_generated_images: int = Field(default=2, alias="maxGeneratedImages", ge=1, le=4)
|
||||
expected_hash: str | None = Field(default=None, alias="expectedHash")
|
||||
|
||||
model_config = {"populate_by_name": True}
|
||||
@@ -193,12 +196,7 @@ def _artifact_rewrite_scope(thread_id: str, virtual_path: str) -> str:
|
||||
|
||||
def _artifact_job_matches(job: dict, *, thread_id: str, virtual_path: str) -> bool:
|
||||
snapshot = job.get("input_snapshot")
|
||||
return bool(
|
||||
isinstance(snapshot, dict)
|
||||
and snapshot.get("kind") == "artifact_document_rewrite"
|
||||
and snapshot.get("thread_id") == thread_id
|
||||
and snapshot.get("path") == virtual_path
|
||||
)
|
||||
return bool(isinstance(snapshot, dict) and snapshot.get("kind") == "artifact_document_rewrite" and snapshot.get("thread_id") == thread_id and snapshot.get("path") == virtual_path)
|
||||
|
||||
|
||||
def _artifact_job_response(job: dict) -> dict:
|
||||
@@ -215,6 +213,8 @@ def _artifact_job_response(job: dict) -> dict:
|
||||
"instruction": str(snapshot.get("instruction") or ""),
|
||||
"style": str(snapshot.get("style") or "professional"),
|
||||
"modelName": snapshot.get("model_name"),
|
||||
"generateImages": bool(snapshot.get("generate_images")),
|
||||
"maxGeneratedImages": int(snapshot.get("max_generated_images") or 2),
|
||||
"originalContent": snapshot.get("original_content") or "",
|
||||
},
|
||||
}
|
||||
@@ -266,10 +266,7 @@ async def _stream_durable_artifact_rewrite_job(
|
||||
yield _sse(
|
||||
"error",
|
||||
{
|
||||
"message": str(
|
||||
current.get("error_message")
|
||||
or "全文改写任务未完成,原文件未被修改。"
|
||||
),
|
||||
"message": str(current.get("error_message") or "全文改写任务未完成,原文件未被修改。"),
|
||||
"stage": str(current.get("phase") or "generation"),
|
||||
},
|
||||
)
|
||||
@@ -397,6 +394,8 @@ async def start_durable_document_rewrite_job(
|
||||
"instruction": body.instruction.strip(),
|
||||
"style": body.style or "professional",
|
||||
"model_name": body.model_name,
|
||||
"generate_images": body.generate_images,
|
||||
"max_generated_images": body.max_generated_images,
|
||||
}
|
||||
request_hash = hashlib.sha256(
|
||||
json.dumps(
|
||||
@@ -405,6 +404,8 @@ async def start_durable_document_rewrite_job(
|
||||
"instruction": body.instruction.strip(),
|
||||
"style": body.style or "professional",
|
||||
"model_name": body.model_name,
|
||||
"generate_images": body.generate_images,
|
||||
"max_generated_images": body.max_generated_images,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
@@ -468,13 +469,7 @@ async def list_durable_document_rewrite_jobs(
|
||||
virtual_path = path.strip()
|
||||
scope = _artifact_rewrite_scope(thread_id, virtual_path)
|
||||
rows = await job_store.list_by_session(scope, user_id=user_id, limit=limit)
|
||||
return {
|
||||
"items": [
|
||||
_artifact_job_response(row)
|
||||
for row in rows
|
||||
if _artifact_job_matches(row, thread_id=thread_id, virtual_path=virtual_path)
|
||||
]
|
||||
}
|
||||
return {"items": [_artifact_job_response(row) for row in rows if _artifact_job_matches(row, thread_id=thread_id, virtual_path=virtual_path)]}
|
||||
|
||||
|
||||
@router.get("/document-rewrite/jobs/{job_id}/stream", response_class=StreamingResponse)
|
||||
@@ -665,10 +660,14 @@ async def rewrite_document(
|
||||
"plan": requirements_plan,
|
||||
},
|
||||
)
|
||||
inline_think_filter = InlineThinkTagFilter()
|
||||
async for chunk in model.astream(messages, config={"run_name": "document_rewrite"}):
|
||||
thinking_delta, text_delta = _extract_chunk_parts(chunk)
|
||||
if thinking_delta:
|
||||
yield _sse("thinking", {"chunk": thinking_delta})
|
||||
text_delta, inline_thinking = inline_think_filter.push_parts(text_delta)
|
||||
if inline_thinking:
|
||||
yield _sse("thinking", {"chunk": inline_thinking})
|
||||
if text_delta:
|
||||
draft_parts.append(text_delta)
|
||||
yield _sse(
|
||||
@@ -679,6 +678,19 @@ async def rewrite_document(
|
||||
},
|
||||
)
|
||||
|
||||
tail, inline_thinking_tail = inline_think_filter.finish_parts()
|
||||
if inline_thinking_tail:
|
||||
yield _sse("thinking", {"chunk": inline_thinking_tail})
|
||||
if tail:
|
||||
draft_parts.append(tail)
|
||||
yield _sse(
|
||||
"rewrite_delta",
|
||||
{
|
||||
"delta": tail,
|
||||
"charCount": _count_document_chars("".join(draft_parts)),
|
||||
},
|
||||
)
|
||||
|
||||
rewritten = "".join(draft_parts).strip()
|
||||
yield _sse("validation_started", {})
|
||||
validation_error = _markdown_validation_error(rewritten)
|
||||
@@ -688,11 +700,7 @@ async def rewrite_document(
|
||||
|
||||
heading_count_before = sum(1 for line in original.splitlines() if line.lstrip().startswith("#"))
|
||||
heading_count_after = sum(1 for line in rewritten.splitlines() if line.lstrip().startswith("#"))
|
||||
warnings = (
|
||||
["标题数量发生变化,请在前后对比中确认结构。"]
|
||||
if heading_count_before != heading_count_after
|
||||
else []
|
||||
)
|
||||
warnings = ["标题数量发生变化,请在前后对比中确认结构。"] if heading_count_before != heading_count_after else []
|
||||
yield _sse(
|
||||
"validation_completed",
|
||||
{
|
||||
@@ -891,12 +899,21 @@ async def rewrite_selection(
|
||||
async def generate():
|
||||
try:
|
||||
model = create_chat_model(name=body.model_name, thinking_enabled=thinking_enabled, app_config=config)
|
||||
inline_think_filter = InlineThinkTagFilter()
|
||||
async for chunk in model.astream(messages, config={"run_name": "writing_rewrite"}):
|
||||
thinking_delta, text_delta = _extract_chunk_parts(chunk)
|
||||
if thinking_delta:
|
||||
yield _sse("thinking", {"chunk": thinking_delta})
|
||||
text_delta, inline_thinking = inline_think_filter.push_parts(text_delta)
|
||||
if inline_thinking:
|
||||
yield _sse("thinking", {"chunk": inline_thinking})
|
||||
if text_delta:
|
||||
yield _sse("text", {"chunk": text_delta})
|
||||
tail, inline_thinking_tail = inline_think_filter.finish_parts()
|
||||
if inline_thinking_tail:
|
||||
yield _sse("thinking", {"chunk": inline_thinking_tail})
|
||||
if tail:
|
||||
yield _sse("text", {"chunk": tail})
|
||||
yield _sse("done", {})
|
||||
except Exception as e:
|
||||
logger.exception("writing/rewrite failed: thread=%s action=%s", body.thread_id, action)
|
||||
|
||||
@@ -101,7 +101,7 @@ models:
|
||||
max_retries: 2
|
||||
stream_usage: true
|
||||
supports_thinking: true
|
||||
supports_reasoning_effort: false
|
||||
supports_reasoning_effort: true
|
||||
supports_vision: false
|
||||
- name: qwen3.6
|
||||
display_name: qwen3.6
|
||||
@@ -207,17 +207,18 @@ vision:
|
||||
# max_tokens: 2048
|
||||
|
||||
# 深度研究可选的报告配图。默认关闭;仅在部署方配置文生图模型后,前端才会展示开关。
|
||||
# 使用 OpenAI 兼容的 POST {base_url}/images/generations 协议,并强制要求 b64_json
|
||||
# 返回,以便将图片保存为当前研究会话的受鉴权产物,而不是引用会过期的公网 URL。
|
||||
# provider: openai_compatible 使用 POST {base_url}/images/generations 并要求 b64_json。
|
||||
# provider: dashscope_native 用于千问 Token Plan 的 qwen-image-3.0-pro / wan2.7-image:
|
||||
# 使用原生多模态 generation 接口,服务返回的临时图片 URL 会立即下载并保存为受鉴权产物。
|
||||
deep_research:
|
||||
image_generation:
|
||||
enabled: true
|
||||
provider: openai_compatible
|
||||
base_url: https://token-plan.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation # 例如 https://api.openai.com/v1
|
||||
provider: dashscope_native
|
||||
base_url: https://token-plan.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
|
||||
api_key: sk-sp-H.XDIPL.Zgvs.MEQCIBasaS2RPHwgNUpGVfFJeRaTp5UgmZ4Y2rCVGNtpwfD1AiBTFg3S-uE_gqVDnHgdyEhDwcfaVRLi92xviye80AZnkg # 生产环境建议填 $DEEP_RESEARCH_IMAGE_API_KEY
|
||||
model: wan2.7-image # 例如 gpt-image-1
|
||||
model: wan2.7-image # 也可设为 qwen-image-3.0-pro
|
||||
size: 1024x1024
|
||||
# quality: standard
|
||||
watermark: false
|
||||
timeout_seconds: 120
|
||||
|
||||
# browser_act 相关配置
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ path and commit below, and keep the Apache-2.0 notice in the distribution.
|
||||
| `runners/deep.py` | `gpt_researcher/skills/deep_research.py` | Breadth/depth branching, learnings and follow-up questions are preserved with an explicit global budget, semaphores and cooperative cancellation. |
|
||||
| `runners/multi_agent.py` | `multi_agents/agents/{orchestrator,editor,writer,fact_checker}.py` | Editor/researcher/writer/reviewer roles become a LangGraph 1.x `StateGraph`, with the review pause persisted as a durable job state. |
|
||||
| `adapters/context.py`, `adapters/material.py` | `gpt_researcher/context/compression.py`, `gpt_researcher/skills/researcher.py` | Retains context/de-duplication intent while preserving DeerFlow provenance (`rec_uuid`, source id, source type) and enforcing the existing material-provider boundary. |
|
||||
| `runners/images.py`, `adapters/image.py` | `gpt_researcher/skills/image_generator.py` | Retains report-image placement intent, but image generation uses a configured DeerFlow OpenAI-compatible adapter and protected hidden-thread artifacts. |
|
||||
| `runners/images.py`, `adapters/image.py` | `gpt_researcher/skills/image_generator.py` | Retains report-image placement intent, while configured OpenAI-compatible and DashScope-native adapters both persist protected hidden-thread artifacts. |
|
||||
|
||||
## Required adaptation invariants
|
||||
|
||||
|
||||
+211
-12
@@ -1,14 +1,17 @@
|
||||
"""Optional, DeerFlow-configured report image generation.
|
||||
|
||||
The upstream GPT Researcher image skill owns its provider configuration, so it
|
||||
cannot be safely reused in DeerFlow. This adapter instead talks to a deployment
|
||||
configured OpenAI-compatible ``/images/generations`` endpoint. It is never
|
||||
configured from a browser request: model credentials stay in ``config.yaml``
|
||||
and the per-session snapshot contains only the boolean ``generate_images``.
|
||||
cannot be safely reused in DeerFlow. This adapter supports both a deployment
|
||||
configured OpenAI-compatible ``/images/generations`` endpoint and the native
|
||||
DashScope multimodal-generation endpoint used by Qwen Image 3.0 and Wan 2.7.
|
||||
It is never configured from a browser request: model credentials stay in
|
||||
``config.yaml`` and the per-session snapshot contains only the boolean
|
||||
``generate_images``.
|
||||
|
||||
Images are requested as base64 rather than provider-hosted URLs. The runner can
|
||||
therefore put the exact bytes into the session's protected artifact directory;
|
||||
reports never depend on an expiring public image URL.
|
||||
OpenAI-compatible images are requested as base64; DashScope image URLs are
|
||||
downloaded immediately. The runner therefore always puts exact bytes into the
|
||||
session's protected artifact directory, and reports never depend on an expiring
|
||||
public image URL.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,11 +19,13 @@ from __future__ import annotations
|
||||
import base64
|
||||
import binascii
|
||||
from typing import Any, Literal, Protocol, runtime_checkable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
_MAX_IMAGE_BYTES = 20 * 1024 * 1024
|
||||
_DASHSCOPE_GENERATION_PATH = "/api/v1/services/aigc/multimodal-generation/generation"
|
||||
|
||||
|
||||
class ImageGenerationError(RuntimeError):
|
||||
@@ -28,17 +33,17 @@ class ImageGenerationError(RuntimeError):
|
||||
|
||||
|
||||
class ImageGenerationSettings(BaseModel):
|
||||
"""Server-only configuration for an OpenAI-compatible image endpoint.
|
||||
"""Server-only configuration for a report image endpoint.
|
||||
|
||||
Example ``config.yaml`` section::
|
||||
|
||||
deep_research:
|
||||
image_generation:
|
||||
enabled: true
|
||||
provider: openai_compatible
|
||||
base_url: https://api.openai.com/v1
|
||||
provider: dashscope_native
|
||||
base_url: https://token-plan.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
|
||||
api_key: $DEEP_RESEARCH_IMAGE_API_KEY
|
||||
model: gpt-image-1
|
||||
model: qwen-image-3.0-pro
|
||||
|
||||
``api_key`` is resolved by :class:`AppConfig` while loading YAML, but this
|
||||
object is deliberately not placed in ``DeepResearchConfig`` and is never
|
||||
@@ -46,12 +51,13 @@ class ImageGenerationSettings(BaseModel):
|
||||
"""
|
||||
|
||||
enabled: bool = False
|
||||
provider: Literal["openai_compatible"] = "openai_compatible"
|
||||
provider: Literal["openai_compatible", "dashscope_native"] = "openai_compatible"
|
||||
base_url: str = ""
|
||||
api_key: str = ""
|
||||
model: str = ""
|
||||
size: str = "1024x1024"
|
||||
quality: str | None = None
|
||||
watermark: bool = False
|
||||
timeout_seconds: float = Field(default=120, ge=1, le=300)
|
||||
|
||||
model_config = {"extra": "ignore"}
|
||||
@@ -215,11 +221,203 @@ class OpenAICompatibleImageProvider:
|
||||
return {"data": data, "mime_type": mime_type, "alt": alt, "prompt": prompt}
|
||||
|
||||
|
||||
class DashScopeNativeImageProvider:
|
||||
"""Generate report illustrations through DashScope's native image API.
|
||||
|
||||
Qwen Image 3.0 and Wan 2.7 do not implement the OpenAI
|
||||
``/images/generations`` request/response contract. They receive a
|
||||
multimodal ``input.messages`` payload and normally return a short-lived
|
||||
image URL. The URL is downloaded immediately so the research report keeps
|
||||
a protected local artifact, just like the OpenAI-compatible provider.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: ImageGenerationSettings,
|
||||
*,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
) -> None:
|
||||
if not settings.is_configured:
|
||||
raise ValueError("Image generation provider is not configured")
|
||||
self._settings = settings
|
||||
self._transport = transport
|
||||
|
||||
async def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
*,
|
||||
section_id: str = "",
|
||||
user_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
del user_id # Credentials are deployment-scoped; users never supply them.
|
||||
body = _dashscope_request_body(self._settings, prompt)
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self._settings.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=self._settings.timeout_seconds,
|
||||
transport=self._transport,
|
||||
follow_redirects=True,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
_dashscope_generation_endpoint(self._settings.base_url),
|
||||
json=body,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
encoded, image_url, mime_type = _dashscope_image_result(payload)
|
||||
if encoded:
|
||||
data = _decode_image_base64(encoded)
|
||||
elif image_url:
|
||||
data, mime_type = await _download_dashscope_image(client, image_url, mime_type)
|
||||
else:
|
||||
raise ImageGenerationError("千问图片生成服务未返回图片地址或图片数据")
|
||||
except ImageGenerationError:
|
||||
raise
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ImageGenerationError("图片生成服务响应超时") from exc
|
||||
except httpx.HTTPStatusError as exc:
|
||||
raise ImageGenerationError(_http_error_message(exc.response)) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ImageGenerationError("图片生成服务暂时不可用") from exc
|
||||
except ValueError as exc:
|
||||
raise ImageGenerationError("图片生成服务返回了无效响应") from exc
|
||||
|
||||
if not data or len(data) > _MAX_IMAGE_BYTES:
|
||||
raise ImageGenerationError("生成图片为空或超过大小限制")
|
||||
alt = f"{section_id or '研究报告'}配图"
|
||||
return {"data": data, "mime_type": _normalise_mime_type(mime_type), "alt": alt, "prompt": prompt}
|
||||
|
||||
|
||||
def _dashscope_generation_endpoint(base_url: str) -> str:
|
||||
"""Resolve a native DashScope endpoint without relying on a workspace id.
|
||||
|
||||
Token Plan deployments commonly expose the full native endpoint, while
|
||||
regular DashScope configuration often uses just an API origin. Supporting
|
||||
both avoids an accidental ``.../generation/images/generations`` path.
|
||||
"""
|
||||
|
||||
base = base_url.rstrip("/")
|
||||
if base.endswith(_DASHSCOPE_GENERATION_PATH):
|
||||
return base
|
||||
parsed = urlparse(base)
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
return base
|
||||
return f"{parsed.scheme}://{parsed.netloc}{_DASHSCOPE_GENERATION_PATH}"
|
||||
|
||||
|
||||
def _dashscope_request_body(settings: ImageGenerationSettings, prompt: str) -> dict[str, Any]:
|
||||
parameters: dict[str, Any] = {
|
||||
"n": 1,
|
||||
"size": settings.size.replace("x", "*").replace("X", "*"),
|
||||
"watermark": settings.watermark,
|
||||
}
|
||||
# ``prompt_extend`` is a Qwen Image-only parameter. Wan 2.7 rejects
|
||||
# unrelated generation options, so do not send it there.
|
||||
if settings.model.strip().lower().startswith("qwen-image-"):
|
||||
parameters["prompt_extend"] = True
|
||||
return {
|
||||
"model": settings.model,
|
||||
"input": {
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [{"text": prompt}],
|
||||
}
|
||||
]
|
||||
},
|
||||
"parameters": parameters,
|
||||
}
|
||||
|
||||
|
||||
def _dashscope_image_result(payload: object) -> tuple[str, str, str]:
|
||||
"""Return optional base64, image URL and MIME type from native output."""
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
return "", "", ""
|
||||
output = payload.get("output")
|
||||
choices = output.get("choices") if isinstance(output, dict) else None
|
||||
if not isinstance(choices, list):
|
||||
return "", "", ""
|
||||
for choice in choices:
|
||||
message = choice.get("message") if isinstance(choice, dict) else None
|
||||
content = message.get("content") if isinstance(message, dict) else None
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for part in content:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
encoded = str(part.get("b64_json") or "")
|
||||
raw_image_url = part.get("image") or part.get("image_url")
|
||||
if isinstance(raw_image_url, dict):
|
||||
raw_image_url = raw_image_url.get("url")
|
||||
image_url = str(raw_image_url or "")
|
||||
if encoded or image_url:
|
||||
return encoded, image_url, str(part.get("mime_type") or "")
|
||||
return "", "", ""
|
||||
|
||||
|
||||
async def _download_dashscope_image(
|
||||
client: httpx.AsyncClient,
|
||||
image_url: str,
|
||||
mime_type: str,
|
||||
) -> tuple[bytes, str]:
|
||||
"""Download only an HTTPS model result, never forwarding the API key."""
|
||||
|
||||
parsed = urlparse(image_url)
|
||||
if parsed.scheme != "https" or not parsed.netloc:
|
||||
raise ImageGenerationError("千问图片生成服务返回了不安全的图片地址")
|
||||
response = await client.get(image_url, headers={"Accept": "image/png,image/jpeg,image/webp"})
|
||||
response.raise_for_status()
|
||||
final_url = urlparse(str(response.url))
|
||||
if final_url.scheme != "https" or not final_url.netloc:
|
||||
raise ImageGenerationError("千问图片下载地址不安全")
|
||||
response_mime_type = response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
||||
return response.content, response_mime_type or mime_type
|
||||
|
||||
|
||||
def _decode_image_base64(encoded: str) -> bytes:
|
||||
if encoded.startswith("data:") and "," in encoded:
|
||||
encoded = encoded.split(",", 1)[1]
|
||||
try:
|
||||
return base64.b64decode(encoded, validate=True)
|
||||
except (ValueError, binascii.Error) as exc:
|
||||
raise ImageGenerationError("图片生成服务返回的图片编码无效") from exc
|
||||
|
||||
|
||||
def _normalise_mime_type(value: str) -> str:
|
||||
mime_type = value.lower()
|
||||
return mime_type if mime_type in {"image/png", "image/jpeg", "image/webp"} else "image/png"
|
||||
|
||||
|
||||
def _http_error_message(response: httpx.Response) -> str:
|
||||
"""Expose a short provider message without leaking credentials or payloads."""
|
||||
|
||||
detail = ""
|
||||
try:
|
||||
payload = response.json()
|
||||
if isinstance(payload, dict):
|
||||
error = payload.get("error")
|
||||
source = error if isinstance(error, dict) else payload
|
||||
message = source.get("message") if isinstance(source, dict) else None
|
||||
if isinstance(message, str) and message.strip():
|
||||
detail = f":{message.strip()[:300]}"
|
||||
except ValueError:
|
||||
pass
|
||||
return f"图片生成服务返回 HTTP {response.status_code}{detail}"
|
||||
|
||||
|
||||
def build_image_provider() -> ImageProvider:
|
||||
"""Build the optional provider from server config, or a safe no-op."""
|
||||
settings = ImageGenerationSettings.from_app_config()
|
||||
if not settings.is_configured:
|
||||
return NullImageProvider()
|
||||
if settings.provider == "dashscope_native":
|
||||
return DashScopeNativeImageProvider(settings)
|
||||
return OpenAICompatibleImageProvider(settings)
|
||||
|
||||
|
||||
@@ -229,5 +427,6 @@ __all__ = [
|
||||
"ImageProvider",
|
||||
"NullImageProvider",
|
||||
"OpenAICompatibleImageProvider",
|
||||
"DashScopeNativeImageProvider",
|
||||
"build_image_provider",
|
||||
]
|
||||
+46
-22
@@ -33,6 +33,7 @@ from deerflow.agents.deep_research.cancellation import CancellationToken
|
||||
from deerflow.agents.deep_research.config import DeepResearchConfig, ModelRole
|
||||
from deerflow.agents.deep_research.events import EventSink
|
||||
from deerflow.agents.deep_research.types import CompletionResult
|
||||
from deerflow.utils.stream_text import InlineThinkTagFilter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from langchain.chat_models import BaseChatModel
|
||||
@@ -83,6 +84,16 @@ def _content_to_text(resp: Any) -> str:
|
||||
if isinstance(block, str):
|
||||
parts.append(block)
|
||||
elif isinstance(block, dict):
|
||||
# Never fall through to ``content`` for structured reasoning
|
||||
# blocks. Providers differ here, but those blocks are not
|
||||
# report prose and must not reach ReportChunkEmitter.
|
||||
if block.get("type") in {
|
||||
"thinking",
|
||||
"thinking_delta",
|
||||
"reasoning",
|
||||
"reasoning_delta",
|
||||
}:
|
||||
continue
|
||||
parts.append(str(block.get("text") or block.get("content") or ""))
|
||||
return "".join(parts)
|
||||
return str(content or "")
|
||||
@@ -99,7 +110,20 @@ def _reasoning_delta(chunk: Any) -> str:
|
||||
"""
|
||||
ak = getattr(chunk, "additional_kwargs", None) or {}
|
||||
val = ak.get("reasoning_content") or ak.get("reasoning") or ""
|
||||
return val if isinstance(val, str) else ""
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
# Anthropic/OpenAI-compatible adapters may put the same increment in an
|
||||
# explicitly typed content block instead of ``additional_kwargs``.
|
||||
content = getattr(chunk, "content", None)
|
||||
if isinstance(content, list):
|
||||
parts = [
|
||||
str(block.get("text") or block.get("content") or "")
|
||||
for block in content
|
||||
if isinstance(block, dict)
|
||||
and block.get("type") in {"thinking", "thinking_delta", "reasoning", "reasoning_delta"}
|
||||
]
|
||||
return "".join(parts)
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_usage(resp: Any) -> dict[str, Any]:
|
||||
@@ -234,9 +258,7 @@ class DeerFlowCompletionBackend:
|
||||
parsed = _try_parse_structured(text, response_schema)
|
||||
if parsed is not None:
|
||||
await self._record_usage(model_name, operation, usage)
|
||||
return CompletionResult(
|
||||
text=text, model=model_name, usage=usage, structured=parsed
|
||||
)
|
||||
return CompletionResult(text=text, model=model_name, usage=usage, structured=parsed)
|
||||
if attempt == 0:
|
||||
# One repair re-prompt (§9.5).
|
||||
logger.warning("deep_research llm: JSON parse failed for %s, retrying", operation)
|
||||
@@ -306,13 +328,20 @@ 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)
|
||||
delta = _content_to_text(chunk)
|
||||
# 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:
|
||||
@@ -321,6 +350,14 @@ class DeerFlowCompletionBackend:
|
||||
if any(chunk_usage.values()):
|
||||
usage = chunk_usage
|
||||
|
||||
tail, inline_reasoning_tail = inline_think_filter.finish_parts()
|
||||
if inline_reasoning_tail and on_reasoning is not None:
|
||||
await on_reasoning(inline_reasoning_tail)
|
||||
if tail:
|
||||
text_parts.append(tail)
|
||||
if on_delta is not None:
|
||||
await on_delta(tail)
|
||||
|
||||
await self._record_usage(model_name, operation, usage)
|
||||
return CompletionResult(text="".join(text_parts), model=model_name, usage=usage)
|
||||
|
||||
@@ -328,9 +365,7 @@ class DeerFlowCompletionBackend:
|
||||
|
||||
async def _record_usage(self, model_name: str, operation: str, usage: dict[str, Any]) -> None:
|
||||
"""Accumulate per-model totals + emit a ``model_usage`` event."""
|
||||
bucket = self._usage_totals.setdefault(
|
||||
model_name, {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
|
||||
)
|
||||
bucket = self._usage_totals.setdefault(model_name, {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0})
|
||||
for k in bucket:
|
||||
bucket[k] += int(usage.get(k, 0) or 0)
|
||||
|
||||
@@ -390,10 +425,7 @@ def _schema_instructions(schema: type[BaseModel]) -> str:
|
||||
"""Build a compact "respond as JSON matching this schema" instruction."""
|
||||
props = schema.model_json_schema().get("properties", {})
|
||||
fields = ", ".join(f'"{k}"' for k in props)
|
||||
return (
|
||||
"Respond with ONLY a valid JSON object (no markdown, no prose) "
|
||||
f"containing these keys: {fields}."
|
||||
)
|
||||
return f"Respond with ONLY a valid JSON object (no markdown, no prose) containing these keys: {fields}."
|
||||
|
||||
|
||||
def _inject_schema_hint(messages: list[BaseMessage], hint: str) -> list[BaseMessage]:
|
||||
@@ -403,21 +435,13 @@ def _inject_schema_hint(messages: list[BaseMessage], hint: str) -> list[BaseMess
|
||||
return [*messages, SystemMessage(content=hint)]
|
||||
|
||||
|
||||
def _inject_repair_hint(
|
||||
messages: list[BaseMessage], bad_text: str, schema: type[BaseModel]
|
||||
) -> list[BaseMessage]:
|
||||
def _inject_repair_hint(messages: list[BaseMessage], bad_text: str, schema: type[BaseModel]) -> list[BaseMessage]:
|
||||
"""Re-prompt: 'your last reply was invalid JSON, fix it'."""
|
||||
from langchain_core.messages import HumanMessage
|
||||
|
||||
return [
|
||||
*messages,
|
||||
HumanMessage(
|
||||
content=(
|
||||
"Your previous reply was not valid JSON and could not be parsed:\n"
|
||||
f"{bad_text[:500]}\n\n"
|
||||
"Please respond again with ONLY a valid JSON object."
|
||||
)
|
||||
),
|
||||
HumanMessage(content=(f"Your previous reply was not valid JSON and could not be parsed:\n{bad_text[:500]}\n\nPlease respond again with ONLY a valid JSON object.")),
|
||||
]
|
||||
|
||||
|
||||
|
||||
+5
@@ -63,6 +63,11 @@ ALL_PHASES: tuple[ResearchPhase, ...] = (
|
||||
|
||||
EventType = Literal[
|
||||
"job_status",
|
||||
# Terminal events are kept separate from job_status for the historical
|
||||
# event timeline. The executor persists these after the DB state has
|
||||
# been committed, so a reconnecting browser receives an explicit end.
|
||||
"job_completed",
|
||||
"job_failed",
|
||||
"phase_changed",
|
||||
"plan_created",
|
||||
"queries_planned",
|
||||
|
||||
+1
@@ -364,6 +364,7 @@ class BasicRunner:
|
||||
messages=[{"role": "system", "content": _SYSTEM}, {"role": "user", "content": prompt}],
|
||||
operation="write_report",
|
||||
on_delta=emitter.add,
|
||||
on_reasoning=emitter.add_thinking,
|
||||
)
|
||||
await emitter.flush()
|
||||
return result.text
|
||||
|
||||
+3
@@ -338,6 +338,7 @@ class DetailedRunner(BasicRunner):
|
||||
],
|
||||
operation="write_detailed_introduction",
|
||||
on_delta=emitter.add,
|
||||
on_reasoning=emitter.add_thinking,
|
||||
)
|
||||
await emitter.flush()
|
||||
return result.text
|
||||
@@ -373,6 +374,7 @@ class DetailedRunner(BasicRunner):
|
||||
],
|
||||
operation="write_detailed_section",
|
||||
on_delta=emitter.add,
|
||||
on_reasoning=emitter.add_thinking,
|
||||
)
|
||||
await emitter.flush()
|
||||
return result.text
|
||||
@@ -389,6 +391,7 @@ class DetailedRunner(BasicRunner):
|
||||
],
|
||||
operation="write_detailed_conclusion",
|
||||
on_delta=emitter.add,
|
||||
on_reasoning=emitter.add_thinking,
|
||||
)
|
||||
await emitter.flush()
|
||||
return result.text
|
||||
|
||||
+20
-3
@@ -64,6 +64,7 @@ async def generate_report_images(
|
||||
)
|
||||
image_paths: dict[str, str] = {}
|
||||
amended_report = report_markdown
|
||||
total = len(sections)
|
||||
|
||||
for position, section in enumerate(sections, 1):
|
||||
if cancellation is not None:
|
||||
@@ -72,7 +73,7 @@ async def generate_report_images(
|
||||
await adapters.events.emit(
|
||||
"image_generation_started",
|
||||
phase="illustrating",
|
||||
payload={"section": section, "position": position},
|
||||
payload={"section": section, "position": position, "total": total},
|
||||
)
|
||||
try:
|
||||
generated = await adapters.images.generate(
|
||||
@@ -95,13 +96,26 @@ async def generate_report_images(
|
||||
await adapters.events.emit(
|
||||
"image_generated",
|
||||
phase="illustrating",
|
||||
payload={"section": section, "position": position, "name": name, "alt": alt},
|
||||
payload={
|
||||
"section": section,
|
||||
"position": position,
|
||||
"total": total,
|
||||
"name": name,
|
||||
"alt": alt,
|
||||
},
|
||||
)
|
||||
except ImageGenerationError as exc:
|
||||
await adapters.events.emit(
|
||||
"warning",
|
||||
phase="illustrating",
|
||||
payload={"code": "image_generation_failed", "message": str(exc), "recoverable": True},
|
||||
payload={
|
||||
"code": "image_generation_failed",
|
||||
"message": str(exc),
|
||||
"recoverable": True,
|
||||
"section": section,
|
||||
"position": position,
|
||||
"total": total,
|
||||
},
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
# Third-party image APIs and artifact storage must never turn a
|
||||
@@ -114,6 +128,9 @@ async def generate_report_images(
|
||||
"code": "image_generation_failed",
|
||||
"message": "报告配图生成失败,已继续保留文字报告",
|
||||
"recoverable": True,
|
||||
"section": section,
|
||||
"position": position,
|
||||
"total": total,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
+1
@@ -321,6 +321,7 @@ class MultiAgentRunner(BasicRunner):
|
||||
],
|
||||
operation="revise_multi_agent_report",
|
||||
on_delta=emitter.add,
|
||||
on_reasoning=emitter.add_thinking,
|
||||
)
|
||||
await emitter.flush()
|
||||
return {"report": result.text, "revision_count": int(state.get("revision_count") or 0) + 1}
|
||||
|
||||
+14
@@ -64,6 +64,20 @@ class ReportChunkEmitter:
|
||||
await self._emit(self._buffer[: self._chunk_size])
|
||||
self._buffer = self._buffer[self._chunk_size :]
|
||||
|
||||
async def add_thinking(self, delta: str) -> None:
|
||||
"""Forward reasoning to the live UI without persisting it as report text."""
|
||||
if not delta:
|
||||
return
|
||||
await self._events.publish_live(
|
||||
"report_thinking",
|
||||
phase=self._phase,
|
||||
payload={
|
||||
"delta": delta,
|
||||
"target": self._target,
|
||||
"reportVersion": self._report_version,
|
||||
},
|
||||
)
|
||||
|
||||
async def flush(self) -> None:
|
||||
"""Persist the final tail once the model stream has finished."""
|
||||
if self._buffer:
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Safe helpers for provider text streams.
|
||||
|
||||
Some OpenAI-compatible providers place reasoning in the normal ``content``
|
||||
stream as ``<think>...</think>`` instead of using LangChain's dedicated
|
||||
reasoning fields. Those fragments must be separated from report/file content
|
||||
while callers can still surface them in an explicitly marked live UI trace.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class InlineThinkTagFilter:
|
||||
"""Separate inline ``<think>`` blocks while preserving token streaming.
|
||||
|
||||
Tags can be split across arbitrary provider chunks, so regex-per-chunk is
|
||||
not safe: it can leak a partial tag or the model's reasoning into the
|
||||
visible draft. This small state machine holds only the suffix that might
|
||||
still form a tag and emits all confirmed answer text immediately.
|
||||
"""
|
||||
|
||||
_OPEN_TAG = "<think>"
|
||||
_CLOSE_TAG = "</think>"
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._inside_think = False
|
||||
self._pending = ""
|
||||
|
||||
@staticmethod
|
||||
def _possible_tag_prefix_size(content: str, tag: str) -> int:
|
||||
"""Return the longest suffix which may become the next tag."""
|
||||
lowered = content.lower()
|
||||
for size in range(min(len(content), len(tag) - 1), 0, -1):
|
||||
if lowered[-size:] == tag[:size]:
|
||||
return size
|
||||
return 0
|
||||
|
||||
def push_parts(self, chunk: str) -> tuple[str, str]:
|
||||
"""Return ``(visible_text, thinking_text)`` for one provider chunk."""
|
||||
if not chunk:
|
||||
return "", ""
|
||||
|
||||
remaining = self._pending + chunk
|
||||
self._pending = ""
|
||||
visible: list[str] = []
|
||||
thinking: list[str] = []
|
||||
|
||||
while remaining:
|
||||
tag = self._CLOSE_TAG if self._inside_think else self._OPEN_TAG
|
||||
marker_at = remaining.lower().find(tag)
|
||||
if marker_at >= 0:
|
||||
(thinking if self._inside_think else visible).append(remaining[:marker_at])
|
||||
remaining = remaining[marker_at + len(tag) :]
|
||||
self._inside_think = not self._inside_think
|
||||
continue
|
||||
|
||||
suffix_size = self._possible_tag_prefix_size(remaining, tag)
|
||||
confirmed = remaining[:-suffix_size] if suffix_size else remaining
|
||||
(thinking if self._inside_think else visible).append(confirmed)
|
||||
self._pending = remaining[-suffix_size:] if suffix_size else ""
|
||||
break
|
||||
|
||||
return "".join(visible), "".join(thinking)
|
||||
|
||||
def push(self, chunk: str) -> str:
|
||||
"""Compatibility helper returning only confirmed visible text."""
|
||||
return self.push_parts(chunk)[0]
|
||||
|
||||
def finish_parts(self) -> tuple[str, str]:
|
||||
"""Flush the remaining visible or thinking text at end of stream."""
|
||||
if self._inside_think:
|
||||
thinking = self._pending
|
||||
self._pending = ""
|
||||
self._inside_think = False
|
||||
return "", thinking
|
||||
tail = self._pending
|
||||
self._pending = ""
|
||||
return tail, ""
|
||||
|
||||
def finish(self) -> str:
|
||||
"""Compatibility helper returning only the visible stream tail."""
|
||||
return self.finish_parts()[0]
|
||||
|
||||
|
||||
def strip_inline_think_tags(content: str) -> str:
|
||||
"""Return complete text with inline model-thinking blocks removed."""
|
||||
text_filter = InlineThinkTagFilter()
|
||||
return text_filter.push(content) + text_filter.finish()
|
||||
|
||||
|
||||
__all__ = ["InlineThinkTagFilter", "strip_inline_think_tags"]
|
||||
@@ -38,17 +38,27 @@ class _ChainStore:
|
||||
return self.chain
|
||||
|
||||
|
||||
class _AgentStore:
|
||||
def __init__(self, agents: dict[str, dict[str, object]] | None = None) -> None:
|
||||
self.agents = agents or {}
|
||||
|
||||
async def get_any(self, agent_id: str) -> dict[str, object] | None:
|
||||
return self.agents.get(agent_id)
|
||||
|
||||
|
||||
def _request(
|
||||
role: str,
|
||||
chain: dict[str, object] | None = None,
|
||||
*,
|
||||
email: str = "lqq@example.com",
|
||||
agents: dict[str, dict[str, object]] | None = None,
|
||||
):
|
||||
return SimpleNamespace(
|
||||
app=SimpleNamespace(
|
||||
state=SimpleNamespace(
|
||||
business_mapping_store=_MappingStore(),
|
||||
roundtable_chain_store=_ChainStore(chain),
|
||||
agent_store=_AgentStore(agents),
|
||||
)
|
||||
),
|
||||
state=SimpleNamespace(user=SimpleNamespace(id="admin-id", email=email, system_role=role)),
|
||||
@@ -130,3 +140,34 @@ async def test_global_mapping_rejects_a_private_chain() -> None:
|
||||
|
||||
assert error.value.status_code == 400
|
||||
assert request.app.state.business_mapping_store.calls == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_global_mapping_rejects_a_chain_with_an_unpublished_agent_seat() -> None:
|
||||
request = _request(
|
||||
"admin",
|
||||
{
|
||||
"id": "chain-8bf",
|
||||
"title": "岗位协同链",
|
||||
"is_public": True,
|
||||
"seats": [
|
||||
{"agent_id": "published", "name": "已发布智能体"},
|
||||
{"agent_id": "private", "name": "未发布智能体"},
|
||||
],
|
||||
},
|
||||
agents={
|
||||
"published": {"id": "published", "user_id": "owner", "published": True, "is_private": False},
|
||||
"private": {"id": "private", "user_id": "owner", "published": False, "is_private": False},
|
||||
},
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
await business_mapping_router.update_mapping(
|
||||
request,
|
||||
"8BF",
|
||||
business_mapping_router.BusinessMappingUpdateRequest(chain_id="chain-8bf"),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 400
|
||||
assert "未发布智能体" in error.value.detail
|
||||
assert request.app.state.business_mapping_store.calls == []
|
||||
@@ -4,6 +4,7 @@ import pytest
|
||||
|
||||
from app.gateway import deep_research_job_executor as executor_module
|
||||
from app.gateway.deep_research_job_executor import DeepResearchJobExecutor
|
||||
from deerflow.agents.deep_research.events import DeepResearchEvent
|
||||
from deerflow.agents.deep_research.types import DeepResearchResult
|
||||
|
||||
|
||||
@@ -64,3 +65,8 @@ async def test_report_projection_failure_never_marks_job_completed(monkeypatch):
|
||||
)
|
||||
|
||||
assert jobs.progress_calls == []
|
||||
|
||||
|
||||
def test_terminal_timeline_events_are_valid_durable_event_types():
|
||||
assert DeepResearchEvent(type="job_completed", phase="done").type == "job_completed"
|
||||
assert DeepResearchEvent(type="job_failed", phase="done").type == "job_failed"
|
||||
@@ -117,6 +117,61 @@ async def test_queued_job_still_starts_when_session_projection_temporarily_fails
|
||||
assert dispatcher.nudges == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_report_card_can_enable_images_after_collection(monkeypatch):
|
||||
"""The write-time card override must win over the collection-time default."""
|
||||
|
||||
async def fake_require_user(request): # noqa: ANN001
|
||||
return "u1"
|
||||
|
||||
class _ChatSessionStore(_SessionStore):
|
||||
async def get(self, session_id: str, *, user_id: str): # noqa: ARG002
|
||||
return {
|
||||
"id": session_id,
|
||||
"query": "测试主题",
|
||||
"title": "测试主题",
|
||||
"runtime_thread_id": "collector-thread",
|
||||
"config_snapshot": {
|
||||
"mode": "basic",
|
||||
"collection_mode": "chat",
|
||||
"generate_images": False,
|
||||
"max_generated_images": 2,
|
||||
},
|
||||
}
|
||||
|
||||
class _CapturingJobStore(_JobStore):
|
||||
def __init__(self) -> None:
|
||||
self.created: dict | None = None
|
||||
|
||||
async def try_create_or_get_active(self, **kwargs): # noqa: ANN003
|
||||
self.created = kwargs
|
||||
return {"id": "drj_images", "status": "queued"}, True
|
||||
|
||||
monkeypatch.setattr(deep_research, "_require_user", fake_require_user)
|
||||
sessions = _ChatSessionStore()
|
||||
jobs = _CapturingJobStore()
|
||||
response = await deep_research.start_job(
|
||||
"drs_1",
|
||||
deep_research.StartJobRequest(
|
||||
entry="chat",
|
||||
config={"generate_images": True, "max_generated_images": 3},
|
||||
),
|
||||
_request(sessions=sessions, jobs=jobs, dispatcher=_Dispatcher()),
|
||||
)
|
||||
|
||||
assert response["jobId"] == "drj_images"
|
||||
assert jobs.created is not None
|
||||
snapshot = jobs.created["input_snapshot"]["config"]
|
||||
assert snapshot["generate_images"] is True
|
||||
assert snapshot["max_generated_images"] == 3
|
||||
# The session snapshot is persisted too, so a reload/replay keeps the
|
||||
# write-time choice instead of reverting to the creation-time false.
|
||||
assert any(
|
||||
update.get("config_snapshot", {}).get("generate_images") is True
|
||||
for update in sessions.updates
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_stays_open_when_durable_replay_has_a_transient_failure(monkeypatch):
|
||||
"""A stream DB blip must yield a recoverable warning, not an ASGI error group."""
|
||||
|
||||
@@ -206,14 +206,14 @@ def test_position_intent_prompt_keeps_the_original_step_one_guardrails():
|
||||
assert phrase in prompt
|
||||
|
||||
|
||||
def test_position_intent_clarification_waits_for_the_user_before_ready():
|
||||
"""A same-run READY block must not consume the user-assistance pause."""
|
||||
def test_fresh_intent_clarification_waits_for_the_user_before_ready():
|
||||
"""A same-run READY block must not consume a fresh assistance pause."""
|
||||
assert intent_router._clarification_blocks_ready(
|
||||
intent_router.POSITION_INTENT_AGENT_ID,
|
||||
{"name": "ask_clarification"},
|
||||
is_fresh=True,
|
||||
)
|
||||
assert not intent_router._clarification_blocks_ready(
|
||||
assert intent_router._clarification_blocks_ready(
|
||||
intent_router.INTENT_AGENT_ID,
|
||||
{"name": "ask_clarification"},
|
||||
is_fresh=True,
|
||||
|
||||
Reference in new issue
Block a user