Files
planet/backend/app/services/ai/scene_directives.py
T

151 lines
8.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Shared `<planet_scene>` prompt guidance and streaming extraction for Earth Influence Zones."""
from __future__ import annotations
import json
import re
from typing import Any
from app.core.logging import get_logger
from app.services.ai.workflow_runtime import validate_influence_zones
logger = get_logger(__name__, service="ai_scene")
PLANET_SCENE_TAG_OPEN = "<planet_scene>"
PLANET_SCENE_RE = re.compile(r"<planet_scene>\s*(.*?)\s*</planet_scene>", re.DOTALL | re.IGNORECASE)
PLANET_SCENE_OPEN_RE = re.compile(r"<\s*planet_scene\b", re.IGNORECASE)
_CODE_FENCE_OPEN_RE = re.compile(r"^\s*```[a-zA-Z0-9_-]*\s*\n?")
_CODE_FENCE_CLOSE_RE = re.compile(r"\n?\s*```\s*$")
_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")
INFLUENCE_ZONE_GUIDANCE = (
"【地球影响范围联动指令】正文仍用自然 Markdown 输出(绝不在正文解释本标签);"
"只要分析涉及明确地理国家、地区、消费/市场辐射域、基础设施影响区、海域/海峡走廊、峰会/组织或用户询问“影响范围/影响地区/覆盖区域”,"
"就必须在回答**最末尾另起一行**附带一个纯 JSON(禁用 markdown 代码围栏)的系统隐藏标签:\n"
"<planet_scene>{...}</planet_scene>\n"
"分层输出规范(严格遵循):\n"
"- 第一层(必需,直接当事国/核心对象):shape.mode=\"countries\",color=\"#ef4444\",opacity=0.54,edge.style=\"sharp\";必须填全所有直接核心国家且严格使用标准 ISO-3 代码(如朝鲜必须写 \"PRK\",禁用 \"DPRK\";中国 \"CHN\"、韩国 \"KOR\"、日本 \"JPN\"、俄罗斯 \"RUS\"、英国 \"GBR\")。\n"
"- 第二层(若事件存在跨国/区域外溢则必填;纯单一国内消费/内部新闻则不填第二、三层):次级邻近/区域辐射,shape.mode=\"countries\" 或已支持的 \"region_preset\",color=\"#f59e0b\",opacity=0.32,edge.style=\"soft\"。\n"
"- 第三层(仅当明确涉及海峡、海域航道或边境辐射带时可选):shape.mode=\"circle\"(center:[lat,lon], radius_km),color=\"#38bdf8\",opacity=0.28,edge.style=\"soft\"。\n"
"完整单国示例:\n"
"<planet_scene>{\"influence_zones\":[{\"id\":\"chn-core\",\"label\":\"直接影响:中国\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\"]}}],\"camera_hint\":{\"lat\":35.0,\"lon\":104.0}}</planet_scene>\n"
"双国核心+区域外溢+海域辐射示例:\n"
"<planet_scene>{\"influence_zones\":[{\"id\":\"core\",\"label\":\"核心国家\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\",\"PRK\"]}},{\"id\":\"spill\",\"label\":\"东北亚周边外溢\",\"color\":\"#f59e0b\",\"opacity\":0.32,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"fade\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"KOR\",\"JPN\",\"RUS\"]}},{\"id\":\"sea\",\"label\":\"黄海—朝鲜海峡航道辐射\",\"color\":\"#38bdf8\",\"opacity\":0.28,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"radial\"},\"shape\":{\"mode\":\"circle\",\"center\":[36.5,124.5],\"radius_km\":850}}],\"camera_hint\":{\"lat\":38.0,\"lon\":122.0}}</planet_scene>\n"
"可选 region_preset 枚举(仅限此列表,勿自造名称):"
"APEC, ASIA_PACIFIC, NORTHEAST_ASIA, EAST_ASIA, KOREAN_PENINSULA, SOUTHEAST_ASIA, SOUTH_ASIA, CENTRAL_ASIA, ASEAN, INDO_PACIFIC, "
"EU, EUROPE, EASTERN_EUROPE, NORTHERN_EUROPE, WESTERN_EUROPE, G7, BRICS, NATO, MIDDLE_EAST, MENA, AMERICAS, NORTH_AMERICA, SOUTH_AMERICA, AFRICA;"
"animation.type 选 \"sweep\"、\"radial\" 或 \"fade\"。"
)
def sanitize_camera_hint(raw: Any) -> dict[str, float] | None:
if not isinstance(raw, dict):
return None
cleaned: dict[str, float] = {}
for key in ("lat", "lon", "altitude", "zoom"):
val = raw.get(key)
if isinstance(val, (int, float)) and not isinstance(val, bool):
cleaned[key] = float(val)
return cleaned if ("lat" in cleaned and "lon" in cleaned) else None
def _parse_scene_json_candidate(raw_json: str) -> dict[str, Any] | None:
"""Parse JSON inside `<planet_scene>` even if wrapped in code fences or containing trailing commas."""
text = str(raw_json or "").strip()
if not text:
return None
text = _CODE_FENCE_OPEN_RE.sub("", text)
text = _CODE_FENCE_CLOSE_RE.sub("", text).strip()
candidates = [text]
first_brace = text.find("{")
last_brace = text.rfind("}")
if first_brace != -1 and last_brace > first_brace:
sliced = text[first_brace : last_brace + 1]
if sliced != text:
candidates.append(sliced)
for cand in candidates:
for attempt in (cand, _TRAILING_COMMA_RE.sub(r"\1", cand)):
try:
parsed = json.loads(attempt)
except Exception:
continue
if isinstance(parsed, dict):
return parsed
return None
def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | None]:
"""Strip `<planet_scene>...</planet_scene>` blocks and return validated scene spec fields."""
if not text:
return "", None
parsed_scene: dict[str, Any] | None = None
matches = PLANET_SCENE_RE.findall(text)
for raw_json in matches:
payload = _parse_scene_json_candidate(raw_json)
if payload is None:
continue
zones = [z.model_dump(mode="json") for z in validate_influence_zones(payload.get("influence_zones"))]
camera_hint = sanitize_camera_hint(payload.get("camera_hint"))
if zones or camera_hint:
parsed_scene = {}
if zones:
parsed_scene["influence_zones"] = zones
if camera_hint:
parsed_scene["camera_hint"] = camera_hint
if matches and parsed_scene is not None:
extracted_zones = parsed_scene.get("influence_zones") or []
logger.info_event(
"Extracted planet scene directives",
event="ai_scene.directive.extracted",
context={
"zones_count": len(extracted_zones),
"zone_ids": [z.get("id") for z in extracted_zones if isinstance(z, dict)],
"has_camera_hint": "camera_hint" in parsed_scene,
},
)
elif matches:
logger.warning_event(
"Planet scene directive ignored after parse/validation failure",
event="ai_scene.directive.dropped",
context={"snippet": str(matches[-1])[:300]},
)
cleaned = PLANET_SCENE_RE.sub("", text)
open_match = PLANET_SCENE_OPEN_RE.search(cleaned)
if open_match:
cleaned = cleaned[: open_match.start()]
return cleaned.rstrip(), parsed_scene
def consume_text_holding_scene_tag(buffer: str, *, flush_all: bool = False) -> tuple[str, str]:
"""Yield visible text before `<planet_scene` while holding back partial tag prefixes."""
stripped_blocks = PLANET_SCENE_RE.sub("", buffer)
open_match = PLANET_SCENE_OPEN_RE.search(stripped_blocks)
if open_match:
return stripped_blocks[: open_match.start()], stripped_blocks[open_match.start() :]
if flush_all:
return stripped_blocks, ""
last_lt = stripped_blocks.rfind("<")
if last_lt != -1:
tail = stripped_blocks[last_lt:]
if len(tail) < len(PLANET_SCENE_TAG_OPEN) and PLANET_SCENE_TAG_OPEN.startswith(tail.lower()):
return stripped_blocks[:last_lt], tail
return stripped_blocks, ""
def merge_scene_specs(
base_scene: dict[str, Any] | None,
parsed_scene: dict[str, Any] | None,
*,
domain: str | None = None,
) -> dict[str, Any] | None:
if not parsed_scene and not isinstance(base_scene, dict):
return None
merged: dict[str, Any] = dict(base_scene) if isinstance(base_scene, dict) else {}
if parsed_scene:
merged.update(parsed_scene)
if domain and not merged.get("domain"):
merged["domain"] = domain
return merged