181 lines
7.0 KiB
Python
181 lines
7.0 KiB
Python
from __future__ import annotations
|
||
|
||
from collections import Counter
|
||
from datetime import UTC, datetime, timedelta
|
||
from typing import Any
|
||
|
||
from sqlalchemy import func, select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from app.models.alert import Alert, AlertStatus
|
||
from app.models.datasource import DataSource
|
||
from app.models.task import CollectionTask
|
||
from app.schemas.ai import SituationalAnalysisRequest
|
||
from app.ai_tasks.prompts import get_effective_prompt
|
||
|
||
ALERT_BRIEF_PROMPT_KEY = "alerts.brief"
|
||
|
||
|
||
def _format_counter(counter: Counter[str], empty_text: str = "无") -> str:
|
||
if not counter:
|
||
return empty_text
|
||
return ",".join(f"{key} {value}" for key, value in counter.items())
|
||
|
||
|
||
async def _collect_operational_health(db: AsyncSession) -> dict[str, Any]:
|
||
"""Query failed collection tasks and unhealthy data sources, degrading safely."""
|
||
summary: dict[str, Any] = {
|
||
"failed_tasks_24h": 0,
|
||
"recent_failed_tasks": [],
|
||
"failed_datasources": [],
|
||
}
|
||
try:
|
||
cutoff = datetime.now(UTC) - timedelta(hours=24)
|
||
failed_24h_count = await db.execute(
|
||
select(func.count(CollectionTask.id))
|
||
.where(CollectionTask.status == "failed")
|
||
.where(CollectionTask.created_at >= cutoff)
|
||
)
|
||
failed_tasks_rows = await db.execute(
|
||
select(CollectionTask)
|
||
.where(CollectionTask.status == "failed")
|
||
.order_by(CollectionTask.created_at.desc(), CollectionTask.id.desc())
|
||
.limit(6)
|
||
)
|
||
failed_sources_rows = await db.execute(
|
||
select(DataSource)
|
||
.where(DataSource.is_active.is_(True))
|
||
.where(DataSource.last_status.in_(["failed", "error"]))
|
||
)
|
||
summary["failed_tasks_24h"] = int(failed_24h_count.scalar() or 0)
|
||
summary["recent_failed_tasks"] = [
|
||
{
|
||
"source": task.source or f"datasource:{task.datasource_id}",
|
||
"task_type": task.task_type,
|
||
"error": (task.error_message or "")[:160],
|
||
}
|
||
for task in failed_tasks_rows.scalars().all()
|
||
]
|
||
summary["failed_datasources"] = [
|
||
{"source": ds.source, "name": ds.name, "status": ds.last_status}
|
||
for ds in failed_sources_rows.scalars().all()
|
||
]
|
||
except Exception:
|
||
# Keep brief generation resilient even in minimal test DB fixtures.
|
||
pass
|
||
return summary
|
||
|
||
|
||
async def build_alert_brief_request(
|
||
db: AsyncSession,
|
||
*,
|
||
alert_limit: int = 8,
|
||
) -> tuple[SituationalAnalysisRequest, list[str], dict[str, Any]]:
|
||
recent_alerts_result = await db.execute(
|
||
select(Alert)
|
||
.order_by(Alert.created_at.desc(), Alert.id.desc())
|
||
.limit(max(alert_limit, 1))
|
||
)
|
||
total_result = await db.execute(select(func.count(Alert.id)))
|
||
active_result = await db.execute(select(func.count(Alert.id)).where(Alert.status == AlertStatus.ACTIVE))
|
||
acknowledged_result = await db.execute(
|
||
select(func.count(Alert.id)).where(Alert.status == AlertStatus.ACKNOWLEDGED)
|
||
)
|
||
resolved_result = await db.execute(select(func.count(Alert.id)).where(Alert.status == AlertStatus.RESOLVED))
|
||
|
||
recent_alerts = recent_alerts_result.scalars().all()
|
||
total_alerts = total_result.scalar() or 0
|
||
active_alerts = active_result.scalar() or 0
|
||
acknowledged_alerts = acknowledged_result.scalar() or 0
|
||
resolved_alerts = resolved_result.scalar() or 0
|
||
|
||
severity_counts = Counter((item.severity.value if item.severity else "unknown") for item in recent_alerts)
|
||
status_counts = Counter((item.status.value if item.status else "unknown") for item in recent_alerts)
|
||
datasource_counts = Counter((item.datasource_name or "未命名数据源") for item in recent_alerts)
|
||
active_datasource_counts = Counter(
|
||
(item.datasource_name or "未命名数据源")
|
||
for item in recent_alerts
|
||
if item.status == AlertStatus.ACTIVE
|
||
)
|
||
|
||
facts = [
|
||
f"告警总量 {total_alerts} 条,其中 active {active_alerts} 条、acknowledged {acknowledged_alerts} 条、resolved {resolved_alerts} 条。",
|
||
f"最近告警严重度分布:{_format_counter(severity_counts)}。",
|
||
f"最近告警状态分布:{_format_counter(status_counts)}。",
|
||
f"最近告警数据源分布:{_format_counter(Counter(dict(datasource_counts.most_common(6))))}。",
|
||
]
|
||
|
||
if active_datasource_counts:
|
||
facts.append(
|
||
"当前待处理告警主要集中在:"
|
||
+ _format_counter(Counter(dict(active_datasource_counts.most_common(5))))
|
||
+ "。"
|
||
)
|
||
|
||
if recent_alerts:
|
||
facts.append(
|
||
"最近告警摘录:"
|
||
+ ";".join(
|
||
[
|
||
f"{item.datasource_name or '未命名数据源'} / {item.severity.value if item.severity else '-'} / {item.status.value if item.status else '-'} / {item.message or '-'}"
|
||
for item in recent_alerts[:6]
|
||
]
|
||
)
|
||
)
|
||
|
||
health = await _collect_operational_health(db)
|
||
failed_sources = health["failed_datasources"]
|
||
failed_tasks = health["recent_failed_tasks"]
|
||
facts.append(
|
||
f"近 24 小时采集任务失败 {health['failed_tasks_24h']} 次,"
|
||
f"当前处于异常/失败状态的活跃数据源 {len(failed_sources)} 个。"
|
||
)
|
||
if failed_sources:
|
||
facts.append(
|
||
"异常数据源:"
|
||
+ "、".join(f"{item['name']} ({item['source']})" for item in failed_sources[:6])
|
||
+ "。"
|
||
)
|
||
if failed_tasks:
|
||
facts.append(
|
||
"最近失败任务摘录:"
|
||
+ ";".join(
|
||
f"{item['source']} [{item['task_type']}] {item['error'] or 'failed'}"
|
||
for item in failed_tasks[:4]
|
||
)
|
||
)
|
||
|
||
context = {
|
||
"source": "alerts",
|
||
"total_alerts": total_alerts,
|
||
"active_alerts": active_alerts,
|
||
"acknowledged_alerts": acknowledged_alerts,
|
||
"resolved_alerts": resolved_alerts,
|
||
"severity_distribution": dict(severity_counts),
|
||
"status_distribution": dict(status_counts),
|
||
"top_datasources": dict(datasource_counts.most_common(6)),
|
||
"top_active_datasources": dict(active_datasource_counts.most_common(5)),
|
||
"failed_tasks_24h": health["failed_tasks_24h"],
|
||
"recent_failed_tasks": failed_tasks,
|
||
"failed_datasources": failed_sources,
|
||
}
|
||
prompt = await get_effective_prompt(db, ALERT_BRIEF_PROMPT_KEY)
|
||
|
||
return (
|
||
SituationalAnalysisRequest(
|
||
title="告警态势 AI 简报",
|
||
objective=prompt.prompt,
|
||
system_prompt=prompt.system_prompt or None,
|
||
observations=facts,
|
||
constraints=[
|
||
"明确区分事实、推断与建议。",
|
||
"优先指出仍处于 active 状态且高严重度的告警簇。",
|
||
"不要把 acknowledged 或 resolved 告警误判成当前仍在扩大。",
|
||
"如果证据不足,请明确指出缺失的上下文。",
|
||
],
|
||
context=context,
|
||
),
|
||
facts,
|
||
context,
|
||
)
|