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

无法从langchain_core.runnables.config导入_set_config_context的解决方法咨询

解决LangChain中导入BaseTool时的_set_config_context缺失错误

问题原因

项目中ollama_functions.py导入langchain_core.tools.BaseTool时,langchain_core/tools.py尝试从langchain_core.runnables.config导入内部函数_set_config_context,但当前安装的langchain-core版本中不存在该函数,触发ImportError。

可行解决办法

1. 对齐LangChain Core版本

_set_config_context作为内部函数,其存在性随langchain-core版本变化:

  • 升级到兼容版本:如果该函数是新版本新增的,执行命令升级:
    pip install --upgrade langchain-core
    
  • 降级到兼容版本:如果新版本移除了该函数,查找包含该函数的旧版本(例如0.1.45)并降级:
    pip install langchain-core==0.1.45
    

2. 手动添加猴子补丁

若不想调整版本,可在ollama_functions.py开头添加猴子补丁,手动定义并注入该函数:

import sys
from langchain_core.runnables.config import var_child_runnable_config

def _set_config_context(config):
    try:
        from langsmith import RunTree, run_helpers
        var_child_runnable_config.set(config)
        if hasattr(RunTree, "from_runnable_config"):
            rt = RunTree.from_runnable_config(dict(config))
            tc = run_helpers.get_tracing_context()
            run_helpers._set_tracing_context({**tc, "parent": rt})
    except ImportError:
        # 兼容langsmith未安装或版本不匹配的情况
        var_child_runnable_config.set(config)

# 将函数注入目标模块
sys.modules['langchain_core.runnables.config']._set_config_context = _set_config_context

# 之后再导入BaseTool
from langchain_core.tools import BaseTool

3. 替换依赖类(备选)

如果项目对BaseTool的依赖并非必须,可尝试自定义工具基类,或使用langchain.tools中的其他替代类,避免导入触发错误的模块。

内容的提问来源于stack exchange,提问作者mgpopinjay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:27:18