id stringlengths 14 16 | text stringlengths 45 2.73k | source stringlengths 49 114 |
|---|---|---|
20444c3240ea-1 | prompt = PromptTemplate(
template="Answer the user query.\n{format_instructions}\n{query}\n",
input_variables=["query"],
partial_variables={"format_instructions": parser.get_format_instructions()}
)
_input = prompt.format_prompt(query=joke_query)
output = model(_input.to_string())
parser.parse(output)
Joke(... | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html |
c4ffd56654c2-0 | .ipynb
.pdf
CommaSeparatedListOutputParser
CommaSeparatedListOutputParser#
Here’s another parser strictly less powerful than Pydantic/JSON parsing.
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langch... | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/comma_separated.html |
849eeed8fa53-0 | .ipynb
.pdf
Structured Output Parser
Structured Output Parser#
While the Pydantic/JSON parser is more powerful, we initially experimented data structures having text fields only.
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain.prompts import PromptTemplate, ChatPromptTemplate,... | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html |
849eeed8fa53-1 | ],
input_variables=["question"],
partial_variables={"format_instructions": format_instructions}
)
_input = prompt.format_prompt(question="what's the capital of france")
output = chat_model(_input.to_messages())
output_parser.parse(output.content)
{'answer': 'Paris', 'source': 'https://en.wikipedia.org/wiki/Pari... | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html |
f16da179eeb8-0 | .ipynb
.pdf
LengthBased ExampleSelector
LengthBased ExampleSelector#
This ExampleSelector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while ... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
f16da179eeb8-1 | # it is provided as a default value if none is specified.
# get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x))
)
dynamic_prompt = FewShotPromptTemplate(
# We provide an ExampleSelector instead of examples.
example_selector=example_selector,
example_prompt=example_prompt,
pref... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
f16da179eeb8-2 | Input: sunny
Output: gloomy
Input: windy
Output: calm
Input: big
Output: small
Input: enthusiastic
Output:
previous
How to create a custom example selector
next
Maximal Marginal Relevance ExampleSelector
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
d6d546624dc7-0 | .ipynb
.pdf
Maximal Marginal Relevance ExampleSelector
Maximal Marginal Relevance ExampleSelector#
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddin... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html |
d6d546624dc7-1 | k=2
)
mmr_prompt = FewShotPromptTemplate(
# We provide an ExampleSelector instead of examples.
example_selector=example_selector,
example_prompt=example_prompt,
prefix="Give the antonym of every input",
suffix="Input: {adjective}\nOutput:",
input_variables=["adjective"],
)
# Input is a feeling,... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html |
5fe32a1c0cdb-0 | .ipynb
.pdf
NGram Overlap ExampleSelector
NGram Overlap ExampleSelector#
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive.
The selector allows for a th... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
5fe32a1c0cdb-1 | {"input": "Spot can run.", "output": "Spot puede correr."},
]
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Input: {input}\nOutput: {output}",
)
example_selector = NGramOverlapExampleSelector(
# These are the examples it has available to choose from.
examples=examples, ... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
5fe32a1c0cdb-2 | Output: Ver correr a Spot.
Input: My dog barks.
Output: Mi perro ladra.
Input: Spot can run fast.
Output:
# You can add examples to NGramOverlapExampleSelector as well.
new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."}
example_selector.add_example(new_example)
print(dynamic_prompt.format(se... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
5fe32a1c0cdb-3 | Input: Spot plays fetch.
Output: Spot juega a buscar.
Input: Spot can play fetch.
Output:
# Setting threshold greater than 1.0
example_selector.threshold=1.0+1e-9
print(dynamic_prompt.format(sentence="Spot can play fetch."))
Give the Spanish translation of every input
Input: Spot can play fetch.
Output:
previous
Maxima... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
cffc3f9b9e08-0 | .ipynb
.pdf
Similarity ExampleSelector
Similarity ExampleSelector#
The SemanticSimilarityExampleSelector selects examples based on which examples are most similar to the inputs. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs.
from langchain.prompts.exam... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html |
cffc3f9b9e08-1 | example_prompt=example_prompt,
prefix="Give the antonym of every input",
suffix="Input: {adjective}\nOutput:",
input_variables=["adjective"],
)
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
# Input is a feeling, so should select the happy/sad example
pr... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html |
a51ef4a9081a-0 | .md
.pdf
How to create a custom example selector
Contents
Implement custom example selector
Use custom example selector
How to create a custom example selector#
In this tutorial, we’ll create a custom example selector that selects every alternate example from a given list of examples.
An ExampleSelector must implemen... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html |
a51ef4a9081a-1 | # Add new example to the set of examples
example_selector.add_example({"foo": "4"})
example_selector.examples
# -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}]
# Select examples
example_selector.select_examples({"foo": "foo"})
# -> array([{'foo': '1'}, {'foo': '4'}], dtype=object)
previous
Example Selectors... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html |
74751a4d3c88-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... | https://python.langchain.com/en/latest/modules/memory/how_to_guides.html |
4bfadebce600-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... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
4bfadebce600-1 | history.messages
[HumanMessage(content='hi!', additional_kwargs={}),
AIMessage(content='whats up?', additional_kwargs={})]
ConversationBufferMemory#
We now show how to use this simple concept in a chain. We first showcase ConversationBufferMemory which is just a wrapper around ChatMessageHistory that extracts the mess... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
4bfadebce600-2 | Current conversation:
Human: Hi there!
AI:
> Finished chain.
" Hi there! It's nice to meet you. How can I help you today?"
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation betw... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
4bfadebce600-3 | Human: Tell me about yourself.
AI:
> Finished chain.
" Sure! I'm an AI created to help people with their everyday tasks. I'm programmed to understand natural language and provide helpful information. I'm also constantly learning and updating my knowledge base so I can provide more accurate and helpful answers."
Saving ... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
832c10a81ef8-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... | https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html |
832c10a81ef8-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:
... | https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html |
832c10a81ef8-2 | AI: Sounds like a productive day! What kind of documentation are you writing?
Human: For LangChain! Have you heard of it?
AI:
> Finished chain.
" 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 wr... | https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html |
66b795720ee1-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... | https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html |
66b795720ee1-1 | 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=ConversationSummaryBufferMemory(llm=OpenAI(), max_token_limit=40),
verbose=True
)
conversation_with_summary.predict(input="Hi, w... | https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html |
66b795720ee1-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:
... | https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html |
66b795720ee1-3 | AI:
> Finished chain.
' Oh, okay. What is LangChain?'
previous
ConversationSummaryMemory
next
ConversationTokenBufferMemory
Contents
Using in a chain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html |
893127a7bad9-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... | https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
893127a7bad9-1 | memory = VectorStoreRetrieverMemory(retriever=retriever)
# When added to an agent, the memory object can save pertinent information from conversations or used tools
memory.save_context({"input": "My favorite food is pizza"}, {"output": "thats good to know"})
memory.save_context({"input": "My favorite sport is soccer"},... | https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
893127a7bad9-2 | memory=memory,
verbose=True
)
conversation_with_summary.predict(input="Hi, my name is Perry, what's up?")
> 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.... | https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
893127a7bad9-3 | conversation_with_summary.predict(input="Whats my favorite food")
> 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 que... | https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
893127a7bad9-4 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
19724393fab9-0 | .ipynb
.pdf
ConversationSummaryMemory
Contents
Using in a chain
ConversationSummaryMemory#
Now let’s take a look at using a slightly more complex type of memory - ConversationSummaryMemory. This type of memory creates a summary of the conversation over time. This can be useful for condensing information from the conv... | https://python.langchain.com/en/latest/modules/memory/types/summary.html |
19724393fab9-1 | conversation_with_summary = ConversationChain(
llm=llm,
memory=ConversationSummaryMemory(llm=OpenAI()),
verbose=True
)
conversation_with_summary.predict(input="Hi, what's up?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an... | https://python.langchain.com/en/latest/modules/memory/types/summary.html |
19724393fab9-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:
... | https://python.langchain.com/en/latest/modules/memory/types/summary.html |
c1b54d367eed-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).... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-1 | AIMessage(content=' That sounds like a great project! What kind of project are they working on?', additional_kwargs={})],
'entities': {'Sam': 'Sam is working on a hackathon project with Deven.'}}
Using in a chain#
Let’s now use it in a chain!
from langchain.chains import ConversationChain
from langchain.memory import ... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-2 | Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.
Context:
{'Deven': 'Deven is wor... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-3 | 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 ... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-4 | You are an assistant to a human, powered by a large language model trained by OpenAI.
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 t... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-5 | AI: That sounds like a great project! What kind of project are they working on?
Human: They are trying to add more complex memory structures to Langchain
AI: That sounds like an interesting project! What kind of memory structures are they trying to add?
Last line:
Human: They are adding in a key-value store for entit... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-6 | 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... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-7 | {'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, including a key-value store for '
'e... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-8 | You are an assistant to a human, powered by a large language model trained by OpenAI.
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 t... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-9 | 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 conversation. They seem to be working hard on this project and have a great idea for how ... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-10 | '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 add more '
'complex memory structures to Langchain, including a key-value store '
'for entities mentioned so far in t... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-11 | 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... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
c1b54d367eed-12 | 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 hackathon project with Deven to add more complex memory structures to Langchain. They seem to have a great idea for how the key-value store can help.'
previous
Convers... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
67c868c5c5c0-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... | https://python.langchain.com/en/latest/modules/memory/types/buffer.html |
67c868c5c5c0-1 | Current conversation:
Human: Hi there!
AI:
> Finished chain.
" Hi there! It's nice to meet you. How can I help you today?"
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation betw... | https://python.langchain.com/en/latest/modules/memory/types/buffer.html |
67c868c5c5c0-2 | Human: Tell me about yourself.
AI:
> Finished chain.
" Sure! I'm an AI created to help people with their everyday tasks. I'm programmed to understand natural language and provide helpful information. I'm also constantly learning and updating my knowledge base so I can provide more accurate and helpful answers."
And tha... | https://python.langchain.com/en/latest/modules/memory/types/buffer.html |
d209daf9dcf0-0 | .ipynb
.pdf
Conversation Knowledge Graph Memory
Contents
Using in a chain
Conversation Knowledge Graph Memory#
This type of memory uses a knowledge graph to recreate memory.
Let’s first walk through how to use the utilities
from langchain.memory import ConversationKGMemory
from langchain.llms import OpenAI
llm = Open... | https://python.langchain.com/en/latest/modules/memory/types/kg.html |
d209daf9dcf0-1 | Let’s now use this in a chain!
llm = OpenAI(temperature=0)
from langchain.prompts.prompt import PromptTemplate
from langchain.chains import ConversationChain
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 ... | https://python.langchain.com/en/latest/modules/memory/types/kg.html |
d209daf9dcf0-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. The AI ONLY uses info... | https://python.langchain.com/en/latest/modules/memory/types/kg.html |
a3b151955d86-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 ... | https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html |
a3b151955d86-1 | memory=ConversationBufferWindowMemory(k=2),
verbose=True
)
conversation_with_summary.predict(input="Hi, what's up?")
> 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 ... | https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html |
a3b151955d86-2 | Current conversation:
Human: Hi, what's up?
AI: Hi there! I'm doing great. I'm currently helping a customer with a technical issue. How about you?
Human: What's their issues?
AI: The customer is having trouble connecting to their Wi-Fi network. I'm helping them troubleshoot the issue and get them connected.
Human: Is... | https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html |
7068818ce94e-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... | https://python.langchain.com/en/latest/modules/memory/examples/postgres_chat_message_history.html |
78df0db5b761-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... | https://python.langchain.com/en/latest/modules/memory/examples/redis_chat_message_history.html |
7a65031a9e33-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... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
7a65031a9e33-1 | Current conversation:
Human: Hi there!
AI: Hi there! It's nice to meet you. How can I help you today?
Human: What's the weather?
AI:
> Finished ConversationChain chain.
' The current weather is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the next few days is sunny with temperatures in ... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
7a65031a9e33-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:
... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
7a65031a9e33-3 | verbose=True,
memory=ConversationBufferMemory(human_prefix="Friend")
)
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 co... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
b484c0650999-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-1 | )
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=prompt)
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
agent_chain = AgentExecutor.from_agent... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-4 | Action: Search
Action Input: National Anthem of Canada
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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-8 | Action: Search
Action Input: national anthem of [country]
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 o... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
b484c0650999-9 | 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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html |
eeb656b58be7-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-1 | {chat_history}
Question: {input}
{agent_scratchpad}"""
prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_variables=["input", "chat_history", "agent_scratchpad"]
)
Now we can create the ChatMessageHistory backed by the database.
message_history = RedisChatMessageHistory(... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-4 | Action: Search
Action Input: National Anthem of Canada
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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-8 | Action: Search
Action Input: national anthem of [country]
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 o... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
eeb656b58be7-9 | 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... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
5eeb23b8c9f4-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... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html |
5eeb23b8c9f4-1 | 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!"
previous
VectorStore-Backed Memory
next
How to add memory to a Multi-Input Chain
By Harrison Chase
© Copyright 2023, Harrison Chase.... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html |
af7fd366180f-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... | https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html |
af7fd366180f-1 | Summary of conversation:
Current conversation:
Human: Hi!
AI:
> Finished chain.
' Hi there! How can I help you?'
conversation.run("Can you tell me a joke?")
> 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... | https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html |
f843e032d91b-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... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
f843e032d91b-1 | {context}
{chat_history}
Human: {human_input}
Chatbot:"""
prompt = PromptTemplate(
input_variables=["chat_history", "human_input", "context"],
template=template
)
memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input")
chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
7c208d5ef626-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... | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html |
7c208d5ef626-1 | 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 Bob, nice to meet you! How are you doing today?
Human: wh... | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html |
3fef3db89e5e-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 ... | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
3fef3db89e5e-1 | """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, in this case the entity key."""
# Get the input text and run through spacy
doc = nlp(inputs[lis... | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
3fef3db89e5e-2 | {entities}
Conversation:
Human: {input}
AI:"""
prompt = PromptTemplate(
input_variables=["entities", "input"], template=template
)
And now we put it all together!
llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, prompt=prompt, verbose=True, memory=SpacyEntityMemory())
In the first example, with... | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
3fef3db89e5e-3 | Relevant entity information:
Harrison likes machine learning
Conversation:
Human: What do you think Harrison's favorite subject in college was?
AI:
> Finished ConversationChain chain.
' From what I know about Harrison, I believe his favorite subject in college was machine learning. He has expressed a strong interest in... | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html |
27f31a10fd8b-0 | .rst
.pdf
How-To Guides
How-To Guides#
A chain is made up of links, which can be either primitives or other chains.
Primitives can be either prompts, models, arbitrary functions, or other chains.
The examples here are broken up into three sections:
Generic Functionality
Covers both generic chains (that are useful in a ... | https://python.langchain.com/en/latest/modules/chains/how_to_guides.html |
32a08caeb0fa-0 | .ipynb
.pdf
Getting Started
Contents
Why do we need chains?
Query an LLM with the LLMChain
Combine chains with the SequentialChain
Create a custom chain with the Chain class
Getting Started#
In this tutorial, we will learn about creating simple chains in LangChain. We will learn how to create a chain, add components ... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
32a08caeb0fa-1 | print(chain.run("colorful socks"))
Rainbow Socks Co.
You can use a chat model in an LLMChain as well:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
)
human_message_prompt = HumanMessagePromptTemplate(
prompt=PromptTempla... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.