Files
planet/backend/app/services/ai/workflow_evolver.py
T
linkong 3b1b9ef68c
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.83.0
2026-12-02 18:53:58 +08:00

2528 lines
100 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.
"""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
import re
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,
DRAFT_BINDINGS_KEY,
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 []
FIXTURE_EXPECT_KEY = "expect"
_UNCERTAINTY_MARKERS = (
"待核实", "待查", "不确定", "证据不足", "无法确认", "尚无法", "有待", "unverified", "uncertain", "insufficient evidence",
)
def normalize_fixture_expect(raw: Any) -> dict[str, Any]:
"""Normalize gradable fixture assertions stored under `context_json["expect"]`."""
if not isinstance(raw, dict):
return {}
def _str_list(key: str) -> list[str]:
vals = raw.get(key)
if not isinstance(vals, list):
return []
return [str(v).strip()[:120] for v in vals if str(v).strip()][:10]
numbers: list[str] = []
for val in raw.get("numbers") or []:
if isinstance(val, bool):
continue
if isinstance(val, (int, float)):
numbers.append(str(int(val)) if float(val).is_integer() else str(val))
elif isinstance(val, str) and re.fullmatch(r"-?\d+(?:\.\d+)?", val.strip()):
numbers.append(val.strip())
expect: dict[str, Any] = {}
if numbers:
expect["numbers"] = numbers[:10]
for key in ("must_include", "must_not_include"):
items = _str_list(key)
if items:
expect[key] = items
if raw.get("require_uncertainty_without_evidence"):
expect["require_uncertainty_without_evidence"] = True
min_evidence = raw.get("min_evidence")
if isinstance(min_evidence, int) and not isinstance(min_evidence, bool) and min_evidence > 0:
expect["min_evidence"] = min(min_evidence, 50)
return expect
def _answer_contains_number(answer: str, number: str) -> bool:
return re.search(rf"(?<![\d.]){re.escape(number)}(?!\d|\.\d)", answer) is not None
def grade_fixture_result(result: dict[str, Any], expect: dict[str, Any]) -> list[str]:
"""Return the failed checks for one sample run (empty list == pass)."""
failures: list[str] = []
answer = str(result.get("answer") or "")
if result.get("error"):
failures.append(f"执行出错:{str(result['error'])[:120]}")
if not answer.strip():
failures.append("没有输出正文")
if result.get("verification_passed") is False:
warns = ";".join(result.get("verification_warnings") or []) or "护栏校验失败"
failures.append(f"护栏校验未通过:{warns}")
for number in expect.get("numbers") or []:
if not _answer_contains_number(answer, number):
failures.append(f"未给出期望数值 {number}")
for phrase in expect.get("must_include") or []:
if phrase not in answer:
failures.append(f"缺少必备表述「{phrase}」")
for phrase in expect.get("must_not_include") or []:
if phrase in answer:
failures.append(f"出现禁用表述「{phrase}」")
evidence_count = int(result.get("evidence_count") or 0)
if expect.get("min_evidence") and evidence_count < int(expect["min_evidence"]):
failures.append(f"证据条目 {evidence_count} 少于要求的 {expect['min_evidence']}")
if expect.get("require_uncertainty_without_evidence") and evidence_count == 0:
lowered = answer.lower()
if not any(marker in lowered for marker in _UNCERTAINTY_MARKERS):
failures.append("证据不足时未保留不确定性(缺少「待核实/证据不足」等表述)")
return failures
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
graded = 0
regressions: list[str] = []
for row in rows:
question = str(row.sample_question or "").strip() or f"请分析 {row.name}"
ctx = dict(row.context_json or {})
expect = normalize_fixture_expect(ctx.pop(FIXTURE_EXPECT_KEY, None))
if expect:
graded += 1
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,
)
for res in (base_res, prop_res):
res["failures"] = grade_fixture_result(res, expect)
res["ok"] = not res["failures"]
res["answer_preview"] = str(res.pop("answer", ""))[:280]
if base_res["ok"]:
base_ok += 1
if prop_res["ok"]:
prop_ok += 1
if base_res["ok"] and not prop_res["ok"]:
regressions.append(str(row.name))
comparisons.append(
{
"fixture_id": row.id,
"fixture_name": row.name,
"question": question[:160],
"graded": bool(expect),
"expect": expect,
"base": base_res,
"proposed": prop_res,
}
)
if regressions or prop_ok < base_ok:
verdict = "regressed"
elif prop_ok > base_ok:
verdict = "improved"
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"
graded_note = "" if graded else "(样本未设置可判对错的断言,仅校验执行成功与护栏)"
return {
"evaluator_id": self.evaluator_id,
"fixture_count": len(comparisons),
"graded_fixture_count": graded,
"base_passed": base_ok,
"proposed_passed": prop_ok,
"regressions": regressions,
"verdict": verdict,
"summary": (
f"已对照 {len(comparisons)} 组样本(含断言 {graded} 组):原版通过 {base_ok}/{len(comparisons)},"
f"新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict}){graded_note}。"
),
"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_target = meta_canary.get("target_revision")
meta_live = (
await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == META_WORKFLOW_ID))
).scalar_one_or_none()
if isinstance(meta_target, int) and meta_live is not None and int(meta_live) != meta_target:
await update_ledger_entry(
db,
str(meta_canary["id"]),
{
"status": "superseded",
"superseded_reason": f"元引擎当前生效版本已变为 v{int(meta_live)}(灰度目标 v{meta_target}),终止灰度且不回滚。",
},
)
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
# A manual publish / rollback after this canary started supersedes it: rolling back now would
# overwrite the newer live revision (e.g. revert a hand-published v3 to v1).
target_rev = canary.get("target_revision")
live_rev = (
await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if isinstance(target_rev, int) and live_rev is not None and int(live_rev) != target_rev:
updated = await update_ledger_entry(
db,
str(canary["id"]),
{
"status": "superseded",
"superseded_reason": f"当前生效版本已变为 v{int(live_rev)}(灰度目标 v{target_rev}),终止本轮灰度且不回滚。",
},
)
logger.info_event(
"Workflow canary superseded by a newer live revision",
event="ai_evolver.canary.superseded",
context={"workflow_id": workflow_id, "target_revision": target_rev, "live_revision": int(live_rev)},
)
return {"action": "superseded", "entry": updated}
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')} 支持原生联网检索,开启后可协同补充最新一手信源。",
}
)
# No capability mismatch found -> no change (never pad with generic prompt clauses).
summary = (
f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。"
if patches
else 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 and instruction.strip():
# Only an explicit admin instruction justifies a prompt edit without a detected signal.
base_sys = str(llm_node.get("system_prompt") or "").strip()
target_note = instruction.strip()
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": "按管理员调优目标加固提示词护栏。",
}
)
if not patches:
return "未检测到需要调整的信号,本轮无需修改。", []
summary = (
f"已针对「{instruction.strip()}」生成节点调优建议。"
if instruction.strip()
else "已结合近期运行失败/差评与健康度指标生成微调建议。"
)
return summary, patches
# Every (node, field) the meta-evolver may change must measurably alter the business proposal
# request built below; anything else would create versions that change nothing downstream.
META_EVOLVABLE_FIELDS: frozenset[tuple[str, str]] = frozenset(
{
("diag_node", "system_prompt"),
("diag_node", "prompt"),
("patch_node", "system_prompt"),
("patch_node", "prompt"),
("patch_node", "thinking_enabled"),
}
)
_DEFAULT_EVOLVER_SYSTEM_PROMPT = "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。"
_NO_CHANGE_CLAUSE = "若现有工作流已满足目标、无需调整,请返回空的 node_patches 数组,并在 summary 中说明理由。"
def build_business_evolution_request(
*,
workflow_id: str,
mode: str,
instruction: str,
diag_node: dict[str, Any],
patch_node: dict[str, Any],
schema: dict[str, Any],
context: dict[str, Any],
) -> SituationalAnalysisRequest:
"""Build the business-evolution LLM request from the live meta-evolver nodes."""
diag_sys = str(diag_node.get("system_prompt") or "").strip()
diag_prompt = str(diag_node.get("prompt") or "").strip()
patch_sys = str(patch_node.get("system_prompt") or "").strip()
patch_prompt = str(patch_node.get("prompt") or "").strip()
combined_sys = f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip() if (patch_sys or diag_sys) else ""
objective_parts = [
f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)",
f"工作流 ID:{workflow_id}",
f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}",
]
if diag_prompt:
objective_parts.append(f"[诊断任务]\n{diag_prompt}")
if patch_prompt:
objective_parts.append(f"[补丁任务]\n{patch_prompt}")
objective_parts.append(_NO_CHANGE_CLAUSE)
return SituationalAnalysisRequest(
title=f"Evolve workflow {workflow_id}",
objective="\n".join(objective_parts)[:16000],
system_prompt=(combined_sys or _DEFAULT_EVOLVER_SYSTEM_PROMPT)[:8000],
context=context,
thinking={"mode": "auto"} if bool(patch_node.get("thinking_enabled", True)) else {"mode": "off"},
response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}},
)
def _full_graph_diff(base_graph: dict[str, Any], proposed_graph: dict[str, Any]) -> list[dict[str, Any]]:
"""All node/edge differences between two graphs (layout positions ignored)."""
try:
base = _validate_graph_payload(base_graph)
proposed = _validate_graph_payload(proposed_graph)
except HTTPException:
return []
base_nodes = {str(n["id"]): n for n in base.get("nodes") or []}
prop_nodes = {str(n["id"]): n for n in proposed.get("nodes") or []}
changes: list[dict[str, Any]] = []
for nid in sorted(set(base_nodes) | set(prop_nodes)):
bnode, pnode = base_nodes.get(nid), prop_nodes.get(nid)
if bnode is None or pnode is None:
changes.append(
{
"node_id": nid,
"node_title": (pnode or bnode or {}).get("title") or nid,
"field": "__node__",
"before": None if bnode is None else "present",
"after": None if pnode is None else "present",
}
)
continue
for key in sorted(set(bnode) | set(pnode)):
if key == "position" or bnode.get(key) == pnode.get(key):
continue
changes.append(
{
"node_id": nid,
"node_title": pnode.get("title") or nid,
"field": key,
"before": copy.deepcopy(bnode.get(key)),
"after": copy.deepcopy(pnode.get(key)),
}
)
def _edge_keys(graph: dict[str, Any]) -> set[tuple[str, str, str]]:
return {
(str(e.get("source")), str(e.get("target")), str(e.get("condition") or "always"))
for e in graph.get("edges") or []
if isinstance(e, dict)
}
base_edges, prop_edges = _edge_keys(base), _edge_keys(proposed)
if base_edges != prop_edges:
changes.append(
{
"node_id": "__edges__",
"node_title": "edges",
"field": "edges",
"before": sorted(list(e) for e in base_edges - prop_edges),
"after": sorted(list(e) for e in prop_edges - base_edges),
}
)
return changes
def _no_change_result(
*,
workflow_id: str,
mode: str,
base_revision: int,
summary: str,
proposed_graph: dict[str, Any],
health: dict[str, Any] | None = None,
meta_revision: int | None = None,
) -> dict[str, Any]:
return {
"workflow_id": workflow_id,
"mode": mode,
"base_revision": base_revision,
"meta_revision": meta_revision,
"summary": summary,
"changes": [],
"changes_vs_live": [],
"proposed_graph": proposed_graph,
"constitution_ok": True,
"violations": [],
"applied_status": "no_change",
"new_revision": None,
"blocked_reason": "",
"ledger_entry": None,
"ab_eval": None,
"health": health,
}
def _ab_gate_allows_auto_publish(ab_eval: dict[str, Any]) -> tuple[bool, str]:
"""Auto-publish only when graded fixtures show the candidate is not worse than live."""
if int(ab_eval.get("fixture_count") or 0) == 0:
return False, "自动发布需先通过 A/B 门禁:当前工作流没有固定样本(Fixtures)。"
if int(ab_eval.get("graded_fixture_count") or 0) == 0:
return False, "自动发布需先通过 A/B 门禁:固定样本均未设置可判对错的断言(expect),无法证明候选版本不退化。"
regressions = list(ab_eval.get("regressions") or [])
if regressions:
return False, f"A/B 门禁未通过:{len(regressions)} 条样本在候选版本上退化({', '.join(regressions[:3])})。"
verdict = str(ab_eval.get("verdict") or "")
if verdict in {"regressed", "slower"}:
return False, f"A/B 门禁未通过(判定:{verdict})。"
return True, ""
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)
live_graph = copy.deepcopy(wf.published_graph or {})
# Only an admin explicitly tuning into a draft may build on their own unpublished draft.
# Background / auto-publish evolution always starts from the live revision so it can never
# smuggle unpublished human edits into production or clear them.
builds_on_human_draft = trigger == "manual" and apply_mode != "auto" and wf.draft_graph is not None
base_graph = copy.deepcopy(wf.draft_graph if builds_on_human_draft else live_graph)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
# 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)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
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]] = []
ai_decided = False
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"],
}
req = build_business_evolution_request(
workflow_id=workflow_id,
mode=mode,
instruction=instruction,
diag_node=diag_node,
patch_node=patch_node,
schema=schema,
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,
},
)
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"]
# A valid, explicitly empty patch list means "no change needed" — honour it.
ai_decided = True
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 ai_decided:
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)
if not diffs:
return _no_change_result(
workflow_id=workflow_id,
mode=mode,
base_revision=parent_revision,
summary=summary or "引擎判断当前工作流无需修改。",
proposed_graph=proposed_graph,
health=health,
)
is_auto_apply = apply_mode == "auto"
# Everything that would actually ship, measured against the live revision (not just engine patches).
changes_vs_live = _full_graph_diff(live_graph, proposed_graph)
constitution_ok, violations = validate_evolution_patch(
live_graph if is_auto_apply else base_graph,
proposed_graph,
changes_vs_live if is_auto_apply else diffs,
is_meta=False,
is_auto=is_auto_apply,
)
applied_status = "preview"
new_revision = None
blocked_reason = ""
ledger_entry: dict[str, Any] | None = None
ab_eval: dict[str, Any] | None = None
if apply_mode == "draft":
if trigger != "manual" and wf.draft_graph is not None:
# Never overwrite an admin's unpublished draft from a background run.
applied_status = "skipped"
blocked_reason = "存在未发布的人工草稿,自动进化不覆盖草稿,本轮跳过。"
elif not constitution_ok:
applied_status = "blocked"
blocked_reason = ";".join(violations)
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,
"changes_vs_live": changes_vs_live,
"built_on_human_draft": builds_on_human_draft,
},
)
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:
applied_status = "blocked"
blocked_reason = ";".join(violations)
else:
# Auto-publish must prove on graded fixtures that the candidate is not worse than live.
ab_eval = await run_fixture_ab_eval(db, workflow_id, proposed_graph, max_fixtures=5)
gate_ok, gate_msg = _ab_gate_allows_auto_publish(ab_eval)
if not gate_ok:
applied_status = "blocked"
blocked_reason = gate_msg
if applied_status != "blocked":
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",
keep_draft=True,
)
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,
"changes_vs_live": changes_vs_live,
"ab_eval_summary": (ab_eval or {}).get("summary"),
},
)
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,
"changes_vs_live": changes_vs_live,
},
)
return {
"workflow_id": workflow_id,
"mode": mode,
"base_revision": parent_revision,
"meta_revision": meta_revision,
"summary": summary or "暂无需要变更的字段。",
"changes": diffs,
"changes_vs_live": changes_vs_live,
"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,
"ab_eval": ab_eval,
"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] = []
verification: dict[str, Any] = {}
evidence_count = 0
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 [])]
if isinstance(ev_data.get("verification"), dict):
verification = ev_data["verification"]
if isinstance(ev_data.get("evidence"), dict):
evidence_count = len(ev_data["evidence"])
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 {
"answer": answer,
"latency_ms": latency_ms,
"answer_length": len(answer.strip()),
"nodes": nodes_done,
"error": err,
"verification_passed": bool(verification.get("passed", True)),
"verification_warnings": list(verification.get("warnings") or []),
"evidence_count": evidence_count,
}
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")
builds_on_human_draft = trigger == "meta_manual" and apply_mode != "auto" and meta_wf.draft_graph is not None
base_graph = copy.deepcopy(
meta_wf.draft_graph if builds_on_human_draft else (meta_wf.published_graph or {})
)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
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]] = []
meta_ai_decided = False
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` 的 system_prompt/prompt,或 `patch_node` 的 system_prompt/prompt/thinking_enabled;"
"严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。\n"
f"{_NO_CHANGE_CLAUSE}"
),
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"]
meta_ai_decided = True
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 meta_ai_decided and (instruction.strip() or outcomes):
# Deterministic refinement needs a real basis: an admin instruction or ledger outcomes.
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})生成元引擎自举方案。"
)
# Drop patches to fields that have no downstream effect on the business proposal request.
raw_patches = [
p
for p in raw_patches
if isinstance(p, dict)
and (str(p.get("node_id") or ""), str(p.get("field") or "")) in META_EVOLVABLE_FIELDS
]
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
if not diffs:
return {
**_no_change_result(
workflow_id=META_WORKFLOW_ID,
mode="meta",
base_revision=int(meta_wf.active_revision or 1),
summary=summary or "元引擎判断当前策略无需修改(暂无进化台账结果或明确指示)。",
proposed_graph=proposed_graph,
),
"outcomes_analyzed": len(outcomes),
}
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 trigger != "meta_manual" and meta_wf.draft_graph is not None:
applied_status = "skipped"
blocked_reason = "存在未发布的人工元引擎草稿,自动元进化不覆盖草稿,本轮跳过。"
elif not constitution_ok:
applied_status = "blocked"
blocked_reason = ";".join(violations)
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:
applied_status = "blocked"
blocked_reason = ";".join(violations)
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,
keep_draft=True,
)
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))