Runnables can easily be used to string together multiple Chains
Runnables 可以很容易地用于将多个链串在一起
安装依赖
pip install --upgrade --quiet langchain-core langchain-community langchain-openai
编写代码
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}")
观察代码
chain1 = prompt1 | model | StrOutputParser() chain2 = ( {"city": chain1, "language": itemgetter("language")} | prompt2 | model | StrOutputParser() )
我们可以发现, chian1
和 chian2
可以很方便的串联在一起,方便我们进行扩展。
运行结果
➜ python3 test07.py message: Chicago, Illinois, se encuentra en los Estados Unidos.