You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:55:10