id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
c3bbe19d8844-16 | Use an LLM to create an elaborate on debate topic
Define the speaker selection function
Main Loop
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
acce03792de7-0 | .ipynb
.pdf
Generative Agents in LangChain
Contents
Generative Agent Memory Components
Memory Lifecycle
Create a Generative Character
Pre-Interview with Character
Step through the day’s observations.
Interview after the day
Adding Multiple Characters
Pre-conversation interviews
Dialogue between Generative Agents
Let’... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-1 | Memories are retrieved using a weighted sum of salience, recency, and importance.
You can review the definitions of the GenerativeAgent and GenerativeAgentMemory in the reference documentation for the following imports, focusing on add_memory and summarize_related_memories methods.
from langchain.experimental.generativ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-2 | def create_new_memory_retriever():
"""Create a new vector store retriever unique to the agent."""
# Define your embedding model
embeddings_model = OpenAIEmbeddings()
# Initialize the vectorstore as empty
embedding_size = 1536
index = faiss.IndexFlatL2(embedding_size)
vectorstore = FAISS(embe... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-3 | "Tommie remembers his dog, Bruno, from when he was a kid",
"Tommie feels tired from driving so far",
"Tommie sees the new home",
"The new neighbors have a cat",
"The road is noisy at night",
"Tommie is hungry",
"Tommie tries to get some rest.",
]
for observation in tommie_observations:
tommi... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-4 | interview_agent(tommie, "What are you looking forward to doing today?")
'Tommie said "Well, today I\'m mostly focused on getting settled into my new home. But once that\'s taken care of, I\'m looking forward to exploring the neighborhood and finding some new design inspiration. What about you?"'
interview_agent(tommie,... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-5 | "Tommie leaves the job fair feeling disappointed.",
"Tommie stops by a local diner to grab some lunch.",
"The service is slow, and Tommie has to wait for 30 minutes to get his food.",
"Tommie overhears a conversation at the next table about a job opening.",
"Tommie asks the diners about the job opening ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-6 | print(colored(observation, "green"), reaction)
if ((i+1) % 20) == 0:
print('*'*40)
print(colored(f"After {i+1} observations, Tommie's summary is:\n{tommie.get_summary(force_refresh=True)}", "blue"))
print('*'*40)
Tommie wakes up to the sound of a noisy construction site outside his window. T... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-7 | The line to get in is long, and Tommie has to wait for an hour. Tommie sighs and looks around, feeling impatient and frustrated.
Tommie meets several potential employers at the job fair but doesn't receive any offers. Tommie Tommie's shoulders slump and he sighs, feeling discouraged.
Tommie leaves the job fair feeling ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-8 | Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Tommie is hopeful and proactive in his job search, but easily becomes discouraged when faced with setbacks. He enjoys spending time outdoors and interacting with animals. Tommie is also productive and enjoys updating his resume and cover letter. He ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-9 | interview_agent(tommie, "Tell me about how your day has been going")
'Tommie said "Well, it\'s been a bit of a mixed day. I\'ve had some setbacks in my job search, but I also had some fun playing frisbee and spending time outdoors. How about you?"'
interview_agent(tommie, "How do you feel about coffee?")
'Tommie said "... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-10 | eve_observations = [
"Eve overhears her colleague say something about a new client being hard to work with",
"Eve wakes up and hear's the alarm",
"Eve eats a boal of porridge",
"Eve helps a coworker on a task",
"Eve plays tennis with her friend Xu before going to work",
"Eve overhears her collea... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-11 | interview_agent(eve, "You'll have to ask him. He may be a bit anxious, so I'd appreciate it if you keep the conversation going and ask as many questions as possible.")
'Eve said "Sure, I can definitely ask him a lot of questions to keep the conversation going. Thanks for the heads up about his anxiety."'
Dialogue betwe... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-12 | Eve said "Sure, Tommie. I found that networking and reaching out to professionals in my field was really helpful. I also made sure to tailor my resume and cover letter to each job I applied to. Do you have any specific questions about those strategies?"
Tommie said "Thank you, Eve. That's really helpful advice. Did you... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-13 | Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Tommie is a hopeful and proactive individual who is searching for a job. He becomes discouraged when he doesn't receive any offers or positive responses, but he tries to stay productive and calm by updating his resume, going for walks, and talking t... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
acce03792de7-14 | interview_agent(eve, "What do you wish you would have said to Tommie?")
'Eve said "Well, I think I covered most of the topics Tommie was interested in, but if I had to add one thing, it would be to make sure to follow up with any connections you make during your job search. It\'s important to maintain those relationshi... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
eb2777aae758-0 | .ipynb
.pdf
CAMEL Role-Playing Autonomous Cooperative Agents
Contents
Import LangChain related modules
Define a CAMEL agent helper class
Setup OpenAI API key and roles and task for role-playing
Create a task specify agent for brainstorming and get the specified task
Create inception prompts for AI assistant and AI us... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-1 | Arxiv paper: https://arxiv.org/abs/2303.17760
Import LangChain related modules#
from typing import List
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import (
AIMessage,
HumanMessage,
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-2 | Create a task specify agent for brainstorming and get the specified task#
task_specifier_sys_msg = SystemMessage(content="You can make a task more specific.")
task_specifier_prompt = (
"""Here is a task that {assistant_role_name} will help {user_role_name} to complete: {task}.
Please make it more specific. Be creative ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-3 | I must give you one instruction at a time.
You must write a specific solution that appropriately completes the requested instruction.
You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.
Do not add anything else ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-4 | You should instruct me not ask me questions.
Now you must start to instruct me using the two ways described above.
Do not add anything else other than your instruction and the optional corresponding input!
Keep giving me instructions and necessary inputs until you think the task is completed.
When the task is completed... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-5 | "Now start to give me introductions one by one. "
"Only reply with Instruction and Input."))
user_msg = HumanMessage(content=f"{assistant_sys_msg.content}")
user_msg = assistant_agent.step(user_msg)
Start role-playing session to solve the task!#
print(f"Original task prompt:\n{task}\n")
print(f"Specifie... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-6 | pip install pandas numpy matplotlib ta-lib
```
Next request.
AI User (Stock Trader):
Instruction: Import the necessary libraries in the Python script.
Input: None
AI Assistant (Python Programmer):
Solution: We can import the necessary libraries in the Python script using the import statement. We need to import pandas, ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-7 | df = df.set_index('date')
df = df.sort_index(ascending=True)
```
This will set the date column as the index and sort the DataFrame in ascending order by date. Next request.
AI User (Stock Trader):
Instruction: Calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from t... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-8 | ```
new_df = pd.concat([df, short_ma, long_ma], axis=1)
new_df.columns = ['open', 'high', 'low', 'close', 'volume', 'short_ma', 'long_ma']
```
This will create a new DataFrame called `new_df` that combines the historical stock data with the short-term and long-term moving averages. The columns of the new DataFrame are ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-9 | Input: The stop loss and profit target as percentages.
AI Assistant (Python Programmer):
Solution: We can create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. We need to pass the stop loss and profit target a... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-10 | ```
This will create a new column called 'pnl' in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. The stop loss and profit target are calculated based on the stop_loss_percent and profit_target_percent variables, respectively.... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-11 | plt.plot(new_df.index, new_df['close'], label='Close')
plt.plot(new_df.index, new_df['short_ma'], label='Short MA')
plt.plot(new_df.index, new_df['long_ma'], label='Long MA')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Stock Data with Moving Averages')
plt.legend()
plt.show()
```
This will create a line chart tha... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-12 | AI User (Stock Trader):
Instruction: Print the total profit or loss for all trades.
Input: None.
AI Assistant (Python Programmer):
Solution: We can print the total profit or loss for all trades using the `print()` function. We can use the following code to print the total profit or loss:
```
print('Total Profit/Loss: {... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-13 | # Create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages
new_df['signal'] = np.where(new_df['short_ma'] > new_df['long_ma'], 1, -1)
# Create a new column in the DataFrame that indicates the profit or loss for each trade ba... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-14 | plt.plot(new_df.index, new_df['close'], label='Close')
plt.plot(new_df.index, new_df['short_ma'], label='Short MA')
plt.plot(new_df.index, new_df['long_ma'], label='Long MA')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Stock Data with Moving Averages')
plt.legend()
plt.show()
# Visualize the buy and sell signals ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
eb2777aae758-15 | Create a task specify agent for brainstorming and get the specified task
Create inception prompts for AI assistant and AI user for role-playing
Create a helper helper to get system messages for AI assistant and AI user from role names and the task
Create AI assistant agent and AI user agent from obtained system message... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
ee71bc677703-0 | .ipynb
.pdf
Multi-agent authoritarian speaker selection
Contents
Import LangChain related modules
DialogueAgent and DialogueSimulator classes
DirectorDialogueAgent class
Define participants and topic
Generate system messages
Use an LLM to create an elaborate on debate topic
Define the speaker selection function
Main ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-1 | self.reset()
def reset(self):
self.message_history = ["Here is the conversation so far."]
def send(self) -> str:
"""
Applies the chatmodel to the message history
and returns the message string
"""
message = self.model(
[
self.s... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-2 | # 3. everyone receives message
for receiver in self.agents:
receiver.receive(speaker.name, message)
# 4. increment time
self._step += 1
return speaker.name, message
DirectorDialogueAgent class#
The DirectorDialogueAgent is a privileged agent that chooses which of the other ag... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-3 | class IntegerOutputParser(RegexParser):
def get_format_instructions(self) -> str:
return 'Your response should be an integer delimited by angled brackets, like this: <int>.'
class DirectorDialogueAgent(DialogueAgent):
def __init__(
self,
name,
system_message: SystemMessage,
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-4 | {self.choice_parser.get_format_instructions()}
Do nothing else.
""")
# 3. have a prompt for prompting the next speaker to speak
self.prompt_next_speaker_prompt_template = PromptTemplate(
input_variables=["message_history", "next_speaker"],
template=f"""{{message_... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-5 | choice_prompt = self.choose_next_speaker_prompt_template.format(
message_history='\n'.join(self.message_history + [self.prefix] + [self.response]),
speaker_names=speaker_names
)
choice_string = self.model(
[
self.system_message,
HumanMe... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-6 | director_name = "Jon Stewart"
agent_summaries = OrderedDict({
"Jon Stewart": ("Host of the Daily Show", "New York"),
"Samantha Bee": ("Hollywood Correspondent", "Los Angeles"),
"Aasif Mandvi": ("CIA Correspondent", "Washington D.C."),
"Ronny Chieng": ("Average American Correspondent", "Cleveland, Ohio"... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-7 | Your description is as follows: {agent_description}
You are discussing the topic: {topic}.
Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location.
"""
def generate_agent_system_message(agent_name, agent_header):
return SystemMe... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-8 | print(f'\nSystem Message:\n{system_message.content}')
Jon Stewart Description:
Jon Stewart, the sharp-tongued and quick-witted host of the Daily Show, holding it down in the hustle and bustle of New York City. Ready to deliver the news with a comedic twist, while keeping it real in the city that never sleeps.
Header:
T... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-9 | - Aasif Mandvi: CIA Correspondent, located in Washington D.C.
- Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio.
Your name is Jon Stewart, your role is Host of the Daily Show, and you are located in New York.
Your description is as follows: Jon Stewart, the sharp-tongued and quick-witted host o... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-10 | The episode features
- Jon Stewart: Host of the Daily Show, located in New York
- Samantha Bee: Hollywood Correspondent, located in Los Angeles
- Aasif Mandvi: CIA Correspondent, located in Washington D.C.
- Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio.
Your name is Samantha Bee, your role ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-11 | You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze.
Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location.
You will speak in the style of Samantha Bee, and exagger... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-12 | Your description is as follows: Aasif Mandvi, the CIA Correspondent in the heart of Washington D.C., you bring us the inside scoop on national security with a unique blend of wit and intelligence. The nation's capital is lucky to have you, Aasif - keep those secrets safe!
You are discussing the topic: The New Workout T... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-13 | Do not say the same things over and over again.
Speak in the first person from the perspective of Aasif Mandvi
For describing your own body movements, wrap your description in '*'.
Do not change roles!
Do not speak from the perspective of anyone else.
Speak only from the perspective of Aasif Mandvi.
Stop speaking the m... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-14 | Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location.
System Message:
This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze.
The episo... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-15 | Never forget to keep your response to 50 words!
Do not add anything else.
Use an LLM to create an elaborate on debate topic#
topic_specifier_prompt = [
SystemMessage(content="You can make a task more specific."),
HumanMessage(content=
f"""{conversation_description}
Please elaborate... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-16 | """
# the director speaks on odd steps
if step % 2 == 1:
idx = 0
else:
# here the director chooses the next speaker
idx = director.select_next_speaker() + 1 # +1 because we excluded the director
return idx
Main Loop#
director = DirectorDialogueAgent(
name=director_name, ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-17 | Stop? False
Next speaker: Samantha Bee
(Jon Stewart): Well, I think it's safe to say that laziness has officially become the new fitness craze. I mean, who needs to break a sweat when you can just sit your way to victory? But in all seriousness, I think people are drawn to the idea of competition and the sense of acco... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-18 | (Ronny Chieng): Well, Jon, I gotta say, I'm not surprised that competitive sitting is taking off. I mean, have you seen the size of the chairs these days? They're practically begging us to sit in them all day. And as for exercise routines, let's just say I've never been one for the gym. But I can definitely see the app... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-19 | (Aasif Mandvi): Well Jon, as a CIA correspondent, I have to say that I'm always thinking about the potential threats to our nation's security. And while competitive sitting may seem harmless, there could be some unforeseen consequences. For example, what if our enemies start training their soldiers in the art of sittin... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-20 | (Ronny Chieng): Absolutely, Jon. We live in a world where everything is at our fingertips, and we expect things to be easy and convenient. So it's no surprise that people are drawn to a fitness trend that requires minimal effort and can be done from the comfort of their own homes. But I think it's important to remember... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
ee71bc677703-21 | (Samantha Bee): Oh, Jon, you know I love a good conspiracy theory. And let me tell you, I think there's something more sinister at play here. I mean, think about it - what if the government is behind this whole competitive sitting trend? They want us to be lazy and complacent so we don't question their actions. It's li... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
cd49a02b002d-0 | .rst
.pdf
Indexes
Contents
Go Deeper
Indexes#
Note
Conceptual Guide
Indexes refer to ways to structure documents so that LLMs can best interact with them.
This module contains utility functions for working with documents, different types of indexes, and then examples for using those indexes in chains.
The most common... | https://python.langchain.com/en/latest/modules/indexes.html |
cd49a02b002d-1 | previous
Zep Memory
next
Getting Started
Contents
Go Deeper
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/indexes.html |
12537e7f56c3-0 | .rst
.pdf
Prompts
Contents
Getting Started
Go Deeper
Prompts#
Note
Conceptual Guide
The new way of programming models is through prompts.
A “prompt” refers to the input to the model.
This input is rarely hard coded, but rather is often constructed from multiple components.
A PromptTemplate is responsible for the cons... | https://python.langchain.com/en/latest/modules/prompts.html |
52776ac625a9-0 | .rst
.pdf
Chains
Chains#
Note
Conceptual Guide
Using an LLM in isolation is fine for some simple applications,
but many more complex ones require chaining LLMs - either with each other or with other experts.
LangChain provides a standard interface for Chains, as well as some common implementations of chains for ease of... | https://python.langchain.com/en/latest/modules/chains.html |
9d9a77cb02c7-0 | .rst
.pdf
Agents
Contents
Action Agents
Plan-and-Execute Agents
Agents#
Note
Conceptual Guide
Some applications will require not just a predetermined chain of calls to LLMs/other tools,
but potentially an unknown chain that depends on the user’s input.
In these types of chains, there is a “agent” which has access to ... | https://python.langchain.com/en/latest/modules/agents.html |
9d9a77cb02c7-1 | The different abstractions involved in agents are as follows:
Agent: this is where the logic of the application lives. Agents expose an interface that takes in user input along with a list of previous steps the agent has taken, and returns either an AgentAction or AgentFinish
AgentAction corresponds to the tool to use ... | https://python.langchain.com/en/latest/modules/agents.html |
9d9a77cb02c7-2 | Agents
In this section we cover the different types of agents LangChain supports natively.
We then cover how to modify and create your own agents.
Toolkits
In this section we go over the various toolkits that LangChain supports out of the box,
and how to create an agent from them.
Agent Executor
In this section we go o... | https://python.langchain.com/en/latest/modules/agents.html |
291a2130beac-0 | .rst
.pdf
Memory
Memory#
Note
Conceptual Guide
By default, Chains and Agents are stateless,
meaning that they treat each incoming query independently (as are the underlying LLMs and chat models).
In some applications (chatbots being a GREAT example) it is highly important
to remember previous interactions, both at a sh... | https://python.langchain.com/en/latest/modules/memory.html |
97afe287fb37-0 | .rst
.pdf
Models
Contents
Getting Started
Go Deeper
Models#
Note
Conceptual Guide
This section of the documentation deals with different types of models that are used in LangChain.
On this page we will go over the model types at a high level,
but we have individual pages for each model type.
The pages contain more de... | https://python.langchain.com/en/latest/modules/models.html |
d44e1d7cf74a-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 |
27c9b1538d32-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 |
27c9b1538d32-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 |
27c9b1538d32-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 |
27c9b1538d32-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 |
7590281efb22-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 |
7590281efb22-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 |
7590281efb22-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 |
7f981bb7ae43-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 |
7f981bb7ae43-1 | '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 ConversationEntityMemory
from langchain.memory.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE
from pydantic import BaseM... | https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7f981bb7ae43-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 |
7cf41df972b5-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 |
7cf41df972b5-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 |
7cf41df972b5-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 |
ee4eabb35a04-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 |
ee4eabb35a04-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 |
ee4eabb35a04-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 |
ee4eabb35a04-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 |
ee4eabb35a04-4 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html |
13403f3f668d-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 |
13403f3f668d-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 |
13403f3f668d-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 |
13403f3f668d-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 May 28, 2023. | https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html |
f452446dd996-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 |
f452446dd996-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 |
f452446dd996-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 |
281ac2eb0646-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.