⚡ 函数工具 函数工具是您创建并集成到智能体中的自定义 Python 函数。这是为智能体添加特定功能时最灵活且最常用的方法。 您将学到的内容 函数工具的创建:构建自定义 Python 函数作为工具 工具注册:如何将函数注册到您的智能体中 参数处理:管理工具的输入和输出 错误处理:工具中稳健的错误管理 最佳实践:设计有效的函数工具模式 核心概念:函数工具 函数工具是具有特殊属性的Python 函数: 描述性文档字符串:帮助智能体理解何时使用它们 类型注解:清晰的输入和输出规范 返回字典:结构化、信息丰富的响应 错误处理:优雅的失败管理 主要优势 ✅ 最大灵活性:可创建任何所需功能 ✅ 易于集成:简单的 Python 函数 ✅ 完全控制:对行为的完全掌控 ✅ 调试方便:易于测试和调试
函数工具是您创建并集成到智能体中的自定义 Python 函数。这是为智能体添加特定功能时最灵活且最常用的方法。
函数工具是具有特殊属性的Python 函数:
def calculate_compound_interest(principal: float, rate: float, years: int) -> dict: """ Calculate compound interest for an investment. Use this function when users ask about investment growth, compound interest calculations, or future value of investments. Args: principal: Initial investment amount rate: Annual interest rate (as decimal, e.g., 0.05 for 5%) years: Number of years to compound Returns: Dictionary with calculation results and breakdown """
return { "result": final_amount, "calculation_breakdown": { "principal": principal, "rate": rate, "years": years, "total_interest": total_interest }, "status": "success" }
try: # Tool logic here return {"result": result, "status": "success"} except ValueError as e: return {"error": str(e), "status": "error"}
本子示例包含两个实用实现:
位置:./calculator_agent/
Location: ./utility_agent/
4_2_function_tools/ ├── README.md # This file - function tools guide ├── requirements.txt # Dependencies for function tools ├── .env.example # Environment variables template (shared) ├── calculator_agent/ # Mathematical tools implementation │ ├── __init__.py │ ├── agent.py # Calculator agent with custom tools │ └── tools.py # Mathematical function tools └── utility_agent/ # Utility tools implementation ├── __init__.py ├── agent.py # Utility agent with various tools └── tools.py # Text processing, date/time, and data utilities
完成本子示例后,您将掌握:
设置您的环境:
cd 4_2_function_tools # Copy the environment template cp env.example .env # Edit .env and add your Google AI API key # Get your API key from: https://aistudio.google.com/
安装依赖:
# Install required packages pip install -r requirements.txt
运行智能体:
# Start the ADK web interface adk web # In the web interface, select: # - calculator_agent: For mathematical calculations and conversions # - utility_agent: For text processing, date/time, and data utilities
尝试智能体:
创建您自己的工具:针对您的用例构建自定义工具
def add_numbers(a: float, b: float) -> dict: """Add two numbers together.""" return {"result": a + b, "operation": "addition"}
def analyze_text(text: str) -> dict: """Analyze text for word count, sentiment, etc.""" return { "word_count": len(text.split()), "character_count": len(text), "sentiment": "neutral" # Placeholder }
def get_weather(city: str) -> dict: """Get weather information for a city.""" try: # API call logic here return {"temperature": 72, "condition": "sunny"} except Exception as e: return {"error": str(e), "status": "failed"}
def convert_temperature(temp: float, from_unit: str, to_unit: str) -> dict: """Convert temperature between units.""" # Conversion logic return { "original": {"value": temp, "unit": from_unit}, "converted": {"value": converted_temp, "unit": to_unit} }
免责声明:
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。