tool
@tool
装饰器
@tool
装饰器是定义⾃定义⼯具的最简单⽅式。
- 自动 推断工具名、描述、参数 schem
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""获取指定城市的天气状况"""
return f"当前{city}的天气状况是晴朗"
可以传入参数来自定义工具名称和参数 schem
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class Weather(BaseModel):
city: str = Field(description="城市名称")
@tool("weather", args_schema=Weather, return_direct=True)
def get_weather(city: str) -> str:
"""获取指定城市的天气状况"""
return f"当前{city}的天气状况是晴朗"
StructuredTool.from_function(结构化工具)
from pydantic import BaseModel, Field
from langchain_core.tools import StructuredTool
class GetWeather(BaseModel):
city: str = Field(description="城市名称")
def get_weather(city: str) -> str:
"""获取指定城市的天气状况"""
return f"当前{city}的天气状况是晴朗"
calc = StructuredTool.from_function(
func=get_weather,
name="get_weather",
description="获取指定城市的天气状况",
args_schema=GetWeather,
return_direct=True,
)
- 支持 自定义名称、描述、参数 schema,并可校验输
- 默认 infer_schema=True 会根据函数签名自动生成 schema
JSON 参数
自动生成的 JSON schema 示例:
{
"type": "object",
"properties": {
"a": {"title": "A", "description": "first number", "type": "integer"},
"b": {"title": "B", "description": "second number", "type": "integer"}
},
"required": ["a", "b"]
}
错误处理机制
在⼯具内部抛出 ToolException
,并使⽤ handle_tool_error
指定⼀个错误处理程序。 当指定了错误处理程序时,异常将被捕获,错误处理程序将决定从⼯具返回哪个输出。 可以将 handle_tool_error 设置为 True 、字符串值或函数
抛出错误:ToolException
from langchain_core.tools import ToolException
def get_weather(city: str) -> int:
raise ToolException(f"City '{city}' not found")
handle_tool_error 的几种设定方式
- 布尔值
True
:直接返回异常 message 字符串
tool = StructuredTool.from_function(func=get_weather, handle_tool_error=True)
tool.invoke({"city":"foobar"})
# 返回 "City 'foobar' not found"
- 字符串:总是返回这个固定响应
tool = StructuredTool.from_function(func=get_weather, handle_tool_error="City 不存在")
tool.invoke({"city":"foobar"})
# 返回 "City 不存在"
- 函数:可自定义返回格式
def handle(e: ToolException) -> str:
return f"发生错误:{e.args[0]}"
tool = StructuredTool.from_function(func=get_weather, handle_tool_error=handle)
tool.invoke({"city":"foobar"})
# 发生错误:City '北京' not found