掌握LangChain工具调用错误处理策略,提升模型稳定性

138 阅读2分钟

引言

在使用大型语言模型(LLM)进行工具调用时,虽然比单纯的提示要可靠,但仍然不完美。可能会出现模型调用不存在的工具,或未能返回与请求架构匹配的参数等问题。尽管可以通过简化架构、减少工具数量以及起好名字和描述来减轻这些风险,但这些方法并不万无一失。本文将介绍如何在链中构建错误处理以缓解这些故障模式。

主要内容

设置环境

在这篇文章中,我们将使用LangChain库。首先,安装以下Python包:

%pip install --upgrade --quiet langchain-core langchain-openai

定义工具和链

我们定义一个复杂的工具,其需要三个参数:int_argfloat_argdict_arg。接下来,创建一个链条来调用这个工具:

from langchain_core.tools import tool

@tool
def complex_tool(int_arg: int, float_arg: float, dict_arg: dict) -> int:
    """Do something complex with a complex tool."""
    return int_arg * float_arg

llm_with_tools = llm.bind_tools([complex_tool])

# 定义链
chain = llm_with_tools | (lambda msg: msg.tool_calls[0]["args"]) | complex_tool

错误处理策略

使用try/except捕获工具调用错误

from typing import Any

def try_except_tool(tool_args: dict, config: RunnableConfig) -> Any:
    try:
        return complex_tool.invoke(tool_args, config=config)
    except Exception as e:
        return f"Calling tool with arguments:\n\n{tool_args}\n\nraised the following error:\n\n{type(e)}: {e}"

chain = llm_with_tools | (lambda msg: msg.tool_calls[0]["args"]) | try_except_tool

print(
    chain.invoke(
        "use complex tool. the args are 5, 2.1, empty dictionary. don't forget dict_arg"
    )
)

使用回退机制

在工具调用错误时使用回退到更好的模型:

better_model = ChatOpenAI(model="gpt-4-1106-preview", temperature=0).bind_tools(
    [complex_tool], tool_choice="complex_tool"
)

better_chain = better_model | (lambda msg: msg.tool_calls[0]["args"]) | complex_tool

chain_with_fallback = chain.with_fallbacks([better_chain])

result = chain_with_fallback.invoke(
    "use complex tool. the args are 5, 2.1, empty dictionary. don't forget dict_arg"
)

print(result)

自动重试

通过传递异常信息来自动重试,使模型有机会纠正其行为:

from langchain_core.messages import AIMessage, HumanMessage, ToolCall, ToolMessage

def tool_custom_exception(msg: AIMessage, config: RunnableConfig) -> Any:
    try:
        return complex_tool.invoke(msg.tool_calls[0]["args"], config=config)
    except Exception as e:
        raise CustomToolException(msg.tool_calls[0], e)

# 在初始链调用失败时重试
self_correcting_chain = chain.with_fallbacks(
    [exception_to_messages | chain], exception_key="exception"
)

result = self_correcting_chain.invoke(
    {
        "input": "use complex tool. the args are 5, 2.1, empty dictionary. don't forget dict_arg"
    }
)

print(result)

总结和进一步学习资源

通过以上策略,可以更好地处理在LangChain中调用工具时遇到的错误。接下来,您可以进一步学习以下主题:

  • 使用工具进行少样本提示
  • 流式工具调用
  • 将运行时值传递给工具
  • 获取模型的结构化输出

参考资料

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

---END---