from Khartoum prison"}, {"innerText": "WHO warns of \\u2018biological risk\\u2019 after Sudan fighters seize lab, as violence mars US-brokered ceasefire"}, {"innerText": "How Colombia\\u2019s Petro, a former leftwing guerrilla, found his opening in Washington"}, {"innerText": "Bolsonaro accidentally created Facebook post questioning Brazil election results, say his attorneys"}, {"innerText": "Crowd kills over a dozen suspected gang members in Haiti"}, {"innerText": "Thousands of tequila bottles containing liquid meth seized"}, {"innerText": "Why send a US stealth submarine to South Korea \\u2013 and tell the world about it?"}, {"innerText": "Fukushima\\u2019s fishing industry survived a nuclear disaster. 12 years on, it fears Tokyo\\u2019s next move may finish it off"}, {"innerText": "Singapore executes man for trafficking two pounds of cannabis"}, {"innerText": "Conservative Thai party looks to woo voters with promise to legalize sex toys"}, {"innerText": "Inside the Italian village being repopulated by Americans"},


"Inside the Italian village being repopulated by Americans"}, {"innerText": "Strikes, soaring airfares and yo-yoing hotel fees: A traveler\\u2019s guide to the coronation"}, {"innerText": "A year in Azerbaijan: From spring\\u2019s Grand Prix to winter ski adventures"}, {"innerText": "The bicycle mayor peddling a two-wheeled revolution in Cape Town"}, {"innerText": "Tokyo ramen shop bans customers from using their phones while eating"}, {"innerText": "South African opera star will perform at coronation of King Charles III"}, {"innerText": "Luxury loot under the hammer: France auctions goods seized from drug dealers"}, {"innerText": "Judy Blume\\u2019s books were formative for generations of readers. Here\\u2019s why they endure"}, {"innerText": "Craft, salvage and sustainability take center stage at Milan Design Week"}, {"innerText": "Life-sized chocolate King Charles III sculpture unveiled to celebrate coronation"}, {"innerText": "Severe storms to strike the South again as millions in Texas could see damaging winds and


as millions in Texas could see damaging winds and hail"}, {"innerText": "The South is in the crosshairs of severe weather again, as the multi-day threat of large hail and tornadoes continues"}, {"innerText": "Spring snowmelt has cities along the Mississippi bracing for flooding in homes and businesses"}, {"innerText": "Know the difference between a tornado watch, a tornado warning and a tornado emergency"}, {"innerText": "Reporter spotted familiar face covering Sudan evacuation. See what happened next"}, {"innerText": "This country will soon become the world\\u2019s most populated"}, {"innerText": "April 27, 2023 - Russia-Ukraine news"}, {"innerText": "\\u2018Often they shoot at each other\\u2019: Ukrainian drone operator details chaos in Russian ranks"}, {"innerText": "Hear from family members of Americans stuck in Sudan frustrated with US response"}, {"innerText": "U.S. talk show host Jerry Springer dies at 79"}, {"innerText": "Bureaucracy stalling at least one family\\u2019s evacuation from Sudan"}, {"innerText":


evacuation from Sudan"}, {"innerText": "Girl to get life-saving treatment for rare immune disease"}, {"innerText": "Haiti\\u2019s crime rate more than doubles in a year"}, {"innerText": "Ocean census aims to discover 100,000 previously unknown marine species"}, {"innerText": "Wall Street Journal editor discusses reporter\\u2019s arrest in Moscow"}, {"innerText": "Can Tunisia\\u2019s democracy be saved?"}, {"innerText": "Yasmeen Lari, \\u2018starchitect\\u2019 turned social engineer, wins one of architecture\\u2019s most coveted prizes"}, {"innerText": "A massive, newly restored Frank Lloyd Wright mansion is up for sale"}, {"innerText": "Are these the most sustainable architectural projects in the world?"}, {"innerText": "Step inside a $72 million London townhouse in a converted army barracks"}, {"innerText": "A 3D-printing company is preparing to build on the lunar surface. But first, a moonshot at home"}, {"innerText": "Simona Halep says \\u2018the stress is huge\\u2019 as she battles to


stress is huge\\u2019 as she battles to return to tennis following positive drug test"}, {"innerText": "Barcelona reaches third straight Women\\u2019s Champions League final with draw against Chelsea"}, {"innerText": "Wrexham: An intoxicating tale of Hollywood glamor and sporting romance"}, {"innerText": "Shohei Ohtani comes within inches of making yet more MLB history in Angels win"}, {"innerText": "This CNN Hero is recruiting recreational divers to help rebuild reefs in Florida one coral at a time"}, {"innerText": "This CNN Hero offers judgment-free veterinary care for the pets of those experiencing homelessness"}, {"innerText": "Don\\u2019t give up on milestones: A CNN Hero\\u2019s message for Autism Awareness Month"}, {"innerText": "CNN Hero of the Year Nelly Cheboi returned to Kenya with plans to lift more students out of poverty"}]'


# If the agent wants to remember the current webpage, it can use the `current_webpage` tool
await tools_by_name['current_webpage'].arun({})
'https://web.archive.org/web/20230428133211/https://cnn.com/world'
previous
Pandas Dataframe Agent
next
PowerBI Dataset Agent
 Contents

Instantiating a Browser Toolkit
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Vectorstore Agent
 Contents
Create the Vectorstores
Initialize Toolkit and Agent
Examples
Multiple Vectorstores
Examples
Vectorstore Agent#
This notebook showcases an agent designed to retrieve information from one or more vectorstores, either with or without sources.
Create the Vectorstores#
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter import CharacterTextSplitter
from langchain import OpenAI, VectorDBQA
llm = OpenAI(temperature=0)
from langchain.document_loaders import TextLoader
loader = TextLoader('../../../state_of_the_union.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
state_of_union_store = Chroma.from_documents(texts, embeddings, collection_name="state-of-union")
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
from langchain.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://beta.ruff.rs/docs/faq/")
docs = loader.load()
ruff_texts = text_splitter.split_documents(docs)
ruff_store = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff")
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
Initialize Toolkit and Agent#
First, we’ll create an agent with a single vectorstore.
from langchain.agents.agent_toolkits import (
    create_vectorstore_agent,
    VectorStoreToolkit,
    VectorStoreInfo,
)
vectorstore_info = VectorStoreInfo(
    name="state_of_union_address",


)
vectorstore_info = VectorStoreInfo(
    name="state_of_union_address",
    description="the most recent state of the Union adress",
    vectorstore=state_of_union_store
)
toolkit = VectorStoreToolkit(vectorstore_info=vectorstore_info)
agent_executor = create_vectorstore_agent(
    llm=llm,
    toolkit=toolkit,
    verbose=True
)
Examples#
agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?")
> Entering new AgentExecutor chain...
 I need to find the answer in the state of the union address
Action: state_of_union_address
Action Input: What did biden say about ketanji brown jackson
Observation:  Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
Thought: I now know the final answer
Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
> Finished chain.
"Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address? List the source.")
> Entering new AgentExecutor chain...
 I need to use the state_of_union_address_with_sources tool to answer this question.
Action: state_of_union_address_with_sources
Action Input: What did biden say about ketanji brown jackson


Action Input: What did biden say about ketanji brown jackson
Observation: {"answer": " Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence.\n", "sources": "../../state_of_the_union.txt"}
Thought: I now know the final answer
Final Answer: Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt
> Finished chain.
"Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt"
Multiple Vectorstores#
We can also easily use this initialize an agent with multiple vectorstores and use the agent to route between them. To do this. This agent is optimized for routing, so it is a different toolkit and initializer.
from langchain.agents.agent_toolkits import (
    create_vectorstore_router_agent,
    VectorStoreRouterToolkit,
    VectorStoreInfo,
)
ruff_vectorstore_info = VectorStoreInfo(
    name="ruff",
    description="Information about the Ruff python linting library",
    vectorstore=ruff_store
)
router_toolkit = VectorStoreRouterToolkit(
    vectorstores=[vectorstore_info, ruff_vectorstore_info],
    llm=llm
)
agent_executor = create_vectorstore_router_agent(
    llm=llm,
    toolkit=router_toolkit,
    verbose=True
)


toolkit=router_toolkit,
    verbose=True
)
Examples#
agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?")
> Entering new AgentExecutor chain...
 I need to use the state_of_union_address tool to answer this question.
Action: state_of_union_address
Action Input: What did biden say about ketanji brown jackson
Observation:  Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
Thought: I now know the final answer
Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
> Finished chain.
"Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
agent_executor.run("What tool does ruff use to run over Jupyter Notebooks?")
> Entering new AgentExecutor chain...
 I need to find out what tool ruff uses to run over Jupyter Notebooks
Action: ruff
Action Input: What tool does ruff use to run over Jupyter Notebooks?
Observation:  Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb
Thought: I now know the final answer


Thought: I now know the final answer
Final Answer: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb
> Finished chain.
'Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb'
agent_executor.run("What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?")
> Entering new AgentExecutor chain...
 I need to find out what tool ruff uses and if the president mentioned it in the state of the union.
Action: ruff
Action Input: What tool does ruff use to run over Jupyter Notebooks?
Observation:  Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb
Thought: I need to find out if the president mentioned nbQA in the state of the union.
Action: state_of_union_address
Action Input: Did the president mention nbQA in the state of the union?
Observation:  No, the president did not mention nbQA in the state of the union.
Thought: I now know the final answer.
Final Answer: No, the president did not mention nbQA in the state of the union.
> Finished chain.
'No, the president did not mention nbQA in the state of the union.'
previous
SQL Database Agent
next


previous
SQL Database Agent
next
Agent Executors
 Contents

Create the Vectorstores
Initialize Toolkit and Agent
Examples
Multiple Vectorstores
Examples
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Jira
Jira#
This notebook goes over how to use the Jira tool.
The Jira tool allows agents to interact with a given Jira instance, performing actions such as searching for issues and creating issues, the tool wraps the atlassian-python-api library, for more see: https://atlassian-python-api.readthedocs.io/jira.html
To use this tool, you must first set as environment variables:
JIRA_API_TOKEN
JIRA_USERNAME
JIRA_INSTANCE_URL
%pip install atlassian-python-api
import os
from langchain.agents import AgentType
from langchain.agents import initialize_agent
from langchain.agents.agent_toolkits.jira.toolkit import JiraToolkit
from langchain.llms import OpenAI
from langchain.utilities.jira import JiraAPIWrapper
os.environ["JIRA_API_TOKEN"] = "abc"
os.environ["JIRA_USERNAME"] = "123"
os.environ["JIRA_INSTANCE_URL"] = "https://jira.atlassian.com"
os.environ["OPENAI_API_KEY"] = "xyz"
llm = OpenAI(temperature=0)
jira = JiraAPIWrapper()
toolkit = JiraToolkit.from_jira_api_wrapper(jira)
agent = initialize_agent(
    toolkit.get_tools(),
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)
agent.run("make a new issue in project PW to remind me to make more fried rice")
> Entering new AgentExecutor chain...
 I need to create an issue in project PW
Action: Create Issue
Action Input: {"summary": "Make more fried rice", "description": "Reminder to make more fried rice", "issuetype": {"name": "Task"}, "priority": {"name": "Low"}, "project": {"key": "PW"}}


Observation: None
Thought: I now know the final answer
Final Answer: A new issue has been created in project PW with the summary "Make more fried rice" and description "Reminder to make more fried rice".
> Finished chain.
'A new issue has been created in project PW with the summary "Make more fried rice" and description "Reminder to make more fried rice".'
previous
CSV Agent
next
JSON Agent
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
PowerBI Dataset Agent
 Contents
Some notes
Initialization
Example: describing a table
Example: simple query on a table
Example: running queries
Example: add your own few-shot prompts
PowerBI Dataset Agent#
This notebook showcases an agent designed to interact with a Power BI Dataset. The agent is designed to answer more general questions about a dataset, as well as recover from errors.
Note that, as this agent is in active development, all answers might not be correct. It runs against the executequery endpoint, which does not allow deletes.
Some notes#
It relies on authentication with the azure.identity package, which can be installed with pip install azure-identity. Alternatively you can create the powerbi dataset with a token as a string without supplying the credentials.
You can also supply a username to impersonate for use with datasets that have RLS enabled.
The toolkit uses a LLM to create the query from the question, the agent uses the LLM for the overall execution.
Testing was done mostly with a text-davinci-003 model, codex models did not seem to perform ver well.
Initialization#
from langchain.agents.agent_toolkits import create_pbi_agent
from langchain.agents.agent_toolkits import PowerBIToolkit
from langchain.utilities.powerbi import PowerBIDataset
from langchain.llms.openai import AzureOpenAI
from langchain.agents import AgentExecutor
from azure.identity import DefaultAzureCredential
fast_llm = AzureOpenAI(temperature=0.5, max_tokens=1000, deployment_name="gpt-35-turbo", verbose=True)
smart_llm = AzureOpenAI(temperature=0, max_tokens=100, deployment_name="gpt-4", verbose=True)
toolkit = PowerBIToolkit(


toolkit = PowerBIToolkit(
    powerbi=PowerBIDataset(dataset_id="<dataset_id>", table_names=['table1', 'table2'], credential=DefaultAzureCredential()),
    llm=smart_llm
)
agent_executor = create_pbi_agent(
    llm=fast_llm,
    toolkit=toolkit,
    verbose=True,
)
Example: describing a table#
agent_executor.run("Describe table1")
Example: simple query on a table#
In this example, the agent actually figures out the correct query to get a row count of the table.
agent_executor.run("How many records are in table1?")
Example: running queries#
agent_executor.run("How many records are there by dimension1 in table2?")
agent_executor.run("What unique values are there for dimensions2 in table2")
Example: add your own few-shot prompts#
#fictional example
few_shots = """
Question: How many rows are in the table revenue?
DAX: EVALUATE ROW("Number of rows", COUNTROWS(revenue_details))
----
Question: How many rows are in the table revenue where year is not empty?
DAX: EVALUATE ROW("Number of rows", COUNTROWS(FILTER(revenue_details, revenue_details[year] <> "")))
----
Question: What was the average of value in revenue in dollars?
DAX: EVALUATE ROW("Average", AVERAGE(revenue_details[dollar_value]))
----
"""
toolkit = PowerBIToolkit(
    powerbi=PowerBIDataset(dataset_id="<dataset_id>", table_names=['table1', 'table2'], credential=DefaultAzureCredential()),
    llm=smart_llm,
    examples=few_shots,
)
agent_executor = create_pbi_agent(


examples=few_shots,
)
agent_executor = create_pbi_agent(
    llm=fast_llm,
    toolkit=toolkit,
    verbose=True,
)
agent_executor.run("What was the maximum of value in revenue in dollars in 2022?")
previous
PlayWright Browser Toolkit
next
Python Agent
 Contents

Some notes
Initialization
Example: describing a table
Example: simple query on a table
Example: running queries
Example: add your own few-shot prompts
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
JSON Agent
 Contents
Initialization
Example: getting the required POST parameters for a request
JSON Agent#
This notebook showcases an agent designed to interact with large JSON/dict objects. This is useful when you want to answer questions about a JSON blob that’s too large to fit in the context window of an LLM. The agent is able to iteratively explore the blob to find what it needs to answer the user’s question.
In the below example, we are using the OpenAPI spec for the OpenAI API, which you can find here.
We will use the JSON agent to answer some questions about the API spec.
Initialization#
import os
import yaml
from langchain.agents import (
    create_json_agent,
    AgentExecutor
)
from langchain.agents.agent_toolkits import JsonToolkit
from langchain.chains import LLMChain
from langchain.llms.openai import OpenAI
from langchain.requests import TextRequestsWrapper
from langchain.tools.json.tool import JsonSpec
with open("openai_openapi.yml") as f:
    data = yaml.load(f, Loader=yaml.FullLoader)
json_spec = JsonSpec(dict_=data, max_value_length=4000)
json_toolkit = JsonToolkit(spec=json_spec)
json_agent_executor = create_json_agent(
    llm=OpenAI(temperature=0),
    toolkit=json_toolkit,
    verbose=True
)
Example: getting the required POST parameters for a request#
json_agent_executor.run("What are the required parameters in the request body to the /completions endpoint?")
> Entering new AgentExecutor chain...
Action: json_spec_list_keys
Action Input: data
Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta']


Thought: I should look at the paths key to see what endpoints exist
Action: json_spec_list_keys
Action Input: data["paths"]
Observation: ['/engines', '/engines/{engine_id}', '/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations']
Thought: I should look at the /completions endpoint to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]
Observation: ['post']
Thought: I should look at the post key to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]
Observation: ['operationId', 'tags', 'summary', 'requestBody', 'responses', 'x-oaiMeta']
Thought: I should look at the requestBody key to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"]
Observation: ['required', 'content']
Thought: I should look at the required key to see what parameters are required
Action: json_spec_get_value
Action Input: data["paths"]["/completions"]["post"]["requestBody"]["required"]
Observation: True
Thought: I should look at the content key to see what parameters are required
Action: json_spec_list_keys


Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]
Observation: ['application/json']
Thought: I should look at the application/json key to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]
Observation: ['schema']
Thought: I should look at the schema key to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]
Observation: ['$ref']
Thought: I should look at the $ref key to see what parameters are required
Action: json_spec_get_value
Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]
Observation: #/components/schemas/CreateCompletionRequest
Thought: I should look at the CreateCompletionRequest schema to see what parameters are required
Action: json_spec_list_keys
Action Input: data["components"]["schemas"]["CreateCompletionRequest"]
Observation: ['type', 'properties', 'required']
Thought: I should look at the required key to see what parameters are required
Action: json_spec_get_value
Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"]
Observation: ['model']
Thought: I now know the final answer
Final Answer: The required parameters in the request body to the /completions endpoint are 'model'.
> Finished chain.
"The required parameters in the request body to the /completions endpoint are 'model'."
previous
Jira
next
OpenAPI agents
 Contents

Initialization
Example: getting the required POST parameters for a request
By Harrison Chase


Initialization
Example: getting the required POST parameters for a request
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Pandas Dataframe Agent
Pandas Dataframe Agent#
This notebook shows how to use agents to interact with a pandas dataframe. It is mostly optimized for question answering.
NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously.
from langchain.agents import create_pandas_dataframe_agent
from langchain.llms import OpenAI
import pandas as pd
df = pd.read_csv('titanic.csv')
agent = create_pandas_dataframe_agent(OpenAI(temperature=0), df, verbose=True)
agent.run("how many rows are there?")
> Entering new AgentExecutor chain...
Thought: I need to count the number of rows
Action: python_repl_ast
Action Input: len(df)
Observation: 891
Thought: I now know the final answer
Final Answer: There are 891 rows in the dataframe.
> Finished chain.
'There are 891 rows in the dataframe.'
agent.run("how many people have more than 3 sibligngs")
> Entering new AgentExecutor chain...
Thought: I need to count the number of people with more than 3 siblings
Action: python_repl_ast
Action Input: df[df['SibSp'] > 3].shape[0]
Observation: 30
Thought: I now know the final answer
Final Answer: 30 people have more than 3 siblings.
> Finished chain.
'30 people have more than 3 siblings.'
agent.run("whats the square root of the average age?")
> Entering new AgentExecutor chain...
Thought: I need to calculate the average age first
Action: python_repl_ast
Action Input: df['Age'].mean()


Action: python_repl_ast
Action Input: df['Age'].mean()
Observation: 29.69911764705882
Thought: I can now calculate the square root
Action: python_repl_ast
Action Input: math.sqrt(df['Age'].mean())
Observation: name 'math' is not defined
Thought: I need to import the math library
Action: python_repl_ast
Action Input: import math
Observation: None
Thought: I can now calculate the square root
Action: python_repl_ast
Action Input: math.sqrt(df['Age'].mean())
Observation: 5.449689683556195
Thought: I now know the final answer
Final Answer: 5.449689683556195
> Finished chain.
'5.449689683556195'
previous
Natural Language APIs
next
PlayWright Browser Toolkit
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
CSV Agent
CSV Agent#
This notebook shows how to use agents to interact with a csv. It is mostly optimized for question answering.
NOTE: this agent calls the Pandas DataFrame agent under the hood, which in turn calls the Python agent, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously.
from langchain.agents import create_csv_agent
from langchain.llms import OpenAI
agent = create_csv_agent(OpenAI(temperature=0), 'titanic.csv', verbose=True)
agent.run("how many rows are there?")
> Entering new AgentExecutor chain...
Thought: I need to count the number of rows
Action: python_repl_ast
Action Input: len(df)
Observation: 891
Thought: I now know the final answer
Final Answer: There are 891 rows in the dataframe.
> Finished chain.
'There are 891 rows in the dataframe.'
agent.run("how many people have more than 3 sibligngs")
> Entering new AgentExecutor chain...
Thought: I need to count the number of people with more than 3 siblings
Action: python_repl_ast
Action Input: df[df['SibSp'] > 3].shape[0]
Observation: 30
Thought: I now know the final answer
Final Answer: 30 people have more than 3 siblings.
> Finished chain.
'30 people have more than 3 siblings.'
agent.run("whats the square root of the average age?")
> Entering new AgentExecutor chain...
Thought: I need to calculate the average age first
Action: python_repl_ast
Action Input: df['Age'].mean()
Observation: 29.69911764705882


Observation: 29.69911764705882
Thought: I can now calculate the square root
Action: python_repl_ast
Action Input: math.sqrt(df['Age'].mean())
Observation: name 'math' is not defined
Thought: I need to import the math library
Action: python_repl_ast
Action Input: import math
Observation:
Thought: I can now calculate the square root
Action: python_repl_ast
Action Input: math.sqrt(df['Age'].mean())
Observation: 5.449689683556195
Thought: I now know the final answer
Final Answer: 5.449689683556195
> Finished chain.
'5.449689683556195'
previous
Toolkits
next
Jira
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Defining Custom Tools
 Contents
Completely New Tools
Tool dataclass
Subclassing the BaseTool class
Using the tool decorator
Modify existing tools
Defining the priorities among Tools
Using tools to return directly
Defining Custom Tools#
When constructing your own agent, you will need to provide it with a list of Tools that it can use. Besides the actual function that is called, the Tool consists of several components:
name (str), is required and must be unique within a set of tools provided to an agent
description (str), is optional but recommended, as it is used by an agent to determine tool use
return_direct (bool), defaults to False
args_schema (Pydantic BaseModel), is optional but recommended, can be used to provide more information or validation for expected parameters.
The function that should be called when the tool is selected should return a single string.
There are two ways to define a tool, we will cover both in the example below.
# Import things that are needed generically
from langchain import LLMMathChain, SerpAPIWrapper
from langchain.agents import AgentType, Tool, initialize_agent, tool
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool
Initialize the LLM to use for the agent.
llm = ChatOpenAI(temperature=0)
Completely New Tools#
First, we show how to create completely new tools from scratch.
There are two ways to do this: either by using the Tool dataclass, or by subclassing the BaseTool class.
Tool dataclass#
# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
tools = [
    Tool(
        name = "Search",
        func=search.run,


tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events"
    ),
]
# You can also define an args_schema to provide more information about inputs
from pydantic import BaseModel, Field
class CalculatorInput(BaseModel):
    question: str = Field()

tools.append(
    Tool(
        name="Calculator",
        func=llm_math_chain.run,
        description="useful for when you need to answer questions about math",
        args_schema=CalculatorInput
    )
)
# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
> Entering new AgentExecutor chain...
I need to find out Leo DiCaprio's girlfriend's name and her age
Action: Search
Action Input: "Leo DiCaprio girlfriend"DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years.I need to find out Camila Morrone's current age
Action: Calculator
Action Input: 25^(0.43)
> Entering new LLMMathChain chain...
25^(0.43)```text
25**(0.43)
```
...numexpr.evaluate("25**(0.43)")...
Answer: 3.991298452658078
> Finished chain.
Answer: 3.991298452658078I now know the final answer
Final Answer: 3.991298452658078


Final Answer: 3.991298452658078
> Finished chain.
'3.991298452658078'
Subclassing the BaseTool class#
from typing import Type
class CustomSearchTool(BaseTool):
    name = "Search"
    description = "useful for when you need to answer questions about current events"
    def _run(self, query: str) -> str:
        """Use the tool."""
        return search.run(query)

    async def _arun(self, query: str) -> str:
        """Use the tool asynchronously."""
        raise NotImplementedError("BingSearchRun does not support async")

class CustomCalculatorTool(BaseTool):
    name = "Calculator"
    description = "useful for when you need to answer questions about math"
    args_schema: Type[BaseModel] = CalculatorInput
    def _run(self, query: str) -> str:
        """Use the tool."""
        return llm_math_chain.run(query)

    async def _arun(self, query: str) -> str:
        """Use the tool asynchronously."""
        raise NotImplementedError("BingSearchRun does not support async")
tools = [CustomSearchTool(), CustomCalculatorTool()]
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
> Entering new AgentExecutor chain...
I need to find out Leo DiCaprio's girlfriend's name and her age
Action: Search


I need to find out Leo DiCaprio's girlfriend's name and her age
Action: Search
Action Input: "Leo DiCaprio girlfriend"DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years.I need to find out Camila Morrone's current age
Action: Calculator
Action Input: 25^(0.43)
> Entering new LLMMathChain chain...
25^(0.43)```text
25**(0.43)
```
...numexpr.evaluate("25**(0.43)")...
Answer: 3.991298452658078
> Finished chain.
Answer: 3.991298452658078I now know the final answer
Final Answer: 3.991298452658078
> Finished chain.
'3.991298452658078'
Using the tool decorator#
To make it easier to define custom tools, a @tool decorator is provided. This decorator can be used to quickly create a Tool from a simple function. The decorator uses the function name as the tool name by default, but this can be overridden by passing a string as the first argument. Additionally, the decorator will use the function’s docstring as the tool’s description.
from langchain.agents import tool
@tool
def search_api(query: str) -> str:
    """Searches the API for the query."""
    return f"Results for query {query}"
search_api


return f"Results for query {query}"
search_api
Tool(name='search_api', description='search_api(query: str) -> str - Searches the API for the query.', args_schema=<class 'pydantic.main.SearchApi'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bd664c0>, coroutine=None)
You can also provide arguments like the tool name and whether to return directly.
@tool("search", return_direct=True)
def search_api(query: str) -> str:
    """Searches the API for the query."""
    return "Results"
search_api
Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class 'pydantic.main.SearchApi'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bd66310>, coroutine=None)
You can also provide args_schema to provide more information about the argument
class SearchInput(BaseModel):
    query: str = Field(description="should be a search query")

@tool("search", return_direct=True, args_schema=SearchInput)
def search_api(query: str) -> str:
    """Searches the API for the query."""
    return "Results"
search_api


"""Searches the API for the query."""
    return "Results"
search_api
Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class '__main__.SearchInput'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bcf0ee0>, coroutine=None)
Modify existing tools#
Now, we show how to load existing tools and just modify them. In the example below, we do something really simple and change the Search tool to have the name Google Search.
from langchain.agents import load_tools
tools = load_tools(["serpapi", "llm-math"], llm=llm)
tools[0].name = "Google Search"
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
> Entering new AgentExecutor chain...
I need to find out Leo DiCaprio's girlfriend's name and her age.
Action: Google Search
Action Input: "Leo DiCaprio girlfriend"I draw the lime at going to get a Mohawk, though." DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid.Now I need to find out Camila Morrone's current age.
Action: Calculator
Action Input: 25^0.43Answer: 3.991298452658078I now know the final answer.


Final Answer: Camila Morrone's current age raised to the 0.43 power is approximately 3.99.
> Finished chain.
"Camila Morrone's current age raised to the 0.43 power is approximately 3.99."
Defining the priorities among Tools#
When you made a Custom tool, you may want the Agent to use the custom tool more than normal tools.
For example, you made a custom tool, which gets information on music from your database. When a user wants information on songs, You want the Agent to use  the custom tool more than the normal Search tool. But the Agent might prioritize a normal Search tool.
This can be accomplished by adding a statement such as Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?' to the description.
An example is below.
# Import things that are needed generically
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.llms import OpenAI
from langchain import LLMMathChain, SerpAPIWrapper
search = SerpAPIWrapper()
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events"
    ),
    Tool(
        name="Music Search",
        func=lambda x: "'All I Want For Christmas Is You' by Mariah Carey.", #Mock Function
        description="A Music search engine. Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?'",
    )
]


)
]
agent = initialize_agent(tools, OpenAI(temperature=0), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("what is the most famous song of christmas")
> Entering new AgentExecutor chain...
 I should use a music search engine to find the answer
Action: Music Search
Action Input: most famous song of christmas'All I Want For Christmas Is You' by Mariah Carey. I now know the final answer
Final Answer: 'All I Want For Christmas Is You' by Mariah Carey.
> Finished chain.
"'All I Want For Christmas Is You' by Mariah Carey."
Using tools to return directly#
Often, it can be desirable to have a tool output returned directly to the user, if it’s called. You can do this easily with LangChain by setting the return_direct flag for a tool to be True.
llm_math_chain = LLMMathChain(llm=llm)
tools = [
    Tool(
        name="Calculator",
        func=llm_math_chain.run,
        description="useful for when you need to answer questions about math",
        return_direct=True
    )
]
llm = OpenAI(temperature=0)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("whats 2**.12")
> Entering new AgentExecutor chain...
 I need to calculate this
Action: Calculator
Action Input: 2**.12Answer: 1.086734862526058
> Finished chain.
'Answer: 1.086734862526058'
previous
Getting Started
next
Multi-Input Tools
 Contents

Completely New Tools
Tool dataclass
Subclassing the BaseTool class
Using the tool decorator


Tool dataclass
Subclassing the BaseTool class
Using the tool decorator
Modify existing tools
Defining the priorities among Tools
Using tools to return directly
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Multi-Input Tools
Multi-Input Tools#
This notebook shows how to use a tool that requires multiple inputs with an agent.
The difficulty in doing so comes from the fact that an agent decides its next step from a language model, which outputs a string. So if that step requires multiple inputs, they need to be parsed from that. Therefore, the currently supported way to do this is to write a smaller wrapper function that parses a string into multiple inputs.
For a concrete example, let’s work on giving an agent access to a multiplication function, which takes as input two integers. In order to use this, we will tell the agent to generate the “Action Input” as a comma-separated list of length two. We will then write a thin wrapper that takes a string, splits it into two around a comma, and passes both parsed sides as integers to the multiplication function.
from langchain.llms import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
Here is the multiplication function, as well as a wrapper to parse a string as input.
def multiplier(a, b):
    return a * b
def parsing_multiplier(string):
    a, b = string.split(",")
    return multiplier(int(a), int(b))
llm = OpenAI(temperature=0)
tools = [
    Tool(
        name = "Multiplier",
        func=parsing_multiplier,
        description="useful for when you need to multiply two numbers together. The input to this tool should be a comma separated list of numbers of length two, representing the two numbers you want to multiply together. For example, `1,2` would be the input if you wanted to multiply 1 by 2."
    )
]


)
]
mrkl = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
mrkl.run("What is 3 times 4")
> Entering new AgentExecutor chain...
 I need to multiply two numbers
Action: Multiplier
Action Input: 3,4
Observation: 12
Thought: I now know the final answer
Final Answer: 3 times 4 is 12
> Finished chain.
'3 times 4 is 12'
previous
Defining Custom Tools
next
Tool Input Schema
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Tool Input Schema
Tool Input Schema#
By default, tools infer the argument schema by inspecting the function signature. For more strict requirements, custom input schema can be specified, along with custom validation logic.
from typing import Any, Dict
from langchain.agents import AgentType, initialize_agent
from langchain.llms import OpenAI
from langchain.tools.requests.tool import RequestsGetTool, TextRequestsWrapper
from pydantic import BaseModel, Field, root_validator
llm = OpenAI(temperature=0)
!pip install tldextract > /dev/null
[notice] A new release of pip is available: 23.0.1 -> 23.1
[notice] To update, run: pip install --upgrade pip
import tldextract
_APPROVED_DOMAINS = {
    "langchain",
    "wikipedia",
}
class ToolInputSchema(BaseModel):
    url: str = Field(...)

    @root_validator
    def validate_query(cls, values: Dict[str, Any]) -> Dict:
        url = values["url"]
        domain = tldextract.extract(url).domain
        if domain not in _APPROVED_DOMAINS:
            raise ValueError(f"Domain {domain} is not on the approved list:"
                             f" {sorted(_APPROVED_DOMAINS)}")
        return values

tool = RequestsGetTool(args_schema=ToolInputSchema, requests_wrapper=TextRequestsWrapper())
agent = initialize_agent([tool], llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False)
# This will succeed, since there aren't any arguments that will be triggered during validation
answer = agent.run("What's the main title on langchain.com?")
print(answer)


answer = agent.run("What's the main title on langchain.com?")
print(answer)
The main title of langchain.com is "LANG CHAIN 🦜🔗 Official Home Page"
agent.run("What's the main title on google.com?")
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[7], line 1
----> 1 agent.run("What's the main title on google.com?")
File ~/code/lc/lckg/langchain/chains/base.py:213, in Chain.run(self, *args, **kwargs)
    211     if len(args) != 1:
    212         raise ValueError("`run` supports only one positional argument.")
--> 213     return self(args[0])[self.output_keys[0]]
    215 if kwargs and not args:
    216     return self(kwargs)[self.output_keys[0]]
File ~/code/lc/lckg/langchain/chains/base.py:116, in Chain.__call__(self, inputs, return_only_outputs)
    114 except (KeyboardInterrupt, Exception) as e:
    115     self.callback_manager.on_chain_error(e, verbose=self.verbose)
--> 116     raise e
    117 self.callback_manager.on_chain_end(outputs, verbose=self.verbose)
    118 return self.prep_outputs(inputs, outputs, return_only_outputs)
File ~/code/lc/lckg/langchain/chains/base.py:113, in Chain.__call__(self, inputs, return_only_outputs)
    107 self.callback_manager.on_chain_start(
    108     {"name": self.__class__.__name__},
    109     inputs,
    110     verbose=self.verbose,
    111 )
    112 try:
--> 113     outputs = self._call(inputs)


112 try:
--> 113     outputs = self._call(inputs)
    114 except (KeyboardInterrupt, Exception) as e:
    115     self.callback_manager.on_chain_error(e, verbose=self.verbose)
File ~/code/lc/lckg/langchain/agents/agent.py:792, in AgentExecutor._call(self, inputs)
    790 # We now enter the agent loop (until it returns something).
    791 while self._should_continue(iterations, time_elapsed):
--> 792     next_step_output = self._take_next_step(
    793         name_to_tool_map, color_mapping, inputs, intermediate_steps
    794     )
    795     if isinstance(next_step_output, AgentFinish):
    796         return self._return(next_step_output, intermediate_steps)
File ~/code/lc/lckg/langchain/agents/agent.py:695, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps)
    693         tool_run_kwargs["llm_prefix"] = ""
    694     # We then call the tool on the tool input to get an observation
--> 695     observation = tool.run(
    696         agent_action.tool_input,
    697         verbose=self.verbose,
    698         color=color,
    699         **tool_run_kwargs,
    700     )
    701 else:
    702     tool_run_kwargs = self.agent.tool_run_logging_kwargs()
File ~/code/lc/lckg/langchain/tools/base.py:110, in BaseTool.run(self, tool_input, verbose, start_color, color, **kwargs)
    101 def run(
    102     self,
    103     tool_input: Union[str, Dict],
   (...)


103     tool_input: Union[str, Dict],
   (...)
    107     **kwargs: Any,
    108 ) -> str:
    109     """Run the tool."""
--> 110     run_input = self._parse_input(tool_input)
    111     if not self.verbose and verbose is not None:
    112         verbose_ = verbose
File ~/code/lc/lckg/langchain/tools/base.py:71, in BaseTool._parse_input(self, tool_input)
     69 if issubclass(input_args, BaseModel):
     70     key_ = next(iter(input_args.__fields__.keys()))
---> 71     input_args.parse_obj({key_: tool_input})
     72 # Passing as a positional argument is more straightforward for
     73 # backwards compatability
     74 return tool_input
File ~/code/lc/lckg/.venv/lib/python3.11/site-packages/pydantic/main.py:526, in pydantic.main.BaseModel.parse_obj()
File ~/code/lc/lckg/.venv/lib/python3.11/site-packages/pydantic/main.py:341, in pydantic.main.BaseModel.__init__()
ValidationError: 1 validation error for ToolInputSchema
__root__
  Domain google is not on the approved list: ['langchain', 'wikipedia'] (type=value_error)
previous
Multi-Input Tools
next
Apify
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.md
.pdf
Getting Started
 Contents
List of Tools
Getting Started#
Tools are functions that agents can use to interact with the world.
These tools can be generic utilities (e.g. search), other chains, or even other agents.
Currently, tools can be loaded with the following snippet:
from langchain.agents import load_tools
tool_names = [...]
tools = load_tools(tool_names)
Some tools (e.g. chains, agents) may require a base LLM to use to initialize them.
In that case, you can pass in an LLM as well:
from langchain.agents import load_tools
tool_names = [...]
llm = ...
tools = load_tools(tool_names, llm=llm)
Below is a list of all supported tools and relevant information:
Tool Name: The name the LLM refers to the tool by.
Tool Description: The description of the tool that is passed to the LLM.
Notes: Notes about the tool that are NOT passed to the LLM.
Requires LLM: Whether this tool requires an LLM to be initialized.
(Optional) Extra Parameters: What extra parameters are required to initialize this tool.
List of Tools#
python_repl
Tool Name: Python REPL
Tool Description: A Python shell. Use this to execute python commands. Input should be a valid python command. If you expect output it should be printed out.
Notes: Maintains state.
Requires LLM: No
serpapi
Tool Name: Search
Tool Description: A search engine. Useful for when you need to answer questions about current events. Input should be a search query.
Notes: Calls the Serp API and then parses results.
Requires LLM: No
wolfram-alpha
Tool Name: Wolfram Alpha


Requires LLM: No
wolfram-alpha
Tool Name: Wolfram Alpha
Tool Description: A wolfram alpha search engine. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query.
Notes: Calls the Wolfram Alpha API and then parses results.
Requires LLM: No
Extra Parameters: wolfram_alpha_appid: The Wolfram Alpha app id.
requests
Tool Name: Requests
Tool Description: A portal to the internet. Use this when you need to get specific content from a site. Input should be a specific url, and the output will be all the text on that page.
Notes: Uses the Python requests module.
Requires LLM: No
terminal
Tool Name: Terminal
Tool Description: Executes commands in a terminal. Input should be valid commands, and the output will be any output from running that command.
Notes: Executes commands with subprocess.
Requires LLM: No
pal-math
Tool Name: PAL-MATH
Tool Description: A language model that is excellent at solving complex word math problems. Input should be a fully worded hard word math problem.
Notes: Based on this paper.
Requires LLM: Yes
pal-colored-objects
Tool Name: PAL-COLOR-OBJ
Tool Description: A language model that is wonderful at reasoning about position and the color attributes of objects. Input should be a fully worded hard reasoning problem. Make sure to include all information about the objects AND the final question you want to answer.
Notes: Based on this paper.
Requires LLM: Yes
llm-math
Tool Name: Calculator
Tool Description: Useful for when you need to answer questions about math.
Notes: An instance of the LLMMath chain.
Requires LLM: Yes
open-meteo-api
Tool Name: Open Meteo API


Requires LLM: Yes
open-meteo-api
Tool Name: Open Meteo API
Tool Description: Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the Open Meteo API (https://api.open-meteo.com/), specifically the /v1/forecast endpoint.
Requires LLM: Yes
news-api
Tool Name: News API
Tool Description: Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the News API (https://newsapi.org), specifically the /v2/top-headlines endpoint.
Requires LLM: Yes
Extra Parameters: news_api_key (your API key to access this endpoint)
tmdb-api
Tool Name: TMDB API
Tool Description: Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the TMDB API (https://api.themoviedb.org/3), specifically the /search/movie endpoint.
Requires LLM: Yes
Extra Parameters: tmdb_bearer_token (your Bearer Token to access this endpoint - note that this is different from the API key)
google-search
Tool Name: Search
Tool Description: A wrapper around Google Search. Useful for when you need to answer questions about current events. Input should be a search query.
Notes: Uses the Google Custom Search API
Requires LLM: No
Extra Parameters: google_api_key, google_cse_id
For more information on this, see this page
searx-search
Tool Name: Search


For more information on this, see this page
searx-search
Tool Name: Search
Tool Description: A wrapper around SearxNG meta search engine. Input should be a search query.
Notes: SearxNG is easy to deploy self-hosted. It is a good privacy friendly alternative to Google Search. Uses the SearxNG API.
Requires LLM: No
Extra Parameters: searx_host
google-serper
Tool Name: Search
Tool Description: A low-cost Google Search API. Useful for when you need to answer questions about current events. Input should be a search query.
Notes: Calls the serper.dev Google Search API and then parses results.
Requires LLM: No
Extra Parameters: serper_api_key
For more information on this, see this page
wikipedia
Tool Name: Wikipedia
Tool Description: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, historical events, or other subjects. Input should be a search query.
Notes: Uses the wikipedia Python package to call the MediaWiki API and then parses results.
Requires LLM: No
Extra Parameters: top_k_results
podcast-api
Tool Name: Podcast API
Tool Description: Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the Listen Notes Podcast API (https://www.PodcastAPI.com), specifically the /search/ endpoint.
Requires LLM: Yes
Extra Parameters: listen_api_key (your api key to access this endpoint)
openweathermap-api
Tool Name: OpenWeatherMap
Tool Description: A wrapper around OpenWeatherMap API. Useful for fetching current weather information for a specified location. Input should be a location string (e.g. ‘London,GB’).


Notes: A connection to the OpenWeatherMap API (https://api.openweathermap.org), specifically the /data/2.5/weather endpoint.
Requires LLM: No
Extra Parameters: openweathermap_api_key (your API key to access this endpoint)
previous
Tools
next
Defining Custom Tools
 Contents

List of Tools
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
File System Tools
 Contents
The FileManagementToolkit
Selecting File System Tools
File System Tools#
LangChain provides tools for interacting with a local file system out of the box. This notebook walks through some of them.
Note: these tools are not recommended for use outside a sandboxed environment!
First, we’ll import the tools.
from langchain.tools.file_management import (
    ReadFileTool,
    CopyFileTool,
    DeleteFileTool,
    MoveFileTool,
    WriteFileTool,
    ListDirectoryTool,
)
from langchain.agents.agent_toolkits import FileManagementToolkit
from tempfile import TemporaryDirectory
# We'll make a temporary directory to avoid clutter
working_directory = TemporaryDirectory()
The FileManagementToolkit#
If you want to provide all the file tooling to your agent, it’s easy to do so with the toolkit. We’ll pass the temporary directory in as a root directory as a workspace for the LLM.
It’s recommended to always pass in a root directory, since without one, it’s easy for the LLM to pollute the working directory, and without one, there isn’t any validation against
straightforward prompt injection.
toolkit = FileManagementToolkit(root_dir=str(working_directory.name)) # If you don't provide a root_dir, operations will default to the current working directory
toolkit.get_tools()


toolkit.get_tools()
[CopyFileTool(name='copy_file', description='Create a copy of a file in a specified location', args_schema=<class 'langchain.tools.file_management.copy.FileCopyInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
 DeleteFileTool(name='file_delete', description='Delete a file', args_schema=<class 'langchain.tools.file_management.delete.FileDeleteInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
 FileSearchTool(name='file_search', description='Recursively search for files in a subdirectory that match the regex pattern', args_schema=<class 'langchain.tools.file_management.file_search.FileSearchInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),


MoveFileTool(name='move_file', description='Move or rename a file from one location to another', args_schema=<class 'langchain.tools.file_management.move.FileMoveInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
 ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
 WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
 ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]


Selecting File System Tools#
If you only want to select certain tools, you can pass them in as arguments when initializing the toolkit, or you can individually initialize the desired tools.
tools = FileManagementToolkit(root_dir=str(working_directory.name), selected_tools=["read_file", "write_file", "list_directory"]).get_tools()
tools
[ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
 WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
 ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]
read_tool, write_tool, list_tool = tools
write_tool.run({"file_path": "example.txt", "text": "Hello World!"})


write_tool.run({"file_path": "example.txt", "text": "Hello World!"})
'File written successfully to example.txt.'
# List files in the working directory
list_tool.run({})
'example.txt'
previous
DuckDuckGo Search
next
Google Places
 Contents

The FileManagementToolkit
Selecting File System Tools
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Google Search
 Contents
Number of Results
Metadata Results
Google Search#
This notebook goes over how to use the google search component.
First, you need to set up the proper API keys and environment variables. To set it up, create the GOOGLE_API_KEY in the Google Cloud credential console (https://console.cloud.google.com/apis/credentials) and a GOOGLE_CSE_ID using the Programmable Search Enginge (https://programmablesearchengine.google.com/controlpanel/create). Next, it is good to follow the instructions found here.
Then we will need to set some environment variables.
import os
os.environ["GOOGLE_CSE_ID"] = ""
os.environ["GOOGLE_API_KEY"] = ""
from langchain.utilities import GoogleSearchAPIWrapper
search = GoogleSearchAPIWrapper()
search.run("Obama's first name?")


'1 Child\'s First Name. 2. 6. 7d. Street Address. 71. (Type or print). BARACK. Sex. 3. This Birth. 4. If Twin or Triplet,. Was Child Born. Barack Hussein Obama II is an American retired politician who served as the 44th president of the United States from 2009 to 2017. His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Feb 9, 2015 ... Michael Jordan misspelled Barack Obama\'s first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama\'s first name. Miller knew that every answer had to end\xa0... First Lady Michelle LaVaughn Robinson Obama is a lawyer, writer, and the wife of the 44th President, Barack Obama. She is the first African-American First\xa0... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009–17) and the first\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Feb 27, 2020 ... President Barack Obama was born Barack Hussein Obama, II, as shown here on his birth certificate here . As reported by Reuters here , his\xa0... Jan 16, 2007 ... 4, 1961, in Honolulu. His first name means "one who is blessed" in Swahili. While Obama\'s father, Barack Hussein Obama Sr., was from Kenya, his\xa0...'


Number of Results#
You can use the k parameter to set the number of results
search = GoogleSearchAPIWrapper(k=1)
search.run("python")
'The official home of the Python Programming Language.'
‘The official home of the Python Programming Language.’
Metadata Results#
Run query through GoogleSearch and return snippet, title, and link metadata.
Snippet: The description of the result.
Title: The title of the result.
Link: The link to the result.
search = GoogleSearchAPIWrapper()
search.results("apples", 5)
[{'snippet': 'Discover the innovative world of Apple and shop everything iPhone, iPad, Apple Watch, Mac, and Apple TV, plus explore accessories, entertainment,\xa0...',
  'title': 'Apple',
  'link': 'https://www.apple.com/'},
 {'snippet': "Jul 10, 2022 ... Whether or not you're up on your apple trivia, no doubt you know how delicious this popular fruit is, and how nutritious. Apples are rich in\xa0...",
  'title': '25 Types of Apples and What to Make With Them - Parade ...',
  'link': 'https://parade.com/1330308/bethlipton/types-of-apples/'},
 {'snippet': 'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the\xa0...',
  'title': 'Apple - Wikipedia',
  'link': 'https://en.wikipedia.org/wiki/Apple'},
 {'snippet': 'Apples are a popular fruit. They contain antioxidants, vitamins, dietary fiber, and a range of other nutrients. Due to their varied nutrient content,\xa0...',
  'title': 'Apples: Benefits, nutrition, and tips',


'title': 'Apples: Benefits, nutrition, and tips',
  'link': 'https://www.medicalnewstoday.com/articles/267290'},
 {'snippet': "An apple is a crunchy, bright-colored fruit, one of the most popular in the United States. You've probably heard the age-old saying, “An apple a day keeps\xa0...",
  'title': 'Apples: Nutrition & Health Benefits',
  'link': 'https://www.webmd.com/food-recipes/benefits-apples'}]
previous
Google Places
next
Google Serper API
 Contents

Number of Results
Metadata Results
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Bing Search
 Contents
Number of results
Metadata Results
Bing Search#
This notebook goes over how to use the bing search component.
First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found here.
Then we will need to set some environment variables.
import os
os.environ["BING_SUBSCRIPTION_KEY"] = ""
os.environ["BING_SEARCH_URL"] = ""
from langchain.utilities import BingSearchAPIWrapper
search = BingSearchAPIWrapper()
search.run("python")


'Thanks to the flexibility of Python and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with Python by Dan Taylor. Python releases by version number: Release version Release date Click for more. Python 3.11.1 Dec. 6, 2022 Download Release Notes. Python 3.10.9 Dec. 6, 2022 Download Release Notes. Python 3.9.16 Dec. 6, 2022 Download Release Notes. Python 3.8.16 Dec. 6, 2022 Download Release Notes. Python 3.7.16 Dec. 6, 2022 Download Release Notes. In this lesson, we will look at the += operator in Python and see how it works with several simple examples.. The operator ‘+=’ is a shorthand for the addition assignment operator.It adds two values and assigns the sum


assignment operator.It adds two values and assigns the sum to a variable (left operand). W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more. This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see The Python Standard ... Python is a general-purpose, versatile, and powerful programming language. It's a great first language because Python code is concise and easy to read. Whatever you want to do, python can do it. From web development to machine learning to data science, Python is the language for you. To install Python using the Microsoft Store:


To install Python using the Microsoft Store: Go to your Start menu (lower left Windows icon), type "Microsoft Store", select the link to open the store. Once the store is open, select Search from the upper-right menu and enter "Python". Select which version of Python you would like to use from the results under Apps. Under the “Python Releases for Mac OS X” heading, click the link for the Latest Python 3 Release - Python 3.x.x. As of this writing, the latest version was Python 3.8.4. Scroll to the bottom and click macOS 64-bit installer to start the download. When the installer is finished downloading, move on to the next step. Step 2: Run the Installer'


Number of results#
You can use the k parameter to set the number of results
search = BingSearchAPIWrapper(k=1)
search.run("python")
'Thanks to the flexibility of Python and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with Python by Dan Taylor.'
Metadata Results#
Run query through BingSearch and return snippet, title, and link metadata.
Snippet: The description of the result.
Title: The title of the result.
Link: The link to the result.
search = BingSearchAPIWrapper()
search.results("apples", 5)
[{'snippet': 'Lady Alice. Pink Lady apples aren’t the only lady in the apple family. Lady Alice apples were discovered growing, thanks to bees pollinating, in Washington. They are smaller and slightly more stout in appearance than other varieties. Their skin color appears to have red and yellow stripes running from stem to butt.',
  'title': '25 Types of Apples - Jessica Gavin',
  'link': 'https://www.jessicagavin.com/types-of-apples/'},
 {'snippet': 'Apples can do a lot for you, thanks to plant chemicals called flavonoids. And they have pectin, a fiber that breaks down in your gut. If you take off the apple’s skin before eating it, you won ...',
  'title': 'Apples: Nutrition & Health Benefits - WebMD',
  'link': 'https://www.webmd.com/food-recipes/benefits-apples'},


{'snippet': 'Apples boast many vitamins and minerals, though not in high amounts. However, apples are usually a good source of vitamin C. Vitamin C. Also called ascorbic acid, this vitamin is a common ...',
  'title': 'Apples 101: Nutrition Facts and Health Benefits',
  'link': 'https://www.healthline.com/nutrition/foods/apples'},
 {'snippet': 'Weight management. The fibers in apples can slow digestion, helping one to feel greater satisfaction after eating. After following three large prospective cohorts of 133,468 men and women for 24 years, researchers found that higher intakes of fiber-rich fruits with a low glycemic load, particularly apples and pears, were associated with the least amount of weight gain over time.',
  'title': 'Apples | The Nutrition Source | Harvard T.H. Chan School of Public Health',
  'link': 'https://www.hsph.harvard.edu/nutritionsource/food-features/apples/'}]
previous
Shell Tool
next
ChatGPT Plugins
 Contents

Number of results
Metadata Results
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
SerpAPI
 Contents
Custom Parameters
SerpAPI#
This notebook goes over how to use the SerpAPI component to search the web.
from langchain.utilities import SerpAPIWrapper
search = SerpAPIWrapper()
search.run("Obama's first name?")
'Barack Hussein Obama II'
Custom Parameters#
You can also customize the SerpAPI wrapper with arbitrary parameters. For example, in the below example we will use bing instead of google.
params = {
    "engine": "bing",
    "gl": "us",
    "hl": "en",
}
search = SerpAPIWrapper(params=params)
search.run("Obama's first name?")
'Barack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American presi…New content will be added above the current area of focus upon selectionBarack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American president of the United States. He previously served as a U.S. senator from Illinois from 2005 to 2008 and as an Illinois state senator from 1997 to 2004, and previously worked as a civil rights lawyer before entering politics.Wikipediabarackobama.com'
from langchain.agents import Tool
# You can create the tool to pass to an agent
repl_tool = Tool(
    name="python_repl",


repl_tool = Tool(
    name="python_repl",
    description="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.",
    func=search.run,
)
previous
SearxNG Search API
next
Wikipedia API
 Contents

Custom Parameters
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Google Places
Google Places#
This notebook goes through how to use Google Places API
#!pip install googlemaps
import os
os.environ["GPLACES_API_KEY"] = ""
from langchain.tools import GooglePlacesTool
places = GooglePlacesTool()
places.run("al fornos")
"1. Delfina Restaurant\nAddress: 3621 18th St, San Francisco, CA 94110, USA\nPhone: (415) 552-4055\nWebsite: https://www.delfinasf.com/\n\n\n2. Piccolo Forno\nAddress: 725 Columbus Ave, San Francisco, CA 94133, USA\nPhone: (415) 757-0087\nWebsite: https://piccolo-forno-sf.com/\n\n\n3. L'Osteria del Forno\nAddress: 519 Columbus Ave, San Francisco, CA 94133, USA\nPhone: (415) 982-1124\nWebsite: Unknown\n\n\n4. Il Fornaio\nAddress: 1265 Battery St, San Francisco, CA 94111, USA\nPhone: (415) 986-0100\nWebsite: https://www.ilfornaio.com/\n\n"
previous
File System Tools
next
Google Search
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Wolfram Alpha
Wolfram Alpha#
This notebook goes over how to use the wolfram alpha component.
First, you need to set up your Wolfram Alpha developer account and get your APP ID:
Go to wolfram alpha and sign up for a developer account here
Create an app and get your APP ID
pip install wolframalpha
Then we will need to set some environment variables:
Save your APP ID into WOLFRAM_ALPHA_APPID env variable
pip install wolframalpha
import os
os.environ["WOLFRAM_ALPHA_APPID"] = ""
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
wolfram = WolframAlphaAPIWrapper()
wolfram.run("What is 2x+5 = -3x + 7?")
'x = 2/5'
previous
Wikipedia API
next
Zapier Natural Language Actions API
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Google Serper API
 Contents
As part of a Self Ask With Search Chain
Google Serper API#
This notebook goes over how to use the Google Serper component to search the web. First you need to sign up for a free account at serper.dev and get your api key.
import os
os.environ["SERPER_API_KEY"] = ""
from langchain.utilities import GoogleSerperAPIWrapper
search = GoogleSerperAPIWrapper()
search.run("Obama's first name?")
'Barack Hussein Obama II'
As part of a Self Ask With Search Chain#
os.environ['OPENAI_API_KEY'] = ""
from langchain.utilities import GoogleSerperAPIWrapper
from langchain.llms.openai import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
llm = OpenAI(temperature=0)
search = GoogleSerperAPIWrapper()
tools = [
    Tool(
        name="Intermediate Answer",
        func=search.run,
        description="useful for when you need to ask with search"
    )
]
self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True)
self_ask_with_search.run("What is the hometown of the reigning men's U.S. Open champion?")
> Entering new AgentExecutor chain...
 Yes.
Follow up: Who is the reigning men's U.S. Open champion?
Intermediate answer: Current champions Carlos Alcaraz, 2022 men's singles champion.
Follow up: Where is Carlos Alcaraz from?
Intermediate answer: El Palmar, Spain
So the final answer is: El Palmar, Spain
> Finished chain.
'El Palmar, Spain'
previous
Google Search
next
Gradio Tools


'El Palmar, Spain'
previous
Google Search
next
Gradio Tools
 Contents

As part of a Self Ask With Search Chain
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Python REPL
Python REPL#
Sometimes, for complex calculations, rather than have an LLM generate the answer directly, it can be better to have the LLM generate code to calculate the answer, and then run that code to get the answer. In order to easily do that, we provide a simple Python REPL to execute commands in.
This interface will only return things that are printed - therefor, if you want to use it to calculate an answer, make sure to have it print out the answer.
from langchain.agents import Tool
from langchain.utilities import PythonREPL
python_repl = PythonREPL()
python_repl.run("print(1+1)")
'2\n'
# You can create the tool to pass to an agent
repl_tool = Tool(
    name="python_repl",
    description="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.",
    func=python_repl
)
previous
OpenWeatherMap API
next
Requests
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
IFTTT WebHooks
 Contents
Creating a webhook
Configuring the “If This”
Configuring the “Then That”
Finishing up
IFTTT WebHooks#
This notebook shows how to use IFTTT Webhooks.
From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.
Creating a webhook#
Go to https://ifttt.com/create
Configuring the “If This”#
Click on the “If This” button in the IFTTT interface.
Search for “Webhooks” in the search bar.
Choose the first option for “Receive a web request with a JSON payload.”
Choose an Event Name that is specific to the service you plan to connect to.
This will make it easier for you to manage the webhook URL.
For example, if you’re connecting to Spotify, you could use “Spotify” as your
Event Name.
Click the “Create Trigger” button to save your settings and create your webhook.
Configuring the “Then That”#
Tap on the “Then That” button in the IFTTT interface.
Search for the service you want to connect, such as Spotify.
Choose an action from the service, such as “Add track to a playlist”.
Configure the action by specifying the necessary details, such as the playlist name,
e.g., “Songs from AI”.
Reference the JSON Payload received by the Webhook in your action. For the Spotify
scenario, choose “{{JsonPayload}}” as your search query.
Tap the “Create Action” button to save your action settings.
Once you have finished configuring your action, click the “Finish” button to
complete the setup.
Congratulations! You have successfully connected the Webhook to the desired
service, and you’re ready to start receiving data and triggering actions 🎉


service, and you’re ready to start receiving data and triggering actions 🎉
Finishing up#
To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
from langchain.tools.ifttt import IFTTTWebhook
import os
key = os.environ["IFTTTKey"]
url = f"https://maker.ifttt.com/trigger/spotify/json/with/key/{key}"
tool = IFTTTWebhook(name="Spotify", description="Add a song to spotify playlist", url=url)
tool.run("taylor swift")
"Congratulations! You've fired the spotify JSON event"
previous
Human as a tool
next
OpenWeatherMap API
 Contents

Creating a webhook
Configuring the “If This”
Configuring the “Then That”
Finishing up
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
Requests
Requests#
The web contains a lot of information that LLMs do not have access to. In order to easily let LLMs interact with that information, we provide a wrapper around the Python Requests module that takes in a URL and fetches data from that URL.
from langchain.utilities import TextRequestsWrapper
requests = TextRequestsWrapper()
requests.get("https://www.google.com")


'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s information, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/logos/doodles/2023/international-womens-day-2023-6753651837109578-l.png" itemprop="image"><meta content="International Women\'s Day 2023" property="twitter:title"><meta content="International Women\'s Day 2023! #GoogleDoodle" property="twitter:description"><meta content="International Women\'s Day 2023! #GoogleDoodle" property="og:description"><meta content="summary_large_image" property="twitter:card"><meta content="@GoogleDoodles" property="twitter:site"><meta content="https://www.google.com/logos/doodles/2023/international-womens-day-2023-6753651837109578-2x.png" property="twitter:image"><meta content="https://www.google.com/logos/doodles/2023/international-womens-day-2023-6753651837109578-2x.png" property="og:image"><meta content="1000" property="og:image:width"><meta content="400" property="og:image:height"><title>Google</title><script


!important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}\n</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#1558d6}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}body{background:#fff;color:#000}a{color:#4b11a8;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#1558d6}a:visited{color:#4b11a8}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#f8f9fa;border:solid 1px;border-color:#dadce0 #70757a #70757a #dadce0;height:30px}.lsbb{display:block}#WqQANb a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261px


0 -261px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#dadce0}.lst:focus{outline:none}</style><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){window.google.erd={jsr:1,bv:1756,de:true};\nvar h=this||self;var k,l=null!=(k=h.mei)?k:1,n,p=null!=(n=h.sdo)?n:!0,q=0,r,t=google.erd,v=t.jsr;google.ml=function(a,b,d,m,e){e=void 0===e?2:e;b&&(r=a&&a.message);if(google.dl)return google.dl(a,e,d),null;if(0>v){window.console&&console.error(a,d);if(-2===v)throw a;b=!1}else b=!a||!a.message||"Error loading script"===a.message||q>=l&&!m?!1:!0;if(!b)return null;q++;d=d||{};b=encodeURIComponent;var c="/gen_204?atyp=i&ei="+b(google.kEI);google.kEXPI&&(c+="&jexpid="+b(google.kEXPI));c+="&srcpg="+b(google.sn)+"&jsr="+b(t.jsr)+"&bver="+b(t.bv);var f=a.lineNumber;void 0!==f&&(c+="&line="+f);var


f=a.lineNumber;void 0!==f&&(c+="&line="+f);var g=\na.fileName;g&&(0<g.indexOf("-extension:/")&&(e=3),c+="&script="+b(g),f&&g===window.location.href&&(f=document.documentElement.outerHTML.split("\\n")[f],c+="&cad="+b(f?f.substring(0,300):"No script found.")));c+="&jsel="+e;for(var u in d)c+="&",c+=b(u),c+="=",c+=b(d[u]);c=c+"&emsg="+b(a.name+": "+a.message);c=c+"&jsst="+b(a.stack||"N/A");12288<=c.length&&(c=c.substr(0,12288));a=c;m||google.log(0,"",a);return a};window.onerror=function(a,b,d,m,e){r!==a&&(a=e instanceof Error?e:Error(a),void 0===d||"lineNumber"in a||(a.lineNumber=d),void 0===b||"fileName"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,"SyntaxError"===a.name||"SyntaxError"===a.message.substring(0,11)||-1!==a.message.indexOf("Script error")?3:0));r=null;p&&q>=l&&(window.onerror=null)};})();</script></head><body bgcolor="#fff"><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){var src=\'/images/nav_logo229.png\';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}\nif


window.n();if (document.images){new Image().src=src;}\nif (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}\n}\n})();</script>

<nobr>Search Images Maps Play YouTube News Gmail Drive More »</nobr>

<nobr>Web History | <a


class=gb4>Web History | Settings | Sign in</nobr>

<img alt="International Women\'s Day 2023" border="0" height="200"


Women\'s Day 2023" border="0" height="200" src="/logos/doodles/2023/international-womens-day-2023-6753651837109578-l.png" title="International Women\'s Day 2023" width="500" id="hplogo">

<form action="/search" name="f">

 	<input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden">
<input class="lst" style="margin:0;padding:5px 8px 0 6px;vertical-align:top;color:#000" autocomplete="off" value="" title="Google Search" maxlength="2048" name="q" size="57">

<input class="lsb" value="Google Search" name="btnG" type="submit"><input class="lsb" id="tsuid_1" value="I\'m Feeling Lucky" name="btnI" type="submit">


Feeling Lucky" name="btnI" type="submit"><input value="AK50M_UAAAAAZAjn9T7DxAH0-e8rhw3d8palbJFsdibi" name="iflsig" type="hidden">	Advanced search

<input id="gbv" name="gbv" type="hidden" value="1">


f=google.gbvu,g=document.getElementById("gbv");g&&(g.value=a);f&&window.setTimeout(function(){location.href=f},0)};}).call(this);</script></form>

Celebrate International Women\'s Day with Google

<div


id="footer">

AdvertisingBusiness SolutionsAbout Google

© 2023 - Privacy - Terms


nonce="skA52jTjrFARNMkurZZTjQ">(function(){var u=\'/xjs/_/js/k\\x3dxjs.hp.en.ObwAV4EjOBQ.O/am\\x3dAACgEwBAAYAF/d\\x3d1/ed\\x3d1/rs\\x3dACT90oGDUDSLlBIGF3CSmUWoHe0AKqeZ6w/m\\x3dsb_he,d\';var amd=0;\nvar d=this||self,e=function(a){return a};var g;var l=function(a,b){this.g=b===h?a:""};l.prototype.toString=function(){return this.g+""};var h={};\nfunction m(){var a=u;google.lx=function(){p(a);google.lx=function(){}};google.bx||google.lx()}\nfunction p(a){google.timers&&google.timers.load&&google.tick&&google.tick("load","xjsls");var b=document;var c="SCRIPT";"application/xhtml+xml"===b.contentType&&(c=c.toLowerCase());c=b.createElement(c);a=null===a?"null":void 0===a?"undefined":a;if(void 0===g){b=null;var k=d.trustedTypes;if(k&&k.createPolicy){try{b=k.createPolicy("goog#html",{createHTML:e,createScript:e,createScriptURL:e})}catch(q){d.console&&d.console.error(q.message)}g=b}else g=b}a=(b=g)?b.createScriptURL(a):a;a=new l(a,h);c.src=\na instanceof l&&a.constructor===l?a.g:"type_error:TrustedResourceUrl";var


Search\\x22,\\x22dym\\x22:\\x22Did you mean:\\x22,\\x22lcky\\x22:\\x22I\\\\u0026#39;m Feeling Lucky\\x22,\\x22lml\\x22:\\x22Learn more\\x22,\\x22psrc\\x22:\\x22This search was removed from your \\\\u003Ca href\\x3d\\\\\\x22/history\\\\\\x22\\\\u003EWeb History\\\\u003C/a\\\\u003E\\x22,\\x22psrl\\x22:\\x22Remove\\x22,\\x22sbit\\x22:\\x22Search by image\\x22,\\x22srch\\x22:\\x22Google Search\\x22},\\x22ovr\\x22:{},\\x22pq\\x22:\\x22\\x22,\\x22rfs\\x22:[],\\x22sbas\\x22:\\x220 3px 8px 0 rgba(0,0,0,0.2),0 0 0 1px rgba(0,0,0,0.08)\\x22,\\x22stok\\x22:\\x222J2TpqBbW29n4YEWhckcWkIgvqM\\x22}}\';google.pmc=JSON.parse(pmc);})();</script>        </body></html>'


previous
Python REPL
next
SceneXplain
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on May 01, 2023.


.ipynb
.pdf
SearxNG Search API
 Contents
Custom Parameters
Obtaining results with metadata
SearxNG Search API#
This notebook goes over how to use a self hosted SearxNG search API to search the web.
You can check this link for more informations about Searx API parameters.
import pprint
from langchain.utilities import SearxSearchWrapper
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888")
For some engines, if a direct answer is available the warpper will print the answer instead of the full list of search results. You can use the results method of the wrapper if you want to obtain all the results.
search.run("What is the capital of France")
'Paris is the capital of France, the largest country of Europe with 550 000 km2 (65 millions inhabitants). Paris has 2.234 million inhabitants end 2011. She is the core of Ile de France region (12 million people).'
Custom Parameters#
SearxNG supports up to 139 search engines. You can also customize the Searx wrapper with arbitrary named parameters that will be passed to the Searx search API . In the below example we will making a more interesting use of custom search parameters from searx search api.
In this example we will be using the engines parameters to query wikipedia
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888", k=5) # k is for max number of items
search.run("large language model ", engines=['wiki'])


search.run("large language model ", engines=['wiki'])
'Large language models (LLMs) represent a major advancement in AI, with the promise of transforming domains through learned knowledge. LLM sizes have been increasing 10X every year for the last few years, and as these models grow in complexity and size, so do their capabilities.\n\nGPT-3 can translate language, write essays, generate computer code, and more — all with limited to no supervision. In July 2020, OpenAI unveiled GPT-3, a language model that was easily the largest known at the time. Put simply, GPT-3 is trained to predict the next word in a sentence, much like how a text message autocomplete feature works.\n\nA large language model, or LLM, is a deep learning algorithm that can recognize, summarize, translate, predict and generate text and other content based on knowledge gained from massive datasets. Large language models are among the most successful applications of transformer models.\n\nAll of today’s well-known language models—e.g., GPT-3 from OpenAI, PaLM or LaMDA from Google, Galactica or OPT from Meta, Megatron-Turing from Nvidia/Microsoft, Jurassic-1 from AI21 Labs—are...\n\nLarge language models (LLMs) such as GPT-3are increasingly being used to generate text. These tools should be used with care, since they can generate content that is biased, non-verifiable, constitutes original research, or violates copyrights.'
Passing other Searx parameters for searx like language
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888", k=1)
search.run("deep learning", language='es', engines=['wiki'])


search.run("deep learning", language='es', engines=['wiki'])
'Aprendizaje profundo (en inglés, deep learning) es un conjunto de algoritmos de aprendizaje automático (en inglés, machine learning) que intenta modelar abstracciones de alto nivel en datos usando arquitecturas computacionales que admiten transformaciones no lineales múltiples e iterativas de datos expresados en forma matricial o tensorial. 1'
Obtaining results with metadata#
In this example we will be looking for scientific paper using the categories parameter and limiting the results to a time_range (not all engines support the time range option).
We also would like to obtain the results in a structured way including metadata. For this we will be using the results method of the wrapper.
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888")
results = search.results("Large Language Model prompt", num_results=5, categories='science', time_range='year')
pprint.pp(results)
[{'snippet': '… on natural language instructions, large language models (… the '
             'prompt used to steer the model, and most effective prompts … to '
             'prompt engineering, we propose Automatic Prompt …',
  'title': 'Large language models are human-level prompt engineers',
  'link': 'https://arxiv.org/abs/2211.01910',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… Large language models (LLMs) have introduced new possibilities '
             'for prototyping with AI [18]. Pre-trained on a large amount of '
             'text data, models … language instructions called prompts. …',
  'title': 'Promptchainer: Chaining large language model prompts through '


'title': 'Promptchainer: Chaining large language model prompts through '
           'visual programming',
  'link': 'https://dl.acm.org/doi/abs/10.1145/3491101.3519729',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… can introspect the large prompt model. We derive the view '
             'ϕ0(X) and the model h0 from T01. However, instead of fully '
             'fine-tuning T0 during co-training, we focus on soft prompt '
             'tuning, …',
  'title': 'Co-training improves prompt-based learning for large language '
           'models',
  'link': 'https://proceedings.mlr.press/v162/lang22a.html',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… With the success of large language models (LLMs) of code and '
             'their use as … prompt design process become important. In this '
             'work, we propose a framework called Repo-Level Prompt …',
  'title': 'Repository-level prompt generation for large language models of '
           'code',
  'link': 'https://arxiv.org/abs/2206.12839',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… Figure 2 | The benefits of different components of a prompt '
             'for the largest language model (Gopher), as estimated from '
             'hierarchical logistic regression. Each point estimates the '
             'unique …',
  'title': 'Can language models learn from explanations in context?',
  'link': 'https://arxiv.org/abs/2204.02329',


'link': 'https://arxiv.org/abs/2204.02329',
  'engines': ['google scholar'],
  'category': 'science'}]
Get papers from arxiv
results = search.results("Large Language Model prompt", num_results=5, engines=['arxiv'])
pprint.pp(results)
[{'snippet': 'Thanks to the advanced improvement of large pre-trained language '
             'models, prompt-based fine-tuning is shown to be effective on a '
             'variety of downstream tasks. Though many prompting methods have '
             'been investigated, it remains unknown which type of prompts are '
             'the most effective among three types of prompts (i.e., '
             'human-designed prompts, schema prompts and null prompts). In '
             'this work, we empirically compare the three types of prompts '
             'under both few-shot and fully-supervised settings. Our '
             'experimental results show that schema prompts are the most '
             'effective in general. Besides, the performance gaps tend to '
             'diminish when the scale of training data grows large.',
  'title': 'Do Prompts Solve NLP Tasks Using Natural Language?',
  'link': 'http://arxiv.org/abs/2203.00902v1',
  'engines': ['arxiv'],
  'category': 'science'},
 {'snippet': 'Cross-prompt automated essay scoring (AES) requires the system '
             'to use non target-prompt essays to award scores to a '
             'target-prompt essay. Since obtaining a large quantity of '
             'pre-graded essays to a particular prompt is often difficult and '
             'unrealistic, the task of cross-prompt AES is vital for the '
             'development of real-world AES systems, yet it remains an '


'development of real-world AES systems, yet it remains an '
             'under-explored area of research. Models designed for '
             'prompt-specific AES rely heavily on prompt-specific knowledge '
             'and perform poorly in the cross-prompt setting, whereas current '
             'approaches to cross-prompt AES either require a certain quantity '
             'of labelled target-prompt essays or require a large quantity of '
             'unlabelled target-prompt essays to perform transfer learning in '
             'a multi-step manner. To address these issues, we introduce '
             'Prompt Agnostic Essay Scorer (PAES) for cross-prompt AES. Our '
             'method requires no access to labelled or unlabelled '
             'target-prompt data during training and is a single-stage '
             'approach. PAES is easy to apply in practice and achieves '
             'state-of-the-art performance on the Automated Student Assessment '
             'Prize (ASAP) dataset.',
  'title': 'Prompt Agnostic Essay Scorer: A Domain Generalization Approach to '
           'Cross-prompt Automated Essay Scoring',
  'link': 'http://arxiv.org/abs/2008.01441v1',
  'engines': ['arxiv'],
  'category': 'science'},
 {'snippet': 'Research on prompting has shown excellent performance with '
             'little or even no supervised training across many tasks. '
             'However, prompting for machine translation is still '
             'under-explored in the literature. We fill this gap by offering a '
             'systematic study on prompting strategies for translation, '
             'examining various factors for prompt template and demonstration '
             'example selection. We further explore the use of monolingual '


'example selection. We further explore the use of monolingual '
             'data and the feasibility of cross-lingual, cross-domain, and '
             'sentence-to-document transfer learning in prompting. Extensive '
             'experiments with GLM-130B (Zeng et al., 2022) as the testbed '
             'show that 1) the number and the quality of prompt examples '
             'matter, where using suboptimal examples degenerates translation; '
             '2) several features of prompt examples, such as semantic '
             'similarity, show significant Spearman correlation with their '
             'prompting performance; yet, none of the correlations are strong '
             'enough; 3) using pseudo parallel prompt examples constructed '
             'from monolingual data via zero-shot prompting could improve '
             'translation; and 4) improved performance is achievable by '
             'transferring knowledge from prompt examples selected in other '
             'settings. We finally provide an analysis on the model outputs '
             'and discuss several problems that prompting still suffers from.',
  'title': 'Prompting Large Language Model for Machine Translation: A Case '
           'Study',
  'link': 'http://arxiv.org/abs/2301.07069v2',
  'engines': ['arxiv'],
  'category': 'science'},
 {'snippet': 'Large language models can perform new tasks in a zero-shot '
             'fashion, given natural language prompts that specify the desired '
             'behavior. Such prompts are typically hand engineered, but can '
             'also be learned with gradient-based methods from labeled data. '
             'However, it is underexplored what factors make the prompts '
             'effective, especially when the prompts are natural language. In '