1531 lines
67 KiB
Python
1531 lines
67 KiB
Python
"""Lightweight topological DAG workflow executor for AI Advisor and Earth Copilot."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
from collections import defaultdict, deque
|
||
from datetime import UTC, datetime
|
||
import json
|
||
import re
|
||
from typing import Any, AsyncIterator
|
||
|
||
from app.core.logging import get_logger
|
||
from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest
|
||
from app.services.ai.dag_evidence import EvidenceLedger
|
||
from app.services.ai.scene_directives import (
|
||
INFLUENCE_ZONE_GUIDANCE,
|
||
consume_text_holding_scene_tag,
|
||
extract_planet_scene_from_text,
|
||
merge_scene_specs,
|
||
)
|
||
from app.services.ai.thinking_sanitizer import strip_thinking_text
|
||
from app.services.ai.tool_registry import (
|
||
TimeBasis,
|
||
isolate_untrusted_external_text,
|
||
query_bgp_incidents_tool,
|
||
query_cable_posture_tool,
|
||
query_cloud_posture_tool,
|
||
query_compute_posture_tool,
|
||
query_global_situational_tool,
|
||
query_recent_earth_news_tool,
|
||
query_satellite_posture_tool,
|
||
query_vessel_posture_tool,
|
||
query_wind_posture_tool,
|
||
safe_web_fetch,
|
||
)
|
||
from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES, _extract_first_json_object
|
||
|
||
logger = get_logger(__name__, service="ai_dag_executor")
|
||
|
||
_TEMPLATE_VAR_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}")
|
||
_L1_KNOWLEDGE_TOOL_IDS = frozenset(
|
||
{"builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"}
|
||
)
|
||
|
||
|
||
def summarize_targets(targets: list[dict[str, Any]] | None) -> str:
|
||
"""Format selected Earth targets into a concise deterministic summary."""
|
||
if not targets:
|
||
return "全球多域当前态势"
|
||
parts: list[str] = []
|
||
for item in targets[:8]:
|
||
etype = str(item.get("entity_type") or item.get("type") or "entity").strip()
|
||
label = str(item.get("label") or item.get("name") or item.get("entity_id") or "").strip()
|
||
lat = item.get("latitude")
|
||
lon = item.get("longitude")
|
||
coord = ""
|
||
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
|
||
coord = f"({lat:.2f}, {lon:.2f})"
|
||
token = f"{etype}「{label or etype}」{coord}"
|
||
parts.append(token)
|
||
return "; ".join(parts)
|
||
|
||
|
||
def render_workflow_template(
|
||
template: str,
|
||
*,
|
||
question: str = "",
|
||
targets: list[dict[str, Any]] | None = None,
|
||
node_outputs: dict[str, str] | None = None,
|
||
node_data: dict[str, dict[str, Any]] | None = None,
|
||
workflow_state: dict[str, Any] | None = None,
|
||
) -> str:
|
||
"""Interpolate `{{...}}` placeholders safely without Python `.format` or eval."""
|
||
raw = str(template or "")
|
||
if not raw or "{{" not in raw:
|
||
return raw
|
||
first = targets[0] if targets else {}
|
||
outputs = node_outputs or {}
|
||
structured = node_data or {}
|
||
state = workflow_state or {}
|
||
targets_summary = summarize_targets(targets)
|
||
|
||
def _serialize_val(val: Any) -> str:
|
||
if val is None:
|
||
return ""
|
||
if isinstance(val, (dict, list)):
|
||
return json.dumps(val, ensure_ascii=False, default=str)[:4000]
|
||
return str(val)[:4000]
|
||
|
||
def _lookup(key: str) -> str:
|
||
if key == "question":
|
||
return question
|
||
if key == "targets_summary":
|
||
return targets_summary
|
||
if key.startswith("target."):
|
||
sub = key[len("target.") :]
|
||
if sub == "label":
|
||
return str(first.get("label") or first.get("name") or "")
|
||
if sub == "type":
|
||
return str(first.get("entity_type") or first.get("type") or "")
|
||
if sub == "id":
|
||
return str(first.get("entity_id") or first.get("id") or "")
|
||
if sub == "lat":
|
||
val = first.get("latitude")
|
||
return f"{val:.4f}" if isinstance(val, (int, float)) else ""
|
||
if sub == "lon":
|
||
val = first.get("longitude")
|
||
return f"{val:.4f}" if isinstance(val, (int, float)) else ""
|
||
if sub in {"kind", "layer"}:
|
||
return str(first.get(sub) or "")
|
||
return ""
|
||
if key.startswith("state."):
|
||
skey = key[len("state.") :]
|
||
return _serialize_val(state.get(skey))
|
||
if key.startswith("node."):
|
||
rest = key[len("node.") :]
|
||
if "." in rest:
|
||
nid, sub = rest.split(".", 1)
|
||
nd = structured.get(nid) or {}
|
||
if sub in nd:
|
||
return _serialize_val(nd.get(sub))
|
||
return str(outputs.get(rest) or "")[:4000]
|
||
if key.endswith(".output"):
|
||
nid = key[: -len(".output")]
|
||
return str(outputs.get(nid) or "")[:4000]
|
||
return ""
|
||
|
||
return _TEMPLATE_VAR_RE.sub(lambda m: _lookup(m.group(1)), raw)
|
||
|
||
|
||
def _target_entity_type(target: dict[str, Any]) -> str:
|
||
return str(target.get("entity_type") or target.get("type") or "").strip().lower()
|
||
|
||
|
||
def _target_id_for_types(
|
||
targets: list[dict[str, Any]],
|
||
entity_types: frozenset[str],
|
||
) -> str | None:
|
||
"""Return the ID of the first selected target whose type matches `entity_types`.
|
||
|
||
Each data source must query its own object: a multi-select of cable + vessel + BGP
|
||
must never leak the cable ID into the vessel or BGP lookup, regardless of click order.
|
||
"""
|
||
for target in targets:
|
||
if _target_entity_type(target) in entity_types:
|
||
raw = str(target.get("entity_id") or target.get("id") or "").strip()
|
||
if raw:
|
||
return raw
|
||
return None
|
||
|
||
|
||
def _extract_codes_and_mode(earth_context: dict[str, Any]) -> tuple[list[str], str]:
|
||
codes = earth_context.get("selected_codes")
|
||
if not isinstance(codes, list) or not codes:
|
||
codes = ["CN", "US"]
|
||
else:
|
||
codes = [str(c).strip().upper() for c in codes if str(c).strip()][:12] or ["CN", "US"]
|
||
mode = str(earth_context.get("mode") or "global_share")
|
||
return codes, mode
|
||
|
||
|
||
_BGP_ENTITY_TYPES = frozenset({"bgp"})
|
||
_CABLE_ENTITY_TYPES = frozenset({"cable", "landing_point"})
|
||
_SATELLITE_ENTITY_TYPES = frozenset({"satellite"})
|
||
_VESSEL_ENTITY_TYPES = frozenset({"vessel"})
|
||
_COMPUTE_FACILITY_TYPES = frozenset(
|
||
{"supercomputer", "gpu_cluster", "data_center", "cloud_center", "edge_node", "compute_center_unresolved"}
|
||
)
|
||
|
||
|
||
async def _execute_tool(
|
||
db: Any,
|
||
tool_id: str,
|
||
*,
|
||
question: str,
|
||
targets: list[dict[str, Any]],
|
||
earth_context: dict[str, Any],
|
||
allow_external_tools: bool,
|
||
node_params: dict[str, Any] | None = None,
|
||
node_data: dict[str, dict[str, Any]] | None = None,
|
||
workflow_state: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Execute one whitelisted read-only or controlled workflow tool cleanly."""
|
||
state = workflow_state if workflow_state is not None else {}
|
||
params = node_params or {}
|
||
|
||
if tool_id == "location_normalize_context":
|
||
from app.services.location.workflow_tools import tool_location_normalize_context
|
||
|
||
return await tool_location_normalize_context(
|
||
db,
|
||
question=question,
|
||
targets=targets,
|
||
earth_context=earth_context,
|
||
node_params=params,
|
||
workflow_state=state,
|
||
)
|
||
if tool_id == "location_knowledge_lookup" or tool_id in _L1_KNOWLEDGE_TOOL_IDS:
|
||
from app.services.location.workflow_tools import tool_location_knowledge_lookup
|
||
|
||
return await tool_location_knowledge_lookup(
|
||
db,
|
||
question=question,
|
||
targets=targets,
|
||
earth_context=earth_context,
|
||
node_params=params,
|
||
workflow_state=state,
|
||
)
|
||
if tool_id == "location_web_research":
|
||
from app.services.location.workflow_tools import tool_location_web_research
|
||
|
||
return await tool_location_web_research(
|
||
db,
|
||
node_params=params,
|
||
workflow_state=state,
|
||
allow_external_tools=allow_external_tools,
|
||
)
|
||
if tool_id in {"location_geocode_verify", "geocode_verify"}:
|
||
from app.services.location.workflow_tools import tool_location_geocode_verify
|
||
|
||
return await tool_location_geocode_verify(workflow_state=state)
|
||
if tool_id == "location_persist_outcome":
|
||
from app.services.location.workflow_tools import tool_location_persist_outcome
|
||
|
||
return await tool_location_persist_outcome(
|
||
db,
|
||
node_params=params,
|
||
workflow_state=state,
|
||
)
|
||
|
||
codes, mode = _extract_codes_and_mode(earth_context)
|
||
time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment]
|
||
if time_basis not in {"live", "as_known_then", "retrospective"}:
|
||
time_basis = "retrospective"
|
||
cutoff_at = earth_context.get("cutoff_at")
|
||
visible_layers = earth_context.get("visible_layers")
|
||
visible_layers_dict = visible_layers if isinstance(visible_layers, dict) else None
|
||
|
||
if tool_id == "query_global_situational":
|
||
return await query_global_situational_tool(
|
||
db,
|
||
selected_codes=codes,
|
||
visible_layers=visible_layers_dict,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
)
|
||
if tool_id == "query_compute_posture":
|
||
res = await query_compute_posture_tool(
|
||
db,
|
||
countries=codes,
|
||
mode=mode,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
as_of=earth_context.get("as_of"),
|
||
publish_id=earth_context.get("publish_id"),
|
||
)
|
||
from app.services.compute_lineage import build_revision_change_context, is_revision_question
|
||
|
||
if is_revision_question(question) and not res.get("snapshot_unavailable"):
|
||
rev_ctx = await build_revision_change_context(
|
||
db,
|
||
publish_id=res.get("publish_id") or earth_context.get("publish_id"),
|
||
redact=not allow_external_tools,
|
||
)
|
||
if rev_ctx:
|
||
res["revision_context"] = rev_ctx
|
||
return res
|
||
if tool_id == "query_bgp_incidents":
|
||
incidents = await query_bgp_incidents_tool(
|
||
db,
|
||
incident_key=_target_id_for_types(targets, _BGP_ENTITY_TYPES),
|
||
limit=8,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
)
|
||
return {"items": incidents, "count": len(incidents)}
|
||
if tool_id == "query_cable_posture":
|
||
return await query_cable_posture_tool(
|
||
db,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
entity_id=_target_id_for_types(targets, _CABLE_ENTITY_TYPES),
|
||
)
|
||
if tool_id == "query_satellite_posture":
|
||
return await query_satellite_posture_tool(
|
||
db,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
entity_id=_target_id_for_types(targets, _SATELLITE_ENTITY_TYPES),
|
||
)
|
||
if tool_id == "query_vessel_posture":
|
||
return await query_vessel_posture_tool(
|
||
db,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
entity_id=_target_id_for_types(targets, _VESSEL_ENTITY_TYPES),
|
||
)
|
||
if tool_id == "query_cloud_posture":
|
||
first = targets[0] if targets else {}
|
||
return await query_cloud_posture_tool(
|
||
db,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
latitude=first.get("latitude"),
|
||
longitude=first.get("longitude"),
|
||
)
|
||
if tool_id == "query_wind_posture":
|
||
first = targets[0] if targets else {}
|
||
return await query_wind_posture_tool(
|
||
db,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
latitude=first.get("latitude"),
|
||
longitude=first.get("longitude"),
|
||
)
|
||
if tool_id == "query_recent_earth_news":
|
||
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
|
||
region = str(news_ctx.get("region_key") or "").strip() or None
|
||
return await query_recent_earth_news_tool(db, region=region, limit=10)
|
||
if tool_id == "web_search":
|
||
if not allow_external_tools:
|
||
return {"skipped": "external_web_search_admin_only"}
|
||
from app.api.v1.settings import get_web_search_client
|
||
|
||
client = await get_web_search_client(db)
|
||
custom_q = render_workflow_template(
|
||
str(params.get("query_template") or ""),
|
||
question=question,
|
||
targets=targets,
|
||
node_data=node_data,
|
||
workflow_state=state,
|
||
).strip()
|
||
search_q = (
|
||
custom_q
|
||
or " ".join(part for part in [summarize_targets(targets) if targets else "", question] if part).strip()
|
||
)[:200]
|
||
if not search_q:
|
||
return {"items": []}
|
||
hits = await client.search(search_q, max_results=5)
|
||
return {
|
||
"items": [
|
||
{
|
||
"title": h.title,
|
||
"url": h.url,
|
||
"snippet": h.compact_text(400),
|
||
"source_provider": h.source_provider,
|
||
}
|
||
for h in hits
|
||
]
|
||
}
|
||
if tool_id in {"safe_web_fetch", "fetch_source_url"}:
|
||
if not allow_external_tools:
|
||
return {"skipped": "external_fetch_admin_only"}
|
||
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
|
||
target_props = targets[0].get("properties") if targets and isinstance(targets[0].get("properties"), dict) else {}
|
||
custom_u = render_workflow_template(
|
||
str(params.get("url_template") or ""),
|
||
question=question,
|
||
targets=targets,
|
||
node_data=node_data,
|
||
workflow_state=state,
|
||
).strip()
|
||
url = (custom_u or str(news_ctx.get("url") or target_props.get("url") or "")).strip()
|
||
if not url:
|
||
return {"skipped": "no_target_url"}
|
||
fetched = await safe_web_fetch(url)
|
||
return isolate_untrusted_external_text(fetched.final_url or fetched.url, fetched.title, fetched.text)
|
||
return {"skipped": f"unsupported_tool:{tool_id}"}
|
||
|
||
|
||
def _has_meaningful_tool_data(tool_results: dict[str, Any]) -> bool:
|
||
for val in tool_results.values():
|
||
if not isinstance(val, dict):
|
||
continue
|
||
if val.get("skipped") or val.get("error"):
|
||
continue
|
||
for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels", "new_ids"):
|
||
seq = val.get(key)
|
||
if isinstance(seq, list) and len(seq) > 0:
|
||
return True
|
||
if val.get("excerpt") or val.get("summary") or val.get("found") is True or val.get("is_terminal") is True:
|
||
return True
|
||
if isinstance(val.get("evidence_count"), int) and val["evidence_count"] > 0:
|
||
return True
|
||
if isinstance(val.get("context"), dict) and val["context"]:
|
||
return True
|
||
return False
|
||
|
||
|
||
def _topological_sort_nodes(
|
||
nodes: list[dict[str, Any]],
|
||
edges: list[dict[str, Any]],
|
||
) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, Any]]], dict[str, list[str]]]:
|
||
enabled_nodes = [n for n in nodes if isinstance(n, dict) and n.get("enabled", True)][:MAX_WORKFLOW_NODES]
|
||
node_map = {str(n["id"]): n for n in enabled_nodes if n.get("id")}
|
||
adj: dict[str, list[str]] = {nid: [] for nid in node_map}
|
||
incoming: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||
indeg: dict[str, int] = {nid: 0 for nid in node_map}
|
||
|
||
for edge in edges:
|
||
if not isinstance(edge, dict):
|
||
continue
|
||
src = str(edge.get("source") or "")
|
||
tgt = str(edge.get("target") or "")
|
||
if src in node_map and tgt in node_map and src != tgt:
|
||
adj[src].append(tgt)
|
||
incoming[tgt].append(edge)
|
||
indeg[tgt] += 1
|
||
|
||
queue = deque(nid for nid, d in indeg.items() if d == 0)
|
||
ordered: list[dict[str, Any]] = []
|
||
while queue:
|
||
nid = queue.popleft()
|
||
ordered.append(node_map[nid])
|
||
for nxt in adj[nid]:
|
||
indeg[nxt] -= 1
|
||
if indeg[nxt] == 0:
|
||
queue.append(nxt)
|
||
|
||
# Fallback: preserve enabled order if partial edge misalignment occurs.
|
||
seen = {str(n["id"]) for n in ordered}
|
||
for n in enabled_nodes:
|
||
if str(n["id"]) not in seen:
|
||
ordered.append(n)
|
||
return ordered, incoming, adj
|
||
|
||
|
||
def _has_downstream_llm(
|
||
start_id: str,
|
||
adj: dict[str, list[str]],
|
||
node_types: dict[str, str],
|
||
) -> bool:
|
||
visited: set[str] = set()
|
||
stack = list(adj.get(start_id) or [])
|
||
while stack:
|
||
cur = stack.pop()
|
||
if cur in visited:
|
||
continue
|
||
visited.add(cur)
|
||
if node_types.get(cur) in {"llm_agent", "tool_agent"}:
|
||
return True
|
||
stack.extend(adj.get(cur) or [])
|
||
return False
|
||
|
||
|
||
TRIGGER_SOURCES = frozenset({"interactive", "ingest"})
|
||
|
||
|
||
def _eval_edge_condition(
|
||
edge: dict[str, Any],
|
||
pred_state: dict[str, Any],
|
||
targets: list[dict[str, Any]],
|
||
trigger_source: str = "interactive",
|
||
pred_data: dict[str, Any] | None = None,
|
||
) -> bool:
|
||
cond = str(edge.get("condition") or "always").strip()
|
||
data = pred_data if isinstance(pred_data, dict) else (
|
||
pred_state.get("data") if isinstance(pred_state.get("data"), dict) else {}
|
||
)
|
||
if cond in TRIGGER_SOURCES:
|
||
# Background RSS ingest and user-clicked analysis share one graph; only the branch
|
||
# matching the actual trigger may run (avoids a second model call and leaked JSON).
|
||
return cond == trigger_source
|
||
if cond in {"always", ""}:
|
||
return True
|
||
if cond == "not_terminal":
|
||
return not bool(pred_state.get("is_terminal") or data.get("is_terminal"))
|
||
if cond == "on_terminal":
|
||
return bool(pred_state.get("is_terminal") or data.get("is_terminal"))
|
||
if cond == "high_confidence_hit":
|
||
return bool(pred_state.get("high_confidence_hit") or data.get("high_confidence_hit"))
|
||
if cond == "fallback_to_agent":
|
||
return not bool(pred_state.get("high_confidence_hit") or data.get("high_confidence_hit"))
|
||
if cond == "on_guardrail_passed":
|
||
return bool(pred_state.get("guardrail_passed", True))
|
||
if cond == "on_guardrail_failed":
|
||
return not bool(pred_state.get("guardrail_passed", True))
|
||
if cond == "on_field_equals":
|
||
raw_expr = str(edge.get("condition_value") or "").strip()
|
||
if "=" not in raw_expr:
|
||
return False
|
||
field_name, expected_raw = raw_expr.split("=", 1)
|
||
field_key = field_name.strip()
|
||
wanted = {item.strip().lower() for item in expected_raw.split(",") if item.strip()}
|
||
if not field_key or not wanted:
|
||
return False
|
||
actual = data.get(field_key)
|
||
if actual is None:
|
||
actual = pred_state.get(field_key)
|
||
if actual is None:
|
||
return False
|
||
return str(actual).strip().lower() in wanted
|
||
if cond == "on_empty_or_low_confidence":
|
||
return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6
|
||
if cond == "on_entity_type":
|
||
raw_val = str(edge.get("condition_value") or "").strip()
|
||
if not raw_val:
|
||
return False
|
||
wanted = {item.strip().lower() for item in raw_val.split(",") if item.strip()}
|
||
target_types = {str(t.get("entity_type") or t.get("type") or "").strip().lower() for t in targets}
|
||
return bool(wanted & target_types)
|
||
return True
|
||
|
||
|
||
def _build_deterministic_fallback_markdown(
|
||
*,
|
||
workflow_name: str,
|
||
question: str,
|
||
targets: list[dict[str, Any]],
|
||
tool_results: dict[str, Any],
|
||
ai_configured: bool,
|
||
) -> str:
|
||
lines = [f"### {workflow_name}", ""]
|
||
if targets:
|
||
lines.append(f"- **聚焦目标**:{summarize_targets(targets)}")
|
||
if question:
|
||
lines.append(f"- **分析问题**:{question}")
|
||
if tool_results:
|
||
lines.append("- **已加载遥测工具**:" + "、".join(f"`{k}`" for k in tool_results.keys()))
|
||
lines.append("")
|
||
if not ai_configured:
|
||
lines.append("> 当前系统尚未配置可用 AI Provider,以上为确定性规则与遥测快照摘要;配置模型后可启用深度推理节点。")
|
||
elif tool_results:
|
||
preview = json.dumps(tool_results, ensure_ascii=False, default=str)[:1200]
|
||
lines.append(f"```json\n{preview}\n```")
|
||
return "\n".join(lines).strip()
|
||
|
||
|
||
# Prompt keys whose LLM contract is a strict JSON object (rendered as cards, never streamed raw).
|
||
COMPUTE_BRIEF_PROMPT_KEY = "compute.posture.brief"
|
||
_STRUCTURED_JSON_PROMPT_KEYS = frozenset({COMPUTE_BRIEF_PROMPT_KEY})
|
||
_COMPUTE_BRIEF_SCHEMA_HINT = (
|
||
"严格输出单个紧凑 JSON 对象(不加围栏外文字),字段结构:\n"
|
||
'{"headline": str, "headline_en": str, "executive_assertion": str, "executive_assertion_en": str, '
|
||
'"causes": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], '
|
||
'"breakthrough_levers": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], '
|
||
'"blind_spots": [str], "evidence_ids": [str]};所有 evidence_ids 必须来自 context.evidence。'
|
||
)
|
||
_EVIDENCE_GAP_SUGGESTIONS = (
|
||
"补充一手信源(运营商公告、BGP 采集器原始记录、官方通报)后复核成因",
|
||
"核对事件时间窗与受影响前缀 / 资产是否与所选对象一致",
|
||
)
|
||
|
||
|
||
def _node_wants_structured_json(node: dict[str, Any]) -> bool:
|
||
params = node.get("params") if isinstance(node.get("params"), dict) else {}
|
||
return (
|
||
str(node.get("prompt_key") or "") in _STRUCTURED_JSON_PROMPT_KEYS
|
||
or str(params.get("output_format") or "").strip().lower() == "json"
|
||
)
|
||
|
||
|
||
def _compute_series_from_tools(tool_results: dict[str, Any]) -> dict[str, Any] | None:
|
||
series = tool_results.get("query_compute_posture")
|
||
if not isinstance(series, dict) or series.get("error"):
|
||
return None
|
||
if not series.get("compute") and not series.get("years"):
|
||
return None
|
||
return series
|
||
|
||
|
||
def _resolve_compute_brief(
|
||
parsed: dict[str, Any] | None,
|
||
series: dict[str, Any],
|
||
) -> tuple[Any, bool]:
|
||
"""Validate an LLM compute brief against verified evidence; fall back to the deterministic baseline."""
|
||
from app.services.ai.posture_agent import (
|
||
StrategicPostureBrief,
|
||
build_deterministic_posture_brief,
|
||
verify_brief_citations,
|
||
)
|
||
|
||
if isinstance(parsed, dict):
|
||
try:
|
||
brief = StrategicPostureBrief.model_validate(parsed)
|
||
return verify_brief_citations(brief, series.get("evidence") or {}), True
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Compute brief failed schema or citation verification; using deterministic baseline",
|
||
event="ai_dag.compute_brief.fallback",
|
||
context={"error": str(exc)[:300]},
|
||
)
|
||
return build_deterministic_posture_brief(series), False
|
||
|
||
|
||
def _render_structured_markdown(parsed: dict[str, Any]) -> str:
|
||
"""Render a structured JSON analysis (e.g. StrategicPostureBrief) as readable Markdown."""
|
||
lines: list[str] = []
|
||
headline = str(parsed.get("headline") or parsed.get("title") or "").strip()
|
||
if headline:
|
||
lines.append(f"### {headline}")
|
||
assertion = str(
|
||
parsed.get("executive_assertion") or parsed.get("summary") or parsed.get("answer_markdown") or ""
|
||
).strip()
|
||
if assertion:
|
||
lines.extend(["", assertion])
|
||
for key, label in (
|
||
("key_judgments", "核心判断"),
|
||
("causes", "成因归因"),
|
||
("breakthrough_levers", "突破杠杆"),
|
||
):
|
||
items = parsed.get(key)
|
||
if not isinstance(items, list) or not items:
|
||
continue
|
||
lines.extend(["", f"**{label}**"])
|
||
for item in items[:6]:
|
||
if isinstance(item, dict):
|
||
item_label = str(item.get("label") or item.get("title") or "").strip()
|
||
detail = str(item.get("detail") or item.get("text") or "").strip()
|
||
if item_label and detail:
|
||
lines.append(f"- **{item_label}**:{detail}")
|
||
elif item_label or detail:
|
||
lines.append(f"- {item_label or detail}")
|
||
elif str(item).strip():
|
||
lines.append(f"- {str(item).strip()}")
|
||
blind_spots = [str(b).strip() for b in (parsed.get("blind_spots") or []) if str(b).strip()]
|
||
if blind_spots:
|
||
lines.extend(["", "**待核实盲区**", *[f"- {b}" for b in blind_spots[:4]]])
|
||
return "\n".join(lines).strip()
|
||
|
||
|
||
def _compile_compute_workbench(
|
||
series: dict[str, Any],
|
||
brief: Any,
|
||
earth_context: dict[str, Any],
|
||
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
|
||
"""Compile the existing compute `ViewSpec` workbench (trend + matrix) from verified series."""
|
||
from app.services.ai.workflow_runtime import compile_compute_view_spec
|
||
|
||
codes, mode = _extract_codes_and_mode(earth_context)
|
||
raw_focus_year = earth_context.get("focus_year")
|
||
focus_year = int(raw_focus_year) if isinstance(raw_focus_year, int) else None
|
||
try:
|
||
view, scene = compile_compute_view_spec(
|
||
codes=codes,
|
||
mode=mode,
|
||
series=series,
|
||
posture={"payload": brief.model_dump(mode="json")},
|
||
focus_year=focus_year,
|
||
)
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Compute workbench compilation failed",
|
||
event="ai_dag.compute_view_spec.failed",
|
||
context={"error": str(exc)[:300]},
|
||
)
|
||
return None, None
|
||
return view.model_dump(mode="json"), scene.model_dump(mode="json")
|
||
|
||
|
||
def _build_evidence_gap_markdown(tool_results: dict[str, Any], warnings: list[str]) -> str:
|
||
"""User-facing block delivered when an evidence guardrail fails: cause pending + follow-ups."""
|
||
pending: list[str] = []
|
||
for tid, res in tool_results.items():
|
||
if not isinstance(res, dict):
|
||
continue
|
||
if res.get("error") or res.get("skipped") or not _has_meaningful_tool_data({tid: res}):
|
||
pending.append(f"`{tid}` 未返回可溯源数据,需人工补查")
|
||
pending.extend(_EVIDENCE_GAP_SUGGESTIONS)
|
||
reason = ";".join(warnings) or "缺少结构化证据"
|
||
lines = [
|
||
"",
|
||
"",
|
||
f"> **证据校验未通过({reason})**:以上成因判断一律视为「原因待核实」,不作为定论。",
|
||
"> **待查项**:",
|
||
*[f"> - {item}" for item in pending[:6]],
|
||
]
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _render_output_schema_prompt(schema: dict[str, Any]) -> str:
|
||
"""Render an inline JSON Schema contract directly into the system prompt for cross-provider reliability."""
|
||
props = schema.get("properties") if isinstance(schema.get("properties"), dict) else {}
|
||
required = set(str(k) for k in (schema.get("required") or []) if k)
|
||
field_lines: list[str] = []
|
||
for name, spec in props.items():
|
||
if not isinstance(spec, dict):
|
||
continue
|
||
req_tag = "必填" if name in required else "可选"
|
||
enum_vals = spec.get("enum")
|
||
type_desc = (
|
||
f"枚举: {' | '.join(str(v) for v in enum_vals)}"
|
||
if isinstance(enum_vals, list) and enum_vals
|
||
else str(spec.get("type") or "string")
|
||
)
|
||
desc = str(spec.get("description") or "").strip()
|
||
line = f'- "{name}" ({req_tag}, {type_desc})'
|
||
if desc:
|
||
line += f": {desc}"
|
||
field_lines.append(line)
|
||
return (
|
||
"【严格输出要求】仅返回单个合法 JSON 对象(禁止输出 Markdown 围栏外文字或思考过程)。字段契约:\n"
|
||
+ "\n".join(field_lines)
|
||
)
|
||
|
||
|
||
async def _repair_json_once(
|
||
*,
|
||
ai_client: Any,
|
||
schema_hint: str,
|
||
prior_text: str,
|
||
timeout_sec: int,
|
||
) -> dict[str, Any] | None:
|
||
"""Single no-search JSON format repair pass when a structured llm_agent returns non-JSON."""
|
||
req = SituationalAnalysisRequest(
|
||
title="Repair structured workflow JSON",
|
||
objective="Convert prior output into one valid JSON object matching the required schema.",
|
||
system_prompt=f"{schema_hint}\n严禁新增原始回复中未出现的 URL、evidence_ids 或事实。",
|
||
context={"prior_output": prior_text[:2500]},
|
||
thinking={"mode": "off"},
|
||
)
|
||
try:
|
||
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=min(timeout_sec, 45))
|
||
except Exception:
|
||
return None
|
||
clean_text, _ = strip_thinking_text(str(getattr(resp, "content", "") or ""))
|
||
return _extract_first_json_object(clean_text or str(getattr(resp, "content", "") or ""))
|
||
|
||
|
||
async def run_workflow_dag_stream(
|
||
*,
|
||
db: Any,
|
||
workflow: dict[str, Any],
|
||
question: str,
|
||
use_draft: bool = False,
|
||
targets: list[dict[str, Any]] | None = None,
|
||
earth_context: dict[str, Any] | None = None,
|
||
attachments: list[dict[str, Any]] | None = None,
|
||
images: list[dict[str, Any]] | None = None,
|
||
history: list[dict[str, Any]] | None = None,
|
||
ai_client: Any = None,
|
||
request: Any = None,
|
||
run_id: str = "",
|
||
model_override: str | None = None,
|
||
allow_external_tools: bool = False,
|
||
extra_meta: dict[str, Any] | None = None,
|
||
trigger_source: str = "interactive",
|
||
cancel_event: asyncio.Event | None = None,
|
||
) -> AsyncIterator[dict[str, Any]]:
|
||
"""Execute a workflow DAG topologically and emit structured SSE-ready events."""
|
||
if trigger_source not in TRIGGER_SOURCES:
|
||
trigger_source = "interactive"
|
||
wf_id = str(workflow.get("workflow_id") or "default.general")
|
||
wf_name = str(workflow.get("name") or wf_id)
|
||
active_rev = int(workflow.get("active_revision") or 1)
|
||
bindings = workflow.get("bindings") if isinstance(workflow.get("bindings"), dict) else {}
|
||
draft_graph = workflow.get("draft_graph")
|
||
if use_draft and isinstance(draft_graph, dict) and isinstance(draft_graph.get("bindings"), dict):
|
||
bindings = draft_graph["bindings"]
|
||
graph = (
|
||
workflow.get("draft_graph")
|
||
if use_draft and isinstance(workflow.get("draft_graph"), dict)
|
||
else workflow.get("published_graph")
|
||
) or {}
|
||
raw_nodes = list(graph.get("nodes") or [])
|
||
raw_edges = list(graph.get("edges") or [])
|
||
ordered_nodes, incoming_map, adj = _topological_sort_nodes(raw_nodes, raw_edges)
|
||
node_types = {str(n["id"]): str(n.get("node_type") or "llm_agent") for n in ordered_nodes}
|
||
|
||
clean_targets = [t for t in (targets or []) if isinstance(t, dict)][:8]
|
||
clean_earth_ctx = dict(earth_context or {})
|
||
location_runtime = clean_earth_ctx.pop("_location_runtime", None)
|
||
planned_ids = [str(n["id"]) for n in ordered_nodes]
|
||
|
||
yield {
|
||
"event": "meta",
|
||
"data": {
|
||
"run_id": run_id,
|
||
"workflow_id": wf_id,
|
||
"workflow_name": wf_name,
|
||
"active_revision": active_rev,
|
||
"use_draft": use_draft,
|
||
"targets_count": len(clean_targets),
|
||
"planned_nodes": planned_ids,
|
||
"nodes": planned_ids,
|
||
**(extra_meta or {}),
|
||
},
|
||
}
|
||
|
||
ai_ready = False
|
||
provider_name = ""
|
||
default_model = ""
|
||
if ai_client is not None and hasattr(ai_client, "is_ready"):
|
||
try:
|
||
ai_ready, provider_name, default_model = await ai_client.is_ready()
|
||
except Exception:
|
||
ai_ready = False
|
||
elif ai_client is not None and (hasattr(ai_client, "analyze") or hasattr(ai_client, "stream_analyze")):
|
||
ai_ready = True
|
||
|
||
node_states: dict[str, dict[str, Any]] = {}
|
||
node_outputs: dict[str, str] = {}
|
||
node_data: dict[str, dict[str, Any]] = {}
|
||
tool_results: dict[str, Any] = {}
|
||
evidence: dict[str, Any] = {}
|
||
executed_trace: list[str] = []
|
||
node_traces: list[dict[str, Any]] = []
|
||
evidence_ledger = EvidenceLedger()
|
||
workflow_state: dict[str, Any] = {
|
||
"evidence_ledger": evidence_ledger,
|
||
"attempted_queries": [],
|
||
**(location_runtime if isinstance(location_runtime, dict) else {}),
|
||
}
|
||
effective_question = question.strip()
|
||
final_answer_md = ""
|
||
final_reasoning_md = ""
|
||
generation_mode = "deterministic_baseline"
|
||
zero_token = True
|
||
resolved_provider: str | None = provider_name or None
|
||
resolved_model: str | None = default_model or None
|
||
scene_spec: dict[str, Any] | None = None
|
||
parsed_dag_scene: dict[str, Any] | None = None
|
||
view_spec: dict[str, Any] | None = None
|
||
compute_brief: Any = None
|
||
compute_brief_llm_verified = False
|
||
guardrail_ran = False
|
||
guardrail_warnings: list[str] = []
|
||
last_llm_output: str = ""
|
||
|
||
for node in ordered_nodes:
|
||
if cancel_event is not None and cancel_event.is_set():
|
||
return
|
||
nid = str(node["id"])
|
||
ntype = str(node.get("node_type") or "llm_agent")
|
||
ntitle = str(node.get("title") or nid)
|
||
node_params = node.get("params") if isinstance(node.get("params"), dict) else {}
|
||
|
||
inc_edges = incoming_map.get(nid) or []
|
||
if inc_edges:
|
||
join_mode = str(node_params.get("join_mode") or "any").strip().lower()
|
||
if join_mode == "all":
|
||
passed = True
|
||
for edge in inc_edges:
|
||
pred_id = str(edge.get("source") or "")
|
||
pred_state = node_states.get(pred_id)
|
||
if not pred_state or pred_state.get("skipped"):
|
||
passed = False
|
||
break
|
||
if not _eval_edge_condition(
|
||
edge, pred_state, clean_targets, trigger_source, pred_data=node_data.get(pred_id)
|
||
):
|
||
passed = False
|
||
break
|
||
else:
|
||
passed = False
|
||
for edge in inc_edges:
|
||
pred_id = str(edge.get("source") or "")
|
||
pred_state = node_states.get(pred_id)
|
||
if not pred_state or pred_state.get("skipped"):
|
||
continue
|
||
if _eval_edge_condition(
|
||
edge, pred_state, clean_targets, trigger_source, pred_data=node_data.get(pred_id)
|
||
):
|
||
passed = True
|
||
break
|
||
if not passed:
|
||
node_states[nid] = {"skipped": True, "confidence": 1.0, "is_empty": False}
|
||
node_traces.append({"node_id": nid, "node_type": ntype, "status": "skipped", "duration_ms": 0})
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "skipped"},
|
||
}
|
||
continue
|
||
|
||
node_started = datetime.now(UTC)
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "running"},
|
||
}
|
||
|
||
if ntype in {"trigger", "input"}:
|
||
tmpl = str(bindings.get("prompt_template") or node.get("prompt") or "").strip()
|
||
if not effective_question and tmpl:
|
||
effective_question = render_workflow_template(
|
||
tmpl,
|
||
question=effective_question,
|
||
targets=clean_targets,
|
||
node_outputs=node_outputs,
|
||
node_data=node_data,
|
||
workflow_state=workflow_state,
|
||
).strip()
|
||
summary = summarize_targets(clean_targets)
|
||
node_outputs[nid] = summary
|
||
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
|
||
executed_trace.append(nid)
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
continue
|
||
|
||
if ntype == "deterministic":
|
||
local_results: dict[str, Any] = {}
|
||
merged_data: dict[str, Any] = {}
|
||
l1_ran = False
|
||
for tid in node.get("tools") or []:
|
||
if tid in _L1_KNOWLEDGE_TOOL_IDS:
|
||
if l1_ran:
|
||
continue
|
||
l1_ran = True
|
||
result_key = "l1_facility_lookup"
|
||
else:
|
||
result_key = tid
|
||
try:
|
||
res = await _execute_tool(
|
||
db,
|
||
tid,
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
earth_context=clean_earth_ctx,
|
||
allow_external_tools=allow_external_tools,
|
||
node_params=node_params,
|
||
node_data=node_data,
|
||
workflow_state=workflow_state,
|
||
)
|
||
local_results[result_key] = res
|
||
tool_results[result_key] = res
|
||
if isinstance(res, dict):
|
||
merged_data.update(res)
|
||
if isinstance(res.get("evidence"), dict):
|
||
evidence.update(res["evidence"])
|
||
executed_trace.append(f"{nid}:{tid}")
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Deterministic DAG tool failed",
|
||
event="ai_dag.tool.failed",
|
||
context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)},
|
||
)
|
||
local_results[result_key] = {"error": str(exc)}
|
||
if evidence_ledger.items:
|
||
evidence.update(evidence_ledger.to_evidence_dict())
|
||
has_data = _has_meaningful_tool_data(local_results)
|
||
node_data[nid] = merged_data
|
||
node_outputs[nid] = json.dumps(local_results, ensure_ascii=False, default=str)[:4000]
|
||
node_states[nid] = {
|
||
"skipped": False,
|
||
"confidence": 0.9 if has_data else 0.4,
|
||
"is_empty": not has_data,
|
||
"is_terminal": bool(merged_data.get("is_terminal")),
|
||
"high_confidence_hit": bool(merged_data.get("high_confidence_hit")),
|
||
"data": merged_data,
|
||
}
|
||
if nid not in executed_trace:
|
||
executed_trace.append(nid)
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
|
||
yield {
|
||
"event": "node",
|
||
"data": {
|
||
"node_id": nid,
|
||
"title": ntitle,
|
||
"node_type": ntype,
|
||
"status": "completed",
|
||
"tools_count": len(local_results),
|
||
},
|
||
}
|
||
continue
|
||
|
||
if ntype in {"llm_agent", "tool_agent"}:
|
||
has_next_llm = _has_downstream_llm(nid, adj, node_types)
|
||
schema_spec = node_params.get("output_schema") if isinstance(node_params.get("output_schema"), dict) else None
|
||
sys_prompt = render_workflow_template(
|
||
str(node.get("system_prompt") or "").strip()
|
||
or "你是智能星球(Planet)AI 参谋。结合当前地球上下文、选中交互物件与工具证据,给出严谨客观的中文分析。",
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
node_outputs=node_outputs,
|
||
node_data=node_data,
|
||
workflow_state=workflow_state,
|
||
)
|
||
node_prompt = render_workflow_template(
|
||
str(node.get("prompt") or "").strip(),
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
node_outputs=node_outputs,
|
||
node_data=node_data,
|
||
workflow_state=workflow_state,
|
||
)
|
||
objective = (
|
||
f"{node_prompt}\n\n用户请求:{effective_question or question}"
|
||
if node_prompt
|
||
else (effective_question or question)
|
||
)
|
||
structured = _node_wants_structured_json(node) or bool(schema_spec)
|
||
is_compute_brief = str(node.get("prompt_key") or "") == COMPUTE_BRIEF_PROMPT_KEY
|
||
if is_compute_brief:
|
||
objective = f"{objective}\n\n{_COMPUTE_BRIEF_SCHEMA_HINT}"
|
||
schema_hint = _render_output_schema_prompt(schema_spec) if schema_spec else ""
|
||
if schema_hint:
|
||
sys_prompt = f"{sys_prompt}\n\n{schema_hint}".strip()
|
||
|
||
wants_scene_zones = (
|
||
not has_next_llm
|
||
and not structured
|
||
and (wf_id.startswith("earth.") or bool(clean_earth_ctx) or bool(clean_targets))
|
||
)
|
||
if wants_scene_zones:
|
||
sys_prompt = f"{sys_prompt}\n\n{INFLUENCE_ZONE_GUIDANCE}".strip()
|
||
objective = (
|
||
f"{objective}\n\n"
|
||
"【空间联动提醒】若本回答涉及任何明确国家、地区、海域走廊或地理影响范围,请务必按系统指令在正文最末尾另起一行附带 <planet_scene>...</planet_scene>。"
|
||
)
|
||
objective = objective.strip()
|
||
|
||
# Execute any extra read-only tools configured directly on the LLM node before inference.
|
||
node_tool_results: dict[str, Any] = {}
|
||
for tid in node.get("tools") or []:
|
||
if tid in tool_results or tid in _L1_KNOWLEDGE_TOOL_IDS:
|
||
continue
|
||
try:
|
||
res = await _execute_tool(
|
||
db,
|
||
tid,
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
earth_context=clean_earth_ctx,
|
||
allow_external_tools=allow_external_tools,
|
||
node_params=node_params,
|
||
node_data=node_data,
|
||
workflow_state=workflow_state,
|
||
)
|
||
node_tool_results[tid] = res
|
||
tool_results[tid] = res
|
||
if isinstance(res, dict) and isinstance(res.get("evidence"), dict):
|
||
evidence.update(res["evidence"])
|
||
except Exception as exc:
|
||
node_tool_results[tid] = {"error": str(exc)}
|
||
if evidence_ledger.items:
|
||
evidence.update(evidence_ledger.to_evidence_dict())
|
||
|
||
ctx_payload: dict[str, Any] = {
|
||
"targets": clean_targets,
|
||
"targets_summary": summarize_targets(clean_targets),
|
||
"tool_results": tool_results,
|
||
"upstream_outputs": {k: v[:2000] for k, v in node_outputs.items()},
|
||
"evidence": evidence,
|
||
}
|
||
if workflow_state.get("location_ctx"):
|
||
ctx_payload["location_target"] = workflow_state["location_ctx"]
|
||
if evidence_ledger.items:
|
||
ctx_payload["evidence_items"] = evidence_ledger.to_prompt_items()
|
||
if clean_earth_ctx:
|
||
ctx_payload["earth_context"] = clean_earth_ctx
|
||
if wants_scene_zones:
|
||
ctx_payload["scene_overlay_guidance"] = INFLUENCE_ZONE_GUIDANCE
|
||
if attachments:
|
||
ctx_payload["attachments"] = attachments[:8]
|
||
|
||
parsed_images: list[ImageAttachment] = []
|
||
if not has_next_llm and images:
|
||
for raw_img in images[:8]:
|
||
try:
|
||
parsed_images.append(ImageAttachment.model_validate(raw_img))
|
||
except Exception:
|
||
continue
|
||
|
||
chat_msgs = [
|
||
ChatMessage(role=str(m["role"]), content=str(m["content"])) # type: ignore[arg-type]
|
||
for m in (history or [])[-12:]
|
||
if isinstance(m, dict) and m.get("role") in {"user", "assistant"} and m.get("content")
|
||
]
|
||
|
||
preferred_model = (
|
||
str(model_override or "").strip()
|
||
or str(node.get("model_override") or "").strip()
|
||
or None
|
||
)
|
||
native_search = bool(node.get("native_web_search", False)) and allow_external_tools
|
||
req = SituationalAnalysisRequest(
|
||
title=f"Planet AI Advisor · {wf_name}",
|
||
objective=objective[:24000],
|
||
system_prompt=sys_prompt[:8000],
|
||
context=ctx_payload,
|
||
preferred_model=preferred_model,
|
||
thinking={"mode": "auto"} if bool(node.get("thinking_enabled", True)) else {"mode": "off"},
|
||
native_web_search=native_search,
|
||
messages=[] if (has_next_llm or schema_spec) else chat_msgs,
|
||
images=parsed_images,
|
||
)
|
||
|
||
compute_series = _compute_series_from_tools(tool_results) if is_compute_brief else None
|
||
|
||
if schema_spec is not None:
|
||
cap_reason = str(workflow_state.get("capability_reason") or "").strip()
|
||
if not ai_ready or ai_client is None:
|
||
parsed_schema = {
|
||
"decision": "unresolved",
|
||
"reasoning": cap_reason or "当前未配置可用 AI Provider",
|
||
}
|
||
elif (
|
||
cap_reason
|
||
and evidence_ledger.evidence_calls == 0
|
||
and not native_search
|
||
):
|
||
parsed_schema = {"decision": "unresolved", "reasoning": cap_reason}
|
||
else:
|
||
timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300))
|
||
try:
|
||
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec)
|
||
except Exception as exc:
|
||
parsed_schema = {
|
||
"decision": "unresolved",
|
||
"reasoning": f"模型研判请求失败:{exc}",
|
||
}
|
||
else:
|
||
raw_out = str(getattr(resp, "content", "") or "")
|
||
clean_text, inline_thoughts = strip_thinking_text(raw_out)
|
||
resolved_provider = getattr(resp, "provider", None) or resolved_provider or None
|
||
resolved_model = getattr(resp, "model", None) or preferred_model or resolved_model or None
|
||
if inline_thoughts:
|
||
final_reasoning_md = f"{final_reasoning_md}\n\n" + "\n\n".join(inline_thoughts)
|
||
final_reasoning_md = final_reasoning_md.strip()
|
||
for cite_u in getattr(resp, "citation_urls", None) or []:
|
||
u_str = str(cite_u or "").strip()
|
||
if u_str:
|
||
evidence_ledger.record_call()
|
||
evidence_ledger.add(url=u_str, title="Provider Web Citation", tool="native_web_search")
|
||
if evidence_ledger.items:
|
||
evidence.update(evidence_ledger.to_evidence_dict())
|
||
generation_mode = "llm_verified"
|
||
zero_token = False
|
||
parsed_schema = _extract_first_json_object(clean_text or raw_out)
|
||
if parsed_schema is None and (clean_text or raw_out).strip():
|
||
parsed_schema = await _repair_json_once(
|
||
ai_client=ai_client,
|
||
schema_hint=schema_hint,
|
||
prior_text=clean_text or raw_out,
|
||
timeout_sec=timeout_sec,
|
||
)
|
||
if parsed_schema is None:
|
||
parsed_schema = {
|
||
"decision": "unresolved",
|
||
"reasoning": "模型未返回可解析的结构化 JSON 结论",
|
||
}
|
||
if (
|
||
node_params.get("allow_followup") is False
|
||
and str(parsed_schema.get("decision") or "").strip().lower() == "need_followup"
|
||
):
|
||
parsed_schema["decision"] = "unresolved"
|
||
node_data[nid] = parsed_schema
|
||
workflow_state["latest_llm_data"] = parsed_schema
|
||
node_outputs[nid] = json.dumps(parsed_schema, ensure_ascii=False, default=str)[:4000]
|
||
node_states[nid] = {
|
||
"skipped": False,
|
||
"confidence": float(parsed_schema.get("confidence") or 0.7),
|
||
"is_empty": False,
|
||
"data": parsed_schema,
|
||
}
|
||
executed_trace.append(nid)
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append(
|
||
{
|
||
"node_id": nid,
|
||
"node_type": ntype,
|
||
"status": "completed",
|
||
"duration_ms": dur_ms,
|
||
"decision": parsed_schema.get("decision"),
|
||
}
|
||
)
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
continue
|
||
|
||
if not ai_ready or ai_client is None:
|
||
if compute_series is not None and not has_next_llm:
|
||
compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, compute_series)
|
||
fallback_md = (
|
||
_render_structured_markdown(compute_brief.model_dump(mode="json"))
|
||
+ "\n\n> 当前未配置可用 AI Provider,以上为基于已核验算力台账的确定性研判。"
|
||
)
|
||
else:
|
||
fallback_md = _build_deterministic_fallback_markdown(
|
||
workflow_name=wf_name,
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
tool_results=tool_results,
|
||
ai_configured=False,
|
||
)
|
||
node_outputs[nid] = fallback_md
|
||
node_states[nid] = {"skipped": False, "confidence": 0.65, "is_empty": False}
|
||
executed_trace.append(nid)
|
||
if not has_next_llm:
|
||
final_answer_md = fallback_md
|
||
yield {"event": "text", "data": {"delta": fallback_md}}
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
continue
|
||
|
||
timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300))
|
||
if cancel_event is not None and cancel_event.is_set():
|
||
return
|
||
if has_next_llm or structured:
|
||
# Intermediate nodes and strict-JSON nodes run non-streaming so raw JSON never reaches the user.
|
||
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec)
|
||
if cancel_event is not None and cancel_event.is_set():
|
||
return
|
||
clean_text, inline_thoughts = strip_thinking_text(str(getattr(resp, "content", "") or ""))
|
||
node_outputs[nid] = clean_text or str(getattr(resp, "content", "") or "")
|
||
if node_outputs[nid]:
|
||
last_llm_output = node_outputs[nid]
|
||
resolved_provider = getattr(resp, "provider", None) or provider_name
|
||
resolved_model = getattr(resp, "model", None) or preferred_model or default_model
|
||
if inline_thoughts:
|
||
final_reasoning_md = f"{final_reasoning_md}\n\n" + "\n\n".join(inline_thoughts)
|
||
final_reasoning_md = final_reasoning_md.strip()
|
||
generation_mode = "llm_verified"
|
||
zero_token = False
|
||
if structured and not has_next_llm:
|
||
parsed = _extract_first_json_object(node_outputs[nid])
|
||
if isinstance(parsed, dict):
|
||
node_data[nid] = parsed
|
||
narrative = ""
|
||
if compute_series is not None:
|
||
compute_brief, compute_brief_llm_verified = _resolve_compute_brief(parsed, compute_series)
|
||
narrative = _render_structured_markdown(compute_brief.model_dump(mode="json"))
|
||
if not compute_brief_llm_verified:
|
||
narrative += "\n\n> 模型结论未通过结构或证据 ID 核验,已改用已核验台账的确定性研判。"
|
||
elif parsed:
|
||
narrative = _render_structured_markdown(parsed)
|
||
narrative = narrative.strip() or node_outputs[nid].strip()
|
||
node_outputs[nid] = narrative
|
||
last_llm_output = narrative
|
||
final_answer_md = narrative
|
||
if narrative:
|
||
yield {"event": "text", "data": {"delta": narrative}}
|
||
node_states[nid] = {
|
||
"skipped": False,
|
||
"confidence": 0.85 if node_outputs[nid] else 0.4,
|
||
"is_empty": not bool(node_outputs[nid].strip()),
|
||
**({"data": node_data[nid]} if nid in node_data else {}),
|
||
}
|
||
executed_trace.append(nid)
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
else:
|
||
text_parts: list[str] = []
|
||
reasoning_parts: list[str] = []
|
||
pending_scene_tail = ""
|
||
resolved_provider = provider_name or None
|
||
resolved_model = preferred_model or default_model or None
|
||
async for ev in ai_client.stream_analyze(req, request_id=run_id):
|
||
if (cancel_event is not None and cancel_event.is_set()) or (
|
||
request is not None and await request.is_disconnected()
|
||
):
|
||
return
|
||
ev_type = str(ev.get("event") or "")
|
||
if ev_type == "start":
|
||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||
resolved_provider = ev["provider"]
|
||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||
resolved_model = ev["model"]
|
||
elif ev_type == "reasoning" and ev.get("delta"):
|
||
delta = str(ev["delta"])
|
||
reasoning_parts.append(delta)
|
||
yield {"event": "reasoning", "data": {"delta": delta}}
|
||
elif ev_type == "text" and ev.get("delta"):
|
||
delta = str(ev["delta"])
|
||
text_parts.append(delta)
|
||
combined_buf = pending_scene_tail + delta
|
||
emit_chunk, pending_scene_tail = consume_text_holding_scene_tag(combined_buf)
|
||
if emit_chunk:
|
||
yield {"event": "text", "data": {"delta": emit_chunk}}
|
||
elif ev_type == "done":
|
||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||
resolved_provider = ev["provider"]
|
||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||
resolved_model = ev["model"]
|
||
elif ev_type == "error":
|
||
err_msg = str(ev.get("message") or ev.get("detail") or "AI stream error")
|
||
raise RuntimeError(err_msg)
|
||
|
||
if pending_scene_tail:
|
||
cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail)
|
||
if cleaned_tail:
|
||
yield {"event": "text", "data": {"delta": cleaned_tail}}
|
||
if cancel_event is not None and cancel_event.is_set():
|
||
return
|
||
|
||
raw_text = "".join(text_parts)
|
||
clean_text, inline_thoughts = strip_thinking_text(raw_text)
|
||
stripped_answer, node_parsed_scene = extract_planet_scene_from_text(clean_text or raw_text)
|
||
if node_parsed_scene:
|
||
parsed_dag_scene = node_parsed_scene
|
||
logger.info_event(
|
||
"DAG LLM node emitted scene directives",
|
||
event="ai_dag.scene.extracted",
|
||
context={
|
||
"workflow_id": wf_id,
|
||
"run_id": run_id,
|
||
"node_id": nid,
|
||
"zones_count": len(node_parsed_scene.get("influence_zones") or []),
|
||
},
|
||
)
|
||
final_answer_md = stripped_answer.strip()
|
||
if inline_thoughts:
|
||
reasoning_parts.extend(inline_thoughts)
|
||
if reasoning_parts:
|
||
joined = "".join(reasoning_parts).strip()
|
||
final_reasoning_md = f"{final_reasoning_md}\n\n{joined}".strip() if final_reasoning_md else joined
|
||
generation_mode = "llm_verified"
|
||
zero_token = False
|
||
node_outputs[nid] = final_answer_md
|
||
node_states[nid] = {
|
||
"skipped": False,
|
||
"confidence": 0.9 if final_answer_md else 0.35,
|
||
"is_empty": not bool(final_answer_md),
|
||
}
|
||
executed_trace.append(nid)
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
continue
|
||
|
||
if ntype == "guardrail":
|
||
gr = node.get("guardrails") if isinstance(node.get("guardrails"), dict) else {}
|
||
passed = True
|
||
warnings: list[str] = []
|
||
if gr.get("require_evidence") and not evidence:
|
||
passed = False
|
||
warnings.append("缺少结构化证据条目(require_evidence)")
|
||
min_chars = int(gr.get("min_output_chars") or 0)
|
||
if min_chars > 0 and len(final_answer_md) < min_chars:
|
||
passed = False
|
||
warnings.append(f"输出长度低于最低阈值({min_chars} 字符)")
|
||
forbidden = gr.get("forbidden_phrases")
|
||
if isinstance(forbidden, list) and final_answer_md:
|
||
hits = [str(p) for p in forbidden if str(p) and str(p) in final_answer_md]
|
||
if hits:
|
||
passed = False
|
||
warnings.append("命中禁用表述: " + ", ".join(hits[:5]))
|
||
if gr.get("geo_verification") or any(
|
||
k in gr
|
||
for k in (
|
||
"min_confidence",
|
||
"enforce_country_match",
|
||
"require_tool_cited_urls",
|
||
"downgrade_geocoded_site_to_city",
|
||
)
|
||
):
|
||
from app.services.location.workflow_tools import evaluate_location_geo_guardrail
|
||
|
||
geo_eval = evaluate_location_geo_guardrail(gr, workflow_state)
|
||
node_data[nid] = geo_eval
|
||
if not geo_eval.get("passed", False):
|
||
passed = False
|
||
for gw in geo_eval.get("warnings") or []:
|
||
if gw and gw not in warnings:
|
||
warnings.append(str(gw))
|
||
|
||
disclaimer = str(gr.get("append_disclaimer") or "").strip()
|
||
if disclaimer and final_answer_md and disclaimer not in final_answer_md:
|
||
extra_block = f"\n\n> {disclaimer}"
|
||
final_answer_md += extra_block
|
||
yield {"event": "text", "data": {"delta": extra_block}}
|
||
guardrail_ran = True
|
||
if not passed:
|
||
guardrail_warnings.extend(w for w in warnings if w not in guardrail_warnings)
|
||
if gr.get("require_evidence") and not evidence:
|
||
# Evidence-required analyses must not present unverified causes as conclusions.
|
||
gap_block = _build_evidence_gap_markdown(tool_results, warnings)
|
||
final_answer_md += gap_block
|
||
yield {"event": "text", "data": {"delta": gap_block}}
|
||
node_states[nid] = {
|
||
"skipped": False,
|
||
"confidence": 0.95 if passed else 0.45,
|
||
"is_empty": False,
|
||
"guardrail_passed": passed,
|
||
"warnings": warnings,
|
||
**({"data": node_data[nid]} if nid in node_data else {}),
|
||
}
|
||
executed_trace.append(nid)
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append(
|
||
{
|
||
"node_id": nid,
|
||
"node_type": ntype,
|
||
"status": "completed",
|
||
"duration_ms": dur_ms,
|
||
"guardrail_passed": passed,
|
||
**({"warnings": warnings[:3]} if warnings else {}),
|
||
}
|
||
)
|
||
yield {
|
||
"event": "node",
|
||
"data": {
|
||
"node_id": nid,
|
||
"title": ntitle,
|
||
"node_type": ntype,
|
||
"status": "completed",
|
||
"guardrail_passed": passed,
|
||
},
|
||
}
|
||
continue
|
||
|
||
if ntype == "output":
|
||
params = node_params
|
||
for tid in node.get("tools") or []:
|
||
try:
|
||
out_res = await _execute_tool(
|
||
db,
|
||
tid,
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
earth_context=clean_earth_ctx,
|
||
allow_external_tools=allow_external_tools,
|
||
node_params=params,
|
||
node_data=node_data,
|
||
workflow_state=workflow_state,
|
||
)
|
||
if isinstance(out_res, dict):
|
||
node_data[nid] = out_res
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Output DAG tool failed",
|
||
event="ai_dag.output_tool.failed",
|
||
context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)},
|
||
)
|
||
if isinstance(workflow_state.get("final_answer_markdown"), str) and workflow_state["final_answer_markdown"]:
|
||
final_answer_md = workflow_state["final_answer_markdown"]
|
||
yield {"event": "text", "data": {"delta": final_answer_md}}
|
||
if isinstance(workflow_state.get("final_scene_spec"), dict):
|
||
scene_spec = workflow_state["final_scene_spec"]
|
||
fly_enabled = bool(params.get("fly_to_target", True))
|
||
if scene_spec is None and fly_enabled and clean_targets:
|
||
first = clean_targets[0]
|
||
lat = first.get("latitude")
|
||
lon = first.get("longitude")
|
||
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
|
||
scene_spec = {
|
||
"fly_to": {
|
||
"lat": float(lat),
|
||
"lon": float(lon),
|
||
"zoom": float(params.get("fly_zoom") or 1.45),
|
||
},
|
||
"highlight_entities": [
|
||
str(t.get("entity_id") or t.get("id"))
|
||
for t in clean_targets
|
||
if t.get("entity_id") or t.get("id")
|
||
],
|
||
}
|
||
wants_compute_view = compute_brief is not None or str(params.get("view_spec") or "") == "compute"
|
||
series_for_view = _compute_series_from_tools(tool_results) if wants_compute_view else None
|
||
if series_for_view is not None:
|
||
if compute_brief is None:
|
||
compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, series_for_view)
|
||
view_spec, compute_scene = _compile_compute_workbench(series_for_view, compute_brief, clean_earth_ctx)
|
||
if scene_spec is None and compute_scene is not None:
|
||
scene_spec = compute_scene
|
||
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
|
||
outcome_tag = str(workflow_state.get("outcome_tag") or "").strip()
|
||
executed_trace.append(f"{nid}:{outcome_tag}" if outcome_tag else nid)
|
||
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
|
||
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
|
||
if not final_answer_md:
|
||
final_answer_md = last_llm_output or _build_deterministic_fallback_markdown(
|
||
workflow_name=wf_name,
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
tool_results=tool_results,
|
||
ai_configured=ai_ready,
|
||
)
|
||
yield {"event": "text", "data": {"delta": final_answer_md}}
|
||
|
||
if parsed_dag_scene:
|
||
dag_domain = str((clean_earth_ctx or {}).get("domain") or "global")
|
||
scene_spec = merge_scene_specs(scene_spec, parsed_dag_scene, domain=dag_domain)
|
||
|
||
if view_spec is not None:
|
||
# Late `meta` patch: the Earth copilot already applies `view_spec` from meta events to render
|
||
# trend/matrix workbench cards; the DAG only knows the spec after the series + brief nodes ran.
|
||
yield {
|
||
"event": "meta",
|
||
"data": {"run_id": run_id, "domain": "compute", "view_spec": view_spec, "scene_spec": scene_spec},
|
||
}
|
||
|
||
if isinstance(scene_spec, dict) and (
|
||
scene_spec.get("influence_zones")
|
||
or parsed_dag_scene
|
||
or isinstance(workflow_state.get("final_scene_spec"), dict)
|
||
):
|
||
yield {"event": "scene", "data": {"scene_spec": scene_spec}}
|
||
|
||
verification = {
|
||
"guardrail_ran": guardrail_ran,
|
||
"passed": not guardrail_warnings,
|
||
"warnings": guardrail_warnings,
|
||
}
|
||
yield {
|
||
"event": "done",
|
||
"data": {
|
||
"run_id": run_id,
|
||
"workflow_id": wf_id,
|
||
"workflow_name": wf_name,
|
||
"status": "completed" if not guardrail_warnings else "unverified",
|
||
"generation_mode": generation_mode,
|
||
"zero_token": zero_token,
|
||
"provider": resolved_provider,
|
||
"model": resolved_model,
|
||
"nodes": executed_trace,
|
||
"evidence": evidence,
|
||
"scene_spec": scene_spec,
|
||
"view_spec": view_spec,
|
||
"verification": verification,
|
||
"answer_markdown": final_answer_md,
|
||
"reasoning_markdown": final_reasoning_md,
|
||
"text_length": len(final_answer_md),
|
||
**({"structured_output": workflow_state["structured_output"]} if "structured_output" in workflow_state else {}),
|
||
"node_traces": node_traces,
|
||
},
|
||
}
|