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

运行LangChain检索示例代码报TypeError:dict与str不支持|操作符

问题分析与解决:LangChain中TypeError: unsupported operand type(s) for |: 'dict' and 'str'错误

问题原因

你遇到的错误本质是Python 3.10不支持字典与非字典对象使用|运算符。LangChain表达式语言(LCEL)的示例代码里,用{"context": retriever, "question": RunnablePassthrough()}这种字典语法定义并行任务,再通过|和后续的prompt、model等Runnable对象组合,但Python 3.10中|仅能用于字典之间的合并操作,当右边是prompt这类非字典对象时,就会触发类型错误。

解决方法

有两种可行的解决方式:

  • 升级Python版本:将Python环境升级到3.11及以上,Python 3.11正式引入了字典的|运算符扩展支持,能兼容LCEL的这种语法写法。
  • 替换字典为RunnableParallel:如果无法升级Python,直接用LangChain提供的RunnableParallel类替代字典语法,代码修改如下:
from langchain_core.runnables import RunnableParallel, RunnablePassthrough

chain = (
    RunnableParallel({"context": retriever, "question": RunnablePassthrough()})
    | prompt
    | model
    | StrOutputParser()
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:56:02