'3 times 4 is 12'
Multi-Input Tools with a string format#
An alternative to the structured tool would be to use the regular Tool class and accept a single string. The tool would then have to handle the parsing logic to extract the relavent values from the text, which tightly couples the tool representation to the agent prompt. This is still useful if the underlying language model can’t reliabl generate structured schema.
Let’s take the multiplication function as an example. 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...


> 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
 Contents

Multi-Input Tools with a string format
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 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 Jun 07, 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)


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)
    114 except (KeyboardInterrupt, Exception) as e:


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],
   (...)
    107     **kwargs: Any,
    108 ) -> str:


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 Jun 07, 2023.


.ipynb
.pdf
Wikipedia
Wikipedia#
Wikipedia is a multilingual free online encyclopedia written and maintained by a community of volunteers, known as Wikipedians, through open collaboration and using a wiki-based editing system called MediaWiki. Wikipedia is the largest and most-read reference work in history.
First, you need to install wikipedia python package.
!pip install wikipedia
from langchain.utilities import WikipediaAPIWrapper
wikipedia = WikipediaAPIWrapper()
wikipedia.run('HUNTER X HUNTER')


'Page: Hunter × Hunter\nSummary: Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses since 2006. Its chapters have been collected in 37 tankōbon volumes as of November 2022. The story focuses on a young boy named Gon Freecss who discovers that his father, who left him at a young age, is actually a world-renowned Hunter, a licensed professional who specializes in fantastical pursuits such as locating rare or unidentified animal species, treasure hunting, surveying unexplored enclaves, or hunting down lawless individuals. Gon departs on a journey to become a Hunter and eventually find his father. Along the way, Gon meets various other Hunters and encounters the paranormal.\nHunter × Hunter was adapted into a 62-episode anime television series produced by Nippon Animation and directed by Kazuhiro Furuhashi, which ran on Fuji Television from October 1999 to March 2001. Three separate original video animations (OVAs) totaling 30 episodes were subsequently produced by Nippon Animation and released in Japan from 2002 to 2004. A second anime television series by Madhouse aired on Nippon Television from October 2011 to September 2014, totaling 148 episodes, with two animated theatrical films released in 2013. There are also numerous audio albums, video games, musicals, and other media based on Hunter × Hunter.\nThe manga has been translated into English and released in North America by Viz Media since April 2005. Both television series have been also licensed by Viz Media, with the first series having aired on the Funimation Channel in 2009


by Viz Media, with the first series having aired on the Funimation Channel in 2009 and the second series broadcast on Adult Swim\'s Toonami programming block from April 2016 to June 2019.\nHunter × Hunter has been a huge critical and financial success and has become one of the best-selling manga series of all time, having over 84 million copies in circulation by July 2022.\n\nPage: Hunter × Hunter (2011 TV series)\nSummary: Hunter × Hunter is an anime television series that aired from 2011 to 2014 based on Yoshihiro Togashi\'s manga series Hunter × Hunter. The story begins with a young boy named Gon Freecss, who one day discovers that the father who he thought was dead, is in fact alive and well. He learns that his father, Ging, is a legendary "Hunter", an individual who has proven themselves an elite member of humanity. Despite the fact that Ging left his son with his relatives in order to pursue his own dreams, Gon becomes determined to follow in his father\'s footsteps, pass the rigorous "Hunter Examination", and eventually find his father to become a Hunter in his own right.\nThis new Hunter × Hunter anime was announced on July 24, 2011. It is a complete reboot of the anime adaptation starting from the beginning of the manga, with no connections to the first anime from 1999. Produced by Nippon TV, VAP, Shueisha and Madhouse, the series is directed by Hiroshi Kōjina, with Atsushi Maekawa and Tsutomu Kamishiro handling series composition, Takahiro Yoshimatsu designing the characters and Yoshihisa Hirano composing the music. Instead of having the old cast reprise their roles for the new adaptation, the series features an entirely new cast to voice the characters. The new series premiered airing weekly on Nippon TV and the nationwide


cast to voice the characters. The new series premiered airing weekly on Nippon TV and the nationwide Nippon News Network from October 2, 2011.  The series started to be collected in both DVD and Blu-ray format on January 25, 2012. Viz Media has licensed the anime for a DVD/Blu-ray release in North America with an English dub. On television, the series began airing on Adult Swim\'s Toonami programming block on April 17, 2016, and ended on June 23, 2019.The anime series\' opening theme is alternated between the song "Departure!" and an alternate version titled "Departure! -Second Version-" both sung by Galneryus\' vocalist Masatoshi Ono. Five pieces of music were used as the ending theme; "Just Awake" by the Japanese band Fear, and Loathing in Las Vegas in episodes 1 to 26, "Hunting for Your Dream" by Galneryus in episodes 27 to 58, "Reason" sung by Japanese duo Yuzu in episodes 59 to 75, "Nagareboshi Kirari" also sung by Yuzu from episode 76 to 98, which was originally from the anime film adaptation, Hunter × Hunter: Phantom Rouge, and "Hyōri Ittai" by Yuzu featuring Hyadain from episode 99 to 146, which was also used in the film Hunter × Hunter: The Last Mission. The background music and soundtrack for the series was composed by Yoshihisa Hirano.\n\n\n\nPage: List of Hunter × Hunter characters\nSummary: The Hunter × Hunter manga series, created by Yoshihiro Togashi, features an extensive cast of characters. It takes place in a fictional universe where licensed specialists known as Hunters travel the world taking on special jobs ranging from treasure hunting to assassination. The story initially focuses on Gon Freecss and


on special jobs ranging from treasure hunting to assassination. The story initially focuses on Gon Freecss and his quest to become a Hunter in order to find his father, Ging, who is himself a famous Hunter. On the way, Gon meets and becomes close friends with Killua Zoldyck, Kurapika and Leorio Paradinight.\nAlthough most characters are human, most possess superhuman strength and/or supernatural abilities due to Nen, the ability to control one\'s own life energy or aura. The world of the series also includes fantastical beasts such as the Chimera Ants or the Five great calamities.'


previous
Twilio
next
Wolfram Alpha
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Apify
Apify#
This notebook shows how to use the Apify integration for LangChain.
Apify is a cloud platform for web scraping and data extraction,
which provides an ecosystem of more than a thousand
ready-made apps called Actors for various web scraping, crawling, and data extraction use cases.
For example, you can use it to extract Google Search results, Instagram and Facebook profiles, products from Amazon or Shopify, Google Maps reviews, etc. etc.
In this example, we’ll use the Website Content Crawler Actor,
which can deeply crawl websites such as documentation, knowledge bases, help centers, or blogs,
and extract text content from the web pages. Then we feed the documents into a vector index and answer questions from it.
#!pip install apify-client
First, import ApifyWrapper into your source code:
from langchain.document_loaders.base import Document
from langchain.indexes import VectorstoreIndexCreator
from langchain.utilities import ApifyWrapper
Initialize it using your Apify API token and for the purpose of this example, also with your OpenAI API key:
import os
os.environ["OPENAI_API_KEY"] = "Your OpenAI API key"
os.environ["APIFY_API_TOKEN"] = "Your Apify API token"
apify = ApifyWrapper()
Then run the Actor, wait for it to finish, and fetch its results from the Apify dataset into a LangChain document loader.
Note that if you already have some results in an Apify dataset, you can load them directly using ApifyDatasetLoader, as shown in this notebook. In that notebook, you’ll also find the explanation of the dataset_mapping_function, which is used to map fields from the Apify dataset records to LangChain Document fields.
loader = apify.call_actor(
    actor_id="apify/website-content-crawler",


actor_id="apify/website-content-crawler",
    run_input={"startUrls": [{"url": "https://python.langchain.com/en/latest/"}]},
    dataset_mapping_function=lambda item: Document(
        page_content=item["text"] or "", metadata={"source": item["url"]}
    ),
)
Initialize the vector index from the crawled documents:
index = VectorstoreIndexCreator().from_loaders([loader])
And finally, query the vector index:
query = "What is LangChain?"
result = index.query_with_sources(query)
print(result["answer"])
print(result["sources"])
 LangChain is a standard interface through which you can interact with a variety of large language models (LLMs). It provides modules that can be used to build language model applications, and it also provides chains and agents with memory capabilities.
https://python.langchain.com/en/latest/modules/models/llms.html, https://python.langchain.com/en/latest/getting_started/getting_started.html
previous
Tool Input Schema
next
ArXiv API Tool
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
OpenWeatherMap API
 Contents
Use the wrapper
Use the tool
OpenWeatherMap API#
This notebook goes over how to use the OpenWeatherMap component to fetch weather information.
First, you need to sign up for an OpenWeatherMap API key:
Go to OpenWeatherMap and sign up for an API key here
pip install pyowm
Then we will need to set some environment variables:
Save your API KEY into OPENWEATHERMAP_API_KEY env variable
Use the wrapper#
from langchain.utilities import OpenWeatherMapAPIWrapper
import os
os.environ["OPENWEATHERMAP_API_KEY"] = ""
weather = OpenWeatherMapAPIWrapper()
weather_data = weather.run("London,GB")
print(weather_data)
In London,GB, the current weather is as follows:
Detailed status: broken clouds
Wind speed: 2.57 m/s, direction: 240°
Humidity: 55%
Temperature:
  - Current: 20.12°C
  - High: 21.75°C
  - Low: 18.68°C
  - Feels like: 19.62°C
Rain: {}
Heat index: None
Cloud cover: 75%
Use the tool#
from langchain.llms import OpenAI
from langchain.agents import load_tools, initialize_agent, AgentType
import os
os.environ["OPENAI_API_KEY"] = ""
os.environ["OPENWEATHERMAP_API_KEY"] = ""
llm = OpenAI(temperature=0)
tools = load_tools(["openweathermap-api"], llm)
agent_chain = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)


agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)
agent_chain.run("What's the weather like in London?")
> Entering new AgentExecutor chain...
 I need to find out the current weather in London.
Action: OpenWeatherMap
Action Input: London,GB
Observation: In London,GB, the current weather is as follows:
Detailed status: broken clouds
Wind speed: 2.57 m/s, direction: 240°
Humidity: 56%
Temperature:
  - Current: 20.11°C
  - High: 21.75°C
  - Low: 18.68°C
  - Feels like: 19.64°C
Rain: {}
Heat index: None
Cloud cover: 75%
Thought: I now know the current weather in London.
Final Answer: The current weather in London is broken clouds, with a wind speed of 2.57 m/s, direction 240°, humidity of 56%, temperature of 20.11°C, high of 21.75°C, low of 18.68°C, and a heat index of None.
> Finished chain.
'The current weather in London is broken clouds, with a wind speed of 2.57 m/s, direction 240°, humidity of 56%, temperature of 20.11°C, high of 21.75°C, low of 18.68°C, and a heat index of None.'
previous
Metaphor Search
next
PubMed Tool
 Contents

Use the wrapper
Use the tool
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Brave Search
Brave Search#
This notebook goes over how to use the Brave Search tool.
from langchain.tools import BraveSearch
api_key = "..."
tool = BraveSearch.from_api_key(api_key=api_key, search_kwargs={"count": 3})
tool.run("obama middle name")


'[{"title": "Barack Obama - Wikipedia", "link": "https://en.wikipedia.org/wiki/Barack_Obama", "snippet": "Outside of politics, Obama has published three bestselling books: Dreams from My Father (1995), The Audacity of Hope (2006) and A Promised Land (2020). Rankings by scholars and historians, in which he has been featured since 2010, place him in the middle to upper tier of American presidents."}, {"title": "Obama\'s Middle Name -- My Last Name -- is \'Hussein.\' So?", "link": "https://www.cair.com/cair_in_the_news/obamas-middle-name-my-last-name-is-hussein-so/", "snippet": "Many Americans understand that common names don\\u2019t only come in the form of a \\u201cSmith\\u201d or a \\u201cJohnson.\\u201d Perhaps, they have a neighbor, mechanic or teacher named Hussein. Or maybe they\\u2019ve seen fashion designer Hussein Chalayan in the pages of Vogue or recall King Hussein, our ally in the Middle East."}, {"title": "What\'s up with Obama\'s middle name? - Quora", "link": "https://www.quora.com/Whats-up-with-Obamas-middle-name", "snippet": "Answer (1 of 15): A better question would be, \\u201cWhat\\u2019s up with Obama\\u2019s first name?\\u201d President Barack Hussein Obama\\u2019s father\\u2019s name was Barack Hussein Obama. He was named after his father. Hussein, Obama\\u2019s middle name, is a very common Arabic name, meaning


Hussein, Obama\\u2019s middle name, is a very common Arabic name, meaning "good," "handsome," or "beautiful.""}]'


previous
Bing Search
next
ChatGPT Plugins
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Shell Tool
 Contents
Use with Agents
Shell Tool#
Giving agents access to the shell is powerful (though risky outside a sandboxed environment).
The LLM can use it to execute any shell commands. A common use case for this is letting the LLM interact with your local file system.
from langchain.tools import ShellTool
shell_tool = ShellTool()
print(shell_tool.run({"commands": ["echo 'Hello World!'", "time"]}))
Hello World!
real	0m0.000s
user	0m0.000s
sys	0m0.000s
/Users/wfh/code/lc/lckg/langchain/tools/shell/tool.py:34: UserWarning: The shell tool has no safeguards by default. Use at your own risk.
  warnings.warn(
Use with Agents#
As with all tools, these can be given to an agent to accomplish more complex tasks. Let’s have the agent fetch some links from a web page.
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent
from langchain.agents import AgentType
llm = ChatOpenAI(temperature=0)
shell_tool.description = shell_tool.description + f"args {shell_tool.args}".replace("{", "{{").replace("}", "}}")
self_ask_with_search = initialize_agent([shell_tool], llm, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
self_ask_with_search.run("Download the langchain.com webpage and grep for all urls. Return only a sorted list of them. Be sure to use double quotes.")
> Entering new AgentExecutor chain...
Question: What is the task?
Thought: We need to download the langchain.com webpage and extract all the URLs from it. Then we need to sort the URLs and return them.
Action:
```


Action:
```
{
  "action": "shell",
  "action_input": {
    "commands": [
      "curl -s https://langchain.com | grep -o 'http[s]*://[^\" ]*' | sort"
    ]
  }
}
```
/Users/wfh/code/lc/lckg/langchain/tools/shell/tool.py:34: UserWarning: The shell tool has no safeguards by default. Use at your own risk.
  warnings.warn(
Observation: https://blog.langchain.dev/
https://discord.gg/6adMQxSpJS
https://docs.langchain.com/docs/
https://github.com/hwchase17/chat-langchain
https://github.com/hwchase17/langchain
https://github.com/hwchase17/langchainjs
https://github.com/sullivan-sean/chat-langchainjs
https://js.langchain.com/docs/
https://python.langchain.com/en/latest/
https://twitter.com/langchainai
Thought:The URLs have been successfully extracted and sorted. We can return the list of URLs as the final answer.
Final Answer: ["https://blog.langchain.dev/", "https://discord.gg/6adMQxSpJS", "https://docs.langchain.com/docs/", "https://github.com/hwchase17/chat-langchain", "https://github.com/hwchase17/langchain", "https://github.com/hwchase17/langchainjs", "https://github.com/sullivan-sean/chat-langchainjs", "https://js.langchain.com/docs/", "https://python.langchain.com/en/latest/", "https://twitter.com/langchainai"]
> Finished chain.


> Finished chain.
'["https://blog.langchain.dev/", "https://discord.gg/6adMQxSpJS", "https://docs.langchain.com/docs/", "https://github.com/hwchase17/chat-langchain", "https://github.com/hwchase17/langchain", "https://github.com/hwchase17/langchainjs", "https://github.com/sullivan-sean/chat-langchainjs", "https://js.langchain.com/docs/", "https://python.langchain.com/en/latest/", "https://twitter.com/langchainai"]'
previous
AWS Lambda API
next
Bing Search
 Contents

Use with Agents
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
AWS Lambda API
AWS Lambda API#
This notebook goes over how to use the AWS Lambda Tool component.
AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS), designed to allow developers to build and run applications and services without the need for provisioning or managing servers. This serverless architecture enables you to focus on writing and deploying code, while AWS automatically takes care of scaling, patching, and managing the infrastructure required to run your applications.
By including a awslambda in the list of tools provided to an Agent, you can grant your Agent the ability to invoke code running in your AWS Cloud for whatever purposes you need.
When an Agent uses the awslambda tool, it will provide an argument of type string which will in turn be passed into the Lambda function via the event parameter.
First, you need to install boto3 python package.
!pip install boto3 > /dev/null
In order for an agent to use the tool, you must provide it with the name and description that match the functionality of you lambda function’s logic.
You must also provide the name of your function.
Note that because this tool is effectively just a wrapper around the boto3 library, you will need to run aws configure in order to make use of the tool. For more detail, see here
from langchain import OpenAI
from langchain.agents import load_tools, AgentType
llm = OpenAI(temperature=0)
tools = load_tools(
    ["awslambda"],
    awslambda_tool_name="email-sender",
    awslambda_tool_description="sends an email with the specified content to test@testing123.com",
    function_name="testFunction1"
)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)


agent.run("Send an email to test@testing123.com saying hello world.")
previous
ArXiv API Tool
next
Shell Tool
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
ArXiv API Tool
 Contents
The ArXiv API Wrapper
ArXiv API Tool#
This notebook goes over how to use the arxiv component.
First, you need to install arxiv python package.
!pip install arxiv
from langchain.chat_models import ChatOpenAI
from langchain.agents import load_tools, initialize_agent, AgentType
llm = ChatOpenAI(temperature=0.0)
tools = load_tools(
    ["arxiv"],
)
agent_chain = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)
agent_chain.run(
    "What's the paper 1605.08386 about?",
)
> Entering new AgentExecutor chain...
I need to use Arxiv to search for the paper.
Action: Arxiv
Action Input: "1605.08386"
Observation: Published: 2016-05-26
Title: Heat-bath random walks with Markov bases
Authors: Caprice Stanley, Tobias Windisch
Summary: Graphs on lattice points are studied whose edges come from a finite set of
allowed moves of arbitrary length. We show that the diameter of these graphs on
fibers of a fixed integer matrix can be bounded from above by a constant. We
then study the mixing behaviour of heat-bath random walks on these graphs. We
also state explicit conditions on the set of moves so that the heat-bath random
walk, a generalization of the Glauber dynamics, is an expander in fixed
dimension.
Thought:The paper is about heat-bath random walks with Markov bases on graphs of lattice points.


Final Answer: The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points.
> Finished chain.
'The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points.'
The ArXiv API Wrapper#
The tool wraps the API Wrapper. Below, we can explore some of the features it provides.
from langchain.utilities import ArxivAPIWrapper
Run a query to get information about some scientific article/articles. The query text is limited to 300 characters.
It returns these article fields:
Publishing date
Title
Authors
Summary
Next query returns information about one article with arxiv Id equal “1605.08386”.
arxiv = ArxivAPIWrapper()
docs = arxiv.run("1605.08386")
docs
'Published: 2016-05-26\nTitle: Heat-bath random walks with Markov bases\nAuthors: Caprice Stanley, Tobias Windisch\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.'
Now, we want to get information about one author, Caprice Stanley.
This query returns information about three articles. By default, the query returns information only about three top articles.
docs = arxiv.run("Caprice Stanley")
docs


docs = arxiv.run("Caprice Stanley")
docs
'Published: 2017-10-10\nTitle: On Mixing Behavior of a Family of Random Walks Determined by a Linear Recurrence\nAuthors: Caprice Stanley, Seth Sullivant\nSummary: We study random walks on the integers mod $G_n$ that are determined by an\ninteger sequence $\\{ G_n \\}_{n \\geq 1}$ generated by a linear recurrence\nrelation. Fourier analysis provides explicit formulas to compute the\neigenvalues of the transition matrices and we use this to bound the mixing time\nof the random walks.\n\nPublished: 2016-05-26\nTitle: Heat-bath random walks with Markov bases\nAuthors: Caprice Stanley, Tobias Windisch\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.\n\nPublished: 2003-03-18\nTitle: Calculation of fluxes of charged particles and neutrinos from atmospheric showers\nAuthors: V. Plyaskin\nSummary: The results on the fluxes of charged particles and neutrinos from a\n3-dimensional (3D) simulation of atmospheric showers are presented. An\nagreement of calculated fluxes with data on charged particles from the AMS and\nCAPRICE detectors is demonstrated. Predictions on neutrino fluxes at different\nexperimental sites are compared with results from other calculations.'


Now, we are trying to find information about non-existing article. In this case, the response is “No good Arxiv Result was found”
docs = arxiv.run("1605.08386WWW")
docs
'No good Arxiv Result was found'
previous
Apify
next
AWS Lambda API
 Contents

The ArXiv API Wrapper
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
GraphQL tool
GraphQL tool#
This Jupyter Notebook demonstrates how to use the BaseGraphQLTool component with an Agent.
GraphQL is a query language for APIs and a runtime for executing those queries against your data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
By including a BaseGraphQLTool in the list of tools provided to an Agent, you can grant your Agent the ability to query data from GraphQL APIs for any purposes you need.
In this example, we’ll be using the public Star Wars GraphQL API available at the following endpoint: https://swapi-graphql.netlify.app/.netlify/functions/index.
First, you need to install httpx and gql Python packages.
pip install httpx gql > /dev/null
Now, let’s create a BaseGraphQLTool instance with the specified Star Wars API endpoint and initialize an Agent with the tool.
from langchain import OpenAI
from langchain.agents import load_tools, initialize_agent, AgentType
from langchain.utilities import GraphQLAPIWrapper
llm = OpenAI(temperature=0)
tools = load_tools(["graphql"], graphql_endpoint="https://swapi-graphql.netlify.app/.netlify/functions/index", llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
Now, we can use the Agent to run queries against the Star Wars GraphQL API. Let’s ask the Agent to list all the Star Wars films and their release dates.
graphql_fields = """allFilms {
    films {
      title
      director
      releaseDate
      speciesConnection {
        species {
          name
          classification
          homeworld {
            name
          }


name
          classification
          homeworld {
            name
          }
        }
      }
    }
  }
"""
suffix = "Search for the titles of all the stawars films stored in the graphql database that has this schema "
agent.run(suffix + graphql_fields)
> Entering new AgentExecutor chain...
 I need to query the graphql database to get the titles of all the star wars films
Action: query_graphql
Action Input: query { allFilms { films { title } } }
Observation: "{\n  \"allFilms\": {\n    \"films\": [\n      {\n        \"title\": \"A New Hope\"\n      },\n      {\n        \"title\": \"The Empire Strikes Back\"\n      },\n      {\n        \"title\": \"Return of the Jedi\"\n      },\n      {\n        \"title\": \"The Phantom Menace\"\n      },\n      {\n        \"title\": \"Attack of the Clones\"\n      },\n      {\n        \"title\": \"Revenge of the Sith\"\n      }\n    ]\n  }\n}"
Thought: I now know the titles of all the star wars films
Final Answer: The titles of all the star wars films are: A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, and Revenge of the Sith.
> Finished chain.
'The titles of all the star wars films are: A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, and Revenge of the Sith.'
previous
Gradio Tools
next
HuggingFace Tools
By Harrison Chase

      © Copyright 2023, Harrison Chase.


By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Twilio
 Contents
Setup
Sending a message
Twilio#
This notebook goes over how to use the Twilio API wrapper to send a text message.
Setup#
To use this tool you need to install the Python Twilio package twilio
# !pip install twilio
You’ll also need to set up a Twilio account and get your credentials. You’ll need your Account String Identifier (SID) and your Auth Token. You’ll also need a number to send messages from.
You can either pass these in to the TwilioAPIWrapper as named parameters account_sid, auth_token, from_number, or you can set the environment variables TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_FROM_NUMBER.
Sending a message#
from langchain.utilities.twilio import TwilioAPIWrapper
twilio = TwilioAPIWrapper(
#     account_sid="foo",
#     auth_token="bar",
#     from_number="baz,"
)
twilio.run("hello world", "+16162904619")
previous
SerpAPI
next
Wikipedia
 Contents

Setup
Sending a message
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Human as a tool
 Contents
Configuring the Input Function
Human as a tool#
Human are AGI so they can certainly be used as a tool to help out AI agent
when it is confused.
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
llm = ChatOpenAI(temperature=0.0)
math_llm = OpenAI(temperature=0.0)
tools = load_tools(
    ["human", "llm-math"],
    llm=math_llm,
)
agent_chain = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)
In the above code you can see the tool takes input directly from command line.
You can customize prompt_func and input_func according to your need (as shown below).
agent_chain.run("What's my friend Eric's surname?")
# Answer with 'Zhu'
> Entering new AgentExecutor chain...
I don't know Eric's surname, so I should ask a human for guidance.
Action: Human
Action Input: "What is Eric's surname?"
What is Eric's surname?
 Zhu
Observation: Zhu
Thought:I now know Eric's surname is Zhu.
Final Answer: Eric's surname is Zhu.
> Finished chain.
"Eric's surname is Zhu."
Configuring the Input Function#
By default, the HumanInputRun tool uses the python input function to get input from the user.
You can customize the input_func to be anything you’d like.
For instance, if you want to accept multi-line input, you could do the following:
def get_input() -> str:


def get_input() -> str:
    print("Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.")
    contents = []
    while True:
        try:
            line = input()
        except EOFError:
            break
        if line == "q":
            break
        contents.append(line)
    return "\n".join(contents)
# You can modify the tool when loading
tools = load_tools(
    ["human", "ddg-search"],
    llm=math_llm,
    input_func=get_input
)
# Or you can directly instantiate the tool
from langchain.tools import HumanInputRun
tool = HumanInputRun(input_func=get_input)
agent_chain = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)
agent_chain.run("I need help attributing a quote")
> Entering new AgentExecutor chain...
I should ask a human for guidance
Action: Human
Action Input: "Can you help me attribute a quote?"
Can you help me attribute a quote?
Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.
 vini
 vidi
 vici
 q
Observation: vini
vidi
vici
Thought:I need to provide more context about the quote
Action: Human
Action Input: "The quote is 'Veni, vidi, vici'"
The quote is 'Veni, vidi, vici'
Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.
 oh who said it
 q
Observation: oh who said it


oh who said it
 q
Observation: oh who said it
Thought:I can use DuckDuckGo Search to find out who said the quote
Action: DuckDuckGo Search
Action Input: "Who said 'Veni, vidi, vici'?"


Observation: Updated on September 06, 2019. "Veni, vidi, vici" is a famous phrase said to have been spoken by the Roman Emperor Julius Caesar (100-44 BCE) in a bit of stylish bragging that impressed many of the writers of his day and beyond. The phrase means roughly "I came, I saw, I conquered" and it could be pronounced approximately Vehnee, Veedee ... Veni, vidi, vici (Classical Latin: [weːniː wiːdiː wiːkiː], Ecclesiastical Latin: [ˈveni ˈvidi ˈvitʃi]; "I came; I saw; I conquered") is a Latin phrase used to refer to a swift, conclusive victory.The phrase is popularly attributed to Julius Caesar who, according to Appian, used the phrase in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short ... veni, vidi, vici Latin quotation from Julius Caesar ve· ni, vi· di, vi· ci ˌwā-nē ˌwē-dē ˈwē-kē ˌvā-nē ˌvē-dē ˈvē-chē : I came, I saw, I conquered Articles Related to veni, vidi, vici 'In Vino Veritas' and Other Latin... Dictionary Entries Near veni, vidi, vici Venite veni, vidi, vici Venizélos See More Nearby Entries Cite this Entry Style The simplest explanation for why veni, vidi, vici is a popular saying is that it comes from Julius Caesar, one of history's most famous figures, and has a simple, strong meaning: I'm powerful and fast. But it's not just the meaning that makes


simple, strong meaning: I'm powerful and fast. But it's not just the meaning that makes the phrase so powerful. Caesar was a gifted writer, and the phrase makes use of Latin grammar to ... One of the best known and most frequently quoted Latin expression, veni, vidi, vici may be found hundreds of times throughout the centuries used as an expression of triumph. The words are said to have been used by Caesar as he was enjoying a triumph.


Thought:I now know the final answer
Final Answer: Julius Caesar said the quote "Veni, vidi, vici" which means "I came, I saw, I conquered".
> Finished chain.
'Julius Caesar said the quote "Veni, vidi, vici" which means "I came, I saw, I conquered".'
previous
HuggingFace Tools
next
IFTTT WebHooks
 Contents

Configuring the Input Function
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
YouTubeSearchTool
YouTubeSearchTool#
This notebook shows how to use a tool to search YouTube
Adapted from venuv/langchain_yt_tools
#! pip install youtube_search
from langchain.tools import YouTubeSearchTool
tool = YouTubeSearchTool()
tool.run("lex friedman")
"['/watch?v=VcVfceTsD0A&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=gPfriiHBBek&pp=ygUMbGV4IGZyaWVkbWFu']"
You can also specify the number of results that are returned
tool.run("lex friedman,5")
"['/watch?v=VcVfceTsD0A&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=YVJ8gTnDC4Y&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=Udh22kuLebg&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=gPfriiHBBek&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=L_Guz73e6fw&pp=ygUMbGV4IGZyaWVkbWFu']"
previous
Wolfram Alpha
next
Zapier Natural Language Actions API
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 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 - therefore, 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.run
)
previous
PubMed Tool
next
Requests
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Search Tools
 Contents
Google Serper API Wrapper
SerpAPI
GoogleSearchAPIWrapper
SearxNG Meta Search Engine
Search Tools#
This notebook shows off usage of various search tools.
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
Google Serper API Wrapper#
First, let’s try to use the Google Serper API tool.
tools = load_tools(["google-serper"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret?")
> Entering new AgentExecutor chain...
 I should look up the current weather conditions.
Action: Search
Action Input: "weather in Pomfret"
Observation: 37°F
Thought: I now know the current temperature in Pomfret.
Final Answer: The current temperature in Pomfret is 37°F.
> Finished chain.
'The current temperature in Pomfret is 37°F.'
SerpAPI#
Now, let’s use the SerpAPI tool.
tools = load_tools(["serpapi"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret?")
> Entering new AgentExecutor chain...
 I need to find out what the current weather is in Pomfret.
Action: Search
Action Input: "weather in Pomfret"


Action: Search
Action Input: "weather in Pomfret"
Observation: Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 ...
Thought: I now know the current weather in Pomfret.
Final Answer: Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 mph.
> Finished chain.
'Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 mph.'
GoogleSearchAPIWrapper#
Now, let’s use the official Google Search API Wrapper.
tools = load_tools(["google-search"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret?")
> Entering new AgentExecutor chain...
 I should look up the current weather conditions.
Action: Google Search
Action Input: "weather in Pomfret"


Action: Google Search
Action Input: "weather in Pomfret"
Observation: Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%. Pomfret, CT Weather Forecast, with current conditions, wind, air quality, and what to expect for the next 3 days. Hourly Weather-Pomfret, CT. As of 12:52 am EST. Special Weather Statement +2 ... Hazardous Weather Conditions. Special Weather Statement ... Pomfret CT. Tonight ... National Digital Forecast Database Maximum Temperature Forecast. Pomfret Center Weather Forecasts. Weather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for ... Pomfret, CT 12 hour by hour weather forecast includes precipitation, temperatures, sky conditions, rain chance, dew-point, relative humidity, wind direction ... North Pomfret Weather Forecasts. Weather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for ... Today's Weather - Pomfret, CT. Dec 31, 2022 4:00 PM. Putnam MS. --. Weather forecast icon. Feels like --. Hi --. Lo --. Pomfret, CT temperature trend for the next 14 Days. Find daytime highs and nighttime lows from TheWeatherNetwork.com. Pomfret, MD Weather Forecast Date: 332 PM EST Wed Dec 28 2022. The area/counties/county of: Charles, including the cites of: St. Charles and Waldorf.
Thought: I now know the current weather conditions in Pomfret.


Thought: I now know the current weather conditions in Pomfret.
Final Answer: Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%.
> Finished AgentExecutor chain.
'Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%.'
SearxNG Meta Search Engine#
Here we will be using a self hosted SearxNG meta search engine.
tools = load_tools(["searx-search"], searx_host="http://localhost:8888", llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret")
> Entering new AgentExecutor chain...
 I should look up the current weather
Action: SearX Search
Action Input: "weather in Pomfret"
Observation: Mainly cloudy with snow showers around in the morning. High around 40F. Winds NNW at 5 to 10 mph. Chance of snow 40%. Snow accumulations less than one inch.
10 Day Weather - Pomfret, MD As of 1:37 pm EST Today 49°/ 41° 52% Mon 27 | Day 49° 52% SE 14 mph Cloudy with occasional rain showers. High 49F. Winds SE at 10 to 20 mph. Chance of rain 50%....


10 Day Weather - Pomfret, VT As of 3:51 am EST Special Weather Statement Today 39°/ 32° 37% Wed 01 | Day 39° 37% NE 4 mph Cloudy with snow showers developing for the afternoon. High 39F....
Pomfret, CT ; Current Weather. 1:06 AM. 35°F · RealFeel® 32° ; TODAY'S WEATHER FORECAST. 3/3. 44°Hi. RealFeel® 50° ; TONIGHT'S WEATHER FORECAST. 3/3. 32°Lo.
Pomfret, MD Forecast Today Hourly Daily Morning 41° 1% Afternoon 43° 0% Evening 35° 3% Overnight 34° 2% Don't Miss Finally, Here’s Why We Get More Colds and Flu When It’s Cold Coast-To-Coast...
Pomfret, MD Weather Forecast | AccuWeather Current Weather 5:35 PM 35° F RealFeel® 36° RealFeel Shade™ 36° Air Quality Excellent Wind E 3 mph Wind Gusts 5 mph Cloudy More Details WinterCast...
Pomfret, VT Weather Forecast | AccuWeather Current Weather 11:21 AM 23° F RealFeel® 27° RealFeel Shade™ 25° Air Quality Fair Wind ESE 3 mph Wind Gusts 7 mph Cloudy More Details WinterCast...
Pomfret Center, CT Weather Forecast | AccuWeather Daily Current Weather 6:50 PM 39° F RealFeel® 36° Air Quality Fair Wind NW 6 mph Wind Gusts 16 mph Mostly clear More Details WinterCast...


12:00 pm · Feels Like36° · WindN 5 mph · Humidity43% · UV Index3 of 10 · Cloud Cover65% · Rain Amount0 in ...
Pomfret Center, CT Weather Conditions | Weather Underground star Popular Cities San Francisco, CA 49 °F Clear Manhattan, NY 37 °F Fair Schiller Park, IL (60176) warning39 °F Mostly Cloudy...
Thought: I now know the final answer
Final Answer: The current weather in Pomfret is mainly cloudy with snow showers around in the morning. The temperature is around 40F with winds NNW at 5 to 10 mph. Chance of snow is 40%.
> Finished chain.
'The current weather in Pomfret is mainly cloudy with snow showers around in the morning. The temperature is around 40F with winds NNW at 5 to 10 mph. Chance of snow is 40%.'
previous
SceneXplain
next
SearxNG Search API
 Contents

Google Serper API Wrapper
SerpAPI
GoogleSearchAPIWrapper
SearxNG Meta Search Engine
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
HuggingFace Tools
HuggingFace Tools#
Huggingface Tools supporting text I/O can be
loaded directly using the load_huggingface_tool function.
# Requires transformers>=4.29.0 and huggingface_hub>=0.14.1
!pip install --upgrade transformers huggingface_hub > /dev/null
from langchain.agents import load_huggingface_tool
tool = load_huggingface_tool("lysandre/hf-model-downloads")
print(f"{tool.name}: {tool.description}")
model_download_counter: This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. It takes the name of the category (such as text-classification, depth-estimation, etc), and returns the name of the checkpoint
tool.run("text-classification")
'facebook/bart-large-mnli'
previous
GraphQL tool
next
Human as a tool
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Google Serper API
 Contents
As part of a Self Ask With Search Chain
Obtaining results with metadata
Searching for Google Images
Searching for Google News
Searching for Google Places
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
import pprint
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


Intermediate answer: El Palmar, Spain
So the final answer is: El Palmar, Spain
> Finished chain.
'El Palmar, Spain'
Obtaining results with metadata#
If you would also like to obtain the results in a structured way including metadata. For this we will be using the results method of the wrapper.
search = GoogleSerperAPIWrapper()
results = search.results("Apple Inc.")
pprint.pp(results)
{'searchParameters': {'q': 'Apple Inc.',
                      'gl': 'us',
                      'hl': 'en',
                      'num': 10,
                      'type': 'search'},
 'knowledgeGraph': {'title': 'Apple',
                    'type': 'Technology company',
                    'website': 'http://www.apple.com/',
                    'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwGQRv5TjjkycpctY66mOg_e2-npacrmjAb6_jAWhzlzkFE3OTjxyzbA&s=0',
                    'description': 'Apple Inc. is an American multinational '
                                   'technology company headquartered in '
                                   'Cupertino, California. Apple is the '
                                   "world's largest technology company by "
                                   'revenue, with US$394.3 billion in 2022 '
                                   'revenue. As of March 2023, Apple is the '
                                   "world's biggest...",
                    'descriptionSource': 'Wikipedia',
                    'descriptionLink': 'https://en.wikipedia.org/wiki/Apple_Inc.',
                    'attributes': {'Customer service': '1 (800) 275-2273',
                                   'CEO': 'Tim Cook (Aug 24, 2011–)',


'CEO': 'Tim Cook (Aug 24, 2011–)',
                                   'Headquarters': 'Cupertino, CA',
                                   'Founded': 'April 1, 1976, Los Altos, CA',
                                   'Founders': 'Steve Jobs, Steve Wozniak, '
                                               'Ronald Wayne, and more',
                                   'Products': 'iPhone, iPad, Apple TV, and '
                                               'more'}},
 'organic': [{'title': 'Apple',
              'link': 'https://www.apple.com/',
              'snippet': 'Discover the innovative world of Apple and shop '
                         'everything iPhone, iPad, Apple Watch, Mac, and Apple '
                         'TV, plus explore accessories, entertainment, ...',
              'sitelinks': [{'title': 'Support',
                             'link': 'https://support.apple.com/'},
                            {'title': 'iPhone',
                             'link': 'https://www.apple.com/iphone/'},
                            {'title': 'Site Map',
                             'link': 'https://www.apple.com/sitemap/'},
                            {'title': 'Business',
                             'link': 'https://www.apple.com/business/'},
                            {'title': 'Mac',
                             'link': 'https://www.apple.com/mac/'},
                            {'title': 'Watch',
                             'link': 'https://www.apple.com/watch/'}],
              'position': 1},
             {'title': 'Apple Inc. - Wikipedia',
              'link': 'https://en.wikipedia.org/wiki/Apple_Inc.',
              'snippet': 'Apple Inc. is an American multinational technology '
                         'company headquartered in Cupertino, California. '
                         "Apple is the world's largest technology company by "
                         'revenue, ...',


'revenue, ...',
              'attributes': {'Products': 'AirPods; Apple Watch; iPad; iPhone; '
                                         'Mac; Full list',
                             'Founders': 'Steve Jobs; Steve Wozniak; Ronald '
                                         'Wayne; Mike Markkula'},
              'sitelinks': [{'title': 'History',
                             'link': 'https://en.wikipedia.org/wiki/History_of_Apple_Inc.'},
                            {'title': 'Timeline of Apple Inc. products',
                             'link': 'https://en.wikipedia.org/wiki/Timeline_of_Apple_Inc._products'},
                            {'title': 'Litigation involving Apple Inc.',
                             'link': 'https://en.wikipedia.org/wiki/Litigation_involving_Apple_Inc.'},
                            {'title': 'Apple Store',
                             'link': 'https://en.wikipedia.org/wiki/Apple_Store'}],
              'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvmB5fT1LjqpZx02UM7IJq0Buoqt0DZs_y0dqwxwSWyP4PIN9FaxuTea0&s',
              'position': 2},
             {'title': 'Apple Inc. | History, Products, Headquarters, & Facts '
                       '| Britannica',
              'link': 'https://www.britannica.com/topic/Apple-Inc',
              'snippet': 'Apple Inc., formerly Apple Computer, Inc., American '
                         'manufacturer of personal computers, smartphones, '
                         'tablet computers, computer peripherals, and computer '
                         '...',
              'attributes': {'Related People': 'Steve Jobs Steve Wozniak Jony '
                                               'Ive Tim Cook Angela Ahrendts',


'Ive Tim Cook Angela Ahrendts',
                             'Date': '1976 - present'},
              'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3liELlhrMz3Wpsox29U8jJ3L8qETR0hBWHXbFnwjwQc34zwZvFELst2E&s',
              'position': 3},
             {'title': 'AAPL: Apple Inc Stock Price Quote - NASDAQ GS - '
                       'Bloomberg.com',
              'link': 'https://www.bloomberg.com/quote/AAPL:US',
              'snippet': 'AAPL:USNASDAQ GS. Apple Inc. COMPANY INFO ; Open. '
                         '170.09 ; Prev Close. 169.59 ; Volume. 48,425,696 ; '
                         'Market Cap. 2.667T ; Day Range. 167.54170.35.',
              'position': 4},
             {'title': 'Apple Inc. (AAPL) Company Profile & Facts - Yahoo '
                       'Finance',
              'link': 'https://finance.yahoo.com/quote/AAPL/profile/',
              'snippet': 'Apple Inc. designs, manufactures, and markets '
                         'smartphones, personal computers, tablets, wearables, '
                         'and accessories worldwide. The company offers '
                         'iPhone, a line ...',
              'position': 5},
             {'title': 'Apple Inc. (AAPL) Stock Price, News, Quote & History - '
                       'Yahoo Finance',
              'link': 'https://finance.yahoo.com/quote/AAPL',
              'snippet': 'Find the latest Apple Inc. (AAPL) stock quote, '


'snippet': 'Find the latest Apple Inc. (AAPL) stock quote, '
                         'history, news and other vital information to help '
                         'you with your stock trading and investing.',
              'position': 6}],
 'peopleAlsoAsk': [{'question': 'What does Apple Inc do?',
                    'snippet': 'Apple Inc. (Apple) designs, manufactures and '
                               'markets smartphones, personal\n'
                               'computers, tablets, wearables and accessories '
                               'and sells a range of related\n'
                               'services.',
                    'title': 'AAPL.O - | Stock Price & Latest News - Reuters',
                    'link': 'https://www.reuters.com/markets/companies/AAPL.O/'},
                   {'question': 'What is the full form of Apple Inc?',
                    'snippet': '(formerly Apple Computer Inc.) is an American '
                               'computer and consumer electronics\n'
                               'company famous for creating the iPhone, iPad '
                               'and Macintosh computers.',
                    'title': 'What is Apple? An products and history overview '
                             '- TechTarget',
                    'link': 'https://www.techtarget.com/whatis/definition/Apple'},
                   {'question': 'What is Apple Inc iPhone?',
                    'snippet': 'Apple Inc (Apple) designs, manufactures, and '
                               'markets smartphones, tablets,\n'
                               'personal computers, and wearable devices. The '
                               'company also offers software\n'
                               'applications and related services, '
                               'accessories, and third-party digital content.\n'
                               "Apple's product portfolio includes iPhone, "
                               'iPad, Mac, iPod, Apple Watch, and\n'
                               'Apple TV.',
                    'title': 'Apple Inc Company Profile - Apple Inc Overview - '


'title': 'Apple Inc Company Profile - Apple Inc Overview - '
                             'GlobalData',
                    'link': 'https://www.globaldata.com/company-profile/apple-inc/'},
                   {'question': 'Who runs Apple Inc?',
                    'snippet': 'Timothy Donald Cook (born November 1, 1960) is '
                               'an American business executive\n'
                               'who has been the chief executive officer of '
                               'Apple Inc. since 2011. Cook\n'
                               "previously served as the company's chief "
                               'operating officer under its co-founder\n'
                               'Steve Jobs. He is the first CEO of any Fortune '
                               '500 company who is openly gay.',
                    'title': 'Tim Cook - Wikipedia',
                    'link': 'https://en.wikipedia.org/wiki/Tim_Cook'}],
 'relatedSearches': [{'query': 'Who invented the iPhone'},
                     {'query': 'Apple iPhone'},
                     {'query': 'History of Apple company PDF'},
                     {'query': 'Apple company history'},
                     {'query': 'Apple company introduction'},
                     {'query': 'Apple India'},
                     {'query': 'What does Apple Inc own'},
                     {'query': 'Apple Inc After Steve'},
                     {'query': 'Apple Watch'},
                     {'query': 'Apple App Store'}]}
Searching for Google Images#
We can also query Google Images using this wrapper. For example:
search = GoogleSerperAPIWrapper(type="images")
results = search.results("Lion")
pprint.pp(results)
{'searchParameters': {'q': 'Lion',
                      'gl': 'us',
                      'hl': 'en',
                      'num': 10,
                      'type': 'images'},
 'images': [{'title': 'Lion - Wikipedia',


'images': [{'title': 'Lion - Wikipedia',
             'imageUrl': 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/1200px-Lion_waiting_in_Namibia.jpg',
             'imageWidth': 1200,
             'imageHeight': 900,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRye79ROKwjfb6017jr0iu8Bz2E1KKuHg-A4qINJaspyxkZrkw&s',
             'thumbnailWidth': 259,
             'thumbnailHeight': 194,
             'source': 'Wikipedia',
             'domain': 'en.wikipedia.org',
             'link': 'https://en.wikipedia.org/wiki/Lion',
             'position': 1},
            {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica',
             'imageUrl': 'https://cdn.britannica.com/55/2155-050-604F5A4A/lion.jpg',
             'imageWidth': 754,
             'imageHeight': 752,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3fnDub1GSojI0hJ-ZGS8Tv-hkNNloXh98DOwXZoZ_nUs3GWSd&s',
             'thumbnailWidth': 225,
             'thumbnailHeight': 224,
             'source': 'Encyclopedia Britannica',
             'domain': 'www.britannica.com',
             'link': 'https://www.britannica.com/animal/lion',
             'position': 2},


'position': 2},
            {'title': 'African lion, facts and photos',
             'imageUrl': 'https://i.natgeofe.com/n/487a0d69-8202-406f-a6a0-939ed3704693/african-lion.JPG',
             'imageWidth': 3072,
             'imageHeight': 2043,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPlTarrtDbyTiEm-VI_PML9VtOTVPuDXJ5ybDf_lN11H2mShk&s',
             'thumbnailWidth': 275,
             'thumbnailHeight': 183,
             'source': 'National Geographic',
             'domain': 'www.nationalgeographic.com',
             'link': 'https://www.nationalgeographic.com/animals/mammals/facts/african-lion',
             'position': 3},
            {'title': 'Saint Louis Zoo | African Lion',
             'imageUrl': 'https://optimise2.assets-servd.host/maniacal-finch/production/animals/african-lion-01-01.jpg?w=1200&auto=compress%2Cformat&fit=crop&dm=1658933674&s=4b63f926a0f524f2087a8e0613282bdb',
             'imageWidth': 1200,
             'imageHeight': 1200,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTlewcJ5SwC7yKup6ByaOjTnAFDeoOiMxyJTQaph2W_I3dnks4&s',


'thumbnailWidth': 225,
             'thumbnailHeight': 225,
             'source': 'St. Louis Zoo',
             'domain': 'stlzoo.org',
             'link': 'https://stlzoo.org/animals/mammals/carnivores/lion',
             'position': 4},
            {'title': 'How to Draw a Realistic Lion like an Artist - Studio '
                      'Wildlife',
             'imageUrl': 'https://studiowildlife.com/wp-content/uploads/2021/10/245528858_183911853822648_6669060845725210519_n.jpg',
             'imageWidth': 1431,
             'imageHeight': 2048,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmn5HayVj3wqoBDQacnUtzaDPZzYHSLKUlIEcni6VB8w0mVeA&s',
             'thumbnailWidth': 188,
             'thumbnailHeight': 269,
             'source': 'Studio Wildlife',
             'domain': 'studiowildlife.com',
             'link': 'https://studiowildlife.com/how-to-draw-a-realistic-lion-like-an-artist/',
             'position': 5},
            {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica',
             'imageUrl': 'https://cdn.britannica.com/29/150929-050-547070A1/lion-Kenya-Masai-Mara-National-Reserve.jpg',
             'imageWidth': 1600,
             'imageHeight': 1085,


'imageWidth': 1600,
             'imageHeight': 1085,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCqaKY_THr0IBZN8c-2VApnnbuvKmnsWjfrwKoWHFR9w3eN5o&s',
             'thumbnailWidth': 273,
             'thumbnailHeight': 185,
             'source': 'Encyclopedia Britannica',
             'domain': 'www.britannica.com',
             'link': 'https://www.britannica.com/animal/lion',
             'position': 6},
            {'title': "Where do lions live? Facts about lions' habitats and "
                      'other cool facts',
             'imageUrl': 'https://www.gannett-cdn.com/-mm-/b2b05a4ab25f4fca0316459e1c7404c537a89702/c=0-0-1365-768/local/-/media/2022/03/16/USATODAY/usatsports/imageForEntry5-ODq.jpg?width=1365&height=768&fit=crop&format=pjpg&auto=webp',
             'imageWidth': 1365,
             'imageHeight': 768,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTc_4vCHscgvFvYy3PSrtIOE81kNLAfhDK8F3mfOuotL0kUkbs&s',
             'thumbnailWidth': 299,
             'thumbnailHeight': 168,
             'source': 'USA Today',


'thumbnailHeight': 168,
             'source': 'USA Today',
             'domain': 'www.usatoday.com',
             'link': 'https://www.usatoday.com/story/news/2023/01/08/where-do-lions-live-habitat/10927718002/',
             'position': 7},
            {'title': 'Lion',
             'imageUrl': 'https://i.natgeofe.com/k/1d33938b-3d02-4773-91e3-70b113c3b8c7/lion-male-roar_square.jpg',
             'imageWidth': 3072,
             'imageHeight': 3072,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQqLfnBrBLcTiyTZynHH3FGbBtX2bd1ScwpcuOLnksTyS9-4GM&s',
             'thumbnailWidth': 225,
             'thumbnailHeight': 225,
             'source': 'National Geographic Kids',
             'domain': 'kids.nationalgeographic.com',
             'link': 'https://kids.nationalgeographic.com/animals/mammals/facts/lion',
             'position': 8},
            {'title': "Lion | Smithsonian's National Zoo",
             'imageUrl': 'https://nationalzoo.si.edu/sites/default/files/styles/1400_scale/public/animals/exhibit/africanlion-005.jpg?itok=6wA745g_',
             'imageWidth': 1400,
             'imageHeight': 845,


'imageWidth': 1400,
             'imageHeight': 845,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgB3z_D4dMEOWJ7lajJk4XaQSL4DdUvIRj4UXZ0YoE5fGuWuo&s',
             'thumbnailWidth': 289,
             'thumbnailHeight': 174,
             'source': "Smithsonian's National Zoo",
             'domain': 'nationalzoo.si.edu',
             'link': 'https://nationalzoo.si.edu/animals/lion',
             'position': 9},
            {'title': "Zoo's New Male Lion Explores Habitat for the First Time "
                      '- Virginia Zoo',
             'imageUrl': 'https://virginiazoo.org/wp-content/uploads/2022/04/ZOO_0056-scaled.jpg',
             'imageWidth': 2560,
             'imageHeight': 2141,
             'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDCG7XvXRCwpe_-Vy5mpvrQpVl5q2qwgnDklQhrJpQzObQGz4&s',
             'thumbnailWidth': 246,
             'thumbnailHeight': 205,
             'source': 'Virginia Zoo',
             'domain': 'virginiazoo.org',
             'link': 'https://virginiazoo.org/zoos-new-male-lion-explores-habitat-for-thefirst-time/',
             'position': 10}]}
Searching for Google News#
We can also query Google News using this wrapper. For example:


Searching for Google News#
We can also query Google News using this wrapper. For example:
search = GoogleSerperAPIWrapper(type="news")
results = search.results("Tesla Inc.")
pprint.pp(results)
{'searchParameters': {'q': 'Tesla Inc.',
                      'gl': 'us',
                      'hl': 'en',
                      'num': 10,
                      'type': 'news'},
 'news': [{'title': 'ISS recommends Tesla investors vote against re-election '
                    'of Robyn Denholm',
           'link': 'https://www.reuters.com/business/autos-transportation/iss-recommends-tesla-investors-vote-against-re-election-robyn-denholm-2023-05-04/',
           'snippet': 'Proxy advisory firm ISS on Wednesday recommended Tesla '
                      'investors vote against re-election of board chair Robyn '
                      'Denholm, citing "concerns on...',
           'date': '5 mins ago',
           'source': 'Reuters',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcROdETe_GUyp1e8RHNhaRM8Z_vfxCvdfinZwzL1bT1ZGSYaGTeOojIdBoLevA&s',
           'position': 1},
          {'title': 'Global companies by market cap: Tesla fell most in April',
           'link': 'https://www.reuters.com/markets/global-companies-by-market-cap-tesla-fell-most-april-2023-05-02/',
           'snippet': 'Tesla Inc was the biggest loser among top companies by '
                      'market capitalisation in April, hit by disappointing '
                      'quarterly earnings after it...',


'quarterly earnings after it...',
           'date': '1 day ago',
           'source': 'Reuters',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ4u4CP8aOdGyRFH6o4PkXi-_eZDeY96vLSag5gDjhKMYf98YBER2cZPbkStQ&s',
           'position': 2},
          {'title': 'Tesla Wanted an EV Price War. Ford Showed Up.',
           'link': 'https://www.bloomberg.com/opinion/articles/2023-05-03/tesla-wanted-an-ev-price-war-ford-showed-up',
           'snippet': 'The legacy automaker is paring back the cost of its '
                      'Mustang Mach-E model after Tesla discounted its '
                      'competing EVs, portending tighter...',
           'date': '6 hours ago',
           'source': 'Bloomberg.com',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_3Eo4VI0H-nTeIbYc5DaQn5ep7YrWnmhx6pv8XddFgNF5zRC9gEpHfDq8yQ&s',
           'position': 3},
          {'title': 'Joby Aviation to get investment from Tesla shareholder '
                    'Baillie Gifford',
           'link': 'https://finance.yahoo.com/news/joby-aviation-investment-tesla-shareholder-204450712.html',
           'snippet': 'This comes days after Joby clinched a $55 million '
                      'contract extension to deliver up to nine air taxis to '


'contract extension to deliver up to nine air taxis to '
                      'the U.S. Air Force,...',
           'date': '4 hours ago',
           'source': 'Yahoo Finance',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQO0uVn297LI-xryrPNqJ-apUOulj4ohM-xkN4OfmvMOYh1CPdUEBbYx6hviw&s',
           'position': 4},
          {'title': 'Tesla resumes U.S. orders for a Model 3 version at lower '
                    'price, range',
           'link': 'https://finance.yahoo.com/news/tesla-resumes-us-orders-model-045736115.html',
           'snippet': '(Reuters) -Tesla Inc has resumed taking orders for its '
                      'Model 3 long-range vehicle in the United States, the '
                      "company's website showed late on...",
           'date': '19 hours ago',
           'source': 'Yahoo Finance',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIZetJ62sQefPfbQ9KKDt6iH7Mc0ylT5t_hpgeeuUkHhJuAx2FOJ4ZTRVDFg&s',
           'position': 5},
          {'title': 'The Tesla Model 3 Long Range AWD Is Now Available in the '
                    'U.S. With 325 Miles of Range',
           'link': 'https://www.notateslaapp.com/news/1393/tesla-reopens-orders-for-model-3-long-range-after-months-of-unavailability',


'snippet': 'Tesla has reopened orders for the Model 3 Long Range '
                      'RWD, which has been unavailable for months due to high '
                      'demand.',
           'date': '7 hours ago',
           'source': 'Not a Tesla App',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSecrgxZpRj18xIJY-nDHljyP-A4ejEkswa9eq77qhMNrScnVIqe34uql5U4w&s',
           'position': 6},
          {'title': 'Tesla Cybertruck alpha prototype spotted at the Fremont '
                    'factory in new pics and videos',
           'link': 'https://www.teslaoracle.com/2023/05/03/tesla-cybertruck-alpha-prototype-interior-and-exterior-spotted-at-the-fremont-factory-in-new-pics-and-videos/',
           'snippet': 'A Tesla Cybertruck alpha prototype goes to Fremont, '
                      'California for another round of testing before going to '
                      'production later this year (pics...',
           'date': '14 hours ago',
           'source': 'Tesla Oracle',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRO7M5ZLQE-Zo4-_5dv9hNAQZ3wSqfvYCuKqzxHG-M6CgLpwPMMG_ssebdcMg&s',
           'position': 7},
          {'title': 'Tesla putting facility in new part of country - Austin '
                    'Business Journal',


'Business Journal',
           'link': 'https://www.bizjournals.com/austin/news/2023/05/02/tesla-leases-building-seattle-area.html',
           'snippet': 'Check out what Puget Sound Business Journal has to '
                      "report about the Austin-based company's real estate "
                      'footprint in the Pacific Northwest.',
           'date': '22 hours ago',
           'source': 'The Business Journals',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9kIEHWz1FcHKDUtGQBS0AjmkqtyuBkQvD8kyIY3kpaPrgYaN7I_H2zoOJsA&s',
           'position': 8},
          {'title': 'Tesla (TSLA) Resumes Orders for Model 3 Long Range After '
                    'Backlog',
           'link': 'https://www.bloomberg.com/news/articles/2023-05-03/tesla-resumes-orders-for-popular-model-3-long-range-at-47-240',
           'snippet': 'Tesla Inc. has resumed taking orders for its Model 3 '
                      'Long Range edition with a starting price of $47240, '
                      'according to its website.',
           'date': '5 hours ago',
           'source': 'Bloomberg.com',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTWWIC4VpMTfRvSyqiomODOoLg0xhoBf-Tc1qweKnSuaiTk-Y1wMJZM3jct0w&s',
           'position': 9}]}


'position': 9}]}
If you want to only receive news articles published in the last hour, you can do the following:
search = GoogleSerperAPIWrapper(type="news", tbs="qdr:h")
results = search.results("Tesla Inc.")
pprint.pp(results)
{'searchParameters': {'q': 'Tesla Inc.',
                      'gl': 'us',
                      'hl': 'en',
                      'num': 10,
                      'type': 'news',
                      'tbs': 'qdr:h'},
 'news': [{'title': 'Oklahoma Gov. Stitt sees growing foreign interest in '
                    'investments in ...',
           'link': 'https://www.reuters.com/world/us/oklahoma-gov-stitt-sees-growing-foreign-interest-investments-state-2023-05-04/',
           'snippet': 'T)), a battery supplier to electric vehicle maker Tesla '
                      'Inc (TSLA.O), said on Sunday it is considering building '
                      'a battery plant in Oklahoma, its third in...',
           'date': '53 mins ago',
           'source': 'Reuters',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSTcsXeenqmEKdiekvUgAmqIPR4nlAmgjTkBqLpza-lLfjX1CwB84MoNVj0Q&s',
           'position': 1},
          {'title': 'Ryder lanza solución llave en mano para vehículos '
                    'eléctricos en EU',
           'link': 'https://www.tyt.com.mx/nota/ryder-lanza-solucion-llave-en-mano-para-vehiculos-electricos-en-eu',


'snippet': 'Ryder System Inc. presentó RyderElectric+ TM como su '
                      'nueva solución llave en mano ... Ryder también tiene '
                      'reservados los semirremolques Tesla y continúa...',
           'date': '56 mins ago',
           'source': 'Revista Transportes y Turismo',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJhXTQQtjSUZf9YPM235WQhFU5_d7lEA76zB8DGwZfixcgf1_dhPJyKA1Nbw&s',
           'position': 2},
          {'title': '"I think people can get by with $999 million," Bernie '
                    'Sanders tells American Billionaires.',
           'link': 'https://thebharatexpressnews.com/i-think-people-can-get-by-with-999-million-bernie-sanders-tells-american-billionaires-heres-how-the-ultra-rich-can-pay-less-income-tax-than-you-legally/',
           'snippet': 'The report noted that in 2007 and 2011, Amazon.com Inc. '
                      'founder Jeff Bezos “did not pay a dime in federal ... '
                      'If you want to bet on Musk, check out Tesla.',
           'date': '11 mins ago',
           'source': 'THE BHARAT EXPRESS NEWS',
           'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_X9qqSwVFBBdos2CK5ky5IWIE3aJPCQeRYR9O1Jz4t-MjaEYBuwK7AU3AJQ&s',
           'position': 3}]}


'position': 3}]}
Some examples of the tbs parameter:
qdr:h (past hour)
qdr:d (past day)
qdr:w (past week)
qdr:m (past month)
qdr:y (past year)
You can specify intermediate time periods by adding a number:
qdr:h12 (past 12 hours)
qdr:d3 (past 3 days)
qdr:w2 (past 2 weeks)
qdr:m6 (past 6 months)
qdr:m2 (past 2 years)
For all supported filters simply go to Google Search, search for something, click on “Tools”, add your date filter and check the URL for “tbs=”.
Searching for Google Places#
We can also query Google Places using this wrapper. For example:
search = GoogleSerperAPIWrapper(type="places")
results = search.results("Italian restaurants in Upper East Side")
pprint.pp(results)
{'searchParameters': {'q': 'Italian restaurants in Upper East Side',
                      'gl': 'us',
                      'hl': 'en',
                      'num': 10,
                      'type': 'places'},
 'places': [{'position': 1,
             'title': "L'Osteria",
             'address': '1219 Lexington Ave',
             'latitude': 40.777154599999996,
             'longitude': -73.9571363,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNjU7BWEq_aYQANBCbX52Kb0lDpd_lFIx5onw40=w92-h92-n-k-no',
             'rating': 4.7,
             'ratingCount': 91,
             'category': 'Italian'},


'ratingCount': 91,
             'category': 'Italian'},
            {'position': 2,
             'title': "Tony's Di Napoli",
             'address': '1081 3rd Ave',
             'latitude': 40.7643567,
             'longitude': -73.9642373,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNbNv6jZkJ9nyVi60__8c1DQbe_eEbugRAhIYye=w92-h92-n-k-no',
             'rating': 4.5,
             'ratingCount': 2265,
             'category': 'Italian'},
            {'position': 3,
             'title': 'Caravaggio',
             'address': '23 E 74th St',
             'latitude': 40.773412799999996,
             'longitude': -73.96473379999999,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPDGchokDvppoLfmVEo6X_bWd3Fz0HyxIHTEe9V=w92-h92-n-k-no',
             'rating': 4.5,
             'ratingCount': 276,
             'category': 'Italian'},
            {'position': 4,
             'title': 'Luna Rossa',
             'address': '347 E 85th St',
             'latitude': 40.776593999999996,
             'longitude': -73.950351,


'longitude': -73.950351,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNPCpCPuqPAb1Mv6_fOP7cjb8Wu1rbqbk2sMBlh=w92-h92-n-k-no',
             'rating': 4.5,
             'ratingCount': 140,
             'category': 'Italian'},
            {'position': 5,
             'title': "Paola's",
             'address': '1361 Lexington Ave',
             'latitude': 40.7822019,
             'longitude': -73.9534096,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPJr2Vcx-B6K-GNQa4koOTffggTePz8TKRTnWi3=w92-h92-n-k-no',
             'rating': 4.5,
             'ratingCount': 344,
             'category': 'Italian'},
            {'position': 6,
             'title': 'Come Prima',
             'address': '903 Madison Ave',
             'latitude': 40.772124999999996,
             'longitude': -73.965012,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNrX19G0NVdtDyMovCQ-M-m0c_gLmIxrWDQAAbz=w92-h92-n-k-no',
             'rating': 4.5,
             'ratingCount': 176,
             'category': 'Italian'},
            {'position': 7,
             'title': 'Botte UES',
             'address': '1606 1st Ave.',


'address': '1606 1st Ave.',
             'latitude': 40.7750785,
             'longitude': -73.9504801,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPPN5GXxfH3NDacBc0Pt3uGAInd9OChS5isz9RF=w92-h92-n-k-no',
             'rating': 4.4,
             'ratingCount': 152,
             'category': 'Italian'},
            {'position': 8,
             'title': 'Piccola Cucina Uptown',
             'address': '106 E 60th St',
             'latitude': 40.7632468,
             'longitude': -73.9689825,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPifIgzOCD5SjgzzqBzGkdZCBp0MQsK5k7M7znn=w92-h92-n-k-no',
             'rating': 4.6,
             'ratingCount': 941,
             'category': 'Italian'},
            {'position': 9,
             'title': 'Pinocchio Restaurant',
             'address': '300 E 92nd St',
             'latitude': 40.781453299999995,
             'longitude': -73.9486788,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNtxlIyEEJHtDtFtTR9nB38S8A2VyMu-mVVz72A=w92-h92-n-k-no',
             'rating': 4.5,
             'ratingCount': 113,


'rating': 4.5,
             'ratingCount': 113,
             'category': 'Italian'},
            {'position': 10,
             'title': 'Barbaresco',
             'address': '843 Lexington Ave #1',
             'latitude': 40.7654332,
             'longitude': -73.9656873,
             'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipMb9FbPuXF_r9g5QseOHmReejxSHgSahPMPJ9-8=w92-h92-n-k-no',
             'rating': 4.3,
             'ratingCount': 122,
             'locationHint': 'In The Touraine',
             'category': 'Italian'}]}
previous
Google Search
next
Gradio Tools
 Contents

As part of a Self Ask With Search Chain
Obtaining results with metadata
Searching for Google Images
Searching for Google News
Searching for Google Places
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Jun 07, 2023.


.ipynb
.pdf
Zapier Natural Language Actions API
 Contents
Zapier Natural Language Actions API
Example with Agent
Example with SimpleSequentialChain
Zapier Natural Language Actions API#
Full docs here: https://nla.zapier.com/api/v1/docs
Zapier Natural Language Actions gives you access to the 5k+ apps, 20k+ actions on Zapier’s platform through a natural language API interface.
NLA supports apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot, Google Sheets, Microsoft Teams, and thousands more apps: https://zapier.com/apps
Zapier NLA handles ALL the underlying API auth and translation from natural language –> underlying API call –> return simplified output for LLMs. The key idea is you, or your users, expose a set of actions via an oauth-like setup window, which you can then query and execute via a REST API.
NLA offers both API Key and OAuth for signing NLA API requests.
Server-side (API Key): for quickly getting started, testing, and production scenarios where LangChain will only use actions exposed in the developer’s Zapier account (and will use the developer’s connected accounts on Zapier.com)
User-facing (Oauth): for production scenarios where you are deploying an end-user facing application and LangChain needs access to end-user’s exposed actions and connected accounts on Zapier.com
This quick start will focus on the server-side use case for brevity. Review full docs or reach out to nla@zapier.com for user-facing oauth developer support.
This example goes over how to use the Zapier integration with a SimpleSequentialChain, then an Agent.
In code, below:
import os
# get from https://platform.openai.com/
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "")


os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "")
# get from https://nla.zapier.com/demo/provider/debug (under User Information, after logging in):
os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "")
Example with Agent#
Zapier tools can be used with an agent. See the example below.
from langchain.llms import OpenAI
from langchain.agents import initialize_agent
from langchain.agents.agent_toolkits import ZapierToolkit
from langchain.agents import AgentType
from langchain.utilities.zapier import ZapierNLAWrapper
## step 0. expose gmail 'find email' and slack 'send channel message' actions
# first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all fields "Have AI guess"
# in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first
llm = OpenAI(temperature=0)
zapier = ZapierNLAWrapper()
toolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier)
agent = initialize_agent(toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("Summarize the last email I received regarding Silicon Valley Bank. Send the summary to the #test-zapier channel in slack.")
> Entering new AgentExecutor chain...
 I need to find the email and summarize it.
Action: Gmail: Find Email
Action Input: Find the latest email from Silicon Valley Bank


Action: Gmail: Find Email
Action Input: Find the latest email from Silicon Valley Bank
Observation: {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "sreply@svb.com", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.svb.com/NjEwLUtBSy0yNjYAAAGKgoxUeBCLAyF_NxON97X4rKEaNBLG", "reply_to__email": "sreply@svb.com", "subject": "Meet the new CEO Tim Mayopoulos", "date": "Tue, 14 Mar 2023 23:42:29 -0500 (CDT)", "message_url": "https://mail.google.com/mail/u/0/#inbox/186e393b13cfdf0a", "attachment_count": "0", "to__emails": "ankush@langchain.dev", "message_id": "186e393b13cfdf0a", "labels": "IMPORTANT, CATEGORY_UPDATES, INBOX"}
Thought: I need to summarize the email and send it to the #test-zapier channel in Slack.
Action: Slack: Send Channel Message
Action Input: Send a slack message to the #test-zapier channel with the text "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild."


Observation: {"message__text": "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild.", "message__permalink": "https://langchain.slack.com/archives/C04TSGU0RA7/p1678859932375259", "channel": "C04TSGU0RA7", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:58:52Z", "message__bot_profile__icons__image_36": "https://avatars.slack-edge.com/2022-08-02/3888649620612_f864dc1bb794cf7d82b0_36.png", "message__blocks[]block_id": "kdZZ", "message__blocks[]elements[]type": "['rich_text_section']"}
Thought: I now know the final answer.
Final Answer: I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack.
> Finished chain.
'I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack.'
Example with SimpleSequentialChain#
If you need more explicit control, use a chain, like below.
from langchain.llms import OpenAI
from langchain.chains import LLMChain, TransformChain, SimpleSequentialChain
from langchain.prompts import PromptTemplate


from langchain.prompts import PromptTemplate
from langchain.tools.zapier.tool import ZapierNLARunAction
from langchain.utilities.zapier import ZapierNLAWrapper
## step 0. expose gmail 'find email' and slack 'send direct message' actions
# first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all fields "Have AI guess"
# in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first
actions = ZapierNLAWrapper().list()
## step 1. gmail find email
GMAIL_SEARCH_INSTRUCTIONS = "Grab the latest email from Silicon Valley Bank"
def nla_gmail(inputs):
    action = next((a for a in actions if a["description"].startswith("Gmail: Find Email")), None)
    return {"email_data": ZapierNLARunAction(action_id=action["id"], zapier_description=action["description"], params_schema=action["params"]).run(inputs["instructions"])}
gmail_chain = TransformChain(input_variables=["instructions"], output_variables=["email_data"], transform=nla_gmail)
## step 2. generate draft reply
template = """You are an assisstant who drafts replies to an incoming email. Output draft reply in plain text (not JSON).
Incoming email:
{email_data}
Draft email reply:"""
prompt_template = PromptTemplate(input_variables=["email_data"], template=template)
reply_chain = LLMChain(llm=OpenAI(temperature=.7), prompt=prompt_template)
## step 3. send draft reply via a slack direct message
SLACK_HANDLE = "@Ankush Gola"
def nla_slack(inputs):