构建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!
相关推荐
Johny_Zhao10 小时前
CentOS Stream 8 高可用 Kuboard 部署方案
linux·网络·python·网络安全·docker·信息安全·kubernetes·云计算·shell·yum源·系统运维·kuboard
站大爷IP11 小时前
精通einsum():多维数组操作的瑞士军刀
python
沐森11 小时前
langchain相关介绍
langchain·ai编程
站大爷IP12 小时前
Python与MongoDB的亲密接触:从入门到实战的代码指南
python
Roc-xb12 小时前
/etc/profile.d/conda.sh: No such file or directory : numeric argument required
python·ubuntu·conda
世由心生13 小时前
[从0到1]环境准备--anaconda与pycharm的安装
ide·python·pycharm
猛犸MAMMOTH14 小时前
Python打卡第54天
pytorch·python·深度学习
梓羽玩Python14 小时前
12K+ Star的离线语音神器!50MB模型秒杀云端API,隐私零成本,20+语种支持!
人工智能·python·github
成都犀牛14 小时前
LangGraph 深度学习笔记:构建真实世界的智能代理
人工智能·pytorch·笔记·python·深度学习
終不似少年遊*15 小时前
【数据可视化】Pyecharts-家乡地图
python·信息可视化·数据挖掘·数据分析·数据可视化·pyecharts