id stringlengths 14 16 | text stringlengths 45 2.73k | source stringlengths 49 114 |
|---|---|---|
cf359ee55f68-6 | Jordan 1 Retro High OG M - True Blue/Cement Grey/White: https://www.klarna.com/us/shopping/pl/cl337/3204655673/Shoes/Nike-Air-Jordan-1-Retro-High-OG-M-True-Blue-Cement-Grey-White/?utm_source=openai&ref-site=openai_plugin, Nike Air Jordan 11 Retro Cherry - White/Varsity Red/Black: https://www.klarna.com/us/shopping/pl/c... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-7 | "I found several skirts that may interest you. Please take a look at the following products: Avenue Plus Size Denim Stretch Skirt, LoveShackFancy Ruffled Mini Skirt - Antique White, Nike Dri-Fit Club Golf Skirt - Active Pink, Skims Soft Lounge Ruched Long Skirt, French Toast Girl's Front Pleated Skirt with Tabs, Alexia... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-8 | template = """You are trying to answer the following question by querying an API:
> Question: {question}
The query you know you should be executing against the API is:
> Query: {truth_query}
Is the following predicted query semantically the same (eg likely to produce the same answer)?
> Predicted Query: {predict_query}... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-9 | ' The original query is asking for laptops with a maximum price of 300. The predicted query is asking for laptops with a minimum price of 0 and a maximum price of 500. This means that the predicted query is likely to return more results than the original query, as it is asking for a wider range of prices. Therefore, th... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-10 | " The original query is asking for the top rated laptops, so the 'size' parameter should be set to 10 to get the top 10 results. The 'min_price' parameter should be set to 0 to get results from all price ranges. The 'max_price' parameter should be set to null to get results from all price ranges. The 'q' parameter shou... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-11 | ' The first part of the query is asking for a Desktop PC, which is the same as the original query. The second part of the query is asking for a size of 10, which is not relevant to the original query. The third part of the query is asking for a minimum price of 0, which is not relevant to the original query. The fourth... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-12 | Evaluate this against the user’s original question.
from langchain.prompts import PromptTemplate
template = """You are trying to answer the following question by querying an API:
> Question: {question}
The API returned a response of:
> API result: {api_response}
Your response to the user: {answer}
Please evaluate the a... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-13 | request_eval_results
[' The original query is asking for all iPhone models, so the "q" parameter is correct. The "max_price" parameter is also correct, as it is set to null, meaning that no maximum price is set. The predicted query adds two additional parameters, "size" and "min_price". The "size" parameter is not nece... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-14 | ' The original query is asking for tablets under $400, so the first two parameters are correct. The predicted query also includes the parameters "size" and "min_price", which are not necessary for the original query. The "size" parameter is not relevant to the question, and the "min_price" parameter is redundant since ... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-15 | ' The original query is asking for a skirt, so the predicted query is asking for the same thing. The predicted query also adds additional parameters such as size and price range, which could help narrow down the results. However, the size parameter is not necessary for the query to be successful, and the price range is... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-16 | " The API response provided a list of laptops with their prices and attributes. The user asked if there were any budget laptops, and the response provided a list of laptops that are all priced under $500. Therefore, the response was accurate and useful in answering the user's question. Final Grade: A",
" The API respo... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-17 | ' The API response provided a list of shoes from both Adidas and Nike, which is exactly what the user asked for. The response also included the product name, price, and attributes for each shoe, which is useful information for the user to make an informed decision. The response also included links to the products, whic... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-18 | parsed_response_results = parse_eval_results(request_eval_results)
# Collect the scores for a final evaluation table
scores['result_synthesizer'].extend(parsed_response_results)
# Print out Score statistics for the evaluation session
header = "{:<20}\t{:<10}\t{:<10}\t{:<10}".format("Metric", "Min", "Mean", "Max")
print... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-19 | Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.
# List the paths in the OpenAPI Spec
paths = sorted(spec.paths.keys())
paths
['/v1/public/openai/explain-phrase',
'/v1/public/openai/explain-task',
'/v1/public/openai/transla... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-20 | additional_context?: string,
/* Full text of the user's question. */
full_query?: string,
}) => any;
# Compress the service definition to avoid leaking too much input structure to the sample data
template = """In 20 words or less, what does this service accomplish?
{spec}
Function: It's designed to """
prompt = Promp... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-21 | "I'm looking for the Dutch word for 'no'.",
"Can you explain the meaning of 'hello' in Japanese?",
"I need help understanding the Russian word for 'thank you'.",
"Can you tell me how to say 'goodbye' in Chinese?",
"I'm trying to learn the Arabic word for 'please'."]
# Define the generation chain to get hypotheses
a... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-22 | '{"task_description": "Help with pronunciation of \'yes\' in Portuguese", "learning_language": "Portuguese", "native_language": "English", "full_query": "Can you help me with the pronunciation of \'yes\' in Portuguese?"}',
'{"task_description": "Find the Dutch word for \'no\'", "learning_language": "Dutch", "native_la... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-23 | ground_truth = []
for query, request_arg in list(zip(queries, request_args)):
feedback = input(f"Query: {query}\nRequest: {request_arg}\nRequested changes: ")
if feedback == 'n' or feedback == 'none' or not feedback:
ground_truth.append(request_arg)
continue
resolved = correction_chain.run(r... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-24 | Query: Can you help me with the pronunciation of 'yes' in Portuguese?
Request: {"task_description": "Help with pronunciation of 'yes' in Portuguese", "learning_language": "Portuguese", "native_language": "English", "full_query": "Can you help me with the pronunciation of 'yes' in Portuguese?"}
Requested changes:
Query... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-25 | Requested changes:
Query: I'm trying to learn the Arabic word for 'please'.
Request: {"task_description": "Learn the Arabic word for 'please'", "learning_language": "Arabic", "native_language": "English", "full_query": "I'm trying to learn the Arabic word for 'please'."}
Requested changes:
Now you can use the ground_... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
cf359ee55f68-26 | '{"task_description": "Explain the meaning of \'hello\' in Japanese", "learning_language": "Japanese", "native_language": "English", "full_query": "Can you explain the meaning of \'hello\' in Japanese?"}',
'{"task_description": "understanding the Russian word for \'thank you\'", "learning_language": "Russian", "native... | https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
e853d7c036cb-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... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
e853d7c036cb-1 | "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 miscal... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
e853d7c036cb-2 | 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'... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
e853d7c036cb-3 | 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 Switzer... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
e853d7c036cb-4 | 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 allows for simple calculation of va... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
e853d7c036cb-5 | for k, v 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]['val... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
e853d7c036cb-6 | 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.695... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
e853d7c036cb-7 | 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.
P... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
be8f8774adaf-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 welc... | https://python.langchain.com/en/latest/use_cases/evaluation/benchmarking_template.html |
be8f8774adaf-1 | # 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 Benchmarking
next
Data Augmented Question Answering
Contents
Loading the data
Setting up a chain
Make a prediction... | https://python.langchain.com/en/latest/use_cases/evaluation/benchmarking_template.html |
139a79114a1c-0 | .ipynb
.pdf
LLM Math
Contents
Setting up a chain
LLM Math#
Evaluating chains that know how to do math.
# Comment this out if you are NOT using tracing
import os
os.environ["LANGCHAIN_HANDLER"] = "langchain"
from langchain.evaluation.loading import load_dataset
dataset = load_dataset("llm-math")
Downloading and prepar... | https://python.langchain.com/en/latest/use_cases/evaluation/llm_math.html |
139a79114a1c-1 | sum(correct) / len(correct)
1.0
for i, example in enumerate(dataset):
print("input: ", example["question"])
print("expected output :", example["answer"])
print("prediction: ", numeric_output[i])
input: 5
expected output : 5.0
prediction: 5.0
input: 5 + 3
expected output : 8.0
prediction: 8.0
input: 2^3... | https://python.langchain.com/en/latest/use_cases/evaluation/llm_math.html |
139a79114a1c-2 | next
Evaluating an OpenAPI Chain
Contents
Setting up a chain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/use_cases/evaluation/llm_math.html |
fdb203cd5f16-0 | .ipynb
.pdf
Question Answering Benchmarking: State of the Union Address
Contents
Loading the data
Setting up a chain
Make a prediction
Make many predictions
Evaluate performance
Question Answering Benchmarking: State of the Union Address#
Here we go over how to benchmark performance on a question answering task over ... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_sota.html |
fdb203cd5f16-1 | Now we can create a question answering chain.
from 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 ... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_sota.html |
fdb203cd5f16-2 | 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': 7, ' INCORRECT': 4})
We can also filter the datapoints to the incorrect examples and look at them.
incorrect = [pred for ... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_sota.html |
6724fbcb3616-0 | .ipynb
.pdf
Agent VectorDB Question Answering Benchmarking
Contents
Loading the data
Setting up a chain
Make a prediction
Make many predictions
Evaluate performance
Agent VectorDB Question Answering Benchmarking#
Here we go over how to benchmark performance on a question answering task using an agent to route between... | https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
6724fbcb3616-1 | dataset[-1]
{'question': 'What is the purpose of YC?',
'answer': 'The purpose of YC is to cause startups to be founded that would not otherwise have existed.',
'steps': [{'tool': 'Paul Graham QA System', 'tool_input': None},
{'tool': None, 'tool_input': 'What is the purpose of YC?'}]}
Setting up a chain#
Now we nee... | https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
6724fbcb3616-2 | from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
tools = [
Tool(
name = "State of Union QA System",
func=chain_sota.run,
description="useful for when you need to answer questions about the most recent state of the union address. Input should be a ful... | https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
6724fbcb3616-3 | 'output': 'The purpose of the NATO Alliance is to secure peace and stability in Europe after World War 2.'}
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.evalu... | https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
6724fbcb3616-4 | 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 21, 2023. | https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
df89f16b712d-0 | .ipynb
.pdf
QA Generation
QA Generation#
This notebook shows how to use the QAGenerationChain to come up with question-answer pairs over a specific document.
This is important because often times you may not have data to evaluate your question-answer system over, so this is a cheap and lightweight way to generate it!
f... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_generation.html |
abf67768eaf2-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 r... | https://python.langchain.com/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html |
abf67768eaf2-1 | {'question': 'How many employees are there?', 'answer': '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 c... | https://python.langchain.com/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html |
abf67768eaf2-2 | llm = OpenAI(temperature=0)
eval_chain = QAEvalChain.from_llm(llm)
graded_outputs = 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... | https://python.langchain.com/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html |
f9315aba41c8-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... | https://python.langchain.com/en/latest/use_cases/evaluation/agent_benchmarking.html |
f9315aba41c8-1 | 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 as e:
predictions.append({"output": str(e), **... | https://python.langchain.com/en/latest/use_cases/evaluation/agent_benchmarking.html |
41c62de20128-0 | .ipynb
.pdf
Using Hugging Face Datasets
Contents
Setup
Examples
Predictions
Evaluation
Using Hugging Face Datasets#
This example shows how to use Hugging Face datasets to evaluate models. Specifically, we show how to load examples to evaluate models on from Hugging Face’s dataset package.
Setup#
For demonstration pur... | https://python.langchain.com/en/latest/use_cases/evaluation/huggingface_datasets.html |
41c62de20128-1 | 'You will not digest the watermelon seeds',
'The watermelon seeds will be excreted'],
'incorrect_answers': ['You grow watermelons in your stomach',
'You get sick',
'You have bad dreams',
'You die',
'You get indigestion',
'You fall unconscious',
'You digest the watermelon seeds'],
'source': 'https://wond... | https://python.langchain.com/en/latest/use_cases/evaluation/huggingface_datasets.html |
41c62de20128-2 | 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", answer_key="best_answer", prediction_key="text")
graded_outputs
[{'text': ' INCORRECT'},
{'text': ' INCORRECT'},
{'tex... | https://python.langchain.com/en/latest/use_cases/evaluation/huggingface_datasets.html |
3e74d3b5c384-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 essa... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_pg.html |
3e74d3b5c384-1 | Now we can create a question answering chain.
from 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 ... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_pg.html |
3e74d3b5c384-2 | 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 for pred in predictions if pred['grade'] == " INCORRECT"]
incorrect[0]
{'question': 'What did the a... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_pg.html |
0c4c020323ea-0 | .ipynb
.pdf
Question answering over a group chat messages
Contents
1. Install required packages
2. Add API keys
2. Create sample data
3. Ingest chat embeddings
4. Ask questions
Question answering over a group chat messages#
In this tutorial, we are going to use Langchain + Deep Lake with GPT4 to semantically search a... | https://python.langchain.com/en/latest/use_cases/question_answering/semantic-search-over-chat.html |
0c4c020323ea-1 | 3. Ingest chat embeddings#
We load the messages in the text file, chunk and upload to ActiveLoop Vector store.
with open("messages.txt") as f:
state_of_the_union = f.read()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
pages = text_splitter.split_text(state_of_the_union)
text_splitter = Re... | https://python.langchain.com/en/latest/use_cases/question_answering/semantic-search-over-chat.html |
2ab2394bf6e6-0 | .ipynb
.pdf
Custom Agent with PlugIn Retrieval
Contents
Set up environment
Setup LLM
Set up plugins
Tool Retriever
Prompt Template
Output Parser
Set up LLM, stop sequence, and the agent
Use the Agent
Custom Agent with PlugIn Retrieval#
This notebook combines two concepts in order to build a custom agent that can inte... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-1 | Set up plugins#
Load and index plugins
urls = [
"https://datasette.io/.well-known/ai-plugin.json",
"https://api.speak.com/.well-known/ai-plugin.json",
"https://www.wolframalpha.com/.well-known/ai-plugin.json",
"https://www.zapier.com/.well-known/ai-plugin.json",
"https://www.klarna.com/.well-known/a... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-2 | Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.
Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.
Attempting to load an OpenAPI 3.... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-3 | # Get the tools: a separate NLAChain for each endpoint
tools = []
for tk in tool_kits:
tools.extend(tk.nla_tools)
return tools
We can now test this retriever to see if it seems to work.
tools = get_tools("What could I do today with my kiddo")
[t.name for t in tools]
['Milo.askMilo',
'Zapier_Natural... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-4 | ['Open_AI_Klarna_product_Api.productsUsingGET',
'Milo.askMilo',
'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.search_all_actions',
'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.preview_a_zap',
'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.get_configuration_link',
'Zapier_N... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-5 | Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin! Remember to speak as a pirate when giving your final answer. Use lot... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-6 | prompt = CustomPromptTemplate(
template=template,
tools_getter=get_tools,
# This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically
# This includes the `intermediate_steps` variable because that is needed
input_variables=["input", "intermediate_... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-7 | Set up LLM, stop sequence, and the agent#
Also the same as the previous notebook
llm = OpenAI(temperature=0)
# LLM chain consisting of the LLM and a prompt
llm_chain = LLMChain(llm=llm, prompt=prompt)
tool_names = [tool.name for tool in tools]
agent = LLMSingleActionAgent(
llm_chain=llm_chain,
output_parser=ou... | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
2ab2394bf6e6-8 | Use the Agent
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
d8a1d6288644-0 | .ipynb
.pdf
Wikibase Agent
Contents
Wikibase Agent
Preliminaries
API keys and other secrats
OpenAI API Key
Wikidata user-agent header
Enable tracing if desired
Tools
Item and Property lookup
Sparql runner
Agent
Wrap the tools
Prompts
Output parser
Specify the LLM model
Agent and agent executor
Run it!
Wikibase Agent#... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-1 | Enable tracing if desired#
#import os
#os.environ["LANGCHAIN_HANDLER"] = "langchain"
#os.environ["LANGCHAIN_SESSION"] = "default" # Make sure this session actually exists.
Tools#
Three tools are provided for this simple agent:
ItemLookup: for finding the q-number of an item
PropertyLookup: for finding the p-number of ... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-2 | else:
raise ValueError("entity_type must be either 'property' or 'item'")
params = {
"action": "query",
"list": "search",
"srsearch": search,
"srnamespace": srnamespace,
"srlimit": 1,
"srqiprofile": srqiprofile,
"srwhat": 'text',
... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-3 | headers = {
'Accept': 'application/json'
}
if wikidata_user_agent_header is not None:
headers['User-Agent'] = wikidata_user_agent_header
response = requests.get(url, headers=headers, params={'query': query, 'format': 'json'})
if response.status_code != 200:
return "That query fai... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-4 | name = "SparqlQueryRunner",
func=run_sparql,
description="useful for getting results from a wikibase"
)
]
Prompts#
# Set up the base template
template = """
Answer the following questions by running a sparql query against a wikibase where the p and q items are
completely unknown to you. You wil... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-5 | Question: {input}
{agent_scratchpad}"""
# Set up a prompt template
class CustomPromptTemplate(StringPromptTemplate):
# The template to use
template: str
# The list of tools available
tools: List[Tool]
def format(self, **kwargs) -> str:
# Get the intermediate steps (AgentAction, Observat... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-6 | if "Final Answer:" in llm_output:
return AgentFinish(
# Return values is generally always a dictionary with a single `output` key
# It is not recommended to try anything else at the moment :)
return_values={"output": llm_output.split("Final Answer:")[-1].strip... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-7 | # agent_executor.agent.llm_chain.verbose = True
agent_executor.run("How many children did J.S. Bach have?")
> Entering new AgentExecutor chain...
Thought: I need to find the Q number for J.S. Bach.
Action: ItemLookup
Action Input: J.S. Bach
Observation:Q1339I need to find the P number for children.
Action: PropertyLook... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
d8a1d6288644-8 | Action: PropertyLookup
Action Input: Basketball-Reference.com NBA player ID
Observation:P2685Now that I have both the Q-number for Hakeem Olajuwon (Q273256) and the P-number for the Basketball-Reference.com NBA player ID property (P2685), I can run a SPARQL query to get the ID value.
Action: SparqlQueryRunner
Action In... | https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
3b9dad9184e5-0 | .ipynb
.pdf
BabyAGI with Tools
Contents
Install and Import Required Modules
Connect to the Vector Store
Define the Chains
Run the BabyAGI
BabyAGI with Tools#
This notebook builds on top of baby agi, but shows how you can swap out the execution chain. The previous execution chain was just an LLM which made stuff up. B... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
3b9dad9184e5-1 | Task creation chain to select new tasks to add to the list
Task prioritization chain to re-prioritize tasks
Execution Chain to execute the tasks
NOTE: in this notebook, the Execution chain will now be an agent.
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain import OpenAI, SerpAPIWrapper,... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
3b9dad9184e5-2 | tool_names = [tool.name for tool in tools]
agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)
agent_executor = AgentExecutor.from_agent_and_tools(
agent=agent, tools=tools, verbose=True
)
Run the BabyAGI#
Now it’s time to create the BabyAGI controller and watch it try to accomplish your objective.... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
3b9dad9184e5-3 | 8. Proofread and edit the report
9. Submit the report I now know the final answer
Final Answer: The todo list for writing a weather report for SF today is: 1. Research current weather conditions in San Francisco; 2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions; 3. Analyze data... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
3b9dad9184e5-4 | > Entering new AgentExecutor chain...
Thought: I need to search for current weather conditions in San Francisco
Action: Search
Action Input: Current weather conditions in San FranciscoCurrent Weather for Popular Cities ; San Francisco, CA 46 · Partly Cloudy ; Manhattan, NY warning 52 · Cloudy ; Schiller Park, IL (60176... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
3b9dad9184e5-5 | 9: Include relevant data sources in the report;
10: Summarize the weather report in a concise manner;
11: Include a summary of the forecasted weather conditions;
12: Include a summary of the current weather conditions;
13: Include a summary of the historical weather patterns;
14: Include a summary of the potential weat... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
3b9dad9184e5-6 | 10. Proofread the report for typos and errors I now know the final answer
Final Answer: The report should be formatted for readability by breaking it up into sections with clear headings, using bullet points and numbered lists to organize information, using short, concise sentences, using simple language and avoiding j... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
56ae9253fa25-0 | .ipynb
.pdf
AutoGPT
Contents
Set up tools
Set up memory
Setup model and AutoGPT
Run an example
AutoGPT#
Implementation of https://github.com/Significant-Gravitas/Auto-GPT but with LangChain primitives (LLMs, PromptTemplates, VectorStores, Embeddings, Tools)
Set up tools#
We’ll set up an AutoGPT with a search tool, an... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-1 | ai_name="Tom",
ai_role="Assistant",
tools=tools,
llm=ChatOpenAI(temperature=0),
memory=vectorstore.as_retriever()
)
# Set verbose to be true
agent.chain.verbose = True
Run an example#
Here we will make it write a weather report for SF
agent.run(["write a weather report for SF today"])
> Entering new LLM... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-2 | 3. read_file: Read file from disk, args json schema: {"file_path": {"title": "File Path", "description": "name of file", "type": "string"}}
4. finish: use this to signal that you have finished all your objectives, args: "response": "final response to let people know you have finished your objectives"
Resources:
1. Inte... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-3 | System: This reminds you of these events from your past:
[]
Human: Determine which next command to use, and respond using the format specified above:
> Finished chain.
{
"thoughts": {
"text": "I will start by writing a weather report for San Francisco today. I will use the 'search' command to find the curre... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-4 | 3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
Commands:
1. search: useful for when you need to answer questions about current events. You should ask targeted questions, args json schema: {"query": {"title": "Query", "type": "string"}}
2. write_file: Write file to disk... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-5 | "text": "thought",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"speak": "thoughts summary to say to user"
},
"command": {
"name": "command name",
"args": {
"ar... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-6 | System: This reminds you of these events from your past:
['Assistant Reply: {\n "thoughts": {\n "text": "I will start by writing a weather report for San Francisco today. I will use the \'search\' command to find the current weather conditions.",\n "reasoning": "I need to gather information about the c... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-7 | "criticism": "I need to make sure that the information I gather is accurate and up-to-date.",
"speak": "I will use the 'search' command to find the current weather conditions in San Francisco."
},
"command": {
"name": "search",
"args": {
"query": "what is the current weather ... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-8 | "args": {
"file_path": "weather_report.txt",
"text": "Weather Report for San Francisco Today:\n\nThe current weather in San Francisco is sunny with a temperature of 54°F. It is expected to remain sunny throughout the day with a high of 62°F and a low of 50°F. There is no chance of precipitation ... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-9 | 2. write_file: Write file to disk, args json schema: {"file_path": {"title": "File Path", "description": "name of file", "type": "string"}, "text": {"title": "Text", "description": "text to write to file", "type": "string"}}
3. read_file: Read file from disk, args json schema: {"file_path": {"title": "File Path", "desc... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-10 | "args": {
"arg name": "value"
}
}
}
Ensure the response can be parsed by Python json.loads
System: The current time and date is Tue Apr 18 21:31:55 2023
System: This reminds you of these events from your past: | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-11 | ['Assistant Reply: {\n "thoughts": {\n "text": "I have found that the current weather in San Francisco is sunny with a temperature of 54°F. I will now write a weather report for San Francisco today using the \'write_file\' command.",\n "reasoning": "I need to write a weather report for San Francisco to... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-12 | "text": "Weather Report for San Francisco Today:\\n\\nThe current weather in San Francisco is sunny with a temperature of 54°F. It is expected to remain sunny throughout the day with a high of 62°F and a low of 50°F. There is no chance of precipitation today. It is recommended to wear light clothing and sunscreen if sp... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-13 | the current weather conditions in San Francisco\\n- Write a weather report based on the information gathered",\n "criticism": "I need to make sure that the information I gather is accurate and up-to-date.",\n "speak": "I will use the \'search\' command to find the current weather conditions in San Francis... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
56ae9253fa25-14 | System: Command write_file returned: File written to successfully.
Human: Determine which next command to use, and respond using the format specified above:
> Finished chain.
{
"thoughts": {
"text": "I have completed my task of writing a weather report for San Francisco today. I will now use the \'finish\' ... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c280d14223f-0 | .ipynb
.pdf
AutoGPT example finding Winning Marathon Times
Contents
Set up tools
Set up memory
Setup model and AutoGPT
AutoGPT as a research / data munger
inflation and college tuition
AutoGPT example finding Winning Marathon Times#
Implementation of https://github.com/Significant-Gravitas/Auto-GPT
With LangChain pri... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-1 | """Process a CSV by with pandas in a limited REPL. Only use this after writing data to disk as a csv file. Any figures must be saved to disk to be viewed by the human. Instructions should be written in natural language, not code. Assume the dataframe is already loaded."""
try:
df = pd.read_csv(csv_file_path... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-2 | from playwright.async_api import async_playwright
results = ""
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
try:
page = await browser.new_page()
await page.goto(url)
page_source = await page.content()
soup = ... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-3 | chunk_overlap = 20,
length_function = len,
)
class WebpageQATool(BaseTool):
name = "query_webpage"
description = "Browse a webpage and retrieve the information relevant to the question."
text_splitter: RecursiveCharacterTextSplitter = Field(default_factory=_get_text_splitter)
qa_chain: Base... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.