Skip to content

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): 修复turbo ppt生图意图识别错误

KevinLLLoveea0dc1dc3673
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/image_prepare.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/image_prepare.py
index edd0dffd18..af9302cc11 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/image_prepare.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/image_prepare.py
@@ -267,18 +267,54 @@ class ImagePrepareNode(PlanNode):
logger.error("[P6.5] output_dir 为空,跳过图片准备")
return {"image_map_path": ""}
- # 生图能力检测:读 P2 写的 imagegen_status.json
- ai_supported = await self._read_imagegen_status(self, output_dir)
- if ai_supported and "ai" not in image_sources:
+ # ── 意图信号:读 P2.4 写的 image_requirements.json ──
+ requirements = await self._read_image_requirements(self, output_dir)
+ if requirements is not None:
+ image_mode = requirements.get("mode", "none")
+ else:
+ # 兼容旧文件:无 image_requirements.json 时读旧 imagegen_status.json
+ legacy = await self._read_imagegen_status(self, output_dir)
+ image_mode = "desired" if legacy else "none"
+
+ # ── 能力信号:真实探测工具(对齐 visual-image.md,supported 语义归 P6.5)──
+ ai_supported = self.has_tool("generate_image")
+ if output_dir:
+ try:
+ content = json.dumps(
+ {"supported": ai_supported, "probe": "has_tool"},
+ ensure_ascii=False,
+ )
+ await PptCommon.write_file(
+ self, f"{output_dir}/imagegen_status.json",
+ content, label="imagegen_status",
+ )
+ logger.info(
+ "[P6.5] imagegen_status.json 已写入 (supported=%s)", ai_supported
+ )
+ except Exception as e:
+ if isinstance(e, AbortError):
+ raise
+ logger.warning("[P6.5] 写 imagegen_status.json 失败: %s", e)
+
+ # ── 门控:双信号(意图 × 能力)──
+ user_wants = image_mode == "desired"
+ if user_wants and ai_supported and "ai" not in image_sources:
image_sources.append("ai")
- logger.info("[P6.5] imagegen_status.supported=true,已添加 ai 源")
+ logger.info("[P6.5] 意图=desired + 工具可用,已添加 ai 源")
- # 门控
local_ok = bool(image_paths)
- ai_ok = "ai" in image_sources and ai_supported
+ ai_ok = user_wants and ai_supported
if not local_ok and not ai_ok:
- logger.info("[P6.5] 无可用图片来源(local=%s, ai=%s),跳过", local_ok, ai_ok)
- return {"image_map_path": ""}
+ if image_mode == "forbidden":
+ reason = "用户明确禁图"
+ elif image_mode == "none":
+ reason = "用户未要求配图"
+ elif not ai_supported:
+ reason = "要求配图但 AI 生图能力不可用(generate_image 未注册)"
+ else:
+ reason = f"无可用来源 (local={local_ok}, ai={ai_ok})"
+ logger.info("[P6.5] 图片准备跳过:%s", reason)
+ return {"image_map_path": "", "image_skip_reason": reason}
image_map_path = f"{output_dir}/image_map.json"
for attempt in range(_MAX_RETRIES):
@@ -684,7 +720,7 @@ class ImagePrepareNode(PlanNode):
@staticmethod
async def _read_imagegen_status(node: "ImagePrepareNode", output_dir: str) -> bool:
- """读 P2 写的 imagegen_status.json,返回 supported 字段。"""
+ """读 imagegen_status.json,返回 supported 字段(兼容旧 P2 写的意图布尔)。"""
status_path = f"{output_dir}/imagegen_status.json"
raw = await PptCommon.read_file(node, status_path, label="imagegen_status")
if not raw:
@@ -698,6 +734,24 @@ class ImagePrepareNode(PlanNode):
logger.warning("[P6.5] 解析 imagegen_status.json 失败: %s", e)
return False
+ @staticmethod
+ async def _read_image_requirements(
+ node: "ImagePrepareNode", output_dir: str
+ ) -> dict[str, Any] | None:
+ """读 P2.4 写的 image_requirements.json(意图信号)。不存在返回 None。"""
+ req_path = f"{output_dir}/image_requirements.json"
+ raw = await PptCommon.read_file(node, req_path, label="image_requirements")
+ if not raw:
+ return None
+ try:
+ data = json.loads(raw)
+ return data if isinstance(data, dict) else None
+ except Exception as e:
+ if isinstance(e, AbortError):
+ raise
+ logger.warning("[P6.5] 解析 image_requirements.json 失败: %s", e)
+ return None
+
async def _cleanup(self, output_dir: str) -> None:
targets = [Path(output_dir) / f for f in _INTERMEDIATE_FILES]
paths_str = " ".join(quote_path(str(t)) for t in targets if t.is_file())
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py
index bb518ab839..076328ee04 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py
@@ -44,6 +44,32 @@ _EXPLICIT_NO_SEARCH_RE = re.compile(
r"(不要搜索|不搜索|无需搜索|禁止搜索|不用搜索|无需联网|不要联网)"
)
+# ── 图片意图确定性词表(代码域,不进 prompt)── 对齐 SKILL.md §1.2.E
+# 禁图词最高优先:用户明确不要图 → forbidden
+_FORBIDDEN_IMAGE_RE = re.compile(
+ r"无图版"
+ r"|不(?:要|用|需|加|得|可|许|想)(?:[\u4e00-\u9fff]{0,3}?)"
+ r"(?:图|配图|插图|插画|图片|背景图|封面图|海报|照片|视觉素材)"
+ r"|无(?:需|须|要)(?:[\u4e00-\u9fff]{0,3}?)"
+ r"(?:图|配图|插图|插画|图片)"
+ r"|禁(?:止|用)(?:[\u4e00-\u9fff]{0,3}?)"
+ r"(?:图|配图|插图|插画|图片|背景图|封面图|海报)"
+)
+# 配图意图提示词:用户原文出现这些词 → desired(即使 LLM 采样判 false 也翻正)
+_IMAGE_INTENT_HINT_RE = re.compile(
+ r"画面|配图|插图|插画|背景图|封面图|海报|视觉|意象|组合画面|"
+ r"image|illustration|background|imagery",
+ re.IGNORECASE,
+)
+# 否定前缀:hint 词前 5 字内出现这些词 → forbidden(防止"不要配图"翻正为 desired)
+_NEGATION_PREFIX_RE = re.compile(
+ r"不(?:要|用|需|加|得|可|许|想)|无(?:需|须|要)|禁(?:止|用)|别|勿|免"
+)
+# 内容约束抽取:如"不出现人像""背景必须是森林"
+_IMAGE_CONSTRAINT_RE = re.compile(
+ r"(不(?:出现|要|得有)[^,。、;\n]{0,20}|必须(?:是|有|包含)[^,。、;\n]{0,20})"
+)
+
_STYLE_LABEL_TO_ID: dict[str, str] = {
"商务经典": "business-classic",
"华为": "business-classic",
@@ -179,7 +205,12 @@ research_depth 规则(与 search_mode、page_count 联动;L1/L2/L3 含义见
- page_count 在 8~15 → L2
- 其余(含 auto 且页数 ≤7)→ L1
-need_imagegen 规则:用户 query 明确要求 AI 生图/生成配图 → true,否则 → false
+need_imagegen 规则(对齐 skill SKILL.md §1.2.E 图片意图归一:本地图片之外是否需要 ai 兜底来源):
+- 用户提出配图要求 → true:明确要求 AI 生图/生成配图/插图/插画;或描述了希望出现的
+ 具体画面/场景/元素(如"画面包含X、Y、Z""X组合画面""要配风电场景图");
+ 或对画面内容有具体约束(如"不出现人像""背景必须是森林")
+- 仅泛泛的主题词或风格词(如"科技风""简约大气"),未提出任何配图要求 → false
+- 用户未提配图要求时不得因生图工具存在而置 true
必须只输出单行 JSON,四个字段均必填且取值必须在枚举内;禁止 markdown 围栏、禁止前后附加说明:
{"search_mode":"auto","source_type":"topic","research_depth":"L2","need_imagegen":false}"""
@@ -817,6 +848,46 @@ def _parse_derive_params_response(raw: str) -> dict[str, str]:
}
+def _extract_image_constraints(user_text: str) -> list[str]:
+ """从用户原文抽取图片内容约束(如"不出现人像""背景必须是森林")。"""
+ if not user_text:
+ return []
+ constraints: list[str] = []
+ for m in _IMAGE_CONSTRAINT_RE.finditer(user_text):
+ s = m.group(1).strip()
+ if s and s not in constraints:
+ constraints.append(s)
+ return constraints
+
+
+def _resolve_image_mode(
+ user_text: str, llm_need_imagegen: bool
+) -> tuple[str, str]:
+ """意图归一:forbidden_keyword > llm > keyword_fallback(带否定守卫)。
+
+ 返回 (mode, decision_source)。mode ∈ {desired, forbidden, none}。
+ 对齐 SKILL.md §1.2.E:用户提出配图要求 → desired;禁图 → forbidden;无诉求 → none。
+ """
+ if _FORBIDDEN_IMAGE_RE.search(user_text):
+ return "forbidden", "forbidden_keyword"
+ if llm_need_imagegen:
+ return "desired", "llm"
+ # keyword_fallback:hint 命中但前 5 字内有否定前缀 → forbidden,否则 desired
+ any_hint = False
+ any_non_negated = False
+ for m in _IMAGE_INTENT_HINT_RE.finditer(user_text):
+ any_hint = True
+ prefix = user_text[max(0, m.start() - 5):m.start()]
+ if not _NEGATION_PREFIX_RE.search(prefix):
+ any_non_negated = True
+ break
+ if any_hint:
+ if any_non_negated:
+ return "desired", "keyword_fallback"
+ return "forbidden", "forbidden_keyword"
+ return "none", "llm"
+
+
def _extract_reference_urls(text: str) -> list[str]:
if not text:
return []
@@ -1666,41 +1737,43 @@ class P24DeriveParamsNode(PlanNode):
derived = await _derive_params_via_llm(self, inputs)
inputs.update(derived)
- # 写 imagegen_status.json(供 P6.5 读取)
- need_imagegen = derived.get("need_imagegen", False)
+ # 写 image_requirements.json(意图信号;对齐 SKILL.md §1.2.E)
+ # 能力信号 imagegen_status.json 归 P6.5(has_tool 探测),不在 P2 写
+ user_text = _collect_user_text(inputs)
output_dir = str(inputs.get("output_dir", "")).strip()
- if need_imagegen and output_dir:
+ image_mode, decision_source = _resolve_image_mode(
+ user_text, derived.get("need_imagegen", False)
+ )
+ # 回写权威值:P4.3 content_plan._has_no_image_source 与 P6.5 读同一信号
+ inputs["need_imagegen"] = image_mode == "desired"
+ if decision_source == "keyword_fallback":
+ logger.info(
+ "[P2.4] need_imagegen 由关键词兜底翻正"
+ "(LLM 采样判定与原文视觉诉求冲突)"
+ )
+ if output_dir:
try:
content = json.dumps(
- {"supported": True},
+ {
+ "mode": image_mode,
+ "decision_source": decision_source,
+ "constraints": _extract_image_constraints(user_text),
+ },
ensure_ascii=False,
)
await PptCommon.write_file(
- self, f"{output_dir}/imagegen_status.json",
- content, label="imagegen_status",
+ self, f"{output_dir}/image_requirements.json",
+ content, label="image_requirements",
error_type=RequirementCollectError,
)
- logger.info("[P2.4] imagegen_status.json 已写入 (supported=true)")
- except Exception as e:
- if isinstance(e, AbortError):
- raise
- logger.warning("[P2.4] 写 imagegen_status.json 失败: %s", e)
- elif not need_imagegen and output_dir:
- try:
- content = json.dumps(
- {"supported": False},
- ensure_ascii=False,
- )
- await PptCommon.write_file(
- self, f"{output_dir}/imagegen_status.json",
- content, label="imagegen_status",
- error_type=RequirementCollectError,
+ logger.info(
+ "[P2.4] image_requirements.json 已写入 (mode=%s, source=%s)",
+ image_mode, decision_source,
)
- logger.info("[P2.4] imagegen_status.json 已写入 (supported=false)")
except Exception as e:
if isinstance(e, AbortError):
raise
- logger.warning("[P2.4] 写 imagegen_status.json 失败: %s", e)
+ logger.warning("[P2.4] 写 image_requirements.json 失败: %s", e)
return inputs
@@ -1795,7 +1868,7 @@ class RequirementCollectNode(PlanNode):
def _ensure_image_vars(self, ctx: dict[str, Any]) -> None:
"""图片变量兜底:image_paths 空数组 + image_sources 默认 local。
- ai 源由 P6.5 读取 imagegen_status.json 动态启用,不在此处判断。
+ ai 源由 P6.5 读取 image_requirements.json(意图)+ has_tool 探测(能力)双信号启用,不在此处判断。
"""
ctx.setdefault("image_paths", [])
ctx.setdefault("image_sources", ["local"])