AI创想

标题: 1. langchain中的tool使用 (How to create tools) [打印本页]

作者: 云端714    时间: 昨天 21:49
标题: 1. langchain中的tool使用 (How to create tools)
作者:CSDN博客
本教程将介绍如何使用 LangChain 库中的工具(Tool)功能。通过一系列示例代码,我们将展示如何定义、使用和扩展工具。
1. 定义简单的工具

首先,我们从定义一个简单的乘法工具开始。
  1. from langchain_core.tools import tool
  2. @tooldefmultiply(a:int, b:int)->int:"""Multiply two numbers."""return a * b
  3. # 查看工具的属性print(multiply.name)print(multiply.description)print(multiply.args)
复制代码
输出:
  1. multiply
  2. Multiply two numbers.
  3. {'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}
复制代码
解释

2. 定义异步工具

接下来,我们定义一个异步的乘法工具。
  1. from langchain_core.tools import tool
  2. @toolasyncdefamultiply(a:int, b:int)->int:"""Multiply two numbers."""return a * b
复制代码
解释

3. 使用注解定义工具参数

我们可以使用注解来更详细地描述工具的参数。
  1. from typing import Annotated, List
  2. @tooldefmultiply_by_max(
  3.     a: Annotated[str,"scale factor"],
  4.     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())
复制代码
输出:
  1. {'description': 'Multiply a by the maximum of b.',
  2. 'properties': {'a': {'description': 'scale factor',
  3.    'title': 'A',
  4.    'type': 'string'},
  5.   'b': {'description': 'list of ints over which to take maximum',
  6.    'items': {'type': 'integer'},
  7.    'title': 'B',
  8.    'type': 'array'}},
  9. 'required': ['a', 'b'],
  10. 'title': 'multiply_by_max',
  11. 'type': 'object'}
复制代码
解释

4. 使用 Pydantic 定义工具参数

我们可以使用 Pydantic 库来更严格地定义工具的参数。
  1. from pydantic import BaseModel, Field
  2. classCalculatorInput(BaseModel):
  3.     a:int= Field(description="first number")
  4.     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
  5. # 查看工具的属性print(multiply.name)print(multiply.description)print(multiply.args)print(multiply.return_direct)
复制代码
输出:
  1. multiplication-tool
  2. Multiply two numbers.
  3. {'a': {'description': 'first number', 'title': 'A', 'type': 'integer'}, 'b': {'description': 'second number', 'title': 'B', 'type': 'integer'}}
  4. True
复制代码
解释

5. 自动解析文档字符串

我们可以让 LangChain 自动解析函数的文档字符串来生成参数模式。
  1. @tool(parse_docstring=True)deffoo(bar:str, baz:int)->str:"""The foo.
  2.     Args:
  3.         bar: The bar.
  4.         baz: The baz.
  5.     """return bar
  6. print(foo.args_schema.schema())
复制代码
输出:
  1. {'description': 'The foo.',
  2. 'properties': {'bar': {'description': 'The bar.',
  3.    'title': 'Bar',
  4.    'type': 'string'},
  5.   'baz': {'description': 'The baz.', 'title': 'Baz', 'type': 'integer'}},
  6. 'required': ['bar', 'baz'],
  7. 'title': 'foo',
  8. 'type': 'object'}
复制代码
解释

6. 使用 StructuredTool

我们可以使用 StructuredTool 来创建工具实例。
  1. from langchain_core.tools import StructuredTool
  2. defmultiply(a:int, b:int)->int:"""Multiply two numbers."""return a * b
  3. asyncdefamultiply(a:int, b:int)->int:"""Multiply two numbers."""return a * b
  4. calculator = StructuredTool.from_function(func=multiply, coroutine=amultiply)print(calculator.invoke({"a":2,"b":3}))print(await calculator.ainvoke({"a":2,"b":5}))
复制代码
输出:
  1. 6
  2. 10
复制代码
解释

7. 自定义工具

我们可以自定义工具类。
  1. classCalculatorInput(BaseModel):
  2.     a:int= Field(description="first number")
  3.     b:int= Field(description="second number")defmultiply(a:int, b:int)->int:"""Multiply two numbers."""return a * b
  4. calculator = StructuredTool.from_function(
  5.     func=multiply,
  6.     name="Calculator",
  7.     description="multiply numbers",
  8.     args_schema=CalculatorInput,
  9.     return_direct=True,)print(calculator.invoke({"a":2,"b":3}))print(calculator.name)print(calculator.description)print(calculator.args)
复制代码
输出:
  1. 6
  2. Calculator
  3. multiply numbers
  4. {'a': {'description': 'first number', 'title': 'A', 'type': 'integer'}, 'b': {'description': 'second number', 'title': 'B', 'type': 'integer'}}
复制代码
解释

8. 将链式调用转换为工具

我们可以将链式调用转换为工具。
  1. from langchain_core.language_models import GenericFakeChatModel
  2. from langchain_core.output_parsers import StrOutputParser
  3. from langchain_core.prompts import ChatPromptTemplate
  4. prompt = ChatPromptTemplate.from_messages([("human","Hello. Please respond in the style of {answer_style}.")])# 占位符 LLM
  5. llm = GenericFakeChatModel(messages=iter(["hello matey"]))
  6. chain = prompt | llm | StrOutputParser()
  7. as_tool = chain.as_tool(
  8.     name="Style responder", description="Description of when to use tool.")print(as_tool.args)
复制代码
输出:
  1. {'answer_style': {'title': 'Answer Style', 'type': 'string'}}
复制代码
解释

9. 处理工具错误

我们可以定义工具错误处理。
  1. defget_weather(city:str)->int:"""Get weather for the given city."""raise ToolException(f"Error: There is no city by the name of {city}.")
  2. get_weather_tool = StructuredTool.from_function(
  3.     func=get_weather,
  4.     handle_tool_error=True,)print(get_weather_tool.invoke({"city":"foobar"}))
复制代码
输出:
  1. Error: There is no city by the name of foobar.
复制代码
解释

10. 自定义错误信息

我们可以自定义工具错误信息。
  1. get_weather_tool = StructuredTool.from_function(
  2.     func=get_weather,
  3.     handle_tool_error="There is no such city, but it's probably above 0K there!",)print(get_weather_tool.invoke({"city":"foobar"}))
复制代码
输出:
  1. "There is no such city, but it's probably above 0K there!"
复制代码
解释

11. 生成随机数工具

我们可以定义生成随机数的工具。
  1. import random
  2. from typing import List, Tuple
  3. @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]."""
  4.     array =[random.randint(min,max)for _ inrange(size)]
  5.     content =f"Successfully generated array of {size} random ints in [{min}, {max}]."return content, array
  6. print(generate_random_ints.invoke({"min":0,"max":9,"size":10}))
复制代码
输出:
  1. 'Successfully generated array of 10 random ints in [0, 9].'
复制代码
解释

12. 带有工具调用的生成随机数

我们可以使用工具调用格式生成随机数。
  1. print(generate_random_ints.invoke({"name":"generate_random_ints","args":{"min":0,"max":9,"size":10},"id":"123",# required"type":"tool_call",# required}))
复制代码
输出:
  1. ToolMessage(content='Successfully generated array of 10 random ints in [0, 9].', name='generate_random_ints', tool_call_id='123', artifact=[0, 4, 2, 7, 4, 3, 1, 7, 5, 1])
复制代码
解释

13. 生成随机浮点数工具

我们可以定义生成随机浮点数的工具。
  1. from langchain_core.tools import BaseTool
  2. classGenerateRandomFloats(BaseTool):
  3.     name:str="generate_random_floats"
  4.     description:str="Generate size random floats in the range [min, max]."
  5.     response_format:str="content_and_artifact"
  6.     ndigits:int=2def_run(self,min:float,max:float, size:int)-> Tuple[str, List[float]]:
  7.         range_ =max-min
  8.         array =[round(min+(range_ * random.random()), ndigits=self.ndigits)for _ inrange(size)]
  9.         content =f"Generated {size} floats in [{min}, {max}], rounded to {self.ndigits} decimals."return content, array
  10. rand_gen = GenerateRandomFloats(ndigits=4)print(rand_gen.invoke({"name":"generate_random_floats","args":{"min":0.1,"max":3.3333,"size":3},"id":"123","type":"tool_call",}))
复制代码
输出:
  1. ToolMessage(content='Generated 3 floats in [0.1, 3.3333], rounded to 4 decimals.', name='generate_random_floats', tool_call_id='123', artifact=[2.033, 2.6058, 2.5919])
复制代码
解释

通过以上示例,我们展示了如何使用 LangChain 库中的工具功能,包括定义工具、使用注解和 Pydantic、处理错误、生成随机数等。希望这些示例能帮助你更好地理解和应用 LangChain 工具。
参考链接:https://python.langchain.com/docs/how_to/custom_tools/

原文地址:https://blog.csdn.net/qq_41472205/article/details/144141262




欢迎光临 AI创想 (https://www.llms-ai.com/) Powered by Discuz! X3.4