处理 Tool Call error

准备

import os

# os.environ['HTTP_PROXY'] = 'http://127.0.0.1:10809'
# os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:10809'
os.environ['LANGSMITH_TRACING'] = 'true'
os.environ['LANGSMITH_ENDPOINT'] = 'https://api.smith.langchain.com'
os.environ['LANGSMITH_API_KEY'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
os.environ['LANGSMITH_PROJECT'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

例子1

首先,定义一个模拟天气工具,该工具对输入查询有一些隐藏的限制。此处的目的是模拟模型无法正确调用工具的真实情况:

from langchain_core.tools import tool


@tool
def get_weather(location: str):
    """Call to get the current weather."""
    if location == "san francisco":
        return "It's 60 degrees and foggy."
    elif location == "San Francisco":
        raise ValueError("Please lowercase the first letter of the place name")
    else:
        raise ValueError("Invalid input.")

接下来,设置 ReAct 代理的图形实现。此代理将一些查询作为输入,然后重复调用 tools,直到它有足够的信息来解析查询。我们将使用预构建的 ToolNode 来执行 called tools

png

当您尝试调用该工具时,您可以看到模型使用错误的输入调用该工具,从而导致工具引发错误。执行该工具的预构建 ToolNode 具有一些内置的错误处理功能,可以捕获错误并将其传递回模型,以便它可以重试:

在这个例子中,

  1. LLM 使用 San Francisco 作为参数查询天气

  2. 我们手动设置了一个陷阱,如果是首字母大写了,返回错误:Please lowercase the first letter of the place name

  3. LLM 能够理解错误并改正

例子2

在这个例子中,

  1. LLM 能够准确理解参数限制

    1. 如果第一次理解不了,pydantic 输出的 error 也能帮助 LLM 修改参数

  2. 我们手动设置了一个陷阱,topic 不能直接包含 "water"

  3. LLM 能够理解错误并改正

我们使用 pydantic 设置的参数限制,LLM 能看到

最后更新于