adityadixit7/ai-incident-response-system

GitHub: adityadixit7/ai-incident-response-system

该项目是一个基于向量检索与 LLM 的实时运维事件响应系统,通过自学习记忆机制实现故障自动检测、根因分析和修复方案推荐。

Stars: 0 | Forks: 0

# Incident AI 系统 ## 目录 1. [架构概述](#architecture-overview) 2. [工作原理](#how-it-works) 3. [安装](#installation) 4. [运行服务器](#running-the-server) 5. [API 参考](#api-reference) 6. [Curl 示例](#curl-examples) 7. [投资者演示脚本](#investor-demo-script) 8. [项目结构](#project-structure) 9. [配置](#configuration) ## 架构概述 ``` ┌─────────────────────────────────────────────────────────────────┐ │ FastAPI Application │ │ │ │ ┌────────────┐ ┌────────────┐ ┌──────────┐ ┌──────────┐ │ │ │ /incidents │ │ /ask-ai │ │ /resolve │ │ /memory │ │ │ └─────┬──────┘ └─────┬──────┘ └────┬─────┘ └────┬─────┘ │ │ │ │ │ │ │ │ ┌─────▼─────────────────▼───────────────▼──────────────▼─────┐ │ │ │ API Router (routes.py) │ │ │ └──────────────────────────────┬─────────────────────────────┘ │ │ │ │ │ ┌───────────────────────┼───────────────────┐ │ │ ▼ ▼ ▼ │ │ ┌─────────────┐ ┌───────────────────────┐ ┌──────────────┐ │ │ │ Incident │ │ Reasoning Engine │ │ Memory │ │ │ │ Repository │ │ (AI Analysis Core) │ │ Repository │ │ │ └─────────────┘ └───────────┬───────────┘ └──────────────┘ │ │ │ │ │ ┌───────────┼────────────┐ │ │ ▼ ▼ ▼ │ │ ┌──────────┐ ┌─────────┐ ┌──────────┐ │ │ │Embedding │ │Confidence│ │ Vector │ │ │ │ Service │ │ Engine │ │ Search │ │ │ └──────────┘ └─────────┘ └──────────┘ │ │ │ │ ╔══════════════════════════════════════════════════════════╗ │ │ ║ Mock Elasticsearch Client (in-memory store) ║ │ │ ║ Logs Index │ Incidents Index │ Memory Index ║ │ │ ╚══════════════════════════════════════════════════════════╝ │ │ │ │ ┌──────────────────────┐ ┌─────────────────────────────────┐ │ │ │ Log Generator Task │ │ Incident Detector Task │ │ │ │ (every 2 seconds) │ │ (every 10 seconds, ES|QL-sim) │ │ │ └──────────────────────┘ └─────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ``` ### 关键设计原则 | 关注点 | 实现方式 | |---------|---------------| | 存储 | 内存字典存储(模拟 Elasticsearch 客户端) | | 聚合 | 基于 Python 的 ES|QL 模拟(按服务统计错误数) | | Embeddings | 通过 SentenceTransformers 使用 `all-MiniLM-L6-v2`(384维) | | 相似度 | 手动余弦相似度(仅使用 NumPy,不使用 scipy) | | 检测 | Asyncio 后台任务 —— 每个时间窗口的错误阈值 | | 记忆 | 历史解决方案与 embedding 一起存储;在每次分析时进行搜索 | | 置信度 | 相似度 + 模式匹配 + 严重程度的加权综合评分 | ## 工作原理 ### 1. 模拟日志 后台任务每 **2 秒**生成一次真实的服务日志。每次触发时有 15% 的概率,为随机选择的服务注入**错误峰值**,产生 6-12 条连续的 ERROR 级别日志条目。 ### 2. 检测循环 每 **10 秒**,检测器执行一次 ES|QL 风格的聚合: ``` FROM incident-ai-logs | WHERE log_level == "ERROR" AND timestamp > NOW() - INTERVAL 30 SECONDS | STATS error_count = COUNT(*) BY service_name | SORT error_count DESC ``` 如果任何服务的错误超过 **3 个**,则会创建一个事件。 ### 3. AI 分析 (`POST /ask-ai`) 1. 加载事件摘要 2. 使用 SentenceTransformer 将其编码为 384 维向量 3. 对所有记忆进行余弦相似度计算(模拟 Elasticsearch kNN) 4. 如果最佳匹配度 ≥ 0.70 → 推荐经过验证的历史修复方案 5. 否则 → 从规则引擎应用特定于服务的通用修复方案 6. 计算置信度:`(similarity × 0.5) + (pattern_match × 0.3) + (severity × 0.2)` ### 4. 解决方案记忆 (`POST /resolve`) 当操作员解决一个事件时: 1. 对 `root_cause + fix_applied` 文本进行 Embedding 处理 2. 将 embedding 存储在记忆索引中 3. 未来的同类型事件现在将获得该修复方案的推荐 该系统具备**自我改进**能力 —— 每次解决方案都会使未来的推荐更加准确。 ## 安装 ``` # 进入项目目录 cd incident-ai-system # (推荐) 创建虚拟环境 python -m venv venv source venv/bin/activate # Linux/macOS venv\Scripts\activate # Windows # 安装依赖 pip install -r requirements.txt ``` ## 运行服务器 ``` uvicorn app.main:app --reload ``` 服务器在 **http://localhost:8000** 启动 - **Swagger UI(交互式文档):** http://localhost:8000/docs - **API 根路径:** http://localhost:8000/api/v1 ## API 参考 ### `GET /api/v1/incidents` 列出所有事件,最新的排在前面。 **响应:** ``` { "total": 3, "incidents": [ { "id": "abc-123", "service_name": "payment-service", "error_count": 7, "pattern_hash": "a1b2c3d4e5f60001", "top_error_message": "Connection timeout to payment gateway", "status": "open", "created_at": "2024-06-01T12:00:00+00:00", "resolved_at": null, "summary": "Service payment-service experienced 7 errors. ..." } ] } ``` ### `POST /api/v1/ask-ai` 触发针对某个事件的 AI 分析。 **请求体:** ``` { "incident_id": "abc-123" } ``` **响应:** ``` { "incident_id": "abc-123", "service_name": "payment-service", "probable_root_cause": "Payment gateway connection pool exhausted due to high traffic", "suggested_fix": "Restart connection pool and increase gateway timeout to 30s", "confidence_score": 0.885, "similar_incidents": [ { "memory_id": "mem-001", "service_name": "payment-service", "root_cause": "Payment gateway connection pool exhausted due to high traffic", "fix_applied": "Restart connection pool and increase gateway timeout to 30s", "similarity_score": 0.91 } ], "reasoning_path": [ "Loaded incident: Service payment-service experienced 7 errors...", "Encoded incident summary into 384-dim vector.", "Searched 2 memory entries. Retrieved top 2 candidates.", "High-similarity memory found (score=0.9100 ≥ threshold=0.70). Reusing proven fix.", "Confidence score: 88.50% (similarity=0.91, pattern_match=True, errors=7)" ] } ``` ### `POST /api/v1/resolve` 解决事件并将修复方案存储在 AI 记忆中。 **请求体:** ``` { "incident_id": "abc-123", "root_cause": "Payment gateway connection pool exhausted due to high traffic", "fix_applied": "Restart connection pool and increase gateway timeout to 30s" } ``` **响应:** ``` { "success": true, "message": "Incident resolved. Fix has been stored in AI memory.", "memory_id": "def-456", "service": "payment-service" } ``` ### `GET /api/v1/memory` 查看所有已存储的解决方案记忆(为便于展示,已省略 embedding 向量)。 **响应:** ``` { "total": 3, "memories": [ { "id": "mem-001", "incident_id": "abc-123", "service_name": "payment-service", "root_cause": "Payment gateway connection pool exhausted", "fix_applied": "Restart connection pool and increase timeout", "created_at": "2024-06-01T12:30:00+00:00", "embedding_dimensions": 384 } ] } ``` ### `GET /api/v1/health` 系统健康状态和索引统计信息。 **响应:** ``` { "status": "healthy", "mode": "demo — in-memory simulation (no real Elasticsearch required)", "elastic_url": "http://dummy-elastic:9200", "embedding_model_loaded": true, "index_stats": { "incident-ai-logs": 142, "incident-ai-incidents": 3, "incident-ai-memory": 2 } } ``` ## Curl 示例 ``` # 1. 检查系统健康状态 curl http://localhost:8000/api/v1/health # 2. 列出所有 incidents curl http://localhost:8000/api/v1/incidents # 3. 触发 AI 分析 (将 INCIDENT_ID 替换为步骤 2 中的真实 UUID) curl -X POST http://localhost:8000/api/v1/ask-ai \ -H "Content-Type: application/json" \ -d '{"incident_id": "INCIDENT_ID"}' # 4. 解决 incident 并保存修复方案 curl -X POST http://localhost:8000/api/v1/resolve \ -H "Content-Type: application/json" \ -d '{ "incident_id": "INCIDENT_ID", "root_cause": "Connection pool exhausted due to traffic spike", "fix_applied": "Increased pool size to 50 and restarted gateway service" }' # 5. 验证 memory 是否已更新 curl http://localhost:8000/api/v1/memory ``` ## 投资者演示脚本 ### 准备工作(在演示之前完成) ``` cd incident-ai-system pip install -r requirements.txt uvicorn app.main:app --reload ``` 等待控制台显示: ``` [SYSTEM] All systems online. Ready to receive requests. ``` ### 现场演示流程(5 分钟) **步骤 1 — 展示系统正在运行** ``` curl http://localhost:8000/api/v1/health ``` 指出:`embedding_model_loaded: true`,以及不断增长的索引统计信息。 **步骤 2 — 观察控制台 20-30 秒** 你会看到类似以下的条目: ``` [LOG-GEN] Injecting error spike for: payment-service (8 error logs to follow) [DETECTOR] Incident Created for payment-service | Errors: 5 | Pattern: a1b2c3d4 ``` 这展示了**自主的实时监控**能力。 **步骤 3 — 查看开启的事件** ``` curl http://localhost:8000/api/v1/incidents ``` 复制开启事件的 `id`(status: "open")。 **步骤 4 — 让 AI 进行分析** ``` curl -X POST http://localhost:8000/api/v1/ask-ai \ -H "Content-Type: application/json" \ -d '{"incident_id": "PASTE_ID_HERE"}' ``` 指出: - `confidence_score`(例如 0.885 = **88.5% 置信度**) - `similar_incidents` 展示了它找到的历史解决方案 - `reasoning_path` —— AI 决策的完整审计追踪 控制台将显示: ``` [AI] Similar Incident Found (Similarity: 0.91) ``` **步骤 5 — 应用修复方案** ``` curl -X POST http://localhost:8000/api/v1/resolve \ -H "Content-Type: application/json" \ -d '{ "incident_id": "PASTE_ID_HERE", "root_cause": "Connection pool exhausted due to traffic surge", "fix_applied": "Restarted payment-service with pool size increased to 50" }' ``` 控制台: ``` [MEMORY] Resolution Stored for incident | service=payment-service [RESOLVE] Incident resolved | service=payment-service ``` **步骤 6 — 展示记忆已增长** ``` curl http://localhost:8000/api/v1/memory ``` 新的解决方案现在出现了。指出: - `embedding_dimensions: 384` —— 修复方案以语义向量的形式存储 - **下次**发生这种错误模式时,系统将立即以高置信度推荐这个确切的修复方案 ### 面向投资者的关键谈论点 | 功能 | 话术要点 | |---------|-------------| | **ES|QL 模拟** | "检测器每 10 秒在所有日志中运行一次 ES|QL 风格的查询" | | **向量记忆** | "每个解决方案都存储为一个 384 维向量 —— 系统在语义上记住了这些修复方案" | | **自学习** | "每解决一个事件,置信度就会提升 —— 系统会自动变得更聪明" | | **模式哈希** | "即使错误消息略有不同,也能检测到反复出现的故障模式" | | **生产就绪** | "将模拟客户端替换为真实的 elasticsearch-py 客户端,它就可以连接到任何 ES 集群" | ## 项目结构 ``` incident-ai-system/ │ ├── app/ │ ├── main.py # FastAPI app, lifespan, background tasks, seed data │ ├── config.py # Settings (dummy ES credentials, thresholds, model name) │ │ │ ├── core/ │ │ ├── constants.py # Index names, service lists, error messages, fix templates │ │ └── utils.py # ID generation, timestamps, pattern hashing, cosine similarity │ │ │ ├── elastic/ │ │ ├── mock_client.py # Thread-safe in-memory Elasticsearch simulation │ │ ├── log_repository.py # Log CRUD + ES|QL aggregation │ │ ├── incident_repository.py # Incident CRUD + status queries │ │ └── memory_repository.py # Memory CRUD + kNN vector search │ │ │ ├── detection/ │ │ ├── detector.py # Background asyncio task: error threshold monitoring │ │ └── pattern_engine.py # Pattern hash generation + incident summary builder │ │ │ ├── embeddings/ │ │ └── embedding_service.py # SentenceTransformer wrapper (singleton) │ │ │ ├── ai/ │ │ ├── reasoning_engine.py # Full AI analysis pipeline │ │ └── confidence_engine.py # Weighted confidence score calculator │ │ │ ├── models/ │ │ ├── incident_model.py # Incident Pydantic models │ │ └── resolution_model.py # Resolution, AIAnalysis Pydantic models │ │ │ └── api/ │ └── routes.py # All FastAPI route handlers │ ├── requirements.txt └── README.md ``` ## 配置 所有可调整的值都位于 `app/config.py` 中: | 设置 | 默认值 | 描述 | |---------|---------|-------------| | `ELASTIC_URL` | `http://dummy-elastic:9200` | 虚拟地址 —— 不需要真实的 ES | | `ELASTIC_API_KEY` | (虚拟 base64) | 虚拟密钥 —— 不需要真实的 ES | | `EMBEDDING_MODEL` | `all-MiniLM-L6-v2` | HuggingFace 模型名称 | | `ERROR_THRESHOLD` | `3` | 每个时间窗口内触发事件的错误数 | | `DETECTION_INTERVAL_SECONDS` | `10` | 检测器运行的频率 | | `DETECTION_WINDOW_SECONDS` | `30` | 错误次数统计的回溯时间窗口 | | `LOG_GENERATION_INTERVAL_SECONDS` | `2.0` | 日志生成触发之间的秒数 | | `ERROR_SPIKE_PROBABILITY` | `0.15` | 每次触发引起错误峰值的机会 | | `SIMILARITY_THRESHOLD` | `0.70` | 复用历史修复方案的最低余弦相似度 | | `TOP_K_SIMILAR` | `3` | 返回的相似记忆数量 | 为了在演示期间让错误峰值发生得更快,请将 `ERROR_SPIKE_PROBABILITY` 降低至 `0.40`,并将 `DETECTION_WINDOW_SECONDS` 降低至 `15`。
标签:AV绕过, DLL 劫持, FastAPI, 人工智能, 向量检索, 大语言模型, 模块化设计, 用户模式Hook绕过, 自动化修复, 计算机取证, 运维监控, 逆向工具