当前位置:   article > 正文

LangChain-07 Multiple Chains 多链串联_langchain中把几个chain串起来

langchain中把几个chain串起来

Runnables can easily be used to string together multiple Chains
Runnables 可以很容易地用于将多个链串在一起
请添加图片描述

安装依赖

pip install --upgrade --quiet  langchain-core langchain-community langchain-openai
  • 1

编写代码

from operator import itemgetter

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

prompt1 = ChatPromptTemplate.from_template("what is the city {person} is from?")
prompt2 = ChatPromptTemplate.from_template(
    "what country is the city {city} in? respond in {language}"
)

model = ChatOpenAI(
    model="gpt-3.5-turbo",
)

chain1 = prompt1 | model | StrOutputParser()

chain2 = (
    {"city": chain1, "language": itemgetter("language")}
    | prompt2
    | model
    | StrOutputParser()
)

message = chain2.invoke({"person": "obama", "language": "spanish"})
print(f"message: {message}")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

观察代码

chain1 = prompt1 | model | StrOutputParser()

chain2 = (
    {"city": chain1, "language": itemgetter("language")}
    | prompt2
    | model
    | StrOutputParser()
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

我们可以发现, chian1chian2 可以很方便的串联在一起,方便我们进行扩展。

运行结果

➜ python3 test07.py
message: Chicago, Illinois, se encuentra en los Estados Unidos.
  • 1
  • 2

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/904699
推荐阅读
相关标签
  

闽ICP备14008679号