☰
Python agent-tools 包实战案例与常见错误
2026/10/4 15:52:11 网站建设 项目流程

1. 引言

随着大语言模型(LLM)与智能体(Agent)技术的快速发展,开发者越来越需要一套轻量、可靠的工具封装库,来帮助 Agent 调用外部函数、解析参数、管理工具注册与执行。Python 的agent-tools包正是为解决这类问题而设计:它提供统一的工具定义、参数校验、自动文档生成和调用分发能力,让开发者可以专注于业务逻辑,而不用重复编写工具注册与解析的样板代码。

本文将从功能特性、安装方式、核心语法与参数、9 个实际应用案例、常见错误与使用注意事项五个方面,系统介绍 agent-tools 包的使用方法。

2. agent-tools 包功能概述

agent-tools 是一个面向 LLM Agent 场景的 Python 工具库,核心目标是把普通 Python 函数快速封装为可供 Agent 调用的“工具”。其主要功能包括:

  • 函数即工具:通过装饰器把普通函数注册为 Agent 可调用的工具,自动提取函数签名与类型注解。
  • 参数自动校验:基于类型注解和默认值,自动完成参数类型转换、必填项检查与范围校验。
  • 工具描述自动生成:根据函数名、docstring 和参数信息,自动生成符合 OpenAI Function Calling 规范的工具描述 JSON。
  • 统一调用分发:提供统一的 invoke 入口,支持按名称调用工具并返回结构化结果。
  • 错误捕获与重试:内置异常捕获机制,可配置重试次数与错误信息格式化。
  • 多后端适配:支持 OpenAI、Claude 等主流模型的 Function Calling / Tool Use 协议。
  • 工具注册表管理:支持工具的注册、注销、列表查询与去重。

3. 安装方式

agent-tools 已发布到 PyPI,推荐使用 pip 进行安装。建议在虚拟环境中操作,避免污染全局 Python 环境。

# 创建并激活虚拟环境(可选但推荐) python -m venv venv source venv/bin/activate # Windows 下使用 venv\Scripts\activate 安装 agent-tools pip install agent-tools

如果需要使用 OpenAI 或 Claude 的适配器,可以安装对应扩展依赖:

# 安装 OpenAI 适配器依赖 pip install agent-tools[openai] 安装 Claude 适配器依赖 pip install agent-tools[claude] 安装全部扩展依赖 pip install agent-tools[all]

安装完成后,可以通过以下命令验证是否安装成功:

python -c "import agent_tools; print(agent_tools.__version__)"

4. 核心语法与参数详解

4.1 基础工具定义

使用@tool装饰器即可把一个普通函数注册为工具。以下是一个最简单的示例:

from agent_tools import tool @tool def add(a: int, b: int) -> int: """计算两个整数的和。""" return a + b

装饰器会自动读取函数名add、参数a、b及其类型注解,并生成对应的工具描述。

4.2 工具参数配置

通过@tool装饰器的参数,可以进一步控制工具的行为:

from agent_tools import tool @tool( name="calculate_add", # 自定义工具名称,默认使用函数名 description="计算两个整数的和,用于数学运算场景。", # 自定义描述 retries=2, # 失败重试次数 timeout=10, # 超时时间(秒) visible=True # 是否对 Agent 可见 ) def add(a: int, b: int) -> int: """计算两个整数的和。""" return a + b

4.3 参数类型与默认值

agent-tools 支持 Python 常见类型注解,包括int、float、str、bool、list、dict以及Optional等。带默认值的参数会被标记为可选参数:

from typing import Optional from agent_tools import tool @tool def greet(name: str, greeting: str = "Hello", times: int = 1) -> str: """向指定用户发送问候语,可重复多次。""" return " ".join([f"{greeting}, {name}!"] * times)

4.4 工具注册与调用

工具定义后,需要通过注册表进行管理,并可通过统一入口调用:

from agent_tools import ToolRegistry, tool @tool def add(a: int, b: int) -> int: """计算两个整数的和。""" return a + b 创建注册表并注册工具 registry = ToolRegistry() registry.register(add) 查看已注册工具 print(registry.list_tools()) 调用工具 result = registry.invoke("add", {"a": 1, "b": 2}) print(result) # 输出: 3

4.5 生成 Function Calling 描述

agent-tools 可以自动生成符合 OpenAI Function Calling 规范的 JSON 描述,方便直接接入大模型:

from agent_tools import tool @tool def get_weather(city: str, unit: str = "celsius") -> str: """查询指定城市的天气信息。""" return f"{city} 的天气:晴,25 度({unit})" 生成工具描述 schema = get_weather.to_openai_schema() print(schema)

输出结果类似:

{ "type": "function", "function": { "name": "get_weather", "description": "查询指定城市的天气信息。", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名称"}, "unit": {"type": "string", "description": "温度单位", "default": "celsius"} }, "required": ["city"] } } }

4.6 与 LLM 集成

agent-tools 提供了与 OpenAI 等模型的便捷集成方式:

from agent_tools import tool from agent_tools.adapters import OpenAIAdapter @tool def add(a: int, b: int) -> int: """计算两个整数的和。""" return a + b 创建适配器并绑定工具 adapter = OpenAIAdapter() adapter.add_tool(add) 将工具描述传给模型 messages = [{"role": "user", "content": "请计算 3 + 5 的结果"}] response = adapter.chat(messages) print(response)

5. 9 个实际应用案例

案例 1:数学计算工具集

为 Agent 提供基础数学运算能力,是最常见的入门场景。

from agent_tools import tool, ToolRegistry @tool def add(a: float, b: float) -> float: """计算两个数的和。""" return a + b @tool def multiply(a: float, b: float) -> float: """计算两个数的乘积。""" return a * b @tool def power(base: float, exp: float) -> float: """计算 base 的 exp 次幂。""" return base ** exp registry = ToolRegistry() registry.register(add, multiply, power) 模拟 Agent 调用 print(registry.invoke("add", {"a": 3, "b": 4})) # 7.0 print(registry.invoke("power", {"base": 2, "exp": 10})) # 1024.0

案例 2:天气查询工具

通过封装外部天气 API,让 Agent 具备实时天气查询能力。

import requests from agent_tools import tool @tool(name="get_weather", description="查询指定城市的实时天气") def get_weather(city: str, unit: str = "celsius") -> str: """调用天气 API 查询城市天气。""" # 这里以模拟数据为例,实际可替换为真实 API weather_map = { "北京": ("晴", 25), "上海": ("多云", 28), "广州": ("小雨", 30), } condition, temp = weather_map.get(city, ("未知", 0)) if unit == "fahrenheit": temp = temp * 9 / 5 + 32 return f"{city}:{condition},{temp}°{unit}"

案例 3:数据库查询工具

将 SQL 查询封装为工具,让 Agent 可以安全地访问数据库。

import sqlite3 from agent_tools import tool @tool def query_user(user_id: int) -> str: """根据用户 ID 查询用户信息。""" conn = sqlite3.connect("app.db") cursor = conn.execute( "SELECT id, name, email FROM users WHERE id = ?", (user_id,) ) row = cursor.fetchone() conn.close() if row: return f"用户 {row[1]}({row[2]})" return "用户不存在"

案例 4:文件读写工具

为 Agent 提供受控的文件读写能力,注意做好路径安全校验。

import os from agent_tools import tool @tool def read_file(path: str) -> str: """读取指定文本文件的内容。""" if not os.path.exists(path): return "文件不存在" with open(path, "r", encoding="utf-8") as f: return f.read() @tool def write_file(path: str, content: str) -> str: """将内容写入指定文件。""" with open(path, "w", encoding="utf-8") as f: f.write(content) return f"已写入 {path}"

案例 5:网络请求工具

封装 HTTP 请求,让 Agent 可以获取网页内容或调用 REST API。

import requests from agent_tools import tool @tool def fetch_url(url: str, timeout: int = 10) -> str: """抓取指定 URL 的文本内容。""" try: resp = requests.get(url, timeout=timeout) resp.raise_for_status() return resp.text[:2000] # 截断避免返回过长 except Exception as e: return f"请求失败:{e}"

案例 6:文本处理工具

提供文本清洗、分词、摘要等常用 NLP 能力。

import re from agent_tools import tool @tool def clean_text(text: str, remove_punctuation: bool = True) -> str: """清洗文本:去除多余空白和可选标点。""" text = re.sub(r"\s+", " ", text).strip() if remove_punctuation: text = re.sub(r"[^\w\s\u4e00-\u9fff]", "", text) return text @tool def word_count(text: str) -> int: """统计文本中的单词数量。""" return len(text.split())

案例 7:定时任务调度工具

将定时任务注册为工具,Agent 可以动态创建或取消任务。

import sched import time from agent_tools import tool scheduler = sched.scheduler(time.time, time.sleep) @tool def schedule_task(delay: float, task_name: str) -> str: """在指定延迟秒数后执行一个命名任务。""" def _run(): print(f"执行任务:{task_name}") scheduler.enter(delay, 1, _run) return f"任务 {task_name} 已安排在 {delay} 秒后执行"

案例 8:图像处理工具

封装 Pillow 实现图像缩放、格式转换等能力。

from PIL import Image from agent_tools import tool @tool def resize_image(input_path: str, output_path: str, width: int, height: int) -> str: """将图片缩放到指定尺寸并保存。""" img = Image.open(input_path) resized = img.resize((width, height)) resized.save(output_path) return f"图片已保存到 {output_path},尺寸 {width}x{height}"

案例 9:多工具组合的客服机器人

综合使用多个工具,构建一个简单的智能客服 Agent。

from agent_tools import tool, ToolRegistry @tool def check_order(order_id: str) -> str: """查询订单状态。""" orders = {"A1001": "已发货", "A1002": "待付款", "A1003": "已完成"} return orders.get(order_id, "订单不存在") @tool def check_refund(order_id: str) -> str: """查询订单退款进度。""" refunds = {"A1001": "退款中", "A1002": "无退款记录"} return refunds.get(order_id, "无退款记录") @tool def recommend_product(category: str) -> str: """根据品类推荐商品。""" products = { "手机": "推荐:X 品牌旗舰机", "电脑": "推荐:Y 品牌轻薄本", "耳机": "推荐:Z 品牌降噪耳机", } return products.get(category, "暂无推荐") registry = ToolRegistry() registry.register(check_order, check_refund, recommend_product) 模拟客服对话 print(registry.invoke("check_order", {"order_id": "A1001"})) print(registry.invoke("recommend_product", {"category": "手机"}))

6. 常见错误与使用注意事项

6.1 常见错误

错误类型错误示例解决方案
参数类型不匹配调用add时传入字符串"3"使用类型注解并开启严格校验,或调用前自行转换
缺少必填参数调用greet时未传name检查工具描述中的required字段,确保必填参数齐全
工具名冲突两个函数注册为同名工具使用name参数指定唯一名称,或注册时检查重复
返回值不可序列化返回自定义对象而非 JSON 兼容类型在工具内部转换为str、dict、list等类型
docstring 缺失函数没有写文档字符串,导致描述为空为每个工具函数编写清晰的 docstring
超时未处理外部 API 调用长时间无响应设置timeout参数并捕获超时异常

《动手学PyTorch建模与应用:从深度学习到大模型》是一本从零基础上手深度学习和大模型的PyTorch实战指南。全书共11章,前6章涵盖深度学习基础,包括张量运算、神经网络原理、数据预处理及卷积神经网络等;后5章进阶探讨图像、文本、音频建模技术,并结合Transformer架构解析大语言模型的开发实践。书中通过房价预测、图像分类等案例讲解模型构建方法,每章附有动手练习题,帮助读者巩固实战能力。内容兼顾数学原理与工程实现,适配PyTorch框架最新技术发展趋势。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询