引言
在构建智能代理时,为其提供一系列可用的工具是至关重要的。LangChain作为一个强大的框架,不仅支持从函数创建工具,还允许通过LangChainRunnables和BaseTool子类实现高自由度的工具开发。本文将深入探讨如何使用LangChain创建和配置这些工具,帮助开发者有效扩展其应用的功能。
主要内容
从函数创建工具
创建工具的最简单方法是通过函数。这可以通过使用@tool
装饰器实现,它利用函数名作为默认工具名,并采用函数的docstring作为工具描述。如果需要更多定制化,可以通过StructuredTool.from_function
类方法进行。
@tool 装饰器
from langchain_core.tools import tool
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
# 检查工具属性
print(multiply.name)
print(multiply.description)
print(multiply.args)
结构化工具
结构化工具提供了更多的配置选项,如同步和异步实现的指定。通过这种方法可以更好地管理工具的输入参数和返回值。
from langchain_core.tools import StructuredTool
from langchain.pydantic_v1 import BaseModel, Field
class CalculatorInput(BaseModel):
a: int = Field(description="first number")
b: int = Field(description="second number")
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
calculator = StructuredTool.from_function(
func=multiply,
name="Calculator",
description="multiply numbers",
args_schema=CalculatorInput,
return_direct=True
)
print(calculator.invoke({"a": 2, "b": 3}))
使用LangChainRunnables
LangChainRunnables可以接受字符串或字典输入,并通过as_tool
方法转换为工具。这种方法适用于需要复杂逻辑或多步骤处理的情况。
通过BaseTool子类化
对于需要极高定制化的场景,通过继承BaseTool可以实现。这种方法虽然代码量较多,但提供了最大的控制权。
代码示例
下面是一个完整的代码示例,演示了如何创建同步和异步工具,并处理工具执行中的错误。
from langchain_core.tools import StructuredTool, 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}.")
get_weather_tool = StructuredTool.from_function(
func=get_weather,
handle_tool_error=True
)
print(get_weather_tool.invoke({"city": "foobar"}))
常见问题和解决方案
-
如何处理工具的执行错误?
定义错误处理策略,并在工具内抛出ToolException
。配置handle_tool_error
来决定工具遇到异常时的行为。 -
异步工具如何与同步工具配合使用?
使用StructuredTool.from_function
可以同时定义同步和异步方法,避免异步代码中的小额外开销。 -
如何在受网络限制的地区使用外部API?
使用API代理服务,以提高访问的稳定性和响应速度。
总结与进一步学习资源
创建和配置LangChain工具为开发人员提供了强大的功能延展能力,尤其是在处理复杂调用链时。更多关于LangChain工具的使用方法,可以参考以下资源:
- LangChain官方文档
- Pydantic数据模型指南
- Python异步编程最佳实践
参考资料
- LangChain官方文档:https://www.langchain.com/docs
- Python Pydantic:https://pydantic-docs.helpmanual.io/
- Async Programming in Python: https://realpython.com/async-io-python/
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—