探索LangChain工具构建:从基础到进阶

73 阅读2分钟
## 引言

在现代AI开发中,为语言模型提供适合的工具可以显著提高其功能和效率。在这篇文章中,我们将探讨如何使用LangChain框架来创建自定义工具,并分享工具构建的不同方法,以满足多样化的需求。

## 主要内容

### 1. 工具的基本组成

构建工具时,需要考虑以下几个重要组件:

- **名称**:工具名称在一个工具集合中需唯一。
- **描述**:描述工具的功能,供LLM或代理参考。
- **Args Schema**:可选项,用于参数验证和提供更多信息。
- **Return Direct**:用于决定是否直接返回结果。

### 2. 从函数创建工具

#### 使用 `@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)  # 输出工具名称
print(multiply.description)
异步实现

可以定义异步工具以支持异步调用。

from langchain_core.tools import tool

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

3. 使用结构化工具

结构化工具提供了更高的配置灵活性。

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, name="Calculator", description="Multiply numbers", return_direct=True)

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

4. 处理工具错误

在工具中处理错误很重要。可以通过抛出 ToolException 并指定错误处理程序来恢复执行。

from langchain_core.tools import ToolException

def get_weather(city: str) -> int:
    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)
get_weather_tool.invoke({"city": "foobar"})

代码示例

以下是一个使用LangChain创建乘法工具的完整示例,包括同步和异步实现:

from langchain_core.tools import tool, StructuredTool

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

@tool
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}))

常见问题和解决方案

  1. 名称冲突:确保每个工具名称唯一。
  2. 异步调用问题:使用异步工具时,应避免同步调用方法。
  3. 错误处理:始终为工具设置错误处理机制,以避免在代理中断执行。

总结和进一步学习资源

LangChain提供了灵活的工具创建方式,可以满足不同的开发需求。建议进一步阅读LangChain的官方文档和示例代码,以掌握更多高级功能。

参考资料

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

---END---