Created
June 24, 2023 17:26
-
-
Save perryism/7a1974ca86e1c395eef752d5867b57fd to your computer and use it in GitHub Desktop.
Simplied SequentialChain in LangChain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from langchain.chains import SequentialChain | |
from langchain.prompts import ChatPromptTemplate | |
from langchain.chains import LLMChain | |
from langchain.chat_models import ChatOpenAI | |
llm = ChatOpenAI(temperature=0.9) | |
class MyChain: | |
def __init__(self, llm=None, template_engine=None): | |
self.llm = llm | |
self.chains = [] | |
self.outputs = [] | |
self.inputs = None | |
self.template_engine= template_engine | |
def first(self, prompt_txt: str, output: str): | |
if len(self.chains) != 0: | |
raise Exception("Chain is not empty") | |
prompt = self.template_engine.from_template(prompt_txt) | |
self.inputs = prompt.messages[0].prompt.input_variables | |
self.next(prompt_txt, output) | |
def next(self, prompt_txt: str, output: str): | |
prompt = self.template_engine.from_template(prompt_txt) | |
self.outputs.append(output) | |
chain = LLMChain(llm=llm, prompt=prompt, | |
output_key=output | |
) | |
self.chains.append(chain) | |
def query(self, **inputs): | |
overall_chain = SequentialChain( | |
chains=self.chains, | |
input_variables=self.inputs, | |
output_variables=self.outputs, | |
verbose=True | |
) | |
return overall_chain(inputs) | |
chain = MyChain(llm=llm, template_engine=ChatPromptTemplate) | |
chain.first(""" | |
Translate the following review to {input_language}: | |
{Review} | |
""", "English_Review") | |
chain.next(""" | |
Can you summarize the following review in 1 sentence: | |
{English_Review} | |
""", "summary") | |
chain.next(""" | |
What language is the following review: | |
{Review} | |
""", "language") | |
chain.next(""" | |
Write a follow up response to the following summary in the specified language: | |
Summary: {summary} | |
Language: {language} | |
""", "followup_message") | |
print(chain.inputs) | |
chain.query(input_language="Chinese", Review="What is it?") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment