- 任何 Python 函数都可以被 Agent 用作工具。
- 使用
@tool装饰器来修改该工具调用之前和之后发生的事情。
任何 Python 函数都可以用作工具
例如,以下是如何将get_top_hackernews_stories 函数用作工具:
hn_agent.py
@tool 装饰器的魔力
要修改工具的行为,请使用 @tool 装饰器。一些值得注意的特性:
requires_confirmation=True: 在执行前需要用户确认。requires_user_input=True: 在执行前需要用户输入。使用user_input_fields指定需要用户输入的字段。external_execution=True: 工具将在 Agent 的控制之外执行。show_result=True: 在 Agent 的响应中显示工具调用的输出。没有此标志,工具调用的结果将被发送到模型进行进一步处理。stop_after_tool_call=True: 在工具调用后停止 Agent 运行。tool_hooks: 在此工具调用之前和之后运行自定义逻辑。cache_results=True: 缓存工具结果以避免重复相同的调用。使用cache_dir和cache_ttl配置缓存。
@tool 装饰器上许多可能参数的示例。
advanced_tool.py
@tool 参数参考
| 参数 | 类型 | 描述 |
|---|---|---|
name | str | 函数名称的替代名称 |
description | str | 函数描述的替代描述 |
show_result | bool | 如果为 True,则在函数调用后显示结果 |
stop_after_tool_call | bool | 如果为 True,Agent 将在函数调用后停止 |
tool_hooks | list[Callable] | 包装函数执行的 Hook 列表 |
pre_hook | Callable | 在函数执行前运行的 Hook |
post_hook | Callable | 在函数执行后运行的 Hook |
requires_confirmation | bool | 如果为 True,则在执行前需要用户确认 |
requires_user_input | bool | 如果为 True,则在执行前需要用户输入 |
user_input_fields | list[str] | 需要用户输入的字段列表 |
external_execution | bool | 如果为 True,工具将在 Agent 的控制之外执行 |
cache_results | bool | 如果为 True,则启用函数结果的缓存 |
cache_dir | str | 用于存储缓存文件的目录 |
cache_ttl | int | 缓存结果的生存时间(以秒为单位,默认为 3600) |