引言
在使用LangChain库构建基于AI的应用时,调用工具通常比纯粹的提示更加可靠。然而,调用工具也并非完美无瑕。模型可能尝试调用不存在的工具,或未能返回匹配请求参数的结果。本文将探讨一些可以内建于链中以减少失败模式的错误处理策略。
主要内容
1. 设置环境
为了进行演示,我们需要安装以下Python包:
%pip install --upgrade --quiet langchain-core langchain-openai
2. 工具调用链
假设我们有一个复杂工具和工具调用链,我们将故意使工具复杂以试图让模型出错。
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
3. 处理工具调用错误
3.1 使用try/except
我们可以用try/except处理工具调用步骤中的错误,并在错误发生时返回帮助信息:
from typing import Any
from langchain_core.runnables import Runnable, RunnableConfig
def try_except_tool(tool_args: dict, config: RunnableConfig) -> Runnable:
try:
return complex_tool.invoke(tool_args, config=config)
except Exception as e:
return f"Error with args: {tool_args}, {type(e)}: {e}"
3.2 使用回退模型
如果工具调用出错,我们可以改用一个更好的模型作为回退:
from langchain_openai import ChatOpenAI
better_model = ChatOpenAI(model="gpt-4-1106-preview", temperature=0).bind_tools(
[complex_tool], tool_choice="complex_tool"
)
chain_with_fallback = chain.with_fallbacks([better_chain])
3.3 自动重试异常
我们可以自动再次运行链,并传递异常信息,以便模型可以尝试纠正其行为:
from langchain_core.messages import AIMessage
# Custom exception class
class CustomToolException(Exception):
"""Custom LangChain tool exception."""
pass
# Method to invoke and catch exception
def tool_custom_exception(msg: AIMessage, config: RunnableConfig) -> Runnable:
try:
return complex_tool.invoke(msg.tool_calls[0]["args"], config=config)
except Exception as e:
raise CustomToolException(msg.tool_calls[0], e)
代码示例
以下是一个完整的错误处理示例代码:
# Define an error handling chain
chain_with_error_handling = prompt | llm_with_tools | tool_custom_exception
# Self-correcting chain with exception retry logic
self_correcting_chain = chain_with_error_handling.with_fallbacks(
[exception_to_messages | chain_with_error_handling], exception_key="exception"
)
# Example invocation
result = self_correcting_chain.invoke(
{"input": "use complex tool. the args are 5, 2.1, empty dictionary. don't forget dict_arg"}
)
常见问题和解决方案
-
问题:调用工具时未传递所有必要的参数。
- 解决方案:确保工具的schema定义清晰,并在调用时使用简明的参数。
-
问题:模型选择了错误的工具。
- 解决方案:给工具设置清晰的名称和描述,以帮助模型做出正确的选择。
总结和进一步学习资源
通过本文的示例,我们了解到如何在LangChain中处理工具调用错误以及一些有效的错误处理策略。进一步的学习可以包括:
参考资料
- LangChain官方文档:LangChain Documentation
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---