教程 6.3:工具执行回调 您将学到的内容 工具执行前回调:监控工具开始执行的时间 工具执行后回调:跟踪工具完成及结果 工具上下文:了解如何监控工具执行 核心概念:工具执行监控 工具执行回调让您能够监控代理何时使用工具、跟踪其执行生命周期并分析结果。这为您提供了对代理如何与外部系统和 API 交互的可见性。 工具执行流程 回调执行时间线 用例 执行监控:跟踪工具开始和完成的时间 参数校验:在执行前检查工具输入 结果记录:记录工具输出和错误 调试:理解工具执行模式 分析:监控哪些工具使用得最多 教程概述 在本教程中,我们将创建一个带有工具执行回调的代理: 使用一个简单的计算器工具 监控工具执行的开始和结束 跟踪工具参数和结果 提供详细的工具使用可视化 项目结构 学习目标
工具执行回调让您能够监控代理何时使用工具、跟踪其执行生命周期并分析结果。这为您提供了对代理如何与外部系统和 API 交互的可见性。
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Tool Call │───▶│ Before Tool │───▶│ Tool Execution │ │ (Agent) │ │ Callback │ │ (External) │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ After Tool │ │ Tool Result │ │ Callback │ │ (Agent) │ └─────────────────┘ └─────────────────┘
Time → 0ms 5ms 10ms 15ms 20ms 25ms │ │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ ▼ [Tool] [Before] [Exec] [After] [Result] Call Callback Start Callback Return
在本教程中,我们将创建一个带有工具执行回调的代理:
6_3_tool_execution_callbacks/ ├── README.md # This file ├── requirements.txt # Dependencies ├── agent.py # Agent with tool callbacks └── app.py # Streamlit interface
完成本教程后,您将掌握:
pip install -r requirements.txt.env with GOOGLE_API_KEY=your_keystreamlit run app.py# Run the Streamlit app streamlit run app.py # Try these test messages: - "Calculate 15 + 27" - "What is 100 divided by 4?" - "Multiply 8 by 12"
tool, args, tool_contexttool, args, tool_context, tool_responsetool_context.agent_nametool_context.state for data sharingtool.nameUser: "Calculate 15 + 27" Tool calculator_tool started Parameters: {'operation': 'add', 'a': 15.0, 'b': 27.0} Agent: tool_execution_demo_agent ✅ Tool calculator_tool completed ⏱️ Duration: 0.0012s Result: 15 + 27 = 42
User: "What is 10 divided by 0?" Tool calculator_tool started Parameters: {'operation': 'divide', 'a': 10.0, 'b': 0.0} Agent: tool_execution_demo_agent ✅ Tool calculator_tool completed ⏱️ Duration: 0.0008s Result: Error: Division by zero
工具必须用 FunctionTool 包装,回调才能正常工作:
# ✅ Correct - Use FunctionTool calculator_function_tool = FunctionTool(func=calculator_tool) agent = LlmAgent(tools=[calculator_function_tool], ...) # ❌ Incorrect - Raw function won't trigger callbacks agent = LlmAgent(tools=[calculator_tool], ...)
请使用正确的参数顺序来定义工具回调:
# ✅ Correct signatures def before_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext): pass def after_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext, tool_response: any): pass
不要在 is_final_response() 后立即中断事件循环:
# ✅ Do this - allows callbacks to complete if event.is_final_response() and event.content: response_text = event.content.parts[0].text.strip() # Don't break - let the loop complete naturally
使用相同的回调注册多个工具:
def weather_tool(city: str) -> str: return f"Weather in {city}: Sunny, 25°C" def calculator_tool(operation: str, a: float, b: float) -> str: # ... implementation # Register multiple tools weather_function_tool = FunctionTool(func=weather_tool) calculator_function_tool = FunctionTool(func=calculator_tool) agent = LlmAgent( name="multi_tool_agent", model="gemini-3-flash-preview", tools=[calculator_function_tool, weather_function_tool], before_tool_callback=before_tool_callback, after_tool_callback=after_tool_callback )
在 before_tool_callback 中实现校验:
def before_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext): tool_name = tool.name # Validate calculator tool parameters if tool_name == "calculator_tool": if "operation" not in args: print("⚠️ Warning: Missing operation parameter") if "a" not in args or "b" not in args: print("⚠️ Warning: Missing numeric parameters") print(f" Tool {tool_name} started") print(f" Parameters: {args}") return None
在 after_tool_callback 中修改工具结果:
def after_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext, tool_response: any): tool_name = tool.name # Add context to calculator results if tool_name == "calculator_tool" and "result" in tool_response: operation = args.get("operation", "unknown") tool_response["context"] = f"Performed {operation} operation" print(f"✅ Tool {tool_name} completed") print(f" Result: {tool_response}") return tool_response # Return modified response
完成本教程后,您将准备好:
免责声明:
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文的母语文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。