824 lines
34 KiB
Python
824 lines
34 KiB
Python
"""Lightweight topological DAG workflow executor for AI Advisor and Earth Copilot."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
from collections import defaultdict, deque
|
||
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.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_compute_posture_tool,
|
||
query_global_situational_tool,
|
||
query_recent_earth_news_tool,
|
||
query_satellite_posture_tool,
|
||
query_vessel_posture_tool,
|
||
safe_web_fetch,
|
||
)
|
||
from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES
|
||
from app.services.compute_center_locations import build_compute_center_location_query
|
||
from app.services.location.agent_resolver import run_l1_structured_facility_resolvers
|
||
|
||
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,
|
||
) -> 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 {}
|
||
targets_summary = summarize_targets(targets)
|
||
|
||
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("node."):
|
||
nid = key[len("node.") :]
|
||
return str(outputs.get(nid) 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 _extract_target_ids_and_codes(
|
||
targets: list[dict[str, Any]],
|
||
earth_context: dict[str, Any],
|
||
) -> tuple[str | None, list[str], str]:
|
||
first = targets[0] if targets else {}
|
||
primary_id = str(
|
||
first.get("entity_id")
|
||
or first.get("id")
|
||
or earth_context.get("entity_id")
|
||
or ""
|
||
).strip() or None
|
||
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 primary_id, codes, mode
|
||
|
||
|
||
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,
|
||
) -> dict[str, Any]:
|
||
"""Execute one whitelisted read-only or controlled external tool cleanly."""
|
||
primary_id, codes, mode = _extract_target_ids_and_codes(targets, 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":
|
||
return await query_compute_posture_tool(
|
||
db,
|
||
countries=codes,
|
||
mode=mode,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
)
|
||
if tool_id == "query_bgp_incidents":
|
||
incidents = await query_bgp_incidents_tool(
|
||
db,
|
||
incident_key=primary_id if any(t.get("entity_type") == "bgp" for t in targets) else None,
|
||
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=primary_id if any(t.get("entity_type") in {"cable", "landing_point"} for t in targets) else None,
|
||
)
|
||
if tool_id == "query_satellite_posture":
|
||
return await query_satellite_posture_tool(
|
||
db,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
entity_id=primary_id if any(t.get("entity_type") == "satellite" for t in targets) else None,
|
||
)
|
||
if tool_id == "query_vessel_posture":
|
||
return await query_vessel_posture_tool(
|
||
db,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
entity_id=primary_id if any(t.get("entity_type") == "vessel" for t in targets) else None,
|
||
)
|
||
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 in _L1_KNOWLEDGE_TOOL_IDS:
|
||
target_name = str(
|
||
(targets[0].get("label") if targets else "")
|
||
or question
|
||
or "Unknown Facility"
|
||
).strip()
|
||
query = build_compute_center_location_query(name=target_name)
|
||
candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db)
|
||
return {
|
||
"candidates": [
|
||
{
|
||
"display_name": c.display_name,
|
||
"country": c.country,
|
||
"latitude": c.latitude,
|
||
"longitude": c.longitude,
|
||
"precision": c.precision,
|
||
"confidence": c.confidence,
|
||
"source": c.source,
|
||
"source_note": c.source_note,
|
||
}
|
||
for c in candidates[:5]
|
||
],
|
||
"resolver_log": resolver_log,
|
||
}
|
||
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)
|
||
search_q = " ".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 {}
|
||
url = 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"):
|
||
seq = val.get(key)
|
||
if isinstance(seq, list) and len(seq) > 0:
|
||
return True
|
||
if val.get("excerpt") or val.get("summary"):
|
||
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
|
||
|
||
|
||
def _eval_edge_condition(
|
||
edge: dict[str, Any],
|
||
pred_state: dict[str, Any],
|
||
targets: list[dict[str, Any]],
|
||
) -> bool:
|
||
cond = str(edge.get("condition") or "always").strip()
|
||
if cond in {"always", "", "interactive", "ingest", "not_terminal", "high_confidence_hit", "fallback_to_agent"}:
|
||
return True
|
||
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()
|
||
|
||
|
||
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,
|
||
) -> AsyncIterator[dict[str, Any]]:
|
||
"""Execute a workflow DAG topologically and emit structured SSE-ready events."""
|
||
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 {}
|
||
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 {})
|
||
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
|
||
|
||
node_states: dict[str, dict[str, Any]] = {}
|
||
node_outputs: dict[str, str] = {}
|
||
tool_results: dict[str, Any] = {}
|
||
evidence: dict[str, Any] = {}
|
||
executed_trace: list[str] = []
|
||
effective_question = question.strip()
|
||
final_answer_md = ""
|
||
final_reasoning_md = ""
|
||
generation_mode = "deterministic_baseline"
|
||
zero_token = True
|
||
resolved_provider: str | None = None
|
||
resolved_model: str | None = None
|
||
scene_spec: dict[str, Any] | None = None
|
||
last_llm_output: str = ""
|
||
|
||
for node in ordered_nodes:
|
||
nid = str(node["id"])
|
||
ntype = str(node.get("node_type") or "llm_agent")
|
||
ntitle = str(node.get("title") or nid)
|
||
|
||
inc_edges = incoming_map.get(nid) or []
|
||
if inc_edges:
|
||
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):
|
||
passed = True
|
||
break
|
||
if not passed:
|
||
node_states[nid] = {"skipped": True, "confidence": 1.0, "is_empty": False}
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "skipped"},
|
||
}
|
||
continue
|
||
|
||
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,
|
||
).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)
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
continue
|
||
|
||
if ntype == "deterministic":
|
||
local_results: 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,
|
||
)
|
||
local_results[result_key] = res
|
||
tool_results[result_key] = res
|
||
if isinstance(res, dict) and 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)}
|
||
has_data = _has_meaningful_tool_data(local_results)
|
||
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,
|
||
}
|
||
if nid not in executed_trace:
|
||
executed_trace.append(nid)
|
||
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)
|
||
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_prompt = render_workflow_template(
|
||
str(node.get("prompt") or "").strip(),
|
||
question=effective_question or question,
|
||
targets=clean_targets,
|
||
node_outputs=node_outputs,
|
||
)
|
||
objective = (
|
||
f"{node_prompt}\n\n用户请求:{effective_question or question}"
|
||
if node_prompt
|
||
else (effective_question or question)
|
||
).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_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)}
|
||
|
||
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 clean_earth_ctx:
|
||
ctx_payload["earth_context"] = clean_earth_ctx
|
||
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
|
||
)
|
||
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=bool(node.get("native_web_search", False)) and allow_external_tools,
|
||
messages=[] if has_next_llm else chat_msgs,
|
||
images=parsed_images,
|
||
)
|
||
|
||
if not ai_ready or ai_client is None:
|
||
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}}
|
||
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 has_next_llm:
|
||
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec)
|
||
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
|
||
node_states[nid] = {
|
||
"skipped": False,
|
||
"confidence": 0.85 if node_outputs[nid] else 0.4,
|
||
"is_empty": not bool(node_outputs[nid].strip()),
|
||
}
|
||
executed_trace.append(nid)
|
||
yield {
|
||
"event": "node",
|
||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||
}
|
||
else:
|
||
text_parts: list[str] = []
|
||
reasoning_parts: list[str] = []
|
||
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 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)
|
||
yield {"event": "text", "data": {"delta": delta}}
|
||
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)
|
||
|
||
raw_text = "".join(text_parts)
|
||
clean_text, inline_thoughts = strip_thinking_text(raw_text)
|
||
final_answer_md = (clean_text or raw_text).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)
|
||
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]))
|
||
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}}
|
||
node_states[nid] = {
|
||
"skipped": False,
|
||
"confidence": 0.95 if passed else 0.45,
|
||
"is_empty": False,
|
||
"warnings": warnings,
|
||
}
|
||
executed_trace.append(nid)
|
||
yield {
|
||
"event": "node",
|
||
"data": {
|
||
"node_id": nid,
|
||
"title": ntitle,
|
||
"node_type": ntype,
|
||
"status": "completed",
|
||
"guardrail_passed": passed,
|
||
},
|
||
}
|
||
continue
|
||
|
||
if ntype == "output":
|
||
params = node.get("params") if isinstance(node.get("params"), dict) else {}
|
||
fly_enabled = bool(params.get("fly_to_target", True))
|
||
if 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")
|
||
],
|
||
}
|
||
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
|
||
executed_trace.append(nid)
|
||
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}}
|
||
|
||
yield {
|
||
"event": "done",
|
||
"data": {
|
||
"run_id": run_id,
|
||
"workflow_id": wf_id,
|
||
"workflow_name": wf_name,
|
||
"status": "completed",
|
||
"generation_mode": generation_mode,
|
||
"zero_token": zero_token,
|
||
"provider": resolved_provider,
|
||
"model": resolved_model,
|
||
"nodes": executed_trace,
|
||
"evidence": evidence,
|
||
"scene_spec": scene_spec,
|
||
"answer_markdown": final_answer_md,
|
||
"reasoning_markdown": final_reasoning_md,
|
||
"text_length": len(final_answer_md),
|
||
},
|
||
}
|