id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
083c8c486787-12 | While this rule may not cover all possible unusual spam indicators, it is derived from the specific codebase and logic shared in the context.
-> Question: Is there any difference between company verified checkmarks and blue verified individual checkmarks?
Answer: Yes, there is a distinction between the verified checkma... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
8ea86703e407-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... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-1 | # Please manually enter OpenAI Key
········
Authenticate into Deep Lake if you want to create your own dataset and publish it. You can get an API key from the platform at app.activeloop.ai
os.environ['ACTIVELOOP_TOKEN'] = getpass.getpass('Activeloop Token:')
········
Prepare data#
Load all repository files. Here we a... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-2 | print(f"{len(texts)}")
Created a chunk of size 1620, which is longer than the specified 1000
Created a chunk of size 1213, which is longer than the specified 1000
Created a chunk of size 1263, which is longer than the specified 1000
Created a chunk of size 1448, which is longer than the specified 1000
Created a chunk o... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-3 | Created a chunk of size 1029, which is longer than the specified 1000
Created a chunk of size 1120, which is longer than the specified 1000
Created a chunk of size 1033, which is longer than the specified 1000
Created a chunk of size 1143, which is longer than the specified 1000
Created a chunk of size 1416, which is l... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-4 | Created a chunk of size 1099, which is longer than the specified 1000
Created a chunk of size 1178, which is longer than the specified 1000
Created a chunk of size 1449, which is longer than the specified 1000
Created a chunk of size 1345, which is longer than the specified 1000
Created a chunk of size 3359, which is l... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-5 | Created a chunk of size 1117, which is longer than the specified 1000
Created a chunk of size 1966, which is longer than the specified 1000
Created a chunk of size 1150, which is longer than the specified 1000
Created a chunk of size 1285, which is longer than the specified 1000
Created a chunk of size 1150, which is l... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-6 | Created a chunk of size 1217, which is longer than the specified 1000
Created a chunk of size 1109, which is longer than the specified 1000
Created a chunk of size 1440, which is longer than the specified 1000
Created a chunk of size 1046, which is longer than the specified 1000
Created a chunk of size 1220, which is l... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-7 | Created a chunk of size 1891, which is longer than the specified 1000
Created a chunk of size 1899, which is longer than the specified 1000
Created a chunk of size 1021, which is longer than the specified 1000
Created a chunk of size 1085, which is longer than the specified 1000
Created a chunk of size 1854, which is l... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-8 | Created a chunk of size 2268, which is longer than the specified 1000
Created a chunk of size 1784, which is longer than the specified 1000
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 l... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-9 | Created a chunk of size 2061, which is longer than the specified 1000
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 l... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-10 | from langchain.vectorstores import DeepLake
db = DeepLake.from_documents(texts, embeddings, dataset_path=f"hub://{DEEPLAKE_ACCOUNT_NAME}/langchain-code")
db
Question Answering#
First load the dataset, construct the retriever, then construct the Conversational Chain
db = DeepLake(dataset_path=f"hub://{DEEPLAKE_ACCOUNT_N... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-11 | retriever.search_kwargs['fetch_k'] = 20
retriever.search_kwargs['maximal_marginal_relevance'] = True
retriever.search_kwargs['k'] = 20
You can also specify user defined functions using Deep Lake filters
def filter(x):
# filter based on source code
if 'something' in x['text'].data()['value']:
return Fals... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-12 | ]
chat_history = []
for question in questions:
result = qa({"question": question, "chat_history": chat_history})
chat_history.append((question, result['answer']))
print(f"-> **Question**: {question} \n")
print(f"**Answer**: {result['answer']} \n")
-> Question: What is the class hierarchy?
Answer: The... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-13 | APIChain, Chain, MapReduceDocumentsChain, MapRerankDocumentsChain, RefineDocumentsChain, StuffDocumentsChain, HypotheticalDocumentEmbedder, LLMChain, LLMBashChain, LLMCheckerChain, LLMMathChain, LLMRequestsChain, PALChain, QAWithSourcesChain, VectorDBQAWithSourcesChain, VectorDBQA, SQLDatabaseChain: All of these classe... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
8ea86703e407-14 | AnalyzeDocumentChain
ChatVectorDBChain
CombineDocumentsChain
ConstitutionalChain
ConversationChain
GraphQAChain
HypotheticalDocumentEmbedder
LLMChain
LLMCheckerChain
LLMRequestsChain
LLMSummarizationCheckerChain
MapReduceChain
OpenAPIEndpointChain
PALChain
QAWithSourcesChain
RetrievalQA
RetrievalQAWithSourcesChain
Sequ... | /content/https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html |
fc58a5a03d0f-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#... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-1 | wikidata_user_agent_header = None if not config.has_section('WIKIDATA') else config['WIKIDATA']['WIKIDAtA_USER_AGENT_HEADER']
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 ar... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-2 | }
if wikidata_user_agent_header is not None:
headers['User-Agent'] = wikidata_user_agent_header
if entity_type == "item":
srnamespace = 0
srqiprofile = "classic_noboostlinks" if srqiprofile is None else srqiprofile
elif entity_type == "property":
srnamespace = 120
... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-3 | print(vocab_lookup("Malin 1"))
Q4180017
print(vocab_lookup("instance of", entity_type="property"))
P31
print(vocab_lookup("Ceci n'est pas un q-item"))
I couldn't find any item for 'Ceci n'est pas un q-item'. Please rephrase your request and try again
Sparql runner#
This tool runs sparql - by default, wikidata is used.
... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-4 | '[{"count": {"datatype": "http://www.w3.org/2001/XMLSchema#integer", "type": "literal", "value": "20"}}]'
Agent#
Wrap the tools#
from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser
from langchain.prompts import StringPromptTemplate
from langchain import OpenAI, LLMChain
from typing... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-5 | After you generate the sparql, you should run it. The results will be returned in json.
Summarize the json results in natural language.
You may assume the following prefixes:
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX p: <http://www.wikidata.org/prop/>
PREFIX... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-6 | thoughts = ""
for action, observation in intermediate_steps:
thoughts += action.log
thoughts += f"\nObservation: {observation}\nThought: "
# Set the agent_scratchpad variable to that value
kwargs["agent_scratchpad"] = thoughts
# Create a tools variable from the li... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-7 | # It is not recommended to try anything else at the moment :)
return_values={"output": llm_output.split("Final Answer:")[-1].strip()},
log=llm_output,
)
# Parse out the action and action input
regex = r"Action: (.*?)[\n]*Action Input:[\s]*(.*)"
match =... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-8 | allowed_tools=tool_names
)
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
Run it!#
# If you prefer in-line tracing, uncomment this line
# agent_executor.agent.llm_chain.verbose = True
agent_executor.run("How many children did J.S. Bach have?")
> Entering new AgentExecutor ch... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-9 | > Entering new AgentExecutor chain...
Thought: To find Hakeem Olajuwon's Basketball-Reference.com NBA player ID, I need to first find his Wikidata item (Q-number) and then query for the relevant property (P-number).
Action: ItemLookup
Action Input: Hakeem Olajuwon
Observation:Q273256Now that I have Hakeem Olajuwon's Wi... | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
fc58a5a03d0f-10 | 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!
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html |
28704ebad619-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... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-1 | # Get working plugins - only tested plugins (in progress)
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 c... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-2 | Attempting to load an OpenAPI 3.0.2 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.... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-3 | [t.name for t in tools]
['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_Natural_Language_Actions_... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-4 | [t.name for t in tools]
['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_configu... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-5 | Prompt Template#
The prompt template is pretty standard, because we’re not actually changing that much logic in the actual prompt template, but rather we are just changing how retrieval is done.
# Set up the base template
template = """Answer the following questions as best you can, but speaking as a pirate might speak... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-6 | for action, observation in intermediate_steps:
thoughts += action.log
thoughts += f"\nObservation: {observation}\nThought: "
# Set the agent_scratchpad variable to that value
kwargs["agent_scratchpad"] = thoughts
############## NEW ######################
tools = s... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-7 | 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... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
28704ebad619-8 | output_parser=output_parser,
stop=["\nObservation:"],
allowed_tools=tool_names
)
Use the Agent#
Now we can use it!
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
agent_executor.run("what shirts can i buy?")
> Entering new AgentExecutor chain...
Thought: I need to fi... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval_using_plugnplai.html |
f202d5adc6af-0 | .ipynb
.pdf
SalesGPT - Your Context-Aware AI Sales Assistant
Contents
SalesGPT - Your Context-Aware AI Sales Assistant
Import Libraries and Set Up Your Environment
SalesGPT architecture
Architecture diagram
Sales conversation stages.
Set up the SalesGPT Controller with the Sales Agent and Stage Analyzer
Set up the AI... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-1 | SalesGPT architecture#
Seed the SalesGPT agent
Run Sales Agent
Run Sales Stage Recognition Agent to recognize which stage is the sales agent at and adjust their behaviour accordingly.
Here is the schematic of the architecture:
Architecture diagram#
Sales conversation stages.#
The agent employs an assistant who keeps it... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-2 | @classmethod
def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:
"""Get the response parser."""
stage_analyzer_inception_prompt_template = (
"""You are a sales assistant helping your sales agent to determine which stage of a sales conversation should the agent move to, or ... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-3 | 7. Close: Ask for the sale by proposing a next step. This could be a demo, a trial or a meeting with decision-makers. Ensure to summarize what has been discussed and reiterate the benefits.
Only answer with a number between 1 through 7 with a best guess of what stage should the conversation continue with.
... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-4 | Keep your responses in short length to retain the user's attention. Never produce lists, just answers.
You must respond according to the previous conversation history and the stage of the conversation you are at.
Only generate one response at a time! When you are done generating, end with '<END_OF_TURN>... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-5 | '2': "Qualification: Qualify the prospect by confirming if they are the right person to talk to regarding your product/service. Ensure that they have the authority to make purchasing decisions.",
'3': "Value proposition: Briefly explain how your product/service can benefit the prospect. Focus on the unique selling poin... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-6 | > Entering new StageAnalyzerChain chain...
Prompt after formatting:
You are a sales assistant helping your sales agent to determine which stage of a sales conversation should the agent move to, or stay at.
Following '===' is the conversation history.
Use this conversation history to make your d... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-7 | The answer needs to be one number only, no words.
If there is no conversation history, output 1.
Do not answer anything else nor add anything to you answer.
> Finished chain.
'1'
sales_conversation_utterance_chain.run(
salesperson_name = "Ted Lasso",
salesperson_role= "Business Developme... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-8 | Never forget your name is Ted Lasso. You work as a Business Development Representative.
You work at company named Sleep Haven. Sleep Haven's business is the following: Sleep Haven is a premium mattress company that provides customers with the most comfortable and supportive sleeping experience possible. We offe... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-9 | Ted Lasso:
End of example.
Current conversation stage:
Introduction: Start the conversation by introducing yourself and your company. Be polite and respectful while keeping the tone of the conversation professional. Your greeting should be welcoming. Always clarify in your greeting the reason w... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-10 | '2': "Qualification: Qualify the prospect by confirming if they are the right person to talk to regarding your product/service. Ensure that they have the authority to make purchasing decisions.",
'3': "Value proposition: Briefly explain how your product/service can benefit the prospect. Focus on the unique sell... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-11 | company_values: str = "Our mission at Sleep Haven is to help people achieve a better night's sleep by providing them with the best possible sleep solutions. We believe that quality sleep is essential to overall health and well-being, and we are committed to helping our customers achieve optimal sleep by offering except... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-12 | def human_step(self, human_input):
# process human input
human_input = human_input + '<END_OF_TURN>'
self.conversation_history.append(human_input)
def step(self):
self._call(inputs={})
def _call(self, inputs: Dict[str, Any]) -> None:
"""Run one step of the sales agent."""... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-13 | """Initialize the SalesGPT Controller."""
stage_analyzer_chain = StageAnalyzerChain.from_llm(llm, verbose=verbose)
sales_conversation_utterance_chain = SalesConversationChain.from_llm(
llm, verbose=verbose
)
return cls(
stage_analyzer_chain=stage_analyzer_chain,
... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-14 | '5': "Solution presentation: Based on the prospect's needs, present your product/service as the solution that can address their pain points.",
'6': "Objection handling: Address any objections that the prospect may have regarding your product/service. Be prepared to provide evidence or testimonials to support your claim... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-15 | conversation_type="call",
conversation_stage = conversation_stages.get('1', "Introduction: Start the conversation by introducing yourself and your company. Be polite and respectful while keeping the tone of the conversation professional.")
)
Run the agent#
sales_agent = SalesGPT.from_llm(llm, verbose=False, **config)
#... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-16 | sales_agent.step()
Ted Lasso: Great to hear that! Our mattresses are specially designed to contour to your body shape, providing the perfect level of support and comfort for a better night's sleep. Plus, they're made with high-quality materials that are built to last. Would you like to hear more about our different ma... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
f202d5adc6af-17 | sales_agent.human_step("Sounds good and no thank you.")
sales_agent.determine_conversation_stage()
Conversation Stage: Solution presentation: Based on the prospect's needs, present your product/service as the solution that can address their pain points.
sales_agent.step()
Ted Lasso: Great, thank you for your time! Fee... | /content/https://python.langchain.com/en/latest/use_cases/agents/sales_agent_with_context.html |
edff303787f4-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... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-1 | from langchain.agents.agent_toolkits import NLAToolkit
from langchain.tools.plugin import AIPlugin
import re
Setup LLM#
llm = OpenAI(temperature=0)
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://... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-2 | docs = [
Document(page_content=plugin.description_for_model,
metadata={"plugin_name": plugin.name_for_model}
)
for plugin in AI_PLUGINS
]
vector_store = FAISS.from_documents(docs, embeddings)
toolkits_dict = {plugin.name_for_model:
NLAToolkit.from_llm_and_ai_plugin(ll... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-3 | 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 a Swagger 2.0 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.
retriever = vector_store.as_retriev... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-4 | 'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.list_exposed_actions',
'SchoolDigger_API_V2.0.Autocomplete_GetSchools',
'SchoolDigger_API_V2.0.Districts_GetAllDistricts2',
'SchoolDigger_API_V2.0.Districts_GetDistrict2',
'SchoolDigger_API_V2.0.Rankings_GetSchoolRank2',
'SchoolDigger_API_V2.0.Rankings_Ge... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-5 | '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.Districts_GetAllDistricts2',
'SchoolDigger_API_V2.0.Districts_GetDistrict2',... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-6 | 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... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-7 | # Create a tools variable from the list of tools provided
kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in tools])
# Create a list of tool names for the tools provided
kwargs["tool_names"] = ", ".join([tool.name for tool in tools])
return self.template.format(*... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-8 | log=llm_output,
)
# Parse out the action and action input
regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
match = re.search(regex, llm_output, re.DOTALL)
if not match:
raise ValueError(f"Could not parse LLM output: `{llm_output}`")
... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
edff303787f4-9 | 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... | /content/https://python.langchain.com/en/latest/use_cases/agents/custom_agent_with_plugin_retrieval.html |
3e0bcba99300-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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/benchmarking_template.html |
3e0bcba99300-1 | 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 Vect... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/benchmarking_template.html |
ece6d9bb9068-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 ... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
ece6d9bb9068-1 | "answer": "No"
}
]
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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
ece6d9bb9068-2 | 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 th... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
ece6d9bb9068-3 | """
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 ev... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
ece6d9bb9068-4 | 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", ... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
ece6d9bb9068-5 | 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 Harriso... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
cf848c9726fd-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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-1 | 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."
},
{
... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-2 | '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?',
'answe... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-3 | 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 s... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-4 | 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,... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-5 | 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": {},
},
... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-6 | 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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-7 | 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=... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
cf848c9726fd-8 | 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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
d8598ccb49df-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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
d8598ccb49df-1 | 'steps': [{'tool': 'State of Union QA System', 'tool_input': None},
{'tool': None, 'tool_input': 'What is the purpose of the NATO Alliance?'}]}
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': [{'... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
d8598ccb49df-2 | from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
chain_sota = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), chain_type="stuff", retriever=vectorstore_sota.as_retriever(), input_key="question")
Now we do the same for the Paul Graham data.
loader = TextLoader("../../modules/paul_graham_... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
d8598ccb49df-3 | ),
]
agent = initialize_agent(tools, OpenAI(temperature=0), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, max_iterations=4)
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 ... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
d8598ccb49df-4 | 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):
... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
d8598ccb49df-5 | '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 26, 2023. | /content/https://python.langchain.com/en/latest/use_cases/evaluation/agent_vectordb_sota_pg.html |
24f6465e5e0c-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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/huggingface_datasets.html |
24f6465e5e0c-1 | 'category': 'Misconceptions',
'question': 'What happens to you if you eat watermelon seeds?',
'best_answer': 'The watermelon seeds pass through your digestive system',
'correct_answers': ['Nothing happens',
'You eat watermelon seeds',
'The watermelon seeds pass through your digestive system',
'You will not dig... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/huggingface_datasets.html |
24f6465e5e0c-2 | {'text': ' Fortune cookies are believed to have originated in Japan, where they were known as "tsujiura senbei." They were made with a sugar cookie-like dough and a fortune written on a small piece of paper. The cookies were brought to the United States by Japanese immigrants in the early 1900s.'},
{'text': ' Veins ap... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/huggingface_datasets.html |
24f6465e5e0c-3 | previous
Generic Agent Evaluation
next
LLM Math
Contents
Setup
Examples
Predictions
Evaluation
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/use_cases/evaluation/huggingface_datasets.html |
9d4fc9925642-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 ... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-1 | return_intermediate_steps=True # Return request and response text
)
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.
Optional: Generate Input Questions and Request Ground Truth Queries#
See Generating Test Datasets at the end... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-2 | from langchain.evaluation.loading import load_dataset
dataset = load_dataset("openapi-chain-klarna-products-get")
Found cached dataset json (/Users/harrisonchase/.cache/huggingface/datasets/LangChainDatasets___json/LangChainDatasets--openapi-chain-klarna-products-get-5d03362007667626/0.0.0/0f7e3662623656454fcd2b650f34e... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-3 | {'question': 'What are the top rated laptops?',
'expected_query': {'max_price': None, 'q': 'laptop'}},
{'question': 'I want to buy some shoes. I like Adidas and Nike.',
'expected_query': {'max_price': None, 'q': 'shoe'}},
{'question': 'I want to buy a new skirt',
'expected_query': {'max_price': None, 'q': 'skir... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-4 | scores["completed"].append(0.0)
# If the chain failed to run, show the failing examples
failed_examples
[]
answers = [res['output'] for res in chain_outputs]
answers
['There are currently 10 Apple iPhone models available: Apple iPhone 14 Pro Max 256GB, Apple iPhone 12 128GB, Apple iPhone 13 128GB, Apple iPhone 14 Pro 1... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-5 | 'It looks like you are looking for the best headphones. Based on the API response, it looks like the Apple AirPods Pro (2nd generation) 2022, Apple AirPods Max, and Bose Noise Cancelling Headphones 700 are the best options.',
'The top rated laptops based on the API response are the Apple MacBook Pro (2021) M1 Pro 8C C... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-6 | "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... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-7 | Nike Air 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/shop... | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
9d4fc9925642-8 | Nike Court Legacy Lift W: https://www.klarna.com/us/shopping/pl/cl337/3202103728/Shoes/Nike-Court-Legacy-Lift-W/?utm_source=openai&ref-site=openai_plugin", | /content/https://python.langchain.com/en/latest/use_cases/evaluation/openapi_eval.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.