cerbug45-ai-agent-tools

TotalClaw 作者 totalclaw

面向 AI 代理的 Python 实用工具库,提供文件操作、文本分析、数据转换、内存管理、数据验证等 6 大类 25+ 函数,仅依赖标准库,无外部依赖。

安装 / 下载方式

TotalClaw CLI推荐
totalclaw skills install shop:totalclaw:totalclaw~cerbug45-ai-agent-tools
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Atotalclaw~cerbug45-ai-agent-tools/file -o cerbug45-ai-agent-tools.md
## 概述(中文)

面向 AI 代理的 Python 实用工具库,提供文件操作、文本分析、数据转换、内存管理、数据验证等 6 大类 25+ 函数,仅依赖标准库,无外部依赖。

## 技能正文

# AI 代理工具 - AI 代理 Python 实用库

## 📖 概述

本库提供 AI 代理可直接使用的 Python 函数,涵盖文件操作、文本分析、数据转换、内存管理与数据验证等任务。

## ⚡ 快速开始

### 安装

#### 方法 1:从 GitHub 克隆
```bash
git clone https://github.com/cerbug45/ai-agent-tools.git
cd ai-agent-tools
```

#### 方法 2:直接下载
```bash
wget https://raw.githubusercontent.com/cerbug45/ai-agent-tools/main/ai_agent_tools.py
```

#### 方法 3:复制粘贴
将 `ai_agent_tools.py` 文件复制到项目目录即可。

### 要求
- Python 3.7 或更高版本
- 无外部依赖(仅使用标准库)

## 🛠️ 可用工具

### 1. FileTools - 文件操作

读取、写入及管理文件的操作。

**可用方法:**

```python
from ai_agent_tools import FileTools

# 读取文件
content = FileTools.read_file("path/to/file.txt")

# 写入文件
FileTools.write_file("path/to/file.txt", "Hello World!")

# 列出目录中的文件
files = FileTools.list_files(".", extension=".py")

# 检查文件是否存在
exists = FileTools.file_exists("path/to/file.txt")
```

**使用场景:**
- 读取配置文件
- 保存代理输出
- 列出可用资源
- 操作前检查文件是否存在

---

### 2. TextTools - 文本处理

从文本中提取信息并处理文本数据。

**可用方法:**

```python
from ai_agent_tools import TextTools

text = "Contact: john@example.com, phone: 0532 123 45 67"

# 提取邮箱
emails = TextTools.extract_emails(text)
# Output: ['john@example.com']

# 提取 URL
urls = TextTools.extract_urls("Visit https://example.com")
# Output: ['https://example.com']

# 提取电话号码
phones = TextTools.extract_phone_numbers(text)
# Output: ['0532 123 45 67']

# 统计词数
count = TextTools.word_count("Hello world from AI")
# Output: 4

# 文本摘要
summary = TextTools.summarize_text("Long text here...", max_length=50)

# 清理空白
clean = TextTools.clean_whitespace("Too   many    spaces")
# Output: "Too many spaces"
```

**使用场景:**
- 从文档提取联系信息
- 清理与格式化文本
- 文本摘要
- 从非结构化文本提取数据

---

### 3. DataTools - 数据转换

在不同数据格式间转换。

**可用方法:**

```python
from ai_agent_tools import DataTools

# 保存为 JSON
data = {"name": "Alice", "age": 30}
DataTools.save_json(data, "output.json")

# 加载 JSON 文件
loaded_data = DataTools.load_json("output.json")

# CSV 文本转字典列表
csv_text = """name,age,city
Alice,30,New York
Bob,25,London"""
data_list = DataTools.csv_to_dict(csv_text)
# Output: [{'name': 'Alice', 'age': '30', 'city': 'New York'}, ...]

# 字典列表转 CSV
data = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25}
]
csv = DataTools.dict_to_csv(data)
```

**使用场景:**
- 保存结构化数据
- 格式间转换
- 处理 API 响应
- 生成报告

---

### 4. UtilityTools - 通用工具

常用操作的辅助函数。

**可用方法:**

```python
from ai_agent_tools import UtilityTools

# 获取当前时间戳
timestamp = UtilityTools.get_timestamp()
# Output: "2026-02-15 14:30:25"

# 从文本生成唯一 ID
id = UtilityTools.generate_id("user_john_doe")
# Output: "a3f5b2c1"

# 计算百分比
percent = UtilityTools.calculate_percentage(25, 100)
# Output: 25.0

# 安全除法(避免除零错误)
result = UtilityTools.safe_divide(10, 0, default=0.0)
# Output: 0.0
```

**使用场景:**
- 事件时间戳
- 生成唯一标识符
- 安全数学运算
- 数据分析计算

---

### 5. MemoryTools - 内存管理

在代理执行期间存储与检索数据。

**可用方法:**

```python
from ai_agent_tools import MemoryTools

# 初始化内存
memory = MemoryTools()

# 存储值
memory.store("user_name", "Alice")
memory.store("session_id", "abc123")

# 检索值
name = memory.retrieve("user_name")
# Output: "Alice"

# 列出所有键
keys = memory.list_keys()
# Output: ["user_name", "session_id"]

# 删除值
memory.delete("session_id")

# 清空所有内存
memory.clear()
```

**使用场景:**
- 维护对话上下文
- 存储中间结果
- 会话管理
- 缓存计算值

---

### 6. ValidationTools - 数据验证

验证不同类型的数据。

**可用方法:**

```python
from ai_agent_tools import ValidationTools

# 验证邮箱
is_valid = ValidationTools.is_valid_email("user@example.com")
# Output: True

# 验证 URL
is_valid = ValidationTools.is_valid_url("https://example.com")
# Output: True

# 验证电话号码(土耳其格式)
is_valid = ValidationTools.is_valid_phone("0532 123 45 67")
# Output: True
```

**使用场景:**
- 输入验证
- 数据质量检查
- 表单验证
- 数据预处理

---

## 💡 完整使用示例

```python
from ai_agent_tools import (
    FileTools, TextTools, DataTools, 
    UtilityTools, MemoryTools, ValidationTools
)

# 初始化会话内存
memory = MemoryTools()

# 读取输入文件
text = FileTools.read_file("contacts.txt")

# 提取信息
emails = TextTools.extract_emails(text)
phones = TextTools.extract_phone_numbers(text)

# 验证提取的数据
valid_emails = [e for e in emails if ValidationTools.is_valid_email(e)]
valid_phones = [p for p in phones if ValidationTools.is_valid_phone(p)]

# 创建结构化数据
contacts = []
for i, (email, phone) in enumerate(zip(valid_emails, valid_phones)):
    contact = {
        "id": UtilityTools.generate_id(f"contact_{i}"),
        "email": email,
        "phone": phone,
        "timestamp": UtilityTools.get_timestamp()
    }
    contacts.append(contact)

# 保存结果
DataTools.save_json(contacts, "output/contacts.json")

# 存入内存
memory.store("total_contacts", len(contacts))
memory.store("last_processed", UtilityTools.get_timestamp())

print(f"Processed {len(contacts)} contacts")
print(f"Saved to: output/contacts.json")
```

## 🎯 最佳实践

### 1. 错误处理
文件操作务必用 try-except 包裹:

```python
try:
    content = FileTools.read_file("data.txt")
    # Process content
except Exception as e:
    print(f"Error reading file: {e}")
```

### 2. 内存管理
不再需要时清理内存:

```python
memory = MemoryTools()
# ... use memory ...
memory.clear()  # Clean up
```

### 3. 数据验证
处理前始终验证数据:

```python
if ValidationTools.is_valid_email(email):
    # Process email
    pass
else:
    print(f"Invalid email: {email}")
```

### 4. 路径处理
使用绝对路径或确保工作目录正确:

```python
import os

base_dir = os.path.dirname(__file__)
filepath = os.path.join(base_dir, "data", "file.txt")
content = FileTools.read_file(filepath)
```

## 🔧 高级用法

### 链式操作

```python
# 读取 -> 处理 -> 验证 -> 保存 流水线
text = FileTools.read_file("input.txt")
cleaned = TextTools.clean_whitespace(text)
emails = TextTools.extract_emails(cleaned)
valid = [e for e in emails if ValidationTools.is_valid_email(e)]
DataTools.save_json({"emails": valid}, "output.json")
```

### 创建自定义工作流

```python
class DataProcessor:
    def __init__(self):
        self.memory = MemoryTools()
        
    def process_document(self, filepath):
        # Read
        text = FileTools.read_file(filepath)
        
        # Extract
        emails = TextTools.extract_emails(text)
        urls = TextTools.extract_urls(text)
        
        # Store results
        self.memory.store("emails", emails)
        self.memory.store("urls", urls)
        
        # Generate report
        report = {
            "timestamp": UtilityTools.get_timestamp(),
            "file": filepath,
            "emails_found": len(emails),
            "urls_found": len(urls)
        }
        
        return report
```

## 📦 与 AI 代理集成

### 示例:LangChain 集成

```python
from langchain.tools import Tool
from ai_agent_tools import FileTools, TextTools

def create_file_reader_tool():
    return Tool(
        name="ReadFile",
        func=FileTools.read_file,
        description="Read contents of a file"
    )

def create_email_extractor_tool():
    return Tool(
        name="ExtractEmails",
        func=TextTools.extract_emails,
        description="Extract email addresses from text"
    )

tools = [create_file_reader_tool(), create_email_extractor_tool()]
```

### 示例:OpenAI Function Calling

```python
tools = [
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Read a file and return its contents",
            "parameters": {
                "type": "object",
                "properties": {
                    "filepath": {
                        "type": "string",
                        "description": "Path to the file"
                    }
                },
                "required": ["filepath"]
            }
        }
    }
]

# In your agent loop
def execute_function(name, arguments):
    if name == "read_file":
        return FileTools.read_file(arguments["filepath"])
```

## 🧪 测试

运行内置测试套件:

```bash
python ai_agent_tools.py
```

预期输出:
```
=== AI Ajanları İçin Araçlar Kütüphanesi ===

1. Dosya Araçları:
   Okunan içerik: Merhaba AI Ajanı!

2. Metin Araçları:
   Bulunan emailler: ['ali@example.com']
   Bulunan telefonlar: ['0532 123 45 67']

3. Veri Araçları:
   CSV çıktısı:
   isim,yaş
   Ali,25
   Ayşe,30

...

✓ T