AI Agent自定义工具开发:一个Python函数加个装饰器

📘 教程 2026-07-16 约 2 分钟阅读

想给Agent加个查天气的功能?不需要懂Agent框架。一个Python函数+一个装饰器,Agent自动学会用。

💡 你将学到

想给Agent加个查天气的功能?不需要懂Agent框架。一个Python函数+一个装饰器,Agent自动学会用。

📜 目录

最被低估的Agent能力:任何Python函数都能变成Agent工具。不需要学LangChain,不需要配MCP Server。

三步写一个工具

Step 1:写一个普通Python函数

def get_stock_price(symbol: str) -> float:
    """获取股票当前价格"""
    import requests
    data = requests.get(f"https://api.example.com/stock/{symbol}").json()
    return data["price"]

Step 2:加个装饰器

from agent_sdk import tool

@tool
def get_stock_price(symbol: str) -> float:
    \"\"\"获取股票当前价格。参数symbol:股票代码,如AAPL、GOOGL\"\"\"

Step 3:注册给Agent

agent.register_tool(get_stock_price)

函数签名为什么重要

函数的名称、参数类型、文档字符串——这三样决定了Agent能不能正确使用你的工具。

总结

给Agent加自定义工具,核心是把函数写好——名字对、参数对、描述对。Agent框架剩下的都帮你做了。

完整的工具开发示例

import requests
from agent_sdk import tool, ToolSet

@tool
def get_exchange_rate(from_currency: str, to_currency: str = "CNY") -> float:
    """获取实时汇率。
    from_currency: 源货币代码(如USD、EUR、JPY)
    to_currency: 目标货币代码(默认CNY)
    返回:汇率值
    """
    url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
    data = requests.get(url).json()
    return data["rates"][to_currency]

# 注册
agent.register_tool(get_exchange_rate)

函数名、参数名、文档字符串——这三样决定了Agent能不能正确使用你的工具。写得越清楚越好用。

相关文章

相关文章
2026-07-26
AI代码审查提示工程
2026-07-17
AI Agent部分结果:一个工具挂了不影响整个任务
2026-08-01
开源AI图像生成模型:8款对比

本站文章由编辑人工撰写,收录的工具均经过实测或公开资料核验。文中链接指向工具官网或 GitHub 仓库,仅作信息参考,不构成付费推广。

💬 评论 (0)

暂无评论,来说两句吧~

登录后评论