@tool 装饰器用于将函数定义为一个工具。multiply 函数接受两个整数参数 a 和 b,返回它们的乘积。通过打印工具的属性,我们可以看到工具的名称、描述和参数信息。
2. 定义异步工具
接下来,我们定义一个异步的乘法工具。
from langchain_core.tools import tool
@toolasyncdefamultiply(a:int, b:int)->int:"""Multiply two numbers."""return a * b
复制代码
解释
使用 async 关键字定义异步函数 amultiply。其他部分与同步工具定义相同。
3. 使用注解定义工具参数
我们可以使用注解来更详细地描述工具的参数。
from typing import Annotated, List
@tooldefmultiply_by_max(
a: Annotated[str,"scale factor"],
b: Annotated[List[int],"list of ints over which to take maximum"],)->int:"""Multiply a by the maximum of b."""return a *max(b)print(multiply_by_max.args_schema.schema())
复制代码
输出:
{'description': 'Multiply a by the maximum of b.',
'b': {'description': 'list of ints over which to take maximum',
'items': {'type': 'integer'},
'title': 'B',
'type': 'array'}},
'required': ['a', 'b'],
'title': 'multiply_by_max',
'type': 'object'}
复制代码
解释
使用 Annotated 类型注解来添加参数的描述。multiply_by_max 函数接受一个字符串 a 和一个整数列表 b,返回 a 与 b 中最大值的乘积。通过打印参数模式(schema),我们可以看到详细的参数描述。
4. 使用 Pydantic 定义工具参数
我们可以使用 Pydantic 库来更严格地定义工具的参数。
from pydantic import BaseModel, Field
classCalculatorInput(BaseModel):
a:int= Field(description="first number")
b:int= Field(description="second number")@tool("multiplication-tool", args_schema=CalculatorInput, return_direct=True)defmultiply(a:int, b:int)->int:"""Multiply two numbers."""return a * b
handle_tool_error="There is no such city, but it's probably above 0K there!",)print(get_weather_tool.invoke({"city":"foobar"}))
复制代码
输出:
"There is no such city, but it's probably above 0K there!"
复制代码
解释
使用 handle_tool_error 参数自定义错误信息。
11. 生成随机数工具
我们可以定义生成随机数的工具。
import random
from typing import List, Tuple
@tool(response_format="content_and_artifact")defgenerate_random_ints(min:int,max:int, size:int)-> Tuple[str, List[int]]:"""Generate size random ints in the range [min, max]."""