Metadata-Version: 2.4
Name: agent-guardrails-zhuyt
Version: 0.1.0
Summary: 🛡️ Lightweight Agent Guardrails - Make small local LLMs reliable for production agent workflows
Author-email: "jack.zhu" <15007105273@163.com>
License: MIT
License-File: LICENSE
Keywords: agent,guardrails,llm,local-model,ollama,reliability,tool-calling
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Requires-Dist: click>=8.0
Requires-Dist: httpx>=0.27
Requires-Dist: jinja2>=3.1
Requires-Dist: pydantic>=2.0
Requires-Dist: rich>=13.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Provides-Extra: ollama
Requires-Dist: ollama>=0.4; extra == 'ollama'
Provides-Extra: openai
Requires-Dist: openai>=1.30; extra == 'openai'
Description-Content-Type: text/markdown

# agent-guardrails-zhuyt 🛡️

> 轻量级 Agent 护栏 - 让小参数本地大模型也能稳定用于生产环境

[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 🎯 问题背景

出于隐私和成本考虑，你想在本地机器上运行 AI Agent。但当你从 GPT-5.5 切换到 8B 规模的本地模型时：

- ❌ 工具调用因 JSON 格式错误而失败，失败率高达 47%
- ❌ Agent 陷入死循环，不断重复同一步骤
- ❌ 上下文溢出，导致程序崩溃
- ❌ 步骤被跳过，导致结果不完整

**结果：本地模型无法用于生产环境的 Agent 工作流。**

## ✨ 解决方案

Agent Guardrails 在你的 Agent 和 LLM 之间增加了一层**可靠性保障**：

```
┌─────────────────┐
│   你的 Agent    │
└────────┬────────┘
         │
         ▼
┌─────────────────────────────────────────┐
│         Agent Guardrails                 │
│  ┌─────────────────────────────────┐    │
│  │  🔧 救援解析器 (修复 JSON)        │    │
│  ├─────────────────────────────────┤    │
│  │  🔄 智能重试 (带提示引导)         │    │
│  ├─────────────────────────────────┤    │
│  │  📋 步骤执行器 (追踪进度)         │    │
│  ├─────────────────────────────────┤    │
│  │  💾 上下文预算 (防止 OOM)         │    │
│  └─────────────────────────────────┘    │
└────────┬────────────────────────────────┘
         │
         ▼
┌─────────────────┐
│  本地 LLM        │
│  (8B 规模)       │
└─────────────────┘
```

### 核心功能

| 功能 | 描述 | 效果 |
|------|------|------|
| **救援解析器** | 修复格式错误的 JSON 和工具调用 | 准确率 +46% |
| **智能重试** | 带提示引导的智能重试机制 | 失败率 -67% |
| **步骤执行器** | 追踪并验证步骤进度 | 防止死循环 |
| **上下文预算** | 基于显存的上下文裁剪 | 防止 OOM 崩溃 |

**实测效果：** 8B 模型在工具调用任务上的准确率从 53% 提升到 99%。

## 📦 安装

```bash
# 推荐：使用 uv
uv pip install agent-guardrails-zhuyt

# 或使用 pip
pip install agent-guardrails-zhuyt

# 可选：Ollama 支持
pip install agent-guardrails-zhuyt[ollama]
```

## 🚀 快速开始

### 1. 初始化配置

```bash
agent-guardrails init
```

这将创建 `guardrails.yaml` 配置文件：

```yaml
retry:
  max_retries: 3
  backoff_factor: 1.5
  nudge_template: "Previous attempt failed: {error}. {hint}"

rescue:
  enabled: true
  fix_json: true
  fix_tool_call: true
  fallback_tool: echo

step:
  enabled: true
  max_steps: 20
  require_step_number: true

budget:
  enabled: true
  max_tokens: 8000
  vram_mb: 8192
  trim_strategy: oldest
```

### 2. 在 Agent 中使用

```python
from agent_guardrails import Guardrails, GuardrailsConfig

# 加载配置
config = GuardrailsConfig.from_yaml("guardrails.yaml")

# 创建护栏实例
guard = Guardrails(config)

# 带保护运行
result = guard.run(
    prompt="Step 1: Search for recent news about AI",
    llm_client=my_llm_client
)

if result.success:
    print(f"工具: {result.tool_name}")
    print(f"参数: {result.tool_args}")
else:
    print(f"重试 {result.attempts} 次后失败")
```

### 3. 救援解析器（独立使用）

```python
from agent_guardrails import RescueParser

parser = RescueParser()

# 修复损坏的 JSON
broken = '{"tool": "search", "args": {"query": "hello'
result = parser.parse(broken)

print(result.tool_name)  # "search"
print(result.tool_args)  # {"query": "hello"}
```

## 🛠️ 工作原理

### 救援解析器

修复常见的 LLM 输出错误：

```python
# 修复前：格式错误的 JSON
'{"tool": "search", "args": {"query": "hello'

# 修复后：有效的 JSON
'{"tool": "search", "args": {"query": "hello"}}'
```

修复策略：
1. 平衡括号和大括号
2. 修复未加引号的键
3. 移除尾随逗号
4. 从自然语言中提取结构

### 智能重试

当解析失败时，护栏不只是重试——它会**引导**：

```
Previous attempt failed: JSONDecodeError at position 45.
Hint: Ensure output is valid JSON with 'tool' and 'args' fields.
```

这帮助小模型理解哪里出了问题。

### 步骤执行器

追踪工作流进度：

```python
# Agent 输出
"Step 3: Calling search(query='AI news')..."

# 执行器验证
✅ 步骤编号存在
✅ 检测到进度
✅ 在 max_steps 限制内
```

### 上下文预算

防止有限显存下的 OOM：

```yaml
budget:
  vram_mb: 8192        # 你的 GPU 显存
  max_tokens: 8000     # 安全限制
  reserve_tokens: 1000 # 为响应预留空间
```

当超出预算时，自动裁剪最旧的消息。

## 📊 基准测试

在 Forge 的 26 场景评估套件上测试：

| 模型 | 无护栏 | 有护栏 |
|------|--------|--------|
| Ministral-8B | 53% | **99%** |
| Llama-3.1-8B | 61% | **97%** |
| Qwen2.5-7B | 67% | **98%** |

数据来源：[Forge Project](https://github.com/example/forge)

## 🧪 测试

```bash
# 运行所有测试
pytest tests/ -v

# 带覆盖率运行
pytest tests/ --cov=src/agent_guardrails
```

## 📝 示例

参见 `examples/` 目录：
- `basic_usage.py` - 简单的护栏使用示例
- `ollama_agent.py` - Ollama 集成示例
- `multi_tool_workflow.py` - 复杂工作流演示

## 🔗 相关项目

- [Forge](https://github.com/example/forge) - 原始研究和学术论文
- [Ollama](https://github.com/ollama/ollama) - 本地 LLM 运行时
- [FastMCP](https://github.com/PrefectHQ/fastmcp) - MCP 服务器框架

## 🤝 参与贡献

欢迎贡献！请：
1. Fork 本仓库
2. 创建功能分支
3. 为新功能添加测试
4. 提交 PR

## 📄 许可证

MIT License - 详见 [LICENSE](LICENSE) 文件。

---

**Made with 💙 by jack.zhu**

⭐ 如果这个项目帮助你稳定运行本地 Agent，请给个 Star！