713 lines
32 KiB
Python
713 lines
32 KiB
Python
"""ContextualCopilotAgent (F-21) & revision-bound Markdown strategic report exporter (F-22 · R2/R5/R6/R7 hardened)."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
from datetime import UTC, datetime
|
||
import hashlib
|
||
import json
|
||
import re
|
||
from typing import Any, Literal
|
||
|
||
from fastapi import HTTPException
|
||
from pydantic import BaseModel, ConfigDict, Field
|
||
from sqlalchemy import desc, select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from app.ai_tasks.prompts import get_effective_prompt
|
||
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,
|
||
ReportSubjectType,
|
||
WorkbenchDomain,
|
||
subject_type_to_domain,
|
||
)
|
||
from app.services.ai.incident_agent import (
|
||
DRILL_INCIDENT_KEY,
|
||
investigate_infrastructure_incident,
|
||
)
|
||
from app.services.ai.posture_agent import generate_or_get_compute_posture
|
||
from app.services.ai.spatial_domain_agent import investigate_spatial_domain
|
||
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_compute_posture_tool
|
||
from app.services.ai_client import AIProviderClient
|
||
|
||
logger = get_logger(__name__, service="ai_copilot")
|
||
|
||
|
||
class CopilotKeyPoint(BaseModel):
|
||
model_config = ConfigDict(extra="forbid")
|
||
|
||
claim: str = Field(min_length=1, max_length=600)
|
||
evidence_ids: list[str] = Field(min_length=1, max_length=6)
|
||
|
||
|
||
class CopilotInvestigationReply(BaseModel):
|
||
model_config = ConfigDict(extra="forbid")
|
||
|
||
answer_markdown: str = Field(min_length=1, max_length=4000)
|
||
key_points: list[CopilotKeyPoint] = Field(default_factory=list, max_length=8)
|
||
highlight_entities: list[str] = Field(default_factory=list, max_length=16)
|
||
suggested_followups: list[str] = Field(default_factory=list, max_length=6)
|
||
evidence_ids: list[str] = Field(min_length=1, max_length=16)
|
||
|
||
|
||
def normalize_copilot_markdown(text: str) -> str:
|
||
"""Ensure headings and bullet items emitted inline by LLMs break onto clean Markdown lines."""
|
||
normalized = (text or "").replace("\r\n", "\n").strip()
|
||
normalized = re.sub(
|
||
r"(^|\n)(#{1,4}\s+[^\n]+?)\s+(?=(?:[-*•]|\d+[.)])\s+)",
|
||
r"\1\2\n\n",
|
||
normalized,
|
||
)
|
||
normalized = re.sub(
|
||
r"([。!?;;::])\s+(?=(?:[-*•]|\d+[.)])\s+\*\*)",
|
||
r"\1\n",
|
||
normalized,
|
||
)
|
||
return normalized
|
||
|
||
|
||
def _deterministic_compute_copilot_reply(
|
||
question: str,
|
||
series: dict[str, Any],
|
||
entity_id: str | None,
|
||
*,
|
||
codes: list[str] | None = None,
|
||
mode: str = "global_share",
|
||
) -> CopilotInvestigationReply:
|
||
evidence = series.get("evidence") or {}
|
||
rpi = series.get("bilateral_rpi") or {}
|
||
tot = rpi.get("latest_total") or {}
|
||
intel = rpi.get("latest_intelligent") or {}
|
||
chip = rpi.get("latest_chip_inflow") or {}
|
||
attr = (series.get("denominator_attribution") or {}).get("CN") or {}
|
||
cn_struct = (series.get("structures") or {}).get("CN") or {}
|
||
innov = series.get("innovation_summary") or {}
|
||
hubs = series.get("national_hubs") or []
|
||
time_basis = series.get("time_basis") or "retrospective"
|
||
cutoff_at = series.get("cutoff_at")
|
||
withheld_sources = series.get("withheld_source_ids") or []
|
||
|
||
fallback_eid = next(iter(evidence.keys()), "unconfigured")
|
||
q_lower = question.lower()
|
||
highlights: list[str] = []
|
||
if entity_id:
|
||
highlights.append(entity_id)
|
||
|
||
cutoff_note = (
|
||
f"\n\n> **历史回放截点**:当前按 `as_known_then`(截至 `{cutoff_at}`)过滤,已隔离 `{len(withheld_sources)}` 份截点后发布报告。"
|
||
if time_basis == "as_known_then" and cutoff_at
|
||
else ""
|
||
)
|
||
|
||
if not evidence:
|
||
return CopilotInvestigationReply(
|
||
answer_markdown=(
|
||
"### 所选范围或历史截点暂无已核验可比报告\n\n"
|
||
"- 当前国家/区域组合或时间截点尚无权威白皮书同年同口径完整观测记录。\n"
|
||
"- 系统严格保持数值留白,绝不以局部设施采集样本外推国家总算力。"
|
||
),
|
||
key_points=[],
|
||
highlight_entities=list(dict.fromkeys([*(codes or []), *highlights]))[:8],
|
||
suggested_followups=["切换回中美全球总算力份额对照", "查看 2024 智算份额与分母稀释拆解"],
|
||
evidence_ids=["unconfigured"],
|
||
)
|
||
|
||
if any(kw in q_lower for kw in ("枢纽", "东数西算", "绿电", "pue", "hub", "west")) and hubs:
|
||
hub_ids = [h["id"] for h in hubs]
|
||
highlights.extend(["CN", *hub_ids[:8]])
|
||
eid = hubs[0]["source_id"] if hubs[0].get("source_id") in evidence else fallback_eid
|
||
eids = [eid] + (["caict-2025"] if "caict-2025" in evidence and eid != "caict-2025" else [])
|
||
return CopilotInvestigationReply(
|
||
answer_markdown=(
|
||
"### “东数西算”八大国家算力枢纽空间协同解析\n\n"
|
||
"- **四大东部算力需求枢纽**(京津冀、长三角、粤港澳大湾区、成渝):聚焦高频低时延 AI 推理、工业互联网与金融实时业务,PUE 严控于 `1.20–1.25`。\n"
|
||
"- **四大西部绿色算力枢纽**(内蒙古和林格尔、贵州贵安、甘肃庆阳、宁夏中卫):依托风光水清洁能源与冷凉气候承接万卡级大模型离线训练与温冷数据底座(PUE 目标 `≤ 1.20`)。\n"
|
||
f"- **战略意义**:依托跨区域绿电调度有效对冲先进制程单卡能效受限带来的电力成本压力。{cutoff_note}"
|
||
),
|
||
key_points=[
|
||
CopilotKeyPoint(
|
||
claim="八大国家算力枢纽形成“东推西训、绿电结对”格局,西部枢纽目标 PUE ≤ 1.20。",
|
||
evidence_ids=[eid],
|
||
),
|
||
],
|
||
highlight_entities=list(dict.fromkeys(highlights)),
|
||
suggested_followups=[
|
||
"为什么中国算力绝对规模大涨,但全球份额出现回落?",
|
||
"只看中美智能算力份额与双边 RPI 对照",
|
||
"做成一页决策简报",
|
||
],
|
||
evidence_ids=list(dict.fromkeys(eids)),
|
||
)
|
||
|
||
if any(kw in q_lower for kw in ("创新", "分差", "效率", "innovation", "moe", "17.95")) and innov:
|
||
highlights.extend(["CN", "US"])
|
||
eids = [eid for eid in ("innovation-2026", "caict-2025") if eid in evidence] or [fallback_eid]
|
||
return CopilotInvestigationReply(
|
||
answer_markdown=(
|
||
"### 硬件份额承压与 AI 创新分差连续收窄的非对称逻辑\n\n"
|
||
f"1. **综合创新差距持续收敛**:据中信所报告,中美 AI 创新指数综合分差由 `{innov.get('from_year', 2023)}` 年的 "
|
||
f"`{innov.get('from_value', 22.02)}` 分连续收窄至 `{innov.get('to_year', 2025)}` 年的 `{innov.get('to_value', 17.95)}` 分(累计缩窄 `{abs(innov.get('delta', -4.07))}` 分)。\n"
|
||
f"2. **算力底座内部提质**:虽然我国全球智能算力竞争份额为 `{intel.get('cn_value', 21)}%`(美国 `{intel.get('us_value', 46)}%`),但我国本国算力设备中智能算力占比已达 `{cn_struct.get('intelligent_share', 81)}%`。\n"
|
||
f"3. **工程与架构增效**:稀疏混合专家(MoE)、混合精度训练与国产集群软硬协同提升了单位 FLOPs 的模型能力产出。{cutoff_note}"
|
||
),
|
||
key_points=[
|
||
CopilotKeyPoint(
|
||
claim=f"中美 AI 创新指数分差连续下降({innov.get('from_value', 22.02)} → {innov.get('to_value', 17.95)} 分)。",
|
||
evidence_ids=[eids[0]],
|
||
),
|
||
],
|
||
highlight_entities=list(dict.fromkeys(highlights)),
|
||
suggested_followups=[
|
||
"下钻查看“东数西算”八大国家算力枢纽如何支撑绿电训练?",
|
||
"换成数据表视图",
|
||
],
|
||
evidence_ids=eids,
|
||
)
|
||
|
||
highlights.extend(codes or ["CN", "US"])
|
||
eids = [
|
||
eid
|
||
for eid in ("caict-2025", "caict-2024", "caict-2023", "epoch-chip-imports-2026", "innovation-2026")
|
||
if eid in evidence
|
||
] or [fallback_eid]
|
||
|
||
if not tot:
|
||
# Multilateral or non-CN/US comparison (e.g. JP / EUROPE / DE)
|
||
rows_txt = []
|
||
comp_rows = list(series.get("compute") or [])
|
||
for code in (codes or []):
|
||
meta = next((c for c in (series.get("countries") or []) if c.get("code") == code), {})
|
||
label = meta.get("name") or meta.get("name_zh") or code
|
||
latest_hit = next(
|
||
(r for r in reversed(comp_rows) if (r.get("values") or {}).get(code) is not None),
|
||
None,
|
||
)
|
||
if latest_hit:
|
||
val = latest_hit["values"][code]
|
||
rows_txt.append(f"- **{label}**({latest_hit['year']}):`{val:g}` {series.get('unit', '%')}")
|
||
else:
|
||
rows_txt.append(f"- **{label}**:暂无同年同口径公开发布值(保持留白)")
|
||
return CopilotInvestigationReply(
|
||
answer_markdown="### 多边算力已核验观测对照\n\n" + "\n".join(rows_txt) + cutoff_note,
|
||
key_points=[],
|
||
highlight_entities=list(dict.fromkeys(highlights))[:8],
|
||
suggested_followups=["切换回中美算力博弈双边对照", "换成数据表视图"],
|
||
evidence_ids=eids[:2],
|
||
)
|
||
|
||
mode_banner = (
|
||
f"当前聚焦口径:**智能算力全球份额**(中国 `{intel['cn_value']}%` vs 美国 `{intel['us_value']}%`,RPI `{intel['rpi_percent']}%`)。"
|
||
if mode == "intelligent_share" and intel
|
||
else f"当前聚焦口径:**{tot.get('year')} 年全球总算力份额**(中国 `{tot.get('cn_value')}%` vs 美国 `{tot.get('us_value')}%`,RPI `{tot.get('rpi_percent')}%`)。"
|
||
)
|
||
denom_line = (
|
||
f"- **分母膨胀数学分解**:我国绝对总算力由 `{attr['country_from']:.0f}` 跃升至 `{attr['country_to']:.0f}` EFlops(`+{attr['country_growth_pct']}%`),全球总算力由 `{attr['global_from']:.0f}` 增至 `{attr['global_to']:.0f}` EFlops(`+{attr['global_growth_pct']}%`),相对份额回落源于全球分母扩张更快。\n"
|
||
if attr and attr.get("global_to")
|
||
else ""
|
||
)
|
||
chip_line = (
|
||
f"- **高端芯片流向约束**:公开统计的高端 AI 芯片新增算力约 `{chip['us_value']}%` 流向美国、我国约 `{chip['cn_value']}%`。"
|
||
if chip
|
||
else ""
|
||
)
|
||
|
||
return CopilotInvestigationReply(
|
||
answer_markdown=(
|
||
"### 中美算力态势对照与分母归因\n\n"
|
||
f"- {mode_banner}\n"
|
||
f"{denom_line}{chip_line}{cutoff_note}"
|
||
).strip(),
|
||
key_points=[
|
||
CopilotKeyPoint(
|
||
claim=f"截至 {tot.get('year')} 年中美全球总算力份额为 {tot.get('cn_value')}% vs {tot.get('us_value')}%(RPI {tot.get('rpi_percent')}%)。",
|
||
evidence_ids=[eids[0]],
|
||
),
|
||
],
|
||
highlight_entities=list(dict.fromkeys(highlights)),
|
||
suggested_followups=[
|
||
"只看智能算力份额对照",
|
||
"算力份额承压下,为什么中美 AI 创新指数分差反而连续收窄?",
|
||
"换成数据表视图",
|
||
],
|
||
evidence_ids=eids,
|
||
)
|
||
|
||
|
||
def _raise_if_cancelled(cancel_event: asyncio.Event | None) -> None:
|
||
if cancel_event is not None and cancel_event.is_set():
|
||
raise asyncio.CancelledError()
|
||
|
||
|
||
async def run_contextual_copilot(
|
||
db: AsyncSession,
|
||
*,
|
||
domain: WorkbenchDomain = "compute",
|
||
selected_codes: list[str] | None = None,
|
||
focus_year: int | None = None,
|
||
mode: str = "global_share",
|
||
entity_id: str | None = None,
|
||
visible_layers: dict[str, bool] | None = None,
|
||
question: str,
|
||
time_basis: TimeBasis = "retrospective",
|
||
cutoff_at: str | None = None,
|
||
allow_drill: bool = False,
|
||
series_override: dict[str, Any] | None = None,
|
||
posture_override: dict[str, Any] | None = None,
|
||
ai_client: AIProviderClient | None = None,
|
||
cancel_event: asyncio.Event | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Answer user spatial follow-up questions with verified evidence citations and 3D highlight IDs."""
|
||
_raise_if_cancelled(cancel_event)
|
||
codes = selected_codes or ["CN", "US"]
|
||
if domain == "bgp":
|
||
effective_drill = allow_drill or entity_id == DRILL_INCIDENT_KEY
|
||
incident_res = await investigate_infrastructure_incident(
|
||
db,
|
||
incident_key=entity_id,
|
||
question=question,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
allow_drill=effective_drill,
|
||
ai_client=ai_client,
|
||
cancel_event=cancel_event,
|
||
)
|
||
evidence_map = incident_res["evidence"]
|
||
payload = incident_res["payload"]
|
||
incident = incident_res.get("incident") or {}
|
||
primary_eid = next(iter(evidence_map.keys()))
|
||
|
||
region_highlights: list[str] = [payload["incident_key"]]
|
||
for reg in incident.get("affected_regions") or []:
|
||
if isinstance(reg, str):
|
||
region_highlights.append(reg)
|
||
elif isinstance(reg, dict) and reg.get("collector"):
|
||
region_highlights.append(str(reg["collector"]))
|
||
|
||
reply = CopilotInvestigationReply(
|
||
answer_markdown=(
|
||
f"### 事件上下文取证:{payload['title']}\n\n"
|
||
+ "\n".join(f"- **已核验事实**:{item['statement']}" for item in payload["confirmed_facts"])
|
||
+ (
|
||
"\n" + "\n".join(f"- **候选研判**:{item['statement']}" for item in payload["candidate_explanations"])
|
||
if payload.get("candidate_explanations")
|
||
else ""
|
||
)
|
||
+ (
|
||
"\n" + "\n".join(f"- **待查缺口**:{g}" for g in payload["open_gaps"][:2])
|
||
if payload.get("open_gaps")
|
||
else ""
|
||
)
|
||
+ f"\n\n> **海缆关联边界**:{payload['cable_correlation_policy']}"
|
||
),
|
||
key_points=[
|
||
CopilotKeyPoint(claim=item["statement"], evidence_ids=item["evidence_ids"])
|
||
for item in payload["confirmed_facts"][:2]
|
||
],
|
||
highlight_entities=region_highlights[:6],
|
||
suggested_followups=[
|
||
"这次事件影响谁、涉及哪些前缀和观测站?",
|
||
"这次路由异动和附近海底光缆有关吗?",
|
||
"若按“当时可知”回放模式过滤,哪些事后信息会被隔离?",
|
||
],
|
||
evidence_ids=list(evidence_map.keys()) or [primary_eid],
|
||
)
|
||
return {
|
||
"domain": domain,
|
||
"subject_key": payload["incident_key"],
|
||
"revision": incident_res["revision"],
|
||
"is_drill": incident_res.get("is_drill", False),
|
||
"analysis_focus": incident_res.get("analysis_focus", "overview"),
|
||
"generation_mode": incident_res["generation_mode"],
|
||
"usage": incident_res.get("usage") or {},
|
||
"reply": reply.model_dump(mode="json"),
|
||
"evidence": evidence_map,
|
||
}
|
||
|
||
if domain in SPATIAL_POSTURE_DOMAINS:
|
||
dom_res = await investigate_spatial_domain(
|
||
db,
|
||
domain=domain, # type: ignore[arg-type]
|
||
question=question,
|
||
selected_codes=codes,
|
||
entity_id=entity_id,
|
||
visible_layers=visible_layers,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
ai_client=ai_client,
|
||
cancel_event=cancel_event,
|
||
)
|
||
payload = dom_res["payload"]
|
||
evidence_map = dom_res["evidence"]
|
||
primary_eid = next(iter(evidence_map.keys()))
|
||
facts = payload.get("confirmed_facts") or []
|
||
gaps = payload.get("open_gaps") or []
|
||
snapshot = dom_res.get("snapshot") or {}
|
||
highlights = [entity_id] if entity_id else []
|
||
if not highlights:
|
||
focused = snapshot.get("focused_entity") if isinstance(snapshot.get("focused_entity"), dict) else None
|
||
if focused and focused.get("name"):
|
||
highlights.append(str(focused["name"]))
|
||
elif domain == "global":
|
||
highlights.extend(codes[:4])
|
||
reply = CopilotInvestigationReply(
|
||
answer_markdown=(
|
||
f"### {payload['title']}\n\n"
|
||
+ f"{payload.get('executive_assertion') or ''}\n\n"
|
||
+ "\n".join(f"- **已核验态势**:{item['statement']}" for item in facts)
|
||
+ ("\n" + "\n".join(f"- **口径边界**:{g}" for g in gaps[:2]) if gaps else "")
|
||
).strip(),
|
||
key_points=[
|
||
CopilotKeyPoint(claim=item["statement"], evidence_ids=item["evidence_ids"])
|
||
for item in facts[:2]
|
||
],
|
||
highlight_entities=highlights[:6],
|
||
suggested_followups=[
|
||
"换成数据表查看结构化明细",
|
||
"在三维地球上演绎空间态势导览",
|
||
"做成一页态势简报",
|
||
],
|
||
evidence_ids=list(evidence_map.keys()) or [primary_eid],
|
||
)
|
||
return {
|
||
"domain": domain,
|
||
"subject_key": dom_res["subject_key"],
|
||
"revision": dom_res["revision"],
|
||
"generation_mode": dom_res["generation_mode"],
|
||
"usage": dom_res.get("usage") or {},
|
||
"reply": reply.model_dump(mode="json"),
|
||
"evidence": evidence_map,
|
||
}
|
||
|
||
series = series_override or await query_compute_posture_tool(
|
||
db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at
|
||
)
|
||
_raise_if_cancelled(cancel_event)
|
||
posture = posture_override or await generate_or_get_compute_posture(
|
||
db,
|
||
countries=codes,
|
||
mode=mode,
|
||
series_payload=series,
|
||
ai_client=ai_client,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
cancel_event=cancel_event,
|
||
)
|
||
evidence_map = series.get("evidence") or {}
|
||
reply_obj: CopilotInvestigationReply | None = None
|
||
generation_mode = "deterministic_baseline"
|
||
llm_usage: dict[str, Any] = {}
|
||
|
||
if ai_client is not None and ai_client.service_url and evidence_map:
|
||
_raise_if_cancelled(cancel_event)
|
||
try:
|
||
prompt_def = await get_effective_prompt(db, "situational.copilot.reply")
|
||
_raise_if_cancelled(cancel_event)
|
||
effective_ai_client, thinking_arg = prepare_situational_ai_call(ai_client)
|
||
compact_evidence = {
|
||
eid: {
|
||
"title": ev.get("title"),
|
||
"publisher": ev.get("publisher"),
|
||
"published_at": ev.get("published_at"),
|
||
"locator": ev.get("locator"),
|
||
}
|
||
for eid, ev in evidence_map.items()
|
||
}
|
||
llm_resp = await effective_ai_client.analyze(
|
||
SituationalAnalysisRequest(
|
||
title="地球空间上下文追问",
|
||
objective=(
|
||
f"{prompt_def.prompt}\n\n"
|
||
f"用户问题:{question}\n"
|
||
"严格输出单个紧凑 JSON 对象(不加围栏外文字),字段结构:\n"
|
||
'{"answer_markdown": str, "key_points": [{"claim": str, "evidence_ids": [str]}], '
|
||
'"highlight_entities": [str], "suggested_followups": [str], "evidence_ids": [str]}'
|
||
),
|
||
system_prompt=prompt_def.system_prompt,
|
||
context={
|
||
"domain": domain,
|
||
"selected_codes": codes,
|
||
"focus_year": focus_year,
|
||
"mode": mode,
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"entity_id": entity_id,
|
||
"bilateral_rpi": series.get("bilateral_rpi"),
|
||
"denominator_attribution": series.get("denominator_attribution"),
|
||
"structures": series.get("structures"),
|
||
"innovation_summary": series.get("innovation_summary"),
|
||
"national_hubs": series.get("national_hubs"),
|
||
"evidence": compact_evidence,
|
||
},
|
||
constraints=[
|
||
"Return strict JSON matching CopilotInvestigationReply.",
|
||
"Every evidence_id must exist in context.evidence.",
|
||
"Never leak <think> or chain-of-thought.",
|
||
],
|
||
thinking=thinking_arg,
|
||
)
|
||
)
|
||
_raise_if_cancelled(cancel_event)
|
||
parsed = extract_json_object(llm_resp.content)
|
||
if parsed:
|
||
candidate = CopilotInvestigationReply.model_validate(parsed)
|
||
cited = list(candidate.evidence_ids) + [
|
||
eid for kp in candidate.key_points for eid in kp.evidence_ids
|
||
]
|
||
if any(eid not in evidence_map for eid in cited):
|
||
raise ValueError("Copilot reply cited unknown evidence_id")
|
||
assert_no_thinking_leak(candidate.model_dump(mode="json"))
|
||
candidate = candidate.model_copy(
|
||
update={"answer_markdown": normalize_copilot_markdown(candidate.answer_markdown)}
|
||
)
|
||
reply_obj = candidate
|
||
generation_mode = "llm_verified"
|
||
llm_usage = extract_response_usage(llm_resp)
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Copilot LLM call fell back to deterministic domain analyst",
|
||
event="ai_copilot.llm.fallback",
|
||
context={"error": str(exc)},
|
||
)
|
||
|
||
if reply_obj is None:
|
||
reply_obj = _deterministic_compute_copilot_reply(
|
||
question, series, entity_id, codes=codes, mode=mode
|
||
)
|
||
|
||
return {
|
||
"domain": domain,
|
||
"subject_key": posture["subject_key"],
|
||
"revision": posture["revision"],
|
||
"config_version": series.get("version"),
|
||
"generation_mode": generation_mode,
|
||
"usage": llm_usage,
|
||
"reply": reply_obj.model_dump(mode="json"),
|
||
"evidence": {eid: evidence_map[eid] for eid in reply_obj.evidence_ids if eid in evidence_map},
|
||
}
|
||
|
||
|
||
async def export_revision_bound_markdown_report(
|
||
db: AsyncSession,
|
||
*,
|
||
subject_type: ReportSubjectType = "compute_posture",
|
||
countries: list[str] | None = None,
|
||
mode: str = "global_share",
|
||
incident_key: str | None = None,
|
||
result_id: str | None = None,
|
||
expected_revision: int | None = None,
|
||
time_basis: TimeBasis = "retrospective",
|
||
cutoff_at: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Export citation-complete Markdown strictly bound to stored `(subject_key, expected_revision)` with 0 DB writes (R7)."""
|
||
from app.services.ai.workflow_runtime import format_frozen_revision_markdown, read_frozen_result_revision
|
||
|
||
codes = countries or ["CN", "US"]
|
||
basis_suffix = f":as_known_then:{cutoff_at}" if time_basis == "as_known_then" and cutoff_at else ""
|
||
if result_id:
|
||
target_key = result_id
|
||
elif subject_type == "bgp_incident":
|
||
target_key = incident_key
|
||
elif subject_type == "global_posture":
|
||
target_key = f"global:{','.join(codes)}:{time_basis}"
|
||
elif subject_type in {"cable_posture", "satellite_posture", "vessel_posture"}:
|
||
dom = subject_type_to_domain(subject_type)
|
||
target_key = f"{dom}:{incident_key or 'global'}:{time_basis}"
|
||
else:
|
||
target_key = f"compute:{','.join(codes)}:{mode}{basis_suffix}"
|
||
|
||
if target_key and hasattr(db, "execute"):
|
||
try:
|
||
latest_rev = (
|
||
await db.execute(
|
||
select(SituationalAssessment.revision)
|
||
.where(
|
||
SituationalAssessment.subject_type == subject_type,
|
||
SituationalAssessment.subject_key == target_key,
|
||
)
|
||
.order_by(desc(SituationalAssessment.revision))
|
||
.limit(1)
|
||
)
|
||
).scalar_one_or_none()
|
||
|
||
if expected_revision is not None:
|
||
exact_row = (
|
||
await db.execute(
|
||
select(SituationalAssessment)
|
||
.where(
|
||
SituationalAssessment.subject_type == subject_type,
|
||
SituationalAssessment.subject_key == target_key,
|
||
SituationalAssessment.revision == expected_revision,
|
||
)
|
||
.limit(1)
|
||
)
|
||
).scalar_one_or_none()
|
||
if exact_row is not None:
|
||
return await read_frozen_result_revision(
|
||
db,
|
||
result_id=target_key,
|
||
revision=expected_revision,
|
||
output_format="markdown",
|
||
)
|
||
if isinstance(latest_rev, int) and expected_revision != latest_rev:
|
||
raise HTTPException(
|
||
status_code=409,
|
||
detail=f"Revision mismatch: requested revision {expected_revision}, available latest revision is {latest_rev}.",
|
||
)
|
||
elif isinstance(latest_rev, int):
|
||
return await read_frozen_result_revision(
|
||
db,
|
||
result_id=target_key,
|
||
revision=latest_rev,
|
||
output_format="markdown",
|
||
)
|
||
except HTTPException:
|
||
raise
|
||
except Exception:
|
||
pass
|
||
|
||
# Ephemeral read-only synthesis when no row was persisted yet (0 DB writes!)
|
||
if expected_revision is not None and expected_revision != 1:
|
||
raise HTTPException(
|
||
status_code=409,
|
||
detail=f"Revision mismatch: requested revision {expected_revision}, current verified revision is 1.",
|
||
)
|
||
|
||
now_iso = datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S UTC")
|
||
if subject_type == "bgp_incident":
|
||
inc = await investigate_infrastructure_incident(
|
||
db,
|
||
incident_key=incident_key,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
allow_drill=(incident_key == DRILL_INCIDENT_KEY),
|
||
persist=False,
|
||
)
|
||
payload = inc["payload"]
|
||
evidence = inc["evidence"]
|
||
rev_num = int(inc.get("revision") or 1)
|
||
lines = [
|
||
f"# {payload['title']} — 基础设施异动取证简报",
|
||
"",
|
||
f"- **事件标识**:`{payload['incident_key']}`",
|
||
f"- **绑定研判版本(Revision)**:`v{rev_num}`",
|
||
f"- **时间回放口径**:`{time_basis}`",
|
||
f"- **导出时间**:`{now_iso}`",
|
||
"",
|
||
"## 一、已确认观测事实",
|
||
*[f"- {item['statement']} (证据:`{', '.join(item['evidence_ids'])}`)" for item in payload["confirmed_facts"]],
|
||
"",
|
||
"## 二、候选根因解释",
|
||
*[f"- {item['statement']} (证据:`{', '.join(item['evidence_ids'])}`)" for item in payload["candidate_explanations"]],
|
||
"",
|
||
"## 三、反证与待核查缺口",
|
||
*[f"- **反证排除**:{item}" for item in payload["counter_evidence"]],
|
||
*[f"- **待查缺口**:{item}" for item in payload["open_gaps"]],
|
||
"",
|
||
"## 四、完整参考文献与证据哈希",
|
||
]
|
||
for eid, ev in evidence.items():
|
||
ev_hash = hashlib.sha256(json.dumps(ev, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:16]
|
||
lines.append(
|
||
f"- **[{eid}]** {ev.get('title')} — {ev.get('publisher')} ({ev.get('published_at') or 'N/A'}) · 位置:{ev.get('locator')} · URL: {ev.get('url')} · `sha256:{ev_hash}`"
|
||
)
|
||
markdown = "\n".join(lines)
|
||
return {
|
||
"subject_type": subject_type,
|
||
"subject_key": payload["incident_key"],
|
||
"revision": rev_num,
|
||
"filename": f"planet-incident-report-{payload['incident_key']}-v{rev_num}.md",
|
||
"markdown": markdown,
|
||
"content_sha256": hashlib.sha256(markdown.encode("utf-8")).hexdigest(),
|
||
}
|
||
|
||
if subject_type in {"global_posture", "cable_posture", "satellite_posture", "vessel_posture"}:
|
||
spatial_domain = subject_type_to_domain(subject_type)
|
||
dom_res = await investigate_spatial_domain(
|
||
db,
|
||
domain=spatial_domain, # type: ignore[arg-type]
|
||
selected_codes=codes,
|
||
entity_id=incident_key,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
persist=False,
|
||
)
|
||
frozen_ephemeral = {
|
||
"result_id": dom_res["subject_key"],
|
||
"subject_type": subject_type,
|
||
"subject_key": dom_res["subject_key"],
|
||
"revision": int(dom_res.get("revision") or 1),
|
||
"replay_supported": True,
|
||
"replay_notice": None,
|
||
"newer_revision_notice": None,
|
||
"input_fingerprint": dom_res.get("input_fingerprint") or "",
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||
"payload": dom_res["payload"],
|
||
"evidence": dom_res["evidence"],
|
||
}
|
||
markdown = format_frozen_revision_markdown(frozen_ephemeral)
|
||
safe_slug = dom_res["subject_key"].replace(":", "-")
|
||
return {
|
||
"subject_type": subject_type,
|
||
"subject_key": dom_res["subject_key"],
|
||
"revision": int(dom_res.get("revision") or 1),
|
||
"filename": f"planet-report-{safe_slug}-v{int(dom_res.get('revision') or 1)}.md",
|
||
"markdown": markdown,
|
||
"content_sha256": hashlib.sha256(markdown.encode("utf-8")).hexdigest(),
|
||
}
|
||
|
||
series = await query_compute_posture_tool(
|
||
db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at
|
||
)
|
||
posture = await generate_or_get_compute_posture(
|
||
db,
|
||
countries=codes,
|
||
mode=mode,
|
||
series_payload=series,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
persist=False,
|
||
)
|
||
brief = posture["payload"]
|
||
evidence = series.get("evidence") or {}
|
||
actual_rev = int(posture.get("revision") or 1)
|
||
lines = [
|
||
f"# {brief['headline']}",
|
||
"",
|
||
f"- **对比范围**:`{', '.join(codes)}` · **主视图口径**:`{mode}`",
|
||
f"- **配置版本**:`{series.get('version')}` · **研判版本(Revision)**:`v{actual_rev}`",
|
||
f"- **导出时间**:`{now_iso}`",
|
||
"",
|
||
"## 一、核心战略态势断言",
|
||
"",
|
||
brief["executive_assertion"],
|
||
"",
|
||
"## 二、核心成因拆解",
|
||
*[f"- **{item['label']}**:{item['detail']} (证据:`{', '.join(item['evidence_ids'])}`)" for item in brief["causes"]],
|
||
"",
|
||
"## 三、完整证据链与哈希",
|
||
]
|
||
for eid, ev in evidence.items():
|
||
ev_hash = hashlib.sha256(json.dumps(ev, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:16]
|
||
lines.append(
|
||
f"- **[{eid}]** {ev.get('title')} — {ev.get('publisher')} ({ev.get('published_at') or 'N/A'}) · 位置:{ev.get('locator')} · URL: {ev.get('url')} · `sha256:{ev_hash}`"
|
||
)
|
||
markdown = "\n".join(lines)
|
||
return {
|
||
"subject_type": subject_type,
|
||
"subject_key": posture["subject_key"],
|
||
"revision": actual_rev,
|
||
"filename": f"planet-compute-report-{'-'.join(codes)}-v{actual_rev}.md",
|
||
"markdown": markdown,
|
||
"content_sha256": hashlib.sha256(markdown.encode("utf-8")).hexdigest(),
|
||
}
|