构建LangChain应用出现的TypeError错误

在阅读LangChain官网给出的一些案列时,实际运行却报错,案列代码如下:

python 复制代码
from langchain.prompts import ChatPromptTemplate
from langchain_community.chat_models import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_template("tell me a short joke about {topic}")
model = ChatOpenAI()
output_parser = StrOutputParser()

chain = prompt | model | output_parser

chain.invoke({"topic": "ice cream"})

错误1:TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: <class 'langchain_core.output_parsers.string.StrOutputParser'>

完整报错信息如下:

bash 复制代码
Traceback (most recent call last):
  File "~/PycharmProjects/LangChain/main.py", line 14, in <module>
    chain = prompt | model | output_parser
  File "~/opt/anaconda3/envs/langchain/lib/python3.8/site-packages/langchain/schema/runnable/base.py", line 1165, in __or__
    last=coerce_to_runnable(other),
  File "~/opt/anaconda3/envs/langchain/lib/python3.8/site-packages/langchain/schema/runnable/base.py", line 2774, in coerce_to_runnable
    raise TypeError(
TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: <class 'langchain_core.output_parsers.string.StrOutputParser'>

出现这个错误的原因是因为输出解析器不正确,不支持StrOutputParser而是要使用BaseOutputParser,因此我们可以自己来实现一个BaseOutputParser:

如下:

python 复制代码
class CommaSeparatedListOutputParser(BaseOutputParser):
    """Parse the output of an LLM call to a comma-separated list."""

    def parse(self, text: str):
        """Parse the output of an LLM call."""

        return text.strip()

即更新代码如下:

python 复制代码
import os
from langchain.prompts import ChatPromptTemplate
from langchain_community.chat_models import ChatOpenAI
from langchain.schema import BaseOutputParser

os.environ["OPENAI_API_KEY"] = "xxx"

class CommaSeparatedListOutputParser(BaseOutputParser):
    """Parse the output of an LLM call to a comma-separated list."""

    def parse(self, text: str):
        """Parse the output of an LLM call."""

        return text.strip()


prompt = ChatPromptTemplate.from_template("tell me a short joke about {topic}")
model = ChatOpenAI()
output_parser = CommaSeparatedListOutputParser()

chain = prompt | model | output_parser

chain.invoke({"topic": "ice cream"})

仍然报错2

错误2:TypeError: Got unknown type ('messages', [HumanMessage(content='tell me a short joke about ice cream')])

错误原因是引入ChatOpenAI的包不对,原始的引入是from langchain_community.chat_models import ChatOpenAI改为from langchain.chat_models import ChatOpenAI即可,修改上面2处问题后,即可正确运行代码

完整正确的代码如下

python 复制代码
import os
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
from langchain.schema import BaseOutputParser

os.environ["OPENAI_API_KEY"] = "xxx"


class CommaSeparatedListOutputParser(BaseOutputParser):
    """Parse the output of an LLM call to a comma-separated list."""

    def parse(self, text: str):
        """Parse the output of an LLM call."""

        return text.strip()


prompt = ChatPromptTemplate.from_template("tell me a short joke about {topic}")
model = ChatOpenAI()
output_parser = CommaSeparatedListOutputParser()

chain = prompt | model | output_parser

res = chain.invoke({"topic": "ice cream"})
print(res)

输出:

bash 复制代码
Why did the ice cream go to therapy?
Because it had too many toppings and couldn't keep its sprinkles together!
相关推荐
大翻哥哥1 天前
Python 2025:低代码开发与自动化运维的新纪元
运维·python·低代码
Source.Liu1 天前
【Pywinauto库】12.2 pywinauto.element_info 后端内部实施模块
windows·python·自动化
Source.Liu1 天前
【Pywinauto库】12.1 pywinauto.backend 后端内部实施模块
开发语言·windows·python·自动化
用户8356290780511 天前
用Python高效处理Excel数据:Excel数据读取指南
后端·python
我星期八休息1 天前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
蒋星熠1 天前
如何在Anaconda中配置你的CUDA & Pytorch & cuNN环境(2025最新教程)
开发语言·人工智能·pytorch·python·深度学习·机器学习·ai
合作小小程序员小小店1 天前
机器学习介绍
人工智能·python·机器学习·scikit-learn·安全威胁分析
JavaEdge在掘金1 天前
掌握Spring IoC容器和Bean作用,轻松实现依赖注入!
python
flysh051 天前
pyAutoGUI 模块主要功能介绍-(2)键盘功能
python·pyautogui
强盛小灵通专卖员1 天前
闪电科创 SCI专业辅导
python·深度强化学习·研究生·ei会议·导师·sci期刊