Como adicionar memória a um LLMChain
Este notebook aborda como usar a classe Memory com um LLMChain. Para este passo a passo, usaremos a classe ConversationBufferMemory
, embora possa ser qualquer classe de memória.
Primeiramente, importamos as classes ConversationBufferMemory, OpenAI, LLMChain e PromptTemplate da biblioteca LangChain.
from langchain.memory import ConversationBufferMemory
from langchain import OpenAI, LLMChain, PromptTemplate
A etapa mais importante é configurar o prompt corretamente. No prompt abaixo, temos duas chaves de entrada: uma para a entrada real, outra para a entrada da classe Memory. É importante garantir que as chaves em PromptTemplate e ConversationBufferMemory correspondam (chat_history
).
Em seguida, criamos uma instância de PromptTemplate com os identificadores “chat_history” e “human_input” e a definimos com um template.
A memória é então definida com a classe ConversationBufferMemory, onde a chave de memória é “chat_history”.
template = """You are a chatbot having a conversation with a human.
{chat_history}
Human: {human_input}
Chatbot:"""
prompt = PromptTemplate(
input_variables=["chat_history", "human_input"],
template=template
)
memory = ConversationBufferMemory(memory_key="chat_history")
O LLMChain é criado em seguida, com uma instância da classe OpenAI como o modelo de linguagem, o prompt que acabamos de criar, a configuração verbose ativada (para impressões de depuração), e a memória que definimos anteriormente.
llm_chain = LLMChain(
llm=OpenAI(),
prompt=prompt,
verbose=True,
memory=memory,
)
llm_chain.predict(human_input="Hi there my friend")
llm_chain.predict(human_input="Hi there my friend")
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: Hi there my friend
Chatbot:
> Finished LLMChain chain.
' Hi there, how are you doing today?'
llm_chain.predict(human_input="Not too bad - how are you?")
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: Hi there my friend
AI: Hi there, how are you doing today?
Human: Not to bad - how are you?
Chatbot:
> Finished LLMChain chain.
" I'm doing great, thank you for asking!"