使用langchain_core.convert_to_openai_function时遇NameError求助
解决LangChain中convert_to_openai_function的NameError问题
问题原因
代码中直接通过langchain_core命名空间调用函数,但未提前导入该模块或对应函数,导致Python无法识别langchain_core名称,触发NameError。
解决方案
方式一:直接导入目标函数(推荐)
直接导入convert_to_openai_function,简化代码调用:
from langchain_core.utils.function_calling import convert_to_openai_function from langchain.tools import GetCurrentWeatherTool tools = [GetCurrentWeatherTool()] functions = [convert_to_openai_function(tool) for tool in tools]
方式二:导入langchain_core模块
若需保留命名空间调用方式,先导入整个langchain_core模块:
import langchain_core from langchain.tools import GetCurrentWeatherTool tools = [GetCurrentWeatherTool()] functions = [langchain_core.utils.function_calling.convert_to_openai_function(tool) for tool in tools]
额外注意事项
- 路径正确性:在LangChain 0.1.x版本中,
convert_to_openai_function的正确路径为langchain_core.utils.function_calling,请勿使用旧版本的路径。 - 工具导入:确保
GetCurrentWeatherTool已从langchain.tools模块正确导入。 - 版本适配:LangChain 0.1.x版本推荐使用
convert_to_openai_function替代旧版的format_tool_to_openai_function,后者已逐步被弃用。
内容的提问来源于stack exchange,提问作者Felipe Martínez Sánchez
相关产品推荐
相关产品推荐

