JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(skill_turbo): 修复文档转 PPT 时解析错误被当作正文
xiaowenzihwl7d680cce41c9
diff --git a/jiuwenswarm/agents/harness/common/rails/read_file_validation.py b/jiuwenswarm/agents/harness/common/rails/read_file_validation.pyindex 10a251584d..f9791999ab 100644--- a/jiuwenswarm/agents/harness/common/rails/read_file_validation.py+++ b/jiuwenswarm/agents/harness/common/rails/read_file_validation.py@@ -9,7 +9,7 @@ import osfrom typing import Any, TYPE_CHECKINGif TYPE_CHECKING:- from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ToolCallInputs+ from openjiuwen.core.single_agent.rail.base import AgentCallbackContextREAD_FILE_TOOL_NAMES = frozenset({@@ -45,7 +45,6 @@ _IMAGE_EXTENSIONS = frozenset(_NON_TEXT_EXTENSIONS = frozenset({- ".pdf",".zip",".gz",".bz2",diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/document_parse.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/document_parse.pyindex c00213cd0d..6736ac8b45 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/document_parse.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/document_parse.py@@ -1,7 +1,5 @@from __future__ import annotations-import json-import refrom collections.abc import AsyncIteratorfrom pathlib import Pathfrom typing import Any@@ -15,8 +13,6 @@ _DOC_RAW_NAME = "doc_raw.md"_MAX_PARSE_ATTEMPTS = 2_DOC_EXCERPT_MAX_CHARS = 8000_PDF_BATCH_SIZE = 10-# Keep in sync with agent-core ReadFileTool.MAX_PDF_SIZE_BYTES_WITHOUT_PAGES (10 MB).-_PDF_LARGE_FILE_BYTES = 10 * 1024 * 1024_PDF_MAX_AUTO_PARSE_PAGES = 200_PDF_TRUNCATION_MARKER = ("\n\n---\n"@@ -53,6 +49,9 @@ def _normalize_tool_text(result: Any) -> str:if isinstance(result, str):return _strip_line_numbers(result)if isinstance(result, dict):+ if result.get("success") is False:+ error = result.get("error") or result.get("message") or "工具调用失败"+ return f"[ERROR]: {error}"for key in ("content", "output", "result", "stdout", "text", "answer"):value = result.get(key)if isinstance(value, str) and value.strip():@@ -63,10 +62,12 @@ def _normalize_tool_text(result: Any) -> str:value = data.get(key)if isinstance(value, str) and value.strip():return _strip_line_numbers(value)- if result.get("success") is False:- error = result.get("error") or result.get("message")- if isinstance(error, str):- return f"[ERROR]: {error}"+ if hasattr(result, "success") and result.success is False:+ error = result.error if hasattr(result, "error") else None+ if not error and hasattr(result, "message"):+ error = result.message+ error = error or "工具调用失败"+ return f"[ERROR]: {error}"if hasattr(result, "data"):data_attr = result.dataif isinstance(data_attr, dict):@@ -79,6 +80,10 @@ def _normalize_tool_text(result: Any) -> str:return _strip_line_numbers(str(result))+def _is_tool_error_text(text: str) -> bool:+ return text.lstrip().startswith(("[ERROR]", "[READ_FILE_ERROR]", "[PDF_READ_ERROR]"))++def _extract_vqa_ocr_section(text: str) -> str:if not text:return ""@@ -207,7 +212,7 @@ class DocumentParseNode(PlanNode):raise DocumentParseError("read_file 工具未注册")raw = await self.call_tool("read_file", file_path=str(path))text = _normalize_tool_text(raw).strip()- if text.startswith("[ERROR]"):+ if _is_tool_error_text(text):raise DocumentParseError(text)if not text:raise DocumentParseError(f"read_file 返回空内容: {path}")@@ -232,10 +237,13 @@ class DocumentParseNode(PlanNode):return "\n\n".join(parts)raise DocumentParseError(text)- if "CODE=PDF_PAGE_RANGE_OUT_OF_BOUNDS" in text:+ if (+ "CODE=PDF_PAGE_RANGE_OUT_OF_BOUNDS" in text+ or "Invalid or empty PDF page range" in text+ ):return None- if text.startswith("[ERROR]") or text.startswith("[PDF_READ_ERROR]"):+ if _is_tool_error_text(text):raise DocumentParseError(text)return text@@ -294,7 +302,7 @@ class DocumentParseNode(PlanNode):try:if _is_image_path(path):content = await self._read_image_file(path)- elif _is_pdf_path(path) and path.stat().st_size > _PDF_LARGE_FILE_BYTES:+ elif _is_pdf_path(path):content = await self._read_large_pdf_file(path)else:content = await self._read_text_file(path)diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.pyindex c44731caf9..205158cffb 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.py@@ -33,6 +33,25 @@ _P3_SKIP_FIELDS = {}+def _document_parse_failed(inputs: dict[str, Any]) -> bool:+ return bool(inputs.get("has_documents")) and inputs.get("doc_parse_ok") is not True+++def _document_parse_failure_result(+ node: str,+ inputs: dict[str, Any],+ results: list[dict[str, Any]],+) -> dict[str, Any]:+ error = inputs.get("doc_parse_error") or "未知原因"+ return {+ "node": node,+ "status": "error",+ "message": f"文档解析失败,已停止生成 PPT:{error}",+ "result": inputs,+ "steps": results,+ }++_MERGE_SKIP_KEYS = frozenset({"node",@@ -147,6 +166,8 @@ class PPTGenRootNode(PlanNode):await self._run_subplan(self._p3, inputs, results)else:await self._skip_p3_subplan(inputs, results)+ if _document_parse_failed(inputs):+ returnawait self._run_subplan(self._p2, inputs, results)async def _execute(self, inputs: dict[str, Any]) -> dict[str, Any]:@@ -157,6 +178,9 @@ class PPTGenRootNode(PlanNode):await self._run_subplan(self._p1, inputs, results)await self._run_p3_and_p2(inputs, results)+ if _document_parse_failed(inputs):+ return _document_parse_failure_result(self.plan_name, inputs, results)+# P3.5 模板叙事上下文预处理(条件执行,节点内部判断 style_mode)await self._run_subplan(self._p3_5, inputs, results)@@ -315,6 +339,9 @@ class PPTGenRootNode(PlanNode):):yield chunk+ if _document_parse_failed(inputs):+ return+async for chunk in self._run_subplan_stream(self._p2, inputs, results, index=4, total_steps=total_steps):@@ -347,6 +374,10 @@ class PPTGenRootNode(PlanNode):async for chunk in self._run_p3_and_p2_stream(inputs, results, total_steps=total_steps):yield chunk+ if _document_parse_failed(inputs):+ yield _document_parse_failure_result(self.plan_name, inputs, results)+ return+# P3.5 模板叙事上下文预处理(条件执行,节点内部判断 style_mode)async for chunk in self._run_subplan_stream(self._p3_5, inputs, results, index=5, total_steps=total_steps,diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_document_parse.py b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_document_parse.pynew file mode 100644index 0000000000..a8edd3f4c9--- /dev/null+++ b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_document_parse.py@@ -0,0 +1,171 @@+from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from jiuwenswarm.agents.harness.common.rails.read_file_validation import (+ is_non_text_file_path,+ validate_read_file_result,+)+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt import document_parse+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.document_parse import (+ DocumentParseNode,+ _normalize_tool_text,+)+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import (+ PPTGenRootNode,+)+from jiuwenswarm.server.runtime.skill_turbo.validator import PlanCodeValidator+++def test_document_parse_passes_builtin_skill_validation() -> None:+ source = Path(document_parse.__file__).read_text(encoding="utf-8")+ validator = PlanCodeValidator.for_builtin_skill_code(+ ["jiuwenswarm.server.runtime.skill_turbo.skill_codes"]+ )++ assert validator.validate(source) == []+++def test_pdf_is_delegated_to_read_file() -> None:+ assert is_non_text_file_path("report.pdf") is False+ assert validate_read_file_result("report.pdf", "extracted PDF text") == (True, None)+++def test_normalize_tool_text_preserves_object_failure() -> None:+ result = SimpleNamespace(success=False, data=None, error="read failed")++ assert _normalize_tool_text(result) == "[ERROR]: read failed"+++async def test_document_parse_marks_tool_output_failure_as_read_failure(+ tmp_path: Path, monkeypatch+) -> None:+ source = tmp_path / "source.docx"+ source.write_bytes(b"placeholder")+ node = DocumentParseNode()+ result = SimpleNamespace(success=False, data=None, error="read failed")++ monkeypatch.setattr(node, "has_tool", lambda _name: True)++ async def call_tool(_name: str, **_kwargs: Any) -> Any:+ return result++ monkeypatch.setattr(node, "call_tool", call_tool)++ _, content = await node._read_single_document(source)++ assert content == "[读取失败: [ERROR]: read failed]"+++async def test_document_parse_reads_pdf_in_page_batches(+ tmp_path: Path, monkeypatch+) -> None:+ source = tmp_path / "source.pdf"+ source.write_bytes(b"%PDF-placeholder")+ node = DocumentParseNode()++ async def read_pdf(path: Path) -> str:+ assert path == source+ return "PDF content"++ async def reject_text_read(_path: Path) -> str:+ raise AssertionError("PDF must use the paged reader")++ monkeypatch.setattr(node, "_read_large_pdf_file", read_pdf)+ monkeypatch.setattr(node, "_read_text_file", reject_text_read)++ _, content = await node._read_single_document(source)++ assert content == "PDF content"+++async def test_pdf_page_batches_stop_on_agent_core_out_of_range_error(+ tmp_path: Path, monkeypatch+) -> None:+ source = tmp_path / "source.pdf"+ source.write_bytes(b"%PDF-placeholder")+ node = DocumentParseNode()+ calls: list[str] = []++ monkeypatch.setattr(node, "has_tool", lambda _name: True)++ async def call_tool(_name: str, **kwargs: Any) -> Any:+ pages = kwargs["pages"]+ calls.append(pages)+ if pages == "1-10":+ return SimpleNamespace(+ success=True,+ data={"content": "first batch"},+ error=None,+ )+ return SimpleNamespace(+ success=False,+ data=None,+ error=f"Invalid or empty PDF page range: '{pages}'",+ )++ monkeypatch.setattr(node, "call_tool", call_tool)++ content = await node._read_large_pdf_file(source)++ assert content == "first batch"+ assert calls == ["1-10", "11-20"]+++async def test_root_stops_when_all_documents_fail(monkeypatch) -> None:+ root = PPTGenRootNode()+ calls: list[str] = []++ async def run_subplan(subplan, inputs, results) -> None:+ calls.append(subplan.plan_name)+ if subplan is root._p1:+ inputs["has_documents"] = True+ if subplan is root._p3:+ inputs["doc_parse_ok"] = False+ inputs["doc_parse_error"] = "all reads failed"+ results.append({"node": subplan.plan_name, "status": "ok"})++ monkeypatch.setattr(root, "_run_subplan", run_subplan)++ result = await root._execute({})++ assert result["status"] == "error"+ assert "all reads failed" in result["message"]+ assert calls == ["p0_pipeline_init", "p1_intent_classify", "p3_document_parse"]+++async def test_stream_root_stops_when_all_documents_fail(monkeypatch) -> None:+ root = PPTGenRootNode()+ calls: list[str] = []++ async def should_skip(_subplan, _inputs) -> bool:+ return False++ async def run_subplan_stream(subplan, inputs, results, **_kwargs):+ calls.append(subplan.plan_name)+ if subplan is root._p1:+ inputs["has_documents"] = True+ if subplan is root._p3:+ inputs["doc_parse_ok"] = False+ inputs["doc_parse_error"] = "all reads failed"+ result = {"node": subplan.plan_name, "status": "ok"}+ results.append({"node": subplan.plan_name, "status": "ok", "result": result})+ yield result++ monkeypatch.setattr(root, "should_skip_subplan", should_skip)+ monkeypatch.setattr(root, "_run_subplan_stream", run_subplan_stream)++ chunks = [chunk async for chunk in root._execute_stream({})]++ assert chunks[-1]["status"] == "error"+ assert "all reads failed" in chunks[-1]["message"]+ assert calls == ["p0_pipeline_init", "p1_intent_classify", "p3_document_parse"]