Memory
class langchain.memory.CassandraChatMessageHistory(contact_points, session_id, port=9042, username='cassandra', password='cassandra', keyspace_name='chat_history', table_name='message_store')[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history that stores history in Cassandra.
Parameters
contact_points (List[str]) – list of ips to connect to Cassandra cluster
session_id (str) – arbitrary key that is used to store the messages
of a single chat session.
port (int) – port to connect to Cassandra cluster
username (str) – username to connect to Cassandra cluster
password (str) – password to connect to Cassandra cluster
keyspace_name (str) – name of the keyspace to use
table_name (str) – name of the table to use
property messages: List[langchain.schema.BaseMessage]
Retrieve the messages from Cassandra
add_message(message)[source]
Append the message to the record in Cassandra
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Clear session memory from Cassandra
Return type
None
class langchain.memory.ChatMessageHistory(*, messages=[])[source]
Bases: langchain.schema.BaseChatMessageHistory, pydantic.main.BaseModel
Parameters
messages (List[langchain.schema.BaseMessage]) – 
Return type
None
attribute messages: List[langchain.schema.BaseMessage] = []
add_message(message)[source]
Add a self-created message to the store
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Remove all messages from the store
Return type
None
class langchain.memory.CombinedMemory(*, memories)[source]
Bases: langchain.schema.BaseMemory
Class for combining multiple memories’ data together.
Parameters
memories (List[langchain.schema.BaseMemory]) – 
Return type
None
attribute memories: List[langchain.schema.BaseMemory] [Required]
For tracking all the memories that should be accessed.
clear()[source]
Clear context from this session for every memory.
Return type
None
load_memory_variables(inputs)[source]
Load all vars from sub-memories.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, str]
save_context(inputs, outputs)[source]
Save context from this session for every memory.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property memory_variables: List[str]
All the memory variables that this instance provides.
class langchain.memory.ConversationBufferMemory(*, chat_memory=None, output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', memory_key='history')[source]
Bases: langchain.memory.chat_memory.BaseChatMemory
Buffer for storing conversation memory.
Parameters
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
human_prefix (str) – 
ai_prefix (str) – 
memory_key (str) – 
Return type
None
attribute ai_prefix: str = 'AI'
attribute human_prefix: str = 'Human'
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Any]
property buffer: Any
String buffer of memory.
class langchain.memory.ConversationBufferWindowMemory(*, chat_memory=None, output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', memory_key='history', k=5)[source]
Bases: langchain.memory.chat_memory.BaseChatMemory
Buffer for storing conversation memory.
Parameters
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
human_prefix (str) – 
ai_prefix (str) – 
memory_key (str) – 
k (int) – 
Return type
None
attribute ai_prefix: str = 'AI'
attribute human_prefix: str = 'Human'
attribute k: int = 5
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, str]
property buffer: List[langchain.schema.BaseMessage]
String buffer of memory.
class langchain.memory.ConversationEntityMemory(*, chat_memory=None, output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', llm, entity_extraction_prompt=PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I\'m working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:', template_format='f-string', validate_template=True), entity_summarization_prompt=PromptTemplate(input_variables=['entity', 'summary', 'history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\n\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), return the existing summary unchanged.\n\nFull conversation history (for context):\n{history}\n\nEntity to summarize:\n{entity}\n\nExisting summary of {entity}:\n{summary}\n\nLast line of conversation:\nHuman: {input}\nUpdated summary:', template_format='f-string', validate_template=True), entity_cache=[], k=3, chat_history_key='history', entity_store=None)[source]
Bases: langchain.memory.chat_memory.BaseChatMemory
Entity extractor & summarizer memory.
Extracts named entities from the recent chat history and generates summaries.
With a swapable entity store, persisting entities across conversations.
Defaults to an in-memory entity store, and can be swapped out for a Redis,
SQLite, or other entity store.
Parameters
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
human_prefix (str) – 
ai_prefix (str) – 
llm (langchain.base_language.BaseLanguageModel) – 
entity_extraction_prompt (langchain.prompts.base.BasePromptTemplate) – 
entity_summarization_prompt (langchain.prompts.base.BasePromptTemplate) – 
entity_cache (List[str]) – 
k (int) – 
chat_history_key (str) – 
entity_store (langchain.memory.entity.BaseEntityStore) – 
Return type
None
attribute ai_prefix: str = 'AI'
attribute chat_history_key: str = 'history'
attribute entity_cache: List[str] = []
attribute entity_extraction_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I\'m working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:', template_format='f-string', validate_template=True)
attribute entity_store: langchain.memory.entity.BaseEntityStore [Optional]
attribute entity_summarization_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['entity', 'summary', 'history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\n\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), return the existing summary unchanged.\n\nFull conversation history (for context):\n{history}\n\nEntity to summarize:\n{entity}\n\nExisting summary of {entity}:\n{summary}\n\nLast line of conversation:\nHuman: {input}\nUpdated summary:', template_format='f-string', validate_template=True)
attribute human_prefix: str = 'Human'
attribute k: int = 3
attribute llm: langchain.base_language.BaseLanguageModel [Required]
clear()[source]
Clear memory contents.
Return type
None
load_memory_variables(inputs)[source]
Returns chat history and all generated entities with summaries if available,
and updates or clears the recent entity cache.
New entity name can be found when calling this method, before the entity
summaries are generated, so the entity cache values may be empty if no entity
descriptions are generated yet.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Any]
save_context(inputs, outputs)[source]
Save context from this conversation history to the entity store.
Generates a summary for each entity in the entity cache by prompting
the model, and saves these summaries to the entity store.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property buffer: List[langchain.schema.BaseMessage]
Access chat memory messages.
class langchain.memory.ConversationKGMemory(*, chat_memory=None, output_key=None, input_key=None, return_messages=False, k=2, human_prefix='Human', ai_prefix='AI', kg=None, knowledge_extraction_prompt=PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template="You are a networked intelligence helping a human track knowledge triples about all relevant people, things, concepts, etc. and integrating them with your knowledge stored within your weights as well as that stored in a knowledge graph. Extract all of the knowledge triples from the last line of conversation. A knowledge triple is a clause that contains a subject, a predicate, and an object. The subject is the entity being described, the predicate is the property of the subject that is being described, and the object is the value of the property.\n\nEXAMPLE\nConversation history:\nPerson #1: Did you hear aliens landed in Area 51?\nAI: No, I didn't hear that. What do you know about Area 51?\nPerson #1: It's a secret military base in Nevada.\nAI: What do you know about Nevada?\nLast line of conversation:\nPerson #1: It's a state in the US. It's also the number 1 producer of gold in the US.\n\nOutput: (Nevada, is a, state)<|>(Nevada, is in, US)<|>(Nevada, is the number 1 producer of, gold)\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: Hello.\nAI: Hi! How are you?\nPerson #1: I'm good. How are you?\nAI: I'm good too.\nLast line of conversation:\nPerson #1: I'm going to the store.\n\nOutput: NONE\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: What do you know about Descartes?\nAI: Descartes was a French philosopher, mathematician, and scientist who lived in the 17th century.\nPerson #1: The Descartes I'm referring to is a standup comedian and interior designer from Montreal.\nAI: Oh yes, He is a comedian and an interior designer. He has been in the industry for 30 years. His favorite food is baked bean pie.\nLast line of conversation:\nPerson #1: Oh huh. I know Descartes likes to drive antique scooters and play the mandolin.\nOutput: (Descartes, likes to drive, antique scooters)<|>(Descartes, plays, mandolin)\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:", template_format='f-string', validate_template=True), entity_extraction_prompt=PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I\'m working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:', template_format='f-string', validate_template=True), llm, summary_message_cls=<class 'langchain.schema.SystemMessage'>, memory_key='history')[source]
Bases: langchain.memory.chat_memory.BaseChatMemory
Knowledge graph memory for storing conversation memory.
Integrates with external knowledge graph to store and retrieve
information about knowledge triples in the conversation.
Parameters
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
k (int) – 
human_prefix (str) – 
ai_prefix (str) – 
kg (langchain.graphs.networkx_graph.NetworkxEntityGraph) – 
knowledge_extraction_prompt (langchain.prompts.base.BasePromptTemplate) – 
entity_extraction_prompt (langchain.prompts.base.BasePromptTemplate) – 
llm (langchain.base_language.BaseLanguageModel) – 
summary_message_cls (Type[langchain.schema.BaseMessage]) – 
memory_key (str) – 
Return type
None
attribute ai_prefix: str = 'AI'
attribute entity_extraction_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I\'m working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:', template_format='f-string', validate_template=True)
attribute human_prefix: str = 'Human'
attribute k: int = 2
attribute kg: langchain.graphs.networkx_graph.NetworkxEntityGraph [Optional]
attribute knowledge_extraction_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template="You are a networked intelligence helping a human track knowledge triples about all relevant people, things, concepts, etc. and integrating them with your knowledge stored within your weights as well as that stored in a knowledge graph. Extract all of the knowledge triples from the last line of conversation. A knowledge triple is a clause that contains a subject, a predicate, and an object. The subject is the entity being described, the predicate is the property of the subject that is being described, and the object is the value of the property.\n\nEXAMPLE\nConversation history:\nPerson #1: Did you hear aliens landed in Area 51?\nAI: No, I didn't hear that. What do you know about Area 51?\nPerson #1: It's a secret military base in Nevada.\nAI: What do you know about Nevada?\nLast line of conversation:\nPerson #1: It's a state in the US. It's also the number 1 producer of gold in the US.\n\nOutput: (Nevada, is a, state)<|>(Nevada, is in, US)<|>(Nevada, is the number 1 producer of, gold)\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: Hello.\nAI: Hi! How are you?\nPerson #1: I'm good. How are you?\nAI: I'm good too.\nLast line of conversation:\nPerson #1: I'm going to the store.\n\nOutput: NONE\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: What do you know about Descartes?\nAI: Descartes was a French philosopher, mathematician, and scientist who lived in the 17th century.\nPerson #1: The Descartes I'm referring to is a standup comedian and interior designer from Montreal.\nAI: Oh yes, He is a comedian and an interior designer. He has been in the industry for 30 years. His favorite food is baked bean pie.\nLast line of conversation:\nPerson #1: Oh huh. I know Descartes likes to drive antique scooters and play the mandolin.\nOutput: (Descartes, likes to drive, antique scooters)<|>(Descartes, plays, mandolin)\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:", template_format='f-string', validate_template=True)
attribute llm: langchain.base_language.BaseLanguageModel [Required]
attribute summary_message_cls: Type[langchain.schema.BaseMessage] = <class 'langchain.schema.SystemMessage'>
Number of previous utterances to include in the context.
clear()[source]
Clear memory contents.
Return type
None
get_current_entities(input_string)[source]
Parameters
input_string (str) – 
Return type
List[str]
get_knowledge_triplets(input_string)[source]
Parameters
input_string (str) – 
Return type
List[langchain.graphs.networkx_graph.KnowledgeTriple]
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Any]
save_context(inputs, outputs)[source]
Save context from this conversation to buffer.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
class langchain.memory.ConversationStringBufferMemory(*, human_prefix='Human', ai_prefix='AI', buffer='', output_key=None, input_key=None, memory_key='history')[source]
Bases: langchain.schema.BaseMemory
Buffer for storing conversation memory.
Parameters
human_prefix (str) – 
ai_prefix (str) – 
buffer (str) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
memory_key (str) – 
Return type
None
attribute ai_prefix: str = 'AI'
Prefix to use for AI generated responses.
attribute buffer: str = ''
attribute human_prefix: str = 'Human'
attribute input_key: Optional[str] = None
attribute output_key: Optional[str] = None
clear()[source]
Clear memory contents.
Return type
None
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, str]
save_context(inputs, outputs)[source]
Save context from this conversation to buffer.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property memory_variables: List[str]
Will always return list of memory variables.
:meta private:
class langchain.memory.ConversationSummaryBufferMemory(*, human_prefix='Human', ai_prefix='AI', llm, prompt=PromptTemplate(input_variables=['summary', 'new_lines'], output_parser=None, partial_variables={}, template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n\nEXAMPLE\nCurrent summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n\nNew lines of conversation:\nHuman: Why do you think artificial intelligence is a force for good?\nAI: Because artificial intelligence will help humans reach their full potential.\n\nNew summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\nEND OF EXAMPLE\n\nCurrent summary:\n{summary}\n\nNew lines of conversation:\n{new_lines}\n\nNew summary:', template_format='f-string', validate_template=True), summary_message_cls=<class 'langchain.schema.SystemMessage'>, chat_memory=None, output_key=None, input_key=None, return_messages=False, max_token_limit=2000, moving_summary_buffer='', memory_key='history')[source]
Bases: langchain.memory.chat_memory.BaseChatMemory, langchain.memory.summary.SummarizerMixin
Buffer with summarizer for storing conversation memory.
Parameters
human_prefix (str) – 
ai_prefix (str) – 
llm (langchain.base_language.BaseLanguageModel) – 
prompt (langchain.prompts.base.BasePromptTemplate) – 
summary_message_cls (Type[langchain.schema.BaseMessage]) – 
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
max_token_limit (int) – 
moving_summary_buffer (str) – 
memory_key (str) – 
Return type
None
attribute max_token_limit: int = 2000
attribute memory_key: str = 'history'
attribute moving_summary_buffer: str = ''
clear()[source]
Clear memory contents.
Return type
None
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Any]
prune()[source]
Prune buffer if it exceeds max token limit
Return type
None
save_context(inputs, outputs)[source]
Save context from this conversation to buffer.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property buffer: List[langchain.schema.BaseMessage]
class langchain.memory.ConversationSummaryMemory(*, human_prefix='Human', ai_prefix='AI', llm, prompt=PromptTemplate(input_variables=['summary', 'new_lines'], output_parser=None, partial_variables={}, template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n\nEXAMPLE\nCurrent summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n\nNew lines of conversation:\nHuman: Why do you think artificial intelligence is a force for good?\nAI: Because artificial intelligence will help humans reach their full potential.\n\nNew summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\nEND OF EXAMPLE\n\nCurrent summary:\n{summary}\n\nNew lines of conversation:\n{new_lines}\n\nNew summary:', template_format='f-string', validate_template=True), summary_message_cls=<class 'langchain.schema.SystemMessage'>, chat_memory=None, output_key=None, input_key=None, return_messages=False, buffer='', memory_key='history')[source]
Bases: langchain.memory.chat_memory.BaseChatMemory, langchain.memory.summary.SummarizerMixin
Conversation summarizer to memory.
Parameters
human_prefix (str) – 
ai_prefix (str) – 
llm (langchain.base_language.BaseLanguageModel) – 
prompt (langchain.prompts.base.BasePromptTemplate) – 
summary_message_cls (Type[langchain.schema.BaseMessage]) – 
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
buffer (str) – 
memory_key (str) – 
Return type
None
attribute buffer: str = ''
clear()[source]
Clear memory contents.
Return type
None
classmethod from_messages(llm, chat_memory, *, summarize_step=2, **kwargs)[source]
Parameters
llm (langchain.base_language.BaseLanguageModel) – 
chat_memory (langchain.schema.BaseChatMessageHistory) – 
summarize_step (int) – 
kwargs (Any) – 
Return type
langchain.memory.summary.ConversationSummaryMemory
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Any]
save_context(inputs, outputs)[source]
Save context from this conversation to buffer.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
class langchain.memory.ConversationTokenBufferMemory(*, chat_memory=None, output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', llm, memory_key='history', max_token_limit=2000)[source]
Bases: langchain.memory.chat_memory.BaseChatMemory
Buffer for storing conversation memory.
Parameters
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
human_prefix (str) – 
ai_prefix (str) – 
llm (langchain.base_language.BaseLanguageModel) – 
memory_key (str) – 
max_token_limit (int) – 
Return type
None
attribute ai_prefix: str = 'AI'
attribute human_prefix: str = 'Human'
attribute llm: langchain.base_language.BaseLanguageModel [Required]
attribute max_token_limit: int = 2000
attribute memory_key: str = 'history'
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Any]
save_context(inputs, outputs)[source]
Save context from this conversation to buffer. Pruned.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property buffer: List[langchain.schema.BaseMessage]
String buffer of memory.
class langchain.memory.CosmosDBChatMessageHistory(cosmos_endpoint, cosmos_database, cosmos_container, session_id, user_id, credential=None, connection_string=None, ttl=None, cosmos_client_kwargs=None)[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat history backed by Azure CosmosDB.
Parameters
cosmos_endpoint (str) – 
cosmos_database (str) – 
cosmos_container (str) – 
session_id (str) – 
user_id (str) – 
credential (Any) – 
connection_string (Optional[str]) – 
ttl (Optional[int]) – 
cosmos_client_kwargs (Optional[dict]) – 
prepare_cosmos()[source]
Prepare the CosmosDB client.
Use this function or the context manager to make sure your database is ready.
Return type
None
load_messages()[source]
Retrieve the messages from Cosmos
Return type
None
add_message(message)[source]
Add a self-created message to the store
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
upsert_messages()[source]
Update the cosmosdb item.
Return type
None
clear()[source]
Clear session memory from this memory and cosmos.
Return type
None
class langchain.memory.DynamoDBChatMessageHistory(table_name, session_id, endpoint_url=None)[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history that stores history in AWS DynamoDB.
This class expects that a DynamoDB table with name table_name
and a partition Key of SessionId is present.
Parameters
table_name (str) – name of the DynamoDB table
session_id (str) – arbitrary key that is used to store the messages
of a single chat session.
endpoint_url (Optional[str]) – URL of the AWS endpoint to connect to. This argument
is optional and useful for test purposes, like using Localstack.
If you plan to use AWS cloud service, you normally don’t have to
worry about setting the endpoint_url.
property messages: List[langchain.schema.BaseMessage]
Retrieve the messages from DynamoDB
add_message(message)[source]
Append the message to the record in DynamoDB
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Clear session memory from DynamoDB
Return type
None
class langchain.memory.FileChatMessageHistory(file_path)[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history that stores history in a local file.
Parameters
file_path (str) – path of the local file to store the messages.
property messages: List[langchain.schema.BaseMessage]
Retrieve the messages from the local file
add_message(message)[source]
Append the message to the record in the local file
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Clear session memory from the local file
Return type
None
class langchain.memory.InMemoryEntityStore(*, store={})[source]
Bases: langchain.memory.entity.BaseEntityStore
Basic in-memory entity store.
Parameters
store (Dict[str, Optional[str]]) – 
Return type
None
attribute store: Dict[str, Optional[str]] = {}
clear()[source]
Delete all entities from store.
Return type
None
delete(key)[source]
Delete entity value from store.
Parameters
key (str) – 
Return type
None
exists(key)[source]
Check if entity exists in store.
Parameters
key (str) – 
Return type
bool
get(key, default=None)[source]
Get entity value from store.
Parameters
key (str) – 
default (Optional[str]) – 
Return type
Optional[str]
set(key, value)[source]
Set entity value in store.
Parameters
key (str) – 
value (Optional[str]) – 
Return type
None
class langchain.memory.MomentoChatMessageHistory(session_id, cache_client, cache_name, *, key_prefix='message_store:', ttl=None, ensure_cache_exists=True)[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history cache that uses Momento as a backend.
See https://gomomento.com/
Parameters
session_id (str) – 
cache_client (momento.CacheClient) – 
cache_name (str) – 
key_prefix (str) – 
ttl (Optional[timedelta]) – 
ensure_cache_exists (bool) – 
classmethod from_client_params(session_id, cache_name, ttl, *, configuration=None, auth_token=None, **kwargs)[source]
Construct cache from CacheClient parameters.
Parameters
session_id (str) – 
cache_name (str) – 
ttl (timedelta) – 
configuration (Optional[momento.config.Configuration]) – 
auth_token (Optional[str]) – 
kwargs (Any) – 
Return type
MomentoChatMessageHistory
property messages: list[langchain.schema.BaseMessage]
Retrieve the messages from Momento.
Raises
SdkException – Momento service or network error
Exception – Unexpected response
Returns
List of cached messages
Return type
list[BaseMessage]
add_message(message)[source]
Store a message in the cache.
Parameters
message (BaseMessage) – The message object to store.
Raises
SdkException – Momento service or network error.
Exception – Unexpected response.
Return type
None
clear()[source]
Remove the session’s messages from the cache.
Raises
SdkException – Momento service or network error.
Exception – Unexpected response.
Return type
None
class langchain.memory.MongoDBChatMessageHistory(connection_string, session_id, database_name='chat_history', collection_name='message_store')[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history that stores history in MongoDB.
Parameters
connection_string (str) – connection string to connect to MongoDB
session_id (str) – arbitrary key that is used to store the messages
of a single chat session.
database_name (str) – name of the database to use
collection_name (str) – name of the collection to use
property messages: List[langchain.schema.BaseMessage]
Retrieve the messages from MongoDB
add_message(message)[source]
Append the message to the record in MongoDB
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Clear session memory from MongoDB
Return type
None
class langchain.memory.MotorheadMemory(*, chat_memory=None, output_key=None, input_key=None, return_messages=False, url='https://api.getmetal.io/v1/motorhead', session_id, context=None, api_key=None, client_id=None, timeout=3000, memory_key='history')[source]
Bases: langchain.memory.chat_memory.BaseChatMemory
Parameters
chat_memory (langchain.schema.BaseChatMessageHistory) – 
output_key (Optional[str]) – 
input_key (Optional[str]) – 
return_messages (bool) – 
url (str) – 
session_id (str) – 
context (Optional[str]) – 
api_key (Optional[str]) – 
client_id (Optional[str]) – 
timeout (int) – 
memory_key (str) – 
Return type
None
attribute api_key: Optional[str] = None
attribute client_id: Optional[str] = None
attribute context: Optional[str] = None
attribute session_id: str [Required]
attribute url: str = 'https://api.getmetal.io/v1/motorhead'
delete_session()[source]
Delete a session
Return type
None
async init()[source]
Return type
None
load_memory_variables(values)[source]
Return key-value pairs given the text input to the chain.
If None, return all memories
Parameters
values (Dict[str, Any]) – 
Return type
Dict[str, Any]
save_context(inputs, outputs)[source]
Save context from this conversation to buffer.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property memory_variables: List[str]
Input keys this memory class will load dynamically.
class langchain.memory.PostgresChatMessageHistory(session_id, connection_string='postgresql://postgres:mypassword@localhost/chat_history', table_name='message_store')[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history stored in a Postgres database.
Parameters
session_id (str) – 
connection_string (str) – 
table_name (str) – 
property messages: List[langchain.schema.BaseMessage]
Retrieve the messages from PostgreSQL
add_message(message)[source]
Append the message to the record in PostgreSQL
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Clear session memory from PostgreSQL
Return type
None
class langchain.memory.ReadOnlySharedMemory(*, memory)[source]
Bases: langchain.schema.BaseMemory
A memory wrapper that is read-only and cannot be changed.
Parameters
memory (langchain.schema.BaseMemory) – 
Return type
None
attribute memory: langchain.schema.BaseMemory [Required]
clear()[source]
Nothing to clear, got a memory like a vault.
Return type
None
load_memory_variables(inputs)[source]
Load memory variables from memory.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, str]
save_context(inputs, outputs)[source]
Nothing should be saved or changed
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property memory_variables: List[str]
Return memory variables.
class langchain.memory.RedisChatMessageHistory(session_id, url='redis://localhost:6379/0', key_prefix='message_store:', ttl=None)[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history stored in a Redis database.
Parameters
session_id (str) – 
url (str) – 
key_prefix (str) – 
ttl (Optional[int]) – 
property key: str
Construct the record key to use
property messages: List[langchain.schema.BaseMessage]
Retrieve the messages from Redis
add_message(message)[source]
Append the message to the record in Redis
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Clear session memory from Redis
Return type
None
class langchain.memory.RedisEntityStore(session_id='default', url='redis://localhost:6379/0', key_prefix='memory_store', ttl=86400, recall_ttl=259200, *args, redis_client=None)[source]
Bases: langchain.memory.entity.BaseEntityStore
Redis-backed Entity store. Entities get a TTL of 1 day by default, and
that TTL is extended by 3 days every time the entity is read back.
Parameters
session_id (str) – 
url (str) – 
key_prefix (str) – 
ttl (Optional[int]) – 
recall_ttl (Optional[int]) – 
args (Any) – 
redis_client (Any) – 
Return type
None
attribute key_prefix: str = 'memory_store'
attribute recall_ttl: Optional[int] = 259200
attribute redis_client: Any = None
attribute session_id: str = 'default'
attribute ttl: Optional[int] = 86400
clear()[source]
Delete all entities from store.
Return type
None
delete(key)[source]
Delete entity value from store.
Parameters
key (str) – 
Return type
None
exists(key)[source]
Check if entity exists in store.
Parameters
key (str) – 
Return type
bool
get(key, default=None)[source]
Get entity value from store.
Parameters
key (str) – 
default (Optional[str]) – 
Return type
Optional[str]
set(key, value)[source]
Set entity value in store.
Parameters
key (str) – 
value (Optional[str]) – 
Return type
None
property full_key_prefix: str
class langchain.memory.SQLChatMessageHistory(session_id, connection_string, table_name='message_store')[source]
Bases: langchain.schema.BaseChatMessageHistory
Chat message history stored in an SQL database.
Parameters
session_id (str) – 
connection_string (str) – 
table_name (str) – 
property messages: List[langchain.schema.BaseMessage]
Retrieve all messages from db
add_message(message)[source]
Append the message to the record in db
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
clear()[source]
Clear session memory from db
Return type
None
class langchain.memory.SQLiteEntityStore(session_id='default', db_file='entities.db', table_name='memory_store', *args)[source]
Bases: langchain.memory.entity.BaseEntityStore
SQLite-backed Entity store
Parameters
session_id (str) – 
db_file (str) – 
table_name (str) – 
args (Any) – 
Return type
None
attribute session_id: str = 'default'
attribute table_name: str = 'memory_store'
clear()[source]
Delete all entities from store.
Return type
None
delete(key)[source]
Delete entity value from store.
Parameters
key (str) – 
Return type
None
exists(key)[source]
Check if entity exists in store.
Parameters
key (str) – 
Return type
bool
get(key, default=None)[source]
Get entity value from store.
Parameters
key (str) – 
default (Optional[str]) – 
Return type
Optional[str]
set(key, value)[source]
Set entity value in store.
Parameters
key (str) – 
value (Optional[str]) – 
Return type
None
property full_table_name: str
class langchain.memory.SimpleMemory(*, memories={})[source]
Bases: langchain.schema.BaseMemory
Simple memory for storing context or other bits of information that shouldn’t
ever change between prompts.
Parameters
memories (Dict[str, Any]) – 
Return type
None
attribute memories: Dict[str, Any] = {}
clear()[source]
Nothing to clear, got a memory like a vault.
Return type
None
load_memory_variables(inputs)[source]
Return key-value pairs given the text input to the chain.
If None, return all memories
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, str]
save_context(inputs, outputs)[source]
Nothing should be saved or changed, my memory is set in stone.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property memory_variables: List[str]
Input keys this memory class will load dynamically.
class langchain.memory.VectorStoreRetrieverMemory(*, retriever, memory_key='history', input_key=None, return_docs=False)[source]
Bases: langchain.schema.BaseMemory
Class for a VectorStore-backed memory object.
Parameters
retriever (langchain.vectorstores.base.VectorStoreRetriever) – 
memory_key (str) – 
input_key (Optional[str]) – 
return_docs (bool) – 
Return type
None
attribute input_key: Optional[str] = None
Key name to index the inputs to load_memory_variables.
attribute memory_key: str = 'history'
Key name to locate the memories in the result of load_memory_variables.
attribute retriever: langchain.vectorstores.base.VectorStoreRetriever [Required]
VectorStoreRetriever object to connect to.
attribute return_docs: bool = False
Whether or not to return the result of querying the database directly.
clear()[source]
Nothing to clear.
Return type
None
load_memory_variables(inputs)[source]
Return history buffer.
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Union[List[langchain.schema.Document], str]]
save_context(inputs, outputs)[source]
Save context from this conversation to buffer.
Parameters
inputs (Dict[str, Any]) – 
outputs (Dict[str, str]) – 
Return type
None
property memory_variables: List[str]
The list of keys emitted from the load_memory_variables method.
class langchain.memory.ZepChatMessageHistory(session_id, url='http://localhost:8000')[source]
Bases: langchain.schema.BaseChatMessageHistory
A ChatMessageHistory implementation that uses Zep as a backend.
Recommended usage:
# Set up Zep Chat History
zep_chat_history = ZepChatMessageHistory(
    session_id=session_id,
    url=ZEP_API_URL,
)
# Use a standard ConversationBufferMemory to encapsulate the Zep chat history
memory = ConversationBufferMemory(
    memory_key="chat_history", chat_memory=zep_chat_history
)
Zep provides long-term conversation storage for LLM apps. The server stores,
summarizes, embeds, indexes, and enriches conversational AI chat
histories, and exposes them via simple, low-latency APIs.
For server installation instructions and more, see: https://getzep.github.io/
This class is a thin wrapper around the zep-python package. Additional
Zep functionality is exposed via the zep_summary and zep_messages
properties.
For more information on the zep-python package, see:
https://github.com/getzep/zep-python
Parameters
session_id (str) – 
url (str) – 
Return type
None
property messages: List[langchain.schema.BaseMessage]
Retrieve messages from Zep memory
property zep_messages: List[Message]
Retrieve summary from Zep memory
property zep_summary: Optional[str]
Retrieve summary from Zep memory
add_message(message)[source]
Append the message to the Zep memory history
Parameters
message (langchain.schema.BaseMessage) – 
Return type
None
search(query, metadata=None, limit=None)[source]
Search Zep memory for messages matching the query
Parameters
query (str) – 
metadata (Optional[Dict]) – 
limit (Optional[int]) – 
Return type
List[MemorySearchResult]
clear()[source]
Clear session memory from Zep. Note that Zep is long-term storage for memory
and this is not advised unless you have specific data retention requirements.
Return type
None