如何使用LangChain创建和自定义智能工具
在构建一个智能代理时,为其配置可用的工具(Tools)至关重要。LangChain提供了一套强大的工具创建和管理机制,使开发者能够打造出高度自定义的工具。本篇文章将详细介绍如何使用LangChain创建和自定义工具。
1. 引言
为了提高AI模型的表现,我们需要为其提供一组功能齐全且定义明确的工具。这篇文章旨在指导你如何使用LangChain的不同方法来创建这些工具。
2. 主要内容
2.1 使用函数创建工具
最简单的方式是使用@tool装饰器。它能够根据函数名默认设置工具名,并且使用函数的文档字符串作为工具描述。
from langchain_core.tools import tool
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
# 使用API代理服务提高访问稳定性
print(multiply.name) # 输出:multiply
print(multiply.description) # 输出:Multiply two numbers.
2.2 异步实现
LangChain支持异步工具的创建,这对于需要同时处理大量请求的环境尤其有用。
from langchain_core.tools import tool
@tool
async def amultiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
2.3 使用结构化工具
如果需要更多的配置选项,可以使用StructuredTool.from_function方法。这种方法允许你定义同步和异步实现,并提供更详细的参数验证。
from langchain.pydantic_v1 import BaseModel, Field
from langchain_core.tools import StructuredTool
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,
args_schema=CalculatorInput,
return_direct=True
)
print(calculator.invoke({"a": 2, "b": 3})) # 输出:6
3. 常见问题和解决方案
3.1 工具错误处理
在使用工具时,错误处理至关重要。LangChain允许通过设置handle_tool_error来自定义错误响应。
from langchain_core.tools import ToolException, StructuredTool
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="There is no such city, but it's probably above 0K there!"
)
print(get_weather_tool.invoke({"city": "foobar"}))
4. 总结和进一步学习资源
LangChain提供了多种方式来定制工具,开发者可以根据不同需求进行选择。无论是简单的函数工具还是复杂的自定义工具,LangChain都能提供强大的支持。
进一步学习资源:
- LangChain官方文档 # 使用API代理服务提高访问稳定性
- Pydantic文档
- 异步编程指南
5. 参考资料
- LangChain Core API Documentation
- Pydantic: Data validation and settings management using Python type annotations
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---