id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
846d1ef53301-1 | human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
# get a chat completion from the formatted messages
chat(chat_prompt.format_prompt(input_language="English", output_langua... | /content/https://python.langchain.com/en/latest/modules/models/chat/integrations/openai.html |
f31c9373548c-0 | .ipynb
.pdf
Anthropic
Contents
ChatAnthropic also supports async and streaming functionality:
Anthropic#
This notebook covers how to get started with Anthropic chat models.
from langchain.chat_models import ChatAnthropic
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
... | /content/https://python.langchain.com/en/latest/modules/models/chat/integrations/anthropic.html |
f31c9373548c-1 | chat(messages)
J'adore programmer.
AIMessage(content=" J'adore programmer.", additional_kwargs={})
previous
Integrations
next
Azure
Contents
ChatAnthropic also supports async and streaming functionality:
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/models/chat/integrations/anthropic.html |
e9142d2e590b-0 | .ipynb
.pdf
Azure
Azure#
This notebook goes over how to connect to an Azure hosted OpenAI endpoint
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage
BASE_URL = "https://${TODO}.openai.azure.com"
API_KEY = "..."
DEPLOYMENT_NAME = "chat"
model = AzureChatOpenAI(
openai_api_ba... | /content/https://python.langchain.com/en/latest/modules/models/chat/integrations/azure_chat_openai.html |
49ca60eed9ab-0 | .ipynb
.pdf
Llama-cpp
Llama-cpp#
This notebook goes over how to use Llama-cpp embeddings within LangChain
!pip install llama-cpp-python
from langchain.embeddings import LlamaCppEmbeddings
llama = LlamaCppEmbeddings(model_path="/path/to/model/ggml-model-q4_0.bin")
text = "This is a test document."
query_result = llama.e... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/llamacpp.html |
abf959667413-0 | .ipynb
.pdf
Aleph Alpha
Contents
Asymmetric
Symmetric
Aleph Alpha#
There are two possible ways to use Aleph Alpha’s semantic embeddings. If you have texts with a dissimilar structure (e.g. a Document and a Query) you would want to use asymmetric embeddings. Conversely, for texts with comparable structures, symmetric ... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/aleph_alpha.html |
a7a99e2a0b2d-0 | .ipynb
.pdf
Self Hosted Embeddings
Self Hosted Embeddings#
Let’s load the SelfHostedEmbeddings, SelfHostedHuggingFaceEmbeddings, and SelfHostedHuggingFaceInstructEmbeddings classes.
from langchain.embeddings import (
SelfHostedEmbeddings,
SelfHostedHuggingFaceEmbeddings,
SelfHostedHuggingFaceInstructEmbeddi... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/self-hosted.html |
a7a99e2a0b2d-1 | Now let’s load an embedding model with a custom load function:
def get_pipeline():
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
pipeline,
) # Must be inside the function in notebooks
model_id = "facebook/bart-base"
tokenizer = AutoTokenizer.from_pretrained(mod... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/self-hosted.html |
2e482558025e-0 | .ipynb
.pdf
Cohere
Cohere#
Let’s load the Cohere Embedding class.
from langchain.embeddings import CohereEmbeddings
embeddings = CohereEmbeddings(cohere_api_key=cohere_api_key)
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
AzureOpe... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/cohere.html |
0e0c4368193e-0 | .ipynb
.pdf
OpenAI
OpenAI#
Let’s load the OpenAI Embedding class.
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
Let’s load the OpenAI Embedding class with fir... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/openai.html |
a53642debdd0-0 | .ipynb
.pdf
TensorflowHub
TensorflowHub#
Let’s load the TensorflowHub Embedding class.
from langchain.embeddings import TensorflowHubEmbeddings
embeddings = TensorflowHubEmbeddings()
2023-01-30 23:53:01.652176: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neu... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/tensorflowhub.html |
f0c7637fb038-0 | .ipynb
.pdf
Jina
Jina#
Let’s load the Jina Embedding class.
from langchain.embeddings import JinaEmbeddings
embeddings = JinaEmbeddings(jina_auth_token=jina_auth_token, model_name="ViT-B-32::openai")
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([t... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/jina.html |
3e38dbfa40cf-0 | .ipynb
.pdf
Sentence Transformers Embeddings
Sentence Transformers Embeddings#
SentenceTransformers embeddings are called using the HuggingFaceEmbeddings integration. We have also added an alias for SentenceTransformerEmbeddings for users who are more familiar with directly using that package.
SentenceTransformers is a... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/sentence_transformers.html |
83e297ba3c57-0 | .ipynb
.pdf
Hugging Face Hub
Hugging Face Hub#
Let’s load the Hugging Face Embedding class.
from langchain.embeddings import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
F... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/huggingfacehub.html |
e402d06e9cf4-0 | .ipynb
.pdf
SageMaker Endpoint Embeddings
SageMaker Endpoint Embeddings#
Let’s load the SageMaker Endpoints Embeddings class. The class can be used if you host, e.g. your own Hugging Face model on SageMaker.
For instructions on how to do this, please see here. Note: In order to handle batched requests, you will need to... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/sagemaker-endpoint.html |
e402d06e9cf4-1 | return response_json["vectors"]
content_handler = ContentHandler()
embeddings = SagemakerEndpointEmbeddings(
# endpoint_name="endpoint-name",
# credentials_profile_name="credentials-profile-name",
endpoint_name="huggingface-pytorch-inference-2023-03-21-16-14-03-834",
region_name="us-east-1",
con... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/sagemaker-endpoint.html |
d53f3c90d292-0 | .ipynb
.pdf
AzureOpenAI
AzureOpenAI#
Let’s load the OpenAI Embedding class with environment variables set to indicate to use Azure endpoints.
# set the environment variables needed for openai package to know to reach out to azure
import os
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https:/... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/azureopenai.html |
8aa9d09c4cab-0 | .ipynb
.pdf
InstructEmbeddings
InstructEmbeddings#
Let’s load the HuggingFace instruct Embeddings class.
from langchain.embeddings import HuggingFaceInstructEmbeddings
embeddings = HuggingFaceInstructEmbeddings(
query_instruction="Represent the query for retrieval: "
)
load INSTRUCTOR_Transformer
max_seq_length 51... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/instruct_embeddings.html |
e69c8e10a440-0 | .ipynb
.pdf
Fake Embeddings
Fake Embeddings#
LangChain also provides a fake embedding class. You can use this to test your pipelines.
from langchain.embeddings import FakeEmbeddings
embeddings = FakeEmbeddings(size=1352)
query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
prev... | /content/https://python.langchain.com/en/latest/modules/models/text_embedding/examples/fake.html |
6fe1e043a3b1-0 | .rst
.pdf
How-To Guides
Contents
Types
Usage
How-To Guides#
Types#
The first set of examples all highlight different types of memory.
ConversationBufferMemory
ConversationBufferWindowMemory
Entity Memory
Conversation Knowledge Graph Memory
ConversationSummaryMemory
ConversationSummaryBufferMemory
ConversationTokenBuf... | /content/https://python.langchain.com/en/latest/modules/memory/how_to_guides.html |
bea1ab2b3b74-0 | .ipynb
.pdf
Getting Started
Contents
ChatMessageHistory
ConversationBufferMemory
Using in a chain
Saving Message History
Getting Started#
This notebook walks through how LangChain thinks about memory.
Memory involves keeping a concept of state around throughout a user’s interactions with an language model. A user’s i... | /content/https://python.langchain.com/en/latest/modules/memory/getting_started.html |
bea1ab2b3b74-1 | You may want to use this class directly if you are managing memory outside of a chain.
from langchain.memory import ChatMessageHistory
history = ChatMessageHistory()
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages
[HumanMessage(content='hi!', additional_kwargs={}),
AIMessage(conten... | /content/https://python.langchain.com/en/latest/modules/memory/getting_started.html |
bea1ab2b3b74-2 | memory.load_memory_variables({})
{'history': [HumanMessage(content='hi!', additional_kwargs={}),
AIMessage(content='whats up?', additional_kwargs={})]}
Using in a chain#
Finally, let’s take a look at using this in a chain (setting verbose=True so we can see the prompt).
from langchain.llms import OpenAI
from langchai... | /content/https://python.langchain.com/en/latest/modules/memory/getting_started.html |
bea1ab2b3b74-3 | AI: Hi there! It's nice to meet you. How can I help you today?
Human: I'm doing well! Just having a conversation with an AI.
AI:
> Finished chain.
" That's great! It's always nice to have a conversation with someone new. What would you like to talk about?"
conversation.predict(input="Tell me about yourself.")
> Enteri... | /content/https://python.langchain.com/en/latest/modules/memory/getting_started.html |
bea1ab2b3b74-4 | from langchain.schema import messages_from_dict, messages_to_dict
history = ChatMessageHistory()
history.add_user_message("hi!")
history.add_ai_message("whats up?")
dicts = messages_to_dict(history.messages)
dicts
[{'type': 'human', 'data': {'content': 'hi!', 'additional_kwargs': {}}},
{'type': 'ai', 'data': {'content... | /content/https://python.langchain.com/en/latest/modules/memory/getting_started.html |
303c589df758-0 | .ipynb
.pdf
Redis Chat Message History
Redis Chat Message History#
This notebook goes over how to use Redis to store chat message history.
from langchain.memory import RedisChatMessageHistory
history = RedisChatMessageHistory("foo")
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages
[A... | /content/https://python.langchain.com/en/latest/modules/memory/examples/redis_chat_message_history.html |
7b0af42b9b89-0 | .ipynb
.pdf
How to customize conversational memory
Contents
AI Prefix
Human Prefix
How to customize conversational memory#
This notebook walks through a few ways to customize conversational memory.
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.memory import Conversati... | /content/https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
7b0af42b9b89-1 | > Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
... | /content/https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
7b0af42b9b89-2 | > Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
... | /content/https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
7b0af42b9b89-3 | # Now we can override it and set it to "Friend"
from langchain.prompts.prompt import PromptTemplate
template = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfull... | /content/https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
7b0af42b9b89-4 | Current conversation:
Friend: Hi there!
AI: Hi there! It's nice to meet you. How can I help you today?
Friend: What's the weather?
AI:
> Finished ConversationChain chain.
' The weather right now is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the rest of the day is mostly sunny with a h... | /content/https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
d27c5d7dc050-0 | .ipynb
.pdf
How to add memory to a Multi-Input Chain
How to add memory to a Multi-Input Chain#
Most memory objects assume a single output. In this notebook, we go over how to add memory to a chain that has multiple outputs. As an example of such a chain, we will add memory to a question/answering chain. This chain take... | /content/https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
d27c5d7dc050-1 | docs = docsearch.similarity_search(query)
from langchain.chains.question_answering import load_qa_chain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
template = """You are a chatbot having a conversation with a human.
Given the follo... | /content/https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
d27c5d7dc050-2 | Human: What did the president say about Justice Breyer
AI: Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.
previous
H... | /content/https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
cd6df6c5ef4e-0 | .ipynb
.pdf
How to add Memory to an LLMChain
How to add Memory to an LLMChain#
This notebook goes over how to use the Memory class with an LLMChain. For the purposes of this walkthrough, we will add the ConversationBufferMemory class, although this can be any memory class.
from langchain.memory import ConversationBuff... | /content/https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html |
cd6df6c5ef4e-1 | > 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... | /content/https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html |
ed586e2bf42c-0 | .ipynb
.pdf
How to add Memory to an Agent
How to add Memory to an Agent#
This notebook goes over adding memory to an Agent. Before going through this notebook, please walkthrough the following notebooks, as this will build on top of both of them:
Adding memory to an LLM Chain
Custom Agents
In order to add a memory to a... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-1 | tools,
prefix=prefix,
suffix=suffix,
input_variables=["input", "chat_history", "agent_scratchpad"]
)
memory = ConversationBufferMemory(memory_key="chat_history")
We can now construct the LLMChain, with the Memory object, and then create the agent.
llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=pr... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-2 | Action: Search
Action Input: Population of Canada
Observation: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-3 | > Finished AgentExecutor chain.
'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'
To test the memory of this agent, we can ask a followup question that relies on information in the previous exchange to be answered corr... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-4 | Observation: Jun 7, 2010 ... https://twitter.com/CanadaImmigrantCanadian National Anthem O Canada in HQ - complete with lyrics, captions, vocals & music.LYRICS:O Canada! Nov 23, 2022 ... After 100 years of tradition, O Canada was proclaimed Canada's national anthem in 1980. The music for O Canada was composed in 1880 b... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-5 | Thought: I now know the final answer.
Final Answer: The national anthem of Canada is called "O Canada".
> Finished AgentExecutor chain.
'The national anthem of Canada is called "O Canada".'
We can see that the agent remembered that the previous question was about Canada, and properly asked Google Search what the name o... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-6 | Action: Search
Action Input: Population of Canada
Observation: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-7 | > Finished AgentExecutor chain.
'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'
agent_without_memory.run("what is their national anthem called?")
> Entering new AgentExecutor chain...
Thought: I should look up the an... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-8 | Observation: Most nation states have an anthem, defined as "a song, as of praise, devotion, or patriotism"; most anthems are either marches or hymns in style. List of all countries around the world with its national anthem. ... Title and lyrics in the language of the country and translated into English, Aug 1, 2021 ...... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-9 | anthem in the ... There are many countries over the world who have a national anthem of their own. | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
ed586e2bf42c-10 | Thought: I now know the final answer
Final Answer: The national anthem of [country] is [name of anthem].
> Finished AgentExecutor chain.
'The national anthem of [country] is [name of anthem].'
previous
How to add memory to a Multi-Input Chain
next
Adding Message Memory backed by a database to an Agent
By Harrison Chase... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
902885ef3f25-0 | .ipynb
.pdf
Motörhead Memory
Contents
Setup
Motörhead Memory#
Motörhead is a memory server implemented in Rust. It automatically handles incremental summarization in the background and allows for stateless applications.
Setup#
See instructions at Motörhead for running the server locally.
from langchain.memory.motorhe... | /content/https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html |
902885ef3f25-1 | AI: Hi Bob, nice to meet you! How are you doing today?
Human: whats my name?
AI:
> Finished chain.
' You said your name is Bob. Is that correct?'
llm_chain.run("whats for dinner?")
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: hi im bob
AI: Hi B... | /content/https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html |
a317375d63ca-0 | .ipynb
.pdf
Postgres Chat Message History
Postgres Chat Message History#
This notebook goes over how to use Postgres to store chat message history.
from langchain.memory import PostgresChatMessageHistory
history = PostgresChatMessageHistory(connection_string="postgresql://postgres:mypassword@localhost/chat_history", se... | /content/https://python.langchain.com/en/latest/modules/memory/examples/postgres_chat_message_history.html |
2ec0921f0fb1-0 | .ipynb
.pdf
Adding Message Memory backed by a database to an Agent
Adding Message Memory backed by a database to an Agent#
This notebook goes over adding memory to an Agent where the memory uses an external message store. Before going through this notebook, please walkthrough the following notebooks, as this will build... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-1 | prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:"""
suffix = """Begin!"
{chat_history}
Question: {input}
{agent_scratchpad}"""
prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_varia... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-2 | Action: Search
Action Input: Population of Canada
Observation: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-3 | > Finished AgentExecutor chain.
'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'
To test the memory of this agent, we can ask a followup question that relies on information in the previous exchange to be answered corr... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-4 | Observation: Jun 7, 2010 ... https://twitter.com/CanadaImmigrantCanadian National Anthem O Canada in HQ - complete with lyrics, captions, vocals & music.LYRICS:O Canada! Nov 23, 2022 ... After 100 years of tradition, O Canada was proclaimed Canada's national anthem in 1980. The music for O Canada was composed in 1880 b... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-5 | Thought: I now know the final answer.
Final Answer: The national anthem of Canada is called "O Canada".
> Finished AgentExecutor chain.
'The national anthem of Canada is called "O Canada".'
We can see that the agent remembered that the previous question was about Canada, and properly asked Google Search what the name o... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-6 | Action: Search
Action Input: Population of Canada
Observation: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-7 | > Finished AgentExecutor chain.
'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'
agent_without_memory.run("what is their national anthem called?")
> Entering new AgentExecutor chain...
Thought: I should look up the an... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-8 | Observation: Most nation states have an anthem, defined as "a song, as of praise, devotion, or patriotism"; most anthems are either marches or hymns in style. List of all countries around the world with its national anthem. ... Title and lyrics in the language of the country and translated into English, Aug 1, 2021 ...... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-9 | anthem in the ... There are many countries over the world who have a national anthem of their own. | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
2ec0921f0fb1-10 | Thought: I now know the final answer
Final Answer: The national anthem of [country] is [name of anthem].
> Finished AgentExecutor chain.
'The national anthem of [country] is [name of anthem].'
previous
How to add Memory to an Agent
next
How to customize conversational memory
By Harrison Chase
© Copyright 202... | /content/https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
ac7e730deae5-0 | .ipynb
.pdf
How to use multiple memory classes in the same chain
How to use multiple memory classes in the same chain#
It is also possible to use multiple memory classes in the same chain. To combine multiple memory classes, we can initialize the CombinedMemory class, and then use that.
from langchain.llms import OpenA... | /content/https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html |
ac7e730deae5-1 | verbose=True,
memory=memory,
prompt=PROMPT
)
conversation.run("Hi!")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the ans... | /content/https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html |
e47488543823-0 | .ipynb
.pdf
How to create a custom Memory class
How to create a custom Memory class#
Although there are a few predefined types of memory in LangChain, it is highly possible you will want to add your own type of memory that is optimal for your application. This notebook covers how to do that.
For this notebook, we will ... | /content/https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
e47488543823-1 | def clear(self):
self.entities = {}
@property
def memory_variables(self) -> List[str]:
"""Define the variables we are providing to the prompt."""
return [self.memory_key]
def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
"""Load the memory variables, ... | /content/https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
e47488543823-2 | else:
self.entities[ent_str] = text
We now define a prompt that takes in information about entities as well as user input
from langchain.prompts.prompt import PromptTemplate
template = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specifi... | /content/https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
e47488543823-3 | Human: Harrison likes machine learning
AI:
> Finished ConversationChain chain.
" That's great to hear! Machine learning is a fascinating field of study. It involves using algorithms to analyze data and make predictions. Have you ever studied machine learning, Harrison?"
Now in the second example, we can see that it pul... | /content/https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
8591ffd4dff9-0 | .ipynb
.pdf
ConversationBufferMemory
Contents
Using in a chain
ConversationBufferMemory#
This notebook shows how to use ConversationBufferMemory. This memory allows for storing of messages and then extracts the messages in a variable.
We can first extract it as a string.
from langchain.memory import ConversationBuffe... | /content/https://python.langchain.com/en/latest/modules/memory/types/buffer.html |
8591ffd4dff9-1 | llm=llm,
verbose=True,
memory=ConversationBufferMemory()
)
conversation.predict(input="Hi there!")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. ... | /content/https://python.langchain.com/en/latest/modules/memory/types/buffer.html |
8591ffd4dff9-2 | Current conversation:
Human: Hi there!
AI: Hi there! It's nice to meet you. How can I help you today?
Human: I'm doing well! Just having a conversation with an AI.
AI: That's great! It's always nice to have a conversation with someone new. What would you like to talk about?
Human: Tell me about yourself.
AI:
> Finish... | /content/https://python.langchain.com/en/latest/modules/memory/types/buffer.html |
1529c00e4017-0 | .ipynb
.pdf
ConversationTokenBufferMemory
Contents
Using in a chain
ConversationTokenBufferMemory#
ConversationTokenBufferMemory keeps a buffer of recent interactions in memory, and uses token length rather than number of interactions to determine when to flush interactions.
Let’s first walk through how to use the ut... | /content/https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html |
1529c00e4017-1 | Using in a chain#
Let’s walk through an example, again setting verbose=True so we can see the prompt.
from langchain.chains import ConversationChain
conversation_with_summary = ConversationChain(
llm=llm,
# We set a very low max_token_limit for the purposes of testing.
memory=ConversationTokenBufferMemory(... | /content/https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html |
1529c00e4017-2 | ' Sounds like a productive day! What kind of documentation are you writing?'
conversation_with_summary.predict(input="For LangChain! Have you heard of it?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and prov... | /content/https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html |
1529c00e4017-3 | Current conversation:
Human: For LangChain! Have you heard of it?
AI: Yes, I have heard of LangChain! It is a decentralized language-learning platform that connects native speakers and learners in real time. Is that the documentation you're writing about?
Human: Haha nope, although a lot of people confuse it for that
... | /content/https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html |
9a7438d088cc-0 | .ipynb
.pdf
ConversationBufferWindowMemory
Contents
Using in a chain
ConversationBufferWindowMemory#
ConversationBufferWindowMemory keeps a list of the interactions of the conversation over time. It only uses the last K interactions. This can be useful for keeping a sliding window of the most recent interactions, so ... | /content/https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html |
9a7438d088cc-1 | AIMessage(content='not much', additional_kwargs={})]}
Using in a chain#
Let’s walk through an example, again setting verbose=True so we can see the prompt.
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
conversation_with_summary = ConversationChain(
llm=OpenAI(temperature=0),
... | /content/https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html |
9a7438d088cc-2 | Human: What's their issues?
AI:
> Finished chain.
" The customer is having trouble connecting to their Wi-Fi network. I'm helping them troubleshoot the issue and get them connected."
conversation_with_summary.predict(input="Is it going well?")
> Entering new ConversationChain chain...
Prompt after formatting:
The follo... | /content/https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html |
9a7438d088cc-3 | Human: Is it going well?
AI: Yes, it's going well so far. We've already identified the problem and are now working on a solution.
Human: What's the solution?
AI:
> Finished chain.
" The solution is to reset the router and reconfigure the settings. We're currently in the process of doing that."
previous
ConversationBuf... | /content/https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html |
cdc669b118a3-0 | .ipynb
.pdf
Entity Memory
Contents
Using in a chain
Inspecting the memory store
Entity Memory#
This notebook shows how to work with a memory module that remembers things about specific entities. It extracts information on entities (using LLMs) and builds up its knowledge about that entity over time (also using LLMs).... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-1 | memory.save_context(
_input,
{"ouput": " That sounds like a great project! What kind of project are they working on?"}
)
memory.load_memory_variables({"input": 'who is Sam'})
{'history': [HumanMessage(content='Deven & Sam are working on a hackathon project', additional_kwargs={}),
AIMessage(content=' That sou... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-2 | You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding convers... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-3 | 'Sam': 'Sam is working on a hackathon project with Deven.'}
conversation.predict(input="They are trying to add more complex memory structures to Langchain")
> Entering new ConversationChain chain...
Prompt after formatting:
You are an assistant to a human, powered by a large language model trained by OpenAI.
You are de... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-4 | Context:
{'Deven': 'Deven is working on a hackathon project with Sam, which they are entering into a hackathon.', 'Sam': 'Sam is working on a hackathon project with Deven.', 'Langchain': ''}
Current conversation:
Human: Deven & Sam are working on a hackathon project
AI: That sounds like a great project! What kind of p... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-5 | You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the ... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-6 | You:
> Finished chain.
' That sounds like a great idea! How will the key-value store help with the project?'
conversation.predict(input="What do you know about Deven & Sam?")
> Entering new ConversationChain chain...
Prompt after formatting:
You are an assistant to a human, powered by a large language model trained by ... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-7 | Context:
{'Deven': 'Deven is working on a hackathon project with Sam, which they are entering into a hackathon. They are trying to add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the conversation.', 'Sam': 'Sam is working on a hackathon project with Deven, t... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-8 | pprint(conversation.memory.entity_store.store)
{'Daimon': 'Daimon is a company founded by Sam, a successful entrepreneur.',
'Deven': 'Deven is working on a hackathon project with Sam, which they are '
'entering into a hackathon. They are trying to add more complex '
'memory structures to Langchain,... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-9 | You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding convers... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-10 | AI: That sounds like a great idea! How will the key-value store help with the project?
Human: What do you know about Deven & Sam?
AI: Deven and Sam are working on a hackathon project together, trying to add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the c... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-11 | 'entities mentioned in the conversation.',
'Langchain': 'Langchain is a project that is trying to add more complex '
'memory structures, including a key-value store for entities '
'mentioned so far in the conversation.',
'Sam': 'Sam is working on a hackathon project with Deven, trying to a... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-12 | You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the ... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-13 | Context:
{'Deven': 'Deven is working on a hackathon project with Sam, which they are entering into a hackathon. They are trying to add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the conversation, and seem to be working hard on this project with a great idea... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
cdc669b118a3-14 | Human: Sam is the founder of a company called Daimon.
AI: That's impressive! It sounds like Sam is a very successful entrepreneur. What kind of company is Daimon?
Last line:
Human: What do you know about Sam?
You:
> Finished chain.
' Sam is the founder of a successful company called Daimon. He is also working on a hac... | /content/https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
e8357ff6dcee-0 | .ipynb
.pdf
VectorStore-Backed Memory
Contents
Initialize your VectorStore
Create your the VectorStoreRetrieverMemory
Using in a chain
VectorStore-Backed Memory#
VectorStoreRetrieverMemory stores memories in a VectorDB and queries the top-K most “salient” docs every time it is called.
This differs from most of the ot... | /content/https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
e8357ff6dcee-1 | The memory object is instantiated from any VectorStoreRetriever.
# In actual usage, you would set `k` to be a higher value, but we use k=1 to show that
# the vector lookup still returns the semantically relevant information
retriever = vectorstore.as_retriever(search_kwargs=dict(k=1))
memory = VectorStoreRetrieverMemor... | /content/https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
e8357ff6dcee-2 | llm = OpenAI(temperature=0) # Can be any valid LLM
_DEFAULT_TEMPLATE = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Relevant pieces... | /content/https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
e8357ff6dcee-3 | # Here, the basketball related content is surfaced
conversation_with_summary.predict(input="what's my favorite sport?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from it... | /content/https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
e8357ff6dcee-4 | # since this query best matches the introduction chat above,
# the agent is able to 'remember' the user's name.
conversation_with_summary.predict(input="What's my name?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talk... | /content/https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
0c0a31d0e70a-0 | .ipynb
.pdf
ConversationSummaryBufferMemory
Contents
Using in a chain
ConversationSummaryBufferMemory#
ConversationSummaryBufferMemory combines the last two ideas. It keeps a buffer of recent interactions in memory, but rather than just completely flushing old interactions it compiles them into a summary and uses bot... | /content/https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html |
0c0a31d0e70a-1 | memory.save_context({"input": "hi"}, {"output": "whats up"})
memory.save_context({"input": "not much you"}, {"output": "not much"})
We can also utilize the predict_new_summary method directly.
messages = memory.chat_memory.messages
previous_summary = ""
memory.predict_new_summary(messages, previous_summary)
'\nThe huma... | /content/https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.