Harshit-J004/toolguard

GitHub: Harshit-J004/toolguard

面向 AI Agent 工具链的 Pytest 风格可靠性测试框架,上线前通过确定性模糊测试捕获幻觉 payload 和级联故障。

Stars: 5 | Forks: 1

# 🛡️ ToolGuard **AI agent 工具链的可靠性测试。** 在上线前捕获级联故障。让 agent 工具调用变得像单元测试让软件可靠一样可预测。 [![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue?style=flat-square)](https://python.org) [![License](https://img.shields.io/badge/license-MIT-green?style=flat-square)](LICENSE) [![Tests](https://img.shields.io/badge/tests-50%20passed-brightgreen?style=flat-square)](#) [![Integrations](https://img.shields.io/badge/integrations-6%20frameworks-blueviolet?style=flat-square)](#native-framework-integrations)
## 🧠 ToolGuard 实际解决的问题 目前,开发者不部署 AI agent 是因为它们本质上不稳定。它们会崩溃。 AI 有两个层面: 1. **层面 1:智能** (评估、推理、准确回答) 2. **层面 2:执行** (工具调用、链式调用、JSON payload、API) **ToolGuard 不测试层面 1。** 我们不在乎你的 AI 是否“聪明”或做出了正确的决策。那是 eval 框架的职责。 **ToolGuard 在数学上证明了层面 2。** 我们解决了 agent 在凌晨 3 点崩溃的问题,原因是 LLM 产生幻觉编造了一个 JSON key、传递了字符串而不是 int,或者外部 API 超时。 ## 🚀 零配置 — 60 秒内试用 ``` pip install py-toolguard toolguard run my_agent.py ``` 就是这样。ToolGuard 自动发现你的工具,使用幻觉攻击(null、类型不匹配、缺失字段)对其进行模糊测试,并打印可靠性报告。无需配置。 ``` 🚀 Auto-discovered 3 tools from my_agent.py • fetch_price (2 params) • calculate_position (3 params) • generate_alert (2 params) 🧪 Running 42 fuzz tests... ╔══════════════════════════════════════════════════════════════╗ ║ Reliability Score: my_agent ║ ╠══════════════════════════════════════════════════════════════╣ ║ Score: 64.3% ║ ║ Risk Level: 🟠 HIGH ║ ║ Deploy: 🚫 BLOCK ║ ╠══════════════════════════════════════════════════════════════╣ ║ ⚠️ Top Risk: Null values propagating through chain ║ ║ ⚠️ Bottleneck Tools: ║ ║ → fetch_price (50% success) ║ ║ → generate_alert (42% success) ║ ╚══════════════════════════════════════════════════════════════╝ 💡 fetch_price: Add null check for 'ticker' — LLM hallucinated None 💡 generate_alert: Field 'severity' expects int, got str from upstream tool ``` 或者使用 Python: ``` from toolguard import create_tool, test_chain, score_chain @create_tool(schema="auto") def parse_csv(raw_csv: str) -> dict: lines = raw_csv.strip().split("\n") headers = lines[0].split(",") records = [dict(zip(headers, line.split(","))) for line in lines[1:]] return {"headers": headers, "records": records, "row_count": len(records)} report = test_chain( [parse_csv], base_input={"raw_csv": "name,age\nAlice,30\nBob,35"}, test_cases=["happy_path", "null_handling", "malformed_data", "type_mismatch", "missing_fields"], ) score = score_chain(report) print(score.summary()) ``` ## 🤖 ToolGuard 的不同之处 大多数测试工具(LangSmith, Promptfoo)通过向实时 LLM 发送提示来测试你的 agent。这既慢、昂贵,又具有非确定性。 **ToolGuard 不使用 LLM 来运行测试。** 当你用 `@create_tool(schema="auto")` 装饰一个函数时,ToolGuard 会读取你的 Python 类型提示并自动生成 Pydantic schema。然后它利用该 schema 确切地知道该破坏哪些字段、交换哪些类型以及将哪些值置为 null —— 无需手动配置。 它就像一个针对 AI 工具执行的确定性模糊器,以编程方式注入 LLM 在生产中可能意外生成的各种错误数据: 1. 缺失字典键 2. Null 值沿链路传播 3. `str` 代替 `int` 4. 巨大的 10MB payload 以压测你的服务器 5. JSON 中额外/意外的字段 ToolGuard 不测试你的 AI 是否聪明。它测试你的 Python 代码是否足够健壮,以便在你的 AI 做蠢事时*幸存* —— 运行只需 1 秒,API 费用为 $0。 ## 功能特性 ### 🛡️ Layer-2 安全防火墙 (V3.0) ToolGuard 具有一个不可穿透的执行层安全框架,保护生产服务器免受严重的 LLM 漏洞利用。 - **人机回环风险等级:** 使用 `@create_tool(risk_tier=2)` 标记破坏性工具。ToolGuard 在数学上拦截这些调用,并在执行前原生流式传输终端批准提示,优雅地保护 `asyncio` 事件循环和无头守护进程环境。 - **递归提示注入模糊测试:** `test_chain` 模糊器自动将 `[SYSTEM OVERRIDE]` 执行 payload 注入你的流水线。一个定制的递归深度优先内存解析器扫描内部自定义对象序列化、字节数组和 `.casefold()` 字符串突变,以消除零日盲点。 - **黄金追踪 (DAG 监控):** 只需两行代码 (`with TraceTracker() as trace:`),ToolGuard 原生拦截 Python `contextvars`,以构建由 LangChain、CrewAI、Swarm 和 AutoGen 编排的所有工具的按时间顺序完美的有向无环图 (DAG)。 - **非确定性验证:** 惩罚 AI 的自我修正是一种反模式。开发者使用 `trace.assert_sequence(["auth", "refund"])` 在数学上强制执行强制性合规检查点,同时允许 LLM 完全自由地自主选择补充网络工具。 ### 🔍 Schema 验证 基于类型提示的自动 Pydantic 输入/输出验证。无需手动编写 schema。 ``` @create_tool(schema="auto") def fetch_price(ticker: str) -> dict: ... ``` ### 🔗 链式测试 针对 **8 种边缘情况类别** 测试多工具链:null 处理、类型不匹配、缺失字段、格式错误数据、大 payload 等。 ``` report = test_chain( [fetch_price, calculate_position, generate_alert], base_input={"ticker": "AAPL"}, test_cases=["happy_path", "null_handling", "type_mismatch"], ) ``` ### ⚡ Async 支持 透明地支持 `def` 和 `async def` 工具。无需特殊标志。 ``` @create_tool(schema="auto") async def fetch_from_api(url: str) -> dict: async with httpx.AsyncClient() as client: resp = await client.get(url) return resp.json() # 相同 API — ToolGuard 自动处理 async report = test_chain([fetch_from_api, process_data], assert_reliability=0.95) ``` ### 🦇 沉浸式实时仪表板 在本地测试时,你不必盯着基础的打印日志。通过传递 `--dashboard`,ToolGuard 会启动一个精美、高对比度的暗色模式终端 UI(基于 Textual 构建)。 ``` toolguard run my_agent.py --dashboard ``` 它实时流式传输并发的模糊测试结果,实时计算指标,并准确追踪哪些函数在 payload 注入下崩溃 —— 全部封装在一个专用的黑客风格“任务控制”界面中。 ### 📊 可靠性评分 量化的信任度,包含风险等级和部署门槛。 ``` score = score_chain(report) if score.deploy_recommendation.value == "BLOCK": sys.exit(1) # CI/CD gate ``` ### ⏪ 本地崩溃重放 当远程工具在生产或测试中崩溃时,ToolGuard 会自动转储结构化的 JSON payload。你可以在本地即时重放确切的崩溃状态以查看堆栈跟踪。 ``` toolguard run my_agent.py --dump-failures toolguard replay .toolguard/failures/fail_1774068587_0.json ``` ### 🎯 边缘情况测试覆盖率 ToolGuard 为你提供 PyTest 风格的覆盖率指标。它不计算任意的行覆盖率,而是精确计算你的测试成功覆盖了 8 种已知 LLM 幻觉类别(null、缺失字段、类型不匹配等)的百分比,并列出未测试的内容。 ### ⚡ 极简 API 为了快速的 Jupyter Notebook 测试和快速演示,请使用高度便携的单行 Python 包装器。 ``` from toolguard import quick_check quick_check(my_agent_function, test_cases=["happy_path", "null_handling"]) ``` ### 🔄 重试与熔断器 内置生产级弹性模式。 ``` from toolguard import with_retry, RetryPolicy, CircuitBreaker, with_circuit_breaker @with_retry(RetryPolicy(max_retries=3, backoff_base=0.5)) def call_api(data: dict) -> dict: ... breaker = CircuitBreaker(failure_threshold=5, reset_timeout=60) @with_circuit_breaker(breaker) def call_flaky_service(data: dict) -> dict: ... ``` ### 🖥️ CLI ``` toolguard run my_agent.py # Zero-config auto-test toolguard run my_agent.py --dashboard # 🦇 Live immersive TUI control center toolguard test --chain my_chain.yaml # YAML-based chain test toolguard test --chain my_chain.yaml --html out.html # HTML report toolguard test --chain my_chain.yaml --junit-xml out.xml # JUnit XML for CI toolguard badge # Generate reliability badge toolguard check --tools my_tools.py # Check compatibility toolguard observe --tools my_tools.py # View tool stats toolguard init --name my_project # Scaffold project ``` ## 🔌 原生框架集成 ToolGuard 适用于你现有的工具。无需重写 —— 只需包装并模糊测试。 ``` # 🦜🔗 LangChain from langchain_core.tools import tool from toolguard import test_chain from toolguard.integrations.langchain import guard_langchain_tool @tool def search(query: str) -> str: """Search the web.""" return f"Results for {query}" guarded = guard_langchain_tool(search) report = test_chain([guarded], base_input={"query": "hello"}) ``` ``` # 🚀 CrewAI from crewai.tools import BaseTool from toolguard.integrations.crewai import guard_crewai_tool guarded = guard_crewai_tool(my_crew_tool) ``` ``` # 🦙 LlamaIndex from llama_index.core.tools import FunctionTool from toolguard.integrations.llamaindex import guard_llamaindex_tool llama_tool = FunctionTool.from_defaults(fn=my_function) guarded = guard_llamaindex_tool(llama_tool) ``` ``` # 🤖 Microsoft AutoGen from autogen_core.tools import FunctionTool from toolguard.integrations.autogen import guard_autogen_tool autogen_tool = FunctionTool(my_function, name="my_tool", description="...") guarded = guard_autogen_tool(autogen_tool) ``` ``` # 🐝 OpenAI Swarm from swarm import Agent from toolguard.integrations.swarm import guard_swarm_agent agent = Agent(name="My Agent", functions=[func_a, func_b]) guarded_tools = guard_swarm_agent(agent) # Returns list of GuardedTools ``` ``` # ⚡ FastAPI from toolguard.integrations.fastapi import as_fastapi_tool guarded = as_fastapi_tool(my_endpoint_function) ``` 所有 6 项集成均使用 **真实的 pip 安装库** 进行测试 —— 不是 mock,不是 duck-type。 ### 🧹 100% 真实测试 ToolGuard 的集成套件仅针对 LangChain、AutoGen、Swarm、FastAPI 和 CrewAI 的 *实际* PyPI 代码库实现运行。绝对没有伪造的兼容性 —— 这是针对实时库在数学上证明的。我们删除了所有虚假的“mock”测试,以确保可靠性标准纯正。 ## 🏗️ CI/CD 集成 ### GitHub Action 添加到任何仓库 —— 在 PR 上自动评论可靠性分数: ``` # .github/workflows/toolguard.yml name: ToolGuard Reliability Check on: [pull_request] jobs: reliability: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: Harshit-J004/toolguard@main with: script_path: src/agent.py github_token: ${{ secrets.GITHUB_TOKEN }} reliability_threshold: "0.95" ``` **PR 评论示例:** ### JUnit XML (Jenkins / GitLab CI) ``` toolguard test --chain config.yaml --junit-xml results.xml ``` 生成标准的 `` XML,Jenkins、GitLab CI 和 CircleCI 可原生解析。 ### 可靠性徽章 ``` toolguard badge ``` 为你的 README 生成 shields.io 徽章 markdown: ![ToolGuard Reliability](https://img.shields.io/badge/ToolGuard-92%25-brightgreen?logo=shield&style=flat-square) ## 📡 可观测性与生产警报 ### 1. 零延迟幻觉警报 在生产中捕获“LLM 漂移”。当 LLM 产生幻觉生成错误的 JSON payload 时,ToolGuard 会立即向你的团队发送后台警报,而不会拖慢 agent: ``` import toolguard toolguard.configure_alerts( slack_webhook_url="https://hooks.slack.com/...", discord_webhook_url="https://discord.com/api/webhooks/...", datadog_api_key="my-api-key", generic_webhook_url="https://my-dashboard.com/api/ingest" ) ``` *使用后台线程池构建,因此网络请求永远不会阻塞 LLM 运行时。* ### 2. OpenTelemetry 追踪 追踪开箱即用,支持 Jaeger、Zipkin、Datadog 等。 ``` from toolguard.core.tracer import init_tracing, trace_tool init_tracing(service_name="my-agent") @trace_tool def my_tool(data: dict) -> dict: ... ``` ## 架构 ``` toolguard/ ├── core/ │ ├── validator.py # @create_tool decorator + GuardedTool (sync + async) │ ├── chain.py # Chain testing engine (8 test types, async-aware) │ ├── schema.py # Auto Pydantic model generation │ ├── scoring.py # Reliability scoring + deploy gates │ ├── report.py # Failure analysis + suggestions │ ├── errors.py # Exception hierarchy + correlation IDs │ ├── retry.py # RetryPolicy + CircuitBreaker │ ├── tracer.py # OpenTelemetry integration │ └── compatibility.py # Schema conflict detection ├── alerts/ │ ├── manager.py # Abstract ThreadPool dispatcher │ ├── slack.py # Block Kit formatting │ ├── discord.py # Embed formatting │ └── datadog.py # HTTP Metrics + Events sink ├── cli/ │ └── commands/ # run, test, check, observe, badge, init ├── reporters/ │ ├── console.py # Rich terminal output │ ├── html.py # Standalone HTML reports │ ├── junit.py # JUnit XML for Jenkins/GitLab CI │ └── github.py # GitHub PR auto-commenter ├── integrations/ │ ├── langchain.py # LangChain adapter │ ├── crewai.py # CrewAI adapter │ ├── llamaindex.py # LlamaIndex adapter │ ├── autogen.py # Microsoft AutoGen adapter │ ├── swarm.py # OpenAI Swarm adapter │ ├── fastapi.py # FastAPI middleware │ └── openai_func.py # OpenAI function calling export ├── tests/ # 50 tests (sync + async + integration) ├── integration_tests/ # Real-library integration tests └── examples/ ├── test_alerts.py # Phase 4 webhook crash simulation ├── weather_chain/ # Working 3-tool example └── demo_failing_chain/ # Intentionally buggy (aha moment) ``` ## 为什么选择 ToolGuard? | | 没有 ToolGuard | 有 ToolGuard | |---|---|---| | **故障检测** | 凌晨 3 点的堆栈跟踪 | 部署前被捕获 | | **根本原因** | "第 47 行 TypeError" | "工具 A 返回了 'price' 的 null" | | **修复指导** | 无 | "添加默认值或验证响应" | | **信心** | "在我机器上能跑" | "92% 可靠性,低风险" | | **CI/CD** | 手动测试 | 流水线中的 `toolguard run` | | **成本** | $0.10/测试 (LLM 调用) | $0 (确定性模糊测试) | | **速度** | 30s (API 往返) | <1s (本地执行) | ## 技术栈 | 组件 | 技术 | 原因 | |---|---|---| | 核心语言 | Python 3.11 - 3.13 | Agent 生态标准 | | Schema 验证 | Pydantic v2 | 比 JSON Schema 快 3.5 倍 | | Async | 原生 asyncio | 企业级并发 | | 测试 | pytest (50 项测试) | CI/CD 原生 | | 可观测性 | OpenTelemetry | 供应商中立 | | CLI | Click + Rich | 美观的终端 UX | | CI/CD | GitHub Actions + JUnit | 一流的流水线支持 | | 分发 | PyPI | `pip install py-toolguard` | ## 许可证 MIT — 随意使用,分叉,发布。
**旨在让 AI agent 真正在生产中运行。** [GitHub](https://github.com/Harshit-J004/toolguard) · [PyPI](https://pypi.org/project/py-toolguard/)
标签:AI基础设施, API测试, Fuzzing, JSON校验, LLM应用开发, LNA, Pytest, Python, TLS, Tool Chains, 单元测试, 可靠性测试, 大模型安全, 安全规则引擎, 容错性, 无后门, 模式验证, 用户代理, 计算机取证, 质量保证, 逆向工具, 防御工具