id
stringlengths
14
16
source
stringlengths
49
117
text
stringlengths
16
2.73k
67a6b5a5599e-4
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
When the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>. Never say <CAMEL_TASK_DONE> unless my responses have solved your task.""" ) Create a helper helper to get system messages for AI assistant and AI user from role names and the task# def get_sys_msgs(assistant_role_name: str, user_role_...
67a6b5a5599e-5
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
print(f"Original task prompt:\n{task}\n") print(f"Specified task prompt:\n{specified_task}\n") chat_turn_limit, n = 30, 0 while n < chat_turn_limit: n += 1 user_ai_msg = user_agent.step(assistant_msg) user_msg = HumanMessage(content=user_ai_msg.content) print(f"AI User ({user_role_name}):\n\n{user_msg.c...
67a6b5a5599e-6
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
Solution: We can import the necessary libraries in the Python script using the import statement. We need to import pandas, numpy, matplotlib, and ta-lib for data analysis and trading. We can use the following code to import these libraries: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt impo...
67a6b5a5599e-7
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
Input: The period for the short-term moving average and the period for the long-term moving average. AI Assistant (Python Programmer): Solution: We can calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from ta-lib. We need to pass the period for the short-term movin...
67a6b5a5599e-8
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
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 named 'open', 'high', 'low', 'close', 'volume', 'short_ma', and 'long_ma'. Next request. AI User (Stock Trader): Instruction: Create a new colu...
67a6b5a5599e-9
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
stop_loss = stop_loss_percent / 100 profit_target = profit_target_percent / 100 new_df['pnl'] = 0.0 buy_price = 0.0 for i in range(1, len(new_df)): if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1: buy_price = new_df['close'][i] elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1: ...
67a6b5a5599e-10
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
Solution: We can calculate the total profit or loss for all trades by summing the values in the 'pnl' column of the DataFrame. We can use the following code to calculate the total profit or loss: ``` total_pnl = new_df['pnl'].sum() ``` This will calculate the total profit or loss for all trades and store it in the tota...
67a6b5a5599e-11
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
buy_signals = new_df[new_df['signal'] == 1] sell_signals = new_df[new_df['signal'] == -1] plt.figure(figsize=(12,6)) plt.scatter(buy_signals.index, buy_signals['close'], label='Buy', marker='^', color='green') plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red') plt.plot(new_df....
67a6b5a5599e-12
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
# Preprocess the historical stock data df = df.set_index('date') df = df.sort_index(ascending=True) # Calculate the short-term and long-term moving averages short_period = 10 long_period = 30 short_ma = ta.SMA(df['close'], timeperiod=short_period) long_ma = ta.SMA(df['close'], timeperiod=long_period) # Create a new Dat...
67a6b5a5599e-13
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
if sell_price <= buy_price * (1 - stop_loss): new_df['pnl'][i] = -stop_loss elif sell_price >= buy_price * (1 + profit_target): new_df['pnl'][i] = profit_target else: new_df['pnl'][i] = (sell_price - buy_price) / buy_price # Calculate the total profit or loss for all ...
67a6b5a5599e-14
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
You need to replace the path/to/csv/file.csv with the actual path to the CSV file containing the historical stock data. You can also adjust the short_period, long_period, stop_loss_percent, and profit_target_percent variables to suit your needs. AI User (Stock Trader): <CAMEL_TASK_DONE> AI Assistant (Python Programmer)...
aaa5da077725-0
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
.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 ...
aaa5da077725-1
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
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.system_message, HumanMessage(content...
aaa5da077725-2
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
# 4. increment time self._step += 1 return speaker.name, message DirectorDialogueAgent class# The DirectorDialogueAgent is a privileged agent that chooses which of the other agents to speak next. This agent is responsible for steering the conversation by choosing which agent speaks when terminating the ...
aaa5da077725-3
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
return 'Your response should be an integer delimited by angled brackets, like this: <int>.' class DirectorDialogueAgent(DialogueAgent): def __init__( self, name, system_message: SystemMessage, model: ChatOpenAI, speakers: List[DialogueAgent], stopping_probability: f...
aaa5da077725-4
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
self.prompt_next_speaker_prompt_template = PromptTemplate( input_variables=["message_history", "next_speaker"], template=f"""{{message_history}} The next speaker is {{next_speaker}}. Prompt the next speaker to speak with an insightful question. {self.prefix} """) def _gener...
aaa5da077725-5
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
choice_string = self.model( [ self.system_message, HumanMessage(content=choice_prompt), ] ).content choice = int(self.choice_parser.parse(choice_string)['choice']) return choice def select_next_speaker(self): retur...
aaa5da077725-6
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
"Samantha Bee": ("Hollywood Correspondent", "Los Angeles"), "Aasif Mandvi": ("CIA Correspondent", "Washington D.C."), "Ronny Chieng": ("Average American Correspondent", "Cleveland, Ohio"), }) word_limit = 50 Generate system messages# agent_summary_string = '\n- '.join([''] + [f'{name}: {role}, located in {loca...
aaa5da077725-7
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
""" def generate_agent_system_message(agent_name, agent_header): return SystemMessage(content=( f"""{agent_header} You will speak in the style of {agent_name}, and exaggerate your personality. Do not say the same things over and over again. Speak in the first person from the perspective of {agent_name} For desc...
aaa5da077725-8
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. 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 Corre...
aaa5da077725-9
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
Your description is as follows: 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. You are discussing the topic: The New Workout Trend: Com...
aaa5da077725-10
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
Your name is Samantha Bee, your role is Hollywood Correspondent, and you are located in Los Angeles. Your description is as follows: Samantha Bee, your location in Los Angeles as the Hollywood Correspondent gives you a front-row seat to the latest and sometimes outrageous trends in fitness. Your comedic wit and sharp c...
aaa5da077725-11
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
Do not say the same things over and over again. Speak in the first person from the perspective of Samantha Bee 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 Samantha Bee. Stop speaking the m...
aaa5da077725-12
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
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...
aaa5da077725-13
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
Ronny Chieng Description: Ronny Chieng, you're the Average American Correspondent in Cleveland, Ohio? Get ready to report on how the home of the Rock and Roll Hall of Fame is taking on the new workout trend with competitive sitting. Let's see if this couch potato craze will take root in the Buckeye State. Header: This ...
aaa5da077725-14
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
- Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Ronny Chieng, your role is Average American Correspondent, and you are located in Cleveland, Ohio. Your description is as follows: Ronny Chieng, you're the Average Ameri...
aaa5da077725-15
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
Please reply with the specified topic in {word_limit} words or less. Do not add anything else.""" ) ] specified_topic = ChatOpenAI(temperature=1.0)(topic_specifier_prompt).content print(f"Original topic:\n{topic}\n") print(f"Detailed topic:\n{specified_topic}\n") Original topic: The New Workout Trend: ...
aaa5da077725-16
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
speakers=[name for name in agent_summaries if name != director_name], stopping_probability=0.2 ) agents = [director] for name, system_message in zip(list(agent_summaries.keys())[1:], agent_system_messages[1:]): agents.append(DialogueAgent( name=name, system_message=system_message, ...
aaa5da077725-17
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
(Samantha Bee): Oh, Jon, you know I love a good social media trend. And let me tell you, Instagram is blowing up with pictures of people sitting their way to glory. It's like the ultimate humble brag. "Oh, just won my third sitting competition this week, no big deal." But on a serious note, I think social media has mad...
aaa5da077725-18
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
(Jon Stewart): It's interesting to see how our society's definition of "fitness" has evolved. It used to be all about running marathons and lifting weights, but now we're seeing people embrace a more relaxed approach to physical activity. Who knows, maybe in a few years we'll have competitive napping as the next big th...
aaa5da077725-19
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
(Jon Stewart): Well, it's clear that competitive sitting has sparked some interesting discussions and perspectives. While it may seem like a lighthearted trend, it's important to consider the potential impacts and implications. But at the end of the day, whether you're a competitive sitter or a marathon runner, the mos...
aaa5da077725-20
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
(Jon Stewart): It's clear that competitive sitting has sparked some interesting discussions and perspectives. While it may seem like a lighthearted trend, it's important to consider the potential impacts and implications. But at the end of the day, whether you're a competitive sitter or a marathon runner, the most impo...
aaa5da077725-21
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
(Jon Stewart): Well, it's clear that competitive sitting has sparked some interesting discussions and perspectives. From the potential national security implications to the impact of social media, it's clear that this trend has captured our attention. But let's not forget the importance of real physical activity and th...
cd3b9faccaba-0
https://python.langchain.com/en/latest/modules/indexes.html
.rst .pdf Indexes Contents Index Types Indexes# Note Conceptual Guide Indexes refer to ways to structure documents so that LLMs can best interact with them. The most common way that indexes are used in chains is in a “retrieval” step. This step refers to taking a user’s query and returning the most relevant documents...
d45a1e6ff6f5-0
https://python.langchain.com/en/latest/modules/prompts.html
.rst .pdf Prompts 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 often constructed from multiple components. A PromptTemplate is responsible for the construction of this input. LangChain provides several classes and functions...
cafe2aa7f222-0
https://python.langchain.com/en/latest/modules/chains.html
.rst .pdf Chains Chains# Note Conceptual Guide Using an LLM in isolation is fine for some simple applications, but more complex applications require chaining LLMs - either with each other or with other experts. LangChain provides a standard interface for Chains, as well as several common implementations of chains. Gett...
19a3023231d2-0
https://python.langchain.com/en/latest/modules/agents.html
.rst .pdf Agents Contents Action Agents Plan-and-Execute Agents Agents# Note Conceptual Guide Some applications 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 an agent which has access to a suit...
19a3023231d2-1
https://python.langchain.com/en/latest/modules/agents.html
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 and the input to that tool AgentFinish means the agent is done...
19a3023231d2-2
https://python.langchain.com/en/latest/modules/agents.html
Agent Executor: The Agent Executor class, which is responsible for calling the agent and tools in a loop. We go over different ways to customize this, and options you can use for more control. Plan-and-Execute Agents# High level pseudocode of the Plan-and-Execute Agents: The user input is received The planner lists out...
5dbed1b4424a-0
https://python.langchain.com/en/latest/modules/memory.html
.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...
fb412e43315c-0
https://python.langchain.com/en/latest/modules/models.html
.rst .pdf Models Contents Model Types 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 detailed “how-to...
5c7c4e24765f-0
https://python.langchain.com/en/latest/modules/memory/how_to_guides.html
.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...
f6e021605763-0
https://python.langchain.com/en/latest/modules/memory/getting_started.html
.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...
f6e021605763-1
https://python.langchain.com/en/latest/modules/memory/getting_started.html
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 messages in a variable. We can first extract it as a string. from langchai...
f6e021605763-2
https://python.langchain.com/en/latest/modules/memory/getting_started.html
" 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 between a human and an AI. The AI is talkative and provides lots ...
f6e021605763-3
https://python.langchain.com/en/latest/modules/memory/getting_started.html
Saving Message History# You may often have to save messages, and then load them to use again. This can be done easily by first converting the messages to normal python dictionaries, saving those (as json or something) and then loading those. Here is an example of doing that. import json from langchain.memory import Cha...
4d1c31fc8933-0
https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html
.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 ...
4d1c31fc8933-1
https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html
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 its context. If the AI does not know the answer to a question, i...
4d1c31fc8933-2
https://python.langchain.com/en/latest/modules/memory/types/buffer_window.html
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 it going well? AI: > Finished chain. " Yes,...
de8b67d665e0-0
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
.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)....
de8b67d665e0-1
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
'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...
de8b67d665e0-2
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
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...
de8b67d665e0-3
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
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 ...
de8b67d665e0-4
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding convers...
de8b67d665e0-5
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
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 entities mentioned so far in the conversation. You: > Finished chain. ' That sounds like a great idea! How will the key-value store help with the project?' conv...
de8b67d665e0-6
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
{'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, trying to ...
de8b67d665e0-7
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
'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 ' 'work...
de8b67d665e0-8
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
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 ...
de8b67d665e0-9
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
That's impressive! It sounds like Sam is a very successful entrepreneur. What kind of company is Daimon? Last line: Human: Sam is the founder of a company called Daimon. You: > Finished chain. " That's impressive! It sounds like Sam is a very successful entrepreneur. What kind of company is Daimon?" from pprint import ...
de8b67d665e0-10
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
'the founder of a successful company called Daimon.'} conversation.predict(input="What do you know about Sam?") > Entering new ConversationChain chain... Prompt after formatting: You are an assistant to a human, powered by a large language model trained by OpenAI. You are designed to be able to assist with a wide range...
de8b67d665e0-11
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
{'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 for how ...
de8b67d665e0-12
https://python.langchain.com/en/latest/modules/memory/types/entity_summary_memory.html
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 ConversationBuffer...
49ac24ca8c10-0
https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html
.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...
49ac24ca8c10-1
https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html
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: Human: Hi, what's up? AI: > Finished chain. " Hi there! I'm doing g...
49ac24ca8c10-2
https://python.langchain.com/en/latest/modules/memory/types/token_buffer.html
> 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 writing about?" # We can see here that the buffer is updated conversation_with_summary.predict(input="Haha nope, although a lot o...
6f3417dbbc8c-0
https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html
.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...
6f3417dbbc8c-1
https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html
# 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"}, {"output": "..."}) memory.save_context({"input": "I don'...
6f3417dbbc8c-2
https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html
> 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. Relevant pieces of pre...
6f3417dbbc8c-3
https://python.langchain.com/en/latest/modules/memory/types/vectorstore_retriever_memory.html
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. Relevant pieces of previous conversation: input: My favorite food is pizza output: thats ...
424d5401753a-0
https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html
.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...
424d5401753a-1
https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html
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, what's up?") > Entering new ConversationChain chain... Prompt after formatting: The following is a ...
424d5401753a-2
https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html
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: System: The human asked the AI what it was up to and the AI respon...
424d5401753a-3
https://python.langchain.com/en/latest/modules/memory/types/summary_buffer.html
ConversationSummaryMemory next ConversationTokenBufferMemory Contents Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
e50f48e51b52-0
https://python.langchain.com/en/latest/modules/memory/types/kg.html
.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...
e50f48e51b52-1
https://python.langchain.com/en/latest/modules/memory/types/kg.html
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 the AI does not know the answer to a question, it truthfull...
e50f48e51b52-2
https://python.langchain.com/en/latest/modules/memory/types/kg.html
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 information contained in the "Relevant Information" section and does no...
4503e6968f97-0
https://python.langchain.com/en/latest/modules/memory/types/buffer.html
.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...
4503e6968f97-1
https://python.langchain.com/en/latest/modules/memory/types/buffer.html
" 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 between a human and an AI. The AI is talkative and provides lots ...
4503e6968f97-2
https://python.langchain.com/en/latest/modules/memory/types/buffer.html
And that’s it for the getting started! There are plenty of different types of memory, check out our examples to see them all previous How-To Guides next ConversationBufferWindowMemory Contents Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
9835ff679734-0
https://python.langchain.com/en/latest/modules/memory/types/summary.html
.ipynb .pdf ConversationSummaryMemory Contents Initializing with messages 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 condensin...
9835ff679734-1
https://python.langchain.com/en/latest/modules/memory/types/summary.html
memory = ConversationSummaryMemory.from_messages(llm=OpenAI(temperature=0), chat_memory=history, return_messages=True) memory.buffer '\nThe human greets the AI, to which the AI responds with a friendly greeting.' Using in a chain# Let’s walk through an example of using this in a chain, again setting verbose=True so we ...
9835ff679734-2
https://python.langchain.com/en/latest/modules/memory/types/summary.html
" Sure! The customer is having trouble with their computer not connecting to the internet. I'm helping them troubleshoot the issue and figure out what the problem is. So far, we've tried resetting the router and checking the network settings, but the issue still persists. We're currently looking into other possible sol...
19e3cdebb95e-0
https://python.langchain.com/en/latest/modules/memory/examples/momento_chat_message_history.html
.ipynb .pdf Momento Chat Message History Momento Chat Message History# 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 wit...
3eb1b3b3da18-0
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
.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 ...
3eb1b3b3da18-1
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
# 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 = ZepChatMessageHistory( session_id=session_id, url=ZEP_API_URL, ...
3eb1b3b3da18-2
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
{"role": "human", "content": "Who were her contemporaries?"}, { "role": "ai", "content": ( "Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R." " Delany, and Joanna Russ." ), }, {"role": "human", "content": "What awards did she win?"}, {...
3eb1b3b3da18-3
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
) Run the agent# Doing so will automatically add the input and response to the Zep memory. agent_chain.run( input="WWhat is the book's relevance to the challenges facing contemporary society?" ) > Entering new AgentExecutor chain... Thought: Do I need to use a tool? No AI: Parable of the Sower is a prescient novel ...
3eb1b3b3da18-4
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
{'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 Fellowship.', 'uuid': 'def4636c-32cb-49ed-b671-32035a03...
3eb1b3b3da18-5
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
{'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...
3eb1b3b3da18-6
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
{'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...
3eb1b3b3da18-7
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
{'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...
3eb1b3b3da18-8
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
{'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...
3eb1b3b3da18-9
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
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...
b856f60ef47c-0
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
.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...
b856f60ef47c-1
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
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_and_tools(agent=agent, tools=tools, verbose=True, memory=memor...
b856f60ef47c-2
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
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's Population and Demography Portal. Population of...
b856f60ef47c-3
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
'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 correctly. agent_chain.run(input="wh...
b856f60ef47c-4
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
Observation: Jun 7, 2010 ... https://twitter.com/CanadaImmigrantCanadian National Anthem O Canada in HQ - complete with lyrics, captions, vocals & music.LYRICS:O Canada! Nov 23, 2022 ... After 100 years of tradition, O Canada was proclaimed Canada's national anthem in 1980. The music for O Canada was composed in 1880 b...
b856f60ef47c-5
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
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 of Canada’s national anthem was. For fu...
b856f60ef47c-6
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
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's Population and Demography Portal. Population of...