Harshit-J004/toolguard
GitHub: Harshit-J004/toolguard
面向 AI Agent 工具链的 Pytest 风格可靠性测试框架,上线前通过确定性模糊测试捕获幻觉 payload 和级联故障。
Stars: 5 | Forks: 1
# 🛡️ ToolGuard
**AI agent 工具链的可靠性测试。**
在上线前捕获级联故障。让 agent 工具调用变得像单元测试让软件可靠一样可预测。
[](https://python.org)
[](LICENSE)
[](#)
[](#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
```
生成标准的 `
**旨在让 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, 单元测试, 可靠性测试, 大模型安全, 安全规则引擎, 容错性, 无后门, 模式验证, 用户代理, 计算机取证, 质量保证, 逆向工具, 防御工具