id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
17ff82e7ee07-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 |
17ff82e7ee07-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 |
17ff82e7ee07-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 |
25fea8286d72-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 |
25fea8286d72-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 |
25fea8286d72-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 |
38a3122fa690-0 | .ipynb
.pdf
Zep Memory
Contents
REACT Agent Chat Message History Example
Initialize the Zep Chat Message History Class and initialize the Agent
Add some history data
Run the agent
Inspect the Zep memory
Vector search over the Zep memory
Zep Memory#
REACT Agent Chat Message History Example#
This notebook demonstrates ... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-1 | session_id = str(uuid4()) # This is a unique identifier for the user
# Load your OpenAI key from a .env file
from dotenv import load_dotenv
load_dotenv()
True
Initialize the Zep Chat Message History Class and initialize the Agent#
ddg = DuckDuckGoSearchRun()
tools = [ddg]
# Set up Zep Chat History
zep_chat_history = Z... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-2 | "The most well-known adaptation of Octavia Butler's work is the FX series"
" Kindred, based on her novel of the same name."
),
},
{"role": "human", "content": "Who were her contemporaries?"},
{
"role": "ai",
"content": (
"Octavia Butler's contemporaries includ... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-3 | ),
},
]
for msg in test_history:
zep_chat_history.append(
HumanMessage(content=msg["content"])
if msg["role"] == "human"
else AIMessage(content=msg["content"])
)
Run the agent#
Doing so will automatically add the input and response to the Zep memory.
agent_chain.run(
input="WWhat... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-4 | Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ.
{'role': 'human', 'content': 'What awards did she win?', 'uuid': '9fa75c3c-edae-41e3-b9bc-9fcf16b523c9', 'created_at': '2023-05-25T15:09:41.91662Z', 'token_count': 8}
{'role': 'ai', 'content': 'Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur F... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-5 | {'role': 'human', 'content': "Write a short synopsis of Butler's book, Parable of the Sower. What is it about?", 'uuid': '5678d056-7f05-4e70-b8e5-f85efa56db01', 'created_at': '2023-05-25T15:09:41.938974Z', 'token_count': 23}
{'role': 'ai', 'content': 'Parable of the Sower is a science fiction novel by Octavia Butler, p... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-6 | {'role': 'ai', 'content': 'Parable of the Sower is a prescient novel that speaks to the challenges facing contemporary society, such as climate change, economic inequality, and the rise of authoritarianism. It is a cautionary tale that warns of the dangers of ignoring these issues and the importance of taking action to... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-7 | {'uuid': '52cfe3e8-b800-4dd8-a7dd-8e9e4764dfc8', 'created_at': '2023-05-25T15:09:41.913856Z', 'role': 'ai', 'content': "Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ.", 'token_count': 27} 0.852352466457884
{'uuid': 'd40da612-0867-4a43-92ec-778b86490a39', 'created_at': '20... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-8 | {'uuid': '862107de-8f6f-43c0-91fa-4441f01b2b3a', 'created_at': '2023-05-25T15:09:41.898149Z', 'role': 'human', 'content': 'Which books of hers were made into movies?', 'token_count': 11} 0.7954322970428519
{'uuid': '97164506-90fe-4c71-9539-69ebcd1d90a2', 'created_at': '2023-05-25T15:09:41.90887Z', 'role': 'human', 'con... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
38a3122fa690-9 | previous
Redis Chat Message History
next
Indexes
Contents
REACT Agent Chat Message History Example
Initialize the Zep Chat Message History Class and initialize the Agent
Add some history data
Run the agent
Inspect the Zep memory
Vector search over the Zep memory
By Harrison Chase
© Copyright 2023, Harris... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
66f3a688f713-0 | .ipynb
.pdf
Momento
Momento#
This notebook goes over how to use Momento Cache to store chat message history using the MomentoChatMessageHistory class. See the Momento docs for more detail on how to get set up with Momento.
Note that, by default we will create a cache if one with the given name doesn’t already exist.
Yo... | https://python.langchain.com/en/latest/modules/memory/examples/momento_chat_message_history.html |
651f71c4899a-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 |
58719f90cede-0 | .ipynb
.pdf
Mongodb Chat Message History
Mongodb Chat Message History#
This notebook goes over how to use Mongodb to store chat message history.
MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas... | https://python.langchain.com/en/latest/modules/memory/examples/mongodb_chat_message_history.html |
5d98474001c2-0 | .ipynb
.pdf
Cassandra Chat Message History
Cassandra Chat Message History#
This notebook goes over how to use Cassandra to store chat message history.
Cassandra is a distributed database that is well suited for storing large amounts of data.
It is a good choice for storing chat message history because it is easy to sca... | https://python.langchain.com/en/latest/modules/memory/examples/cassandra_chat_message_history.html |
264c991579be-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 input. In this notebook, we go over how to add memory to a chain that has multiple inputs. As an example of such a chain, we will add memory to a question/answering chain. This chain takes ... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
264c991579be-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 |
128076dac3d7-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 |
128076dac3d7-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 |
ef3ecd5964c4-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 |
ef3ecd5964c4-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 |
ef3ecd5964c4-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 |
ef3ecd5964c4-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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 |
5ddd85257e2e-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
Cassandra Chat Message History
By Harrison Chase
© Copyright 2023, Harri... | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html |
92f0f6401cd6-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 |
92f0f6401cd6-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 |
92f0f6401cd6-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 |
92f0f6401cd6-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 |
ec9edcd1b8bd-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 |
ec9edcd1b8bd-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 |
f832c02adc1a-0 | .ipynb
.pdf
Dynamodb Chat Message History
Contents
DynamoDBChatMessageHistory
Agent with DynamoDB Memory
Dynamodb Chat Message History#
This notebook goes over how to use Dynamodb to store chat message history.
First make sure you have correctly configured the AWS CLI. Then make sure you have installed boto3.
Next, c... | https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html |
f832c02adc1a-1 | from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.utilities import PythonREPL
from getpass import getpass
message_history = DynamoDBChatMessageHistory(table_name="SessionTable", session_id="1")
memory = ConversationBufferMemory(memory_key="chat_history", chat_memory=mes... | https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html |
f832c02adc1a-2 | }
Observation: X Corp. (2023–present)Twitter, Inc. (2006–2023)
Thought:{
"action": "Final Answer",
"action_input": "X Corp. (2023–present)Twitter, Inc. (2006–2023)"
}
> Finished chain.
'X Corp. (2023–present)Twitter, Inc. (2006–2023)'
agent_chain.run(input="My name is Bob.")
> Entering new AgentExecutor chain..... | https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
c4d154f5ff01-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 |
0437358c3336-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 |
0437358c3336-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 |
493d39cb4331-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 |
1479fa2c87db-0 | .ipynb
.pdf
Getting Started
Contents
Why do we need chains?
Quick start: Using LLMChain
Different ways of calling chains
Add memory to chains
Debug Chain
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 ... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
1479fa2c87db-1 | print(chain.run("colorful socks"))
Colorful Toes Co.
If there are multiple variables, you can input them all at once using a dictionary.
prompt = PromptTemplate(
input_variables=["company", "product"],
template="What is a good name for {company} that makes {product}?",
)
chain = LLMChain(llm=llm, prompt=prompt)... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
1479fa2c87db-2 | llm_chain(inputs={"adjective":"corny"})
{'adjective': 'corny',
'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
By default, __call__ returns both the input and output key values. You can configure it to only return output key values by setting return_only_outputs to True.
llm_chain("corny", r... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
1479fa2c87db-3 | from langchain.memory import ConversationBufferMemory
conversation = ConversationChain(
llm=chat,
memory=ConversationBufferMemory()
)
conversation.run("Answer briefly. What are the first 3 colors of a rainbow?")
# -> The first three colors of a rainbow are red, orange, and yellow.
conversation.run("And the next... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
1479fa2c87db-4 | Current conversation:
Human: What is ChatGPT?
AI:
> Finished chain.
'ChatGPT is an AI language model developed by OpenAI. It is based on the GPT-3 architecture and is capable of generating human-like responses to text prompts. ChatGPT has been trained on a massive amount of text data and can understand and respond to a... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
1479fa2c87db-5 | catchphrase = overall_chain.run("colorful socks")
print(catchphrase)
> Entering new SimpleSequentialChain chain...
Rainbow Socks Co.
"Put a little rainbow in your step!"
> Finished chain.
"Put a little rainbow in your step!"
Create a custom chain with the Chain class#
LangChain provides many chains out of the box, but ... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
1479fa2c87db-6 | prompt_1 = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
chain_1 = LLMChain(llm=llm, prompt=prompt_1)
prompt_2 = PromptTemplate(
input_variables=["product"],
template="What is a good slogan for a company that makes {product}?",
)
chain... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
eff499c00cca-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 |
ae0c88944b2b-0 | .ipynb
.pdf
Vector DB Text Generation
Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
Vector DB Text Generation#
This notebook walks through how to use LangChain for text generation over a vector index. This is useful if we want to generate text that is able to draw from a lar... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-1 | relative_path = markdown_file.relative_to(repo_path)
github_url = f"https://github.com/{repo_owner}/{repo_name}/blob/{git_sha}/{relative_path}"
yield Document(page_content=f.read(), metadata={"source": github_url})
sources = get_github_docs("yirenlu92", "deno-manual-forked")
source_chunk... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-2 | chain = LLMChain(llm=llm, prompt=PROMPT)
Generate Text#
Finally, we write a function to apply our inputs to the chain. The function takes an input parameter topic. We find the documents in the vector index that correspond to that topic, and use them as additional context in our simple LLM chain.
def generate_blog_post(... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-3 | [{'text': '\n\nEnvironment variables are a great way to store and access sensitive information in your Deno applications. Deno offers built-in support for environment variables with `Deno.env`, and you can also use a `.env` file to store and access environment variables.\n\nUsing `Deno.env` is simple. It has getter and... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-4 | into the code. This makes it easier to change settings without having to modify the code.\n\nIn Deno, environment variables can be set in a few different ways. The most common way is to use the `VAR=value` syntax. This will set the environment variable `VAR` to the value `value`. This can be used to set any number of e... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-5 | to hard-code it into their applications. In Deno, you can access environment variables using the `Deno.env.get()` function.\n\nFor example, if you wanted to access the `HOME` environment variable, you could do so like this:\n\n```js\n// env.js\nDeno.env.get("HOME");\n```\n\nWhen running this code, you\'ll need to grant... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-6 | variables are an important part of any programming language, and Deno is no exception. Deno is a secure JavaScript and TypeScript runtime built on the V8 JavaScript engine, and it recently added support for environment variables. This feature was added in Deno version 1.6.0, and it is now available for use in Deno appl... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-7 | example, if you wanted to set the `FOO` environment variable to `bar`, you would use the following code:\n\n```'}] | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
ae0c88944b2b-8 | previous
Retrieval Question Answering with Sources
next
API Chains
Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
3e670e7c3953-0 | .ipynb
.pdf
Summarization
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The refine Chain
Summarization#
This notebook walks through how to use LangChain for summarization over a list of documents. It covers three different chain types: stuff, map_reduce, and refine. For a more in depth explana... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-1 | chain.run(docs)
' In response to Russian aggression in Ukraine, the United States and its allies are taking action to hold Putin accountable, including economic sanctions, asset seizures, and military assistance. The US is also providing economic and humanitarian aid to Ukraine, and has passed the American Rescue Plan ... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-2 | chain.run(docs)
"\n\nIn questa serata, il Presidente degli Stati Uniti ha annunciato una serie di misure per affrontare la crisi in Ucraina, causata dall'aggressione di Putin. Ha anche annunciato l'invio di aiuti economici, militari e umanitari all'Ucraina. Ha anche annunciato che gli Stati Uniti e i loro alleati stann... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-3 | chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True)
chain({"input_documents": docs}, return_only_outputs=True)
{'map_steps': [" In response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sancti... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-4 | prompt_template = """Write a concise summary of the following:
{text}
CONCISE SUMMARY IN ITALIAN:"""
PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-5 | "\n\nStiamo unendo le nostre forze con quelle dei nostri alleati europei per sequestrare yacht, appartamenti di lusso e jet privati di Putin. Abbiamo chiuso lo spazio aereo americano ai voli russi e stiamo fornendo più di un miliardo di dollari in assistenza all'Ucraina. Abbiamo anche mobilitato le nostre forze terrest... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-6 | "\n\nIl Presidente Biden ha lottato per passare l'American Rescue Plan per aiutare le persone che soffrivano a causa della pandemia. Il piano ha fornito sollievo economico immediato a milioni di americani, ha aiutato a mettere cibo sulla loro tavola, a mantenere un tetto sopra le loro teste e a ridurre il costo dell'as... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-7 | The refine Chain#
This sections shows results of using the refine Chain to do summarization.
chain = load_summarize_chain(llm, chain_type="refine")
chain.run(docs)
"\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Put... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-8 | chain({"input_documents": docs}, return_only_outputs=True)
{'refine_steps': [" In response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-9 | "\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains. We are ... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-10 | 'output_text': "\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-11 | "------------\n"
"{text}\n"
"------------\n"
"Given the new context, refine the original summary in Italian"
"If the context isn't useful, return the original summary."
)
refine_prompt = PromptTemplate(
input_variables=["existing_answer", "text"],
template=refine_template,
)
chain = load_summari... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-12 | "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso ... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-13 | "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso ... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
3e670e7c3953-14 | 'output_text': "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagli... | https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html |
aaf4f9bef12e-0 | .ipynb
.pdf
Chat Over Documents with Chat History
Contents
Pass in chat history
Return Source Documents
ConversationalRetrievalChain with search_distance
ConversationalRetrievalChain with map_reduce
ConversationalRetrievalChain with Question Answering with sources
ConversationalRetrievalChain with streaming to stdout... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
aaf4f9bef12e-1 | Using embedded DuckDB without persistence: data will be transient
We can now create a memory object, which is neccessary to track the inputs/outputs and hold a conversation.
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
We now in... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
aaf4f9bef12e-2 | result = qa({"question": query, "chat_history": chat_history})
result["answer"]
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also ... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
aaf4f9bef12e-3 | result['source_documents'][0]
Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life ... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
aaf4f9bef12e-4 | from langchain.chains.question_answering import load_qa_chain
from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT
llm = OpenAI(temperature=0)
question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)
doc_chain = load_qa_chain(llm, chain_type="map_reduce")
chain = Convers... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
aaf4f9bef12e-5 | combine_docs_chain=doc_chain,
)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = chain({"question": query, "chat_history": chat_history})
result['answer']
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private ... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
aaf4f9bef12e-6 | chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from ... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
aaf4f9bef12e-7 | result = qa({"question": query, "chat_history": chat_history})
result['answer']
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also ... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.