Files
planet/backend/app/api/v1/ai_workflows.py
T
linkong 04cebdc504
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.82.0
2026-12-01 18:43:57 +08:00

1054 lines
39 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.
"""Admin AI Advisor workflow management, run history, and pure-chat Playground SSE endpoints."""
from __future__ import annotations
from datetime import UTC, datetime
import json
from typing import Any, Literal
from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.ai_tasks.prompts import reset_prompt_override
from app.core.access_gate import require_admin_user
from app.core.logging import get_logger
from app.db.session import get_db
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture
from app.models.situational_assessment import WorkflowRun
from app.models.user import User
from app.schemas.ai import ChatMessage, ImageAttachment, 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.tool_registry import (
SSRFBlockedError,
isolate_untrusted_external_text,
safe_web_fetch,
)
from app.services.ai.workflow_evolver import (
compute_workflow_health,
dismiss_ledger_entry,
get_evolution_ledger,
get_evolution_policy,
incubate_workflow_from_runs,
propose_meta_evolution,
propose_workflow_evolution,
record_run_feedback,
run_fixture_ab_eval,
schedule_post_run_evolution,
update_evolution_policy,
)
from app.services.ai.workflow_registry import (
clone_workflow,
create_workflow,
delete_workflow,
discard_workflow_draft,
ensure_builtin_workflows,
generate_workflow_optimization_proposal,
get_workflow_detail,
list_public_workflow_bindings,
list_workflows,
publish_workflow,
resolve_runtime_workflow_node,
rollback_workflow,
save_workflow_draft,
update_workflow_metadata,
)
from app.services.ai_client import get_ai_provider_client
from app.services.alert_ai_brief import build_alert_brief_request
from app.services.bgp_ai_brief import build_bgp_brief_request
from app.services.compute_center_locations import build_compute_center_location_query
from app.services.location.agent_resolver import (
run_controlled_location_agent,
run_l1_structured_facility_resolvers,
)
from app.services.situational_alert_ai_brief import build_situational_alert_brief_request
from app.api.v1.settings import get_web_search_client
router = APIRouter()
logger = get_logger(__name__, service="ai_workflows")
class WorkflowDraftUpdateRequest(BaseModel):
graph: dict[str, Any]
bindings: dict[str, Any] | None = None
name: str | None = None
description: str | None = None
class WorkflowPublishRequest(BaseModel):
graph: dict[str, Any] | None = None
bindings: dict[str, Any] | None = None
name: str | None = None
description: str | None = None
change_summary: str = ""
class WorkflowCreateRequest(BaseModel):
workflow_id: str | None = Field(default=None, max_length=80)
name: str = Field(..., min_length=1, max_length=160)
name_en: str = Field(default="", max_length=160)
category: str = Field(default="custom", max_length=60)
description: str = Field(default="", max_length=2000)
description_en: str = Field(default="", max_length=2000)
graph: dict[str, Any] | None = None
bindings: dict[str, Any] | None = None
class WorkflowCloneRequest(BaseModel):
workflow_id: str | None = Field(default=None, max_length=80)
name: str | None = Field(default=None, max_length=160)
name_en: str | None = Field(default=None, max_length=160)
class WorkflowMetadataUpdateRequest(BaseModel):
name: str | None = Field(default=None, max_length=160)
name_en: str | None = Field(default=None, max_length=160)
category: str | None = Field(default=None, max_length=60)
description: str | None = Field(default=None, max_length=2000)
description_en: str | None = Field(default=None, max_length=2000)
bindings: dict[str, Any] | None = None
class EarthTargetInput(BaseModel):
entity_type: str = Field(..., min_length=1, max_length=64)
entity_id: str | None = Field(default=None, max_length=160)
label: str = Field(default="", max_length=200)
latitude: float | None = None
longitude: float | None = None
layer: str | None = Field(default=None, max_length=80)
kind: str | None = Field(default=None, max_length=80)
properties: dict[str, Any] = Field(default_factory=dict)
class WorkflowRollbackRequest(BaseModel):
revision: int = Field(..., ge=1)
class WorkflowOptimizeRequest(BaseModel):
instruction: str = Field(..., min_length=1, max_length=2000)
run_id: str | None = None
class WorkflowRunFeedbackRequest(BaseModel):
rating: Literal[-1, 0, 1]
note: str = Field(default="", max_length=500)
class EvolutionPolicyUpdateRequest(BaseModel):
business_mode: Literal["off", "draft", "auto"] | None = None
meta_mode: Literal["off", "draft", "auto"] | None = None
daily_auto_budget: int | None = Field(default=None, ge=1, le=20)
business_cooldown_hours: int | None = Field(default=None, ge=1, le=168)
meta_cooldown_days: int | None = Field(default=None, ge=1, le=30)
locked_workflows: list[str] | None = None
auto_adapt_on_model_change: bool | None = None
class EvolutionProposeRequest(BaseModel):
mode: Literal["optimize", "model_adapt"] = "optimize"
instruction: str = Field(default="", max_length=2000)
run_id: str | None = None
apply_mode: Literal["preview", "draft", "auto"] = "preview"
branch_from_best: bool = False
class EvolutionEvalRequest(BaseModel):
proposed_graph: dict[str, Any]
max_fixtures: int = Field(default=3, ge=1, le=5)
class MetaEvolveRequest(BaseModel):
instruction: str = Field(default="", max_length=2000)
apply_mode: Literal["preview", "draft", "auto"] = "preview"
class LedgerDismissRequest(BaseModel):
reason: str = Field(default="", max_length=300)
class WorkflowFixtureCreateRequest(BaseModel):
name: str = Field(..., min_length=1, max_length=160)
description: str = ""
earth_context: dict[str, Any] = Field(default_factory=dict)
context_json: dict[str, Any] | None = None
sample_question: str = ""
class AdvisorChatMessageInput(BaseModel):
role: str = Field(..., pattern="^(user|assistant)$")
content: str = Field(..., min_length=1, max_length=16000)
class PlaygroundLinkParseRequest(BaseModel):
url: str = Field(..., min_length=4, max_length=2000)
class PlaygroundAttachmentInput(BaseModel):
kind: Literal["image", "video", "link", "json", "text"]
name: str = Field(default="", max_length=240)
mime_type: str = Field(default="", max_length=120)
url: str | None = Field(default=None, max_length=2000)
text_content: str | None = Field(default=None, max_length=32000)
json_data: Any = None
images: list[ImageAttachment] = Field(default_factory=list, max_length=6)
metadata: dict[str, Any] = Field(default_factory=dict)
class AdvisorPlaygroundChatRequest(BaseModel):
workflow_id: str = "default.general"
use_draft: bool = False
message: str = Field(default="", max_length=16000)
history: list[AdvisorChatMessageInput] = Field(default_factory=list)
earth_context: dict[str, Any] | None = None
attachments: list[PlaygroundAttachmentInput] = Field(default_factory=list, max_length=8)
targets: list[EarthTargetInput] = Field(default_factory=list, max_length=8)
model_override: str | None = None
def _sse_frame(event: str, payload: dict[str, Any]) -> str:
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
def _actor_label(user: User) -> str:
return str(getattr(user, "username", None) or getattr(user, "email", None) or f"user:{user.id}")
@router.get("/workflows")
async def list_ai_workflows(
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
items = await list_workflows(db)
return {"items": items, "total": len(items)}
@router.get("/workflows/bindings")
async def get_public_earth_workflow_bindings(
db: AsyncSession = Depends(get_db),
):
"""Public-safe list of enabled published workflows and their Earth interaction bindings."""
items = await list_public_workflow_bindings(db)
return {"items": items, "total": len(items)}
@router.post("/workflows")
async def create_ai_workflow(
payload: WorkflowCreateRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await create_workflow(
db,
workflow_id=payload.workflow_id,
name=payload.name,
name_en=payload.name_en,
category=payload.category,
description=payload.description,
description_en=payload.description_en,
graph=payload.graph,
bindings=payload.bindings,
actor=_actor_label(admin),
)
@router.post("/workflows/{workflow_id}/clone")
async def clone_ai_workflow(
workflow_id: str,
payload: WorkflowCloneRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await clone_workflow(
db,
workflow_id,
workflow_id=payload.workflow_id,
name=payload.name,
name_en=payload.name_en,
actor=_actor_label(admin),
)
@router.patch("/workflows/{workflow_id}")
async def patch_ai_workflow_metadata(
workflow_id: str,
payload: WorkflowMetadataUpdateRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await update_workflow_metadata(
db,
workflow_id,
name=payload.name,
name_en=payload.name_en,
category=payload.category,
description=payload.description,
description_en=payload.description_en,
bindings=payload.bindings,
actor=_actor_label(admin),
)
@router.delete("/workflows/{workflow_id}")
async def delete_ai_workflow(
workflow_id: str,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await delete_workflow(db, workflow_id)
@router.get("/workflows/{workflow_id}")
async def get_ai_workflow_detail(
workflow_id: str,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await get_workflow_detail(db, workflow_id)
@router.put("/workflows/{workflow_id}/draft")
async def update_ai_workflow_draft(
workflow_id: str,
payload: WorkflowDraftUpdateRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await save_workflow_draft(
db,
workflow_id,
payload.graph,
bindings=payload.bindings,
name=payload.name,
description=payload.description,
actor=_actor_label(admin),
)
@router.delete("/workflows/{workflow_id}/draft")
async def discard_ai_workflow_draft(
workflow_id: str,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await discard_workflow_draft(
db,
workflow_id,
actor=_actor_label(admin),
)
@router.post("/workflows/{workflow_id}/publish")
async def publish_ai_workflow(
workflow_id: str,
payload: WorkflowPublishRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
published = await publish_workflow(
db,
workflow_id,
graph=payload.graph,
bindings=payload.bindings,
name=payload.name,
description=payload.description,
change_summary=payload.change_summary,
actor=_actor_label(admin),
)
# Clear matching legacy SystemSetting prompt overrides so published workflow prompts win cleanly.
for node in (published.get("published_graph") or {}).get("nodes") or []:
prompt_key = str((node or {}).get("prompt_key") or "").strip()
if prompt_key:
try:
await reset_prompt_override(db, prompt_key)
except Exception:
continue
return published
@router.post("/workflows/{workflow_id}/rollback")
async def rollback_ai_workflow(
workflow_id: str,
payload: WorkflowRollbackRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await rollback_workflow(
db,
workflow_id,
payload.revision,
actor=_actor_label(admin),
)
@router.post("/workflows/{workflow_id}/optimize")
async def optimize_ai_workflow(
workflow_id: str,
payload: WorkflowOptimizeRequest,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
ai_client = None
try:
ai_client = await get_ai_provider_client(db)
except Exception:
ai_client = None
return await generate_workflow_optimization_proposal(
db,
workflow_id,
instruction=payload.instruction,
run_id=payload.run_id,
ai_client=ai_client,
)
@router.post("/workflows/{workflow_id}/fixtures")
async def create_ai_workflow_fixture(
workflow_id: str,
payload: WorkflowFixtureCreateRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
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")
ctx_payload = dict(payload.context_json if payload.context_json is not None else payload.earth_context or {})
if payload.description.strip() and "_description" not in ctx_payload:
ctx_payload["_description"] = payload.description.strip()
row = AIWorkflowFixture(
workflow_id=workflow_id,
name=payload.name.strip(),
sample_question=payload.sample_question.strip(),
context_json=ctx_payload,
created_by=_actor_label(admin),
)
db.add(row)
await db.commit()
await db.refresh(row)
return row.to_dict()
@router.delete("/workflows/{workflow_id}/fixtures/{fixture_id}")
async def delete_ai_workflow_fixture(
workflow_id: str,
fixture_id: int,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
row = (
await db.execute(
select(AIWorkflowFixture)
.where(AIWorkflowFixture.id == fixture_id)
.where(AIWorkflowFixture.workflow_id == workflow_id)
)
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail="Fixture not found")
await db.delete(row)
await db.commit()
return {"deleted": True, "id": fixture_id}
@router.get("/runs")
async def list_ai_workflow_runs(
workflow_id: str | None = None,
status: str | None = None,
feedback: Literal["negative", "positive"] | None = None,
limit: int = Query(50, ge=1, le=200),
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
fetch_limit = min(400, limit * 3) if feedback else limit
stmt = select(WorkflowRun).order_by(desc(WorkflowRun.started_at)).limit(fetch_limit)
if workflow_id:
stmt = stmt.where(WorkflowRun.workflow_id == workflow_id)
if status:
stmt = stmt.where(WorkflowRun.status == status)
rows = (await db.execute(stmt)).scalars().all()
if feedback == "negative":
rows = [
row
for row in rows
if row.status == "failed" or int((row.budget_used or {}).get("user_rating") or 0) == -1
]
elif feedback == "positive":
rows = [
row
for row in rows
if int((row.budget_used or {}).get("user_rating") or 0) == 1
]
items = [row.to_dict() for row in rows[:limit]]
return {"items": items, "total": len(items)}
@router.get("/runs/{run_id}")
async def get_ai_workflow_run_detail(
run_id: str,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
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="Workflow run not found")
return row.to_dict()
@router.post("/runs/{run_id}/feedback")
async def submit_ai_workflow_run_feedback(
run_id: str,
payload: WorkflowRunFeedbackRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await record_run_feedback(
db,
run_id,
rating=payload.rating,
note=payload.note,
actor=_actor_label(admin),
)
@router.get("/evolution/policy")
async def get_ai_evolution_policy(
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await get_evolution_policy(db)
@router.put("/evolution/policy")
async def update_ai_evolution_policy(
payload: EvolutionPolicyUpdateRequest,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await update_evolution_policy(db, payload.model_dump(exclude_none=True))
@router.get("/evolution/ledger")
async def list_ai_evolution_ledger(
workflow_id: str | None = None,
limit: int = Query(30, ge=1, le=50),
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
items = await get_evolution_ledger(db, workflow_id=workflow_id, limit=limit)
return {"items": items, "total": len(items)}
@router.post("/evolution/ledger/{entry_id}/dismiss")
async def dismiss_ai_evolution_ledger_entry(
entry_id: str,
payload: LedgerDismissRequest | None = None,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await dismiss_ledger_entry(
db,
entry_id,
reason=(payload.reason if payload else ""),
)
@router.get("/evolution/health/{workflow_id}")
async def get_ai_workflow_evolution_health(
workflow_id: str,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
ai_client = None
try:
ai_client = await get_ai_provider_client(db)
except Exception:
ai_client = None
return await compute_workflow_health(db, workflow_id, ai_client=ai_client)
@router.post("/evolution/propose/{workflow_id}")
async def propose_ai_workflow_evolution(
workflow_id: str,
payload: EvolutionProposeRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
ai_client = None
try:
ai_client = await get_ai_provider_client(db)
except Exception:
ai_client = None
return await propose_workflow_evolution(
db,
workflow_id,
mode=payload.mode,
instruction=payload.instruction,
run_id=payload.run_id,
apply_mode=payload.apply_mode,
trigger="manual",
branch_from_best=payload.branch_from_best,
ai_client=ai_client,
actor=_actor_label(admin),
)
@router.post("/evolution/eval/{workflow_id}")
async def evaluate_ai_workflow_fixtures(
workflow_id: str,
payload: EvolutionEvalRequest,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
return await run_fixture_ab_eval(
db,
workflow_id,
payload.proposed_graph,
max_fixtures=payload.max_fixtures,
)
@router.post("/evolution/incubate")
async def incubate_ai_workflow_candidate(
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
ai_client = None
try:
ai_client = await get_ai_provider_client(db)
except Exception:
ai_client = None
return await incubate_workflow_from_runs(db, ai_client=ai_client)
@router.post("/evolution/meta-evolve")
async def propose_ai_meta_evolution(
payload: MetaEvolveRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
ai_client = None
try:
ai_client = await get_ai_provider_client(db)
except Exception:
ai_client = None
return await propose_meta_evolution(
db,
instruction=payload.instruction,
apply_mode=payload.apply_mode,
trigger="meta_manual",
ai_client=ai_client,
actor=_actor_label(admin),
)
async def _resolve_playground_slash_or_workflow(
*,
db: AsyncSession,
workflow_id: str,
message: str,
use_draft: bool,
earth_context: dict[str, Any] | None,
) -> tuple[str, list[str], SituationalAnalysisRequest | None, dict[str, Any]]:
"""Map slash commands or selected workflow into a runnable prompt/context bundle."""
trimmed = message.strip()
active_wf = workflow_id or "default.general"
tool_trace: list[str] = ["intake"]
extra_meta: dict[str, Any] = {}
if trimmed.startswith("/bgp-brief"):
active_wf = "brief.bgp"
req, facts, ctx = await build_bgp_brief_request(db)
tool_trace.extend(["query_bgp_incidents", "query_bgp_anomalies", "synthesize"])
extra_meta["facts"] = facts
extra_meta["context_keys"] = sorted((ctx or {}).keys())
return active_wf, tool_trace, req, extra_meta
if trimmed.startswith("/alerts-brief"):
active_wf = "brief.alerts"
req, facts, ctx = await build_alert_brief_request(db)
tool_trace.extend(["query_system_alerts", "synthesize"])
extra_meta["facts"] = facts
extra_meta["context_keys"] = sorted((ctx or {}).keys())
return active_wf, tool_trace, req, extra_meta
if trimmed.startswith("/situational-brief"):
active_wf = "brief.alerts"
req, facts, ctx = await build_situational_alert_brief_request(db)
tool_trace.extend(["query_system_alerts", "query_bgp_incidents", "synthesize"])
extra_meta["facts"] = facts
extra_meta["context_keys"] = sorted((ctx or {}).keys())
return active_wf, tool_trace, req, extra_meta
if trimmed.startswith("/locate"):
active_wf = "location.resolve_unknown"
target_name = trimmed[len("/locate") :].strip() or "Unknown Facility"
query = build_compute_center_location_query(name=target_name)
l1_candidates, _, _ = await run_l1_structured_facility_resolvers(query, db=db)
tool_trace.extend(["l0_normalize", "l1_knowledge"])
if l1_candidates:
c0 = l1_candidates[0]
extra_meta["direct_reply"] = (
f"已通过 **L1 设施知识库** (`{c0.source}`) 定位到 **{c0.display_name}**:\n\n"
f"- 国家/地区:{c0.country or '-'}\n"
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`,置信度 `{c0.confidence:.2f}`)\n"
f"- 说明:{c0.source_note}"
)
return active_wf, tool_trace, None, extra_meta
try:
provider_client = await get_ai_provider_client(db)
web_search_client = await get_web_search_client(db)
res, term = await run_controlled_location_agent(
provider_client=provider_client,
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
db=db,
)
tool_trace.extend(["l2_agent_research", "l3_geo_guardrail"])
if res.candidates:
c0 = res.candidates[0]
extra_meta["direct_reply"] = (
f"已通过 **L2/L3 位置 Agent** 核验 **{c0.display_name}**:\n\n"
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`)\n"
f"- 结论:{c0.source_note}"
)
elif term:
extra_meta["direct_reply"] = f"位置 Agent 判定该目标属于终态 `{term}`:{res.failure_reason or ''}"
else:
extra_meta["direct_reply"] = f"未能定位目标「{target_name}」:{res.failure_reason or '暂无可核验公开证据'}。"
except Exception as exc:
extra_meta["direct_reply"] = f"位置 Agent 调试执行失败:{exc}"
extra_meta["direct_reply_error"] = str(exc)
return active_wf, tool_trace, None, extra_meta
detail = await get_workflow_detail(db, active_wf)
wf_obj = detail["workflow"]
graph = (wf_obj.get("draft_graph") if use_draft and wf_obj.get("draft_graph") else wf_obj.get("published_graph")) or {}
nodes = graph.get("nodes") or []
llm_node = next((n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}), nodes[0] if nodes else {})
# Apply node configuration from graph (or fallback)
node_cfg = await resolve_runtime_workflow_node(
db,
active_wf,
str(llm_node.get("id") or "default_advisor"),
use_draft=use_draft,
) or llm_node
for n in nodes:
nid = str(n.get("id") or "")
if nid and nid not in tool_trace:
tool_trace.append(nid)
ctx_payload: dict[str, Any] = {}
if isinstance(earth_context, dict) and earth_context:
ctx_payload["earth_context"] = earth_context
extra_meta["earth_context_attached"] = True
sys_prompt = str(node_cfg.get("system_prompt") or "").strip() or (
"你是智能星球 AI 参谋调试助手。结合附带的地球本地上下文(如有)和用户问题给出严谨、清晰的中文回复。"
)
node_prompt = str(node_cfg.get("prompt") or "").strip()
objective = f"{node_prompt}\n\n用户请求:{trimmed}" if node_prompt else trimmed
req = SituationalAnalysisRequest(
title=f"AI Advisor ({wf_obj.get('name') or active_wf})",
objective=objective,
system_prompt=sys_prompt,
context=ctx_payload,
preferred_model=str(node_cfg.get("model_override") or "") or None,
thinking={"mode": "auto"} if bool(node_cfg.get("thinking_enabled", True)) else {"mode": "off"},
native_web_search=bool(node_cfg.get("native_web_search", False)),
)
return active_wf, tool_trace, req, extra_meta
def _normalize_playground_attachments(
attachments: list[PlaygroundAttachmentInput],
) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
"""Extract prompt-safe attachment summaries and capped multimodal image blocks."""
structured: list[dict[str, Any]] = []
images: list[dict[str, str]] = []
for item in attachments[:8]:
entry: dict[str, Any] = {
"kind": item.kind,
"name": item.name or item.url or item.kind,
}
if item.mime_type:
entry["mime_type"] = item.mime_type
if item.metadata:
entry["metadata"] = item.metadata
if item.kind == "link" and item.url:
entry["url"] = item.url
if item.text_content:
entry["fetched_content"] = isolate_untrusted_external_text(
item.url,
item.name or item.url,
item.text_content,
max_chars=4000,
)
elif item.kind == "json" and item.json_data is not None:
raw_json = json.dumps(item.json_data, ensure_ascii=False, default=str)
entry["json_preview"] = raw_json[:8000]
elif item.kind in {"text", "json"} and item.text_content:
entry["text_preview"] = item.text_content[:8000]
for img in item.images or []:
if len(images) >= 8:
break
images.append(
{
"mime_type": img.mime_type,
"data_base64": img.data_base64,
"name": img.name or item.name,
}
)
if item.images:
entry["image_frames_attached"] = len(item.images)
structured.append(entry)
return structured, images
@router.post("/playground/parse-link")
async def parse_playground_link(
payload: PlaygroundLinkParseRequest,
_admin: User = Depends(require_admin_user),
):
"""Fetch a public HTTP/HTTPS web page with SSRF validation and extract readable text."""
try:
fetched = await safe_web_fetch(payload.url.strip(), timeout_seconds=10)
except SSRFBlockedError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Failed to fetch URL: {exc}") from exc
clean_text = (fetched.text or "")[:12000]
excerpt = clean_text[:320].strip()
return {
"url": fetched.url,
"final_url": fetched.final_url,
"title": fetched.title or fetched.final_url,
"text": clean_text,
"excerpt": excerpt,
"char_count": len(clean_text),
"content_hash": fetched.content_hash,
}
@router.post("/playground/chat/stream")
async def stream_advisor_playground_chat(
payload: AdvisorPlaygroundChatRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
"""Stream AI Advisor Playground execution over SSE (`meta`, `node`, `reasoning`, `text`, `done`, `error`)."""
raw_msg = payload.message.strip()
if not raw_msg and not payload.attachments:
raise HTTPException(status_code=422, detail="Message or attachment is required")
effective_message = raw_msg or "请结合我上传的附件进行分析。"
attachment_summaries, attachment_images = _normalize_playground_attachments(payload.attachments)
run_id = f"run_{uuid4().hex[:16]}"
started_at = datetime.now(UTC)
async def event_stream():
active_wf = payload.workflow_id or "default.general"
tool_trace: list[str] = []
status_value = "completed"
error_text = ""
resolved_model = str(payload.model_override or "").strip()
resolved_provider = ""
workflow_revision = 1
is_slash_cmd = effective_message.strip().startswith(
("/bgp-brief", "/alerts-brief", "/situational-brief", "/locate")
)
try:
if is_slash_cmd:
active_wf, tool_trace, req, extra_meta = await _resolve_playground_slash_or_workflow(
db=db,
workflow_id=active_wf,
message=effective_message,
use_draft=payload.use_draft,
earth_context=payload.earth_context,
)
yield _sse_frame(
"meta",
{
"run_id": run_id,
"workflow_id": active_wf,
"use_draft": payload.use_draft,
"nodes": tool_trace,
**{
k: v
for k, v in extra_meta.items()
if k not in {"direct_reply", "direct_reply_error"}
},
},
)
for node_id in tool_trace:
yield _sse_frame("node", {"node_id": node_id, "status": "completed"})
if "direct_reply" in extra_meta:
reply = str(extra_meta["direct_reply"])
if extra_meta.get("direct_reply_error"):
status_value = "failed"
error_text = str(extra_meta["direct_reply_error"])
yield _sse_frame("text", {"delta": reply})
yield _sse_frame("done", {"run_id": run_id, "workflow_id": active_wf, "nodes": tool_trace})
return
if req is not None:
if attachment_summaries:
req.context = {**(req.context or {}), "attachments": attachment_summaries}
if attachment_images:
req.images = [
ImageAttachment.model_validate(img) for img in attachment_images[:8]
]
if payload.model_override:
req.preferred_model = payload.model_override.strip()
if payload.history:
req.messages = [
ChatMessage(role=m.role, content=m.content) # type: ignore[arg-type]
for m in payload.history[-12:]
]
provider_client = await get_ai_provider_client(db)
ready, active_provider, active_model = await provider_client.is_ready()
resolved_provider = resolved_provider or str(active_provider or "")
resolved_model = resolved_model or str(active_model or "")
if not ready:
status_value = "failed"
error_text = "AI Provider 尚未配置可用密钥或服务地址,请前往「运维与配置 → AI」检查。"
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
return
full_text_parts: list[str] = []
async for item in provider_client.stream_analyze(req, request_id=run_id):
ev = str(item.get("event") or "")
if ev == "reasoning" and item.get("delta"):
yield _sse_frame("reasoning", {"delta": str(item["delta"])})
elif ev == "text" and item.get("delta"):
delta = str(item["delta"])
full_text_parts.append(delta)
yield _sse_frame("text", {"delta": delta})
elif ev == "error":
status_value = "failed"
error_text = str(item.get("message") or "Streaming error")
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
return
cleaned, _ = strip_thinking_text("".join(full_text_parts))
yield _sse_frame(
"done",
{
"run_id": run_id,
"workflow_id": active_wf,
"model": payload.model_override or active_model,
"nodes": tool_trace,
"text_length": len(cleaned),
},
)
return
detail = await get_workflow_detail(db, active_wf)
wf_obj = detail["workflow"]
workflow_revision = int(wf_obj.get("active_revision") or 1)
provider_client = None
try:
provider_client = await get_ai_provider_client(db)
except Exception:
provider_client = None
targets_list = [t.model_dump() for t in payload.targets]
history_list = [{"role": m.role, "content": m.content} for m in payload.history[-12:]]
async for item in run_workflow_dag_stream(
db=db,
workflow=wf_obj,
question=effective_message,
use_draft=payload.use_draft,
targets=targets_list,
earth_context=payload.earth_context,
attachments=attachment_summaries,
images=attachment_images,
history=history_list,
ai_client=provider_client,
run_id=run_id,
model_override=payload.model_override,
allow_external_tools=True,
extra_meta={
"earth_context_attached": bool(payload.earth_context),
"attachments_count": len(attachment_summaries),
},
):
ev_name = str(item.get("event") or "")
ev_data = dict(item.get("data") or {})
if ev_name == "node" and ev_data.get("status") == "completed":
nid = str(ev_data.get("node_id") or "")
if nid and nid not in tool_trace:
tool_trace.append(nid)
elif ev_name == "done":
if isinstance(ev_data.get("nodes"), list):
tool_trace = [str(n) for n in ev_data["nodes"] if n]
if ev_data.get("model"):
resolved_model = str(ev_data["model"])
if ev_data.get("provider"):
resolved_provider = str(ev_data["provider"])
elif ev_name == "error":
status_value = "failed"
error_text = str(ev_data.get("message") or "Workflow execution failed")
yield _sse_frame(ev_name, ev_data)
except Exception as exc:
status_value = "failed"
error_text = str(exc)
logger.warning_event(
"Advisor playground SSE stream failed",
event="ai_workflows.playground.stream_failed",
context={"run_id": run_id, "workflow_id": active_wf, "error": error_text},
)
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
finally:
try:
completed_at = datetime.now(UTC)
latency_ms = max(0, int((completed_at - started_at).total_seconds() * 1000))
db.add(
WorkflowRun(
id=run_id,
workflow_id=active_wf,
status=status_value,
access_tier="admin",
actor_key=_actor_label(admin),
question=effective_message[:500],
input_params={
"use_draft": payload.use_draft,
"model_override": payload.model_override,
"has_earth_context": bool(payload.earth_context),
"attachments_count": len(attachment_summaries),
"targets_count": len(payload.targets),
},
tool_trace=tool_trace,
budget_used={
"steps": len(tool_trace),
"model_used": resolved_model,
"provider": resolved_provider,
"latency_ms": latency_ms,
"workflow_revision": workflow_revision,
},
error_message=error_text[:500],
started_at=started_at,
completed_at=completed_at,
)
)
await db.commit()
if not payload.use_draft:
schedule_post_run_evolution(active_wf, run_id)
except Exception:
try:
await db.rollback()
except Exception:
pass
return StreamingResponse(event_stream(), media_type="text/event-stream")