Files
planet/backend/app/services/ai/workflow_registry.py
T
linkong e1cc27f13d
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.84.0
2026-12-04 07:07:19 +08:00

2113 lines
91 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Unified AI Advisor workflow catalog, versioning, runtime resolution, and AI patch proposals."""
from __future__ import annotations
from collections import deque
import copy
import inspect
import json
import re
from typing import Any
from uuid import uuid4
from fastapi import HTTPException
from sqlalchemy import delete, desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
from app.models.situational_assessment import WorkflowRun
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.location.workflow_tools import (
LOCATION_JUDGE_FINAL_SCHEMA,
LOCATION_JUDGE_R1_SCHEMA,
)
logger = get_logger(__name__, service="ai_workflow_registry")
TOOL_CATALOG: list[dict[str, Any]] = [
{
"id": "query_global_situational",
"name": "全球态势全览快照",
"name_en": "Global Situational Snapshot",
"category": "internal_read",
"description": "汇总算力、BGP、海缆、卫星、船舶五域当前遥测指标,零外部消耗。",
},
{
"id": "query_compute_posture",
"name": "算力多口径与 RPI 查询",
"name_en": "Compute Multi-Metric & RPI Query",
"category": "internal_read",
"description": "读取各国算力份额、绝对规模、双边 RPI、智算结构与八大枢纽。",
},
{
"id": "query_bgp_incidents",
"name": "BGP 事故与异常快照",
"name_en": "BGP Incidents & Anomalies",
"category": "internal_read",
"description": "读取实时或历史截止窗口内的 BGP 路由劫持/泄漏/断网事故。",
},
{
"id": "query_cable_posture",
"name": "海缆与登陆站拓扑",
"name_en": "Submarine Cables & Landing Hubs",
"category": "internal_read",
"description": "查询海底光缆走向、登陆站分布及近邻异常事件。",
},
{
"id": "query_satellite_posture",
"name": "卫星轨道与星座分布",
"name_en": "Satellite Orbits & Constellations",
"category": "internal_read",
"description": "查询在轨卫星目录、轨道层分布及星链覆盖估算。",
},
{
"id": "query_vessel_posture",
"name": "全球 AIS 船舶快照",
"name_en": "AIS Vessel Snapshot",
"category": "internal_read",
"description": "查询航运密度、关键海峡通道船只态势。",
},
{
"id": "query_cloud_posture",
"name": "全球实时红外云图与强对流分析",
"name_en": "Live Satellite Cloud & Convection Analytics",
"category": "internal_read",
"description": "读取全球与重点航运/算力区域云量、强对流云团与云顶亮温数据。",
},
{
"id": "query_wind_posture",
"name": "全球 10m 风场与大风区态势",
"name_en": "Global 10m Wind Field & Gale Analytics",
"category": "internal_read",
"description": "读取 NOAA GFS 全球 10m 风速、风向、大风核心区域与重点航道风场态势。",
},
{
"id": "query_recent_earth_news",
"name": "Earth 近期新闻动态",
"name_en": "Recent Earth News Feed",
"category": "internal_read",
"description": "检索全球近期已入库/汉化新闻头条与地理锚点。",
},
{
"id": "builds_upon_inherit",
"name": "Epoch builds_upon 父集群继承",
"name_en": "Epoch builds_upon Inheritance",
"category": "location_knowledge",
"description": "从已核验的父集群位置继承同园区坐标。",
},
{
"id": "wikidata_lookup",
"name": "Wikidata P625/P276 设施查询",
"name_en": "Wikidata Facility Coordinates",
"category": "location_knowledge",
"description": "检索 Wikidata 超算/国家实验室/数据中心词条与官方坐标。",
},
{
"id": "peeringdb_fac_lookup",
"name": "PeeringDB /api/fac 机房查询",
"name_en": "PeeringDB Facility Lookup",
"category": "location_knowledge",
"description": "按托管园区或运营方查询商业数据中心门牌与经纬度。",
},
{
"id": "ror_lookup",
"name": "ROR 科研机构查询",
"name_en": "ROR Organization Lookup",
"category": "location_knowledge",
"description": "查询科研机构与大学总部位置(自动过滤商业云误配)。",
},
{
"id": "fetch_source_url",
"name": "一手来源 URL 正文抓取",
"name_en": "Primary Source URL Fetch",
"category": "external_evidence",
"description": "SSRF 加固抓取 Epoch Source 1..5 / TOP500 详情页并隔离不可信文本。",
},
{
"id": "web_search",
"name": "可控 Web Search",
"name_en": "Controlled Web Search",
"category": "external_evidence",
"description": "调用系统配置的 Web Search 引擎(Tavily/Brave/SerpAPI/Exa/SearXNG)。",
},
{
"id": "safe_web_fetch",
"name": "SSRF 网页正文抓取",
"name_en": "SSRF-Safe Web Fetch",
"category": "external_evidence",
"description": "受限并发抽取公开网页核心正文并做提示注入隔离。",
},
{
"id": "geocode_verify",
"name": "地理编码器落点校验",
"name_en": "Geocoder Verification",
"category": "location_guardrail",
"description": "将取证地址送入 Nominatim/地理编码器生成唯一候选 ID 与行政区边界。",
},
{
"id": "submit_location_result",
"name": "位置结果强约束提交",
"name_en": "Constrained Location Submit",
"category": "location_guardrail",
"description": "兼容旧版工具式位置提交定义。",
},
{
"id": "location_normalize_context",
"name": "L0 位置上下文归一化与终态检查",
"name_en": "L0 Location Normalize & Terminal Check",
"category": "location_knowledge",
"description": "水合数据库与跨源线索、统一英文国名,并在已确认终态时短路。",
},
{
"id": "location_knowledge_lookup",
"name": "L1 确定性设施知识库查询",
"name_en": "L1 Facility Knowledge Lookup",
"category": "location_knowledge",
"description": "串并行组合查询 builds_upon、ROR、Wikidata(P17) 与 PeeringDB(/api/fac)。",
},
{
"id": "location_web_research",
"name": "L2 并行网页取证与证据编号",
"name_en": "L2 Parallel Web Research",
"category": "external_evidence",
"description": "按轮次并行抓取一手正文并执行结构化英文 WebSearch,为证据编号 E1..En。",
},
{
"id": "location_geocode_verify",
"name": "L3 多粒度级联地理编码校验",
"name_en": "L3 Cascade Geocoder Verify",
"category": "location_guardrail",
"description": "按 街道地址 -> 设施名 -> 城市+省州 -> 城市 级联查 Nominatim 并校验国家与粒度。",
},
{
"id": "location_persist_outcome",
"name": "L4 位置结果输出与终态持久化",
"name_en": "L4 Location Output & Persist",
"category": "location_guardrail",
"description": "输出标准候选坐标载荷与地球联动视角,或在有实证时落库不可定位终态。",
},
]
VALID_TOOL_IDS: frozenset[str] = frozenset(item["id"] for item in TOOL_CATALOG)
MAX_WORKFLOW_NODES = 12
# Graph-level key carrying Earth bindings inside drafts and revision snapshots (no extra column).
DRAFT_BINDINGS_KEY = "bindings"
VALID_NODE_TYPES: frozenset[str] = frozenset(
{"trigger", "deterministic", "llm_agent", "guardrail", "output"}
)
VALID_EDGE_CONDITIONS: frozenset[str] = frozenset(
{
"always",
"on_empty_or_low_confidence",
"on_entity_type",
"on_field_equals",
"on_guardrail_passed",
"on_guardrail_failed",
}
)
PRESERVED_BUILTIN_EDGE_CONDITIONS: frozenset[str] = frozenset(
{"not_terminal", "on_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"}
)
ALLOWED_EDGE_CONDITIONS: frozenset[str] = VALID_EDGE_CONDITIONS | PRESERVED_BUILTIN_EDGE_CONDITIONS
EARTH_ENTITY_TYPES: list[dict[str, str]] = [
{"id": "cable", "name": "海底光缆", "name_en": "Subsea Cable", "group": "infrastructure"},
{"id": "landing_point", "name": "海缆登陆站", "name_en": "Landing Point", "group": "infrastructure"},
{"id": "satellite", "name": "在轨卫星", "name_en": "Satellite", "group": "infrastructure"},
{"id": "vessel", "name": "AIS 船舶", "name_en": "AIS Vessel", "group": "infrastructure"},
{"id": "bgp", "name": "BGP 异常事件", "name_en": "BGP Incident", "group": "infrastructure"},
{"id": "bgp_collector", "name": "BGP 观测站", "name_en": "BGP Collector", "group": "infrastructure"},
{"id": "supercomputer", "name": "超级计算机", "name_en": "Supercomputer", "group": "compute"},
{"id": "gpu_cluster", "name": "GPU 集群", "name_en": "GPU Cluster", "group": "compute"},
{"id": "data_center", "name": "数据中心", "name_en": "Data Center", "group": "compute"},
{"id": "cloud_center", "name": "云计算中心", "name_en": "Cloud Center", "group": "compute"},
{"id": "edge_node", "name": "边缘计算节点", "name_en": "Edge Node", "group": "compute"},
{"id": "compute_center_unresolved", "name": "待定位算力设施", "name_en": "Unresolved Compute Site", "group": "compute"},
{"id": "news", "name": "全球态势新闻", "name_en": "Earth News", "group": "content"},
{"id": "compute_region", "name": "国家/区域算力卡片", "name_en": "Compute Region Card", "group": "content"},
{"id": "viewport", "name": "当前地球视口与图层", "name_en": "Current Earth Viewport", "group": "content"},
{"id": "global", "name": "全球综合态势", "name_en": "Global Posture", "group": "content"},
{"id": "earth_interactable", "name": "自定义交互点", "name_en": "Custom Interactable", "group": "custom"},
]
EARTH_SURFACES: list[dict[str, str]] = [
{"id": "info_card", "name": "地球信息卡顶栏", "name_en": "Earth Info Card"},
{"id": "news_card", "name": "新闻与区域新闻卡", "name_en": "News & Region Cards"},
{"id": "topic_card", "name": "算力专题区域卡", "name_en": "Compute Topic Card"},
{"id": "copilot_quick", "name": "AI 参谋快捷入口", "name_en": "Copilot Quick Actions"},
{"id": "multi_select", "name": "多物件联合对比栏", "name_en": "Multi-Target Compare Tray"},
]
VALID_ENTITY_TYPE_IDS: frozenset[str] = frozenset(item["id"] for item in EARTH_ENTITY_TYPES)
VALID_SURFACE_IDS: frozenset[str] = frozenset(item["id"] for item in EARTH_SURFACES)
MATERIAL_ICON_RE = re.compile(r"^[a-z0-9_]{1,40}$")
WORKFLOW_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{1,78}$")
def normalize_bindings(raw: dict[str, Any] | None) -> dict[str, Any]:
"""Normalize declarative Earth interaction bindings with strict whitelists."""
if not isinstance(raw, dict) or not raw:
return {
"enabled": False,
"surfaces": [],
"entity_types": [],
"interactable_kinds": [],
"min_targets": 1,
"max_targets": 5,
"action_label": "",
"action_label_en": "",
"icon": "forum",
"prompt_template": "",
"priority": 0,
}
surfaces: list[str] = []
for s in raw.get("surfaces") or []:
sid = str(s or "").strip()
if sid in VALID_SURFACE_IDS and sid not in surfaces:
surfaces.append(sid)
entity_types: list[str] = []
for e in raw.get("entity_types") or []:
eid = str(e or "").strip()
if eid in VALID_ENTITY_TYPE_IDS and eid not in entity_types:
entity_types.append(eid)
interactable_kinds: list[str] = []
for k in raw.get("interactable_kinds") or []:
kid = str(k or "").strip()[:60]
if kid and kid not in interactable_kinds:
interactable_kinds.append(kid)
if len(interactable_kinds) >= 20:
break
try:
min_targets = max(1, min(int(raw.get("min_targets") or 1), 5))
except (TypeError, ValueError):
min_targets = 1
try:
max_targets = max(min_targets, min(int(raw.get("max_targets") or 5), 8))
except (TypeError, ValueError):
max_targets = max(min_targets, 5)
try:
priority = max(-100, min(int(raw.get("priority") or 0), 100))
except (TypeError, ValueError):
priority = 0
icon_raw = str(raw.get("icon") or "forum").strip()
icon = icon_raw if MATERIAL_ICON_RE.match(icon_raw) else "forum"
return {
"enabled": bool(raw.get("enabled", False)),
"surfaces": surfaces,
"entity_types": entity_types,
"interactable_kinds": interactable_kinds,
"min_targets": min_targets,
"max_targets": max_targets,
"action_label": str(raw.get("action_label") or "").strip()[:48],
"action_label_en": str(raw.get("action_label_en") or "").strip()[:64],
"icon": icon,
"prompt_template": str(raw.get("prompt_template") or "").strip()[:1000],
"priority": priority,
}
ALLOWED_NODE_PATCH_FIELDS: frozenset[str] = frozenset(
{
"enabled",
"title",
"system_prompt",
"prompt",
"tools",
"model_override",
"thinking_enabled",
"max_steps",
"timeout_seconds",
"native_web_search",
"guardrails",
"params",
}
)
def _node(
node_id: str,
node_type: str,
title: str,
title_en: str,
x: float,
y: float,
*,
description: str = "",
prompt_key: str | None = None,
system_prompt: str = "",
prompt: str = "",
tools: list[str] | None = None,
model_override: str | None = None,
thinking_enabled: bool = True,
max_steps: int = 1,
timeout_seconds: int = 60,
native_web_search: bool = False,
guardrails: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
enabled: bool = True,
) -> dict[str, Any]:
return {
"id": node_id,
"node_type": node_type,
"title": title,
"title_en": title_en,
"description": description,
"position": {"x": x, "y": y},
"enabled": enabled,
"prompt_key": prompt_key,
"system_prompt": system_prompt,
"prompt": prompt,
"tools": list(tools or []),
"model_override": model_override,
"thinking_enabled": thinking_enabled,
"max_steps": max_steps,
"timeout_seconds": timeout_seconds,
"native_web_search": native_web_search,
"guardrails": dict(guardrails or {}),
"params": dict(params or {}),
}
def _edge(
edge_id: str,
source: str,
target: str,
label: str = "",
label_en: str = "",
condition: str = "always",
condition_value: str = "",
) -> dict[str, Any]:
return {
"id": edge_id,
"source": source,
"target": target,
"label": label,
"label_en": label_en or label,
"condition": condition,
"condition_value": condition_value,
}
BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
{
"workflow_id": "default.general",
"name": "默认通用参谋工作流",
"name_en": "Default General Advisor",
"category": "general",
"description": "Playground 默认选项与地球通用追问入口,支持按需挂载五域只读数据与外部搜索。",
"description_en": "Default Playground and general Earth Copilot flow with read-only telemetry and optional web search.",
"is_default": True,
"bindings": {
"enabled": True,
"surfaces": ["copilot_quick", "info_card", "multi_select"],
"entity_types": [
"global",
"viewport",
"cable",
"landing_point",
"satellite",
"vessel",
"bgp",
"bgp_collector",
"supercomputer",
"gpu_cluster",
"data_center",
"cloud_center",
"edge_node",
"earth_interactable",
],
"action_label": "AI 参谋分析",
"action_label_en": "Analyze in AI Copilot",
"icon": "forum",
"priority": 0,
},
"graph": {
"nodes": [
_node(
"intent_router",
"trigger",
"入口:问题与本地上下文接收",
"Trigger: Query & Context",
40,
140,
description="接收用户提问、聚焦实体/新闻与客户端本地记忆备忘。",
),
_node(
"telemetry_context",
"deterministic",
"只读遥测快照装配",
"Telemetry Snapshot",
420,
140,
description="零额外费用装配五域结构化现状与近期新闻索引。",
tools=["query_global_situational", "query_recent_earth_news"],
),
_node(
"advisor_agent",
"llm_agent",
"AI 参谋推理与研判",
"Advisor Reasoning",
800,
140,
description="结合本地记忆与系统遥测输出结构化研判;区分事实与推演。",
prompt_key="situational.copilot.reply",
system_prompt="你是智能星球(Planet)首席态势参谋。仅基于传入事实与工具证据作答,严谨区分确认事实、概率推断与待核验缺口。",
prompt="结合用户聚焦的地球空间上下文、历史记忆与工具数据,给出清晰、可执行、引用可追溯的专业中文分析(若用户使用英文则用英文)。",
tools=["query_global_situational", "query_compute_posture", "query_bgp_incidents", "query_recent_earth_news", "web_search"],
thinking_enabled=True,
max_steps=3,
timeout_seconds=60,
),
_node(
"response_output",
"output",
"SSE 流式响应输出",
"SSE Output",
1180,
140,
description="推送思考过程与正文,并附带本次节点运行轨迹。",
),
],
"edges": [
_edge("e1", "intent_router", "telemetry_context", "初始化上下文", "Load context"),
_edge("e2", "telemetry_context", "advisor_agent", "传入遥测", "Telemetry ready"),
_edge("e3", "advisor_agent", "response_output", "流式返回", "Stream reply"),
],
},
},
{
"workflow_id": "location.resolve_unknown",
"name": "算力/设施未知位置定位工作流",
"name_en": "Compute & Facility Location Agent",
"category": "location",
"description": "真正的条件路由 DAG 工作流:L0 归一化与终态短路 → L1 知识库 → 两轮并行联网取证与单轮结构化研判 → 级联地理编码与 3 条硬护栏。",
"description_en": "True conditional DAG workflow: L0 normalize -> L1 knowledge lookup -> 2-round parallel web research & JSON judgment -> cascade geocoder & 3 hard guardrails.",
"is_default": False,
"bindings": {
"enabled": True,
"surfaces": ["info_card"],
"entity_types": ["compute_center_unresolved"],
"action_label": "AI 坐标定位核验",
"action_label_en": "Verify Coordinates",
"icon": "location_searching",
"priority": 25,
},
"graph": {
"nodes": [
_node(
"l0_normalize",
"deterministic",
"L0:实体归一化与终态检查",
"L0: Normalize & Terminal Check",
40,
180,
description="水合数据库与跨源兄弟线索、转换英文国家名、过滤 .csv 原始表并在已确认终态时直接短路。",
tools=["location_normalize_context"],
params={"short_circuit_terminal_statuses": True},
),
_node(
"l1_knowledge",
"deterministic",
"L1:确定性设施知识库查询",
"L1: Knowledge Resolvers",
380,
80,
description="依次匹配 builds_upon、ROR,并行查询 Wikidata(P625+P17) 与 PeeringDB(/api/fac)。",
tools=["location_knowledge_lookup"],
params={
"builds_upon_enabled": True,
"ror_enabled": True,
"wikidata_enabled": True,
"peeringdb_enabled": True,
},
),
_node(
"l2_research_r1",
"deterministic",
"L2-R1:并行一手抓取与英文搜索",
"L2-R1: Parallel Web Research",
720,
220,
description="并行抓取一手正文链接与 2 条精简英文搜索,为全部证据分配 E1..En 唯一编号。",
tools=["location_web_research"],
params={"round": 1, "max_search_queries": 2, "max_fetch_urls": 2},
),
_node(
"l2_judge_r1",
"llm_agent",
"L2-J1:首轮证据语义研判",
"L2-J1: Round-1 Judgment",
1060,
220,
description="基于 E1..En 证据输出单轮结构化 JSON:直接定位 / 发起定点补查 / 确认终态。",
prompt_key="location.factcheck.resolve",
system_prompt=(
"你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n"
"规则:\n"
"1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n"
"2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n"
"3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n"
"4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。\n"
"5) 输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,且严禁出现 E1、E6、E1-E5 等内部证据编号(仅在 evidence_ids 数组填写编号供校验)。"
),
prompt="核查给定设施的真实物理所在城市与园区位置,并按 JSON 契约返回初判结论。",
thinking_enabled=True,
max_steps=1,
timeout_seconds=60,
native_web_search=False,
params={"output_schema": LOCATION_JUDGE_R1_SCHEMA, "allow_followup": True},
),
_node(
"l2_research_r2",
"deterministic",
"L2-R2:定向补搜与正文全文抓取",
"L2-R2: Targeted Follow-up Research",
1400,
340,
description="仅当 J1 判定需要补查时触发,执行 J1 给出的精准补搜词与候选页全文抓取。",
tools=["location_web_research"],
params={"round": 2, "max_search_queries": 2, "max_fetch_urls": 2},
),
_node(
"l2_judge_r2",
"llm_agent",
"L2-J2:综合全部证据终判",
"L2-J2: Final Evidence Judgment",
1740,
340,
description="结合两轮全部 E1..En 证据给出最终位置研判或明确无法定位原因。",
prompt_key="location.factcheck.resolve",
system_prompt=(
"你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n"
"若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;"
"若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态。\n"
"输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,直接说明物理部署结论或具体信息缺口,严禁出现 E1、E6、E1-E5 等内部证据编号(evidence_ids 数组照常填写供校验)。"
),
prompt="综合两轮证据完成最终物理位置裁决。",
thinking_enabled=True,
max_steps=1,
timeout_seconds=60,
native_web_search=False,
params={"output_schema": LOCATION_JUDGE_FINAL_SCHEMA, "allow_followup": False},
),
_node(
"l3_geocode",
"deterministic",
"L3:多粒度级联地理编码",
"L3: Cascade Geocoder",
2080,
180,
description="由代码按 街道地址 → 设施+城市 → 城市+省州 → 城市 级联查 Nominatim 落点并校验国家。",
tools=["location_geocode_verify"],
),
_node(
"l3_geo_guardrail",
"guardrail",
"L3:抗幻觉地理硬护栏",
"L3: Geo Anti-Hallucination Guardrail",
2420,
180,
description="校验证据真实引用(evidence_ids)、坐标>=城市级精度、置信度下限及受控跨国覆写。",
guardrails={
"geo_verification": True,
"min_confidence": 0.55,
"enforce_country_match": True,
"require_tool_cited_urls": True,
"downgrade_geocoded_site_to_city": True,
},
),
_node(
"l4_persist_outcome",
"output",
"L4:候选输出与终态落库",
"L4: Persist & Structured Output",
2760,
180,
description="输出标准化候选坐标载荷与地球聚焦视角,或在有实证时落库终态。",
tools=["location_persist_outcome"],
params={"persist_terminal_statuses": True, "fly_to_target": True},
),
],
"edges": [
_edge("loc-e1", "l0_normalize", "l1_knowledge", "未标记终态", "Not terminal", "not_terminal"),
_edge("loc-e2", "l0_normalize", "l4_persist_outcome", "已有终态缓存", "Cached terminal", "on_terminal"),
_edge("loc-e3", "l1_knowledge", "l4_persist_outcome", "知识库命中", "L1 hit", "high_confidence_hit"),
_edge("loc-e4", "l1_knowledge", "l2_research_r1", "未命中进联网取证", "Miss -> L2 research", "fallback_to_agent"),
_edge("loc-e5", "l2_research_r1", "l2_judge_r1", "首轮证据就绪", "R1 evidence ready", "always"),
_edge("loc-e6", "l2_judge_r1", "l2_research_r2", "需定向补查", "Need followup", "on_field_equals", "decision=need_followup"),
_edge("loc-e7", "l2_research_r2", "l2_judge_r2", "补查证据就绪", "R2 evidence ready", "always"),
_edge("loc-e8", "l2_judge_r1", "l3_geocode", "J1 定位成功", "J1 located", "on_field_equals", "decision=located"),
_edge("loc-e9", "l2_judge_r2", "l3_geocode", "J2 定位成功", "J2 located", "on_field_equals", "decision=located"),
_edge("loc-e10", "l3_geocode", "l3_geo_guardrail", "送入硬护栏", "Verify geo", "always"),
_edge("loc-e11", "l2_judge_r1", "l3_geo_guardrail", "J1 终态/未定论", "J1 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"),
_edge("loc-e12", "l2_judge_r2", "l3_geo_guardrail", "J2 终态/未定论", "J2 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"),
_edge("loc-e13", "l3_geo_guardrail", "l4_persist_outcome", "输出结论", "Emit outcome", "always"),
],
},
},
{
"workflow_id": "earth.news.analysis",
"name": "Earth 全球新闻分析与汉化工作流",
"name_en": "Earth News Analysis & Enrichment",
"category": "earth",
"description": "涵盖前台点击新闻卡触发的流式局势分析,以及后台 RSS 入库汉化定位任务。",
"description_en": "Powers interactive news deep-dive streaming on Earth and background RSS enrichment/localization.",
"is_default": False,
"bindings": {
"enabled": True,
"surfaces": ["news_card", "info_card", "copilot_quick"],
"entity_types": ["news"],
"action_label": "新闻深度研判",
"action_label_en": "Deep News Analysis",
"icon": "forum",
"priority": 20,
},
"graph": {
"nodes": [
_node("news_trigger", "trigger", "入口:聚焦新闻或 RSS 条目", "Trigger: News Context", 40, 160),
_node(
"news_enrich_node",
"llm_agent",
"RSS 汉化与物理落点 (入库)",
"Background RSS Enrichment",
430,
40,
prompt_key="earth.news.enrich",
system_prompt="",
prompt="Return exactly one strict JSON object with a location object and a localizations object. Infer the most likely physical event location and produce a faithful Simplified Chinese title plus a one-sentence newswire-style Chinese summary based only on the supplied RSS headline, description, source, and date.",
thinking_enabled=False,
max_steps=1,
timeout_seconds=30,
),
_node(
"news_analyst_node",
"llm_agent",
"新闻深度局势研判 (前台流式)",
"Interactive News Analysis",
430,
280,
prompt_key="earth.news.analysis",
system_prompt="你是智能星球的全球新闻与地缘基础设施分析师。严谨区分已报道事实与推演研判,禁止虚构未报道数据。",
prompt="围绕聚焦新闻输出:1) 核心事实与背景;2) 对算力/海缆/航运/航天及地缘格局的影响;3) 后续观察信号与不确定边界。",
tools=["query_recent_earth_news", "query_global_situational", "safe_web_fetch"],
thinking_enabled=True,
max_steps=2,
timeout_seconds=60,
),
_node("news_output", "output", "新闻分析 / 汉化结构输出", "Output Result", 840, 160),
],
"edges": [
_edge("nw-e1", "news_trigger", "news_enrich_node", "后台采集汉化", "Ingest enrich", "ingest"),
_edge("nw-e2", "news_trigger", "news_analyst_node", "前台点击 AI 分析", "User click analyze", "interactive"),
_edge("nw-e3", "news_enrich_node", "news_output", "落库 JSON", "Store"),
_edge("nw-e4", "news_analyst_node", "news_output", "SSE 推送", "SSE stream"),
],
},
},
{
"workflow_id": "compute.comparison",
"name": "算力对比战略推演工作流",
"name_en": "Compute Posture & Extraction",
"category": "wargame",
"description": "负责中美及全球算力对比、双边 RPI 归因推演及报告候选观测值提取。",
"description_en": "Drives bilateral/global compute comparison analysis, RPI attribution, and report evidence extraction.",
"is_default": False,
"bindings": {
"enabled": True,
"surfaces": ["topic_card", "info_card", "multi_select", "copilot_quick"],
"entity_types": [
"compute_region",
"supercomputer",
"gpu_cluster",
"data_center",
"cloud_center",
"edge_node",
],
"action_label": "算力战略对比推演",
"action_label_en": "Compute Strategy Comparison",
"icon": "query_stats",
"priority": 15,
},
"graph": {
"nodes": [
_node("comp_trigger", "trigger", "入口:时间口径与国家焦点", "Trigger: Compute Query", 40, 140),
_node(
"comp_series",
"deterministic",
"多口径算力与 RPI 确定性计算",
"Deterministic Compute Series",
420,
140,
tools=["query_compute_posture"],
),
_node(
"comp_brief_llm",
"llm_agent",
"算力战略参谋结论与候选提取",
"Compute Strategic Synthesis",
800,
140,
prompt_key="compute.posture.brief",
system_prompt="你是国家级算力战略参谋分析师。仅输出严格符合约定 JSON 结构的分析结论,所有证据 ID 必须来自输入 evidence 字典。",
prompt="基于多口径算力对比序列、RPI 与八大枢纽生成战略态势摘要。",
tools=["query_compute_posture", "safe_web_fetch"],
thinking_enabled=True,
max_steps=2,
),
_node("comp_viewspec", "output", "ViewSpec / 地球镜头联动输出", "ViewSpec & Scene Output", 1180, 140),
],
"edges": [
_edge("cp-e1", "comp_trigger", "comp_series", "按截止日期过滤", "Apply cutoff"),
_edge("cp-e2", "comp_series", "comp_brief_llm", "输入确定性序列", "Series ready"),
_edge("cp-e3", "comp_brief_llm", "comp_viewspec", "编译面板与镜头", "Compile blocks"),
],
},
},
{
"workflow_id": "wargame.infrastructure",
"name": "兵棋推演与多域基础设施研判",
"name_en": "Infrastructure & BGP Wargame",
"category": "wargame",
"description": "BGP、海缆、卫星、船舶四域空间异常取证推演与断缆/扰动边界守卫。",
"description_en": "Multi-domain infrastructure incident investigation covering BGP, cables, satellites, and vessels.",
"is_default": False,
"bindings": {
"enabled": True,
"surfaces": ["info_card", "multi_select", "copilot_quick"],
"entity_types": ["cable", "landing_point", "bgp", "vessel", "satellite", "global"],
"action_label": "多域兵棋推演",
"action_label_en": "Multi-Domain Wargame",
"icon": "hub",
"priority": 10,
},
"graph": {
"nodes": [
_node("wg_trigger", "trigger", "入口:空间域与历史推演口径", "Trigger: Domain & TimeBasis", 40, 140),
_node(
"wg_snapshots",
"deterministic",
"多域拓扑与事件隔离快照",
"Isolated Domain Snapshots",
420,
140,
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture"],
),
_node(
"wg_investigator",
"llm_agent",
"基础设施取证与兵棋推演",
"Wargame Investigator",
800,
140,
prompt_key="incident.investigator.brief",
system_prompt="你是全球互联网与海缆基础设施取证参谋。严格区分 confirmed_facts、candidate_explanations、counter_evidence 与 open_gaps;无独立海缆告警证据时严禁将地理邻近推断为物理断缆。",
prompt="结合内部多域快照与受控外部取证槽位,生成结构化事件研判 JSON 与地球高亮实体。",
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture", "web_search", "safe_web_fetch"],
thinking_enabled=True,
max_steps=3,
guardrails={"disallow_unverified_cable_cut": True},
),
_node("wg_output", "output", "推演矩阵与地球态势导览输出", "Topology & Tour Output", 1180, 140),
],
"edges": [
_edge("wg-e1", "wg_trigger", "wg_snapshots", "时间遮蔽加载", "Mask future"),
_edge("wg-e2", "wg_snapshots", "wg_investigator", "传入快照", "Snapshots ready"),
_edge("wg-e3", "wg_investigator", "wg_output", "输出推演结果", "Render workbench"),
],
},
},
{
"workflow_id": "brief.bgp",
"name": "BGP 态势值班简报工作流",
"name_en": "BGP Shift Brief",
"category": "brief",
"description": "已从旧 BGP 页面收编进 AI 参谋 Playground(/bgp-brief),聚合采集器覆盖率与事故。",
"description_en": "Consolidates BGP incidents, anomalies, and collector coverage into Playground shift briefs.",
"is_default": False,
"bindings": {
"enabled": True,
"surfaces": ["info_card", "copilot_quick"],
"entity_types": ["bgp", "bgp_collector"],
"action_label": "BGP 态势值班简报",
"action_label_en": "BGP Duty Brief",
"icon": "lan",
"priority": 15,
},
"graph": {
"nodes": [
_node("bgp_agg", "deterministic", "BGP 事实与覆盖率聚合", "BGP Facts Collector", 40, 140, tools=["query_bgp_incidents"]),
_node(
"bgp_brief_node",
"llm_agent",
"BGP 值班简报生成",
"BGP Brief Writer",
430,
140,
prompt_key="bgp.brief",
system_prompt="你是 BGP 值班分析师。请直接输出面向值班人员的中文 Markdown 简报,只写最终研判内容。",
prompt="基于当前 BGP incidents、anomalies、原始观测事件、观测站覆盖与 prefix geography 证据生成态势简报。",
tools=["query_bgp_incidents"],
thinking_enabled=True,
),
_node("bgp_out", "output", "Markdown 简报输出", "Brief Output", 820, 140),
],
"edges": [
_edge("bb-e1", "bgp_agg", "bgp_brief_node"),
_edge("bb-e2", "bgp_brief_node", "bgp_out"),
],
},
},
{
"workflow_id": "brief.alerts",
"name": "告警与跨模块态势简报工作流",
"name_en": "System & Situational Alert Brief",
"category": "brief",
"description": "收编原系统告警与态势告警中的 AI 简报模块(/alerts-brief、/situational-brief)。",
"description_en": "Consolidates system and cross-module situational alert briefings inside Playground.",
"is_default": False,
"graph": {
"nodes": [
_node("alt_agg", "deterministic", "告警严重度与跨模块联动采样", "Alerts & Cross-Domain Facts", 40, 140, tools=["query_global_situational", "query_bgp_incidents"]),
_node(
"alt_brief_node",
"llm_agent",
"值班告警研判生成",
"Alert Brief Analyst",
430,
140,
prompt_key="alerts.situational.brief",
system_prompt="你是告警研判助手。请基于输入的告警事实、上下文与约束输出可执行的值班研判。",
prompt="综合系统告警、BGP 事故/异常与近期简报,突出待处理风险与优先动作。",
tools=["query_global_situational", "query_bgp_incidents"],
),
_node("alt_out", "output", "研判报告输出", "Alert Brief Output", 820, 140),
],
"edges": [
_edge("ab-e1", "alt_agg", "alt_brief_node"),
_edge("ab-e2", "alt_brief_node", "alt_out"),
],
},
},
{
"workflow_id": "collection.assist",
"name": "采集配置辅助(映射 / 凭据教程)",
"name_en": "Collection DSL & Credential Guide",
"category": "ops",
"description": "管理自定义数据源字段映射 DSL 自动生成与采集器凭据获取教程生成。",
"description_en": "Manages automated datasource field-mapping DSL synthesis and collector credential tutorials.",
"is_default": False,
"graph": {
"nodes": [
_node("col_in", "trigger", "入口:API 样本或数据源声明", "Trigger: Sample / Provider", 40, 140),
_node(
"col_map_node",
"llm_agent",
"字段映射 DSL / 官方凭据教程生成",
"DSL & Guide Generator",
430,
140,
prompt_key="datasource.mapping",
system_prompt="根据用户样本返回合法 JSON 映射 DSL,或在生成凭据教程时仅引用已检出官方网页来源。",
prompt="Return only JSON for a deterministic mapping DSL with source.items_path and fields, or a grounded setup tutorial.",
tools=["web_search"],
thinking_enabled=False,
),
_node("col_out", "output", "DSL Schema / Markdown 指南", "DSL / Guide Output", 820, 140),
],
"edges": [
_edge("cl-e1", "col_in", "col_map_node"),
_edge("cl-e2", "col_map_node", "col_out"),
],
},
},
{
"workflow_id": "ops.diagnostics",
"name": "运维诊断与长对话上下文压缩",
"name_en": "Provider Diagnostics & Compaction",
"category": "ops",
"description": "负责供应商连通性极简探针,以及多轮对话超预算时的滚动摘要压缩。",
"description_en": "Handles lightweight provider connectivity checks and rolling conversation memory compaction.",
"is_default": False,
"graph": {
"nodes": [
_node(
"diag_node",
"llm_agent",
"连通性探针 / 滚动上下文压缩",
"Probe & Compaction Node",
120,
140,
prompt_key="ai.connection_test",
system_prompt="如果是连通性测试只回复 OK;如果是对话压缩请输出不超过 280 字的中文要点摘要。",
prompt="Reply OK.",
thinking_enabled=False,
timeout_seconds=15,
),
_node("diag_out", "output", "状态返回", "Status Output", 540, 140),
],
"edges": [_edge("dg-e1", "diag_node", "diag_out")],
},
},
{
"workflow_id": "meta.workflow_evolver",
"name": "AI 工作流自进化元引擎",
"name_en": "AI Workflow Meta-Evolver",
"category": "meta",
"description": "负责诊断业务工作流失败/差评与模型漂移并生成最小补丁;可基于历史进化台账自我迭代,但受宪法硬校验与灰度回滚约束。",
"description_en": "Diagnoses workflow failures, feedback, and model drift to synthesize minimal patches; self-improves from evolution ledger outcomes under immutable constitution guardrails.",
"is_default": False,
"graph": {
"nodes": [
_node(
"diag_node",
"llm_agent",
"诊断轨迹与模型画像",
"Diagnose Traces & Model Profile",
80,
140,
description="分析运行失败、用户差评原因、闲置工具与当前活跃模型能力特征,定位最需要改进的节点。",
system_prompt=(
"你是智能星球 AI 工作流诊断专家。请结合最近运行失败样本、用户差评说明、当前活跃模型能力画像以及历史进化正负经验,"
"准确定位性能瓶颈或模型适配偏差,给出克制、具体的根因诊断。"
),
prompt=(
"结合 workflow_id={{workflow_id}} 的失败/差评轨迹、闲置工具统计、活跃模型能力画像与历史台账正负经验,"
"输出简洁清晰的节点级诊断重点。"
),
thinking_enabled=True,
max_steps=1,
timeout_seconds=60,
),
_node(
"patch_node",
"llm_agent",
"生成最小补丁方案",
"Synthesize Minimal Patch",
460,
140,
description="基于诊断结果生成最小化、允许字段白名单内的节点补丁 JSON,避免过度重写。",
system_prompt=(
"你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:"
"{\"summary\": string, \"node_patches\": [{\"node_id\": string, \"field\": string, \"after\": any, \"reason\": string}]}。"
"坚持最小改动原则(单次最多调整 1~2 个关键节点),参考历史已验证有效经验并规避曾导致回滚的改法。"
),
prompt=(
"依据诊断结论与允许字段白名单,为目标工作流输出严格 JSON 补丁。"
"严禁虚构工具 ID,严禁清空非空 system_prompt。"
),
thinking_enabled=True,
max_steps=1,
timeout_seconds=60,
),
_node(
"verify_output",
"guardrail",
"宪法硬校验与灰度输出",
"Constitution Gate & Output",
840,
140,
description="受 Python Tier-0 宪法代码保护,负责校验变更半径、防循环图、并触发灰度自动回滚监控。",
guardrails={
"immutable_tier0": True,
"enforce_blast_radius": True,
"enforce_canary_rollback": True,
},
),
],
"edges": [
_edge("meta-e1", "diag_node", "patch_node", "诊断摘要", "Diagnosis"),
_edge("meta-e2", "patch_node", "verify_output", "宪法校验", "Constitution check"),
],
},
},
]
_BUILTIN_BY_ID: dict[str, dict[str, Any]] = {
item["workflow_id"]: item for item in BUILTIN_WORKFLOWS
}
# Exact coordinates shipped in v0.81.0 so untouched stock v1 rows can be upgraded safely.
_LEGACY_BUILTIN_POSITIONS: dict[str, dict[str, tuple[float, float]]] = {
"default.general": {
"intent_router": (40, 120),
"telemetry_context": (320, 120),
"advisor_agent": (620, 120),
"response_output": (920, 120),
},
"location.resolve_unknown": {
"l0_normalize": (40, 140),
"l1_knowledge": (320, 60),
"l2_agent_research": (320, 250),
"l3_geo_guardrail": (640, 140),
"l4_persist_outcome": (940, 140),
},
"earth.news.analysis": {
"news_trigger": (40, 140),
"news_enrich_node": (340, 60),
"news_analyst_node": (340, 240),
"news_output": (680, 140),
},
"compute.comparison": {
"comp_trigger": (40, 130),
"comp_series": (310, 130),
"comp_brief_llm": (610, 130),
"comp_viewspec": (910, 130),
},
"wargame.infrastructure": {
"wg_trigger": (40, 140),
"wg_snapshots": (310, 140),
"wg_investigator": (600, 140),
"wg_output": (900, 140),
},
"brief.bgp": {
"bgp_agg": (60, 130),
"bgp_brief_node": (400, 130),
"bgp_out": (740, 130),
},
"brief.alerts": {
"alt_agg": (60, 130),
"alt_brief_node": (400, 130),
"alt_out": (740, 130),
},
"collection.assist": {
"col_in": (60, 130),
"col_map_node": (400, 130),
"col_out": (740, 130),
},
"ops.diagnostics": {
"diag_node": (240, 130),
"diag_out": (600, 130),
},
}
def _upgrade_untouched_legacy_positions(row: AIWorkflow, spec: dict[str, Any]) -> bool:
"""Upgrade node coordinates only when the workflow is still an untouched stock v1 layout."""
if row.active_revision != 1 or row.draft_graph is not None:
return False
legacy_map = _LEGACY_BUILTIN_POSITIONS.get(row.workflow_id)
graph = row.published_graph if isinstance(row.published_graph, dict) else None
if not legacy_map or not graph:
return False
nodes = graph.get("nodes")
if not isinstance(nodes, list) or len(nodes) != len(legacy_map):
return False
for node in nodes:
if not isinstance(node, dict):
return False
expected = legacy_map.get(str(node.get("id") or ""))
pos = node.get("position")
if not expected or not isinstance(pos, dict):
return False
if pos.get("x") != expected[0] or pos.get("y") != expected[1]:
return False
target_positions = {
str(n["id"]): copy.deepcopy(n["position"])
for n in spec.get("graph", {}).get("nodes", [])
if isinstance(n, dict) and n.get("id") and isinstance(n.get("position"), dict)
}
if len(target_positions) != len(nodes):
return False
updated_graph = copy.deepcopy(graph)
for node in updated_graph["nodes"]:
nid = str(node["id"])
node["position"] = target_positions[nid]
row.published_graph = updated_graph
return True
_LEGACY_LOC_NODE_IDS = frozenset(
{"l0_normalize", "l1_knowledge", "l2_agent_research", "l3_geo_guardrail", "l4_persist_outcome"}
)
def _upgrade_untouched_location_v1(row: AIWorkflow, spec: dict[str, Any]) -> bool:
"""Upgrade retired 5-node `location.resolve_unknown` graphs (and legacy 5-node drafts) to the 9-node DAG."""
if row.workflow_id != "location.resolve_unknown":
return False
changed = False
graph = row.published_graph if isinstance(row.published_graph, dict) else None
if graph:
node_ids = {
str(n.get("id") or "")
for n in (graph.get("nodes") or [])
if isinstance(n, dict) and n.get("id")
}
if node_ids == _LEGACY_LOC_NODE_IDS:
row.published_graph = copy.deepcopy(spec["graph"])
changed = True
draft = row.draft_graph if isinstance(row.draft_graph, dict) else None
if draft:
draft_ids = {
str(n.get("id") or "")
for n in (draft.get("nodes") or [])
if isinstance(n, dict) and n.get("id")
}
if draft_ids == _LEGACY_LOC_NODE_IDS:
row.draft_graph = None
changed = True
return changed
_PREV_LOC_JUDGE_PROMPTS: dict[str, str] = {
"l2_judge_r1": (
"你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n"
"规则:\n"
"1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n"
"2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n"
"3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n"
"4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。"
),
"l2_judge_r2": (
"你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n"
"若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;"
"若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态,并在 reasoning 说明具体缺口。"
),
}
def _upgrade_untouched_location_judge_prompts(row: AIWorkflow, spec: dict[str, Any]) -> bool:
"""Update untouched stock `l2_judge_r1` / `l2_judge_r2` prompts while preserving user edits."""
if row.workflow_id != "location.resolve_unknown":
return False
target_prompts = {
str(n.get("id") or ""): str(n.get("system_prompt") or "")
for n in spec.get("graph", {}).get("nodes", [])
if isinstance(n, dict) and n.get("id") in _PREV_LOC_JUDGE_PROMPTS
}
if len(target_prompts) != len(_PREV_LOC_JUDGE_PROMPTS):
return False
def _patch_graph(raw_graph: Any) -> tuple[dict[str, Any] | None, bool]:
if not isinstance(raw_graph, dict):
return None, False
nodes = raw_graph.get("nodes")
if not isinstance(nodes, list):
return None, False
cloned = copy.deepcopy(raw_graph)
graph_changed = False
for node in cloned.get("nodes", []):
if not isinstance(node, dict):
continue
nid = str(node.get("id") or "")
if nid not in _PREV_LOC_JUDGE_PROMPTS:
continue
current_prompt = str(node.get("system_prompt") or "")
if current_prompt == _PREV_LOC_JUDGE_PROMPTS[nid]:
node["system_prompt"] = target_prompts[nid]
graph_changed = True
return (cloned, True) if graph_changed else (None, False)
changed = False
new_pub, pub_changed = _patch_graph(row.published_graph)
if pub_changed and new_pub is not None:
row.published_graph = new_pub
changed = True
new_draft, draft_changed = _patch_graph(row.draft_graph)
if draft_changed and new_draft is not None:
row.draft_graph = new_draft
changed = True
return changed
async def ensure_builtin_workflows(db: AsyncSession) -> None:
"""Idempotently seed all 9 built-in workflows into `ai_workflows`."""
if not hasattr(db, "execute"):
return
try:
existing_rows = (await db.execute(select(AIWorkflow))).scalars().all()
except Exception:
return
existing_by_id = {row.workflow_id: row for row in existing_rows}
changed = False
for spec in BUILTIN_WORKFLOWS:
wf_id = spec["workflow_id"]
default_bindings = normalize_bindings(spec.get("bindings"))
if wf_id in existing_by_id:
existing_row = existing_by_id[wf_id]
if _upgrade_untouched_legacy_positions(existing_row, spec):
changed = True
if _upgrade_untouched_location_v1(existing_row, spec):
changed = True
if _upgrade_untouched_location_judge_prompts(existing_row, spec):
changed = True
if not existing_row.bindings and spec.get("bindings"):
existing_row.bindings = default_bindings
changed = True
continue
graph = copy.deepcopy(spec["graph"])
db.add(
AIWorkflow(
workflow_id=wf_id,
name=spec["name"],
name_en=spec["name_en"],
category=spec["category"],
description=spec["description"],
description_en=spec["description_en"],
is_default=bool(spec.get("is_default")),
is_builtin=True,
active_revision=1,
published_graph=graph,
draft_graph=None,
bindings=default_bindings,
updated_by="system",
)
)
db.add(
AIWorkflowRevision(
workflow_id=wf_id,
revision=1,
status="published",
graph_json=graph,
change_summary="Initial built-in workflow baseline",
created_by="system",
)
)
changed = True
if changed:
await db.commit()
def _fallback_workflow_dict(workflow_id: str) -> dict[str, Any] | None:
spec = _BUILTIN_BY_ID.get(workflow_id)
if not spec:
return None
return {
"id": None,
"workflow_id": spec["workflow_id"],
"name": spec["name"],
"name_en": spec["name_en"],
"category": spec["category"],
"description": spec["description"],
"description_en": spec["description_en"],
"is_default": bool(spec.get("is_default")),
"is_builtin": True,
"active_revision": 1,
"has_draft": False,
"published_graph": copy.deepcopy(spec["graph"]),
"draft_graph": None,
"bindings": normalize_bindings(spec.get("bindings")),
"updated_by": "system",
"created_at": None,
"updated_at": None,
}
async def list_workflows(db: AsyncSession) -> list[dict[str, Any]]:
await ensure_builtin_workflows(db)
rows = (
await db.execute(select(AIWorkflow).order_by(AIWorkflow.is_default.desc(), AIWorkflow.id.asc()))
).scalars().all()
return [row.to_dict() for row in rows] if rows else [_fallback_workflow_dict(w["workflow_id"]) for w in BUILTIN_WORKFLOWS]
async def list_public_workflow_bindings(db: AsyncSession) -> list[dict[str, Any]]:
"""Return strictly public-safe published workflow metadata & Earth bindings (no prompts/graphs)."""
await ensure_builtin_workflows(db)
rows: list[Any] = []
if hasattr(db, "execute"):
try:
rows = (
await db.execute(select(AIWorkflow).order_by(AIWorkflow.is_builtin.asc(), AIWorkflow.id.asc()))
).scalars().all()
except Exception:
rows = []
raw_items = [row.to_dict() for row in rows] if rows else [
_fallback_workflow_dict(w["workflow_id"]) for w in BUILTIN_WORKFLOWS
]
public_items: list[dict[str, Any]] = []
for item in raw_items:
if not item:
continue
bindings = normalize_bindings(item.get("bindings"))
if not bindings.get("enabled") or not bindings.get("surfaces"):
continue
public_items.append(
{
"workflow_id": item["workflow_id"],
"name": item["name"],
"name_en": item.get("name_en") or item["name"],
"description": item.get("description") or "",
"description_en": item.get("description_en") or item.get("description") or "",
"category": item.get("category") or "custom",
"is_default": bool(item.get("is_default")),
"is_builtin": bool(item.get("is_builtin", True)),
"active_revision": int(item.get("active_revision") or 1),
"bindings": bindings,
}
)
public_items.sort(
key=lambda x: (
-int(x["bindings"].get("priority") or 0),
1 if x["is_builtin"] else 0,
x["workflow_id"],
)
)
return public_items
async def get_workflow_detail(db: AsyncSession, workflow_id: str) -> dict[str, Any]:
await ensure_builtin_workflows(db)
row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
revisions = (
await db.execute(
select(AIWorkflowRevision)
.where(AIWorkflowRevision.workflow_id == workflow_id)
.order_by(desc(AIWorkflowRevision.revision))
.limit(30)
)
).scalars().all()
fixtures = (
await db.execute(
select(AIWorkflowFixture)
.where(AIWorkflowFixture.workflow_id == workflow_id)
.order_by(desc(AIWorkflowFixture.id))
.limit(20)
)
).scalars().all()
return {
"workflow": row.to_dict(),
"revisions": [rev.to_dict() for rev in revisions],
"fixtures": [fix.to_dict() for fix in fixtures],
"tool_catalog": TOOL_CATALOG,
"earth_entity_types": EARTH_ENTITY_TYPES,
"earth_surfaces": EARTH_SURFACES,
}
def _validate_graph_payload(graph: dict[str, Any]) -> dict[str, Any]:
if not isinstance(graph, dict):
raise HTTPException(status_code=422, detail="Workflow graph must be a JSON object")
raw_nodes = graph.get("nodes")
raw_edges = graph.get("edges") or []
if not isinstance(raw_nodes, list) or not raw_nodes:
raise HTTPException(status_code=422, detail="Workflow graph requires at least one node")
if len(raw_nodes) > MAX_WORKFLOW_NODES:
raise HTTPException(
status_code=422,
detail=f"Workflow graph supports at most {MAX_WORKFLOW_NODES} nodes",
)
cleaned_nodes: list[dict[str, Any]] = []
seen_ids: set[str] = set()
for item in raw_nodes:
if not isinstance(item, dict):
continue
nid = str(item.get("id") or "").strip()
if not nid or nid in seen_ids:
raise HTTPException(status_code=422, detail=f"Invalid or duplicate node id: {nid!r}")
node_type = str(item.get("node_type") or "llm_agent").strip()
if node_type not in VALID_NODE_TYPES:
raise HTTPException(status_code=422, detail=f"Unsupported node_type: {node_type!r}")
seen_ids.add(nid)
tools = [str(t).strip() for t in (item.get("tools") or []) if str(t).strip() in VALID_TOOL_IDS]
pos = item.get("position") if isinstance(item.get("position"), dict) else {}
cleaned_nodes.append(
{
"id": nid,
"node_type": node_type,
"title": str(item.get("title") or nid),
"title_en": str(item.get("title_en") or item.get("title") or nid),
"description": str(item.get("description") or ""),
"position": {
"x": float(pos.get("x") or 0),
"y": float(pos.get("y") or 0),
},
"enabled": bool(item.get("enabled", True)),
"prompt_key": str(item["prompt_key"]).strip() if item.get("prompt_key") else None,
"system_prompt": str(item.get("system_prompt") or ""),
"prompt": str(item.get("prompt") or ""),
"tools": tools,
"model_override": str(item["model_override"]).strip() if item.get("model_override") else None,
"thinking_enabled": bool(item.get("thinking_enabled", True)),
"max_steps": max(1, min(int(item.get("max_steps") or 1), 8)),
"timeout_seconds": max(5, min(int(item.get("timeout_seconds") or 60), 300)),
"native_web_search": bool(item.get("native_web_search", False)),
"guardrails": dict(item.get("guardrails") or {}) if isinstance(item.get("guardrails"), dict) else {},
"params": dict(item.get("params") or {}) if isinstance(item.get("params"), dict) else {},
}
)
if not cleaned_nodes:
raise HTTPException(status_code=422, detail="Workflow graph requires at least one valid node")
cleaned_edges: list[dict[str, Any]] = []
adjacency: dict[str, list[str]] = {n["id"]: [] for n in cleaned_nodes}
indegree: dict[str, int] = {n["id"]: 0 for n in cleaned_nodes}
seen_pairs: set[tuple[str, str]] = set()
for idx, edge in enumerate(raw_edges):
if not isinstance(edge, dict):
continue
src = str(edge.get("source") or "").strip()
tgt = str(edge.get("target") or "").strip()
if src not in seen_ids or tgt not in seen_ids:
continue
if src == tgt:
raise HTTPException(status_code=422, detail=f"Self-loop edge on node {src!r} is not allowed")
if (src, tgt) in seen_pairs:
continue
seen_pairs.add((src, tgt))
raw_cond = str(edge.get("condition") or "always").strip()
cond = raw_cond if raw_cond in ALLOWED_EDGE_CONDITIONS else "always"
cleaned_edges.append(
{
"id": str(edge.get("id") or f"e-{idx + 1}"),
"source": src,
"target": tgt,
"label": str(edge.get("label") or ""),
"label_en": str(edge.get("label_en") or edge.get("label") or ""),
"condition": cond,
"condition_value": str(edge.get("condition_value") or "").strip()[:200],
}
)
adjacency[src].append(tgt)
indegree[tgt] += 1
# Enforce DAG invariant with Kahn's topological sort.
queue = deque(nid for nid, deg in indegree.items() if deg == 0)
visited = 0
while queue:
cur = queue.popleft()
visited += 1
for nxt in adjacency[cur]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
if visited != len(cleaned_nodes):
raise HTTPException(status_code=422, detail="Workflow graph cannot contain cycles")
return {"nodes": cleaned_nodes, "edges": cleaned_edges}
def build_starter_workflow_graph(name: str = "") -> dict[str, Any]:
"""Build a minimal valid 3-node DAG skeleton for new custom workflows."""
label = name.strip() or "自定义分析"
return {
"nodes": [
_node(
"trigger_intake",
"trigger",
"入口:交互物件与上下文",
"Trigger: Target & Context",
40,
140,
description="接收地球交互物件或用户提问,装配基础上下文。",
),
_node(
"llm_analyze",
"llm_agent",
f"AI 分析:{label}",
f"Analyze: {label}",
420,
140,
description="结合绑定的工具数据与目标物件进行研判。",
system_prompt="你是智能星球 AI 参谋。结合当前选中交互物件、遥测工具证据与用户问题,给出客观、可验证的结构化分析。",
prompt="围绕 {{targets_summary}},结合问题「{{question}}」进行研判,明确给出证据来源与不确定边界。",
tools=["query_global_situational"],
thinking_enabled=True,
max_steps=2,
timeout_seconds=60,
),
_node(
"output_reply",
"output",
"流式输出与地球联动",
"Stream & Scene Output",
800,
140,
description="推送分析正文,并在存在明确坐标时联动地球镜头。",
params={"fly_to_target": True, "fly_zoom": 1.45},
),
],
"edges": [
_edge("e-start-1", "trigger_intake", "llm_analyze", "传入目标", "Target ready"),
_edge("e-start-2", "llm_analyze", "output_reply", "流式返回", "Stream output"),
],
}
async def create_workflow(
db: AsyncSession,
*,
workflow_id: str | None = None,
name: str,
name_en: str = "",
category: str = "custom",
description: str = "",
description_en: str = "",
graph: dict[str, Any] | None = None,
bindings: dict[str, Any] | None = None,
actor: str = "admin",
) -> dict[str, Any]:
"""Create a brand new custom workflow with initial published revision v1."""
await ensure_builtin_workflows(db)
clean_name = name.strip()
if not clean_name:
raise HTTPException(status_code=422, detail="Workflow name is required")
wf_id = str(workflow_id or "").strip() or f"custom.{uuid4().hex[:8]}"
if wf_id.startswith("meta."):
raise HTTPException(
status_code=400,
detail="Custom workflows cannot use the reserved 'meta.' namespace",
)
if not WORKFLOW_ID_RE.match(wf_id):
raise HTTPException(
status_code=422,
detail="workflow_id must start with a-z/0-9 and use only a-z, 0-9, '.', '-', '_'",
)
existing = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))
).scalar_one_or_none()
if existing is not None:
raise HTTPException(status_code=409, detail=f"Workflow '{wf_id}' already exists")
validated_graph = _validate_graph_payload(graph or build_starter_workflow_graph(clean_name))
normalized_bindings = normalize_bindings(bindings)
row = AIWorkflow(
workflow_id=wf_id,
name=clean_name[:160],
name_en=(name_en.strip() or clean_name)[:160],
category=(category.strip() or "custom")[:60],
description=description.strip(),
description_en=(description_en.strip() or description.strip()),
is_default=False,
is_builtin=False,
active_revision=1,
published_graph=validated_graph,
draft_graph=None,
bindings=normalized_bindings,
updated_by=actor,
)
db.add(row)
db.add(
AIWorkflowRevision(
workflow_id=wf_id,
revision=1,
status="published",
graph_json={**validated_graph, DRAFT_BINDINGS_KEY: dict(normalized_bindings)},
change_summary="Created custom workflow",
created_by=actor,
)
)
await db.commit()
await db.refresh(row)
return row.to_dict()
async def clone_workflow(
db: AsyncSession,
source_workflow_id: str,
*,
workflow_id: str | None = None,
name: str | None = None,
name_en: str | None = None,
actor: str = "admin",
) -> dict[str, Any]:
"""Clone an existing workflow into an editable custom workflow, stripping built-in prompt_keys."""
await ensure_builtin_workflows(db)
src = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == source_workflow_id))
).scalar_one_or_none()
if src is None:
raise HTTPException(status_code=404, detail=f"Workflow '{source_workflow_id}' not found")
cloned_graph = copy.deepcopy(src.draft_graph or src.published_graph or {})
for node in cloned_graph.get("nodes") or []:
if isinstance(node, dict):
node["prompt_key"] = None
cloned_bindings = normalize_bindings(copy.deepcopy(src.bindings or {}))
slug_base = re.sub(r"[^a-z0-9]+", "_", source_workflow_id.lower()).strip("_")[:32] or "wf"
target_id = str(workflow_id or "").strip() or f"custom.{slug_base}.{uuid4().hex[:6]}"
target_name = (name or "").strip() or f"{src.name} (副本)"
target_name_en = (name_en or "").strip() or f"{src.name_en or src.name} (Copy)"
return await create_workflow(
db,
workflow_id=target_id,
name=target_name,
name_en=target_name_en,
category="custom",
description=src.description or "",
description_en=src.description_en or "",
graph=cloned_graph,
bindings=cloned_bindings,
actor=actor,
)
async def update_workflow_metadata(
db: AsyncSession,
workflow_id: str,
*,
name: str | None = None,
name_en: str | None = None,
category: str | None = None,
description: str | None = None,
description_en: str | None = None,
bindings: dict[str, Any] | None = None,
actor: str = "admin",
) -> dict[str, Any]:
"""Update mutable workflow metadata and Earth bindings without disturbing node revisions."""
await ensure_builtin_workflows(db)
row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
if name is not None and name.strip():
row.name = name.strip()[:160]
if name_en is not None and name_en.strip():
row.name_en = name_en.strip()[:160]
if category is not None and category.strip():
row.category = category.strip()[:60]
if description is not None:
row.description = description.strip()
if description_en is not None:
row.description_en = description_en.strip()
if bindings is not None:
# Explicit "save bindings now" is a deliberate live change; keep any pending draft in sync
# so a later draft publish does not silently revert it.
row.bindings = normalize_bindings(bindings)
if isinstance(row.draft_graph, dict):
row.draft_graph = {**row.draft_graph, DRAFT_BINDINGS_KEY: dict(row.bindings)}
row.updated_by = actor
await db.commit()
await db.refresh(row)
return row.to_dict()
async def delete_workflow(db: AsyncSession, workflow_id: str) -> dict[str, Any]:
"""Delete a non-builtin custom workflow and its revisions/fixtures."""
await ensure_builtin_workflows(db)
row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
if bool(row.is_builtin) or bool(row.is_default):
raise HTTPException(
status_code=400,
detail="Built-in or default workflows cannot be deleted; clone it instead.",
)
await db.execute(delete(AIWorkflowFixture).where(AIWorkflowFixture.workflow_id == workflow_id))
await db.execute(delete(AIWorkflowRevision).where(AIWorkflowRevision.workflow_id == workflow_id))
await db.delete(row)
await db.commit()
return {"deleted": True, "workflow_id": workflow_id}
async def save_workflow_draft(
db: AsyncSession,
workflow_id: str,
graph: dict[str, Any],
*,
bindings: dict[str, Any] | None = None,
name: str | None = None,
description: str | None = None,
actor: str,
) -> dict[str, Any]:
await ensure_builtin_workflows(db)
row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
previous_draft_bindings = (
row.draft_graph.get(DRAFT_BINDINGS_KEY) if isinstance(row.draft_graph, dict) else None
)
staged = _validate_graph_payload(graph)
# Draft bindings stay inside the draft so the public Earth entry only changes on publish
# and is restored by discarding the draft.
if bindings is not None:
staged[DRAFT_BINDINGS_KEY] = normalize_bindings(bindings)
elif isinstance(previous_draft_bindings, dict):
staged[DRAFT_BINDINGS_KEY] = previous_draft_bindings
row.draft_graph = staged
if name is not None and name.strip():
row.name = name.strip()[:160]
if description is not None:
row.description = description.strip()
row.updated_by = actor
await db.commit()
await db.refresh(row)
return row.to_dict()
async def discard_workflow_draft(
db: AsyncSession,
workflow_id: str,
*,
actor: str = "admin",
) -> dict[str, Any]:
"""Discard pending draft changes and restore the active published workflow."""
await ensure_builtin_workflows(db)
row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
row.draft_graph = None
row.updated_by = actor
await db.commit()
await db.refresh(row)
return row.to_dict()
async def publish_workflow(
db: AsyncSession,
workflow_id: str,
*,
graph: dict[str, Any] | None = None,
bindings: dict[str, Any] | None = None,
name: str | None = None,
description: str | None = None,
change_summary: str = "",
actor: str = "admin",
keep_draft: bool = False,
) -> dict[str, Any]:
await ensure_builtin_workflows(db)
row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
target_graph = graph if graph is not None else (row.draft_graph or row.published_graph)
staged_bindings = target_graph.get(DRAFT_BINDINGS_KEY) if isinstance(target_graph, dict) else None
validated = _validate_graph_payload(target_graph)
next_rev = int(row.active_revision or 1) + 1
row.published_graph = validated
if not keep_draft:
row.draft_graph = None
row.active_revision = next_rev
if bindings is not None:
row.bindings = normalize_bindings(bindings)
elif isinstance(staged_bindings, dict):
row.bindings = normalize_bindings(staged_bindings)
if name is not None and name.strip():
row.name = name.strip()[:160]
if description is not None:
row.description = description.strip()
row.updated_by = actor
db.add(
AIWorkflowRevision(
workflow_id=workflow_id,
revision=next_rev,
status="published",
# Snapshot bindings with the graph so rollback restores the matching Earth entry.
graph_json={**validated, DRAFT_BINDINGS_KEY: dict(row.bindings or {})},
change_summary=change_summary.strip() or f"Published revision v{next_rev}",
created_by=actor,
)
)
await db.commit()
await db.refresh(row)
return row.to_dict()
async def rollback_workflow(
db: AsyncSession,
workflow_id: str,
target_revision: int,
*,
actor: str = "admin",
) -> dict[str, Any]:
await ensure_builtin_workflows(db)
rev = (
await db.execute(
select(AIWorkflowRevision)
.where(AIWorkflowRevision.workflow_id == workflow_id)
.where(AIWorkflowRevision.revision == int(target_revision))
)
).scalar_one_or_none()
if rev is None:
raise HTTPException(status_code=404, detail=f"Revision v{target_revision} not found")
return await publish_workflow(
db,
workflow_id,
graph=copy.deepcopy(rev.graph_json),
change_summary=f"Rollback to revision v{target_revision}",
actor=actor,
)
async def resolve_runtime_workflow_node(
db: AsyncSession | None,
workflow_id: str,
node_id: str,
*,
use_draft: bool = False,
) -> dict[str, Any] | None:
"""Resolve an active node configuration from DB published/draft graph with builtin fallback."""
graph: dict[str, Any] | None = None
if db is not None and hasattr(db, "execute"):
try:
exec_res = await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
row = exec_res.scalar_one_or_none()
if inspect.iscoroutine(row):
row.close()
row = None
if isinstance(row, AIWorkflow):
graph = (row.draft_graph if use_draft and row.draft_graph else row.published_graph) or None
except Exception:
graph = None
if graph is None:
fallback = _fallback_workflow_dict(workflow_id)
graph = fallback["published_graph"] if fallback else None
if not isinstance(graph, dict):
return None
for node in graph.get("nodes") or []:
if isinstance(node, dict) and node.get("id") == node_id:
return copy.deepcopy(node)
return None
async def resolve_prompt_override_from_workflows(
db: AsyncSession | None,
prompt_key: str,
) -> tuple[str, str] | None:
"""Return `(system_prompt, prompt)` from the first published workflow node matching `prompt_key`."""
if db is None or not hasattr(db, "execute"):
return None
try:
exec_res = await db.execute(select(AIWorkflow))
scalars_obj = exec_res.scalars()
if inspect.iscoroutine(scalars_obj):
scalars_obj.close()
return None
rows = scalars_obj.all()
if inspect.iscoroutine(rows):
rows.close()
return None
except Exception:
return None
for row in rows or []:
if not isinstance(row, AIWorkflow):
continue
graph = row.published_graph or {}
for node in graph.get("nodes") or []:
if isinstance(node, dict) and node.get("prompt_key") == prompt_key:
return str(node.get("system_prompt") or ""), str(node.get("prompt") or "")
return None
def _extract_first_json_object(raw: str) -> dict[str, Any] | None:
text = str(raw or "").strip()
if not text:
return None
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, flags=re.S)
if fenced:
text = fenced.group(1)
start = text.find("{")
end = text.rfind("}")
if start == -1 or end <= start:
return None
try:
parsed = json.loads(text[start : end + 1])
return parsed if isinstance(parsed, dict) else None
except json.JSONDecodeError:
return None
def _apply_validated_node_patches(
base_graph: dict[str, Any],
node_patches: list[dict[str, Any]],
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
proposed_graph = copy.deepcopy(base_graph)
nodes_by_id = {
str(n.get("id")): n
for n in (proposed_graph.get("nodes") or [])
if isinstance(n, dict) and n.get("id")
}
applied_diffs: list[dict[str, Any]] = []
for patch in node_patches:
if not isinstance(patch, dict):
continue
node_id = str(patch.get("node_id") or "").strip()
field = str(patch.get("field") or "").strip()
if node_id not in nodes_by_id or field not in ALLOWED_NODE_PATCH_FIELDS:
continue
node = nodes_by_id[node_id]
after = patch.get("after")
if field == "tools":
if not isinstance(after, list):
continue
after = [str(t).strip() for t in after if str(t).strip() in VALID_TOOL_IDS]
elif field == "max_steps":
after = max(1, min(int(after or 1), 8))
elif field == "timeout_seconds":
after = max(5, min(int(after or 60), 300))
elif field in {"enabled", "thinking_enabled", "native_web_search"}:
after = bool(after)
before = copy.deepcopy(node.get(field))
if before == after:
continue
node[field] = after
applied_diffs.append(
{
"node_id": node_id,
"node_title": node.get("title") or node_id,
"field": field,
"before": before,
"after": after,
"reason": str(patch.get("reason") or "AI optimization proposal"),
}
)
return proposed_graph, applied_diffs
async def generate_workflow_optimization_proposal(
db: AsyncSession,
workflow_id: str,
*,
instruction: str,
run_id: str | None = None,
ai_client: Any = None,
) -> dict[str, Any]:
"""Generate a strict-schema optimization Diff proposal without mutating live workflow state."""
await ensure_builtin_workflows(db)
row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
base_graph = copy.deepcopy(row.draft_graph or row.published_graph)
run_context: dict[str, Any] | None = None
if run_id:
run_row = (
await db.execute(select(WorkflowRun).where(WorkflowRun.id == run_id))
).scalar_one_or_none()
if run_row is not None:
run_context = run_row.to_dict()
ai_ready = False
if ai_client is not None and hasattr(ai_client, "is_ready"):
try:
ai_ready, _, _ = await ai_client.is_ready()
except Exception:
ai_ready = False
summary = ""
raw_patches: list[dict[str, Any]] = []
if ai_ready and ai_client is not None:
schema = {
"type": "object",
"properties": {
"summary": {"type": "string"},
"node_patches": {
"type": "array",
"items": {
"type": "object",
"properties": {
"node_id": {"type": "string"},
"field": {"type": "string", "enum": sorted(ALLOWED_NODE_PATCH_FIELDS)},
"after": {},
"reason": {"type": "string"},
},
"required": ["node_id", "field", "after", "reason"],
},
},
},
"required": ["summary", "node_patches"],
}
req = SituationalAnalysisRequest(
title=f"Optimize workflow {workflow_id}",
objective=(
f"用户调优目标:{instruction}\n"
"请分析当前工作流节点图、工具目录与可选失败运行轨迹,仅针对确实需要改进的节点提出白名单字段修改。"
"严禁输出无效 tool id,严禁直接返回伪造数据。"
),
system_prompt=(
"你是智能星球 AI 工作流架构调优助手。仅输出严格 JSON:"
"{summary: string, node_patches: [{node_id, field, after, reason}]}。"
),
context={
"workflow_id": workflow_id,
"current_graph": base_graph,
"available_tools": [{"id": t["id"], "description": t["description"]} for t in TOOL_CATALOG],
"failed_or_selected_run": run_context,
},
response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}},
)
try:
resp = await ai_client.analyze(req)
clean_text, _ = strip_thinking_text(str(getattr(resp, "content", "") or ""))
parsed = _extract_first_json_object(clean_text or getattr(resp, "content", ""))
if parsed:
summary = str(parsed.get("summary") or "").strip()
if isinstance(parsed.get("node_patches"), list):
raw_patches = parsed["node_patches"]
except Exception as exc:
logger.warning_event(
"AI workflow optimization request failed; falling back to deterministic advice",
event="ai_workflow.optimize.fallback",
context={"workflow_id": workflow_id, "error": str(exc)},
)
if not raw_patches:
# Deterministic fallback proposal targeting common tuning requests safely.
inst_lower = instruction.lower()
llm_node = next(
(n for n in (base_graph.get("nodes") or []) if n.get("node_type") == "llm_agent"),
None,
)
if llm_node:
if any(kw in inst_lower for kw in ("search", "搜索", "取证", "证据", "fetch", "抓取")):
cur_tools = list(llm_node.get("tools") or [])
added = [t for t in ("fetch_source_url", "web_search") if t in VALID_TOOL_IDS and t not in cur_tools]
if added:
raw_patches.append(
{
"node_id": llm_node["id"],
"field": "tools",
"after": [*cur_tools, *added],
"reason": "补充一手网页抓取与 WebSearch 工具以提升事实查证能力。",
}
)
if any(kw in inst_lower for kw in ("step", "步", "深入", "多轮")):
raw_patches.append(
{
"node_id": llm_node["id"],
"field": "max_steps",
"after": min(6, int(llm_node.get("max_steps") or 2) + 1),
"reason": "适当放宽最大 Tool-Calling 步数以便多轮改写查询。",
}
)
if not raw_patches:
base_sys = str(llm_node.get("system_prompt") or "").strip()
suffix = f"\n[调优约束] {instruction.strip()}"
if instruction.strip() and instruction.strip() not in base_sys:
raw_patches.append(
{
"node_id": llm_node["id"],
"field": "system_prompt",
"after": f"{base_sys}{suffix}".strip(),
"reason": "将用户调优要求显式固化到节点系统提示词。",
}
)
summary = summary or f"已针对「{instruction}」生成节点建议修改,请在右侧核对 Diff 后决定是否应用。"
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
return {
"workflow_id": workflow_id,
"base_revision": int(row.active_revision or 1),
"summary": summary or "暂无需要变更的字段。",
"changes": diffs,
"proposed_graph": proposed_graph,
}