Files
planet/backend/app/api/v1/ai_workflows.py
T

515 lines
20 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
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, SituationalAnalysisRequest
from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.ai.workflow_registry import (
ensure_builtin_workflows,
generate_workflow_optimization_proposal,
get_workflow_detail,
list_workflows,
publish_workflow,
resolve_runtime_workflow_node,
rollback_workflow,
save_workflow_draft,
)
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]
class WorkflowPublishRequest(BaseModel):
graph: dict[str, Any] | None = None
change_summary: str = ""
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 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 AdvisorPlaygroundChatRequest(BaseModel):
workflow_id: str = "default.general"
use_draft: bool = False
message: str = Field(..., min_length=1, max_length=16000)
history: list[AdvisorChatMessageInput] = Field(default_factory=list)
earth_context: dict[str, Any] | None = None
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/{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,
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,
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,
limit: int = Query(50, ge=1, le=200),
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
stmt = select(WorkflowRun).order_by(desc(WorkflowRun.started_at)).limit(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()
items = [row.to_dict() for row in rows]
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()
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 = "ops.bgp_brief"
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 = "ops.alerts_brief"
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 = "ops.situational_alerts_brief"
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}"
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
@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`)."""
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 = ""
try:
active_wf, tool_trace, req, extra_meta = await _resolve_playground_slash_or_workflow(
db=db,
workflow_id=active_wf,
message=payload.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 != "direct_reply"},
},
)
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"])
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 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_model = await provider_client.is_ready()
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),
},
)
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:
db.add(
WorkflowRun(
id=run_id,
workflow_id=active_wf,
status=status_value,
access_tier="admin",
actor_key=_actor_label(admin),
question=payload.message[:500],
input_params={
"use_draft": payload.use_draft,
"model_override": payload.model_override,
"has_earth_context": bool(payload.earth_context),
},
tool_trace=tool_trace,
budget_used={"steps": len(tool_trace)},
error_message=error_text[:500],
started_at=started_at,
completed_at=datetime.now(UTC),
)
)
await db.commit()
except Exception:
try:
await db.rollback()
except Exception:
pass
return StreamingResponse(event_stream(), media_type="text/event-stream")