2180 lines
85 KiB
Python
2180 lines
85 KiB
Python
"""Lightweight, extensible 3-tier AI workflow self-evolution & meta-evolution engine.
|
||
|
||
Tier 0 (Immutable Constitution Kernel in Python):
|
||
Enforces blast-radius limits, allowlisted tools, acyclic DAG integrity,
|
||
frozen meta-guardrail nodes, single-level meta recursion lock, cooldown & daily
|
||
auto-evolution budgets, and automatic canary rollback on regression.
|
||
Tier 1 (Business Workflow Optimization & Model Adaptation):
|
||
0-token health/drift diagnostics, 👍/👎 feedback telemetry inside `WorkflowRun.budget_used`,
|
||
GEPA minimal-patch synthesis, DGM archive parent selection, AFlow positive/negative lessons,
|
||
optional Fixture A/B comparison, and workflow incubation from frequent `default.general` usage.
|
||
Tier 2 (Meta-Evolution):
|
||
Bootstraps `meta.workflow_evolver` (diag_node / patch_node) from objective ledger outcomes
|
||
under stricter cooldowns, constitution double-checks, and automatic meta-canary rollback.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
from collections import Counter
|
||
import copy
|
||
from dataclasses import dataclass, field
|
||
from datetime import UTC, datetime, timedelta
|
||
import os
|
||
from typing import Any, Protocol
|
||
from uuid import uuid4
|
||
|
||
from fastapi import HTTPException
|
||
from sqlalchemy import desc, select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from app.core.logging import get_logger
|
||
from app.db.session import async_session_factory
|
||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
|
||
from app.models.situational_assessment import WorkflowRun
|
||
from app.models.system_setting import SystemSetting
|
||
from app.schemas.ai import SituationalAnalysisRequest
|
||
from app.services.ai.dag_executor import run_workflow_dag_stream
|
||
from app.services.ai.thinking_sanitizer import strip_thinking_text
|
||
from app.services.ai.workflow_registry import (
|
||
ALLOWED_NODE_PATCH_FIELDS,
|
||
TOOL_CATALOG,
|
||
VALID_TOOL_IDS,
|
||
_apply_validated_node_patches,
|
||
_extract_first_json_object,
|
||
_validate_graph_payload,
|
||
build_starter_workflow_graph,
|
||
ensure_builtin_workflows,
|
||
publish_workflow,
|
||
resolve_runtime_workflow_node,
|
||
rollback_workflow,
|
||
save_workflow_draft,
|
||
)
|
||
from app.services.ai_client import get_ai_provider_client
|
||
|
||
logger = get_logger(__name__, service="ai_evolver")
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Tier 0: Immutable Constitution Constants (never AI-editable)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
META_WORKFLOW_ID = "meta.workflow_evolver"
|
||
FROZEN_META_NODE_IDS: frozenset[str] = frozenset({"verify_output"})
|
||
POLICY_SETTING_CATEGORY = "ai_evolution_policy"
|
||
LEDGER_SETTING_CATEGORY = "ai_evolution_ledger"
|
||
|
||
VALID_EVOLUTION_MODES: frozenset[str] = frozenset({"off", "draft", "auto"})
|
||
MAX_LEDGER_ENTRIES = 50
|
||
CANARY_OBSERVATION_RUNS = 5
|
||
CANARY_CONSECUTIVE_FAILURES = 2
|
||
CANARY_BAD_RATE_THRESHOLD = 0.40
|
||
META_CANARY_WINDOW = 3
|
||
META_CANARY_FAILURE_ROLLBACK = 2
|
||
MIN_RUNS_FOR_AUTO = 5
|
||
MIN_LEDGER_OUTCOMES_FOR_META = 5
|
||
DEFAULT_DAILY_AUTO_BUDGET = 3
|
||
MAX_AUTO_NODES_CHANGED = 2
|
||
MAX_AUTO_NODE_RATIO = 0.40
|
||
|
||
DEFAULT_POLICY: dict[str, Any] = {
|
||
"business_mode": "draft",
|
||
"meta_mode": "off",
|
||
"daily_auto_budget": DEFAULT_DAILY_AUTO_BUDGET,
|
||
"business_cooldown_hours": 24,
|
||
"meta_cooldown_days": 7,
|
||
"locked_workflows": [],
|
||
"auto_adapt_on_model_change": True,
|
||
}
|
||
|
||
# Keep track of active background tasks per workflow to avoid duplicate concurrent runs.
|
||
_PENDING_BG_WORKFLOWS: set[str] = set()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Extensibility Protocols & Plug-In Registries
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class EvolutionSignal:
|
||
code: str
|
||
severity: str # "info" | "warn" | "critical"
|
||
message: str
|
||
suggested_mode: str = "optimize" # "optimize" | "model_adapt" | "incubate"
|
||
metadata: dict[str, Any] = field(default_factory=dict)
|
||
|
||
def to_dict(self) -> dict[str, Any]:
|
||
return {
|
||
"code": self.code,
|
||
"severity": self.severity,
|
||
"message": self.message,
|
||
"suggested_mode": self.suggested_mode,
|
||
"metadata": dict(self.metadata),
|
||
}
|
||
|
||
|
||
class EvolutionSignalDetector(Protocol):
|
||
detector_id: str
|
||
|
||
def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]:
|
||
...
|
||
|
||
|
||
class EvolutionEvaluator(Protocol):
|
||
evaluator_id: str
|
||
|
||
async def evaluate(
|
||
self,
|
||
db: AsyncSession,
|
||
workflow: dict[str, Any],
|
||
base_graph: dict[str, Any],
|
||
proposed_graph: dict[str, Any],
|
||
*,
|
||
max_fixtures: int = 3,
|
||
) -> dict[str, Any]:
|
||
...
|
||
|
||
|
||
class FailureRateSignalDetector:
|
||
detector_id = "failure_rate"
|
||
|
||
def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]:
|
||
total = int(health_snapshot.get("total_runs") or 0)
|
||
failure_rate = float(health_snapshot.get("failure_rate") or 0.0)
|
||
failed = int(health_snapshot.get("failed_runs") or 0)
|
||
if total >= 3 and failure_rate >= 0.25:
|
||
return [
|
||
EvolutionSignal(
|
||
code="high_failure_rate",
|
||
severity="critical" if failure_rate >= 0.4 else "warn",
|
||
message=f"近 {total} 次运行中有 {failed} 次失败(失败率 {round(failure_rate * 100)}%),建议调优工具或提示词。",
|
||
suggested_mode="optimize",
|
||
metadata={"failed_runs": failed, "total_runs": total, "failure_rate": failure_rate},
|
||
)
|
||
]
|
||
return []
|
||
|
||
|
||
class NegativeFeedbackSignalDetector:
|
||
detector_id = "negative_feedback"
|
||
|
||
def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]:
|
||
downvotes = int(health_snapshot.get("downvotes") or 0)
|
||
rated = int(health_snapshot.get("rated_runs") or 0)
|
||
neg_rate = float(health_snapshot.get("negative_rate") or 0.0)
|
||
if downvotes >= 2 or (rated >= 3 and neg_rate >= 0.30):
|
||
return [
|
||
EvolutionSignal(
|
||
code="negative_feedback_spike",
|
||
severity="warn",
|
||
message=f"收到 {downvotes} 次差评(占已评价 {round(neg_rate * 100)}%),可针对差评样本微调工作流。",
|
||
suggested_mode="optimize",
|
||
metadata={"downvotes": downvotes, "rated_runs": rated, "negative_rate": neg_rate},
|
||
)
|
||
]
|
||
return []
|
||
|
||
|
||
class ModelDriftSignalDetector:
|
||
detector_id = "model_drift"
|
||
|
||
def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]:
|
||
if health_snapshot.get("model_drift_detected"):
|
||
active_model = str((health_snapshot.get("active_model_profile") or {}).get("model") or "")
|
||
recent_models = health_snapshot.get("recent_models") or []
|
||
return [
|
||
EvolutionSignal(
|
||
code="model_capability_drift",
|
||
severity="warn",
|
||
message=(
|
||
f"当前活跃模型({active_model or '已切换'})与近期运行模型({', '.join(recent_models[:2])})不一致,"
|
||
"建议执行一次模型能力自适应。"
|
||
),
|
||
suggested_mode="model_adapt",
|
||
metadata={"active_model": active_model, "recent_models": recent_models},
|
||
)
|
||
]
|
||
return []
|
||
|
||
|
||
class UnusedToolSignalDetector:
|
||
detector_id = "unused_tools"
|
||
|
||
def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]:
|
||
unused = list(health_snapshot.get("unused_tools") or [])
|
||
total = int(health_snapshot.get("total_runs") or 0)
|
||
if unused and total >= 5:
|
||
return [
|
||
EvolutionSignal(
|
||
code="unused_tools_detected",
|
||
severity="info",
|
||
message=f"以下已绑定工具在近期 {total} 次运行中均未实际触发:{', '.join(unused[:4])}。",
|
||
suggested_mode="optimize",
|
||
metadata={"unused_tools": unused},
|
||
)
|
||
]
|
||
return []
|
||
|
||
|
||
class FixtureABEvaluator:
|
||
evaluator_id = "fixture_ab"
|
||
|
||
async def evaluate(
|
||
self,
|
||
db: AsyncSession,
|
||
workflow: dict[str, Any],
|
||
base_graph: dict[str, Any],
|
||
proposed_graph: dict[str, Any],
|
||
*,
|
||
max_fixtures: int = 3,
|
||
) -> dict[str, Any]:
|
||
wf_id = str(workflow.get("workflow_id") or "")
|
||
rows = (
|
||
await db.execute(
|
||
select(AIWorkflowFixture)
|
||
.where(AIWorkflowFixture.workflow_id == wf_id)
|
||
.order_by(desc(AIWorkflowFixture.id))
|
||
.limit(max(1, min(int(max_fixtures or 3), 5)))
|
||
)
|
||
).scalars().all()
|
||
if not rows:
|
||
return {
|
||
"evaluator_id": self.evaluator_id,
|
||
"fixture_count": 0,
|
||
"verdict": "no_fixtures",
|
||
"summary": "当前工作流尚未保存测试样本(Fixtures),请在 Playground 挂载上下文后点击「存为样本」。",
|
||
"comparisons": [],
|
||
}
|
||
|
||
ai_client = None
|
||
try:
|
||
ai_client = await get_ai_provider_client(db)
|
||
except Exception:
|
||
ai_client = None
|
||
|
||
comparisons: list[dict[str, Any]] = []
|
||
base_ok = 0
|
||
prop_ok = 0
|
||
for row in rows:
|
||
question = str(row.sample_question or "").strip() or f"请分析 {row.name}"
|
||
ctx = dict(row.context_json or {})
|
||
base_res = await _run_graph_single_sample(
|
||
db=db,
|
||
workflow=workflow,
|
||
graph=base_graph,
|
||
question=question,
|
||
earth_context=ctx,
|
||
ai_client=ai_client,
|
||
)
|
||
prop_res = await _run_graph_single_sample(
|
||
db=db,
|
||
workflow=workflow,
|
||
graph=proposed_graph,
|
||
question=question,
|
||
earth_context=ctx,
|
||
ai_client=ai_client,
|
||
)
|
||
if base_res["ok"]:
|
||
base_ok += 1
|
||
if prop_res["ok"]:
|
||
prop_ok += 1
|
||
comparisons.append(
|
||
{
|
||
"fixture_id": row.id,
|
||
"fixture_name": row.name,
|
||
"question": question[:160],
|
||
"base": base_res,
|
||
"proposed": prop_res,
|
||
}
|
||
)
|
||
|
||
if prop_ok > base_ok:
|
||
verdict = "improved"
|
||
elif prop_ok < base_ok:
|
||
verdict = "regressed"
|
||
else:
|
||
avg_base_ms = sum(c["base"]["latency_ms"] for c in comparisons) / len(comparisons)
|
||
avg_prop_ms = sum(c["proposed"]["latency_ms"] for c in comparisons) / len(comparisons)
|
||
if avg_prop_ms > avg_base_ms * 1.35 and avg_prop_ms - avg_base_ms > 1500:
|
||
verdict = "slower"
|
||
else:
|
||
verdict = "neutral"
|
||
|
||
return {
|
||
"evaluator_id": self.evaluator_id,
|
||
"fixture_count": len(comparisons),
|
||
"base_passed": base_ok,
|
||
"proposed_passed": prop_ok,
|
||
"verdict": verdict,
|
||
"summary": f"已对照 {len(comparisons)} 组样本:原版通过 {base_ok}/{len(comparisons)},新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict})。",
|
||
"comparisons": comparisons,
|
||
}
|
||
|
||
|
||
SIGNAL_DETECTORS: list[EvolutionSignalDetector] = [
|
||
FailureRateSignalDetector(),
|
||
NegativeFeedbackSignalDetector(),
|
||
ModelDriftSignalDetector(),
|
||
UnusedToolSignalDetector(),
|
||
]
|
||
|
||
EVALUATORS: dict[str, EvolutionEvaluator] = {
|
||
"fixture_ab": FixtureABEvaluator(),
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Helpers & Direct SystemSetting JSON Storage
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _utc_now() -> datetime:
|
||
return datetime.now(UTC)
|
||
|
||
|
||
def _ensure_utc(dt: datetime | None) -> datetime | None:
|
||
if dt is None:
|
||
return None
|
||
if dt.tzinfo is None:
|
||
return dt.replace(tzinfo=UTC)
|
||
return dt.astimezone(UTC)
|
||
|
||
|
||
def _parse_iso(raw: Any) -> datetime | None:
|
||
if not raw:
|
||
return None
|
||
try:
|
||
parsed = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
|
||
return _ensure_utc(parsed)
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
async def _read_setting_json(db: AsyncSession, category: str) -> dict[str, Any] | None:
|
||
if not hasattr(db, "execute"):
|
||
return None
|
||
stmt = select(SystemSetting).where(SystemSetting.category == category)
|
||
if hasattr(stmt, "execution_options"):
|
||
stmt = stmt.execution_options(populate_existing=True)
|
||
record = (await db.execute(stmt)).scalar_one_or_none()
|
||
if record is None or not isinstance(record.payload, dict):
|
||
return None
|
||
return copy.deepcopy(record.payload)
|
||
|
||
|
||
async def _write_setting_json(
|
||
db: AsyncSession,
|
||
category: str,
|
||
payload: dict[str, Any],
|
||
) -> dict[str, Any]:
|
||
stmt = select(SystemSetting).where(SystemSetting.category == category)
|
||
if hasattr(stmt, "execution_options"):
|
||
stmt = stmt.execution_options(populate_existing=True)
|
||
record = (await db.execute(stmt)).scalar_one_or_none()
|
||
clean_payload = copy.deepcopy(payload)
|
||
if record is None:
|
||
record = SystemSetting(category=category, payload=clean_payload)
|
||
db.add(record)
|
||
else:
|
||
record.payload = clean_payload
|
||
await db.commit()
|
||
await db.refresh(record)
|
||
return copy.deepcopy(record.payload)
|
||
|
||
|
||
def _normalize_policy(raw: dict[str, Any] | None) -> dict[str, Any]:
|
||
merged = copy.deepcopy(DEFAULT_POLICY)
|
||
if isinstance(raw, dict):
|
||
for k, v in raw.items():
|
||
if k in merged:
|
||
merged[k] = copy.deepcopy(v)
|
||
if merged["business_mode"] not in VALID_EVOLUTION_MODES:
|
||
merged["business_mode"] = DEFAULT_POLICY["business_mode"]
|
||
if merged["meta_mode"] not in VALID_EVOLUTION_MODES:
|
||
merged["meta_mode"] = DEFAULT_POLICY["meta_mode"]
|
||
try:
|
||
merged["daily_auto_budget"] = max(1, min(int(merged["daily_auto_budget"]), 20))
|
||
except (TypeError, ValueError):
|
||
merged["daily_auto_budget"] = DEFAULT_DAILY_AUTO_BUDGET
|
||
try:
|
||
merged["business_cooldown_hours"] = max(1, min(int(merged["business_cooldown_hours"]), 168))
|
||
except (TypeError, ValueError):
|
||
merged["business_cooldown_hours"] = 24
|
||
try:
|
||
merged["meta_cooldown_days"] = max(1, min(int(merged["meta_cooldown_days"]), 30))
|
||
except (TypeError, ValueError):
|
||
merged["meta_cooldown_days"] = 7
|
||
raw_locked = merged.get("locked_workflows")
|
||
merged["locked_workflows"] = sorted(
|
||
{str(w).strip() for w in (raw_locked if isinstance(raw_locked, list) else []) if str(w).strip()}
|
||
)
|
||
merged["auto_adapt_on_model_change"] = bool(merged.get("auto_adapt_on_model_change", True))
|
||
return merged
|
||
|
||
|
||
async def get_evolution_policy(db: AsyncSession) -> dict[str, Any]:
|
||
raw = await _read_setting_json(db, POLICY_SETTING_CATEGORY)
|
||
return _normalize_policy(raw)
|
||
|
||
|
||
async def update_evolution_policy(db: AsyncSession, updates: dict[str, Any]) -> dict[str, Any]:
|
||
current = await get_evolution_policy(db)
|
||
for key in DEFAULT_POLICY:
|
||
if key in updates and updates[key] is not None:
|
||
current[key] = updates[key]
|
||
normalized = _normalize_policy(current)
|
||
normalized["updated_at"] = _utc_now().isoformat()
|
||
await _write_setting_json(db, POLICY_SETTING_CATEGORY, normalized)
|
||
return _normalize_policy(normalized)
|
||
|
||
|
||
async def _load_ledger_entries(db: AsyncSession) -> list[dict[str, Any]]:
|
||
raw = await _read_setting_json(db, LEDGER_SETTING_CATEGORY)
|
||
entries = raw.get("entries") if isinstance(raw, dict) else None
|
||
if not isinstance(entries, list):
|
||
return []
|
||
return [dict(item) for item in entries if isinstance(item, dict)]
|
||
|
||
|
||
async def get_evolution_ledger(
|
||
db: AsyncSession,
|
||
*,
|
||
workflow_id: str | None = None,
|
||
limit: int = 30,
|
||
) -> list[dict[str, Any]]:
|
||
entries = await _load_ledger_entries(db)
|
||
if workflow_id:
|
||
entries = [e for e in entries if str(e.get("workflow_id") or "") == workflow_id]
|
||
return entries[: max(1, min(int(limit or 30), MAX_LEDGER_ENTRIES))]
|
||
|
||
|
||
async def append_ledger_entry(db: AsyncSession, entry: dict[str, Any]) -> dict[str, Any]:
|
||
entries = await _load_ledger_entries(db)
|
||
clean = dict(entry)
|
||
clean.setdefault("id", f"evo_{uuid4().hex[:12]}")
|
||
clean.setdefault("created_at", _utc_now().isoformat())
|
||
next_entries = [clean, *entries][:MAX_LEDGER_ENTRIES]
|
||
await _write_setting_json(db, LEDGER_SETTING_CATEGORY, {"entries": next_entries})
|
||
return clean
|
||
|
||
|
||
async def update_ledger_entry(
|
||
db: AsyncSession,
|
||
entry_id: str,
|
||
updates: dict[str, Any],
|
||
) -> dict[str, Any] | None:
|
||
entries = await _load_ledger_entries(db)
|
||
updated: dict[str, Any] | None = None
|
||
next_entries: list[dict[str, Any]] = []
|
||
for item in entries:
|
||
if str(item.get("id") or "") == entry_id:
|
||
merged = {**item, **updates, "updated_at": _utc_now().isoformat()}
|
||
updated = merged
|
||
next_entries.append(merged)
|
||
else:
|
||
next_entries.append(item)
|
||
if updated is not None:
|
||
await _write_setting_json(db, LEDGER_SETTING_CATEGORY, {"entries": next_entries})
|
||
return updated
|
||
|
||
|
||
async def dismiss_ledger_entry(
|
||
db: AsyncSession,
|
||
entry_id: str,
|
||
*,
|
||
reason: str = "",
|
||
) -> dict[str, Any]:
|
||
updated = await update_ledger_entry(
|
||
db,
|
||
entry_id,
|
||
{
|
||
"status": "dismissed",
|
||
"dismiss_reason": reason.strip()[:300] or "Dismissed by admin",
|
||
},
|
||
)
|
||
if updated is None:
|
||
raise HTTPException(status_code=404, detail=f"Evolution ledger entry '{entry_id}' not found")
|
||
return updated
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Active Model Capability Profiler (0-Token)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def infer_model_capabilities(provider: str, model: str) -> dict[str, Any]:
|
||
p = str(provider or "").strip().lower()
|
||
m = str(model or "").strip().lower()
|
||
is_reasoning = any(tok in m for tok in ("r1", "reasoner", "o1", "o3", "o4", "thinking", "pro", "opus", "sonnet"))
|
||
is_fast = any(tok in m for tok in ("flash", "mini", "haiku", "nano", "lite", "fast", "turbo"))
|
||
if is_fast and not is_reasoning:
|
||
tier = "fast"
|
||
elif is_reasoning:
|
||
tier = "reasoning"
|
||
else:
|
||
tier = "standard"
|
||
|
||
supports_thinking = is_reasoning or any(tok in m for tok in ("2.5", "gemini-3", "deepseek", "qwen3", "minimax"))
|
||
supports_native_search = any(tok in p for tok in ("gemini", "perplexity", "xai", "grok", "openai")) or any(
|
||
tok in m for tok in ("gemini", "sonar", "grok")
|
||
)
|
||
supports_vision = any(tok in m for tok in ("vision", "vl", "gemini", "gpt-4o", "gpt-4.1", "claude", "sonnet", "opus", "haiku"))
|
||
return {
|
||
"provider": p or "unconfigured",
|
||
"model": str(model or "").strip(),
|
||
"tier": tier,
|
||
"supports_thinking": supports_thinking,
|
||
"supports_native_search": supports_native_search,
|
||
"supports_vision": supports_vision,
|
||
}
|
||
|
||
|
||
async def get_active_model_profile(db: AsyncSession, ai_client: Any = None) -> dict[str, Any]:
|
||
client = ai_client
|
||
if client is None:
|
||
try:
|
||
client = await get_ai_provider_client(db)
|
||
except Exception:
|
||
client = None
|
||
ready = False
|
||
provider = ""
|
||
model = ""
|
||
if client is not None and hasattr(client, "is_ready"):
|
||
try:
|
||
ready, provider, model = await client.is_ready()
|
||
except Exception:
|
||
ready = False
|
||
profile = infer_model_capabilities(provider, model)
|
||
profile["ready"] = bool(ready)
|
||
return profile
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Run Telemetry & Feedback
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _run_model(row: WorkflowRun) -> str:
|
||
bu = row.budget_used if isinstance(row.budget_used, dict) else {}
|
||
inp = row.input_params if isinstance(row.input_params, dict) else {}
|
||
return str(bu.get("model_used") or inp.get("model_override") or "").strip()
|
||
|
||
|
||
def _run_rating(row: WorkflowRun) -> int:
|
||
bu = row.budget_used if isinstance(row.budget_used, dict) else {}
|
||
try:
|
||
val = int(bu.get("user_rating") or 0)
|
||
return val if val in (-1, 0, 1) else 0
|
||
except (TypeError, ValueError):
|
||
return 0
|
||
|
||
|
||
def _run_latency_ms(row: WorkflowRun) -> int | None:
|
||
bu = row.budget_used if isinstance(row.budget_used, dict) else {}
|
||
raw = bu.get("latency_ms")
|
||
if isinstance(raw, (int, float)) and raw >= 0:
|
||
return int(raw)
|
||
started = _ensure_utc(row.started_at)
|
||
completed = _ensure_utc(row.completed_at)
|
||
if started and completed:
|
||
return max(0, int((completed - started).total_seconds() * 1000))
|
||
return None
|
||
|
||
|
||
def _run_revision(row: WorkflowRun) -> int | None:
|
||
bu = row.budget_used if isinstance(row.budget_used, dict) else {}
|
||
raw = bu.get("workflow_revision")
|
||
if isinstance(raw, int) and raw >= 1:
|
||
return raw
|
||
return None
|
||
|
||
|
||
async def record_run_feedback(
|
||
db: AsyncSession,
|
||
run_id: str,
|
||
*,
|
||
rating: int,
|
||
note: str = "",
|
||
actor: str = "admin",
|
||
) -> dict[str, Any]:
|
||
if rating not in (-1, 0, 1):
|
||
raise HTTPException(status_code=422, detail="rating must be -1, 0, or 1")
|
||
row = (await db.execute(select(WorkflowRun).where(WorkflowRun.id == run_id))).scalar_one_or_none()
|
||
if row is None:
|
||
raise HTTPException(status_code=404, detail=f"Workflow run '{run_id}' not found")
|
||
|
||
prev_budget = dict(row.budget_used) if isinstance(row.budget_used, dict) else {}
|
||
prev_budget["user_rating"] = int(rating)
|
||
if note.strip() or rating == 0:
|
||
prev_budget["feedback_note"] = note.strip()[:500] if rating != 0 else ""
|
||
prev_budget["feedback_at"] = _utc_now().isoformat()
|
||
prev_budget["feedback_by"] = actor
|
||
row.budget_used = prev_budget
|
||
await db.commit()
|
||
await db.refresh(row)
|
||
|
||
canary_result = None
|
||
if rating == -1:
|
||
canary_result = await evaluate_canary_and_maybe_rollback(db, row.workflow_id)
|
||
|
||
payload = row.to_dict()
|
||
if canary_result is not None:
|
||
payload["canary_evaluation"] = canary_result
|
||
return payload
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 0-Token Workflow Health Diagnostics & DGM Archive Selection
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
async def compute_workflow_health(
|
||
db: AsyncSession,
|
||
workflow_id: str,
|
||
*,
|
||
ai_client: Any = None,
|
||
) -> dict[str, Any]:
|
||
await ensure_builtin_workflows(db)
|
||
wf = (
|
||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
|
||
).scalar_one_or_none()
|
||
if wf is None:
|
||
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
|
||
|
||
cutoff = _utc_now() - timedelta(days=30)
|
||
runs = (
|
||
await db.execute(
|
||
select(WorkflowRun)
|
||
.where(WorkflowRun.workflow_id == workflow_id)
|
||
.order_by(desc(WorkflowRun.started_at))
|
||
.limit(200)
|
||
)
|
||
).scalars().all()
|
||
recent_runs = [
|
||
r for r in runs if (_ensure_utc(r.started_at) or _utc_now()) >= cutoff
|
||
]
|
||
|
||
total = len(recent_runs)
|
||
completed = sum(1 for r in recent_runs if r.status == "completed")
|
||
failed = sum(1 for r in recent_runs if r.status == "failed")
|
||
latencies = [ms for ms in (_run_latency_ms(r) for r in recent_runs) if ms is not None]
|
||
avg_latency_ms = int(sum(latencies) / len(latencies)) if latencies else 0
|
||
|
||
upvotes = sum(1 for r in recent_runs if _run_rating(r) == 1)
|
||
downvotes = sum(1 for r in recent_runs if _run_rating(r) == -1)
|
||
rated_runs = upvotes + downvotes
|
||
success_rate = round(completed / total, 4) if total else 1.0
|
||
failure_rate = round(failed / total, 4) if total else 0.0
|
||
negative_rate = round(downvotes / rated_runs, 4) if rated_runs else 0.0
|
||
|
||
# Tool usage tracking from trace entries (`node_id:tool_id` or `tool_id`)
|
||
observed_tools: set[str] = set()
|
||
for r in recent_runs:
|
||
for step in r.tool_trace or []:
|
||
s = str(step or "")
|
||
if ":" in s:
|
||
observed_tools.add(s.split(":", 1)[1])
|
||
elif s in VALID_TOOL_IDS:
|
||
observed_tools.add(s)
|
||
|
||
configured_tools: set[str] = set()
|
||
active_graph = wf.draft_graph or wf.published_graph or {}
|
||
for node in active_graph.get("nodes") or []:
|
||
if isinstance(node, dict) and node.get("enabled", True):
|
||
for tid in node.get("tools") or []:
|
||
if str(tid) in VALID_TOOL_IDS:
|
||
configured_tools.add(str(tid))
|
||
unused_tools = sorted(configured_tools - observed_tools) if total >= 5 else []
|
||
|
||
recent_models: list[str] = []
|
||
for r in recent_runs[:20]:
|
||
m = _run_model(r)
|
||
if m and m not in recent_models:
|
||
recent_models.append(m)
|
||
|
||
model_profile = await get_active_model_profile(db, ai_client=ai_client)
|
||
active_model = str(model_profile.get("model") or "").strip()
|
||
model_drift = bool(
|
||
model_profile.get("ready")
|
||
and active_model
|
||
and recent_models
|
||
and active_model not in recent_models[:3]
|
||
)
|
||
|
||
# DGM Revision Archive scoring
|
||
revisions = (
|
||
await db.execute(
|
||
select(AIWorkflowRevision)
|
||
.where(AIWorkflowRevision.workflow_id == workflow_id)
|
||
.order_by(desc(AIWorkflowRevision.revision))
|
||
.limit(20)
|
||
)
|
||
).scalars().all()
|
||
ledger = await get_evolution_ledger(db, workflow_id=workflow_id, limit=50)
|
||
rolled_back_revs = {
|
||
int(e["target_revision"])
|
||
for e in ledger
|
||
if e.get("status") == "rolled_back" and isinstance(e.get("target_revision"), int)
|
||
}
|
||
|
||
runs_by_rev: dict[int, list[WorkflowRun]] = {}
|
||
for r in recent_runs:
|
||
rev_num = _run_revision(r)
|
||
if rev_num is not None:
|
||
runs_by_rev.setdefault(rev_num, []).append(r)
|
||
|
||
archive_scores: list[dict[str, Any]] = []
|
||
for rev in revisions:
|
||
rev_runs = runs_by_rev.get(int(rev.revision), [])
|
||
r_total = len(rev_runs)
|
||
r_comp = sum(1 for r in rev_runs if r.status == "completed")
|
||
r_up = sum(1 for r in rev_runs if _run_rating(r) == 1)
|
||
r_down = sum(1 for r in rev_runs if _run_rating(r) == -1)
|
||
r_rated = r_up + r_down
|
||
r_succ = (r_comp / r_total) if r_total else 0.0
|
||
r_neg = (r_down / r_rated) if r_rated else 0.0
|
||
score = round(r_succ - 0.35 * r_neg, 4) if r_total >= 1 else None
|
||
archive_scores.append(
|
||
{
|
||
"revision": int(rev.revision),
|
||
"runs": r_total,
|
||
"success_rate": round(r_succ, 4) if r_total else None,
|
||
"downvotes": r_down,
|
||
"score": score,
|
||
"rolled_back": int(rev.revision) in rolled_back_revs,
|
||
"created_by": rev.created_by,
|
||
}
|
||
)
|
||
|
||
active_rev = int(wf.active_revision or 1)
|
||
active_entry = next((a for a in archive_scores if a["revision"] == active_rev), None)
|
||
best_parent = None
|
||
candidates = [
|
||
a for a in archive_scores
|
||
if not a["rolled_back"] and a["runs"] >= 3 and a["score"] is not None
|
||
]
|
||
if candidates:
|
||
best_cand = max(candidates, key=lambda x: (float(x["score"] or 0.0), -int(x["revision"])))
|
||
if (
|
||
best_cand["revision"] != active_rev
|
||
and active_entry is not None
|
||
and active_entry["runs"] >= 3
|
||
and active_entry["score"] is not None
|
||
and float(best_cand["score"]) - float(active_entry["score"]) >= 0.15
|
||
):
|
||
best_parent = best_cand["revision"]
|
||
|
||
policy = await get_evolution_policy(db)
|
||
is_locked = workflow_id in set(policy.get("locked_workflows") or [])
|
||
active_canary = next((e for e in ledger if e.get("status") == "canary"), None)
|
||
if active_canary is not None:
|
||
observed = _count_canary_observations(recent_runs, active_canary)
|
||
active_canary = {
|
||
**active_canary,
|
||
"observed_runs": observed["observed"],
|
||
"failed_runs": observed["failed"],
|
||
"downvoted_runs": observed["downvoted"],
|
||
}
|
||
|
||
health: dict[str, Any] = {
|
||
"workflow_id": workflow_id,
|
||
"active_revision": active_rev,
|
||
"is_locked": is_locked,
|
||
"window_days": 30,
|
||
"total_runs": total,
|
||
"completed_runs": completed,
|
||
"failed_runs": failed,
|
||
"success_rate": success_rate,
|
||
"failure_rate": failure_rate,
|
||
"avg_latency_ms": avg_latency_ms,
|
||
"upvotes": upvotes,
|
||
"downvotes": downvotes,
|
||
"rated_runs": rated_runs,
|
||
"negative_rate": negative_rate,
|
||
"recent_models": recent_models[:5],
|
||
"active_model_profile": model_profile,
|
||
"model_drift_detected": model_drift,
|
||
"unused_tools": unused_tools,
|
||
"canary": active_canary,
|
||
"revision_archive": archive_scores[:10],
|
||
"recommended_parent_revision": best_parent,
|
||
"policy": policy,
|
||
}
|
||
signals: list[dict[str, Any]] = []
|
||
for detector in SIGNAL_DETECTORS:
|
||
try:
|
||
for sig in detector.detect(health):
|
||
signals.append(sig.to_dict())
|
||
except Exception:
|
||
continue
|
||
health["signals"] = signals
|
||
return health
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Tier 0: Constitution Patch Validation & Canary Auto-Rollback
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def validate_evolution_patch(
|
||
base_graph: dict[str, Any],
|
||
proposed_graph: dict[str, Any],
|
||
diffs: list[dict[str, Any]],
|
||
*,
|
||
is_meta: bool = False,
|
||
is_auto: bool = False,
|
||
) -> tuple[bool, list[str]]:
|
||
"""Immutable Tier-0 Constitution check; returns `(ok, violations)`."""
|
||
violations: list[str] = []
|
||
try:
|
||
validated = _validate_graph_payload(proposed_graph)
|
||
except HTTPException as exc:
|
||
return False, [f"图结构校验失败:{exc.detail}"]
|
||
|
||
base_nodes = {
|
||
str(n.get("id")): n
|
||
for n in (base_graph.get("nodes") or [])
|
||
if isinstance(n, dict) and n.get("id")
|
||
}
|
||
prop_nodes = {
|
||
str(n.get("id")): n
|
||
for n in (validated.get("nodes") or [])
|
||
if isinstance(n, dict) and n.get("id")
|
||
}
|
||
|
||
# 1. Preserve trigger/output presence if present in baseline
|
||
base_types = {str(n.get("node_type") or "") for n in base_nodes.values()}
|
||
prop_types = {str(n.get("node_type") or "") for n in prop_nodes.values()}
|
||
for required_type in ("trigger", "output"):
|
||
if required_type in base_types and required_type not in prop_types:
|
||
violations.append(f"不可移除基础 {required_type} 节点")
|
||
|
||
# 2. Prevent blanking out non-empty system_prompt
|
||
for nid, bnode in base_nodes.items():
|
||
pnode = prop_nodes.get(nid)
|
||
if not pnode:
|
||
continue
|
||
if str(bnode.get("system_prompt") or "").strip() and not str(pnode.get("system_prompt") or "").strip():
|
||
violations.append(f"节点 {nid} 的 system_prompt 不可被清空")
|
||
|
||
changed_node_ids = {
|
||
str(d.get("node_id") or "")
|
||
for d in diffs
|
||
if isinstance(d, dict) and d.get("node_id")
|
||
}
|
||
|
||
# 3. Meta-workflow specific Constitution guards
|
||
if is_meta:
|
||
touched_frozen = changed_node_ids & FROZEN_META_NODE_IDS
|
||
if touched_frozen:
|
||
violations.append(f"元进化宪法节点不可修改:{', '.join(sorted(touched_frozen))}")
|
||
for frozen_id in FROZEN_META_NODE_IDS:
|
||
if frozen_id in base_nodes:
|
||
if frozen_id not in prop_nodes:
|
||
violations.append(f"不可删除宪法守护节点 {frozen_id}")
|
||
elif prop_nodes[frozen_id] != base_nodes[frozen_id]:
|
||
violations.append(f"宪法守护节点 {frozen_id} 内容受只读保护")
|
||
active_llm_count = sum(
|
||
1
|
||
for n in prop_nodes.values()
|
||
if n.get("node_type") in {"llm_agent", "tool_agent"} and n.get("enabled", True)
|
||
)
|
||
if active_llm_count == 0:
|
||
violations.append("元引擎至少须保留一个启用的 LLM 推理节点")
|
||
patch_node = prop_nodes.get("patch_node")
|
||
if patch_node:
|
||
combined_prompt = f"{patch_node.get('system_prompt') or ''} {patch_node.get('prompt') or ''}"
|
||
if "json" not in combined_prompt.lower() or "node_patches" not in combined_prompt:
|
||
violations.append("patch_node 提示词必须保留 JSON node_patches 结构化输出约束")
|
||
|
||
# 4. Auto-mode blast radius lock
|
||
if is_auto:
|
||
if set(base_nodes.keys()) != set(prop_nodes.keys()):
|
||
violations.append("自动发布模式禁止增删节点拓扑,仅允许节点字段微调")
|
||
max_allowed = 1 if is_meta else max(1, min(MAX_AUTO_NODES_CHANGED, int(len(base_nodes) * MAX_AUTO_NODE_RATIO) or 1))
|
||
if len(changed_node_ids) > max_allowed:
|
||
violations.append(f"自动变更半径超限(最多允许修改 {max_allowed} 个节点,实际 {len(changed_node_ids)} 个)")
|
||
|
||
return len(violations) == 0, violations
|
||
|
||
|
||
def _count_canary_observations(runs: list[WorkflowRun], canary_entry: dict[str, Any]) -> dict[str, Any]:
|
||
started_at = _parse_iso(canary_entry.get("created_at"))
|
||
target_rev = canary_entry.get("target_revision")
|
||
matched: list[WorkflowRun] = []
|
||
for r in runs:
|
||
r_time = _ensure_utc(r.started_at)
|
||
if started_at and r_time and r_time < started_at:
|
||
continue
|
||
r_rev = _run_revision(r)
|
||
if isinstance(target_rev, int) and r_rev is not None and r_rev != target_rev:
|
||
continue
|
||
matched.append(r)
|
||
|
||
# Sort ascending chronologically to measure consecutive failures properly
|
||
matched_asc = sorted(matched, key=lambda x: _ensure_utc(x.started_at) or _utc_now())
|
||
observed = len(matched_asc)
|
||
failed = sum(1 for r in matched_asc if r.status == "failed")
|
||
downvoted = sum(1 for r in matched_asc if _run_rating(r) == -1)
|
||
|
||
max_consec_fail = 0
|
||
cur_consec = 0
|
||
for r in matched_asc:
|
||
if r.status == "failed":
|
||
cur_consec += 1
|
||
max_consec_fail = max(max_consec_fail, cur_consec)
|
||
else:
|
||
cur_consec = 0
|
||
|
||
return {
|
||
"observed": observed,
|
||
"failed": failed,
|
||
"downvoted": downvoted,
|
||
"max_consecutive_failures": max_consec_fail,
|
||
}
|
||
|
||
|
||
async def _evaluate_meta_canary(db: AsyncSession) -> None:
|
||
"""Auto-verify or auto-rollback `meta.workflow_evolver` based on downstream ledger outcomes."""
|
||
entries = await _load_ledger_entries(db)
|
||
meta_canary = next(
|
||
(
|
||
e
|
||
for e in entries
|
||
if e.get("workflow_id") == META_WORKFLOW_ID and e.get("status") == "canary"
|
||
),
|
||
None,
|
||
)
|
||
if meta_canary is None:
|
||
return
|
||
meta_started = _parse_iso(meta_canary.get("created_at"))
|
||
downstream = [
|
||
e
|
||
for e in entries
|
||
if e.get("workflow_id") != META_WORKFLOW_ID
|
||
and e.get("status") in {"verified", "rolled_back"}
|
||
and (_parse_iso(e.get("created_at")) or _utc_now()) >= (meta_started or _utc_now())
|
||
]
|
||
if not downstream:
|
||
return
|
||
recent_outcomes = downstream[:META_CANARY_WINDOW]
|
||
rollbacks = sum(1 for e in recent_outcomes if e.get("status") == "rolled_back")
|
||
if rollbacks >= META_CANARY_FAILURE_ROLLBACK and isinstance(meta_canary.get("base_revision"), int):
|
||
await rollback_workflow(
|
||
db,
|
||
META_WORKFLOW_ID,
|
||
int(meta_canary["base_revision"]),
|
||
actor="system:meta_canary_rollback",
|
||
)
|
||
await update_ledger_entry(
|
||
db,
|
||
str(meta_canary["id"]),
|
||
{
|
||
"status": "rolled_back",
|
||
"rollback_reason": f"新元策略生效后连续 {rollbacks}/{len(recent_outcomes)} 次业务进化被回滚,已自动回退元引擎。",
|
||
},
|
||
)
|
||
elif len(recent_outcomes) >= META_CANARY_WINDOW and rollbacks < META_CANARY_FAILURE_ROLLBACK:
|
||
await update_ledger_entry(
|
||
db,
|
||
str(meta_canary["id"]),
|
||
{
|
||
"status": "verified",
|
||
"verified_summary": f"经 {len(recent_outcomes)} 次下游业务进化验证稳定(回滚 {rollbacks} 次)。",
|
||
},
|
||
)
|
||
|
||
|
||
async def evaluate_canary_and_maybe_rollback(
|
||
db: AsyncSession,
|
||
workflow_id: str,
|
||
) -> dict[str, Any] | None:
|
||
"""Evaluate active canary window for `workflow_id`; roll back automatically on regression."""
|
||
entries = await _load_ledger_entries(db)
|
||
canary = next(
|
||
(
|
||
e
|
||
for e in entries
|
||
if e.get("workflow_id") == workflow_id and e.get("status") == "canary"
|
||
),
|
||
None,
|
||
)
|
||
if canary is None:
|
||
return None
|
||
|
||
runs = (
|
||
await db.execute(
|
||
select(WorkflowRun)
|
||
.where(WorkflowRun.workflow_id == workflow_id)
|
||
.order_by(desc(WorkflowRun.started_at))
|
||
.limit(40)
|
||
)
|
||
).scalars().all()
|
||
stats = _count_canary_observations(runs, canary)
|
||
observed = stats["observed"]
|
||
bad_count = stats["failed"] + stats["downvoted"]
|
||
bad_rate = (bad_count / observed) if observed else 0.0
|
||
baseline_fail = float(canary.get("baseline_failure_rate") or 0.0)
|
||
threshold = max(CANARY_BAD_RATE_THRESHOLD, baseline_fail + 0.15)
|
||
target_window = int(canary.get("canary_runs_target") or CANARY_OBSERVATION_RUNS)
|
||
|
||
tripped_consecutive = stats["max_consecutive_failures"] >= CANARY_CONSECUTIVE_FAILURES
|
||
tripped_rate = observed >= 3 and bad_rate >= threshold
|
||
|
||
if (tripped_consecutive or tripped_rate) and isinstance(canary.get("base_revision"), int):
|
||
base_rev = int(canary["base_revision"])
|
||
reason = (
|
||
f"灰度观察期触发自动回滚(观察 {observed} 次:连续失败 {stats['max_consecutive_failures']} 次,"
|
||
f"失败 {stats['failed']} 次,差评 {stats['downvoted']} 次),已回退至 v{base_rev}。"
|
||
)
|
||
await rollback_workflow(db, workflow_id, base_rev, actor="system:canary_rollback")
|
||
updated = await update_ledger_entry(
|
||
db,
|
||
str(canary["id"]),
|
||
{
|
||
"status": "rolled_back",
|
||
"rollback_reason": reason,
|
||
"observed_runs": observed,
|
||
},
|
||
)
|
||
logger.warning_event(
|
||
"Workflow canary auto-rolled back",
|
||
event="ai_evolver.canary.rollback",
|
||
context={"workflow_id": workflow_id, "base_revision": base_rev, "stats": stats},
|
||
)
|
||
await _evaluate_meta_canary(db)
|
||
return {"action": "rolled_back", "reason": reason, "entry": updated}
|
||
|
||
if observed >= target_window:
|
||
updated = await update_ledger_entry(
|
||
db,
|
||
str(canary["id"]),
|
||
{
|
||
"status": "verified",
|
||
"verified_summary": f"通过 {observed} 次灰度运行观察(失败 {stats['failed']} 次,差评 {stats['downvoted']} 次)。",
|
||
"observed_runs": observed,
|
||
},
|
||
)
|
||
await _evaluate_meta_canary(db)
|
||
return {"action": "verified", "entry": updated}
|
||
|
||
return {"action": "observing", "observed": observed, "target": target_window}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Quota / Cooldown Guardrails
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
async def _check_auto_budget_and_cooldown(
|
||
db: AsyncSession,
|
||
workflow_id: str,
|
||
policy: dict[str, Any],
|
||
*,
|
||
is_meta: bool = False,
|
||
model_drift: bool = False,
|
||
) -> tuple[bool, str]:
|
||
if workflow_id in set(policy.get("locked_workflows") or []):
|
||
return False, "工作流已锁定,禁止自动修改"
|
||
|
||
entries = await _load_ledger_entries(db)
|
||
now = _utc_now()
|
||
day_ago = now - timedelta(days=1)
|
||
|
||
auto_today = sum(
|
||
1
|
||
for e in entries
|
||
if str(e.get("trigger") or "").startswith("auto") or e.get("trigger") == "meta_auto"
|
||
if (_parse_iso(e.get("created_at")) or now) >= day_ago
|
||
and e.get("status") in {"canary", "verified", "rolled_back", "draft_saved"}
|
||
)
|
||
budget = int(policy.get("daily_auto_budget") or DEFAULT_DAILY_AUTO_BUDGET)
|
||
if auto_today >= budget:
|
||
return False, f"今日自动进化次数已达上限({auto_today}/{budget})"
|
||
|
||
latest_for_wf = next(
|
||
(
|
||
e
|
||
for e in entries
|
||
if e.get("workflow_id") == workflow_id
|
||
and e.get("status") in {"canary", "verified", "rolled_back", "draft_saved"}
|
||
),
|
||
None,
|
||
)
|
||
if latest_for_wf is not None:
|
||
last_dt = _parse_iso(latest_for_wf.get("created_at"))
|
||
if last_dt is not None:
|
||
if is_meta:
|
||
cd_days = int(policy.get("meta_cooldown_days") or 7)
|
||
if now - last_dt < timedelta(days=cd_days):
|
||
return False, f"元进化冷却期内({cd_days} 天冷却)"
|
||
else:
|
||
cd_hours = int(policy.get("business_cooldown_hours") or 24)
|
||
if not model_drift and (now - last_dt < timedelta(hours=cd_hours)):
|
||
return False, f"工作流处于冷却期内({cd_hours} 小时内仅自动调整一次)"
|
||
|
||
return True, ""
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Tier 1: Business Workflow Self-Evolution & Model Adaptation
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _build_aflow_lessons(ledger: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
|
||
positive = [
|
||
{
|
||
"workflow_id": e.get("workflow_id"),
|
||
"mode": e.get("mode"),
|
||
"summary": e.get("summary"),
|
||
"changes": (e.get("changes") or [])[:3],
|
||
}
|
||
for e in ledger
|
||
if e.get("status") == "verified"
|
||
][:5]
|
||
negative = [
|
||
{
|
||
"workflow_id": e.get("workflow_id"),
|
||
"mode": e.get("mode"),
|
||
"summary": e.get("summary"),
|
||
"reason": e.get("rollback_reason") or e.get("dismiss_reason") or "",
|
||
"changes": (e.get("changes") or [])[:3],
|
||
}
|
||
for e in ledger
|
||
if e.get("status") in {"rolled_back", "dismissed"}
|
||
][:5]
|
||
return {"verified_lessons": positive, "failed_lessons": negative}
|
||
|
||
|
||
def _deterministic_business_patches(
|
||
base_graph: dict[str, Any],
|
||
*,
|
||
mode: str,
|
||
instruction: str,
|
||
health: dict[str, Any],
|
||
bad_runs: list[dict[str, Any]],
|
||
) -> tuple[str, list[dict[str, Any]]]:
|
||
nodes = [n for n in (base_graph.get("nodes") or []) if isinstance(n, dict)]
|
||
llm_node = next((n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}), None)
|
||
if llm_node is None:
|
||
return "当前工作流无可扩展推理节点。", []
|
||
|
||
patches: list[dict[str, Any]] = []
|
||
if mode == "model_adapt":
|
||
profile = health.get("active_model_profile") or {}
|
||
tier = str(profile.get("tier") or "standard")
|
||
cur_thinking = bool(llm_node.get("thinking_enabled", True))
|
||
cur_search = bool(llm_node.get("native_web_search", False))
|
||
cur_steps = int(llm_node.get("max_steps") or 2)
|
||
if not profile.get("supports_thinking") and cur_thinking:
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "thinking_enabled",
|
||
"after": False,
|
||
"reason": f"当前模型({profile.get('model') or profile.get('provider')})未声明深度思考模式,关闭无效开关以降低首字延迟。",
|
||
}
|
||
)
|
||
elif profile.get("supports_thinking") and tier == "reasoning" and not cur_thinking:
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "thinking_enabled",
|
||
"after": True,
|
||
"reason": f"当前模型({profile.get('model')})支持深度推理,开启思维链以提高复杂研判准确率。",
|
||
}
|
||
)
|
||
if tier == "fast" and cur_steps < 3 and "query_global_situational" in (llm_node.get("tools") or []):
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "max_steps",
|
||
"after": min(4, cur_steps + 1),
|
||
"reason": "轻量高速模型适当增加 1 步工具迭代容错空间,避免单轮遗漏事实。",
|
||
}
|
||
)
|
||
if profile.get("supports_native_search") and not cur_search and any(
|
||
t in (llm_node.get("tools") or []) for t in ("web_search", "fetch_source_url")
|
||
):
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "native_web_search",
|
||
"after": True,
|
||
"reason": f"供应商 {profile.get('provider')} 支持原生联网检索,开启后可协同补充最新一手信源。",
|
||
}
|
||
)
|
||
if not patches:
|
||
base_sys = str(llm_node.get("system_prompt") or "").strip()
|
||
model_name = str(profile.get("model") or "当前模型").strip()
|
||
tag = f"[模型适配 {model_name}] 请优先依据工具返回的实测数值作答,禁止臆测缺失字段。"
|
||
if tag not in base_sys and base_sys:
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "system_prompt",
|
||
"after": f"{base_sys}\n{tag}",
|
||
"reason": f"针对当前模型({model_name})补强事实边界约束。",
|
||
}
|
||
)
|
||
summary = f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。"
|
||
return summary, patches
|
||
|
||
inst_lower = instruction.lower()
|
||
err_text = " ".join(str(r.get("error_message") or "") + " " + str(r.get("feedback_note") or "") for r in bad_runs).lower()
|
||
cur_tools = list(llm_node.get("tools") or [])
|
||
if any(k in (inst_lower + " " + err_text) for k in ("search", "搜索", "取证", "证据", "fetch", "url", "事实不准")):
|
||
added = [t for t in ("fetch_source_url", "web_search") if t in VALID_TOOL_IDS and t not in cur_tools]
|
||
if added:
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "tools",
|
||
"after": [*cur_tools, *added],
|
||
"reason": "针对取证不足或事实误差问题,补充网页核查工具。",
|
||
}
|
||
)
|
||
if any(k in (inst_lower + " " + err_text) for k in ("step", "步", "超时", "timeout", "深入", "多轮")):
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "max_steps",
|
||
"after": min(6, int(llm_node.get("max_steps") or 2) + 1),
|
||
"reason": "放宽最大工具调用步数,提升复杂问题召回率。",
|
||
}
|
||
)
|
||
unused = [t for t in (health.get("unused_tools") or []) if t in cur_tools]
|
||
if not patches and unused and not instruction.strip():
|
||
remaining = [t for t in cur_tools if t not in unused]
|
||
if remaining:
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "tools",
|
||
"after": remaining,
|
||
"reason": f"精简近期零调用的闲置工具({', '.join(unused[:3])}),减少无效上下文干扰。",
|
||
}
|
||
)
|
||
if not patches:
|
||
base_sys = str(llm_node.get("system_prompt") or "").strip()
|
||
target_note = instruction.strip() or (
|
||
"先明确区分已核验事实与待查证缺口,不确定的数值或来源须直接说明。"
|
||
)
|
||
if target_note not in base_sys and base_sys:
|
||
patches.append(
|
||
{
|
||
"node_id": llm_node["id"],
|
||
"field": "system_prompt",
|
||
"after": f"{base_sys}\n[调优约束] {target_note}",
|
||
"reason": "基于近期负反馈或调优目标加固提示词护栏。",
|
||
}
|
||
)
|
||
summary = (
|
||
f"已针对「{instruction.strip()}」生成节点调优建议。"
|
||
if instruction.strip()
|
||
else "已结合近期运行失败/差评与健康度指标生成微调建议。"
|
||
)
|
||
return summary, patches
|
||
|
||
|
||
async def propose_workflow_evolution(
|
||
db: AsyncSession,
|
||
workflow_id: str,
|
||
*,
|
||
mode: str = "optimize",
|
||
instruction: str = "",
|
||
run_id: str | None = None,
|
||
apply_mode: str = "preview",
|
||
trigger: str = "manual",
|
||
branch_from_best: bool = False,
|
||
ai_client: Any = None,
|
||
actor: str = "admin",
|
||
) -> dict[str, Any]:
|
||
"""Generate (and optionally draft/auto-publish) a validated workflow evolution patch."""
|
||
await ensure_builtin_workflows(db)
|
||
wf = (
|
||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
|
||
).scalar_one_or_none()
|
||
if wf is None:
|
||
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
|
||
if workflow_id == META_WORKFLOW_ID:
|
||
return await propose_meta_evolution(
|
||
db,
|
||
instruction=instruction,
|
||
apply_mode=apply_mode,
|
||
trigger="meta_manual" if trigger == "manual" else trigger,
|
||
ai_client=ai_client,
|
||
actor=actor,
|
||
)
|
||
|
||
health = await compute_workflow_health(db, workflow_id, ai_client=ai_client)
|
||
parent_revision = int(wf.active_revision or 1)
|
||
base_graph = copy.deepcopy(wf.draft_graph or wf.published_graph or {})
|
||
|
||
# Optional DGM archive parent selection
|
||
if branch_from_best and health.get("recommended_parent_revision"):
|
||
best_rev = int(health["recommended_parent_revision"])
|
||
rev_row = (
|
||
await db.execute(
|
||
select(AIWorkflowRevision)
|
||
.where(AIWorkflowRevision.workflow_id == workflow_id)
|
||
.where(AIWorkflowRevision.revision == best_rev)
|
||
)
|
||
).scalar_one_or_none()
|
||
if rev_row is not None and isinstance(rev_row.graph_json, dict):
|
||
base_graph = copy.deepcopy(rev_row.graph_json)
|
||
parent_revision = best_rev
|
||
|
||
# Collect bad/selected run context for GEPA diagnosis
|
||
bad_runs_rows = (
|
||
await db.execute(
|
||
select(WorkflowRun)
|
||
.where(WorkflowRun.workflow_id == workflow_id)
|
||
.order_by(desc(WorkflowRun.started_at))
|
||
.limit(40)
|
||
)
|
||
).scalars().all()
|
||
selected_run = next((r for r in bad_runs_rows if run_id and r.id == run_id), None)
|
||
bad_runs: list[dict[str, Any]] = []
|
||
for r in bad_runs_rows:
|
||
rating = _run_rating(r)
|
||
if r.status == "failed" or rating == -1:
|
||
bu = r.budget_used if isinstance(r.budget_used, dict) else {}
|
||
bad_runs.append(
|
||
{
|
||
"id": r.id,
|
||
"status": r.status,
|
||
"question": r.question,
|
||
"error_message": r.error_message,
|
||
"rating": rating,
|
||
"feedback_note": bu.get("feedback_note") or "",
|
||
"tool_trace": r.tool_trace or [],
|
||
"model_used": _run_model(r),
|
||
}
|
||
)
|
||
if len(bad_runs) >= 6:
|
||
break
|
||
|
||
# Tier 2 integration: load live published prompts from `meta.workflow_evolver`
|
||
diag_node = await resolve_runtime_workflow_node(db, META_WORKFLOW_ID, "diag_node") or {}
|
||
patch_node = await resolve_runtime_workflow_node(db, META_WORKFLOW_ID, "patch_node") or {}
|
||
meta_wf = (
|
||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID))
|
||
).scalar_one_or_none()
|
||
meta_revision = int(meta_wf.active_revision or 1) if meta_wf is not None else 1
|
||
|
||
ledger = await _load_ledger_entries(db)
|
||
lessons = _build_aflow_lessons([e for e in ledger if e.get("workflow_id") != META_WORKFLOW_ID])
|
||
|
||
client = ai_client
|
||
ai_ready = False
|
||
if client is None:
|
||
try:
|
||
client = await get_ai_provider_client(db)
|
||
except Exception:
|
||
client = None
|
||
if client is not None and hasattr(client, "is_ready"):
|
||
try:
|
||
ai_ready, _, _ = await client.is_ready()
|
||
except Exception:
|
||
ai_ready = False
|
||
|
||
summary = ""
|
||
raw_patches: list[dict[str, Any]] = []
|
||
if ai_ready and 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"],
|
||
}
|
||
diag_sys = str(diag_node.get("system_prompt") or "").strip()
|
||
patch_sys = str(patch_node.get("system_prompt") or "").strip()
|
||
combined_sys = (
|
||
f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip()
|
||
or "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。"
|
||
)
|
||
objective = (
|
||
f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)\n"
|
||
f"工作流 ID:{workflow_id}\n"
|
||
f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}\n"
|
||
f"{str(patch_node.get('prompt') or '')}"
|
||
).strip()
|
||
req = SituationalAnalysisRequest(
|
||
title=f"Evolve workflow {workflow_id}",
|
||
objective=objective[:16000],
|
||
system_prompt=combined_sys[:8000],
|
||
context={
|
||
"workflow_id": workflow_id,
|
||
"parent_revision": parent_revision,
|
||
"current_graph": base_graph,
|
||
"available_tools": [{"id": t["id"], "description": t["description"]} for t in TOOL_CATALOG],
|
||
"health_summary": {
|
||
k: health[k]
|
||
for k in ("total_runs", "success_rate", "avg_latency_ms", "upvotes", "downvotes", "unused_tools", "model_drift_detected", "active_model_profile", "recent_models")
|
||
},
|
||
"failed_or_downvoted_runs": bad_runs,
|
||
"selected_run": selected_run.to_dict() if selected_run else None,
|
||
"aflow_lessons": lessons,
|
||
},
|
||
response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}},
|
||
)
|
||
try:
|
||
resp = await 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 evolution proposal failed; using deterministic fallback",
|
||
event="ai_evolver.propose.fallback",
|
||
context={"workflow_id": workflow_id, "mode": mode, "error": str(exc)},
|
||
)
|
||
|
||
if not raw_patches:
|
||
summary, raw_patches = _deterministic_business_patches(
|
||
base_graph,
|
||
mode=mode,
|
||
instruction=instruction,
|
||
health=health,
|
||
bad_runs=bad_runs,
|
||
)
|
||
|
||
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
|
||
is_auto_apply = apply_mode == "auto"
|
||
constitution_ok, violations = validate_evolution_patch(
|
||
base_graph,
|
||
proposed_graph,
|
||
diffs,
|
||
is_meta=False,
|
||
is_auto=is_auto_apply,
|
||
)
|
||
|
||
applied_status = "preview"
|
||
new_revision = None
|
||
blocked_reason = ""
|
||
ledger_entry: dict[str, Any] | None = None
|
||
|
||
if apply_mode == "draft":
|
||
if not constitution_ok or not diffs:
|
||
applied_status = "blocked"
|
||
blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动"
|
||
else:
|
||
await save_workflow_draft(
|
||
db,
|
||
workflow_id,
|
||
proposed_graph,
|
||
actor=actor if trigger == "manual" else "system:auto_draft",
|
||
)
|
||
applied_status = "draft_saved"
|
||
ledger_entry = await append_ledger_entry(
|
||
db,
|
||
{
|
||
"workflow_id": workflow_id,
|
||
"mode": mode,
|
||
"trigger": trigger,
|
||
"status": "draft_saved",
|
||
"base_revision": parent_revision,
|
||
"target_revision": None,
|
||
"meta_revision": meta_revision,
|
||
"summary": summary,
|
||
"changes": diffs,
|
||
},
|
||
)
|
||
elif apply_mode == "auto":
|
||
policy = health["policy"]
|
||
budget_ok, budget_msg = await _check_auto_budget_and_cooldown(
|
||
db,
|
||
workflow_id,
|
||
policy,
|
||
is_meta=False,
|
||
model_drift=bool(mode == "model_adapt" and health.get("model_drift_detected")),
|
||
)
|
||
if not budget_ok:
|
||
applied_status = "blocked"
|
||
blocked_reason = budget_msg
|
||
elif not constitution_ok or not diffs:
|
||
applied_status = "blocked"
|
||
blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动"
|
||
else:
|
||
prev_active_rev = int(wf.active_revision or 1)
|
||
published = await publish_workflow(
|
||
db,
|
||
workflow_id,
|
||
graph=proposed_graph,
|
||
change_summary=f"[Auto-Evolve/{mode}] {summary[:120]}",
|
||
actor="system:auto_evolver",
|
||
)
|
||
applied_status = "auto_published"
|
||
new_revision = int(published.get("active_revision") or (prev_active_rev + 1))
|
||
ledger_entry = await append_ledger_entry(
|
||
db,
|
||
{
|
||
"workflow_id": workflow_id,
|
||
"mode": mode,
|
||
"trigger": trigger,
|
||
"status": "canary",
|
||
"base_revision": prev_active_rev,
|
||
"target_revision": new_revision,
|
||
"parent_revision": parent_revision,
|
||
"meta_revision": meta_revision,
|
||
"canary_runs_target": CANARY_OBSERVATION_RUNS,
|
||
"baseline_failure_rate": health["failure_rate"],
|
||
"summary": summary,
|
||
"changes": diffs,
|
||
},
|
||
)
|
||
if applied_status == "blocked":
|
||
ledger_entry = await append_ledger_entry(
|
||
db,
|
||
{
|
||
"workflow_id": workflow_id,
|
||
"mode": mode,
|
||
"trigger": trigger,
|
||
"status": "blocked",
|
||
"base_revision": int(wf.active_revision or 1),
|
||
"meta_revision": meta_revision,
|
||
"summary": summary or f"{mode} blocked",
|
||
"rollback_reason": blocked_reason,
|
||
"changes": diffs,
|
||
},
|
||
)
|
||
|
||
return {
|
||
"workflow_id": workflow_id,
|
||
"mode": mode,
|
||
"base_revision": parent_revision,
|
||
"meta_revision": meta_revision,
|
||
"summary": summary or "暂无需要变更的字段。",
|
||
"changes": diffs,
|
||
"proposed_graph": proposed_graph,
|
||
"constitution_ok": constitution_ok,
|
||
"violations": violations,
|
||
"applied_status": applied_status,
|
||
"new_revision": new_revision,
|
||
"blocked_reason": blocked_reason,
|
||
"ledger_entry": ledger_entry,
|
||
"health": health,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Fixture A/B Evaluation Helper
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
async def _run_graph_single_sample(
|
||
*,
|
||
db: AsyncSession,
|
||
workflow: dict[str, Any],
|
||
graph: dict[str, Any],
|
||
question: str,
|
||
earth_context: dict[str, Any],
|
||
ai_client: Any,
|
||
) -> dict[str, Any]:
|
||
started = _utc_now()
|
||
test_wf = {
|
||
**workflow,
|
||
"published_graph": graph,
|
||
"draft_graph": graph,
|
||
}
|
||
answer = ""
|
||
err = ""
|
||
nodes_done: list[str] = []
|
||
try:
|
||
async for ev in run_workflow_dag_stream(
|
||
db=db,
|
||
workflow=test_wf,
|
||
question=question,
|
||
use_draft=True,
|
||
earth_context=earth_context,
|
||
ai_client=ai_client,
|
||
allow_external_tools=False,
|
||
):
|
||
ev_name = str(ev.get("event") or "")
|
||
ev_data = ev.get("data") if isinstance(ev.get("data"), dict) else {}
|
||
if ev_name == "done":
|
||
answer = str(ev_data.get("answer_markdown") or "")
|
||
nodes_done = [str(x) for x in (ev_data.get("nodes") or [])]
|
||
elif ev_name == "error":
|
||
err = str(ev_data.get("message") or "DAG error")
|
||
except Exception as exc:
|
||
err = str(exc)
|
||
|
||
latency_ms = max(0, int((_utc_now() - started).total_seconds() * 1000))
|
||
return {
|
||
"ok": bool(answer.strip()) and not err,
|
||
"latency_ms": latency_ms,
|
||
"answer_length": len(answer.strip()),
|
||
"nodes": nodes_done,
|
||
"error": err,
|
||
}
|
||
|
||
|
||
async def run_fixture_ab_eval(
|
||
db: AsyncSession,
|
||
workflow_id: str,
|
||
proposed_graph: dict[str, Any],
|
||
*,
|
||
max_fixtures: int = 3,
|
||
evaluator_id: str = "fixture_ab",
|
||
) -> dict[str, Any]:
|
||
await ensure_builtin_workflows(db)
|
||
wf = (
|
||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
|
||
).scalar_one_or_none()
|
||
if wf is None:
|
||
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
|
||
|
||
evaluator = EVALUATORS.get(evaluator_id)
|
||
if evaluator is None:
|
||
raise HTTPException(status_code=400, detail=f"Unknown evaluator '{evaluator_id}'")
|
||
|
||
validated_proposed = _validate_graph_payload(proposed_graph)
|
||
base_graph = copy.deepcopy(wf.published_graph or {})
|
||
return await evaluator.evaluate(
|
||
db,
|
||
wf.to_dict(),
|
||
base_graph,
|
||
validated_proposed,
|
||
max_fixtures=max_fixtures,
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Workflow Incubation from Frequent `default.general` Usage
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_INCUBATION_CLUSTERS: list[dict[str, Any]] = [
|
||
{
|
||
"slug": "bgp_route_audit",
|
||
"keywords": ("bgp", "asn", "路由", "劫持", "泄漏", "前缀"),
|
||
"name": "BGP 路由异常专项排查",
|
||
"name_en": "BGP Route Anomaly Investigation",
|
||
"description": "针对高频 BGP/ASN 路由异常问询孵化:自动拉取 BGP 事故与全球态势快照进行核查。",
|
||
"description_en": "Incubated from frequent BGP/ASN queries with deterministic incident & anomaly tools.",
|
||
"tools": ["query_bgp_incidents", "query_global_situational"],
|
||
"entity_types": ["bgp", "bgp_collector"],
|
||
},
|
||
{
|
||
"slug": "subsea_cable_watch",
|
||
"keywords": ("海缆", "光缆", "登陆站", "cable", "landing", "中断"),
|
||
"name": "海缆与登陆站韧性研判",
|
||
"name_en": "Subsea Cable Resilience Advisor",
|
||
"description": "针对高频海底光缆与登陆站拓扑问询孵化:串联海缆拓扑与船舶近邻工具。",
|
||
"description_en": "Incubated from frequent subsea cable questions combining cable and AIS vessel tools.",
|
||
"tools": ["query_cable_posture", "query_vessel_posture"],
|
||
"entity_types": ["cable", "landing_point"],
|
||
},
|
||
{
|
||
"slug": "compute_cluster_compare",
|
||
"keywords": ("算力", "超算", "gpu", "数据中心", "cluster", "compute", "rpi"),
|
||
"name": "全球算力集群对比专题",
|
||
"name_en": "Compute Cluster Benchmark Advisor",
|
||
"description": "针对高频算力与集群规模对比问询孵化:预载算力多口径指标与新闻态势。",
|
||
"description_en": "Incubated from frequent compute cluster queries using multi-metric & news tools.",
|
||
"tools": ["query_compute_posture", "query_recent_earth_news"],
|
||
"entity_types": ["supercomputer", "gpu_cluster", "data_center", "compute_region"],
|
||
},
|
||
{
|
||
"slug": "satellite_orbit_brief",
|
||
"keywords": ("卫星", "星链", "轨道", "satellite", "starlink", "orbit"),
|
||
"name": "在轨卫星星座态势跟踪",
|
||
"name_en": "Satellite Constellation Brief",
|
||
"description": "针对高频卫星与星座覆蓋问询孵化:自动结合卫星轨道工具进行专项推演。",
|
||
"description_en": "Incubated from frequent satellite questions with orbital telemetry lookup.",
|
||
"tools": ["query_satellite_posture", "query_global_situational"],
|
||
"entity_types": ["satellite"],
|
||
},
|
||
]
|
||
|
||
|
||
async def incubate_workflow_from_runs(
|
||
db: AsyncSession,
|
||
*,
|
||
ai_client: Any = None,
|
||
) -> dict[str, Any]:
|
||
"""Discover frequent unspecialized `default.general` intents and propose a custom workflow draft."""
|
||
await ensure_builtin_workflows(db)
|
||
cutoff = _utc_now() - timedelta(days=30)
|
||
runs = (
|
||
await db.execute(
|
||
select(WorkflowRun)
|
||
.where(WorkflowRun.workflow_id == "default.general")
|
||
.order_by(desc(WorkflowRun.started_at))
|
||
.limit(120)
|
||
)
|
||
).scalars().all()
|
||
recent = [
|
||
r for r in runs
|
||
if (_ensure_utc(r.started_at) or _utc_now()) >= cutoff and str(r.question or "").strip()
|
||
]
|
||
|
||
# Pick dominant cluster deterministically first
|
||
cluster_hits: Counter[str] = Counter()
|
||
cluster_samples: dict[str, list[str]] = {}
|
||
for r in recent:
|
||
q = str(r.question or "").strip()
|
||
ql = q.lower()
|
||
for cl in _INCUBATION_CLUSTERS:
|
||
if any(kw in ql for kw in cl["keywords"]):
|
||
cluster_hits[cl["slug"]] += 1
|
||
cluster_samples.setdefault(cl["slug"], [])
|
||
if q not in cluster_samples[cl["slug"]] and len(cluster_samples[cl["slug"]]) < 5:
|
||
cluster_samples[cl["slug"]].append(q[:140])
|
||
|
||
selected_cluster = _INCUBATION_CLUSTERS[0]
|
||
if cluster_hits:
|
||
top_slug, _ = cluster_hits.most_common(1)[0]
|
||
selected_cluster = next(c for c in _INCUBATION_CLUSTERS if c["slug"] == top_slug)
|
||
sample_questions = cluster_samples.get(selected_cluster["slug"], []) or [
|
||
str(r.question or "")[:140] for r in recent[:4] if str(r.question or "").strip()
|
||
]
|
||
|
||
slug = f"{selected_cluster['slug']}_{uuid4().hex[:4]}"
|
||
candidate: dict[str, Any] = {
|
||
"suggested_workflow_id": f"custom.{slug}",
|
||
"name": selected_cluster["name"],
|
||
"name_en": selected_cluster["name_en"],
|
||
"description": selected_cluster["description"],
|
||
"description_en": selected_cluster["description_en"],
|
||
"tools": [t for t in selected_cluster["tools"] if t in VALID_TOOL_IDS],
|
||
"entity_types": selected_cluster["entity_types"],
|
||
"sample_questions": sample_questions,
|
||
"observed_runs_analyzed": len(recent),
|
||
"rationale": (
|
||
f"在近期 {len(recent)} 条通用参谋记录中识别到高频专项需求,建议沉淀为独立可调优工作流。"
|
||
if recent
|
||
else "基于系统核心态势领域生成标准专项工作流模板,可直接微调后创建。"
|
||
),
|
||
}
|
||
|
||
# Enrich via AI if ready
|
||
client = ai_client
|
||
ai_ready = False
|
||
if client is None:
|
||
try:
|
||
client = await get_ai_provider_client(db)
|
||
except Exception:
|
||
client = None
|
||
if client is not None and hasattr(client, "is_ready"):
|
||
try:
|
||
ai_ready, _, _ = await client.is_ready()
|
||
except Exception:
|
||
ai_ready = False
|
||
|
||
if ai_ready and client is not None and len(recent) >= 4:
|
||
schema = {
|
||
"type": "object",
|
||
"properties": {
|
||
"name": {"type": "string"},
|
||
"name_en": {"type": "string"},
|
||
"description": {"type": "string"},
|
||
"tools": {"type": "array", "items": {"type": "string"}},
|
||
"system_prompt": {"type": "string"},
|
||
"prompt": {"type": "string"},
|
||
"rationale": {"type": "string"},
|
||
},
|
||
"required": ["name", "tools", "system_prompt", "prompt", "rationale"],
|
||
}
|
||
req = SituationalAnalysisRequest(
|
||
title="Incubate new AI workflow",
|
||
objective="请从以下高频通用参谋提问中提炼 1 个最具复用价值的专项工作流方案,输出严格 JSON。",
|
||
system_prompt="你是智能星球 AI 工作流架构师。仅输出符合 JSON schema 的专项工作流方案,tools 仅限白名单 ID。",
|
||
context={
|
||
"recent_questions": [str(r.question or "")[:160] for r in recent[:25]],
|
||
"available_tools": [{"id": t["id"], "description": t["description"]} for t in TOOL_CATALOG],
|
||
},
|
||
response_format={"type": "json_schema", "json_schema": {"name": "incubated_workflow", "schema": schema}},
|
||
)
|
||
try:
|
||
resp = await 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 and str(parsed.get("name") or "").strip():
|
||
valid_tools = [str(t).strip() for t in (parsed.get("tools") or []) if str(t).strip() in VALID_TOOL_IDS]
|
||
if valid_tools:
|
||
candidate["tools"] = valid_tools[:4]
|
||
candidate["name"] = str(parsed["name"]).strip()[:120]
|
||
if parsed.get("name_en"):
|
||
candidate["name_en"] = str(parsed["name_en"]).strip()[:120]
|
||
if parsed.get("description"):
|
||
candidate["description"] = str(parsed["description"]).strip()[:500]
|
||
if parsed.get("rationale"):
|
||
candidate["rationale"] = str(parsed["rationale"]).strip()[:500]
|
||
if parsed.get("system_prompt"):
|
||
candidate["_custom_system_prompt"] = str(parsed["system_prompt"]).strip()[:2000]
|
||
if parsed.get("prompt"):
|
||
candidate["_custom_prompt"] = str(parsed["prompt"]).strip()[:2000]
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"AI workflow incubation failed; using deterministic cluster template",
|
||
event="ai_evolver.incubate.fallback",
|
||
context={"error": str(exc)},
|
||
)
|
||
|
||
graph = build_starter_workflow_graph(candidate["name"])
|
||
for node in graph.get("nodes") or []:
|
||
if isinstance(node, dict) and node.get("node_type") == "llm_agent":
|
||
node["tools"] = candidate["tools"] or ["query_global_situational"]
|
||
if candidate.get("_custom_system_prompt"):
|
||
node["system_prompt"] = candidate["_custom_system_prompt"]
|
||
if candidate.get("_custom_prompt"):
|
||
node["prompt"] = candidate["_custom_prompt"]
|
||
|
||
candidate["graph"] = _validate_graph_payload(graph)
|
||
candidate["bindings"] = {
|
||
"enabled": False,
|
||
"surfaces": ["copilot_quick"],
|
||
"entity_types": candidate["entity_types"],
|
||
"action_label": candidate["name"][:24],
|
||
"action_label_en": candidate["name_en"][:32],
|
||
}
|
||
candidate.pop("_custom_system_prompt", None)
|
||
candidate.pop("_custom_prompt", None)
|
||
return candidate
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Tier 2: Meta-Evolution (Self-Bootstrapping of `meta.workflow_evolver`)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
async def propose_meta_evolution(
|
||
db: AsyncSession,
|
||
*,
|
||
instruction: str = "",
|
||
apply_mode: str = "preview",
|
||
trigger: str = "meta_manual",
|
||
ai_client: Any = None,
|
||
actor: str = "admin",
|
||
) -> dict[str, Any]:
|
||
"""Evolve `meta.workflow_evolver` prompts from objective evolution ledger outcomes."""
|
||
await ensure_builtin_workflows(db)
|
||
meta_wf = (
|
||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID))
|
||
).scalar_one_or_none()
|
||
if meta_wf is None:
|
||
raise HTTPException(status_code=404, detail=f"Workflow '{META_WORKFLOW_ID}' not found")
|
||
|
||
base_graph = copy.deepcopy(meta_wf.draft_graph or meta_wf.published_graph or {})
|
||
ledger = await _load_ledger_entries(db)
|
||
outcomes = [
|
||
e
|
||
for e in ledger
|
||
if e.get("workflow_id") != META_WORKFLOW_ID
|
||
and e.get("status") in {"verified", "rolled_back", "dismissed"}
|
||
]
|
||
verified_count = sum(1 for e in outcomes if e.get("status") == "verified")
|
||
rollback_count = sum(1 for e in outcomes if e.get("status") == "rolled_back")
|
||
dismissed_count = sum(1 for e in outcomes if e.get("status") == "dismissed")
|
||
|
||
client = ai_client
|
||
ai_ready = False
|
||
if client is None:
|
||
try:
|
||
client = await get_ai_provider_client(db)
|
||
except Exception:
|
||
client = None
|
||
if client is not None and hasattr(client, "is_ready"):
|
||
try:
|
||
ai_ready, _, _ = await client.is_ready()
|
||
except Exception:
|
||
ai_ready = False
|
||
|
||
summary = ""
|
||
raw_patches: list[dict[str, Any]] = []
|
||
if ai_ready and client is not None:
|
||
schema = {
|
||
"type": "object",
|
||
"properties": {
|
||
"summary": {"type": "string"},
|
||
"node_patches": {
|
||
"type": "array",
|
||
"items": {
|
||
"type": "object",
|
||
"properties": {
|
||
"node_id": {"type": "string", "enum": ["diag_node", "patch_node"]},
|
||
"field": {"type": "string", "enum": ["system_prompt", "prompt", "thinking_enabled"]},
|
||
"after": {},
|
||
"reason": {"type": "string"},
|
||
},
|
||
"required": ["node_id", "field", "after", "reason"],
|
||
},
|
||
},
|
||
},
|
||
"required": ["summary", "node_patches"],
|
||
}
|
||
req = SituationalAnalysisRequest(
|
||
title="Meta-evolve workflow evolver",
|
||
objective=(
|
||
f"管理员指示:{instruction.strip() or '基于进化台账中已验证与被回滚/忽略的案例,优化元引擎诊断与补丁合成精度。'}\n"
|
||
"仅允许修改 `diag_node` 或 `patch_node` 的提示词或 thinking_enabled;"
|
||
"严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。"
|
||
),
|
||
system_prompt="你是智能星球 AI 元进化策略师。仅输出严格 JSON:{summary, node_patches}。",
|
||
context={
|
||
"meta_graph": base_graph,
|
||
"outcome_counts": {
|
||
"verified": verified_count,
|
||
"rolled_back": rollback_count,
|
||
"dismissed": dismissed_count,
|
||
},
|
||
"lessons": _build_aflow_lessons(outcomes),
|
||
},
|
||
response_format={"type": "json_schema", "json_schema": {"name": "meta_patch", "schema": schema}},
|
||
)
|
||
try:
|
||
resp = await 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 meta-evolution request failed; using deterministic prompt refinement",
|
||
event="ai_evolver.meta.fallback",
|
||
context={"error": str(exc)},
|
||
)
|
||
|
||
if not raw_patches:
|
||
target_node = next(
|
||
(n for n in (base_graph.get("nodes") or []) if n.get("id") == "patch_node"),
|
||
None,
|
||
)
|
||
if target_node is not None:
|
||
base_sys = str(target_node.get("system_prompt") or "").strip()
|
||
if instruction.strip():
|
||
clause = f"[元进化规则] {instruction.strip()}"
|
||
elif rollback_count > verified_count:
|
||
clause = (
|
||
f"[元进化反思 · 历史回滚 {rollback_count} 次] 当近期存在回滚案例时,"
|
||
"优先只调整单一高置信度字段(如 tools 或 max_steps),避免大段重写提示词。"
|
||
)
|
||
else:
|
||
clause = (
|
||
f"[元进化策略] 参考近 {len(outcomes)} 次进化台账结果,优先强化工具核验与模型能力边界说明。"
|
||
)
|
||
if clause not in base_sys:
|
||
raw_patches.append(
|
||
{
|
||
"node_id": "patch_node",
|
||
"field": "system_prompt",
|
||
"after": f"{base_sys}\n{clause}".strip(),
|
||
"reason": "结合进化台账正负结果收敛补丁生成保守度与精准度。",
|
||
}
|
||
)
|
||
summary = summary or (
|
||
f"基于 {len(outcomes)} 条进化台账记录(验证有效 {verified_count},回滚 {rollback_count},忽略 {dismissed_count})生成元引擎自举方案。"
|
||
)
|
||
|
||
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
|
||
is_auto_apply = apply_mode == "auto"
|
||
constitution_ok, violations = validate_evolution_patch(
|
||
base_graph,
|
||
proposed_graph,
|
||
diffs,
|
||
is_meta=True,
|
||
is_auto=is_auto_apply,
|
||
)
|
||
|
||
applied_status = "preview"
|
||
new_revision = None
|
||
blocked_reason = ""
|
||
ledger_entry: dict[str, Any] | None = None
|
||
policy = await get_evolution_policy(db)
|
||
|
||
if apply_mode == "draft":
|
||
if not constitution_ok or not diffs:
|
||
applied_status = "blocked"
|
||
blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动"
|
||
else:
|
||
await save_workflow_draft(
|
||
db,
|
||
META_WORKFLOW_ID,
|
||
proposed_graph,
|
||
actor=actor if trigger == "meta_manual" else "system:meta_draft",
|
||
)
|
||
applied_status = "draft_saved"
|
||
ledger_entry = await append_ledger_entry(
|
||
db,
|
||
{
|
||
"workflow_id": META_WORKFLOW_ID,
|
||
"mode": "meta",
|
||
"trigger": trigger,
|
||
"status": "draft_saved",
|
||
"base_revision": int(meta_wf.active_revision or 1),
|
||
"target_revision": None,
|
||
"summary": summary,
|
||
"changes": diffs,
|
||
},
|
||
)
|
||
elif apply_mode == "auto":
|
||
budget_ok, budget_msg = await _check_auto_budget_and_cooldown(
|
||
db,
|
||
META_WORKFLOW_ID,
|
||
policy,
|
||
is_meta=True,
|
||
)
|
||
if policy.get("meta_mode") != "auto" and trigger != "meta_manual":
|
||
budget_ok = False
|
||
budget_msg = "元进化自动发布开关未开启"
|
||
elif trigger == "meta_auto" and len(outcomes) < MIN_LEDGER_OUTCOMES_FOR_META:
|
||
budget_ok = False
|
||
budget_msg = f"自动元进化至少需要 {MIN_LEDGER_OUTCOMES_FOR_META} 条业务进化结果(当前 {len(outcomes)} 条)"
|
||
|
||
if not budget_ok:
|
||
applied_status = "blocked"
|
||
blocked_reason = budget_msg
|
||
elif not constitution_ok or not diffs:
|
||
applied_status = "blocked"
|
||
blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动"
|
||
else:
|
||
prev_rev = int(meta_wf.active_revision or 1)
|
||
published = await publish_workflow(
|
||
db,
|
||
META_WORKFLOW_ID,
|
||
graph=proposed_graph,
|
||
change_summary=f"[Meta-Evolve] {summary[:120]}",
|
||
actor="system:meta_evolver" if trigger != "meta_manual" else actor,
|
||
)
|
||
applied_status = "auto_published"
|
||
new_revision = int(published.get("active_revision") or (prev_rev + 1))
|
||
ledger_entry = await append_ledger_entry(
|
||
db,
|
||
{
|
||
"workflow_id": META_WORKFLOW_ID,
|
||
"mode": "meta",
|
||
"trigger": trigger,
|
||
"status": "canary",
|
||
"base_revision": prev_rev,
|
||
"target_revision": new_revision,
|
||
"canary_runs_target": META_CANARY_WINDOW,
|
||
"summary": summary,
|
||
"changes": diffs,
|
||
},
|
||
)
|
||
|
||
return {
|
||
"workflow_id": META_WORKFLOW_ID,
|
||
"mode": "meta",
|
||
"base_revision": int(meta_wf.active_revision or 1),
|
||
"summary": summary,
|
||
"changes": diffs,
|
||
"proposed_graph": proposed_graph,
|
||
"constitution_ok": constitution_ok,
|
||
"violations": violations,
|
||
"applied_status": applied_status,
|
||
"new_revision": new_revision,
|
||
"blocked_reason": blocked_reason,
|
||
"ledger_entry": ledger_entry,
|
||
"outcomes_analyzed": len(outcomes),
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Non-Blocking Post-Run Hook
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
async def _post_run_evolution_worker(workflow_id: str, run_id: str) -> None:
|
||
try:
|
||
async with async_session_factory() as db:
|
||
canary_res = await evaluate_canary_and_maybe_rollback(db, workflow_id)
|
||
if canary_res and canary_res.get("action") == "rolled_back":
|
||
return
|
||
|
||
policy = await get_evolution_policy(db)
|
||
biz_mode = str(policy.get("business_mode") or "off")
|
||
if biz_mode in {"draft", "auto"} and workflow_id not in set(policy.get("locked_workflows") or []):
|
||
health = await compute_workflow_health(db, workflow_id)
|
||
signals = health.get("signals") or []
|
||
total_runs = int(health.get("total_runs") or 0)
|
||
drift = bool(health.get("model_drift_detected") and policy.get("auto_adapt_on_model_change", True))
|
||
has_degradation = any(s.get("severity") in {"warn", "critical"} for s in signals)
|
||
|
||
target_mode: str | None = None
|
||
if drift:
|
||
target_mode = "model_adapt"
|
||
elif has_degradation and total_runs >= MIN_RUNS_FOR_AUTO:
|
||
target_mode = "optimize"
|
||
|
||
if target_mode:
|
||
budget_ok, _ = await _check_auto_budget_and_cooldown(
|
||
db,
|
||
workflow_id,
|
||
policy,
|
||
is_meta=False,
|
||
model_drift=(target_mode == "model_adapt"),
|
||
)
|
||
if budget_ok:
|
||
await propose_workflow_evolution(
|
||
db,
|
||
workflow_id,
|
||
mode=target_mode,
|
||
run_id=run_id,
|
||
apply_mode=biz_mode,
|
||
trigger="auto_post_run",
|
||
branch_from_best=bool(health.get("recommended_parent_revision")),
|
||
actor="system:auto_evolver",
|
||
)
|
||
|
||
meta_mode = str(policy.get("meta_mode") or "off")
|
||
if meta_mode in {"draft", "auto"}:
|
||
meta_ok, _ = await _check_auto_budget_and_cooldown(
|
||
db,
|
||
META_WORKFLOW_ID,
|
||
policy,
|
||
is_meta=True,
|
||
)
|
||
if meta_ok:
|
||
await propose_meta_evolution(
|
||
db,
|
||
apply_mode=meta_mode,
|
||
trigger="meta_auto",
|
||
actor="system:meta_evolver",
|
||
)
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Background workflow post-run evolution check failed",
|
||
event="ai_evolver.post_run.failed",
|
||
context={"workflow_id": workflow_id, "run_id": run_id, "error": str(exc)},
|
||
)
|
||
finally:
|
||
_PENDING_BG_WORKFLOWS.discard(workflow_id)
|
||
|
||
|
||
def schedule_post_run_evolution(workflow_id: str, run_id: str) -> None:
|
||
"""Schedule non-blocking post-run canary check & gated auto-evolution."""
|
||
if not workflow_id or workflow_id == META_WORKFLOW_ID:
|
||
return
|
||
if os.getenv("PLANET_DISABLE_BG_EVOLUTION") == "1" or os.getenv("PYTEST_CURRENT_TEST"):
|
||
return
|
||
if workflow_id in _PENDING_BG_WORKFLOWS:
|
||
return
|
||
try:
|
||
loop = asyncio.get_running_loop()
|
||
except RuntimeError:
|
||
return
|
||
_PENDING_BG_WORKFLOWS.add(workflow_id)
|
||
loop.create_task(_post_run_evolution_worker(workflow_id, run_id))
|