id
stringlengths
14
16
text
stringlengths
29
2.31k
source
stringlengths
57
122
bfd89f7b1049-3
score them programatically from langchain.evaluation.qa import QAEvalChain llm = OpenAI(temperature=0) eval_chain = QAEvalChain.from_llm(llm) graded_outputs = eval_chain.evaluate(predicted_dataset, predictions, question_key="input", prediction_key="output") We can add in the graded output to the predictions dict and then get a count of the grades. for i, prediction in enumerate(predictions): prediction['grade'] = graded_outputs[i]['text'] from collections import Counter Counter([pred['grade'] for pred in predictions]) Counter({' CORRECT': 19, ' INCORRECT': 14}) We can also filter the datapoints to the incorrect examples and look at them. incorrect = [pred for pred in predictions if pred['grade'] == " INCORRECT"] incorrect[0] {'input': 'What is the purpose of the Bipartisan Innovation Act mentioned in the text?', 'answer': 'The Bipartisan Innovation Act will make record investments in emerging technologies and American manufacturing to level the playing field with China and other competitors.', 'output': 'The purpose of the Bipartisan Innovation Act is to promote innovation and entrepreneurship in the United States by providing tax incentives and other support for startups and small businesses.', 'grade': ' INCORRECT'} previous Agent Benchmarking: Search + Calculator next Benchmarking Template Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html
6fc47ece4071-0
.ipynb .pdf Agent Benchmarking: Search + Calculator Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance Agent Benchmarking: Search + Calculator# Here we go over how to benchmark performance of an agent on tasks where it has access to a calculator and a search tool. It is highly reccomended that you do any evaluation/benchmarking with tracing enabled. See here for an explanation of what tracing is and how to set it up. # Comment this out if you are NOT using tracing import os os.environ["LANGCHAIN_HANDLER"] = "langchain" Loading the data# First, let’s load the data. from langchain.evaluation.loading import load_dataset dataset = load_dataset("agent-search-calculator") Found cached dataset json (/Users/harrisonchase/.cache/huggingface/datasets/LangChainDatasets___json/LangChainDatasets--agent-search-calculator-8a025c0ce5fb99d2/0.0.0/0f7e3662623656454fcd2b650f34e886a7db4b9104504885bd462096cc7a9f51) Setting up a chain# Now we need to load an agent capable of answering these questions. from langchain.llms import OpenAI from langchain.chains import LLMMathChain from langchain.agents import initialize_agent, Tool, load_tools from langchain.agents import AgentType tools = load_tools(['serpapi', 'llm-math'], llm=OpenAI(temperature=0)) agent = initialize_agent(tools, OpenAI(temperature=0), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION) Make a prediction# First, we can make predictions one datapoint at a time. Doing it at this level of granularity allows use to explore the outputs in detail, and also is a
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/agent_benchmarking.html
6fc47ece4071-1
Doing it at this level of granularity allows use to explore the outputs in detail, and also is a lot cheaper than running over multiple datapoints agent.run(dataset[0]['question']) '38,630,316 people live in Canada as of 2023.' Make many predictions# Now we can make predictions predictions = [] predicted_dataset = [] error_dataset = [] for data in dataset: new_data = {"input": data["question"], "answer": data["answer"]} try: predictions.append(agent(new_data)) predicted_dataset.append(new_data) except Exception: error_dataset.append(new_data) Retrying langchain.llms.openai.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised APIConnectionError: Error communicating with OpenAI: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer')). Evaluate performance# Now we can evaluate the predictions. The first thing we can do is look at them by eye. predictions[0] {'input': 'How many people live in canada as of 2023?', 'answer': 'approximately 38,625,801', 'output': '38,630,316 people live in Canada as of 2023.', 'intermediate_steps': [(AgentAction(tool='Search', tool_input='Population of Canada 2023', log=' I need to find population data\nAction: Search\nAction Input: Population of Canada 2023'), '38,630,316')]} Next, we can use a language model to score them programatically from langchain.evaluation.qa import QAEvalChain llm = OpenAI(temperature=0) eval_chain = QAEvalChain.from_llm(llm) graded_outputs = eval_chain.evaluate(dataset, predictions, question_key="question",
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/agent_benchmarking.html
6fc47ece4071-2
= eval_chain.evaluate(dataset, predictions, question_key="question", prediction_key="output") We can add in the graded output to the predictions dict and then get a count of the grades. for i, prediction in enumerate(predictions): prediction['grade'] = graded_outputs[i]['text'] from collections import Counter Counter([pred['grade'] for pred in predictions]) Counter({' CORRECT': 4, ' INCORRECT': 6}) We can also filter the datapoints to the incorrect examples and look at them. incorrect = [pred for pred in predictions if pred['grade'] == " INCORRECT"] incorrect[0] {'input': "who is dua lipa's boyfriend? what is his age raised to the .43 power?", 'answer': 'her boyfriend is Romain Gravas. his age raised to the .43 power is approximately 4.9373857399466665', 'output': "Isaac Carew, Dua Lipa's boyfriend, is 36 years old and his age raised to the .43 power is 4.6688516567750975.", 'intermediate_steps': [(AgentAction(tool='Search', tool_input="Dua Lipa's boyfriend", log=' I need to find out who Dua Lipa\'s boyfriend is and then calculate his age raised to the .43 power\nAction: Search\nAction Input: "Dua Lipa\'s boyfriend"'), 'Dua and Isaac, a model and a chef, dated on and off from 2013 to 2019. The two first split in early 2017, which is when Dua went on to date LANY ...'), (AgentAction(tool='Search', tool_input='Isaac Carew age', log=' I need to find out Isaac\'s age\nAction: Search\nAction Input: "Isaac Carew age"'), '36 years'),
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/agent_benchmarking.html
6fc47ece4071-3
Search\nAction Input: "Isaac Carew age"'), '36 years'), (AgentAction(tool='Calculator', tool_input='36^.43', log=' I need to calculate 36 raised to the .43 power\nAction: Calculator\nAction Input: 36^.43'), 'Answer: 4.6688516567750975\n')], 'grade': ' INCORRECT'} previous Evaluation next Agent VectorDB Question Answering Benchmarking Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/agent_benchmarking.html
24abbbaf7341-0
.ipynb .pdf Question Answering Contents Setup Examples Predictions Evaluation Customize Prompt Evaluation without Ground Truth Comparing to other evaluation metrics Question Answering# This notebook covers how to evaluate generic question answering problems. This is a situation where you have an example containing a question and its corresponding ground truth answer, and you want to measure how well the language model does at answering those questions. Setup# For demonstration purposes, we will just evaluate a simple question answering system that only evaluates the model’s internal knowledge. Please see other notebooks for examples where it evaluates how the model does at question answering over data not present in what the model was trained on. from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from langchain.llms import OpenAI prompt = PromptTemplate(template="Question: {question}\nAnswer:", input_variables=["question"]) llm = OpenAI(model_name="text-davinci-003", temperature=0) chain = LLMChain(llm=llm, prompt=prompt) Examples# For this purpose, we will just use two simple hardcoded examples, but see other notebooks for tips on how to get and/or generate these examples. examples = [ { "question": "Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?", "answer": "11" }, { "question": 'Is the following sentence plausible? "Joao Moutinho caught the screen pass in the NFC championship."', "answer": "No" } ] Predictions# We can now make and inspect the predictions for these questions. predictions =
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/question_answering.html
24abbbaf7341-1
} ] Predictions# We can now make and inspect the predictions for these questions. predictions = chain.apply(examples) predictions [{'text': ' 11 tennis balls'}, {'text': ' No, this sentence is not plausible. Joao Moutinho is a professional soccer player, not an American football player, so it is not likely that he would be catching a screen pass in the NFC championship.'}] Evaluation# We can see that if we tried to just do exact match on the answer answers (11 and No) they would not match what the language model answered. However, semantically the language model is correct in both cases. In order to account for this, we can use a language model itself to evaluate the answers. from langchain.evaluation.qa import QAEvalChain llm = OpenAI(temperature=0) eval_chain = QAEvalChain.from_llm(llm) graded_outputs = eval_chain.evaluate(examples, predictions, question_key="question", prediction_key="text") for i, eg in enumerate(examples): print(f"Example {i}:") print("Question: " + eg['question']) print("Real Answer: " + eg['answer']) print("Predicted Answer: " + predictions[i]['text']) print("Predicted Grade: " + graded_outputs[i]['text']) print() Example 0: Question: Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now? Real Answer: 11 Predicted Answer: 11 tennis balls Predicted Grade: CORRECT Example 1: Question: Is the following sentence plausible? "Joao Moutinho caught the screen pass in the NFC championship." Real Answer: No Predicted Answer: No, this sentence is not
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/question_answering.html
24abbbaf7341-2
the NFC championship." Real Answer: No Predicted Answer: No, this sentence is not plausible. Joao Moutinho is a professional soccer player, not an American football player, so it is not likely that he would be catching a screen pass in the NFC championship. Predicted Grade: CORRECT Customize Prompt# You can also customize the prompt that is used. Here is an example prompting it using a score from 0 to 10. The custom prompt requires 3 input variables: “query”, “answer” and “result”. Where “query” is the question, “answer” is the ground truth answer, and “result” is the predicted answer. from langchain.prompts.prompt import PromptTemplate _PROMPT_TEMPLATE = """You are an expert professor specialized in grading students' answers to questions. You are grading the following question: {query} Here is the real answer: {answer} You are grading the following predicted answer: {result} What grade do you give from 0 to 10, where 0 is the lowest (very low similarity) and 10 is the highest (very high similarity)? """ PROMPT = PromptTemplate(input_variables=["query", "answer", "result"], template=_PROMPT_TEMPLATE) evalchain = QAEvalChain.from_llm(llm=llm,prompt=PROMPT) evalchain.evaluate(examples, predictions, question_key="question", answer_key="answer", prediction_key="text") Evaluation without Ground Truth# Its possible to evaluate question answering systems without ground truth. You would need a "context" input that reflects what the information the LLM uses to answer the question. This context can be obtained by any retreival system. Here’s an example of how it works: context_examples = [ { "question": "How old am I?", "context": "I am 30
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/question_answering.html
24abbbaf7341-3
old am I?", "context": "I am 30 years old. I live in New York and take the train to work everyday.", }, { "question": 'Who won the NFC championship game in 2023?"', "context": "NFC Championship Game 2023: Philadelphia Eagles 31, San Francisco 49ers 7" } ] QA_PROMPT = "Answer the question based on the context\nContext:{context}\nQuestion:{question}\nAnswer:" template = PromptTemplate(input_variables=["context", "question"], template=QA_PROMPT) qa_chain = LLMChain(llm=llm, prompt=template) predictions = qa_chain.apply(context_examples) predictions [{'text': 'You are 30 years old.'}, {'text': ' The Philadelphia Eagles won the NFC championship game in 2023.'}] from langchain.evaluation.qa import ContextQAEvalChain eval_chain = ContextQAEvalChain.from_llm(llm) graded_outputs = eval_chain.evaluate(context_examples, predictions, question_key="question", prediction_key="text") graded_outputs [{'text': ' CORRECT'}, {'text': ' CORRECT'}] Comparing to other evaluation metrics# We can compare the evaluation results we get to other common evaluation metrics. To do this, let’s load some evaluation metrics from HuggingFace’s evaluate package. # Some data munging to get the examples in the right format for i, eg in enumerate(examples): eg['id'] = str(i) eg['answers'] = {"text": [eg['answer']], "answer_start": [0]} predictions[i]['id'] = str(i) predictions[i]['prediction_text'] = predictions[i]['text'] for p in
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/question_answering.html
24abbbaf7341-4
predictions[i]['prediction_text'] = predictions[i]['text'] for p in predictions: del p['text'] new_examples = examples.copy() for eg in new_examples: del eg ['question'] del eg['answer'] from evaluate import load squad_metric = load("squad") results = squad_metric.compute( references=new_examples, predictions=predictions, ) results {'exact_match': 0.0, 'f1': 28.125} previous QA Generation next SQL Question Answering Benchmarking: Chinook Contents Setup Examples Predictions Evaluation Customize Prompt Evaluation without Ground Truth Comparing to other evaluation metrics By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/question_answering.html
12186184aaee-0
.ipynb .pdf SQL Question Answering Benchmarking: Chinook Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance SQL Question Answering Benchmarking: Chinook# Here we go over how to benchmark performance on a question answering task over a SQL database. It is highly reccomended that you do any evaluation/benchmarking with tracing enabled. See here for an explanation of what tracing is and how to set it up. # Comment this out if you are NOT using tracing import os os.environ["LANGCHAIN_HANDLER"] = "langchain" Loading the data# First, let’s load the data. from langchain.evaluation.loading import load_dataset dataset = load_dataset("sql-qa-chinook") Downloading and preparing dataset json/LangChainDatasets--sql-qa-chinook to /Users/harrisonchase/.cache/huggingface/datasets/LangChainDatasets___json/LangChainDatasets--sql-qa-chinook-7528565d2d992b47/0.0.0/0f7e3662623656454fcd2b650f34e886a7db4b9104504885bd462096cc7a9f51... Dataset json downloaded and prepared to /Users/harrisonchase/.cache/huggingface/datasets/LangChainDatasets___json/LangChainDatasets--sql-qa-chinook-7528565d2d992b47/0.0.0/0f7e3662623656454fcd2b650f34e886a7db4b9104504885bd462096cc7a9f51. Subsequent calls will reuse this data. dataset[0] {'question': 'How many employees are there?', 'answer': '8'} Setting up a chain# This uses the example Chinook database. To set
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html
12186184aaee-1
'8'} Setting up a chain# This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository. Note that here we load a simple chain. If you want to experiment with more complex chains, or an agent, just create the chain object in a different way. from langchain import OpenAI, SQLDatabase, SQLDatabaseChain db = SQLDatabase.from_uri("sqlite:///../../../notebooks/Chinook.db") llm = OpenAI(temperature=0) Now we can create a SQL database chain. chain = SQLDatabaseChain(llm=llm, database=db, input_key="question") Make a prediction# First, we can make predictions one datapoint at a time. Doing it at this level of granularity allows use to explore the outputs in detail, and also is a lot cheaper than running over multiple datapoints chain(dataset[0]) {'question': 'How many employees are there?', 'answer': '8', 'result': ' There are 8 employees.'} Make many predictions# Now we can make predictions. Note that we add a try-except because this chain can sometimes error (if SQL is written incorrectly, etc) predictions = [] predicted_dataset = [] error_dataset = [] for data in dataset: try: predictions.append(chain(data)) predicted_dataset.append(data) except: error_dataset.append(data) Evaluate performance# Now we can evaluate the predictions. We can use a language model to score them programatically from langchain.evaluation.qa import QAEvalChain llm = OpenAI(temperature=0) eval_chain = QAEvalChain.from_llm(llm) graded_outputs = eval_chain.evaluate(predicted_dataset, predictions,
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html
12186184aaee-2
= eval_chain.evaluate(predicted_dataset, predictions, question_key="question", prediction_key="result") We can add in the graded output to the predictions dict and then get a count of the grades. for i, prediction in enumerate(predictions): prediction['grade'] = graded_outputs[i]['text'] from collections import Counter Counter([pred['grade'] for pred in predictions]) Counter({' CORRECT': 3, ' INCORRECT': 4}) We can also filter the datapoints to the incorrect examples and look at them. incorrect = [pred for pred in predictions if pred['grade'] == " INCORRECT"] incorrect[0] {'question': 'How many employees are also customers?', 'answer': 'None', 'result': ' 59 employees are also customers.', 'grade': ' INCORRECT'} previous Question Answering next Installation Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html
e61f5b4f640d-0
.ipynb .pdf Benchmarking Template Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance Benchmarking Template# This is an example notebook that can be used to create a benchmarking notebook for a task of your choice. Evaluation is really hard, and so we greatly welcome any contributions that can make it easier for people to experiment It is highly reccomended that you do any evaluation/benchmarking with tracing enabled. See here for an explanation of what tracing is and how to set it up. # Comment this out if you are NOT using tracing import os os.environ["LANGCHAIN_HANDLER"] = "langchain" Loading the data# First, let’s load the data. # This notebook should so how to load the dataset from LangChainDatasets on Hugging Face # Please upload your dataset to https://huggingface.co/LangChainDatasets # The value passed into `load_dataset` should NOT have the `LangChainDatasets/` prefix from langchain.evaluation.loading import load_dataset dataset = load_dataset("TODO") Setting up a chain# This next section should have an example of setting up a chain that can be run on this dataset. Make a prediction# First, we can make predictions one datapoint at a time. Doing it at this level of granularity allows use to explore the outputs in detail, and also is a lot cheaper than running over multiple datapoints # Example of running the chain on a single datapoint (`dataset[0]`) goes here Make many predictions# Now we can make predictions. # Example of running the chain on many predictions goes here # Sometimes its as simple as `chain.apply(dataset)` # Othertimes you may want to write a for loop to catch errors Evaluate performance# Any guide to evaluating performance in a more systematic manner goes here. previous Agent VectorDB Question Answering
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/benchmarking_template.html
e61f5b4f640d-1
guide to evaluating performance in a more systematic manner goes here. previous Agent VectorDB Question Answering Benchmarking next Data Augmented Question Answering Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/benchmarking_template.html
62936dd5e9fb-0
.ipynb .pdf Question Answering Benchmarking: Paul Graham Essay Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance Question Answering Benchmarking: Paul Graham Essay# Here we go over how to benchmark performance on a question answering task over a Paul Graham essay. It is highly reccomended that you do any evaluation/benchmarking with tracing enabled. See here for an explanation of what tracing is and how to set it up. # Comment this out if you are NOT using tracing import os os.environ["LANGCHAIN_HANDLER"] = "langchain" Loading the data# First, let’s load the data. from langchain.evaluation.loading import load_dataset dataset = load_dataset("question-answering-paul-graham") Found cached dataset json (/Users/harrisonchase/.cache/huggingface/datasets/LangChainDatasets___json/LangChainDatasets--question-answering-paul-graham-76e8f711e038d742/0.0.0/0f7e3662623656454fcd2b650f34e886a7db4b9104504885bd462096cc7a9f51) Setting up a chain# Now we need to create some pipelines for doing question answering. Step one in that is creating an index over the data in question. from langchain.document_loaders import TextLoader loader = TextLoader("../../modules/paul_graham_essay.txt") from langchain.indexes import VectorstoreIndexCreator vectorstore = VectorstoreIndexCreator().from_loaders([loader]).vectorstore Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Now we can create a question answering chain. from langchain.chains import RetrievalQA from langchain.llms import OpenAI chain =
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/qa_benchmarking_pg.html
62936dd5e9fb-1
langchain.chains import RetrievalQA from langchain.llms import OpenAI chain = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=vectorstore.as_retriever(), input_key="question") Make a prediction# First, we can make predictions one datapoint at a time. Doing it at this level of granularity allows use to explore the outputs in detail, and also is a lot cheaper than running over multiple datapoints chain(dataset[0]) {'question': 'What were the two main things the author worked on before college?', 'answer': 'The two main things the author worked on before college were writing and programming.', 'result': ' Writing and programming.'} Make many predictions# Now we can make predictions predictions = chain.apply(dataset) Evaluate performance# Now we can evaluate the predictions. The first thing we can do is look at them by eye. predictions[0] {'question': 'What were the two main things the author worked on before college?', 'answer': 'The two main things the author worked on before college were writing and programming.', 'result': ' Writing and programming.'} Next, we can use a language model to score them programatically from langchain.evaluation.qa import QAEvalChain llm = OpenAI(temperature=0) eval_chain = QAEvalChain.from_llm(llm) graded_outputs = eval_chain.evaluate(dataset, predictions, question_key="question", prediction_key="result") We can add in the graded output to the predictions dict and then get a count of the grades. for i, prediction in enumerate(predictions): prediction['grade'] = graded_outputs[i]['text'] from collections import Counter Counter([pred['grade'] for pred in predictions]) Counter({' CORRECT': 12, ' INCORRECT': 10}) We can also filter the datapoints to the incorrect examples and look at them. incorrect = [pred
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/qa_benchmarking_pg.html
62936dd5e9fb-2
can also filter the datapoints to the incorrect examples and look at them. incorrect = [pred for pred in predictions if pred['grade'] == " INCORRECT"] incorrect[0] {'question': 'What did the author write their dissertation on?', 'answer': 'The author wrote their dissertation on applications of continuations.', 'result': ' The author does not mention what their dissertation was on, so it is not known.', 'grade': ' INCORRECT'} previous Evaluating an OpenAPI Chain next Question Answering Benchmarking: State of the Union Address Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/qa_benchmarking_pg.html
34d8f55800b1-0
.ipynb .pdf Data Augmented Question Answering Contents Setup Examples Evaluate Evaluate with Other Metrics Data Augmented Question Answering# This notebook uses some generic prompts/language models to evaluate an question answering system that uses other sources of data besides what is in the model. For example, this can be used to evaluate a question answering system over your proprietary data. Setup# Let’s set up an example with our favorite example - the state of the union address. from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain.llms import OpenAI from langchain.chains import RetrievalQA from langchain.document_loaders import TextLoader loader = TextLoader('../../modules/state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_documents(texts, embeddings) qa = RetrievalQA.from_llm(llm=OpenAI(), retriever=docsearch.as_retriever()) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Examples# Now we need some examples to evaluate. We can do this in two ways: Hard code some examples ourselves Generate examples automatically, using a language model # Hard-coded examples examples = [ { "query": "What did the president say about Ketanji Brown Jackson", "answer": "He praised her legal ability and said he nominated her for the supreme court." }, { "query": "What did the president say about Michael Jackson",
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
34d8f55800b1-1
"query": "What did the president say about Michael Jackson", "answer": "Nothing" } ] # Generated examples from langchain.evaluation.qa import QAGenerateChain example_gen_chain = QAGenerateChain.from_llm(OpenAI()) new_examples = example_gen_chain.apply_and_parse([{"doc": t} for t in texts[:5]]) new_examples [{'query': 'According to the document, what did Vladimir Putin miscalculate?', 'answer': 'He miscalculated that he could roll into Ukraine and the world would roll over.'}, {'query': 'Who is the Ukrainian Ambassador to the United States?', 'answer': 'The Ukrainian Ambassador to the United States is here tonight.'}, {'query': 'How many countries were part of the coalition formed to confront Putin?', 'answer': '27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.'}, {'query': 'What action is the U.S. Department of Justice taking to target Russian oligarchs?', 'answer': 'The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.'}, {'query': 'How much direct assistance is the United States providing to Ukraine?', 'answer': 'The United States is providing more than $1 Billion in direct assistance to Ukraine.'}] # Combine examples examples += new_examples Evaluate# Now that we have examples, we can use the question answering evaluator to evaluate our question answering chain. from langchain.evaluation.qa import QAEvalChain predictions = qa.apply(examples) llm = OpenAI(temperature=0) eval_chain =
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
34d8f55800b1-2
= qa.apply(examples) llm = OpenAI(temperature=0) eval_chain = QAEvalChain.from_llm(llm) graded_outputs = eval_chain.evaluate(examples, predictions) for i, eg in enumerate(examples): print(f"Example {i}:") print("Question: " + predictions[i]['query']) print("Real Answer: " + predictions[i]['answer']) print("Predicted Answer: " + predictions[i]['result']) print("Predicted Grade: " + graded_outputs[i]['text']) print() Example 0: Question: What did the president say about Ketanji Brown Jackson Real Answer: He praised her legal ability and said he nominated her for the supreme court. Predicted Answer: The president said that she 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 said that she is a consensus builder and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by both Democrats and Republicans. Predicted Grade: CORRECT Example 1: Question: What did the president say about Michael Jackson Real Answer: Nothing Predicted Answer: The president did not mention Michael Jackson in this speech. Predicted Grade: CORRECT Example 2: Question: According to the document, what did Vladimir Putin miscalculate? Real Answer: He miscalculated that he could roll into Ukraine and the world would roll over. Predicted Answer: Putin miscalculated that the world would roll over when he rolled into Ukraine. Predicted Grade: CORRECT Example 3: Question: Who is the Ukrainian Ambassador to the United States? Real Answer: The Ukrainian Ambassador to the United States is here tonight. Predicted
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
34d8f55800b1-3
the United States? Real Answer: The Ukrainian Ambassador to the United States is here tonight. Predicted Answer: I don't know. Predicted Grade: INCORRECT Example 4: Question: How many countries were part of the coalition formed to confront Putin? Real Answer: 27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland. Predicted Answer: The coalition included freedom-loving nations from Europe and the Americas to Asia and Africa, 27 members of the European Union including France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland. Predicted Grade: INCORRECT Example 5: Question: What action is the U.S. Department of Justice taking to target Russian oligarchs? Real Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets. Predicted Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and to find and seize their yachts, luxury apartments, and private jets. Predicted Grade: INCORRECT Example 6: Question: How much direct assistance is the United States providing to Ukraine? Real Answer: The United States is providing more than $1 Billion in direct assistance to Ukraine. Predicted Answer: The United States is providing more than $1 billion in direct assistance to Ukraine. Predicted Grade: CORRECT Evaluate with Other Metrics# In addition to predicting whether the answer is correct or incorrect using a language model, we can also use other metrics to get a more nuanced view on the quality of the answers. To do so, we can use the Critique library, which
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
34d8f55800b1-4
on the quality of the answers. To do so, we can use the Critique library, which allows for simple calculation of various metrics over generated text. First you can get an API key from the Inspired Cognition Dashboard and do some setup: export INSPIREDCO_API_KEY="..." pip install inspiredco import inspiredco.critique import os critique = inspiredco.critique.Critique(api_key=os.environ['INSPIREDCO_API_KEY']) Then run the following code to set up the configuration and calculate the ROUGE, chrf, BERTScore, and UniEval (you can choose other metrics too): metrics = { "rouge": { "metric": "rouge", "config": {"variety": "rouge_l"}, }, "chrf": { "metric": "chrf", "config": {}, }, "bert_score": { "metric": "bert_score", "config": {"model": "bert-base-uncased"}, }, "uni_eval": { "metric": "uni_eval", "config": {"task": "summarization", "evaluation_aspect": "relevance"}, }, } critique_data = [ {"target": pred['result'], "references": [pred['answer']]} for pred in predictions ] eval_results = { k: critique.evaluate(dataset=critique_data, metric=v["metric"], config=v["config"]) for k, v in metrics.items() } Finally, we can print out the results. We can see that overall the
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
34d8f55800b1-5
in metrics.items() } Finally, we can print out the results. We can see that overall the scores are higher when the output is semantically correct, and also when the output closely matches with the gold-standard answer. for i, eg in enumerate(examples): score_string = ", ".join([f"{k}={v['examples'][i]['value']:.4f}" for k, v in eval_results.items()]) print(f"Example {i}:") print("Question: " + predictions[i]['query']) print("Real Answer: " + predictions[i]['answer']) print("Predicted Answer: " + predictions[i]['result']) print("Predicted Scores: " + score_string) print() Example 0: Question: What did the president say about Ketanji Brown Jackson Real Answer: He praised her legal ability and said he nominated her for the supreme court. Predicted Answer: The president said that she 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 said that she is a consensus builder and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by both Democrats and Republicans. Predicted Scores: rouge=0.0941, chrf=0.2001, bert_score=0.5219, uni_eval=0.9043 Example 1: Question: What did the president say about Michael Jackson Real Answer: Nothing Predicted Answer: The president did not mention Michael Jackson in this speech. Predicted Scores: rouge=0.0000, chrf=0.1087, bert_score=0.3486, uni_eval=0.7802 Example 2: Question: According to the
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
34d8f55800b1-6
uni_eval=0.7802 Example 2: Question: According to the document, what did Vladimir Putin miscalculate? Real Answer: He miscalculated that he could roll into Ukraine and the world would roll over. Predicted Answer: Putin miscalculated that the world would roll over when he rolled into Ukraine. Predicted Scores: rouge=0.5185, chrf=0.6955, bert_score=0.8421, uni_eval=0.9578 Example 3: Question: Who is the Ukrainian Ambassador to the United States? Real Answer: The Ukrainian Ambassador to the United States is here tonight. Predicted Answer: I don't know. Predicted Scores: rouge=0.0000, chrf=0.0375, bert_score=0.3159, uni_eval=0.7493 Example 4: Question: How many countries were part of the coalition formed to confront Putin? Real Answer: 27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland. Predicted Answer: The coalition included freedom-loving nations from Europe and the Americas to Asia and Africa, 27 members of the European Union including France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland. Predicted Scores: rouge=0.7419, chrf=0.8602, bert_score=0.8388, uni_eval=0.0669 Example 5: Question: What action is the U.S. Department of Justice taking to target Russian oligarchs? Real Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets. Predicted Answer:
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
34d8f55800b1-7
allies to find and seize their yachts, luxury apartments, and private jets. Predicted Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and to find and seize their yachts, luxury apartments, and private jets. Predicted Scores: rouge=0.9412, chrf=0.8687, bert_score=0.9607, uni_eval=0.9718 Example 6: Question: How much direct assistance is the United States providing to Ukraine? Real Answer: The United States is providing more than $1 Billion in direct assistance to Ukraine. Predicted Answer: The United States is providing more than $1 billion in direct assistance to Ukraine. Predicted Scores: rouge=1.0000, chrf=0.9483, bert_score=1.0000, uni_eval=0.9734 previous Benchmarking Template next Using Hugging Face Datasets Contents Setup Examples Evaluate Evaluate with Other Metrics By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/use_cases/evaluation/data_augmented_question_answering.html
d717e38b6462-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 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. We draw this distinction because (1) an index can be used for other things besides retrieval, and (2) retrieval can use other logic besides an index to find relevant documents. We therefore have a concept of a “Retriever” interface - this is the interface that most chains work with. Most of the time when we talk about indexes and retrieval we are talking about indexing and retrieving unstructured data (like text documents). For interacting with structured data (SQL tables, etc) or APIs, please see the corresponding use case sections for links to relevant functionality. The primary index and retrieval types supported by LangChain are currently centered around vector databases, and therefore a lot of the functionality we dive deep on those topics. For an overview of everything related to this, please see the below notebook for getting started: Getting Started We then provide a deep dive on the four main components. Document Loaders How to load documents from a variety of sources. Text Splitters An overview of the abstractions and implementions around splitting text. VectorStores An overview of VectorStores and the many integrations LangChain provides. Retrievers An overview of Retrievers and the implementations LangChain provides. Go Deeper# Document Loaders Text Splitters Vectorstores Retrievers previous Structured Output Parser next Getting Started Contents Go Deeper By Harrison Chase © Copyright 2023, Harrison
https:///langchain-cn.readthedocs.io/en/latest/modules/indexes.html
d717e38b6462-1
Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/indexes.html
d6838a5d7490-0
.rst .pdf Prompts Contents 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 construction of this input. LangChain provides several classes and functions to make constructing and working with prompts easy. This section of documentation is split into four sections: LLM Prompt Templates How to use PromptTemplates to prompt Language Models. Chat Prompt Templates How to use PromptTemplates to prompt Chat Models. Example Selectors Often times it is useful to include examples in prompts. These examples can be hardcoded, but it is often more powerful if they are dynamically selected. This section goes over example selection. Output Parsers Language models (and Chat Models) output text. But many times you may want to get more structured information than just text back. This is where output parsers come in. Output Parsers are responsible for (1) instructing the model how output should be formatted, (2) parsing output into the desired formatting (including retrying if necessary). Go Deeper# Prompt Templates Chat Prompt Template Example Selectors Output Parsers previous TensorflowHub next Prompt Templates Contents Go Deeper By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/prompts.html
9a60f52f0dbb-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 use. The following sections of documentation are provided: Getting Started: A getting started guide for chains, to get you up and running quickly. How-To Guides: A collection of how-to guides. These highlight how to use various types of chains. Reference: API reference documentation for all Chain classes. previous Redis Chat Message History next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/chains.html
dc530fb67853-0
.rst .pdf Agents Contents Go Deeper 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 a suite of tools. Depending on the user input, the agent can then decide which, if any, of these tools to call. In this section of documentation, we first start with a Getting Started notebook to cover how to use all things related to agents in an end-to-end manner. We then split the documentation into the following sections: Tools An overview of the various tools LangChain supports. Agents An overview of the different agent types. Toolkits An overview of toolkits, and examples of the different ones LangChain supports. Agent Executor An overview of the Agent Executor class and examples of how to use it. Go Deeper# Tools Agents Toolkits Agent Executors previous Chains next Getting Started Contents Go Deeper By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/agents.html
27e613effbc8-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 short term but also at a long term level. The concept of “Memory” exists to do exactly that. LangChain provides memory components in two forms. First, LangChain provides helper utilities for managing and manipulating previous chat messages. These are designed to be modular and useful regardless of how they are used. Secondly, LangChain provides easy ways to incorporate these utilities into chains. The following sections of documentation are provided: Getting Started: An overview of how to get started with different types of memory. How-To Guides: A collection of how-to guides. These highlight different types of memory, as well as how to use memory in chains. Memory Getting Started How-To Guides previous Weaviate Hybrid Search next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory.html
7e0981a27695-0
.rst .pdf Models(模型) Contents 深入了解 Models(模型)# 这份文档的这一部分涉及到 LangChain 中使用的不同类型的模型。在本页中,我们将高层次地讨论这些模型类型,同时我们也会为每个模型类型单独创建页面。 这些页面包含更详细的关于如何使用该模型的指南,以及不同模型提供商的列表。 LLMs 大型语言模型(LLMs)是我们涵盖的第一种模型类型。这些模型以文本串作为输入,并返回文本串作为输出。 Chat Models 聊天模型是我们涵盖的第二种模型类型。这些模型通常由语言模型支持,但它们的 API 更为结构化。具体而言,这些模型以聊天消息列表作为输入,并返回聊天消息。 Text Embedding Models 我们涵盖的第三种模型类型是文本嵌入模型。这些模型以文本作为输入,并返回一个浮点数列表。 深入了解# LLMs (大语言模型) Chat Models Text Embedding Models previous 入门指南 next LLMs (大语言模型) Contents 深入了解 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/models.html
f032a03c5d19-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 ConversationTokenBufferMemory VectorStore-Backed Memory Usage# The examples here all highlight how to use memory in different ways. 如何给 LLM Chain(大语言模型链)添加 Memeory(记忆) How to add memory to a Multi-Input Chain How to add Memory to an Agent 给Agent(代理)添加由数据库支持的消息存储 How to customize conversational memory How to create a custom Memory class Motörhead Memory How to use multiple memory classes in the same chain Postgres Chat Message History Redis Chat Message History previous Getting Started next ConversationBufferMemory Contents Types Usage By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/how_to_guides.html
0a12c0e459b1-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 interactions with a language model are captured in the concept of ChatMessages, so this boils down to ingesting, capturing, transforming and extracting knowledge from a sequence of chat messages. There are many different ways to do this, each of which exists as its own memory type. In general, for each type of memory there are two ways to understanding using memory. These are the standalone functions which extract information from a sequence of messages, and then there is the way you can use this type of memory in a chain. Memory can return multiple pieces of information (for example, the most recent N messages and a summary of all previous messages). The returned information can either be a string or a list of messages. In this notebook, we will walk through the simplest form of memory: “buffer” memory, which just involves keeping a buffer of all prior messages. We will show how to use the modular utility functions here, then show how it can be used in a chain (both returning a string as well as a list of messages). ChatMessageHistory# One of the core utility classes underpinning most (if not all) memory modules is the ChatMessageHistory class. This is a super lightweight wrapper which exposes convienence methods for saving Human messages, AI messages, and then fetching them all. You may want to use this class directly if you are managing memory outside of a chain. from langchain.memory import ChatMessageHistory history = ChatMessageHistory() history.add_user_message("hi!") history.add_ai_message("whats up?") history.messages [HumanMessage(content='hi!', additional_kwargs={}), AIMessage(content='whats up?',
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/getting_started.html
0a12c0e459b1-1
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 messages in a variable. We can first extract it as a string. from langchain.memory import ConversationBufferMemory memory = ConversationBufferMemory() memory.chat_memory.add_user_message("hi!") memory.chat_memory.add_ai_message("whats up?") memory.load_memory_variables({}) {'history': 'Human: hi!\nAI: whats up?'} We can also get the history as a list of messages memory = ConversationBufferMemory(return_messages=True) memory.chat_memory.add_user_message("hi!") memory.chat_memory.add_ai_message("whats up?") memory.load_memory_variables({}) {'history': [HumanMessage(content='hi!', additional_kwargs={}), AIMessage(content='whats up?', additional_kwargs={})]} Using in a chain# Finally, let’s take a look at using this in a chain (setting verbose=True so we can see the prompt). from langchain.llms import OpenAI from langchain.chains import ConversationChain llm = OpenAI(temperature=0) conversation = ConversationChain( llm=llm, verbose=True, memory=ConversationBufferMemory() ) 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 context. If the AI does not know the answer to a question, it truthfully says it does not know. 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/getting_started.html
0a12c0e459b1-2
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 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 there! AI: Hi there! It's nice to meet you. How can I help you today? Human: I'm doing well! Just having a conversation with an AI. AI: > Finished chain. " That's great! It's always nice to have a conversation with someone new. What would you like to talk about?" conversation.predict(input="Tell me about yourself.") > 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: Human: Hi there! AI: Hi there! It's nice to meet you. How can I help you today? Human: I'm doing well! Just having a conversation with an AI. AI: That's great! It's always nice to have a conversation with someone new. What would you like to talk about? 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 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/getting_started.html
0a12c0e459b1-3
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 ChatMessageHistory from langchain.schema import messages_from_dict, messages_to_dict history = ChatMessageHistory() history.add_user_message("hi!") history.add_ai_message("whats up?") dicts = messages_to_dict(history.messages) dicts [{'type': 'human', 'data': {'content': 'hi!', 'additional_kwargs': {}}}, {'type': 'ai', 'data': {'content': 'whats up?', 'additional_kwargs': {}}}] new_messages = messages_from_dict(dicts) new_messages [HumanMessage(content='hi!', additional_kwargs={}), AIMessage(content='whats up?', additional_kwargs={})] 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 Memory next How-To Guides Contents ChatMessageHistory ConversationBufferMemory Using in a chain Saving Message History By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/getting_started.html
30bd455dc3d8-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 the buffer does not get too large Let’s first explore the basic functionality of this type of memory. from langchain.memory import ConversationBufferWindowMemory memory = ConversationBufferWindowMemory( k=1) memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.save_context({"input": "not much you"}, {"ouput": "not much"}) memory.load_memory_variables({}) {'history': 'Human: not much you\nAI: not much'} We can also get the history as a list of messages (this is useful if you are using this with a chat model). memory = ConversationBufferWindowMemory( k=1, return_messages=True) memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.save_context({"input": "not much you"}, {"ouput": "not much"}) memory.load_memory_variables({}) {'history': [HumanMessage(content='not much you', additional_kwargs={}), AIMessage(content='not much', additional_kwargs={})]} Using in a chain# Let’s walk through an example, again setting verbose=True so we can see the prompt. from langchain.llms import OpenAI from langchain.chains import ConversationChain conversation_with_summary = ConversationChain( llm=OpenAI(temperature=0), # We set a low k=2, to only keep the last 2 interactions in memory memory=ConversationBufferWindowMemory(k=2), verbose=True ) conversation_with_summary.predict(input="Hi, what's up?") > Entering new ConversationChain chain... Prompt
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/buffer_window.html
30bd455dc3d8-1
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, it truthfully says it does not know. Current conversation: Human: Hi, what's up? AI: > Finished chain. " Hi there! I'm doing great. I'm currently helping a customer with a technical issue. How about you?" conversation_with_summary.predict(input="What's their issues?") > 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: 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: > Finished chain. " The customer is having trouble connecting to their Wi-Fi network. I'm helping them troubleshoot the issue and get them connected." conversation_with_summary.predict(input="Is it going well?") > 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: 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:
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/buffer_window.html
30bd455dc3d8-2
their Wi-Fi network. I'm helping them troubleshoot the issue and get them connected. Human: Is it going well? AI: > Finished chain. " Yes, it's going well so far. We've already identified the problem and are now working on a solution." # Notice here that the first interaction does not appear. conversation_with_summary.predict(input="What's the solution?") > 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: 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: Yes, it's going well so far. We've already identified the problem and are now working on a solution. Human: What's the solution? AI: > Finished chain. " The solution is to reset the router and reconfigure the settings. We're currently in the process of doing that." previous ConversationBufferMemory next Entity Memory Contents Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/buffer_window.html
cce87b97358b-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). Let’s first walk through using this functionality. from langchain.llms import OpenAI from langchain.memory import ConversationEntityMemory llm = OpenAI(temperature=0) memory = ConversationEntityMemory(llm=llm) _input = {"input": "Deven & Sam are working on a hackathon project"} memory.load_memory_variables(_input) memory.save_context( _input, {"ouput": " That sounds like a great project! What kind of project are they working on?"} ) memory.load_memory_variables({"input": 'who is Sam'}) {'history': 'Human: Deven & Sam are working on a hackathon project\nAI: That sounds like a great project! What kind of project are they working on?', 'entities': {'Sam': 'Sam is working on a hackathon project with Deven.'}} memory = ConversationEntityMemory(llm=llm, return_messages=True) _input = {"input": "Deven & Sam are working on a hackathon project"} memory.load_memory_variables(_input) memory.save_context( _input, {"ouput": " That sounds like a great project! What kind of project are they working on?"} ) memory.load_memory_variables({"input": 'who is Sam'}) {'history': [HumanMessage(content='Deven & Sam are working on a hackathon project', additional_kwargs={}), AIMessage(content=' That sounds like a great project! What kind of project are they working on?', additional_kwargs={})], 'entities': {'Sam': 'Sam is working on a hackathon
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-1
additional_kwargs={})], 'entities': {'Sam': 'Sam is working on a hackathon project with Deven.'}} Using in a chain# Let’s now use it in a chain! from langchain.chains import ConversationChain from langchain.memory import ConversationEntityMemory from langchain.memory.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE from pydantic import BaseModel from typing import List, Dict, Any conversation = ConversationChain( llm=llm, verbose=True, prompt=ENTITY_MEMORY_CONVERSATION_TEMPLATE, memory=ConversationEntityMemory(llm=llm) ) conversation.predict(input="Deven & Sam are working on a hackathon project") > 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 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 conversations and provide responses that are coherent and relevant to the topic at hand. 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 human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics. 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-2
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': '', 'Sam': ''} Current conversation: Last line: Human: Deven & Sam are working on a hackathon project You: > Finished chain. ' That sounds like a great project! What kind of project are they working on?' conversation.memory.store {'Deven': 'Deven is working on a hackathon project with Sam.', 'Sam': 'Sam is working on a hackathon project with Deven.'} conversation.predict(input="They are trying to add more complex memory structures to Langchain") > 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 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 conversations and provide responses that are coherent and relevant to the topic at hand. 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 human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics. 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-3
with a specific question or just wants to have a conversation about a particular topic, you are here to assist. Context: {'Deven': 'Deven is working on a hackathon project with Sam.', 'Sam': 'Sam is working on a hackathon project with Deven.', 'Langchain': ''} Current conversation: Human: Deven & Sam are working on a hackathon project AI: That sounds like a great project! What kind of project are they working on? Last line: Human: They are trying to add more complex memory structures to Langchain You: > Finished chain. ' That sounds like an interesting project! What kind of memory structures are they trying to add?' conversation.predict(input="They are adding in a key-value store for entities mentioned so far in the conversation.") > 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 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 conversations and provide responses that are coherent and relevant to the topic at hand. 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 human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics. 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-4
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 working on a hackathon project with Sam, attempting to add more complex memory structures to Langchain.', 'Sam': 'Sam is working on a hackathon project with Deven, trying to add more complex memory structures to Langchain.', 'Langchain': 'Langchain is a project that is trying to add more complex memory structures.', 'Key-Value Store': ''} Current conversation: Human: Deven & Sam are working on a hackathon project 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 entities mentioned so far in the conversation. You: > Finished chain. ' That sounds like a great idea! How will the key-value store work?' conversation.predict(input="What do you know about Deven & 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 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 conversations and provide responses that are coherent and relevant to the topic at hand. 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-5
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 human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics. 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 working on a hackathon project with Sam, attempting 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 add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the conversation.'} Current conversation: Human: Deven & Sam are working on a hackathon project 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? Human: They are adding in a key-value store for entities mentioned so far in the conversation. AI: That sounds like a great idea! How will the key-value store work? Last line: Human: What do you know about Deven & Sam? You: > Finished chain. ' Deven and Sam are working on a hackathon project together, attempting to add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the conversation.' Inspecting the memory store# We can also
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-6
store for entities mentioned so far in the conversation.' Inspecting the memory store# We can also inspect the memory store directly. In the following examaples, we look at it directly, and then go through some examples of adding information and watch how it changes. from pprint import pprint pprint(conversation.memory.store) {'Deven': 'Deven is working on a hackathon project with Sam, attempting to add ' 'more complex memory structures to Langchain, including a key-value ' 'store for entities mentioned so far in the conversation.', 'Key-Value Store': 'A key-value store that stores entities mentioned in the ' 'conversation.', 'Langchain': 'Langchain is a project that is trying to add more complex ' '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, attempting to add ' 'more complex memory structures to Langchain, including a key-value ' 'store for entities mentioned so far in the conversation.'} conversation.predict(input="Sam is the founder of a company called Daimon.") > 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 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-7
you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand. 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 human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics. 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: {'Daimon': '', 'Sam': 'Sam is working on a hackathon project with Deven to add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the conversation.'} Current conversation: 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? Human: They are adding in a key-value store for entities mentioned so far in the conversation. AI: That sounds like a great idea! How will the key-value store work? Human: What do you know about Deven & Sam? AI: Deven and Sam are working on a hackathon project 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 very motivated and passionate about their project, and are working hard to make it a success. Last line: Human: Sam is the founder of a company called
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-8
hard to make it a success. Last line: Human: Sam is the founder of a company called Daimon. You: > Finished chain. "\nThat's impressive! It sounds like Sam is a very successful entrepreneur. What kind of company is Daimon?" from pprint import pprint pprint(conversation.memory.store) {'Daimon': 'Daimon is a company founded by Sam.', 'Deven': 'Deven is working on a hackathon project with Sam to add more ' 'complex memory structures to Langchain, including a key-value store ' 'for entities mentioned so far in the conversation.', 'Key-Value Store': 'Key-Value Store: A data structure that stores values ' 'associated with a unique key, allowing for efficient ' 'retrieval of values. Deven and Sam are adding a key-value ' 'store for entities mentioned so far in the conversation.', 'Langchain': 'Langchain is a project that seeks to add more complex 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 to add more complex ' 'memory structures to Langchain, including a key-value store for ' 'entities mentioned so far in the conversation. He is also the founder ' 'of a company called
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-9
conversation. He is also the founder ' 'of a 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 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 conversations and provide responses that are coherent and relevant to the topic at hand. 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 human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics. 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: {'Sam': 'Sam is working on a hackathon project with Deven to add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the conversation. He is also the founder of a company called Daimon.', 'Daimon': 'Daimon is a company founded by Sam.'} Current conversation: Human: They are adding in a key-value store for entities mentioned so far in the conversation. AI: That sounds like a great idea! How will
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
cce87b97358b-10
entities mentioned so far in the conversation. AI: That sounds like a great idea! How will the key-value store work? Human: What do you know about Deven & Sam? AI: Deven and Sam are working on a hackathon project 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 very motivated and passionate about their project, and are working hard to make it a success. Human: Sam is the founder of a company called Daimon. AI: That's impressive! It sounds like Sam is a very successful entrepreneur. What kind of company is Daimon? Last line: Human: What do you know about Sam? You: > Finished chain. ' Sam is the founder of a company called Daimon. He is also working on a hackathon project with Deven to add more complex memory structures to Langchain, including a key-value store for entities mentioned so far in the conversation. He seems to be very motivated and passionate about his project, and is working hard to make it a success.' previous ConversationBufferWindowMemory next Conversation Knowledge Graph Memory Contents Using in a chain Inspecting the memory store By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/entity_summary_memory.html
7d2e24426207-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 utilities from langchain.memory import ConversationTokenBufferMemory from langchain.llms import OpenAI llm = OpenAI() memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=10) memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.save_context({"input": "not much you"}, {"ouput": "not much"}) memory.load_memory_variables({}) {'history': 'Human: not much you\nAI: not much'} We can also get the history as a list of messages (this is useful if you are using this with a chat model). memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=10, return_messages=True) memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.save_context({"input": "not much you"}, {"ouput": "not much"}) Using in a chain# Let’s walk through an example, again setting verbose=True so we can see the prompt. 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=ConversationTokenBufferMemory(llm=OpenAI(), max_token_limit=60), 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 its context. If the
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/token_buffer.html
7d2e24426207-1
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 great, just enjoying the day. How about you?" conversation_with_summary.predict(input="Just working on writing some documentation!") > 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: Human: Hi, what's up? AI: Hi there! I'm doing great, just enjoying the day. How about you? Human: Just working on writing some documentation! AI: > Finished chain. ' Sounds like a productive day! What kind of documentation are you writing?' conversation_with_summary.predict(input="For LangChain! Have you heard of it?") > 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: Human: Hi, what's up? AI: Hi there! I'm doing great, just enjoying the day. How about you? Human: Just working on writing some documentation! 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 writing about?" # We
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/token_buffer.html
7d2e24426207-2
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 of people confuse it for that") > 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: Human: For LangChain! Have you heard of it? AI: 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? Human: Haha nope, although a lot of people confuse it for that AI: > Finished chain. " Oh, I see. Is there another language learning platform you're referring to?" previous ConversationSummaryBufferMemory next VectorStore-Backed Memory Contents Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/token_buffer.html
c3f45564a089-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 other Memory classes in that it doesn’t explicitly track the order of interactions. from datetime import datetime from langchain.embeddings.openai import OpenAIEmbeddings from langchain.llms import OpenAI from langchain.memory import VectorStoreRetrieverMemory from langchain.chains import ConversationChain Initialize your VectorStore# Depending on the store you choose, this step may look different. Consult the relevant VectorStore documentation for more details. import faiss from langchain.docstore import InMemoryDocstore from langchain.vectorstores import FAISS embedding_size = 1536 # Dimensions of the OpenAIEmbeddings index = faiss.IndexFlatL2(embedding_size) embedding_fn = OpenAIEmbeddings().embed_query vectorstore = FAISS(embedding_fn, index, InMemoryDocstore({}), {}) Create your the VectorStoreRetrieverMemory# The memory object is instantiated from any VectorStoreRetriever. # In actual usage, you would set `k` to be a higher value, but we use k=1 to show that # the vector lookup still returns the semantically relevant information retriever = vectorstore.as_retriever(search_kwargs=dict(k=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": "check the latest scores of the Warriors game"}, {"output": "the Warriors are up against the Astros 88 to
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/vectorstore_retriever_memory.html
c3f45564a089-1
scores of the Warriors game"}, {"output": "the Warriors are up against the Astros 88 to 84"}) memory.save_context({"input": "I need help doing my taxes - what's the standard deduction this year?"}, {"output": "..."}) memory.save_context({"input": "What's the the time?"}, {"output": f"It's {datetime.now()}"}) # # Notice the first result returned is the memory pertaining to tax help, which the language model deems more semantically relevant # to a 1099 than the other documents, despite them both containing numbers. print(memory.load_memory_variables({"prompt": "What's a 1099?"})["history"]) input: I need help doing my taxes - what's the standard deduction this year? output: ... Using in a chain# Let’s walk through an example, again setting verbose=True so we can see the prompt. llm = OpenAI(temperature=0) # Can be any valid LLM conversation_with_summary = ConversationChain( llm=llm, # We set a very low max_token_limit for the purposes of testing. 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. If the AI does not know the answer to a question, it truthfully says it does not know. Current conversation: input: I need help doing my taxes - what's the standard deduction this year? output: ... Human: Hi, my name is Perry, what's up? AI: > Finished chain. " Hi Perry, my name is AI. I'm doing great, how about you? I understand you need help with your taxes. What
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/vectorstore_retriever_memory.html
c3f45564a089-2
I'm doing great, how about you? I understand you need help with your taxes. What specifically do you need help with?" # Here, the basketball related content is surfaced conversation_with_summary.predict(input="If the Cavaliers were to face off against the Warriers or the Astros, who would they most stand a chance to beat?") > 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: input: check the latest scores of the Warriors game output: the Warriors are up against the Astros 88 to 84 Human: If the Cavaliers were to face off against the Warriers or the Astros, who would they most stand a chance to beat? AI: > Finished chain. " It's hard to say without knowing the current form of the teams. However, based on the current scores, it looks like the Cavaliers would have a better chance of beating the Astros than the Warriors." # Even though the language model is stateless, since relavent memory is fetched, it can "reason" about the time. # Timestamping memories and data is useful in general to let the agent determine temporal relevance conversation_with_summary.predict(input="What day is it tomorrow?") > 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: input: What's the the time? output: It's 2023-04-13 09:18:55.623736 Human: What day is it tomorrow? AI: > Finished chain. ' Tomorrow is
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/vectorstore_retriever_memory.html
c3f45564a089-3
What day is it tomorrow? AI: > Finished chain. ' Tomorrow is 2023-04-14.' # The memories from the conversation are automatically stored, # since this query best matches the introduction chat above, # the agent is able to 'remember' the user's name. conversation_with_summary.predict(input="What's your name?") > 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: input: Hi, my name is Perry, what's up? response: Hi Perry, my name is AI. I'm doing great, how about you? I understand you need help with your taxes. What specifically do you need help with? Human: What's your name? AI: > Finished chain. " My name is AI. It's nice to meet you, Perry." previous ConversationTokenBufferMemory next 如何给 LLM Chain(大语言模型链)添加 Memeory(记忆) Contents Initialize your VectorStore Create your the VectorStoreRetrieverMemory Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/vectorstore_retriever_memory.html
3f36fa3d4155-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 both. Unlike the previous implementation though, it uses token length rather than number of interactions to determine when to flush interactions. Let’s first walk through how to use the utilities from langchain.memory import ConversationSummaryBufferMemory from langchain.llms import OpenAI llm = OpenAI() memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=10) memory.save_context({"input": "hi"}, {"output": "whats up"}) memory.save_context({"input": "not much you"}, {"output": "not much"}) memory.load_memory_variables({}) {'history': 'System: \nThe human says "hi", and the AI responds with "whats up".\nHuman: not much you\nAI: not much'} We can also get the history as a list of messages (this is useful if you are using this with a chat model). memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=10, return_messages=True) memory.save_context({"input": "hi"}, {"output": "whats up"}) memory.save_context({"input": "not much you"}, {"output": "not much"}) We can also utilize the predict_new_summary method directly. messages = memory.chat_memory.messages previous_summary = "" memory.predict_new_summary(messages, previous_summary) '\nThe human and AI state that they are not doing much.' Using in a chain# Let’s walk through an example, again setting verbose=True so we can see the prompt. from langchain.chains import ConversationChain conversation_with_summary = ConversationChain( llm=llm, # We set a very low
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/summary_buffer.html
3f36fa3d4155-1
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 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 great. I'm learning about the latest advances in artificial intelligence. What about you?" conversation_with_summary.predict(input="Just working on writing some documentation!") > 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: Human: Hi, what's up? AI: Hi there! I'm doing great. I'm spending some time learning about the latest developments in AI technology. How about you? Human: Just working on writing some documentation! AI: > Finished chain. ' That sounds like a great use of your time. Do you have experience with writing documentation?' # We can see here that there is a summary of the conversation and then some previous interactions conversation_with_summary.predict(input="For LangChain! Have you heard of it?") > 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/summary_buffer.html
3f36fa3d4155-2
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 responded that it was learning about the latest developments in AI technology. Human: Just working on writing some documentation! AI: That sounds like a great use of your time. Do you have experience with writing documentation? Human: For LangChain! Have you heard of it? AI: > Finished chain. " No, I haven't heard of LangChain. Can you tell me more about it?" # We can see here that the summary and the buffer are updated conversation_with_summary.predict(input="Haha nope, although a lot of people confuse it for that") > 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: System: The human asked the AI what it was up to and the AI responded that it was learning about the latest developments in AI technology. The human then mentioned they were writing documentation, to which the AI responded that it sounded like a great use of their time and asked if they had experience with writing documentation. Human: For LangChain! Have you heard of it? AI: No, I haven't heard of LangChain. Can you tell me more about it? Human: Haha nope, although a lot of people confuse it for that AI: > Finished chain. ' Oh, okay. What is LangChain?' previous ConversationSummaryMemory next ConversationTokenBufferMemory Contents Using in a chain By Harrison Chase ©
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/summary_buffer.html
3f36fa3d4155-3
Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/summary_buffer.html
221059de4e26-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 = OpenAI(temperature=0) memory = ConversationKGMemory(llm=llm) memory.save_context({"input": "say hi to sam"}, {"ouput": "who is sam"}) memory.save_context({"input": "sam is a friend"}, {"ouput": "okay"}) memory.load_memory_variables({"input": 'who is sam'}) {'history': 'On Sam: Sam is friend.'} We can also get the history as a list of messages (this is useful if you are using this with a chat model). memory = ConversationKGMemory(llm=llm, return_messages=True) memory.save_context({"input": "say hi to sam"}, {"ouput": "who is sam"}) memory.save_context({"input": "sam is a friend"}, {"ouput": "okay"}) memory.load_memory_variables({"input": 'who is sam'}) {'history': [SystemMessage(content='On Sam: Sam is friend.', additional_kwargs={})]} We can also more modularly get current entities from a new message (will use previous messages as context.) memory.get_current_entities("what's Sams favorite color?") ['Sam'] We can also more modularly get knowledge triplets from a new message (will use previous messages as context.) memory.get_knowledge_triplets("her favorite color is red") [KnowledgeTriple(subject='Sam', predicate='favorite color', object_='red')] Using in a chain# 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/kg.html
221059de4e26-1
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 truthfully says it does not know. The AI ONLY uses information contained in the "Relevant Information" section and does not hallucinate. Relevant Information: {history} Conversation: Human: {input} AI:""" prompt = PromptTemplate( input_variables=["history", "input"], template=template ) conversation_with_kg = ConversationChain( llm=llm, verbose=True, prompt=prompt, memory=ConversationKGMemory(llm=llm) ) conversation_with_kg.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, it truthfully says it does not know. The AI ONLY uses information contained in the "Relevant Information" section and does not hallucinate. Relevant Information: Conversation: Human: Hi, what's up? AI: > Finished chain. " Hi there! I'm doing great. I'm currently in the process of learning about the world around me. I'm learning about different cultures, languages, and customs. It's really fascinating! How about you?" conversation_with_kg.predict(input="My name is James and I'm helping Will. He's an engineer.") > 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,
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/kg.html
221059de4e26-2
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 not hallucinate. Relevant Information: Conversation: Human: My name is James and I'm helping Will. He's an engineer. AI: > Finished chain. " Hi James, it's nice to meet you. I'm an AI and I understand you're helping Will, the engineer. What kind of engineering does he do?" conversation_with_kg.predict(input="What do you know about Will?") > 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 information contained in the "Relevant Information" section and does not hallucinate. Relevant Information: On Will: Will is an engineer. Conversation: Human: What do you know about Will? AI: > Finished chain. ' Will is an engineer.' previous Entity Memory next ConversationSummaryMemory Contents Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/kg.html
62ce5d0545e7-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 ConversationBufferMemory memory = ConversationBufferMemory() memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.load_memory_variables({}) {'history': 'Human: hi\nAI: whats up'} We can also get the history as a list of messages (this is useful if you are using this with a chat model). memory = ConversationBufferMemory(return_messages=True) memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.load_memory_variables({}) {'history': [HumanMessage(content='hi', additional_kwargs={}), AIMessage(content='whats up', additional_kwargs={})]} Using in a chain# Finally, let’s take a look at using this in a chain (setting verbose=True so we can see the prompt). from langchain.llms import OpenAI from langchain.chains import ConversationChain llm = OpenAI(temperature=0) conversation = ConversationChain( llm=llm, verbose=True, memory=ConversationBufferMemory() ) 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 context. If the AI does not know the answer to a question, it truthfully says it does not know. 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.") >
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/buffer.html
62ce5d0545e7-1
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 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 there! AI: Hi there! It's nice to meet you. How can I help you today? Human: I'm doing well! Just having a conversation with an AI. AI: > Finished chain. " That's great! It's always nice to have a conversation with someone new. What would you like to talk about?" conversation.predict(input="Tell me about yourself.") > 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: Human: Hi there! AI: Hi there! It's nice to meet you. How can I help you today? Human: I'm doing well! Just having a conversation with an AI. AI: That's great! It's always nice to have a conversation with someone new. What would you like to talk about? Human: Tell me about yourself. AI: > Finished chain. " Sure! I'm an AI created to help people with their everyday tasks. I'm programmed to understand natural language and provide helpful information. I'm also constantly learning and updating my knowledge base so I can provide more accurate and helpful answers." And 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/buffer.html
62ce5d0545e7-2
all previous How-To Guides next ConversationBufferWindowMemory Contents Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/buffer.html
6c60ac1220e7-0
.ipynb .pdf ConversationSummaryMemory Contents Using in a chain ConversationSummaryMemory# Now let’s take a look at using a slightly more complex type of memory - ConversationSummaryMemory. This type of memory creates a summary of the conversation over time. This can be useful for condensing information from the conversation over time. Let’s first explore the basic functionality of this type of memory. from langchain.memory import ConversationSummaryMemory from langchain.llms import OpenAI memory = ConversationSummaryMemory(llm=OpenAI(temperature=0)) memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.load_memory_variables({}) {'history': '\nThe human greets the AI, to which the AI responds.'} We can also get the history as a list of messages (this is useful if you are using this with a chat model). memory = ConversationSummaryMemory(llm=OpenAI(temperature=0), return_messages=True) memory.save_context({"input": "hi"}, {"ouput": "whats up"}) memory.load_memory_variables({}) {'history': [SystemMessage(content='\nThe human greets the AI, to which the AI responds.', additional_kwargs={})]} We can also utilize the predict_new_summary method directly. messages = memory.chat_memory.messages previous_summary = "" memory.predict_new_summary(messages, previous_summary) '\nThe human greets the AI, to which the AI responds.' Using in a chain# Let’s walk through an example of using this in a chain, again setting verbose=True so we can see the prompt. from langchain.llms import OpenAI from langchain.chains import ConversationChain llm = OpenAI(temperature=0) conversation_with_summary = ConversationChain( llm=llm, memory=ConversationSummaryMemory(llm=OpenAI()), verbose=True ) conversation_with_summary.predict(input="Hi, what's
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/summary.html
6c60ac1220e7-1
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 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 great. I'm currently helping a customer with a technical issue. How about you?" conversation_with_summary.predict(input="Tell me more about it!") > 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: The human greeted the AI and asked how it was doing. The AI replied that it was doing great and was currently helping a customer with a technical issue. Human: Tell me more about it! AI: > Finished chain. " 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 solutions." conversation_with_summary.predict(input="Very cool -- what is the scope of the project?") > 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: The human greeted the AI and asked how it was doing. The AI
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/summary.html
6c60ac1220e7-2
not know. Current conversation: The human greeted the AI and asked how it was doing. The AI replied that it was doing great and was currently helping a customer with a technical issue where their computer was not connecting to the internet. The AI was troubleshooting the issue and had already tried resetting the router and checking the network settings, but the issue still persisted and they were looking into other possible solutions. Human: Very cool -- what is the scope of the project? AI: > Finished chain. " The scope of the project is to troubleshoot the customer's computer issue and find a solution that will allow them to connect to the internet. We are currently exploring different possibilities and have already tried resetting the router and checking the network settings, but the issue still persists." previous Conversation Knowledge Graph Memory next ConversationSummaryBufferMemory Contents Using in a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/types/summary.html
4fede05c140d-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 an agent we are going to the the following steps: We are going to create an LLMChain with memory. We are going to use that LLMChain to create a custom Agent. For the purposes of this exercise, we are going to create a simple custom Agent that has access to a search tool and utilizes the ConversationBufferMemory class. from langchain.agents import ZeroShotAgent, Tool, AgentExecutor from langchain.memory import ConversationBufferMemory from langchain import OpenAI, LLMChain from langchain.utilities import GoogleSearchAPIWrapper search = GoogleSearchAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] Notice the usage of the chat_history variable in the PromptTemplate, which matches up with the dynamic key name in the ConversationBufferMemory. prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:""" suffix = """Begin!" {chat_history} Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "chat_history", "agent_scratchpad"] ) memory = ConversationBufferMemory(memory_key="chat_history") We can now construct the LLMChain, with the Memory
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory.html
4fede05c140d-1
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=memory) agent_chain.run(input="How many people live in canada?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada 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's Population and Demography Portal. Population of Canada (real- ... Index to the latest information from the Census of Population. This survey conducted by Statistics Canada provides a statistical portrait of Canada and its ... 14 records ... Estimated number of persons by quarter of a year and by year, Canada, provinces and territories. The 2021 Canadian census counted a total population of 36,991,981, an increase of around 5.2 percent over the 2016 figure. ... Between 1990 and 2008, the ... ( 2 ) Census reports and other statistical publications from national statistical offices, ( 3 ) Eurostat: Demographic Statistics, ( 4 ) United Nations ... Canada is a country in North America. Its ten provinces and three territories extend from ... Population. • Q4 2022 estimate. 39,292,355 (37th). Information is available for the total Indigenous population and each of the three ... The term 'Aboriginal' or 'Indigenous' used on the Statistics Canada ... Jun
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory.html
4fede05c140d-2
... The term 'Aboriginal' or 'Indigenous' used on the Statistics Canada ... Jun 14, 2022 ... Determinants of health are the broad range of personal, social, economic and environmental factors that determine individual and population ... COVID-19 vaccination coverage across Canada by demographics and key populations. Updated every Friday at 12:00 PM Eastern Time. Thought: I now know the final answer Final Answer: 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. > 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 correctly. agent_chain.run(input="what is their national anthem called?") > Entering new AgentExecutor chain... Thought: I need to find out what the national anthem of Canada is called. 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 in 1980. The music for O Canada was composed in 1880 by Calixa ... O Canada, national anthem of Canada. It was proclaimed the official national anthem on July 1, 1980. “God Save the Queen” remains the royal anthem of Canada ... O Canada! Our home and native land! True patriot love in all of us command. Car ton bras sait porter l'épée,. Il
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory.html
4fede05c140d-3
patriot love in all of us command. Car ton bras sait porter l'épée,. Il sait porter la croix! "O Canada" (French: Ô Canada) is the national anthem of Canada. The song was originally commissioned by Lieutenant Governor of Quebec Théodore Robitaille ... Feb 1, 2018 ... It was a simple tweak — just two words. But with that, Canada just voted to make its national anthem, “O Canada,” gender neutral, ... "O Canada" was proclaimed Canada's national anthem on July 1,. 1980, 100 years after it was first sung on June 24, 1880. The music. Patriotic music in Canada dates back over 200 years as a distinct category from British or French patriotism, preceding the first legal steps to ... Feb 4, 2022 ... English version: O Canada! Our home and native land! True patriot love in all of us command. With glowing hearts we ... Feb 1, 2018 ... Canada's Senate has passed a bill making the country's national anthem gender-neutral. If you're not familiar with the words to “O Canada,” ... 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 of Canada’s national anthem was. For fun, let’s compare this to an agent that does NOT have memory. prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:""" suffix = """Begin!" Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix,
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory.html
4fede05c140d-4
ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "agent_scratchpad"] ) llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True) agent_without_memory = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_without_memory.run("How many people live in canada?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada 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's Population and Demography Portal. Population of Canada (real- ... Index to the latest information from the Census of Population. This survey conducted by Statistics Canada provides a statistical portrait of Canada and its ... 14 records ... Estimated number of persons by quarter of a year and by year, Canada, provinces and territories. The 2021 Canadian census counted a total population of 36,991,981, an increase of around 5.2 percent over the 2016 figure. ... Between 1990 and 2008, the ... ( 2 ) Census reports and other statistical publications from national statistical offices, ( 3 ) Eurostat: Demographic Statistics, ( 4 ) United Nations ... Canada is a country in North America. Its ten provinces and three territories extend from ... Population. • Q4 2022 estimate. 39,292,355 (37th). Information is available for the total Indigenous population and each of the
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory.html
4fede05c140d-5
(37th). Information is available for the total Indigenous population and each of the three ... The term 'Aboriginal' or 'Indigenous' used on the Statistics Canada ... Jun 14, 2022 ... Determinants of health are the broad range of personal, social, economic and environmental factors that determine individual and population ... COVID-19 vaccination coverage across Canada by demographics and key populations. Updated every Friday at 12:00 PM Eastern Time. Thought: I now know the final answer Final Answer: 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. > 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 answer 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 of the country and translated into English, Aug 1, 2021 ... 1. Afghanistan, "Milli Surood" (National Anthem) · 2. Armenia, "Mer Hayrenik" (Our Fatherland) · 3. Azerbaijan (a transcontinental country with ... A national anthem is a patriotic musical composition symbolizing and evoking eulogies of the history and traditions of a country or nation. National Anthem of Every Country ; Fiji, “Meda Dau Doka” (“God Bless Fiji”) ; Finland,
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory.html
4fede05c140d-6
Country ; Fiji, “Meda Dau Doka” (“God Bless Fiji”) ; Finland, “Maamme”. (“Our Land”) ; France, “La Marseillaise” (“The Marseillaise”). You can find an anthem in the menu at the top alphabetically or you can use the search feature. This site is focussed on the scholarly study of national anthems ... Feb 13, 2022 ... The 38-year-old country music artist had the honor of singing the National Anthem during this year's big game, and she did not disappoint. Oldest of the World's National Anthems ; France, La Marseillaise (“The Marseillaise”), 1795 ; Argentina, Himno Nacional Argentino (“Argentine National Anthem”) ... Mar 3, 2022 ... Country music star Jessie James Decker gained the respect of music and hockey fans alike after a jaw-dropping rendition of "The Star-Spangled ... This list shows the country on the left, the national anthem in the ... There are many countries over the world who have a national anthem of their own. 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 给Agent(代理)添加由数据库支持的消息存储 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory.html
bde6aa228a0e-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", session_id="foo") history.add_user_message("hi!") history.add_ai_message("whats up?") history.messages previous How to use multiple memory classes in the same chain next Redis Chat Message History By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/postgres_chat_message_history.html
fe5f7348db07-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 add a custom memory type to ConversationChain. In order to add a custom memory class, we need to import the base memory class and subclass it. from langchain import OpenAI, ConversationChain from langchain.schema import BaseMemory from pydantic import BaseModel from typing import List, Dict, Any In this example, we will write a custom memory class that uses spacy to extract entities and save information about them in a simple hash table. Then, during the conversation, we will look at the input text, extract any entities, and put any information about them into the context. Please note that this implementation is pretty simple and brittle and probably not useful in a production setting. Its purpose is to showcase that you can add custom memory implementations. For this, we will need spacy. # !pip install spacy # !python -m spacy download en_core_web_lg import spacy nlp = spacy.load('en_core_web_lg') class SpacyEntityMemory(BaseMemory, BaseModel): """Memory class for storing information about entities.""" # Define dictionary to store information about entities. entities: dict = {} # Define key to pass information about entities into prompt. memory_key: str = "entities" def clear(self): self.entities = {} @property def memory_variables(self) -> List[str]: """Define the variables we are providing to the prompt."""
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/custom_memory.html
fe5f7348db07-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[list(inputs.keys())[0]]) # Extract known information about entities, if they exist. entities = [self.entities[str(ent)] for ent in doc.ents if str(ent) in self.entities] # Return combined information about entities to put into context. return {self.memory_key: "\n".join(entities)} def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer.""" # Get the input text and run through spacy text = inputs[list(inputs.keys())[0]] doc = nlp(text) # For each entity that was mentioned, save this information to the dictionary. for ent in doc.ents: ent_str = str(ent) if ent_str in self.entities: self.entities[ent_str] += f"\n{text}" else:
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/custom_memory.html
fe5f7348db07-2
else: self.entities[ent_str] = text We now define a prompt that takes in information about entities as well as user input from langchain.prompts.prompt import PromptTemplate 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 truthfully says it does not know. You are provided with information about entities the Human mentions, if relevant. Relevant entity information: {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 no prior knowledge about Harrison, the “Relevant entity information” section is empty. conversation.predict(input="Harrison likes machine learning") > 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. You are provided with information about entities the Human mentions, if relevant. Relevant entity information: Conversation: Human: Harrison likes machine learning AI: > Finished ConversationChain chain. " That's great to hear! Machine learning is a fascinating field of study. It involves using algorithms to analyze data and make predictions. Have you ever studied machine learning, Harrison?" Now in the second example, we can see that it pulls in information about Harrison. conversation.predict(input="What do you
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/custom_memory.html
fe5f7348db07-3
example, we can see that it pulls in information about Harrison. conversation.predict(input="What do you think Harrison's favorite subject in college was?") > 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. You are provided with information about entities the Human mentions, if relevant. 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 the subject and has mentioned it often.' Again, please note that this implementation is pretty simple and brittle and probably not useful in a production setting. Its purpose is to showcase that you can add custom memory implementations. previous How to customize conversational memory next Motörhead Memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/custom_memory.html
cf67cb1dfca7-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 OpenAI from langchain.prompts import PromptTemplate from langchain.chains import ConversationChain from langchain.memory import ConversationBufferMemory, CombinedMemory, ConversationSummaryMemory conv_memory = ConversationBufferMemory( memory_key="chat_history_lines", input_key="input" ) summary_memory = ConversationSummaryMemory(llm=OpenAI(), input_key="input") # Combined memory = CombinedMemory(memories=[conv_memory, summary_memory]) _DEFAULT_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 truthfully says it does not know. Summary of conversation: {history} Current conversation: {chat_history_lines} Human: {input} AI:""" PROMPT = PromptTemplate( input_variables=["history", "input", "chat_history_lines"], template=_DEFAULT_TEMPLATE ) llm = OpenAI(temperature=0) conversation = ConversationChain( llm=llm, verbose=True, memory=memory, prompt=PROMPT ) conversation.run("Hi!") > 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. Summary of conversation: Current conversation: Human: Hi! AI: > Finished chain. '
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/multiple_memory.html
cf67cb1dfca7-1
know. 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 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. Summary of conversation: The human greets the AI and the AI responds, asking how it can help. Current conversation: Human: Hi! AI: Hi there! How can I help you? Human: Can you tell me a joke? AI: > Finished chain. ' Sure! What did the fish say when it hit the wall?\nHuman: I don\'t know.\nAI: "Dam!"' previous Motörhead Memory next Postgres Chat Message History By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/multiple_memory.html
c343d6c36443-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.motorhead_memory import MotorheadMemory from langchain import OpenAI, LLMChain, PromptTemplate template = """You are a chatbot having a conversation with a human. {chat_history} Human: {human_input} AI:""" prompt = PromptTemplate( input_variables=["chat_history", "human_input"], template=template ) memory = MotorheadMemory( session_id="testing-1", url="http://localhost:8080", memory_key="chat_history" ) await memory.init(); # loads previous state from Motörhead 🤘 llm_chain = LLMChain( llm=OpenAI(), prompt=prompt, verbose=True, memory=memory, ) llm_chain.run("hi im bob") > Entering new LLMChain chain... Prompt after formatting: You are a chatbot having a conversation with a human. Human: hi im bob AI: > Finished chain. ' Hi Bob, nice to meet you! How are you doing today?' llm_chain.run("whats my name?") > 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: whats my name? AI: > Finished chain. ' You said your name is Bob. Is that correct?' llm_chain.run("whats for dinner?") > Entering new
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/motorhead_memory.html
c343d6c36443-1
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: whats my name? AI: You said your name is Bob. Is that correct? Human: whats for dinner? AI: > Finished chain. " I'm sorry, I'm not sure what you're asking. Could you please rephrase your question?" previous How to create a custom Memory class next How to use multiple memory classes in the same chain Contents Setup By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/motorhead_memory.html
7eb052bb2576-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 [AIMessage(content='whats up?', additional_kwargs={}), HumanMessage(content='hi!', additional_kwargs={})] previous Postgres Chat Message History next Chains By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/redis_chat_message_history.html
551132f5ec36-0
.ipynb .pdf 如何给 LLM Chain(大语言模型链)添加 Memeory(记忆) 如何给 LLM Chain(大语言模型链)添加 Memeory(记忆)# 本章介绍了如何将Memory类与LLMChain一起使用。在本指南的示例中,我们将添加 ConversationBufferMemory 类,当然也可以是任何其他 Memory(记忆)类。 from langchain.memory import ConversationBufferMemory from langchain import OpenAI, LLMChain, PromptTemplate 最重要的一步是正确设置提示。在下面的提示中,我们有两个输入键:一个是实际输入的键,另一个是来自Memory类的输入的键。重要的是,我们确保PromptTemplate 中的键和ConversationBufferMemory 中的键匹配(chat_history)。 template = """You are a chatbot having a conversation with a human. {chat_history} Human: {human_input} Chatbot:""" prompt = PromptTemplate( input_variables=["chat_history", "human_input"], template=template ) memory = ConversationBufferMemory(memory_key="chat_history") llm_chain = LLMChain( llm=OpenAI(), prompt=prompt, verbose=True, memory=memory, ) llm_chain.predict(human_input="Hi there my friend") > Entering new LLMChain chain... Prompt after formatting: You are a chatbot having a conversation with a human. Human: Hi there my friend Chatbot: > Finished LLMChain chain. ' Hi there, how are you doing today?' llm_chain.predict(human_input="Not too bad - how are you?") > Entering new LLMChain
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/adding_memory.html
551132f5ec36-1
too bad - how are you?") > Entering new LLMChain chain... Prompt after formatting: You are a chatbot having a conversation with a human. 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. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/adding_memory.html
08f1c2c23166-0
.ipynb .pdf How to add memory to a Multi-Input Chain How to add memory to a Multi-Input Chain# Most memory objects assume a single output. In this notebook, we go over how to add memory to a chain that has multiple outputs. As an example of such a chain, we will add memory to a question/answering chain. This chain takes as inputs both related documents and a user question. from langchain.embeddings.openai import OpenAIEmbeddings from langchain.embeddings.cohere import CohereEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores.elastic_vector_search import ElasticVectorSearch from langchain.vectorstores import Chroma from langchain.docstore.document import Document with open('../../state_of_the_union.txt') as f: state_of_the_union = f.read() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{"source": i} for i in range(len(texts))]) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. query = "What did the president say about Justice Breyer" docs = docsearch.similarity_search(query) from langchain.chains.question_answering import load_qa_chain from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.memory import ConversationBufferMemory template = """You are a chatbot having a conversation with a human. Given the following extracted parts of a long document and a question, create a final answer. {context} {chat_history} Human: {human_input} Chatbot:""" prompt = PromptTemplate(
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html
08f1c2c23166-1
{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", memory=memory, prompt=prompt) query = "What did the president say about Justice Breyer" chain({"input_documents": docs, "human_input": query}, return_only_outputs=True) {'output_text': ' Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.'} print(chain.memory.buffer) Human: What did the president say about Justice Breyer AI: Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. previous 如何给 LLM Chain(大语言模型链)添加 Memeory(记忆) next How to add Memory to an Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html
5edaef49a58f-0
.ipynb .pdf 给Agent(代理)添加由数据库支持的消息存储 给Agent(代理)添加由数据库支持的消息存储# 本章介绍了如何给 Agent(代理) 添加 Memeory(记忆),其中记忆使用外部消息存储。在阅读本章内容之前,请先阅读以下基础内容: 给 LLM Chain(大语言模型链)添加 Memeory(记忆) Custom Agents Agent with Memory 为了向Agent添加具有外部消息存储的记忆,我们将执行以下步骤: 创建一个 RedisChatMessageHistory 以连接到外部数据库并将消息存储其中。 创建一个使用该聊天历史作为记忆的 LLMChain 使用该 LLMChain 创建自定义Agent。 为了本次练习,我们将创建一个简单的自定义Agent,可以访问搜索工具并利用 ConversationBufferMemory 类。 from langchain.agents import ZeroShotAgent, Tool, AgentExecutor from langchain.memory import ConversationBufferMemory from langchain.memory.chat_memory import ChatMessageHistory from langchain.memory.chat_message_histories import RedisChatMessageHistory from langchain import OpenAI, LLMChain from langchain.utilities import GoogleSearchAPIWrapper search = GoogleSearchAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="这对于回答有关当前事件的问题非常有用。" ) ] 请注意在 PromptTemplate 中使用 chat_history 变量,该变量与 `ConversationBufferMemory``
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory_in_db.html
5edaef49a58f-1
PromptTemplate 中使用 chat_history 变量,该变量与 `ConversationBufferMemory`` 中的动态键名相匹配。 prefix = """请与人类交谈,并尽力回答以下问题。您可以使用以下工具:""" suffix = """开始!" {chat_history} Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "chat_history", "agent_scratchpad"] ) 现在我们可以创建由数据库支持的 ChatMessageHistory 了。 message_history = RedisChatMessageHistory(url='redis://localhost:6379/0', ttl=600, session_id='my-session') memory = ConversationBufferMemory(memory_key="chat_history", chat_memory=message_history) 现在我们可以使用 Memory 对象构建 LLMChain,然后创建 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=memory) agent_chain.run(input="How many people live in canada?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada 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's Population and Demography Portal. Population of Canada (real- ... Index to the latest information from the Census of
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory_in_db.html
5edaef49a58f-2
Portal. Population of Canada (real- ... Index to the latest information from the Census of Population. This survey conducted by Statistics Canada provides a statistical portrait of Canada and its ... 14 records ... Estimated number of persons by quarter of a year and by year, Canada, provinces and territories. The 2021 Canadian census counted a total population of 36,991,981, an increase of around 5.2 percent over the 2016 figure. ... Between 1990 and 2008, the ... ( 2 ) Census reports and other statistical publications from national statistical offices, ( 3 ) Eurostat: Demographic Statistics, ( 4 ) United Nations ... Canada is a country in North America. Its ten provinces and three territories extend from ... Population. • Q4 2022 estimate. 39,292,355 (37th). Information is available for the total Indigenous population and each of the three ... The term 'Aboriginal' or 'Indigenous' used on the Statistics Canada ... Jun 14, 2022 ... Determinants of health are the broad range of personal, social, economic and environmental factors that determine individual and population ... COVID-19 vaccination coverage across Canada by demographics and key populations. Updated every Friday at 12:00 PM Eastern Time. Thought: I now know the final answer Final Answer: 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. > 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 correctly. agent_chain.run(input="what is their national anthem
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory_in_db.html
5edaef49a58f-3
information in the previous exchange to be answered correctly. agent_chain.run(input="what is their national anthem called?") > Entering new AgentExecutor chain... Thought: I need to find out what the national anthem of Canada is called. 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 in 1980. The music for O Canada was composed in 1880 by Calixa ... O Canada, national anthem of Canada. It was proclaimed the official national anthem on July 1, 1980. “God Save the Queen” remains the royal anthem of Canada ... O Canada! Our home and native land! True patriot love in all of us command. Car ton bras sait porter l'épée,. Il sait porter la croix! "O Canada" (French: Ô Canada) is the national anthem of Canada. The song was originally commissioned by Lieutenant Governor of Quebec Théodore Robitaille ... Feb 1, 2018 ... It was a simple tweak — just two words. But with that, Canada just voted to make its national anthem, “O Canada,” gender neutral, ... "O Canada" was proclaimed Canada's national anthem on July 1,. 1980, 100 years after it was first sung on June 24, 1880. The music. Patriotic music in Canada dates back over 200 years as a distinct category from British or French patriotism, preceding the first legal steps to ... Feb 4, 2022 ... English version: O Canada! Our home and native land! True patriot love in all of us command. With glowing hearts we ... Feb
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory_in_db.html
5edaef49a58f-4
and native land! True patriot love in all of us command. With glowing hearts we ... Feb 1, 2018 ... Canada's Senate has passed a bill making the country's national anthem gender-neutral. If you're not familiar with the words to “O Canada,” ... 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".' 我们可以看到Agent记住了之前的问题是关于加拿大的,并正确地向Google搜索询问了加拿大的国歌名称。 为了好玩,让我们将其与没有记忆的Agent进行比较。 prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:""" suffix = """Begin!" Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "agent_scratchpad"] ) llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True) agent_without_memory = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_without_memory.run("How many people live in canada?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada 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. ·
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory_in_db.html
5edaef49a58f-5
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 Canada (real- ... Index to the latest information from the Census of Population. This survey conducted by Statistics Canada provides a statistical portrait of Canada and its ... 14 records ... Estimated number of persons by quarter of a year and by year, Canada, provinces and territories. The 2021 Canadian census counted a total population of 36,991,981, an increase of around 5.2 percent over the 2016 figure. ... Between 1990 and 2008, the ... ( 2 ) Census reports and other statistical publications from national statistical offices, ( 3 ) Eurostat: Demographic Statistics, ( 4 ) United Nations ... Canada is a country in North America. Its ten provinces and three territories extend from ... Population. • Q4 2022 estimate. 39,292,355 (37th). Information is available for the total Indigenous population and each of the three ... The term 'Aboriginal' or 'Indigenous' used on the Statistics Canada ... Jun 14, 2022 ... Determinants of health are the broad range of personal, social, economic and environmental factors that determine individual and population ... COVID-19 vaccination coverage across Canada by demographics and key populations. Updated every Friday at 12:00 PM Eastern Time. Thought: I now know the final answer Final Answer: 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. > 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
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory_in_db.html
5edaef49a58f-6
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 answer 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 of the country and translated into English, Aug 1, 2021 ... 1. Afghanistan, "Milli Surood" (National Anthem) · 2. Armenia, "Mer Hayrenik" (Our Fatherland) · 3. Azerbaijan (a transcontinental country with ... A national anthem is a patriotic musical composition symbolizing and evoking eulogies of the history and traditions of a country or nation. National Anthem of Every Country ; Fiji, “Meda Dau Doka” (“God Bless Fiji”) ; Finland, “Maamme”. (“Our Land”) ; France, “La Marseillaise” (“The Marseillaise”). You can find an anthem in the menu at the top alphabetically or you can use the search feature. This site is focussed on the scholarly study of national anthems ... Feb 13, 2022 ... The 38-year-old country music artist had the honor of singing the National Anthem during this year's big game, and she did not disappoint. Oldest of the World's National Anthems ; France, La Marseillaise (“The Marseillaise”), 1795 ; Argentina, Himno Nacional Argentino (“Argentine National Anthem”) ... Mar 3, 2022 ... Country music star Jessie James Decker gained the respect of music and hockey fans alike
https:///langchain-cn.readthedocs.io/en/latest/modules/memory/examples/agent_with_memory_in_db.html