算法是AIOps的"大脑",部署是把大脑装进躯体的手术。手术成功了,运维才算真正有了智能。
传统运维靠静态阈值——CPU超80%就告警。但业务有周期波动,白天正常的高峰到晚上就成了异常;大促期间的流量尖峰,放在平时可能就是故障前兆。AI算法引擎的价值,就是让系统自己学会"什么时候该报警、问题出在哪里"。
在动手部署之前,先看清算法引擎在整个AIOps平台中的定位——它处于数据层之上、执行层之下,是连接"感知"和"行动"的中枢。
算法引擎的核心职责就两件事:发现异常(异常检测)和定位原因(根因分析)。前者负责"报警",后者负责"说清楚为什么报警"。
异常检测不是"一个算法包打天下"。下面这个流程图展示了推荐的混合检测策略——先用轻量算法快速筛查,再用复杂模型深度确认,兼顾效率和准确率。

为什么用混合策略? IQR(四分位距)基于统计原理,计算复杂度O(n),毫秒级完成,适合对海量指标做第一道过滤。Isolation Forest基于随机森林,准确率更高但计算开销也更大,只对IQR筛出的"可疑点"做二次确认。这样既保证了检测精度,又控制了计算成本。
Python凭借丰富的AI/ML生态(scikit-learn、PyTorch、Prophet等),是AIOps算法开发的主力语言。适合模型训练、数据分析和POC验证,开发效率高。
Go语言在高并发、低延迟场景下优势明显。AIOps平台需要实时处理海量监控数据,Go的goroutine和channel模型非常适合构建高性能采集、分发和API服务。
推荐策略:Python做算法训练和离线分析,Go或Java做在线推理API和高并发处理。美团Horae系统的实践也表明,算法服务层需要兼顾模型复杂度和工程性能。
异常检测是AIOps的基础能力。常见算法及适用场景:
# anomaly_detector.py - 基于FastAPI的异常检测服务from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom sklearn.ensemble import IsolationForestimport numpy as npimport pandas as pdfrom datetime import datetime, timedeltaapp = FastAPI(title="AIOps异常检测服务")class MetricRequest(BaseModel): service: str metric_name: str values: list[float] timestamps: list[str]class DetectionResult(BaseModel): is_anomaly: bool confidence: float algorithm: str details: dict# 1. Isolation Forest检测器(适用于多维指标)class IsolationForestDetector: def __init__(self, contamination=0.01): self.model = IsolationForest( contamination=contamination, random_state=42 ) def fit(self, data: np.ndarray): self.model.fit(data) def predict(self, data: np.ndarray) -> tuple[list, float]: pred = self.model.predict(data) anomalies = [i for i, v in enumerate(pred) if v == -1] scores = self.model.score_samples(data) avg_score = float(np.mean(scores))return anomalies, avg_score# 2. IQR检测器(适用于时序单指标)class IQRDetector: def __init__(self, window_size=24): self.window_size = window_size def detect(self, values: list[float]) -> tuple[bool, float]:if len(values) < self.window_size:return False, 0.0 baseline = values[-self.window_size:] q1 = np.percentile(baseline, 25) q3 = np.percentile(baseline, 75) iqr = q3 - q1 current = values[-1] upper_bound = q3 + 1.5 * iqr lower_bound = q1 - 1.5 * iqr is_anomaly = current > upper_bound or current < lower_bound deviation = max( (current - upper_bound) / iqr if current > upper_bound else 0, (lower_bound - current) / iqr if current < lower_bound else 0 )return is_anomaly, float(deviation)iso_detector = IsolationForestDetector()iqr_detector = IQRDetector()@app.post("/detect", response_model=DetectionResult)async def detect_anomaly(request: MetricRequest): values = np.array(request.values).reshape(-1, 1)# 阶段1:IQR快速筛查 iqr_result, deviation = iqr_detector.detect(request.values)if not iqr_result:return DetectionResult( is_anomaly=False, confidence=1.0, algorithm="iqr", details={"deviation": deviation} )# 阶段2:Isolation Forest确认if len(values) >= 10: iso_detector.fit(values[:-1]) anomalies, score = iso_detector.predict(values[-1:]) is_anomaly = len(anomalies) > 0 confidence = 1.0 - abs(score)else: is_anomaly = True confidence = min(0.9, 0.5 + deviation * 0.2)return DetectionResult( is_anomaly=is_anomaly, confidence=confidence, algorithm="hybrid", details={"iqr_deviation": deviation} )# 启动: uvicorn anomaly_detector:app --host 0.0.0.0 --port 8000# /etc/systemd/system/anomaly-detector.service[Unit]Description=AIOps Anomaly Detector ServiceAfter=network.target[Service]Type=simpleUser=aiopsWorkingDirectory=/opt/aiops/algorithmExecStart=/usr/bin/python3 -m uvicorn anomaly_detector:app --host 0.0.0.0 --port 8000Restart=alwaysRestartSec=10[Install]WantedBy=multi-user.target根因分析(RCA)需要整合多模态数据。当前主流方案采用多Agent协同架构,由多个专门Agent分工协作完成推理。某开源项目的实践表明,通过4个Agent协作(监控告警→根因分析→故障自愈→变更审批),MTTR可从40分钟降至5分钟以内。

根因分析需要整合多模态数据:指标异常、日志错误、调用链依赖。核心流程:
// rca_service.go - Go实现的根因分析服务核心框架package mainimport ("encoding/json""fmt""net/http""sort")type ServiceNode struct { ID string `json:"id"` Name string `json:"name"` Depends []string `json:"depends"` DependedBy []string `json:"depended_by"`}type AnomalyEvent struct { ServiceID string `json:"service_id"` MetricName string `json:"metric_name"` Value float64 `json:"value"` Timestamp int64 `json:"timestamp"`}type RCAResult struct { RootCause string `json:"root_cause"` Confidence float64 `json:"confidence"` Evidence []string `json:"evidence"` AffectedPath []string `json:"affected_path"`}type RCAEngine struct { serviceGraph map[string]ServiceNode}func NewRCAEngine() *RCAEngine {return &RCAEngine{ serviceGraph: make(map[string]ServiceNode), }}func (e *RCAEngine) FindRootCause(event AnomalyEvent) RCAResult { visited := make(map[string]bool) queue := []string{event.ServiceID} candidates := []string{}for len(queue) > 0 { current := queue[0] queue = queue[1:]if visited[current] {continue } visited[current] = true node, exists := e.serviceGraph[current]if !exists {continue } candidates = append(candidates, current)for _, upstream := range node.DependedBy {if !visited[upstream] { queue = append(queue, upstream) } } } sort.Slice(candidates, func(i, j int) bool {return len(e.serviceGraph[candidates[i]].DependedBy) > len(e.serviceGraph[candidates[j]].DependedBy) })if len(candidates) == 0 {return RCAResult{ RootCause: "unknown", Confidence: 0.0, Evidence: []string{"未找到候选根因节点"}, } } root := candidates[0]return RCAResult{ RootCause: root, Confidence: 0.72, Evidence: []string{fmt.Sprintf("服务 %s 处于依赖链最上游", root)}, AffectedPath: []string{root, event.ServiceID}, }}func (e *RCAEngine) HandleRCA(w http.ResponseWriter, r *http.Request) { var event AnomalyEventif err := json.NewDecoder(r.Body).Decode(&event); err != nil { http.Error(w, err.Error(), http.StatusBadRequest)return } result := e.FindRootCause(event) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(result)}func main() { engine := NewRCAEngine() // 从CMDB或配置文件加载服务依赖图 // engine.serviceGraph = loadFromCMDB() http.HandleFunc("/rca", engine.HandleRCA) http.ListenAndServe(":8080", nil)}# 验证异常检测服务curl -X POST http://localhost:8000/detect \ -H "Content-Type: application/json" \ -d '{"service":"order-service","metric_name":"cpu_usage","values":[45,47,46,93,48,49]}'# 验证根因分析服务curl -X POST http://localhost:8080/rca \ -H "Content-Type: application/json" \ -d '{"service_id":"order-service","metric_name":"cpu_usage","value":95.3}'快速检查清单:
AIops 运维面试题目详解:AIOps & AI运维面试题详解(2026年大厂/国企版)
欢迎加w一起交流:19067272547