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

📘 AI教程 💬 🔥 Trending

🩺 摘要

想给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能不能正确使用你的工具。

  • 名称要见名知意(search_user 好过 f1
  • 参数类型要明确(str vs int vs list
  • 文档字符串要写清楚"什么时候用这个工具"

总结

给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能不能正确使用你的工具。写得越清楚越好用。