id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
115
e5b1f453d72c-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
e5b1f453d72c-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
e5b1f453d72c-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
e5b1f453d72c-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
e5b1f453d72c-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
e5b1f453d72c-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
e5b1f453d72c-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
e5b1f453d72c-8
Use the Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html
b13fc4f8e86f-0
.ipynb .pdf Plug-and-Plai 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 Plug-and-Plai# This notebook builds upon the idea of tool retrieval, but pulls all tools from plugnplai - a directory of AI Plugins. Set up...
https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html
b13fc4f8e86f-1
urls = plugnplai.get_plugins(filter = 'working') AI_PLUGINS = [AIPlugin.from_url(url + "/.well-known/ai-plugin.json") for url in urls] Tool Retriever# We will use a vectorstore to create embeddings for each tool description. Then, for an incoming query we can create embeddings for that query and do a similarity search ...
https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html
b13fc4f8e86f-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_using_plugnplai.html
b13fc4f8e86f-3
'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.preview_a_zap', 'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.get_configuration_link', 'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.list_exposed_actions', 'SchoolDigger_API_V2.0.Autocomplete_GetSchools', 'SchoolDigger_API_V2.0....
https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html
b13fc4f8e86f-4
'SchoolDigger_API_V2.0.Districts_GetAllDistricts2', 'SchoolDigger_API_V2.0.Districts_GetDistrict2', 'SchoolDigger_API_V2.0.Rankings_GetSchoolRank2', 'SchoolDigger_API_V2.0.Rankings_GetRank_District', 'SchoolDigger_API_V2.0.Schools_GetAllSchools20', 'SchoolDigger_API_V2.0.Schools_GetSchool20'] Prompt Template# The ...
https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html
b13fc4f8e86f-5
template: str ############## NEW ###################### # The list of tools available tools_getter: Callable def format(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("i...
https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html
b13fc4f8e86f-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/custom_agent_with_plugin_retrieval_using_plugnplai.html
b13fc4f8e86f-7
agent_executor.run("what shirts can i buy?") > Entering new AgentExecutor chain... Thought: I need to find a product API Action: Open_AI_Klarna_product_Api.productsUsingGET Action Input: shirts Observation:I found 10 shirts from the API response. They range in price from $9.99 to $450.00 and come in a variety of materi...
https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html
ce095b3e5205-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
ce095b3e5205-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
ce095b3e5205-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
ea2188c435f6-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
ea2188c435f6-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
ea2188c435f6-2
next Evaluating an OpenAPI Chain Contents Setting up a chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/use_cases/evaluation/llm_math.html
bdb1e163d490-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
bdb1e163d490-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
8ecc08fcf15e-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 ...
https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html
8ecc08fcf15e-1
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 th...
https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html
8ecc08fcf15e-2
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 i...
https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html
8ecc08fcf15e-3
context_examples = [ { "question": "How 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 Fra...
https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html
8ecc08fcf15e-4
predictions[i]['id'] = str(i) 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( ...
https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html
f53868190800-0
.ipynb .pdf Generic Agent Evaluation Contents Setup Testing the Agent Evaluating the Agent Generic Agent Evaluation# Good evaluation is key for quickly iterating on your agent’s prompts and tools. Here we provide an example of how to use the TrajectoryEvalChain to evaluate your agent. Setup# Let’s start by defining o...
https://python.langchain.com/en/latest/use_cases/evaluation/generic_agent_evaluation.html
f53868190800-1
memory_key="chat_history", return_messages=True, output_key="output" ) llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo") agent = initialize_agent( tools, llm, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory, return_intermediate_steps=True, # This is n...
https://python.langchain.com/en/latest/use_cases/evaluation/generic_agent_evaluation.html
f53868190800-2
> Entering new AgentExecutor chain... { "action": "Calculator", "action_input": "The length of the Eiffel Tower is 324 meters. The distance from coast to coast in the US is approximately 4,828 kilometers. First, we need to convert 4,828 kilometers to meters, which gives us 4,828,000 meters. To find out how many...
https://python.langchain.com/en/latest/use_cases/evaluation/generic_agent_evaluation.html
f53868190800-3
} > Entering new LLMMathChain chain... The length of the Eiffel Tower is 324 meters. The distance from coast to coast in the US is approximately 4,828 kilometers. First, we need to convert 4,828 kilometers to meters, which gives us 4,828,000 meters. To find out how many Eiffel Towers we need, we can divide 4,828,000 by...
https://python.langchain.com/en/latest/use_cases/evaluation/generic_agent_evaluation.html
f53868190800-4
) print("Score from 1 to 5: ", evaluation["score"]) print("Reasoning: ", evaluation["reasoning"]) Score from 1 to 5: 1 Reasoning: First, let's evaluate the final answer. The final answer is incorrect because it uses the volume of golf balls instead of ping pong balls. The answer is not helpful. Second, does the model...
https://python.langchain.com/en/latest/use_cases/evaluation/generic_agent_evaluation.html
f53868190800-5
) print("Score from 1 to 5: ", evaluation["score"]) print("Reasoning: ", evaluation["reasoning"]) Score from 1 to 5: 3 Reasoning: i. Is the final answer helpful? Yes, the final answer is helpful as it provides an approximate number of Eiffel Towers needed to cover the US from coast to coast. ii. Does the AI language ...
https://python.langchain.com/en/latest/use_cases/evaluation/generic_agent_evaluation.html
f53868190800-6
Setup Testing the Agent Evaluating the Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/use_cases/evaluation/generic_agent_evaluation.html
09a72b9ef196-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
09a72b9ef196-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
774fd21af57c-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
774fd21af57c-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
774fd21af57c-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
dc4a3f1793eb-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
dc4a3f1793eb-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
dc4a3f1793eb-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
50b33c8be811-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
50b33c8be811-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
50b33c8be811-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
9a4ee7d7aae6-0
.ipynb .pdf Evaluating an OpenAPI Chain Contents Load the API Chain Optional: Generate Input Questions and Request Ground Truth Queries Run the API Chain Evaluate the requests chain Evaluate the Response Chain Generating Test Datasets Evaluating an OpenAPI Chain# This notebook goes over ways to semantically evaluate ...
https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html
9a4ee7d7aae6-1
See Generating Test Datasets at the end of this notebook for more details. # import re # from langchain.prompts import PromptTemplate # template = """Below is a service description: # {spec} # Imagine you're a new user trying to use {operation} through a search bar. What are 10 different things you want to request? # W...
https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html
9a4ee7d7aae6-2
dataset [{'question': 'What iPhone models are available?', 'expected_query': {'max_price': None, 'q': 'iPhone'}}, {'question': 'Are there any budget laptops?', 'expected_query': {'max_price': 300, 'q': 'laptop'}}, {'question': 'Show me the cheapest gaming PC.', 'expected_query': {'max_price': 500, 'q': 'gaming ...
https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html
9a4ee7d7aae6-3
chain_outputs = [] failed_examples = [] for question in questions: try: chain_outputs.append(api_chain(question)) scores["completed"].append(1.0) except Exception as e: if raise_error: raise e failed_examples.append({'q': question, 'error': e}) scores["complet...
https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html
9a4ee7d7aae6-4
'Yes, there are several tablets under $400. These include the Apple iPad 10.2" 32GB (2019), Samsung Galaxy Tab A8 10.5 SM-X200 32GB, Samsung Galaxy Tab A7 Lite 8.7 SM-T220 32GB, Amazon Fire HD 8" 32GB (10th Generation), and Amazon Fire HD 10 32GB.', 'It looks like you are looking for the best headphones. Based on the ...
https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html
9a4ee7d7aae6-5
"I found several Nike and Adidas shoes in the API response. Here are the links to the products: Nike Dunk Low M - Black/White: https://www.klarna.com/us/shopping/pl/cl337/3200177969/Shoes/Nike-Dunk-Low-M-Black-White/?utm_source=openai&ref-site=openai_plugin, Nike Air Jordan 4 Retro M - Midnight Navy: https://www.klarna...
https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
9a4ee7d7aae6-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
591051f36fcc-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
0e8efbb281cb-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
0e8efbb281cb-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
0e8efbb281cb-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
0e8efbb281cb-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
0e8efbb281cb-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
0e8efbb281cb-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
0e8efbb281cb-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
0e8efbb281cb-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
492d4740092e-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
492d4740092e-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
492d4740092e-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
492d4740092e-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
492d4740092e-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 28, 2023.
https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html
33ff769e4516-0
.ipynb .pdf Use LangChain, GPT and Deep Lake to work with code base Contents Design Implementation Integration preparations Prepare data Question Answering Use LangChain, GPT and Deep Lake to work with code base# In this tutorial, we are going to use Langchain + Deep Lake with GPT to analyze the code base of the Lang...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-1
········ Prepare data# Load all repository files. Here we assume this notebook is downloaded as the part of the langchain fork and we work with the python files of the langchain repo. If you want to use files from different repo, change root_dir to the root dir of your repo. from langchain.document_loaders import TextL...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-2
Created a chunk of size 1260, which is longer than the specified 1000 Created a chunk of size 1195, which is longer than the specified 1000 Created a chunk of size 2147, which is longer than the specified 1000 Created a chunk of size 1410, which is longer than the specified 1000 Created a chunk of size 1269, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-3
Created a chunk of size 1418, which is longer than the specified 1000 Created a chunk of size 1848, which is longer than the specified 1000 Created a chunk of size 1069, which is longer than the specified 1000 Created a chunk of size 2369, which is longer than the specified 1000 Created a chunk of size 1045, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-4
Created a chunk of size 1589, which is longer than the specified 1000 Created a chunk of size 2104, which is longer than the specified 1000 Created a chunk of size 1505, which is longer than the specified 1000 Created a chunk of size 1387, which is longer than the specified 1000 Created a chunk of size 1215, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-5
Created a chunk of size 1585, which is longer than the specified 1000 Created a chunk of size 1208, which is longer than the specified 1000 Created a chunk of size 1267, which is longer than the specified 1000 Created a chunk of size 1542, which is longer than the specified 1000 Created a chunk of size 1183, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-6
Created a chunk of size 1220, which is longer than the specified 1000 Created a chunk of size 1403, which is longer than the specified 1000 Created a chunk of size 1241, which is longer than the specified 1000 Created a chunk of size 1427, which is longer than the specified 1000 Created a chunk of size 1049, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-7
Created a chunk of size 1085, which is longer than the specified 1000 Created a chunk of size 1854, which is longer than the specified 1000 Created a chunk of size 1672, which is longer than the specified 1000 Created a chunk of size 2537, which is longer than the specified 1000 Created a chunk of size 1251, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-8
Created a chunk of size 1311, which is longer than the specified 1000 Created a chunk of size 2972, which is longer than the specified 1000 Created a chunk of size 1144, which is longer than the specified 1000 Created a chunk of size 1825, which is longer than the specified 1000 Created a chunk of size 1508, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-9
Created a chunk of size 1066, which is longer than the specified 1000 Created a chunk of size 1419, which is longer than the specified 1000 Created a chunk of size 1368, which is longer than the specified 1000 Created a chunk of size 1008, which is longer than the specified 1000 Created a chunk of size 1227, which is l...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-10
- This dataset can be visualized in Jupyter Notebook by ds.visualize() or at https://app.activeloop.ai/user_name/langchain-code / hub://user_name/langchain-code loaded successfully. Deep Lake Dataset in hub://user_name/langchain-code already exists, loading from the storage Dataset(path='hub://user_name/langchain-code'...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html
33ff769e4516-11
from langchain.chains import ConversationalRetrievalChain model = ChatOpenAI(model='gpt-3.5-turbo') # 'ada' 'gpt-3.5-turbo' 'gpt-4', qa = ConversationalRetrievalChain.from_llm(model,retriever=retriever) questions = [ "What is the class hierarchy?", # "What classes are derived from the Chain class?", # "What...
https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html