geeked-anshuk666/NeuralWatch
GitHub: geeked-anshuk666/NeuralWatch
一款零代码改动的 AI 可观测性平台,通过两行 SDK 将 OpenAI 和 Anthropic 调用的成本追踪、prompt 注入检测及欧盟 AI 法案合规评分实时流式传输到 Splunk。
Stars: 0 | Forks: 0
# NeuralWatch - 面向 Splunk 的 AI 舰队观测平台
[](https://python.org)
[](https://pypi.org/project/neuralwatch-splunk/)
[](https://splunk.com)
[](LICENSE)
[](https://openai.com)
[](https://anthropic.com)
NeuralWatch 是一个零代码改动的 AI 可观测性平台,可为工程和合规团队提供对其 AI 系统的完全可见性。通过在库级别对 OpenAI 和 Anthropic Python SDK 进行埋点,NeuralWatch 能够自动捕获每一次 LLM API 调用——包括其成本、延迟、模型、团队归属以及 prompt 内容——并实时将结构化的遥测数据流式传输到 Splunk。无需自定义日志记录。除了单个 `instrument()` 调用外,无需进行任何代码更改。
## 目录
- [架构概述](#architecture-overview)
- [模块分解](#module-breakdown)
- [模块 A - Prompt 注入哨兵](#module-a--prompt-injection-sentinel)
- [模块 B - NLP 查询代理 (MCP)](#module-b--nlp-query-agent-mcp)
- [模块 C - AI 舰队观测平台](#module-c--ai-fleet-observatory)
- [模块 D - 欧盟 AI 法案合规](#module-d--eu-ai-act-compliance)
- [数据流程图](#data-flow-diagram)
- [仓库结构](#repository-structure)
- [快速开始](#quick-start)
- [前置条件](#prerequisites)
- [1. 安装 SDK](#1-install-the-sdk)
- [2. 初始化 NeuralWatch](#2-initialize-neuralwatch)
- [3. 接入您的应用程序](#3-instrument-your-application)
- [4. 安装 Splunk App](#4-install-the-splunk-app)
- [5. 运行实时模拟器](#5-run-the-live-simulator)
- [SDK 参考](#sdk-reference)
- [instrument()](#instrument)
- [set_session_id() 和 trace_context()](#set_session_id-and-trace_context)
- [auto_instrument()](#auto_instrument)
- [CLI 命令](#cli-commands)
- [Splunk App 仪表板](#splunk-app-dashboards)
- [安全性设计](#security-design)
- [欧盟 AI 法案合规评分](#eu-ai-act-compliance-scoring)
- [MCP 代理 - 自然语言查询](#mcp-agent--natural-language-querying)
- [配置参考](#configuration-reference)
- [开发](#development)
- [许可证](#license)
## 架构概述
```
graph TD
subgraph Client Application [Client Application Namespace]
App["Your Application"]
SDK["neuralwatch_sdk"]
App -->|chat.completions.create| SDK
end
subgraph SDK Internals [SDK Engine]
Inst["instrumentor
Patches OpenAI/Claude"] Cost["cost_estimator
USD Pricing lookup"] Fwd["forwarder
Queue-backed async thread"] SDK --> Inst Inst --> Cost Cost --> Fwd end subgraph Splunk Enterprise [Splunk Log Analytics] HEC["HTTP Event Collector"] Index1[("neuralwatch_ai_calls")] Index2[("neuralwatch_injections")] Fwd -->|HTTPS HEC| HEC HEC --> Index1 HEC --> Index2 end subgraph User Interface [Telemetry Dashboards] Dash1["AI Fleet Observatory"] Dash2["Prompt Injection Sentinel"] Dash3["EU AI Act Compliance"] MCP["MCP Query Agent"] Index1 --> Dash1 Index2 --> Dash2 Index1 --> Dash3 Index2 --> Dash3 MCP -->|SPL Query via API| Index1 end ``` ## 模块分解 ### 模块 A - Prompt 注入哨兵 Prompt 注入哨兵会捕获通过已埋点的 LLM 客户端发送的每个 prompt,并使用受 Foundation-Sec 模型架构启发的启发式分类引擎对其对抗性内容进行分类。 **工作原理:** ``` flowchart LR Prompt["User Prompt"] -->|Intercepted by SDK| Classify["foundation_sec_classify.py"] Classify --> Pattern{"Pattern Match?"} Pattern -->|"ignore all previous..." / DAN mode| High["Critical / High Risk"] Pattern -->|"bypass input validation" / XSS| Med["Medium Risk"] Pattern -->|"Benign requests"| Low["Low Risk"] High -->|Assign Injection Score 0.0 - 1.0| Score["Telemetry Event"] Med -->|Assign Injection Score 0.0 - 1.0| Score Low -->|Assign Injection Score 0.0 - 1.0| Score Score -->|Route to neuralwatch_injections| Index[("Splunk Index")] Index --> Dash["Prompt Injection Sentinel Dashboard"] ``` **检测到的威胁类别:** | 风险等级 | 分数范围 | 示例模式 | |---|---|---| | `CRITICAL` | 0.93 – 0.98 | `ignore all previous instructions`, `print system prompt verbatim`, `DAN mode` | | `HIGH` | 0.72 – 0.85 | `grant me access`, `output passwords`, `exfiltrate` | | `MEDIUM` | 0.42 – 0.62 | `bypass input validation`, `sql injection`, `cross-site scripting` | | `LOW` | 0.05 – 0.20 | 良性请求 | **会话持久性检测:** 哨兵会跨多个事件跟踪 `session_id`。如果从同一会话接收到超过 5 个 `HIGH`/`CRITICAL` 事件的服务,将触发提升的 Art. 9 风险评分。 ### 模块 B - NLP 查询代理 (MCP) NeuralWatch MCP 代理提供对 Splunk 中所有遥测数据的自然语言查询访问。它将英语问题转换为 SPL,通过 Splunk Management API 执行,并使用 LLM 合成易于理解的答案。 ``` flowchart TD User["User Question: 'How much did we spend on GPT-4o?'"] -->|Input| Gen["spl_generator.py
NL to SPL Compiler"] Gen -->|Generated SPL Query| Client["mcp_client.py
Splunk SDK Runner"] Client -->|API Request| Splunk[("neuralwatch_ai_calls")] Splunk -->|Raw Results JSON| Synth["agent.py
LLM Synthesizer"] Synth -->|Formatted Summary| Out["User Response: 'GPT-4o cost $12.47 across 3 services...'"] ``` **通过 CLI 可用:** ``` python mcp_agent/cli.py ``` ### 模块 C - AI 舰队观测平台 AI 舰队观测平台是主要的实时操作仪表板,可实时查看所有已埋点服务的 AI API 成本、延迟、token 消耗和模型使用模式。 **跟踪的关键指标:** | 指标 | 来源 | 刷新频率 | |---|---|---| | AI API 总成本 (USD) | 每次调用的 `cost_usd` | 15秒 | | 平均延迟 (ms) | 每次调用的 `latency_ms` | 15秒 | | 错误率 (%) | `status=error` 计数 | 15秒 | | 各模型成本 | 按 model 分组的聚合 `cost_usd` | 15秒 | | 各服务成本 | 按 service 分组的聚合 `cost_usd` | 15秒 | | 延迟 p50/p95 | 各模型的百分位统计数据 | 15秒 | | 活动 AI 调用 (时间图表) | 时间序列调用量 | 15秒 | ### 模块 D - 欧盟 AI 法案合规 NeuralWatch 持续为每个受监控的服务计算欧盟 AI 法案合规分数,将实时遥测数据和静态策略基线映射到五个关键条款。 **评分模型:** ``` graph TD subgraph Adherence [EU AI Act Compliance Scoring Model] Art9["Art. 9: Risk Management
100 - high_incidents * 5"] Art13["Art. 13: Transparency
100 if disclosure_enabled = 1, else 0"] Art14["Art. 14: Human Oversight
100 if no review, else threshold * 100"] Art17["Art. 17: Quality Management
1 - error_rate * 100"] Art72["Art. 72: Systemic Risk
90 Adjusted by Latency Drift"] end Art9 -->|Average| Score["Overall Compliance Score"] Art13 -->|Average| Score Art14 -->|Average| Score Art17 -->|Average| Score Art72 -->|Average| Score Score --> Threshold{"Score Threshold"} Threshold -->|Score >= 90| Comp["✅ COMPLIANT"] Threshold -->|Score >= 70| Risk["⚠️ AT RISK"] Threshold -->|Score < 70| Non["❌ NON-COMPLIANT"] ``` ## 数据流程图 ``` sequenceDiagram participant App as Your Application participant SDK as neuralwatch_sdk participant Queue as Background Queue participant HEC as Splunk HEC participant Splunk as Splunk Indexes participant Dashboard as Dashboards App->>SDK: client.chat.completions.create(...) SDK->>SDK: Extract model, tokens, latency, cost SDK->>SDK: Hash prompt text SDK->>Queue: Enqueue AICallEvent (non-blocking) SDK->>Queue: Enqueue PromptEvent (if capture_prompts=True) SDK->>App: Return API response (zero added latency) Queue-->>HEC: POST /services/collector/event HEC-->>Splunk: Index neuralwatch_ai_calls HEC-->>Splunk: Index neuralwatch_injections Dashboard->>Splunk: SPL Query (every 15s) Splunk-->>Dashboard: Aggregated results Dashboard-->>Dashboard: Render live charts ``` ## 仓库结构 ``` NeuralWatch/ │ ├── neuralwatch_sdk/ # PyPI-publishable Python SDK │ ├── __init__.py # Public API: instrument, set_session_id, trace_context │ ├── instrumentor.py # Core monkey-patching engine (OpenAI + Anthropic) │ ├── forwarder.py # Non-blocking HEC telemetry queue with atexit flush │ ├── cost_estimator.py # Per-model USD pricing table and calculator │ ├── cli.py # `neuralwatch` CLI (init / status / demo) │ └── templates/ # App scaffolding templates │ ├── splunk_app/ # Installable Splunk App │ ├── default/ │ │ ├── app.conf # App metadata │ │ ├── props.conf # Sourcetype extraction rules │ │ ├── transforms.conf # Lookup references │ │ ├── savedsearches.conf # Scheduled alert queries │ │ └── data/ui/views/ # Dashboard XML definitions │ │ ├── neuralwatch_main.xml # AI Fleet Observatory │ │ ├── neuralwatch_injection.xml # Prompt Injection Sentinel │ │ └── neuralwatch_compliance.xml # EU AI Act Compliance │ ├── bin/ │ │ ├── foundation_sec_classify.py # Batch heuristic classifier │ │ └── compliance_score.py # SDK compliance score reporter │ └── lookups/ │ ├── neuralwatch_compliance_baseline.csv # Per-service policy config │ └── neuralwatch_cost_model.csv # Model pricing table │ ├── mcp_agent/ # Natural language Splunk query agent │ ├── agent.py # Core interrogator and answer synthesizer │ ├── mcp_client.py # Splunk SDK query runner │ ├── spl_generator.py # NL → SPL compiler with LLM │ ├── cli.py # Interactive CLI entry point │ └── prompts/ │ └── system_prompt.txt # Agent system prompt with few-shot SPL examples │ ├── demo/ │ ├── live_simulator.py # Continuous telemetry simulator (mocked OpenAI) │ └── dummy_app.py # Integration template for real OpenAI SDK │ ├── tests/ │ ├── unit/ │ │ └── test_instrumentor.py # Unit tests for SDK instrumentation logic │ └── integration/ │ └── test_hec_pipeline.py # End-to-end HEC pipeline tests │ ├── splunk_app.tar.gz # Pre-packaged release artifact for Splunk Web upload ├── pyproject.toml # Build config for pip / PyPI packaging ├── requirements.txt # Runtime dependencies ├── requirements-dev.txt # Development and test dependencies └── LICENSE # MIT License ``` ## 快速开始 ### 前置条件 | 要求 | 版本 | |---|---| | Python | ≥ 3.9 | | Splunk Enterprise | ≥ 9.0 | | Splunk HTTP Event Collector | 已启用 | | OpenAI SDK | ≥ 1.0.0(可选 - 仅在使用真实调用时) | | Anthropic SDK | ≥ 0.3.0(可选 - 仅在使用真实调用时) | ### 1. 安装 SDK **从 PyPI 安装(生产环境 - [pypi.org/project/neuralwatch-splunk](https://pypi.org/project/neuralwatch-splunk/)):** ``` pip install neuralwatch-splunk ``` **从源码安装(开发环境):** ``` git clone https://github.com/geeked-anshuk666/NeuralWatch.git cd NeuralWatch pip install -e . ``` **验证安装:** ``` neuralwatch --help ``` ### 2. 初始化 NeuralWatch 运行交互式设置向导。它将验证您的 HEC 连接并生成本地配置文件: ``` neuralwatch init ``` 系统将提示您输入: - **服务名称** - 您的应用程序名称(例如 `checkout-service`) - **团队名称** - 所属团队(例如 `payments-eng`) - **Splunk HEC URL** - 例如 `https://localhost:8088/services/collector/event` - **HEC Token** - 您的 Splunk HEC token(掩码输入) 这将创建包含您设置的 `.neuralwatch/config.json` 文件。 ### 3. 接入您的应用程序 在应用程序的入口点添加**两行**代码: ``` import openai from neuralwatch_sdk import instrument, set_session_id # 启动时初始化一次 instrument( service="my-service", team="my-team", splunk_hec_url="https://localhost:8088/services/collector/event", splunk_hec_token="your-hec-token", capture_prompts=True, verify_ssl=False ) # 可选:设置用于追踪的 session 或 user ID(类型安全 - 无需更改 SDK) set_session_id("user-session-abc123") # 像往常一样使用 OpenAI - NeuralWatch 会自动捕获所有内容 client = openai.OpenAI(api_key="your-key") response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "How do I reset my password?"}] ) ``` **就是这样。** NeuralWatch 会拦截调用,提取所有遥测数据,并将其发送到 Splunk,同时不会更改响应或给您的应用程序增加任何可观察到的延迟。 #### 使用 `auto_instrument()`(配置文件驱动) 如果您希望从 `neuralwatch init` 创建的 `.neuralwatch/config.json` 文件中加载配置: ``` from neuralwatch_sdk import auto_instrument auto_instrument() ``` #### 使用 `trace_context()`(作用域上下文管理) 用于 Web 框架中的请求范围追踪: ``` from neuralwatch_sdk import trace_context import openai client = openai.OpenAI() with trace_context(session_id=request.user.id): # All AI calls within this block are tagged with the user's session ID response = client.chat.completions.create(...) ``` ### 4. 安装 Splunk App #### 选项 A:通过 Splunk Web 上传(推荐) 1. 导航至 **Splunk Web** → **Apps** → **Manage Apps** 2. 点击 **Install app from file** 3. 从仓库根目录上传 `splunk_app.tar.gz` 4. 如果是更新,请勾选 **Overwrite app** 5. 点击 **Upload** 6. 出现提示时重启 Splunk #### 选项 B:手动安装 ``` # 将 app 目录复制到你的 Splunk home cp -r splunk_app/ $SPLUNK_HOME/etc/apps/neuralwatch/ $SPLUNK_HOME/bin/splunk restart ``` #### 创建所需的 Index 运行 index 设置脚本(需要 Splunk Management API 凭据): ``` python demo/setup_indexes.py ``` 或者在 Splunk Web → **Settings** → **Indexes** 中手动创建它们: | Index 名称 | 类型 | Sourcetypes | |---|---|---| | `neuralwatch_ai_calls` | 事件 | `nw:ai_call` | | `neuralwatch_injections` | 事件 | `nw:prompt` | ### 5. 运行实时模拟器 模拟器提供连续的真实 AI 遥测事件流——包括正常的 API 调用、对抗性注入尝试以及模拟的持久攻击者会话——无需真实的 OpenAI API 密钥。 ``` python demo/live_simulator.py ``` 模拟器将: - 每 **2 秒**触发一次新的模拟 AI 事件 - 将 **40% 的事件**作为对抗性注入尝试路由(HIGH/CRITICAL 风险) - 模拟针对 `auth-service` 的**持久会话攻击**以推动 Art. 9 评分 - 生成 **~10% 的错误事件**以填充 Art. 17 质量指标 - 应用启发式分类并实时填充 `injection_score` 和 `risk_level` 字段 30 秒后打开您的 Splunk 仪表板,即可查看实时更新的指标。 ## SDK 参考 ### `instrument()` 主要的埋点函数。在应用程序启动时调用一次。 ``` from neuralwatch_sdk import instrument instrument( service: str, # Service identifier (e.g., "checkout-service") team: str, # Team identifier (e.g., "payments-eng") splunk_hec_url: str, # Full HEC endpoint URL splunk_hec_token: str, # Splunk HEC authentication token capture_prompts: bool = True, # Whether to capture prompt text for injection analysis verify_ssl: bool = False # SSL certificate verification ) ``` **修补内容:** 使用带 `setattr` 的 monkey-patching 修补 `openai.resources.chat.completions.Completions.create` 和 `anthropic.resources.messages.Messages.create`。原始方法会被保留并调用——NeuralWatch 只是包装了它们。 **每次 API 调用发出的事件:** | 事件 | 目标 Index | 字段 | |---|---|---| | `AICallEvent` | `neuralwatch_ai_calls` | `call_id`, `service`, `team`, `model`, `provider`, `latency_ms`, `input_tokens`, `output_tokens`, `cost_usd`, `status`, `finish_reason`, `prompt_hash` | | `PromptEvent` | `neuralwatch_injections` | `call_id`, `service`, `team`, `prompt_text`, `session_id`, `injection_score`, `risk_level` | ### `set_session_id()` 和 `trace_context()` 线程本地会话跟踪——**类型安全**且兼容原生 SDK 类型检查器。 ``` from neuralwatch_sdk import set_session_id, trace_context # 简单的 setter(对该 thread 持久) set_session_id("user-abc-123") # Context manager(退出时自动恢复之前的 session) with trace_context(session_id="request-xyz-456"): response = client.chat.completions.create(...) # 此处 session_id 会自动恢复为之前的值 ``` ### `auto_instrument()` 从 `.neuralwatch/config.json` 读取配置并自动调用 `instrument()`。适用于通过 `neuralwatch init` 部署的应用程序。 ``` from neuralwatch_sdk import auto_instrument auto_instrument() ``` ### CLI 命令 ``` # 初始化 NeuralWatch 并配置 HEC 连接 neuralwatch init [--service NAME] [--team NAME] [--splunk-url URL] [--token TOKEN] # 检查当前配置和连接状态 neuralwatch status # 发送 100 个测试事件以验证 telemetry pipeline neuralwatch demo ``` ## Splunk App 仪表板 ### 仪表板 1:AI 舰队观测平台 (`neuralwatch_main`) 为工程团队提供的主要操作仪表板。 | 面板 | 查询 | 洞察 | |---|---|---| | 总成本 (24h) | `sum(cost_usd)` | 所有 AI 服务花费的总 USD | | 平均延迟 | `avg(latency_ms)` | 所有模型的平均响应时间 | | 错误率 % | `errors/total × 100` | API 可靠性指标 | | 各模型成本 | 按 `model` 分组 | 哪些模型正在推动支出 | | 各服务成本 | 按 `service` 分组 | 哪些团队是支出大户 | | 延迟 p50/p95 | 百分位统计数据 | 各模型的尾部延迟可见性 | | 调用量 (时间图表) | `timechart span=5m count` | 随时间变化的调用率趋势 | ### 仪表板 2:Prompt 注入哨兵 (`neuralwatch_injection`) 用于检测和跟踪对抗性 prompt 活动的安全仪表板。 | 面板 | 查询 | 洞察 | |---|---|---| | 活动事件 (24h) | `risk_level IN (HIGH,CRITICAL)` | 总计高严重性威胁 | | 威胁分布 | `stats count by risk_level` | 风险等级分布饼图 | | 各服务事件 | `stats count by service` | 哪些服务最受针对 | | 会话持久性 | `stats dc(session_id) by service` | 重复的攻击者会话跟踪 | | 注入趋势 | `timechart span=5m count by risk_level` | 威胁活动时间轴 | ### 仪表板 3:欧盟 AI 法案合规 (`neuralwatch_compliance`) 将实时遥测映射到法规条款评分的合规监控仪表板。 | 面板 | 条款 | 指标 | |---|---|---| | 完全合规的服务 | Art. 13 + 14 | `disclosure_enabled=1 AND human_review_required=0` | | 活动注入事件 | Art 9 | `risk_level IN (HIGH, CRITICAL)` | | 需要人工审查的服务 | Art. 14 | `human_review_required=1` | | 质量错误率 % | Art. 17 | `errors/total × 100` | | 各服务合规记分卡 | All | 各服务的完整评分矩阵 | | 各服务注入事件 | Art. 9 | 事件计数的条形图 | | 披露状态分布 | Art. 13 | 披露合规性的饼图 | | 各服务错误率 | Art. 17 | 各服务的质量管理 | | 各模型延迟漂移 | Art. 72 | p50 与 p95 系统性风险 | | 威胁活动时间轴 | Art. 9 | 每分钟实时注入事件 | ## 安全性设计 NeuralWatch 遵循安全默认设计原则: | 控制措施 | 实现方式 | |---|---| | **机密隔离** | HEC token 绝不会被记录或嵌入源代码中。从环境变量或 `.neuralwatch/config.json`(已 git-ignored)中读取。 | | **Prompt 哈希** | 仅当 `capture_prompts=True` 时,才会将完整 prompt 文本存储在 `nw:prompt` sourcetype 下。Prompt 哈希(SHA-256,截断为 16 个字符)仅与 AI 调用事件一起存储。 | | **非阻塞转发** | 所有遥测均异步排队。转发器在后台 daemon 线程上运行,绝不阻塞应用程序的热路径。 | | **优雅失败** | 每个埋点 hook 都包装在 `try/except` 中。如果 NeuralWatch 遇到错误,您的应用程序将继续正常运行——遥测将被静默丢弃。 | | **SSL 验证** | 可根据部署进行配置。对于使用自签名证书的本地 Splunk 设置,默认禁用。建议在生产环境中使用 `verify_ssl=True`。 | | **队列溢出保护** | 转发器队列的最大容量为 10,000 个事件。溢出的事件将被丢弃并记录警告日志,以防止内存增长。 | | **atexit 刷新** | 在应用程序关闭时,SDK 会等待最多 5 秒以完全排空遥测队列,确保在正常退出时不会丢失任何事件。 | ## 欧盟 AI 法案合规评分 合规评分引擎会根据五个欧盟 AI 法案条款为每个受监控的服务计算加权分数。通过将实时遥测 index 与静态策略基线 CSV (`neuralwatch_compliance_baseline.csv`) 进行连接来实时计算分数。 ### 策略基线配置 `splunk_app/lookups/neuralwatch_compliance_baseline.csv` 文件定义了各服务的合规策略: ``` service,disclosure_enabled,human_review_required,human_review_threshold,risk_category,ai_act_scope checkout-service,1,1,0.95,high_risk,yes auth-service,1,0,0.0,limited_risk,yes fraud-detection-svc,1,1,0.95,high_risk,yes product-svc,1,0,0.0,minimal_risk,yes email-svc,0,0,0.0,minimal_risk,yes ``` | 列 | 描述 | |---|---| | `disclosure_enabled` | 服务是否向最终用户披露 AI 使用情况 (Art. 13) | | `human_review_required` | AI 输出是否强制要求人工审查 (Art. 14) | | `human_review_threshold` | 需要人工审查的置信度阈值 | | `risk_category` | 欧盟 AI 法案风险分类 (`high_risk`, `limited_risk`, `minimal_risk`) | | `ai_act_scope` | 该服务是否属于欧盟 AI 法案的适用范围 | ### 以编程方式运行合规报告 ``` python splunk_app/bin/compliance_score.py ``` **示例输出:** ``` { "status": "success", "overall_average": 87.4, "services": [ { "service": "auth-service", "overall_score": "96.0", "status": "COMPLIANT" }, { "service": "product-svc", "overall_score": "90.0", "status": "COMPLIANT" }, { "service": "checkout-service", "overall_score": "82.0", "status": "AT RISK" }, { "service": "email-svc", "overall_score": "74.0", "status": "AT RISK" }, { "service": "fraud-detection-svc", "overall_score": "68.0", "status": "NON-COMPLIANT" } ] } ``` ## MCP 代理 - 自然语言查询 `mcp_agent` 模块在所有 NeuralWatch Splunk index 之上实现了对话式查询接口。 ### 运行代理 ``` python mcp_agent/cli.py ``` ### 示例查询 ``` You: How much did we spend on GPT-4o today? NeuralWatch: GPT-4o cost $14.23 today across 4 services. checkout-service is the top spender at $6.77 (47.6% of total GPT-4o spend). You: Which service has the most injection incidents this week? NeuralWatch: auth-service leads with 47 HIGH/CRITICAL injection events this week, followed by checkout-service with 31 incidents. You: What is the average latency for Claude models? NeuralWatch: Claude-3-Opus averages 1,847ms (p95: 3,200ms). Claude-3-Sonnet averages 892ms (p95: 1,450ms). ``` ### SPL 生成的工作原理 `spl_generator.py` 模块使用带有专用 system prompt 的 LLM,其中包括: - NeuralWatch index schema 文档 - 每个 sourcetype 的可用字段 - 自然语言 → SPL 翻译的 few-shot 示例 - 用于成本、延迟和安全查询的常见聚合模式 ## 配置参考 ### 环境变量 | 变量 | 必需 | 描述 | |---|---|---| | `SPLUNK_HEC_URL` | 是 | 完整的 HEC endpoint(例如 `https://localhost:8088/services/collector/event`) | | `SPLUNK_HEC_TOKEN` | 是 | Splunk HEC 身份验证 token | | `SPLUNK_HOST` | 否 | Splunk Management API 主机(默认值:`localhost`) | | `SPLUNK_PORT` | 否 | Splunk Management API 端口(默认值:`8089`) | | `SPLUNK_USERNAME` | 否 | Splunk 管理员用户名(默认值:`admin`) | | `SPLUNK_PASSWORD` | 否 | Splunk 管理员密码(MCP 代理和合规报告器必需) | | `OPENAI_API_KEY` | 否 | OpenAI API 密钥(仅在真实 AI 调用和 MCP 代理时必需) | 在仓库根目录中创建一个 `.env` 文件(已被 git-ignored): ``` SPLUNK_HEC_URL=https://localhost:8088/services/collector/event SPLUNK_HEC_TOKEN=your-hec-token-here SPLUNK_HOST=localhost SPLUNK_PORT=8089 SPLUNK_USERNAME=admin SPLUNK_PASSWORD=your-splunk-password OPENAI_API_KEY=sk-your-openai-key ``` ### `instrument()` 参数 | 参数 | 类型 | 默认值 | 描述 | |---|---|---|---| | `service` | `str` | - | 用于遥测归属的服务名称 | | `team` | `str` | - | 用于遥测归属的团队名称 | | `splunk_hec_url` | `str` | - | Splunk HEC endpoint URL | | `splunk_hec_token` | `str` | - | Splunk HEC token | | `capture_prompts` | `bool` | `True` | 启用对 `neuralwatch_injections` 的 prompt 捕获 | | `verify_ssl` | `bool` | `False` | 为 HEC 请求启用 SSL 证书验证 | ## 开发 ### 设置 ``` git clone https://github.com/your-org/neuralwatch.git cd neuralwatch pip install -e ".[dev]" ``` ### 运行测试 ``` pytest tests/ -v --cov=neuralwatch_sdk ``` ### 运行实时模拟器 ``` python demo/live_simulator.py ``` ### 代码质量 ``` ruff check neuralwatch_sdk/ mypy neuralwatch_sdk/ ``` ### 构建 Splunk App 包 ``` tar -czf splunk_app.tar.gz splunk_app/ ``` ### 项目提交历史 | Commit | 描述 | |---|---| | `d4d0faa` | `feat(sdk)` - 核心 monkey-patching 引擎和非阻塞 HEC 转发器 | | `22fff19` | `feat(splunk)` - App 元数据、自定义 props、成本/合规查找 | | `bad5602` | `feat(observability)` - AI 舰队观测平台仪表板和批量模拟器 | | `95555fd` | `feat(security)` - Prompt 注入哨兵和 Foundation-Sec 分类器 | | `d87a5b8` | `feat(mcp)` - MCP 客户端、代理桥接和 NL-to-SPL 编译器 | | `8ec8be3` | `feat(compliance)` - 欧盟 AI 法案评分仪表板和单元/集成测试 | | `8273880` | `feat(demo)` - 带有模拟 OpenAI 客户端的连续实时遥测模拟器 | | `1b21137` | `fix(compliance)` - 实时 index 查询并解决了空的仪表板面板问题 | | `f517893` | `feat(sdk)` - 线程本地会话跟踪、atexit 刷新、PyPI 命名空间隔离 | | `4c3d3b8` | `feat(demo)` - 更新模拟器以与欧盟 AI 法案仪表板风险类别保持一致 | | `1c14979` | `build(release)` - 确定的 Splunk App 发布构件 v1.0.0 | ## 许可证 该项目基于 **MIT License** 授权 - 有关详细信息,请参阅 [LICENSE](LICENSE) 文件。 ``` MIT License Copyright (c) 2026 NeuralWatch Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ```
Patches OpenAI/Claude"] Cost["cost_estimator
USD Pricing lookup"] Fwd["forwarder
Queue-backed async thread"] SDK --> Inst Inst --> Cost Cost --> Fwd end subgraph Splunk Enterprise [Splunk Log Analytics] HEC["HTTP Event Collector"] Index1[("neuralwatch_ai_calls")] Index2[("neuralwatch_injections")] Fwd -->|HTTPS HEC| HEC HEC --> Index1 HEC --> Index2 end subgraph User Interface [Telemetry Dashboards] Dash1["AI Fleet Observatory"] Dash2["Prompt Injection Sentinel"] Dash3["EU AI Act Compliance"] MCP["MCP Query Agent"] Index1 --> Dash1 Index2 --> Dash2 Index1 --> Dash3 Index2 --> Dash3 MCP -->|SPL Query via API| Index1 end ``` ## 模块分解 ### 模块 A - Prompt 注入哨兵 Prompt 注入哨兵会捕获通过已埋点的 LLM 客户端发送的每个 prompt,并使用受 Foundation-Sec 模型架构启发的启发式分类引擎对其对抗性内容进行分类。 **工作原理:** ``` flowchart LR Prompt["User Prompt"] -->|Intercepted by SDK| Classify["foundation_sec_classify.py"] Classify --> Pattern{"Pattern Match?"} Pattern -->|"ignore all previous..." / DAN mode| High["Critical / High Risk"] Pattern -->|"bypass input validation" / XSS| Med["Medium Risk"] Pattern -->|"Benign requests"| Low["Low Risk"] High -->|Assign Injection Score 0.0 - 1.0| Score["Telemetry Event"] Med -->|Assign Injection Score 0.0 - 1.0| Score Low -->|Assign Injection Score 0.0 - 1.0| Score Score -->|Route to neuralwatch_injections| Index[("Splunk Index")] Index --> Dash["Prompt Injection Sentinel Dashboard"] ``` **检测到的威胁类别:** | 风险等级 | 分数范围 | 示例模式 | |---|---|---| | `CRITICAL` | 0.93 – 0.98 | `ignore all previous instructions`, `print system prompt verbatim`, `DAN mode` | | `HIGH` | 0.72 – 0.85 | `grant me access`, `output passwords`, `exfiltrate` | | `MEDIUM` | 0.42 – 0.62 | `bypass input validation`, `sql injection`, `cross-site scripting` | | `LOW` | 0.05 – 0.20 | 良性请求 | **会话持久性检测:** 哨兵会跨多个事件跟踪 `session_id`。如果从同一会话接收到超过 5 个 `HIGH`/`CRITICAL` 事件的服务,将触发提升的 Art. 9 风险评分。 ### 模块 B - NLP 查询代理 (MCP) NeuralWatch MCP 代理提供对 Splunk 中所有遥测数据的自然语言查询访问。它将英语问题转换为 SPL,通过 Splunk Management API 执行,并使用 LLM 合成易于理解的答案。 ``` flowchart TD User["User Question: 'How much did we spend on GPT-4o?'"] -->|Input| Gen["spl_generator.py
NL to SPL Compiler"] Gen -->|Generated SPL Query| Client["mcp_client.py
Splunk SDK Runner"] Client -->|API Request| Splunk[("neuralwatch_ai_calls")] Splunk -->|Raw Results JSON| Synth["agent.py
LLM Synthesizer"] Synth -->|Formatted Summary| Out["User Response: 'GPT-4o cost $12.47 across 3 services...'"] ``` **通过 CLI 可用:** ``` python mcp_agent/cli.py ``` ### 模块 C - AI 舰队观测平台 AI 舰队观测平台是主要的实时操作仪表板,可实时查看所有已埋点服务的 AI API 成本、延迟、token 消耗和模型使用模式。 **跟踪的关键指标:** | 指标 | 来源 | 刷新频率 | |---|---|---| | AI API 总成本 (USD) | 每次调用的 `cost_usd` | 15秒 | | 平均延迟 (ms) | 每次调用的 `latency_ms` | 15秒 | | 错误率 (%) | `status=error` 计数 | 15秒 | | 各模型成本 | 按 model 分组的聚合 `cost_usd` | 15秒 | | 各服务成本 | 按 service 分组的聚合 `cost_usd` | 15秒 | | 延迟 p50/p95 | 各模型的百分位统计数据 | 15秒 | | 活动 AI 调用 (时间图表) | 时间序列调用量 | 15秒 | ### 模块 D - 欧盟 AI 法案合规 NeuralWatch 持续为每个受监控的服务计算欧盟 AI 法案合规分数,将实时遥测数据和静态策略基线映射到五个关键条款。 **评分模型:** ``` graph TD subgraph Adherence [EU AI Act Compliance Scoring Model] Art9["Art. 9: Risk Management
100 - high_incidents * 5"] Art13["Art. 13: Transparency
100 if disclosure_enabled = 1, else 0"] Art14["Art. 14: Human Oversight
100 if no review, else threshold * 100"] Art17["Art. 17: Quality Management
1 - error_rate * 100"] Art72["Art. 72: Systemic Risk
90 Adjusted by Latency Drift"] end Art9 -->|Average| Score["Overall Compliance Score"] Art13 -->|Average| Score Art14 -->|Average| Score Art17 -->|Average| Score Art72 -->|Average| Score Score --> Threshold{"Score Threshold"} Threshold -->|Score >= 90| Comp["✅ COMPLIANT"] Threshold -->|Score >= 70| Risk["⚠️ AT RISK"] Threshold -->|Score < 70| Non["❌ NON-COMPLIANT"] ``` ## 数据流程图 ``` sequenceDiagram participant App as Your Application participant SDK as neuralwatch_sdk participant Queue as Background Queue participant HEC as Splunk HEC participant Splunk as Splunk Indexes participant Dashboard as Dashboards App->>SDK: client.chat.completions.create(...) SDK->>SDK: Extract model, tokens, latency, cost SDK->>SDK: Hash prompt text SDK->>Queue: Enqueue AICallEvent (non-blocking) SDK->>Queue: Enqueue PromptEvent (if capture_prompts=True) SDK->>App: Return API response (zero added latency) Queue-->>HEC: POST /services/collector/event HEC-->>Splunk: Index neuralwatch_ai_calls HEC-->>Splunk: Index neuralwatch_injections Dashboard->>Splunk: SPL Query (every 15s) Splunk-->>Dashboard: Aggregated results Dashboard-->>Dashboard: Render live charts ``` ## 仓库结构 ``` NeuralWatch/ │ ├── neuralwatch_sdk/ # PyPI-publishable Python SDK │ ├── __init__.py # Public API: instrument, set_session_id, trace_context │ ├── instrumentor.py # Core monkey-patching engine (OpenAI + Anthropic) │ ├── forwarder.py # Non-blocking HEC telemetry queue with atexit flush │ ├── cost_estimator.py # Per-model USD pricing table and calculator │ ├── cli.py # `neuralwatch` CLI (init / status / demo) │ └── templates/ # App scaffolding templates │ ├── splunk_app/ # Installable Splunk App │ ├── default/ │ │ ├── app.conf # App metadata │ │ ├── props.conf # Sourcetype extraction rules │ │ ├── transforms.conf # Lookup references │ │ ├── savedsearches.conf # Scheduled alert queries │ │ └── data/ui/views/ # Dashboard XML definitions │ │ ├── neuralwatch_main.xml # AI Fleet Observatory │ │ ├── neuralwatch_injection.xml # Prompt Injection Sentinel │ │ └── neuralwatch_compliance.xml # EU AI Act Compliance │ ├── bin/ │ │ ├── foundation_sec_classify.py # Batch heuristic classifier │ │ └── compliance_score.py # SDK compliance score reporter │ └── lookups/ │ ├── neuralwatch_compliance_baseline.csv # Per-service policy config │ └── neuralwatch_cost_model.csv # Model pricing table │ ├── mcp_agent/ # Natural language Splunk query agent │ ├── agent.py # Core interrogator and answer synthesizer │ ├── mcp_client.py # Splunk SDK query runner │ ├── spl_generator.py # NL → SPL compiler with LLM │ ├── cli.py # Interactive CLI entry point │ └── prompts/ │ └── system_prompt.txt # Agent system prompt with few-shot SPL examples │ ├── demo/ │ ├── live_simulator.py # Continuous telemetry simulator (mocked OpenAI) │ └── dummy_app.py # Integration template for real OpenAI SDK │ ├── tests/ │ ├── unit/ │ │ └── test_instrumentor.py # Unit tests for SDK instrumentation logic │ └── integration/ │ └── test_hec_pipeline.py # End-to-end HEC pipeline tests │ ├── splunk_app.tar.gz # Pre-packaged release artifact for Splunk Web upload ├── pyproject.toml # Build config for pip / PyPI packaging ├── requirements.txt # Runtime dependencies ├── requirements-dev.txt # Development and test dependencies └── LICENSE # MIT License ``` ## 快速开始 ### 前置条件 | 要求 | 版本 | |---|---| | Python | ≥ 3.9 | | Splunk Enterprise | ≥ 9.0 | | Splunk HTTP Event Collector | 已启用 | | OpenAI SDK | ≥ 1.0.0(可选 - 仅在使用真实调用时) | | Anthropic SDK | ≥ 0.3.0(可选 - 仅在使用真实调用时) | ### 1. 安装 SDK **从 PyPI 安装(生产环境 - [pypi.org/project/neuralwatch-splunk](https://pypi.org/project/neuralwatch-splunk/)):** ``` pip install neuralwatch-splunk ``` **从源码安装(开发环境):** ``` git clone https://github.com/geeked-anshuk666/NeuralWatch.git cd NeuralWatch pip install -e . ``` **验证安装:** ``` neuralwatch --help ``` ### 2. 初始化 NeuralWatch 运行交互式设置向导。它将验证您的 HEC 连接并生成本地配置文件: ``` neuralwatch init ``` 系统将提示您输入: - **服务名称** - 您的应用程序名称(例如 `checkout-service`) - **团队名称** - 所属团队(例如 `payments-eng`) - **Splunk HEC URL** - 例如 `https://localhost:8088/services/collector/event` - **HEC Token** - 您的 Splunk HEC token(掩码输入) 这将创建包含您设置的 `.neuralwatch/config.json` 文件。 ### 3. 接入您的应用程序 在应用程序的入口点添加**两行**代码: ``` import openai from neuralwatch_sdk import instrument, set_session_id # 启动时初始化一次 instrument( service="my-service", team="my-team", splunk_hec_url="https://localhost:8088/services/collector/event", splunk_hec_token="your-hec-token", capture_prompts=True, verify_ssl=False ) # 可选:设置用于追踪的 session 或 user ID(类型安全 - 无需更改 SDK) set_session_id("user-session-abc123") # 像往常一样使用 OpenAI - NeuralWatch 会自动捕获所有内容 client = openai.OpenAI(api_key="your-key") response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "How do I reset my password?"}] ) ``` **就是这样。** NeuralWatch 会拦截调用,提取所有遥测数据,并将其发送到 Splunk,同时不会更改响应或给您的应用程序增加任何可观察到的延迟。 #### 使用 `auto_instrument()`(配置文件驱动) 如果您希望从 `neuralwatch init` 创建的 `.neuralwatch/config.json` 文件中加载配置: ``` from neuralwatch_sdk import auto_instrument auto_instrument() ``` #### 使用 `trace_context()`(作用域上下文管理) 用于 Web 框架中的请求范围追踪: ``` from neuralwatch_sdk import trace_context import openai client = openai.OpenAI() with trace_context(session_id=request.user.id): # All AI calls within this block are tagged with the user's session ID response = client.chat.completions.create(...) ``` ### 4. 安装 Splunk App #### 选项 A:通过 Splunk Web 上传(推荐) 1. 导航至 **Splunk Web** → **Apps** → **Manage Apps** 2. 点击 **Install app from file** 3. 从仓库根目录上传 `splunk_app.tar.gz` 4. 如果是更新,请勾选 **Overwrite app** 5. 点击 **Upload** 6. 出现提示时重启 Splunk #### 选项 B:手动安装 ``` # 将 app 目录复制到你的 Splunk home cp -r splunk_app/ $SPLUNK_HOME/etc/apps/neuralwatch/ $SPLUNK_HOME/bin/splunk restart ``` #### 创建所需的 Index 运行 index 设置脚本(需要 Splunk Management API 凭据): ``` python demo/setup_indexes.py ``` 或者在 Splunk Web → **Settings** → **Indexes** 中手动创建它们: | Index 名称 | 类型 | Sourcetypes | |---|---|---| | `neuralwatch_ai_calls` | 事件 | `nw:ai_call` | | `neuralwatch_injections` | 事件 | `nw:prompt` | ### 5. 运行实时模拟器 模拟器提供连续的真实 AI 遥测事件流——包括正常的 API 调用、对抗性注入尝试以及模拟的持久攻击者会话——无需真实的 OpenAI API 密钥。 ``` python demo/live_simulator.py ``` 模拟器将: - 每 **2 秒**触发一次新的模拟 AI 事件 - 将 **40% 的事件**作为对抗性注入尝试路由(HIGH/CRITICAL 风险) - 模拟针对 `auth-service` 的**持久会话攻击**以推动 Art. 9 评分 - 生成 **~10% 的错误事件**以填充 Art. 17 质量指标 - 应用启发式分类并实时填充 `injection_score` 和 `risk_level` 字段 30 秒后打开您的 Splunk 仪表板,即可查看实时更新的指标。 ## SDK 参考 ### `instrument()` 主要的埋点函数。在应用程序启动时调用一次。 ``` from neuralwatch_sdk import instrument instrument( service: str, # Service identifier (e.g., "checkout-service") team: str, # Team identifier (e.g., "payments-eng") splunk_hec_url: str, # Full HEC endpoint URL splunk_hec_token: str, # Splunk HEC authentication token capture_prompts: bool = True, # Whether to capture prompt text for injection analysis verify_ssl: bool = False # SSL certificate verification ) ``` **修补内容:** 使用带 `setattr` 的 monkey-patching 修补 `openai.resources.chat.completions.Completions.create` 和 `anthropic.resources.messages.Messages.create`。原始方法会被保留并调用——NeuralWatch 只是包装了它们。 **每次 API 调用发出的事件:** | 事件 | 目标 Index | 字段 | |---|---|---| | `AICallEvent` | `neuralwatch_ai_calls` | `call_id`, `service`, `team`, `model`, `provider`, `latency_ms`, `input_tokens`, `output_tokens`, `cost_usd`, `status`, `finish_reason`, `prompt_hash` | | `PromptEvent` | `neuralwatch_injections` | `call_id`, `service`, `team`, `prompt_text`, `session_id`, `injection_score`, `risk_level` | ### `set_session_id()` 和 `trace_context()` 线程本地会话跟踪——**类型安全**且兼容原生 SDK 类型检查器。 ``` from neuralwatch_sdk import set_session_id, trace_context # 简单的 setter(对该 thread 持久) set_session_id("user-abc-123") # Context manager(退出时自动恢复之前的 session) with trace_context(session_id="request-xyz-456"): response = client.chat.completions.create(...) # 此处 session_id 会自动恢复为之前的值 ``` ### `auto_instrument()` 从 `.neuralwatch/config.json` 读取配置并自动调用 `instrument()`。适用于通过 `neuralwatch init` 部署的应用程序。 ``` from neuralwatch_sdk import auto_instrument auto_instrument() ``` ### CLI 命令 ``` # 初始化 NeuralWatch 并配置 HEC 连接 neuralwatch init [--service NAME] [--team NAME] [--splunk-url URL] [--token TOKEN] # 检查当前配置和连接状态 neuralwatch status # 发送 100 个测试事件以验证 telemetry pipeline neuralwatch demo ``` ## Splunk App 仪表板 ### 仪表板 1:AI 舰队观测平台 (`neuralwatch_main`) 为工程团队提供的主要操作仪表板。 | 面板 | 查询 | 洞察 | |---|---|---| | 总成本 (24h) | `sum(cost_usd)` | 所有 AI 服务花费的总 USD | | 平均延迟 | `avg(latency_ms)` | 所有模型的平均响应时间 | | 错误率 % | `errors/total × 100` | API 可靠性指标 | | 各模型成本 | 按 `model` 分组 | 哪些模型正在推动支出 | | 各服务成本 | 按 `service` 分组 | 哪些团队是支出大户 | | 延迟 p50/p95 | 百分位统计数据 | 各模型的尾部延迟可见性 | | 调用量 (时间图表) | `timechart span=5m count` | 随时间变化的调用率趋势 | ### 仪表板 2:Prompt 注入哨兵 (`neuralwatch_injection`) 用于检测和跟踪对抗性 prompt 活动的安全仪表板。 | 面板 | 查询 | 洞察 | |---|---|---| | 活动事件 (24h) | `risk_level IN (HIGH,CRITICAL)` | 总计高严重性威胁 | | 威胁分布 | `stats count by risk_level` | 风险等级分布饼图 | | 各服务事件 | `stats count by service` | 哪些服务最受针对 | | 会话持久性 | `stats dc(session_id) by service` | 重复的攻击者会话跟踪 | | 注入趋势 | `timechart span=5m count by risk_level` | 威胁活动时间轴 | ### 仪表板 3:欧盟 AI 法案合规 (`neuralwatch_compliance`) 将实时遥测映射到法规条款评分的合规监控仪表板。 | 面板 | 条款 | 指标 | |---|---|---| | 完全合规的服务 | Art. 13 + 14 | `disclosure_enabled=1 AND human_review_required=0` | | 活动注入事件 | Art 9 | `risk_level IN (HIGH, CRITICAL)` | | 需要人工审查的服务 | Art. 14 | `human_review_required=1` | | 质量错误率 % | Art. 17 | `errors/total × 100` | | 各服务合规记分卡 | All | 各服务的完整评分矩阵 | | 各服务注入事件 | Art. 9 | 事件计数的条形图 | | 披露状态分布 | Art. 13 | 披露合规性的饼图 | | 各服务错误率 | Art. 17 | 各服务的质量管理 | | 各模型延迟漂移 | Art. 72 | p50 与 p95 系统性风险 | | 威胁活动时间轴 | Art. 9 | 每分钟实时注入事件 | ## 安全性设计 NeuralWatch 遵循安全默认设计原则: | 控制措施 | 实现方式 | |---|---| | **机密隔离** | HEC token 绝不会被记录或嵌入源代码中。从环境变量或 `.neuralwatch/config.json`(已 git-ignored)中读取。 | | **Prompt 哈希** | 仅当 `capture_prompts=True` 时,才会将完整 prompt 文本存储在 `nw:prompt` sourcetype 下。Prompt 哈希(SHA-256,截断为 16 个字符)仅与 AI 调用事件一起存储。 | | **非阻塞转发** | 所有遥测均异步排队。转发器在后台 daemon 线程上运行,绝不阻塞应用程序的热路径。 | | **优雅失败** | 每个埋点 hook 都包装在 `try/except` 中。如果 NeuralWatch 遇到错误,您的应用程序将继续正常运行——遥测将被静默丢弃。 | | **SSL 验证** | 可根据部署进行配置。对于使用自签名证书的本地 Splunk 设置,默认禁用。建议在生产环境中使用 `verify_ssl=True`。 | | **队列溢出保护** | 转发器队列的最大容量为 10,000 个事件。溢出的事件将被丢弃并记录警告日志,以防止内存增长。 | | **atexit 刷新** | 在应用程序关闭时,SDK 会等待最多 5 秒以完全排空遥测队列,确保在正常退出时不会丢失任何事件。 | ## 欧盟 AI 法案合规评分 合规评分引擎会根据五个欧盟 AI 法案条款为每个受监控的服务计算加权分数。通过将实时遥测 index 与静态策略基线 CSV (`neuralwatch_compliance_baseline.csv`) 进行连接来实时计算分数。 ### 策略基线配置 `splunk_app/lookups/neuralwatch_compliance_baseline.csv` 文件定义了各服务的合规策略: ``` service,disclosure_enabled,human_review_required,human_review_threshold,risk_category,ai_act_scope checkout-service,1,1,0.95,high_risk,yes auth-service,1,0,0.0,limited_risk,yes fraud-detection-svc,1,1,0.95,high_risk,yes product-svc,1,0,0.0,minimal_risk,yes email-svc,0,0,0.0,minimal_risk,yes ``` | 列 | 描述 | |---|---| | `disclosure_enabled` | 服务是否向最终用户披露 AI 使用情况 (Art. 13) | | `human_review_required` | AI 输出是否强制要求人工审查 (Art. 14) | | `human_review_threshold` | 需要人工审查的置信度阈值 | | `risk_category` | 欧盟 AI 法案风险分类 (`high_risk`, `limited_risk`, `minimal_risk`) | | `ai_act_scope` | 该服务是否属于欧盟 AI 法案的适用范围 | ### 以编程方式运行合规报告 ``` python splunk_app/bin/compliance_score.py ``` **示例输出:** ``` { "status": "success", "overall_average": 87.4, "services": [ { "service": "auth-service", "overall_score": "96.0", "status": "COMPLIANT" }, { "service": "product-svc", "overall_score": "90.0", "status": "COMPLIANT" }, { "service": "checkout-service", "overall_score": "82.0", "status": "AT RISK" }, { "service": "email-svc", "overall_score": "74.0", "status": "AT RISK" }, { "service": "fraud-detection-svc", "overall_score": "68.0", "status": "NON-COMPLIANT" } ] } ``` ## MCP 代理 - 自然语言查询 `mcp_agent` 模块在所有 NeuralWatch Splunk index 之上实现了对话式查询接口。 ### 运行代理 ``` python mcp_agent/cli.py ``` ### 示例查询 ``` You: How much did we spend on GPT-4o today? NeuralWatch: GPT-4o cost $14.23 today across 4 services. checkout-service is the top spender at $6.77 (47.6% of total GPT-4o spend). You: Which service has the most injection incidents this week? NeuralWatch: auth-service leads with 47 HIGH/CRITICAL injection events this week, followed by checkout-service with 31 incidents. You: What is the average latency for Claude models? NeuralWatch: Claude-3-Opus averages 1,847ms (p95: 3,200ms). Claude-3-Sonnet averages 892ms (p95: 1,450ms). ``` ### SPL 生成的工作原理 `spl_generator.py` 模块使用带有专用 system prompt 的 LLM,其中包括: - NeuralWatch index schema 文档 - 每个 sourcetype 的可用字段 - 自然语言 → SPL 翻译的 few-shot 示例 - 用于成本、延迟和安全查询的常见聚合模式 ## 配置参考 ### 环境变量 | 变量 | 必需 | 描述 | |---|---|---| | `SPLUNK_HEC_URL` | 是 | 完整的 HEC endpoint(例如 `https://localhost:8088/services/collector/event`) | | `SPLUNK_HEC_TOKEN` | 是 | Splunk HEC 身份验证 token | | `SPLUNK_HOST` | 否 | Splunk Management API 主机(默认值:`localhost`) | | `SPLUNK_PORT` | 否 | Splunk Management API 端口(默认值:`8089`) | | `SPLUNK_USERNAME` | 否 | Splunk 管理员用户名(默认值:`admin`) | | `SPLUNK_PASSWORD` | 否 | Splunk 管理员密码(MCP 代理和合规报告器必需) | | `OPENAI_API_KEY` | 否 | OpenAI API 密钥(仅在真实 AI 调用和 MCP 代理时必需) | 在仓库根目录中创建一个 `.env` 文件(已被 git-ignored): ``` SPLUNK_HEC_URL=https://localhost:8088/services/collector/event SPLUNK_HEC_TOKEN=your-hec-token-here SPLUNK_HOST=localhost SPLUNK_PORT=8089 SPLUNK_USERNAME=admin SPLUNK_PASSWORD=your-splunk-password OPENAI_API_KEY=sk-your-openai-key ``` ### `instrument()` 参数 | 参数 | 类型 | 默认值 | 描述 | |---|---|---|---| | `service` | `str` | - | 用于遥测归属的服务名称 | | `team` | `str` | - | 用于遥测归属的团队名称 | | `splunk_hec_url` | `str` | - | Splunk HEC endpoint URL | | `splunk_hec_token` | `str` | - | Splunk HEC token | | `capture_prompts` | `bool` | `True` | 启用对 `neuralwatch_injections` 的 prompt 捕获 | | `verify_ssl` | `bool` | `False` | 为 HEC 请求启用 SSL 证书验证 | ## 开发 ### 设置 ``` git clone https://github.com/your-org/neuralwatch.git cd neuralwatch pip install -e ".[dev]" ``` ### 运行测试 ``` pytest tests/ -v --cov=neuralwatch_sdk ``` ### 运行实时模拟器 ``` python demo/live_simulator.py ``` ### 代码质量 ``` ruff check neuralwatch_sdk/ mypy neuralwatch_sdk/ ``` ### 构建 Splunk App 包 ``` tar -czf splunk_app.tar.gz splunk_app/ ``` ### 项目提交历史 | Commit | 描述 | |---|---| | `d4d0faa` | `feat(sdk)` - 核心 monkey-patching 引擎和非阻塞 HEC 转发器 | | `22fff19` | `feat(splunk)` - App 元数据、自定义 props、成本/合规查找 | | `bad5602` | `feat(observability)` - AI 舰队观测平台仪表板和批量模拟器 | | `95555fd` | `feat(security)` - Prompt 注入哨兵和 Foundation-Sec 分类器 | | `d87a5b8` | `feat(mcp)` - MCP 客户端、代理桥接和 NL-to-SPL 编译器 | | `8ec8be3` | `feat(compliance)` - 欧盟 AI 法案评分仪表板和单元/集成测试 | | `8273880` | `feat(demo)` - 带有模拟 OpenAI 客户端的连续实时遥测模拟器 | | `1b21137` | `fix(compliance)` - 实时 index 查询并解决了空的仪表板面板问题 | | `f517893` | `feat(sdk)` - 线程本地会话跟踪、atexit 刷新、PyPI 命名空间隔离 | | `4c3d3b8` | `feat(demo)` - 更新模拟器以与欧盟 AI 法案仪表板风险类别保持一致 | | `1c14979` | `build(release)` - 确定的 Splunk App 发布构件 v1.0.0 | ## 许可证 该项目基于 **MIT License** 授权 - 有关详细信息,请参阅 [LICENSE](LICENSE) 文件。 ``` MIT License Copyright (c) 2026 NeuralWatch Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ```
满怀 ❤️ 为 AI 驱动的企业打造。MIT 授权。
标签:AI可观测性, LLM监控, Python SDK, 人工智能安全, 合规性, 提示词注入检测, 逆向工具