
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( namecalculate_add, # 自定义工具名称默认使用函数名 description计算两个整数的和用于数学运算场景。, # 自定义描述 retries2, # 失败重试次数 timeout10, # 超时时间秒 visibleTrue # 是否对 Agent 可见 ) def add(a: int, b: int) - int: 计算两个整数的和。 return a b4.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) # 输出: 34.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(nameget_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, encodingutf-8) as f: return f.read() tool def write_file(path: str, content: str) - str: 将内容写入指定文件。 with open(path, w, encodingutf-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, timeouttimeout) 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框架最新技术发展趋势。