Files
planet/backend/app/services/ai/spatial_domain_agent.py
T
linkong 41059ca42a
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.80.0
2026-11-26 10:50:38 +08:00

1083 lines
48 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.
"""Unified data-driven situational agent for `global`, `cable`, `satellite`, and `vessel` domains."""
from __future__ import annotations
import asyncio
import hashlib
import json
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.situational_assessment import SituationalAssessment
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.domain_catalog import (
SPATIAL_POSTURE_DOMAINS,
SpatialDomain,
domain_to_subject_type,
)
from app.services.ai.thinking_sanitizer import (
assert_no_thinking_leak,
extract_json_object,
extract_response_usage,
prepare_situational_ai_call,
)
from app.services.ai.tool_registry import (
TimeBasis,
query_cable_posture_tool,
query_global_situational_tool,
query_satellite_posture_tool,
query_vessel_posture_tool,
)
from app.services.ai_client import AIProviderClient
if TYPE_CHECKING:
from app.services.ai.workflow_runtime import SceneSpec, ViewPreset, ViewSpec
logger = get_logger(__name__, service="ai_spatial")
_INCOMPLETE_SPATIAL_REPLAY_NOTICE = (
"不支持完整重放:当前历史记录缺少冻结遥测快照,已禁止回查当前实时地理与流量表替代历史状态,"
"仅保留原始研判结论与已绑定证据编号。"
)
_SPATIAL_DOMAIN_PROMPTS: dict[SpatialDomain, tuple[str, str]] = {
"global": (
"你是 Planet 全球多图层态势研判参谋。只能严格依据输入的五域内置遥测统计(海缆、卫星、算力、AIS船舶、BGP路由)作答,禁止臆测未给出的告警或断缆原因。",
"综合评估当前全球五个空间与网络基础设施域的在轨/在网规模、可见图层与边界缺口。",
),
"cable": (
"你是 Planet 海底光缆态势研判参谋。仅依据内置海缆线路与登陆站拓扑数据(arcgis_cables / arcgis_landing_points)进行事实归纳,禁止把缺失光学监测数据解读为确认完好或物理断缆。",
"梳理当前全球海缆骨干长度、在役状态分布、关键登陆枢纽国家与聚焦实体边界。",
),
"satellite": (
"你是 Planet 轨道与星座态势参谋。仅依据内置星历编目快照(celestrak_tle)按轨道体制与星座群组进行结构化总结,明确标注采样上限与口径边界。",
"梳理当前追踪卫星编目规模、星座集中度、LEO/MEO/GEO 轨道分布与重点轨道目标。",
),
"vessel": (
"你是 Planet 海上 AIS 船舶态势参谋。仅依据内置近期滑动窗口快照(vessels/snapshot)总结在航与锚泊态势、船型构成及航速前位目标。",
"分析当前 AIS 监测窗口内的船舶总规模、在航/锚泊结构、主要船型分布与关注船只。",
),
}
_DOMAIN_TITLES: dict[SpatialDomain, tuple[str, str]] = {
"global": ("全球全图层综合态势", "Global Multi-Domain Posture"),
"cable": ("全球海底光缆与登陆站态势", "Subsea Cable & Landing Posture"),
"satellite": ("全球在轨卫星星座态势", "Orbital Constellation Posture"),
"vessel": ("全球海运 AIS 船舶态势", "Maritime AIS Vessel Posture"),
}
class SpatialClaim(BaseModel):
model_config = ConfigDict(extra="forbid")
statement: str = Field(min_length=4, max_length=600)
evidence_ids: list[str] = Field(min_length=1)
class SpatialDomainAssessmentPayload(BaseModel):
model_config = ConfigDict(extra="forbid")
domain: SpatialDomain
subject_key: str = Field(min_length=1, max_length=255)
title: str = Field(min_length=2, max_length=240)
executive_assertion: str = Field(min_length=4, max_length=800)
confirmed_facts: list[SpatialClaim] = Field(default_factory=list)
analytical_notes: list[SpatialClaim] = Field(default_factory=list)
open_gaps: list[str] = Field(default_factory=list)
evidence_ids: list[str] = Field(min_length=1)
def _raise_if_cancelled(cancel_event: asyncio.Event | None) -> None:
if cancel_event is not None and cancel_event.is_set():
raise asyncio.CancelledError("Spatial domain investigation cancelled")
def _primary_evidence_id(evidence_map: dict[str, dict[str, Any]], domain: SpatialDomain) -> str:
if evidence_map:
return next(iter(evidence_map.keys()))
return f"ev-{domain}-builtin"
def build_deterministic_spatial_assessment(
*,
domain: SpatialDomain,
subject_key: str,
snapshot: dict[str, Any],
evidence_map: dict[str, dict[str, Any]],
) -> SpatialDomainAssessmentPayload:
"""Build strictly grounded deterministic posture summary from built-in telemetry snapshot."""
primary_eid = _primary_evidence_id(evidence_map, domain)
all_eids = list(evidence_map.keys()) or [primary_eid]
zh_title, _ = _DOMAIN_TITLES[domain]
limitations = [str(x) for x in (snapshot.get("limitations") or []) if x]
facts: list[SpatialClaim] = []
notes: list[SpatialClaim] = []
if domain == "global":
summaries = list(snapshot.get("domain_summaries") or [])
visible_names = [s["label"] for s in summaries if s.get("layer_visible")]
total_txt = ";".join(f"{s['label']} {s['metric_text']}" for s in summaries)
bgp_active = int((snapshot.get("bgp_summary") or {}).get("active_count") or 0)
assertion = (
f"当前地球态势共汇聚五大内置数据域({total_txt or '多域待加载'}),"
+ (f"其中当前活跃 BGP 路由异常 {bgp_active} 条。" if bgp_active else "当前未检测到处于 active 状态的 BGP 路由异动。")
)
facts.append(
SpatialClaim(
statement=f"当前地球视图已开启图层:{', '.join(visible_names) if visible_names else '默认视图(未显式传回可见层标记)'}。",
evidence_ids=[primary_eid],
)
)
for s in summaries:
facts.append(
SpatialClaim(
statement=f"【{s['label']}】{s['metric_text']}(状态:{s['status']})。",
evidence_ids=[primary_eid],
)
)
notes.append(
SpatialClaim(
statement="各空间域独立采自内置遥测账本(GeoJSON / TLE / AIS / 计算配置 / BGP 记录),跨图层切换共享同一时间口径与修订版本。",
evidence_ids=all_eids[:3],
)
)
open_gaps = limitations or [
"全局总览展示各域当下体量与活跃状态;针对海缆断纤物理因果或 BGP 单起路由事件,建议切换对应专域继续深挖。"
]
elif domain == "cable":
cables_total = int(snapshot.get("cables_total") or 0)
lps_total = int(snapshot.get("landing_points_total") or 0)
top_cables = list(snapshot.get("top_longest_cables") or [])
top_countries = list(snapshot.get("top_landing_countries") or [])
focused = snapshot.get("focused_entity")
status_counts = dict(snapshot.get("status_counts") or {})
longest_txt = (
",最长骨干含 " + "、".join(
f"{c['name']}({c['length_km']} km)" if c.get("length_km") else c["name"]
for c in top_cables[:3]
)
if top_cables
else ""
)
assertion = (
f"内置海缆目录共收录 {cables_total} 条海底光缆与 {lps_total} 处登陆站"
+ (f"(状态分布:{', '.join(f'{k}:{v}' for k, v in status_counts.items())})" if status_counts else "")
+ f"{longest_txt}。"
)
if cables_total or lps_total:
facts.append(
SpatialClaim(
statement=f"空间骨干网络涵盖 {cables_total} 条海底光缆线路、{lps_total} 个登陆点,登陆站集中度前位地区包括:"
+ ("、".join(f"{c['country']}({c['landing_point_count']})" for c in top_countries[:4]) or "暂无国家聚合"),
evidence_ids=[primary_eid],
)
)
else:
facts.append(
SpatialClaim(
statement="当前库内海缆或登陆站快照暂为空或处于离线模式,未读取到具体海缆线路记录。",
evidence_ids=[primary_eid],
)
)
if focused:
facts.append(
SpatialClaim(
statement=f"聚焦目标 `{focused.get('name') or focused.get('id')}`"
+ (f"(类型:{focused.get('kind')},状态:{focused.get('status') or 'indexed'})" if focused else "")
+ " 已纳入当前工作台锁定上下文。",
evidence_ids=[primary_eid],
)
)
notes.append(
SpatialClaim(
statement="静态海缆地理拓扑用于识别物理冗余度与登陆站单点汇集风险;是否发生实际断缆须结合独立光功率或运营商公告,不能凭地理数据直接推断。",
evidence_ids=[primary_eid],
)
)
open_gaps = limitations or [
"当前海缆图层提供路径与登陆归属资产目录,尚未接入海底中继器实时光功率遥测。"
]
elif domain == "satellite":
sat_total = int(snapshot.get("satellites_total") or 0)
regimes = dict(snapshot.get("by_orbit_regime") or {})
consts = dict(snapshot.get("by_constellation") or {})
focused = snapshot.get("focused_entity")
top_regimes_txt = "、".join(f"{k}:{v}" for k, v in regimes.items()) or "暂无轨道分类"
top_const_txt = "、".join(f"{k}:{v}" for k, v in list(consts.items())[:5]) or "暂无星座分类"
assertion = (
f"内置卫星编目快照当前统计在轨追踪目标 {sat_total} 颗;按轨道体制分布为 {top_regimes_txt},主要星座群组包含 {top_const_txt}。"
)
if sat_total:
facts.append(
SpatialClaim(
statement=f"轨道体制分布:{top_regimes_txt};星座聚合前五:{top_const_txt}。",
evidence_ids=[primary_eid],
)
)
else:
facts.append(
SpatialClaim(
statement="当前轨道快照暂未返回卫星 TLE 目标(可能为离线会话或尚未同步 celestrak_tle)。",
evidence_ids=[primary_eid],
)
)
if focused:
facts.append(
SpatialClaim(
statement=f"锁定星历目标 `{focused.get('name')}`(NORAD `{focused.get('norad_cat_id')}` · {focused.get('constellation_group')} · 轨道 {focused.get('orbit_regime')})。",
evidence_ids=[primary_eid],
)
)
notes.append(
SpatialClaim(
statement="TLE 两行轨道根数反映星历同期传播几何关系;地面站覆盖窗口及频谱干扰分析需叠加具体观测坐标进一步推算。",
evidence_ids=[primary_eid],
)
)
open_gaps = limitations or [
"卫星图层的健康状态为轨道编目传播,不包含星上载荷健康度或链路信噪比实时下行指标。"
]
else: # vessel
v_total = int(snapshot.get("vessels_total") or 0)
underway = int(snapshot.get("underway") or 0)
moored = int(snapshot.get("anchored_or_moored") or 0)
by_type = dict(snapshot.get("by_type") or {})
focused = snapshot.get("focused_entity")
type_txt = "、".join(
f"{k}:{v}" for k, v in sorted(by_type.items(), key=lambda kv: kv[1], reverse=True)[:5]
) or "暂无船型构成"
assertion = (
f"近 {snapshot.get('since_minutes', 60)} 分钟内置 AIS 快照共观测 {v_total} 艘船舶,其中在航 {underway} 艘、锚泊/系泊 {moored} 艘;主要船型分布:{type_txt}。"
)
if v_total:
facts.append(
SpatialClaim(
statement=f"海运态势窗口统计 {v_total} 艘船舶,在航占比 {round(underway / v_total * 100, 1)}%({underway} 艘),锚泊/系泊 {moored} 艘。",
evidence_ids=[primary_eid],
)
)
else:
facts.append(
SpatialClaim(
statement=f"近 {snapshot.get('since_minutes', 60)} 分钟 AIS 窗口内暂未返回活跃船舶样本(或处于离线验证模式)。",
evidence_ids=[primary_eid],
)
)
if focused:
facts.append(
SpatialClaim(
statement=f"聚焦船舶 `{focused.get('name')}`(MMSI `{focused.get('mmsi')}` · {focused.get('vessel_type_name')} · 航速 {focused.get('sog') if focused.get('sog') is not None else 'N/A'} kn)。",
evidence_ids=[primary_eid],
)
)
notes.append(
SpatialClaim(
statement="AIS 位置反映岸基/卫星接收窗口内的报文刷新密度,远洋无信号区域或关闭应答器的目标不会计入活跃计数。",
evidence_ids=[primary_eid],
)
)
open_gaps = limitations or [
"AIS 快照按滑动时间窗口聚合,若需研判海缆邻近抛锚异常,需人工核对船位轨迹与禁锚区边界。"
]
return SpatialDomainAssessmentPayload(
domain=domain,
subject_key=subject_key,
title=f"{zh_title}" + (f" · {snapshot['focused_entity']['name']}" if isinstance(snapshot.get("focused_entity"), dict) and snapshot["focused_entity"].get("name") else ""),
executive_assertion=assertion,
confirmed_facts=facts,
analytical_notes=notes,
open_gaps=open_gaps,
evidence_ids=all_eids,
)
def _validate_spatial_llm_payload(
raw_obj: dict[str, Any],
*,
domain: SpatialDomain,
subject_key: str,
evidence_map: dict[str, dict[str, Any]],
) -> SpatialDomainAssessmentPayload:
valid_eids = set(evidence_map.keys())
candidate = dict(raw_obj)
candidate["domain"] = domain
candidate["subject_key"] = subject_key
for group_key in ("confirmed_facts", "analytical_notes"):
cleaned: list[dict[str, Any]] = []
for item in candidate.get(group_key) or []:
if not isinstance(item, dict):
continue
stmt = str(item.get("statement") or "").strip()
eids = [str(e) for e in (item.get("evidence_ids") or []) if str(e) in valid_eids]
if len(stmt) >= 4 and eids:
cleaned.append({"statement": stmt[:600], "evidence_ids": eids})
candidate[group_key] = cleaned
top_eids = [str(e) for e in (candidate.get("evidence_ids") or []) if str(e) in valid_eids]
if not top_eids:
raise ValueError("Spatial LLM payload lacked valid evidence citations")
candidate["evidence_ids"] = top_eids
return SpatialDomainAssessmentPayload.model_validate(candidate)
async def investigate_spatial_domain(
db: AsyncSession,
*,
domain: SpatialDomain,
question: str = "",
selected_codes: list[str] | None = None,
entity_id: str | None = None,
visible_layers: dict[str, bool] | None = None,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
persist: bool = True,
ai_client: AIProviderClient | None = None,
cancel_event: asyncio.Event | None = None,
) -> dict[str, Any]:
"""Run built-in spatial/global posture query, optional LLM synthesis, and freeze revision."""
if domain not in SPATIAL_POSTURE_DOMAINS:
raise ValueError(f"Unsupported spatial domain: {domain}")
_raise_if_cancelled(cancel_event)
codes = [str(c).upper() for c in (selected_codes or ["CN", "US"]) if c][:8] or ["CN", "US"]
vis = dict(visible_layers or {})
if domain == "global":
snapshot = await query_global_situational_tool(
db,
selected_codes=codes,
visible_layers=vis,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
subject_key = f"global:{','.join(codes)}:{time_basis}"
elif domain == "cable":
snapshot = await query_cable_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
entity_id=entity_id,
)
subject_key = f"cable:{entity_id or 'global'}:{time_basis}"
elif domain == "satellite":
snapshot = await query_satellite_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
entity_id=entity_id,
)
subject_key = f"satellite:{entity_id or 'global'}:{time_basis}"
else:
snapshot = await query_vessel_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
entity_id=entity_id,
)
subject_key = f"vessel:{entity_id or 'global'}:{time_basis}"
_raise_if_cancelled(cancel_event)
evidence_map: dict[str, dict[str, Any]] = dict(snapshot.get("evidence") or {})
if not evidence_map:
eid = _primary_evidence_id(evidence_map, domain)
evidence_map = {
eid: {
"id": eid,
"title": f"Planet 内置 {domain} 态势快照",
"publisher": "Planet Spatial Ledger",
"url": "/earth/",
"published_at": None,
"locator": subject_key,
}
}
subject_type = domain_to_subject_type(domain)
fingerprint = hashlib.sha256(
json.dumps(
{
"domain": domain,
"subject_key": subject_key,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"entity_id": entity_id,
"selected_codes": codes if domain == "global" else [],
"visible_layers": sorted((k, bool(v)) for k, v in vis.items()) if domain == "global" else [],
"metrics_digest": {
k: snapshot.get(k)
for k in (
"cables_total",
"landing_points_total",
"satellites_total",
"vessels_total",
"underway",
"compute_summary",
"bgp_summary",
)
if k in snapshot
},
"question_focus": str(question or "").strip()[:120] if (ai_client is not None and ai_client.service_url) else "",
},
sort_keys=True,
ensure_ascii=False,
).encode("utf-8")
).hexdigest()
fallback_cached: SituationalAssessment | None = None
if hasattr(db, "execute"):
try:
cached_rows = (
(
await db.execute(
select(SituationalAssessment)
.where(
SituationalAssessment.subject_type == subject_type,
SituationalAssessment.subject_key == subject_key,
SituationalAssessment.input_fingerprint == fingerprint,
)
.order_by(desc(SituationalAssessment.revision), desc(SituationalAssessment.id))
.limit(5)
)
)
.scalars()
.all()
)
cached = next(
(r for r in cached_rows if getattr(r, "generation_mode", None) == "llm_verified"),
cached_rows[0] if cached_rows else None,
)
if isinstance(cached, SituationalAssessment) and cached.payload:
cached_meta = cached.audit_meta or {}
wants_llm_upgrade = (
ai_client is not None
and bool(getattr(ai_client, "service_url", ""))
and cached.generation_mode != "llm_verified"
)
if wants_llm_upgrade:
fallback_cached = cached
else:
return {
"domain": domain,
"subject_type": subject_type,
"subject_key": subject_key,
"input_fingerprint": fingerprint,
"revision": int(cached.revision),
"cache_hit": True,
"generation_mode": cached.generation_mode,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"usage": cached_meta.get("llm_usage") or {},
"snapshot": cached_meta.get("frozen_snapshot") if isinstance(cached_meta.get("frozen_snapshot"), dict) else snapshot,
"payload": cached.payload,
"evidence": cached_meta.get("frozen_evidence") if isinstance(cached_meta.get("frozen_evidence"), dict) else evidence_map,
"replay_supported": True,
"replay_notice": None,
}
except Exception:
pass
assessment: SpatialDomainAssessmentPayload | None = None
generation_mode = "deterministic_baseline"
llm_usage: dict[str, Any] = {}
if ai_client is not None and ai_client.service_url:
_raise_if_cancelled(cancel_event)
sys_prompt, base_objective = _SPATIAL_DOMAIN_PROMPTS[domain]
try:
effective_ai_client, thinking_arg = prepare_situational_ai_call(ai_client)
llm_resp = await asyncio.wait_for(
effective_ai_client.analyze(
SituationalAnalysisRequest(
title=f"Planet 空间态势研判({domain}):{subject_key}",
objective=(
f"{base_objective}\n用户问题:{question or '全面态势研判'}\n"
"仅返回单个紧凑 JSON 对象(不加围栏外文字),结构:\n"
'{"domain": str, "subject_key": str, "title": str, "executive_assertion": str, '
'"confirmed_facts": [{"statement": str, "evidence_ids": [str]}], '
'"analytical_notes": [{"statement": str, "evidence_ids": [str]}], '
'"open_gaps": [str], "evidence_ids": [str]}'
),
system_prompt=sys_prompt,
context={
"domain": domain,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"snapshot": {k: v for k, v in snapshot.items() if k != "evidence"},
"evidence": evidence_map,
},
constraints=[
"Return strict JSON matching SpatialDomainAssessmentPayload.",
"Every evidence_id must exist in context.evidence.",
"Never fabricate counts, routes, cable faults, or telemetry missing from context.snapshot.",
],
thinking=thinking_arg,
)
),
timeout=35.0,
)
_raise_if_cancelled(cancel_event)
raw_text = (llm_resp.content or "").strip()
assert_no_thinking_leak(raw_text)
parsed = extract_json_object(raw_text)
if not isinstance(parsed, dict):
raise ValueError("Spatial LLM response was not JSON")
assessment = _validate_spatial_llm_payload(
parsed,
domain=domain,
subject_key=subject_key,
evidence_map=evidence_map,
)
generation_mode = "llm_verified"
llm_usage = extract_response_usage(llm_resp)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning_event(
"Spatial domain LLM synthesis fell back to deterministic baseline",
event="ai_spatial.llm.fallback",
context={"domain": domain, "error": str(exc)},
)
_raise_if_cancelled(cancel_event)
if assessment is None and fallback_cached is not None:
cached_meta = fallback_cached.audit_meta or {}
return {
"domain": domain,
"subject_type": subject_type,
"subject_key": subject_key,
"input_fingerprint": fingerprint,
"revision": int(fallback_cached.revision),
"cache_hit": True,
"generation_mode": fallback_cached.generation_mode,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"usage": {},
"snapshot": cached_meta.get("frozen_snapshot") if isinstance(cached_meta.get("frozen_snapshot"), dict) else snapshot,
"payload": fallback_cached.payload,
"evidence": cached_meta.get("frozen_evidence") if isinstance(cached_meta.get("frozen_evidence"), dict) else evidence_map,
"replay_supported": True,
"replay_notice": None,
}
if assessment is None:
assessment = build_deterministic_spatial_assessment(
domain=domain,
subject_key=subject_key,
snapshot=snapshot,
evidence_map=evidence_map,
)
revision = 1
if persist and hasattr(db, "execute") and hasattr(db, "add") and hasattr(db, "flush"):
_raise_if_cancelled(cancel_event)
try:
latest_rev = (
await db.execute(
select(SituationalAssessment.revision)
.where(
SituationalAssessment.subject_type == subject_type,
SituationalAssessment.subject_key == subject_key,
)
.order_by(desc(SituationalAssessment.revision))
.limit(1)
)
).scalar_one_or_none()
if isinstance(latest_rev, int):
revision = latest_rev + 1
frozen_snap = json.loads(json.dumps(snapshot, ensure_ascii=False, default=str))
frozen_ev = json.loads(json.dumps(evidence_map, ensure_ascii=False, default=str))
record = SituationalAssessment(
subject_type=subject_type,
subject_key=subject_key,
input_fingerprint=fingerprint,
revision=revision,
generation_mode=generation_mode,
payload=assessment.model_dump(mode="json"),
evidence_ids=list(dict.fromkeys(assessment.evidence_ids)),
audit_meta={
"domain": domain,
"entity_id": entity_id,
"selected_codes": codes,
"visible_layers": vis,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"frozen_snapshot": frozen_snap,
"frozen_evidence": frozen_ev,
"llm_usage": llm_usage,
},
)
db.add(record)
await db.flush()
except Exception as exc:
logger.warning_event(
"Spatial domain assessment persistence skipped",
event="ai_spatial.persist.skipped",
context={"domain": domain, "error": str(exc)},
)
return {
"domain": domain,
"subject_type": subject_type,
"subject_key": subject_key,
"input_fingerprint": fingerprint,
"revision": revision,
"cache_hit": False,
"generation_mode": generation_mode,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"usage": llm_usage,
"snapshot": snapshot,
"payload": assessment.model_dump(mode="json"),
"evidence": evidence_map,
"replay_supported": True,
"replay_notice": None,
}
def _spatial_available_presets() -> list[dict[str, str]]:
return [
{"id": "default", "label": "态势工作台", "label_en": "Workbench"},
{"id": "comparison", "label": "结构对照", "label_en": "Chart"},
{"id": "table", "label": "数据表", "label_en": "Table"},
{"id": "topology", "label": "空间拓扑", "label_en": "Topology"},
{"id": "causal", "label": "研判结论", "label_en": "Findings"},
{"id": "evidence", "label": "证据链", "label_en": "Evidence"},
{"id": "onepager", "label": "一页简报", "label_en": "One-Pager"},
]
def _build_spatial_matrix_rows(
domain: SpatialDomain,
snapshot: dict[str, Any],
primary_eid: str,
) -> tuple[list[dict[str, Any]], str]:
rows: list[dict[str, Any]] = []
unit_hint = ""
if domain == "global":
unit_hint = "条 / 颗 / 艘"
code_map = {"cable": "CBL", "satellite": "SAT", "compute": "CMP", "vessel": "AIS", "bgp": "BGP"}
en_map = {
"cable": "Subsea Cables",
"satellite": "Orbital Satellites",
"compute": "Compute Centers",
"vessel": "AIS Vessels",
"bgp": "BGP Signals",
}
items = list(snapshot.get("domain_summaries") or [])
max_v = max((int(it.get("count") or 0) for it in items), default=1) or 1
for it in items:
cnt = int(it.get("count") or 0)
dom = str(it.get("domain") or "global")
rows.append(
{
"code": code_map.get(dom, dom.upper()[:4]),
"label": str(it.get("label") or dom),
"label_en": en_map.get(dom, dom.title()),
"year": "实时",
"value": cnt,
"formatted": str(it.get("metric_text") or cnt),
"bar_pct": round(cnt / max_v * 100.0, 1) if cnt > 0 else 4.0,
"evidence_id": primary_eid,
"is_missing": False,
"missing_reason": None,
}
)
elif domain == "cable":
unit_hint = "km"
cables = list(snapshot.get("top_longest_cables") or [])
max_len = max((float(c.get("length_km") or 0.0) for c in cables), default=1.0) or 1.0
for idx, c in enumerate(cables[:6]):
val = c.get("length_km")
rows.append(
{
"code": f"C{idx + 1}",
"label": str(c.get("name") or f"Cable {idx + 1}"),
"label_en": str(c.get("name") or f"Cable {idx + 1}"),
"year": c.get("rfs") or "—",
"value": float(val) if val is not None else None,
"formatted": f"{val} km" if val is not None else str(c.get("status") or "active"),
"bar_pct": round(float(val) / max_len * 100.0, 1) if val is not None else 18.0,
"evidence_id": primary_eid,
"is_missing": False,
"missing_reason": None,
}
)
if not rows:
for idx, ctry in enumerate(list(snapshot.get("top_landing_countries") or [])[:6]):
cnt = int(ctry.get("landing_point_count") or 0)
rows.append(
{
"code": f"L{idx + 1}",
"label": str(ctry.get("country") or "Unknown"),
"label_en": str(ctry.get("country") or "Unknown"),
"year": "登陆站",
"value": cnt,
"formatted": f"{cnt} 处登陆站",
"bar_pct": 60.0,
"evidence_id": primary_eid,
"is_missing": False,
"missing_reason": None,
}
)
elif domain == "satellite":
unit_hint = "颗"
regimes = dict(snapshot.get("by_orbit_regime") or {})
max_v = max(regimes.values(), default=1) or 1
for k, v in regimes.items():
rows.append(
{
"code": str(k)[:4].upper(),
"label": f"{k} 轨道",
"label_en": f"{k} Orbit",
"year": "TLE",
"value": int(v),
"formatted": f"{int(v)} 颗",
"bar_pct": round(int(v) / max_v * 100.0, 1),
"evidence_id": primary_eid,
"is_missing": False,
"missing_reason": None,
}
)
else: # vessel
unit_hint = "艘"
by_type = dict(snapshot.get("by_type") or {})
sorted_types = sorted(by_type.items(), key=lambda kv: kv[1], reverse=True)[:6]
max_v = max((v for _, v in sorted_types), default=1) or 1
for idx, (k, v) in enumerate(sorted_types):
rows.append(
{
"code": str(k)[:4].upper() or f"V{idx + 1}",
"label": str(k),
"label_en": str(k),
"year": f"{snapshot.get('since_minutes', 60)}m",
"value": int(v),
"formatted": f"{int(v)} 艘",
"bar_pct": round(int(v) / max_v * 100.0, 1),
"evidence_id": primary_eid,
"is_missing": False,
"missing_reason": None,
}
)
if not rows:
rows.append(
{
"code": domain[:3].upper(),
"label": _DOMAIN_TITLES[domain][0],
"label_en": _DOMAIN_TITLES[domain][1],
"year": "—",
"value": 0,
"formatted": "暂无样本记录",
"bar_pct": 0.0,
"evidence_id": primary_eid,
"is_missing": True,
"missing_reason": "当前无在线数据记录或处于离线测试上下文",
}
)
return rows, unit_hint
def _build_spatial_topology_data(domain: SpatialDomain, snapshot: dict[str, Any]) -> dict[str, Any]:
focused = snapshot.get("focused_entity") if isinstance(snapshot.get("focused_entity"), dict) else None
telemetry_metrics: list[dict[str, str]] = []
focus_chips: list[dict[str, str]] = []
related_entities: list[str] = []
if domain == "global":
notice = "五域内置图层共享地球视角与时间口径:高空卫星/BGP弧线与海缆/船舶实体在各自物理或控制面独立校验。"
for s in (snapshot.get("domain_summaries") or []):
telemetry_metrics.append({"label": s["label"], "value": s["metric_text"]})
for code in (snapshot.get("selected_codes") or []):
focus_chips.append({"id": str(code), "label": str(code), "meta": "算力/区域焦点"})
related_entities.append(str(code))
elif domain == "cable":
notice = "海底光缆线网与登陆站拓扑源于内置 ArcGIS 数据集;物理断缆或光功率告警需另行通过运营商实时报文验证。"
telemetry_metrics.extend(
[
{"label": "海缆总量", "value": f"{int(snapshot.get('cables_total') or 0)} 条"},
{"label": "登陆站点", "value": f"{int(snapshot.get('landing_points_total') or 0)} 处"},
{
"label": "前位枢纽国家",
"value": "、".join(
f"{c['country']}({c['landing_point_count']})"
for c in (snapshot.get("top_landing_countries") or [])[:3]
) or "未统计",
},
]
)
for hub in (snapshot.get("top_landing_hubs") or [])[:6]:
focus_chips.append(
{
"id": str(hub.get("name") or hub.get("id")),
"label": str(hub.get("name") or hub.get("city") or hub.get("country")),
"meta": f"{hub.get('country')} · {hub.get('cable_count')} 条海缆",
}
)
related_entities.append(str(hub.get("name") or ""))
elif domain == "satellite":
notice = "在轨星历基于 celestrak_tle 两行轨道根数传播,展示星座分布与轨道体制分层。"
telemetry_metrics.extend(
[
{"label": "在轨追踪样本", "value": f"{int(snapshot.get('satellites_total') or 0)} 颗"},
{
"label": "轨道体制",
"value": "、".join(f"{k} {v}" for k, v in (snapshot.get("by_orbit_regime") or {}).items()) or "未统计",
},
]
)
for group, cnt in list((snapshot.get("by_constellation") or {}).items())[:6]:
focus_chips.append({"id": str(group), "label": str(group), "meta": f"{cnt} 颗"})
related_entities.append(str(group))
else: # vessel
notice = f"AIS 海运船舶聚合窗口覆盖近 {snapshot.get('since_minutes', 60)} 分钟观测样本。"
telemetry_metrics.extend(
[
{"label": "活跃船舶数", "value": f"{int(snapshot.get('vessels_total') or 0)} 艘"},
{"label": "在航 / 锚泊", "value": f"{int(snapshot.get('underway') or 0)} / {int(snapshot.get('anchored_or_moored') or 0)}"},
{
"label": "高频船籍",
"value": "、".join(f"{k}({v})" for k, v in list((snapshot.get("top_flags") or {}).items())[:3]) or "未统计",
},
]
)
for v in (snapshot.get("sample_vessels") or [])[:6]:
focus_chips.append(
{
"id": str(v.get("mmsi") or v.get("name")),
"label": str(v.get("name") or v.get("mmsi")),
"meta": f"{v.get('vessel_type_name')} · {v.get('sog') if v.get('sog') is not None else '—'} kn",
}
)
related_entities.append(str(v.get("mmsi") or v.get("name") or ""))
if focused and focused.get("name"):
related_entities.insert(0, str(focused["name"]))
return {
"topology_kind": f"{domain}_summary",
"domain": domain,
"network_layer_notice": notice,
"focused_entity": focused,
"telemetry_metrics": telemetry_metrics,
"focus_chips": focus_chips,
"related_entities": [r for r in dict.fromkeys(related_entities) if r][:8],
"status": "telemetry_online" if snapshot.get("available") else "standby_or_empty",
}
def compile_spatial_domain_view_spec(
*,
domain_res: dict[str, Any],
preset: ViewPreset = "default",
auto_play: bool = False,
) -> tuple[ViewSpec, SceneSpec]:
"""Compile ViewSpec & SceneSpec for `global`, `cable`, `satellite`, or `vessel`."""
from app.services.ai.workflow_runtime import (
SceneSpec,
ViewSpec,
WorkbenchBlockSpec,
verify_view_spec_consistency,
)
domain: SpatialDomain = domain_res["domain"]
payload = dict(domain_res.get("payload") or {})
snapshot = dict(domain_res.get("snapshot") or {})
evidence_map: dict[str, dict[str, Any]] = dict(domain_res.get("evidence") or {})
rev_num = int(domain_res.get("revision") or 0)
time_basis: TimeBasis = domain_res.get("time_basis") or "retrospective"
cutoff_at = domain_res.get("cutoff_at")
replay_supported = bool(domain_res.get("replay_supported", True))
replay_notice = domain_res.get("replay_notice") or (
_INCOMPLETE_SPATIAL_REPLAY_NOTICE if not replay_supported else None
)
primary_eid = _primary_evidence_id(evidence_map, domain)
evidence_items = []
for eid, ev in evidence_map.items():
ev_hash = hashlib.sha256(json.dumps(ev, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:12]
evidence_items.append(
{
"evidence_id": eid,
"title": str(ev.get("title") or eid),
"publisher": str(ev.get("publisher") or ""),
"published_at": str(ev.get("published_at") or ""),
"locator": str(ev.get("locator") or ""),
"url": str(ev.get("url") or ""),
"sha256_prefix": ev_hash,
}
)
matrix_rows, unit_hint = _build_spatial_matrix_rows(domain, snapshot, primary_eid) if replay_supported else ([], "")
topology_data = _build_spatial_topology_data(domain, snapshot) if replay_supported else {
"topology_kind": f"{domain}_summary",
"domain": domain,
"network_layer_notice": _INCOMPLETE_SPATIAL_REPLAY_NOTICE,
"telemetry_metrics": [],
"focus_chips": [],
"related_entities": [],
"status": "incomplete_snapshot",
}
causal_data = {
"executive_assertion": str(payload.get("executive_assertion") or ""),
"math_decomposition": [],
"causal_candidates": [
{
"label": f"已核验态势 #{idx + 1}",
"detail": str(item.get("statement") or ""),
"evidence_ids": [eid for eid in (item.get("evidence_ids") or []) if eid in evidence_map],
}
for idx, item in enumerate(payload.get("confirmed_facts") or [])
],
"counter_evidence_and_levers": [
{
"label": f"域边界说明 #{idx + 1}",
"detail": str(item.get("statement") or ""),
"evidence_ids": [eid for eid in (item.get("evidence_ids") or []) if eid in evidence_map],
}
for idx, item in enumerate(payload.get("analytical_notes") or [])
],
"unknown_gaps": list(payload.get("open_gaps") or [])
+ ([replay_notice] if replay_notice else []),
}
zh_title, en_title = _DOMAIN_TITLES[domain]
onepager_data = {
"headline": str(payload.get("title") or zh_title),
"scope_line": f"域:{domain} · 标的:{payload.get('subject_key', domain)} · 口径:{time_basis}" + (f" · Rev.{rev_num}" if rev_num else ""),
"revision_tag": f"Rev.{rev_num}" if rev_num else "实时",
"executive_assertion": str(payload.get("executive_assertion") or ""),
"key_metrics": [f"{m['label']}:{m['value']}" for m in (topology_data.get("telemetry_metrics") or [])] if replay_supported else ["快照缺失:不支持完整数据重放"],
"core_takeaways": [str(item.get("statement") or "") for item in (payload.get("confirmed_facts") or [])[:4]],
"boundary_notes": list(causal_data["unknown_gaps"]),
"replay_supported": replay_supported,
}
blocks: list[WorkbenchBlockSpec] = []
if preset == "onepager":
blocks.append(
WorkbenchBlockSpec(
block_id=f"blk-{domain}-onepager",
block_type="executive_onepager",
title=f"{zh_title}一页简报",
title_en=f"{en_title} One-Pager",
data=onepager_data,
)
)
else:
if preset in {"default", "comparison", "table"} and replay_supported:
blocks.append(
WorkbenchBlockSpec(
block_id=f"blk-{domain}-matrix",
block_type="comparison_matrix",
title=f"{zh_title}结构对照",
title_en=f"{en_title} Comparison",
data={
"mode": domain,
"unit": unit_hint,
"view_style": "table" if preset == "table" else "bars",
"entity_column_label": "数据域 / 分类" if domain == "global" else "对象 / 分组",
"entity_column_label_en": "Domain / Category",
"rows": matrix_rows,
"replay_supported": replay_supported,
},
)
)
if preset in {"default", "topology"} and replay_supported:
blocks.append(
WorkbenchBlockSpec(
block_id=f"blk-{domain}-topology",
block_type="impact_topology",
title="空间构成与焦点实体",
title_en="Spatial Composition & Focus Entities",
data=topology_data,
)
)
if preset in {"default", "causal", "comparison", "table", "topology"}:
blocks.append(
WorkbenchBlockSpec(
block_id=f"blk-{domain}-causal",
block_type="causal_brief",
title="态势研判与口径边界",
title_en="Situational Findings & Boundaries",
data=causal_data,
)
)
blocks.append(
WorkbenchBlockSpec(
block_id=f"blk-{domain}-evidence",
block_type="evidence_drawer",
title=f"内置数据源核验记录({len(evidence_items)})",
title_en=f"Telemetry Provenance ({len(evidence_items)})",
collapsed=(preset != "evidence"),
data={"items": evidence_items, "withheld_source_ids": []},
)
)
verify_view_spec_consistency(
blocks,
evidence_map,
matrix_rows=matrix_rows if (replay_supported and preset in {"default", "comparison", "table"}) else None,
)
followups_map: dict[SpatialDomain, list[str]] = {
"global": [
"展开当前海缆与登陆站骨干态势",
"分析当前在轨卫星星座轨道分布",
"查看当前近 60 分钟 AIS 船舶航行态势",
],
"cable": [
"哪些国家的海缆登陆站最集中?",
"切换到全球多域综合态势对照",
"做成一页海缆态势简报",
],
"satellite": [
"LEO、MEO、GEO 各轨道卫星有多少颗?",
"在三维地球上演绎空间态势导览",
"做成一页卫星编目简报",
],
"vessel": [
"目前在航和锚泊的船舶比例与主力船型是什么?",
"切换到海缆图层对照海缆登陆枢纽",
"做成一页海运 AIS 简报",
],
}
highlight_entities = list(topology_data.get("related_entities") or [])
if domain == "global" and not highlight_entities:
highlight_entities = list(snapshot.get("selected_codes") or ["CN", "US"])
view_spec = ViewSpec(
view_id=f"view-{payload.get('subject_key', domain)}-v{rev_num}-{preset}",
active_preset=preset,
available_presets=_spatial_available_presets(),
headline=str(payload.get("title") or zh_title),
headline_en=en_title,
subtitle=f"{zh_title}" + (f" · Rev.{rev_num}" if rev_num else "") + (" · 不支持完整重放" if not replay_supported else ""),
is_drill=False,
time_basis=time_basis,
cutoff_at=cutoff_at,
replay_supported=replay_supported,
replay_status="frozen" if replay_supported else "incomplete_snapshot",
replay_notice=replay_notice,
blocks=blocks,
followups=followups_map[domain],
)
scene_spec = SceneSpec(
domain=domain,
highlight_entities=highlight_entities[:8],
compute_mode=None,
focus_year=None,
enable_national_hubs=False,
camera_hint=snapshot.get("camera_hint") if isinstance(snapshot.get("camera_hint"), dict) else None,
presentation_key=f"spatial-{domain}-tour",
auto_play_presentation=auto_play,
)
return view_spec, scene_spec