必应搜索# – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）Bing 搜索（Bing Search）

必应搜索#
本教程介绍如何使用必应搜索组件。
首先，您需要设置正确的API密钥和环境变量。要设置它，请按照此处 (opens in a new tab)的说明操作。
然后我们需要设置一些环境变量。

```code
import os
os.environ["BING_SUBSCRIPTION_KEY"] = ""
os.environ["BING_SEARCH_URL"] = ""

```

```code
from langchain.utilities import BingSearchAPIWrapper

```

```code
search = BingSearchAPIWrapper()

```

```code
search.run("python")

```

```code
'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor. <b>Python</b> releases by version number: Release version Release date Click for more. <b>Python</b> 3.11.1 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.10.9 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.9.16 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.8.16 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.7.16 Dec. 6, 2022 Download Release Notes. In this lesson, we will look at the += operator in <b>Python</b> and see how it works with several simple examples.. The operator ‘+=’ is a shorthand for the addition assignment operator.It adds two values and assigns the sum to a variable (left operand). W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, <b>Python</b>, SQL, Java, and many, many more. This tutorial introduces the reader informally to the basic concepts and features of the <b>Python</b> language and system. It helps to have a <b>Python</b> interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see The <b>Python</b> Standard ... <b>Python</b> is a general-purpose, versatile, and powerful programming language. It's a great first language because <b>Python</b> code is concise and easy to read. Whatever you want to do, <b>python</b> can do it. From web development to machine learning to data science, <b>Python</b> is the language for you. To install <b>Python</b> using the Microsoft Store: Go to your Start menu (lower left Windows icon), type "Microsoft Store", select the link to open the store. Once the store is open, select Search from the upper-right menu and enter "<b>Python</b>". Select which version of <b>Python</b> you would like to use from the results under Apps. Under the “<b>Python</b> Releases for Mac OS X” heading, click the link for the Latest <b>Python</b> 3 Release - <b>Python</b> 3.x.x. As of this writing, the latest version was <b>Python</b> 3.8.4. Scroll to the bottom and click macOS 64-bit installer to start the download. When the installer is finished downloading, move on to the next step. Step 2: Run the Installer'

```

结果数量#
您可以使用
```code
k
```
参数设置结果数量。

```code
search = BingSearchAPIWrapper(k=1)

```

```code
search.run("python")

```

```code
'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor.'

```

元数据结果#
通过BingSearch运行查询并返回片段、标题和链接元数据。

片段：结果的描述。

标题：结果的标题。

链接：结果的链接。

```code
search = BingSearchAPIWrapper()

```

```code
search.results("apples", 5)

```

```code
[{'snippet': 'Lady Alice. Pink Lady <b>apples</b> aren’t the only lady in the apple family. Lady Alice <b>apples</b> were discovered growing, thanks to bees pollinating, in Washington. They are smaller and slightly more stout in appearance than other varieties. Their skin color appears to have red and yellow stripes running from stem to butt.',
'title': '25 Types of Apples - Jessica Gavin',
'link': 'https://www.jessicagavin.com/types-of-apples/'},
{'snippet': '<b>Apples</b> can do a lot for you, thanks to plant chemicals called flavonoids. And they have pectin, a fiber that breaks down in your gut. If you take off the apple’s skin before eating it, you won ...',
'title': 'Apples: Nutrition & Health Benefits - WebMD',
'link': 'https://www.webmd.com/food-recipes/benefits-apples'},
{'snippet': '<b>Apples</b> boast many vitamins and minerals, though not in high amounts. However, <b>apples</b> are usually a good source of vitamin C. Vitamin C. Also called ascorbic acid, this vitamin is a common ...',
'title': 'Apples 101: Nutrition Facts and Health Benefits',
'link': 'https://www.healthline.com/nutrition/foods/apples'},
{'snippet': 'Weight management. The fibers in <b>apples</b> can slow digestion, helping one to feel greater satisfaction after eating. After following three large prospective cohorts of 133,468 men and women for 24 years, researchers found that higher intakes of fiber-rich fruits with a low glycemic load, particularly <b>apples</b> and pears, were associated with the least amount of weight gain over time.',
'title': 'Apples | The Nutrition Source | Harvard T.H. Chan School of Public Health',
'link': 'https://www.hsph.harvard.edu/nutritionsource/food-features/apples/'}]

```
BashChatGPT 插件（ChatGPT Plugins）


ChatGPT插件# – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）ChatGPT 插件（ChatGPT Plugins）

ChatGPT插件#
此示例显示如何在LangChain抽象中使用ChatGPT插件。
注1：目前仅适用于没有身份验证的插件。
注2：几乎肯定还有其他方法可以做到这一点，这只是第一次尝试。 如果您有更好的想法，请打开PR！

```code
from langchain.chat_models import ChatOpenAI
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
from langchain.tools import AIPluginTool

```

```code
tool = AIPluginTool.from_plugin_url("https://www.klarna.com/.well-known/ai-plugin.json")

```

```code
llm = ChatOpenAI(temperature=0)
tools = load_tools(["requests_all"] )
tools += [tool]

agent_chain = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent_chain.run("what t shirts are available in klarna?")

```

```code
> Entering new AgentExecutor chain...
I need to check the Klarna Shopping API to see if it has information on available t shirts.
Action: KlarnaProducts
Action Input: None
Observation: Usage Guide: Use the Klarna plugin to get relevant product suggestions for any shopping or researching purpose. The query to be sent should not include stopwords like articles, prepositions and determinants. The api works best when searching for words that are related to products, like their name, brand, model or category. Links will always be returned and should be shown to the user.

OpenAPI Spec: {'openapi': '3.0.1', 'info': {'version': 'v0', 'title': 'Open AI Klarna product Api'}, 'servers': [{'url': 'https://www.klarna.com/us/shopping'}], 'tags': [{'name': 'open-ai-product-endpoint', 'description': 'Open AI Product Endpoint. Query for products.'}], 'paths': {'/public/openai/v0/products': {'get': {'tags': ['open-ai-product-endpoint'], 'summary': 'API for fetching Klarna product information', 'operationId': 'productsUsingGET', 'parameters': [{'name': 'q', 'in': 'query', 'description': 'query, must be between 2 and 100 characters', 'required': True, 'schema': {'type': 'string'}}, {'name': 'size', 'in': 'query', 'description': 'number of products returned', 'required': False, 'schema': {'type': 'integer'}}, {'name': 'budget', 'in': 'query', 'description': 'maximum price of the matching product in local currency, filters results', 'required': False, 'schema': {'type': 'integer'}}], 'responses': {'200': {'description': 'Products found', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/ProductResponse'}}}}, '503': {'description': 'one or more services are unavailable'}}, 'deprecated': False}}}, 'components': {'schemas': {'Product': {'type': 'object', 'properties': {'attributes': {'type': 'array', 'items': {'type': 'string'}}, 'name': {'type': 'string'}, 'price': {'type': 'string'}, 'url': {'type': 'string'}}, 'title': 'Product'}, 'ProductResponse': {'type': 'object', 'properties': {'products': {'type': 'array', 'items': {'$ref': '#/components/schemas/Product'}}}, 'title': 'ProductResponse'}}}}
Thought:I need to use the Klarna Shopping API to search for t shirts.
Action: requests_get
Action Input: https://www.klarna.com/us/shopping/public/openai/v0/products?q=t%20shirts
Observation: {"products":[{"name":"Lacoste Men's Pack of Plain T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202043025/Clothing/Lacoste-Men-s-Pack-of-Plain-T-Shirts/?utm_source=openai","price":"$26.60","attributes":["Material:Cotton","Target Group:Man","Color:White,Black"]},{"name":"Hanes Men's Ultimate 6pk. Crewneck T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201808270/Clothing/Hanes-Men-s-Ultimate-6pk.-Crewneck-T-Shirts/?utm_source=openai","price":"$13.82","attributes":["Material:Cotton","Target Group:Man","Color:White"]},{"name":"Nike Boy's Jordan Stretch T-shirts","url":"https://www.klarna.com/us/shopping/pl/cl359/3201863202/Children-s-Clothing/Nike-Boy-s-Jordan-Stretch-T-shirts/?utm_source=openai","price":"$14.99","attributes":["Material:Cotton","Color:White,Green","Model:Boy","Size (Small-Large):S,XL,L,M"]},{"name":"Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203028500/Clothing/Polo-Classic-Fit-Cotton-V-Neck-T-Shirts-3-Pack/?utm_source=openai","price":"$29.95","attributes":["Material:Cotton","Target Group:Man","Color:White,Blue,Black"]},{"name":"adidas Comfort T-shirts Men's 3-pack","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202640533/Clothing/adidas-Comfort-T-shirts-Men-s-3-pack/?utm_source=openai","price":"$14.99","attributes":["Material:Cotton","Target Group:Man","Color:White,Black","Neckline:Round"]}]}
Thought:The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack.
Final Answer: The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack.

> Finished chain.

```

```code
"The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack."

```
Bing 搜索（Bing Search）DuckDuckGo


DuckDuckGo搜索 – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）DuckDuckGo

DuckDuckGo搜索
本教程介绍了如何使用"duck-duck-go"搜索组件。

```code
# !pip install duckduckgo-search

```

```code
from langchain.tools import DuckDuckGoSearchRun

```

```code
search = DuckDuckGoSearchRun()

```

```code
search.run("Obama's first name?")

```

```code
'Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009-17) and the first African American to hold the office. Before winning the presidency, Obama represented Illinois in the U.S. Senate (2005-08). Barack Hussein Obama II (/ b ə ˈ r ɑː k h uː ˈ s eɪ n oʊ ˈ b ɑː m ə / bə-RAHK hoo-SAYN oh-BAH-mə; born August 4, 1961) is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African-American president of the United States. Obama previously served as a U.S. senator representing ... Barack Obama was the first African American president of the United States (2009-17). He oversaw the recovery of the U.S. economy (from the Great Recession of 2008-09) and the enactment of landmark health care reform (the Patient Protection and Affordable Care Act ). In 2009 he was awarded the Nobel Peace Prize. His birth certificate lists his first name as Barack: That\'s how Obama has spelled his name throughout his life. His name derives from a Hebrew name which means "lightning.". The Hebrew word has been transliterated into English in various spellings, including Barak, Buraq, Burack, and Barack. Most common names of U.S. presidents 1789-2021. Published by. Aaron O\'Neill , Jun 21, 2022. The most common first name for a U.S. president is James, followed by John and then William. Six U.S ...'

```
ChatGPT 插件（ChatGPT Plugins）文件系统（Filesystem）


文件系统工具# – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）文件系统（Filesystem）

文件系统工具#
LangChain提供了与本地文件系统交互的工具。本教程演示了其中的一些。
注意：这些工具不建议在沙盒环境之外使用！
首先，我们将导入工具。

```code
from langchain.tools.file_management import (
ReadFileTool,
CopyFileTool,
DeleteFileTool,
MoveFileTool,
WriteFileTool,
ListDirectoryTool,
)
from langchain.agents.agent_toolkits import FileManagementToolkit
from tempfile import TemporaryDirectory

# We'll make a temporary directory to avoid clutter
working_directory = TemporaryDirectory()

```

文件管理工具包#
如果您想为代理提供所有文件工具，使用工具包很容易。我们将临时目录作为根目录传递给LLM作为工作区。
建议始终传递根目录，因为没有根目录，LLM很容易污染工作目录，没有根目录，也没有验证可以防止简单的提示注入。

```code
toolkit = FileManagementToolkit(root_dir=str(working_directory.name)) # If you don't provide a root_dir, operations will default to the current working directory
toolkit.get_tools()

```

```code
[CopyFileTool(name='copy_file', description='Create a copy of a file in a specified location', args_schema=<class 'langchain.tools.file_management.copy.FileCopyInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
DeleteFileTool(name='file_delete', description='Delete a file', args_schema=<class 'langchain.tools.file_management.delete.FileDeleteInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
FileSearchTool(name='file_search', description='Recursively search for files in a subdirectory that match the regex pattern', args_schema=<class 'langchain.tools.file_management.file_search.FileSearchInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
MoveFileTool(name='move_file', description='Move or rename a file from one location to another', args_schema=<class 'langchain.tools.file_management.move.FileMoveInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]

```

选择文件系统工具#
如果您只想选择某些工具，在初始化工具包时可以将它们作为参数传递，或者您可以单独初始化所需的工具。

```code
tools = FileManagementToolkit(root_dir=str(working_directory.name), selected_tools=["read_file", "write_file", "list_directory"]).get_tools()
tools

```

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

```

```code
read_tool, write_tool, list_tool = tools
write_tool.run({"file_path": "example.txt", "text": "Hello World!"})

```

```code
'File written successfully to example.txt.'

```

```code
# List files in the working directory
list_tool.run({})

```

```code
'example.txt'

```
DuckDuckGoGoogle 地点（Google Places）


Google地点 – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）Google 地点（Google Places）

Google地点
本教程将介绍如何使用Google Places API。

```code
#!pip install googlemaps

```

```code
import os
os.environ["GPLACES_API_KEY"] = ""

```

```code
from langchain.tools import GooglePlacesTool

```

```code
places = GooglePlacesTool()

```

```code
places.run("al fornos")

```

```code
"1. Delfina Restaurant\nAddress: 3621 18th St, San Francisco, CA 94110, USA\nPhone: (415) 552-4055\nWebsite: https://www.delfinasf.com/  \n2. Piccolo Forno\nAddress: 725 Columbus Ave, San Francisco, CA 94133, USA\nPhone: (415) 757-0087\nWebsite: https://piccolo-forno-sf.com/  \n3. L'Osteria del Forno\nAddress: 519 Columbus Ave, San Francisco, CA 94133, USA\nPhone: (415) 982-1124\nWebsite: Unknown  \n4. Il Fornaio\nAddress: 1265 Battery St, San Francisco, CA 94111, USA\nPhone: (415) 986-0100\nWebsite: https://www.ilfornaio.com/  "

```
文件系统（Filesystem）Google 搜索（Google Search）


Python编程语言的官方网站 – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）Google 搜索（Google Search）

使用Google搜索组件
本教程将介绍如何使用Google搜索组件。
首先，您需要设置适当的API密钥和环境变量。
要设置它，请在Google Cloud凭据控制台 (opens in a new tab)中创建GOOGLE_API_KEY，
并使用Programmable Search Enginge (opens in a new tab)创建GOOGLE_CSE_ID。
接下来，最好按照这里 (opens in a new tab)的说明操作。
然后，我们需要设置一些环境变量。

```code
import os
os.environ["GOOGLE_CSE_ID"] = ""
os.environ["GOOGLE_API_KEY"] = ""

```

```code
from langchain.tools import Tool
from langchain.utilities import GoogleSearchAPIWrapper

search = GoogleSearchAPIWrapper()

tool = Tool(
name = "Google Search",
description="Search Google for recent results.",
func=search.run
)

```

```code
tool.run("Obama's first name?")

```

```code
"STATE OF HAWAII. 1 Child's First Name. (Type or print). 2. Sex. BARACK. 3. This Birth. CERTIFICATE OF LIVE BIRTH. FILE. NUMBER 151 le. lb. Middle Name. Barack Hussein Obama II is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Jan 19, 2017 ... Jordan Barack Treasure, New York City, born in 2008 ... Jordan Barack Treasure made national news when he was the focus of a New York newspaper\xa0... Portrait of George Washington, the 1st President of the United States ... Portrait of Barack Obama, the 44th President of the United States\xa0... His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Mar 22, 2008 ... Barry Obama decided that he didn't like his nickname. A few of his friends at Occidental College had already begun to call him Barack (his\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama's first name. Miller knew that every answer had to\xa0... Feb 9, 2015 ... Michael Jordan misspelled Barack Obama's first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\xa0... 4 days ago ... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009–17) and\xa0..."

```

结果数量
您可以使用
```code
k
```
参数来设置结果数量。

```code
search = GoogleSearchAPIWrapper(k=1)

tool = Tool(
name = "I'm Feeling Lucky",
description="Search Google and return the first result.",
func=search.run
)

```

```code
tool.run("python")

```

```code
'The official home of the Python Programming Language.'

```

Python编程语言的官方网站
元数据结果
运行通过GoogleSearch查询并返回片段、标题和链接元数据。

片段：结果的描述。
标题：结果的标题。
链接：结果的链接。

```code
search = GoogleSearchAPIWrapper()

def top5_results(query):
return search.results(query, 5)

tool = Tool(
name = "Google Search Snippets",
description="Search Google for recent results.",
func=top5_results
)

```
Google 地点（Google Places）Google SERP


Google Serper API# – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）Google SERP

Google Serper API#
本笔记介绍如何使用Google Serper组件搜索网络。首先，您需要在serper.dev (opens in a new tab)注册免费帐户并获取API密钥。

```code
import os
import pprint
os.environ["SERPER_API_KEY"] = ""

```

```code
from langchain.utilities import GoogleSerperAPIWrapper

```

```code
search = GoogleSerperAPIWrapper()

```

```code
search.run("Obama's first name?")

```

```code
'Barack Hussein Obama II'

```

作为自问自答搜索链的一部分#

```code
os.environ['OPENAI_API_KEY'] = ""

```

```code
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?")

```

```code
> Entering new AgentExecutor chain...
Yes.
Follow up: Who is the reigning men's U.S. Open champion?
Intermediate answer: Current champions Carlos Alcaraz, 2022 men's singles champion.
Follow up: Where is Carlos Alcaraz from?
Intermediate answer: El Palmar, Spain
So the final answer is: El Palmar, Spain

> Finished chain.

```

```code
'El Palmar, Spain'

```

获取带元数据的结果#
如果您还希望以结构化方式获取结果，包括元数据。为此，我们将使用包装器的
```code
results
```
方法。

```code
search = GoogleSerperAPIWrapper()
results = search.results("Apple Inc.")
pprint.pp(results)

```

```code
{'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–)',
'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, ...',
'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',
'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, '
'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 - '
'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'}]}

```

搜索Google图像#
我们还可以使用这个包装器查询Google图像。例如：

```code
search = GoogleSerperAPIWrapper(type="images")
results = search.results("Lion")
pprint.pp(results)

```

```code
{'searchParameters': {'q': 'Lion',
'gl': 'us',
'hl': 'en',
'num': 10,
'type': 'images'},
'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},
{'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,
'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',
'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,
'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}]}

```

搜索Google新闻#
我们还可以使用这个包装器查询谷歌新闻。例如：

```code
search = GoogleSerperAPIWrapper(type="news")
results = search.results("Tesla Inc.")
pprint.pp(results)

```

```code
{'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...',
'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',
'snippet': 'This comes days after Joby clinched a $55 million '
'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',
'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',
'link': 'https://www.bizjournals.com/austin/news/2023/05/02/tesla-leases-building-seattle-area',
'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}]}

```

如果你只想收到过去一小时内发布的新闻文章，可以按照以下步骤操作：

```code
search = GoogleSerperAPIWrapper(type="news", tbs="qdr:h")
results = search.results("Tesla Inc.")
pprint.pp(results)

```

```code
{'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}]}

```

```code
tbs
```
参数的一些示例：

```code
qdr:h
```
（过去一小时)

```code
qdr:d
```
（过去一天)

```code
qdr:w
```
（过去一周)

```code
qdr:m
```
（过去一个月)

```code
qdr:y
```
（过去一年)
你可以通过添加一个数字来指定中间时间段：

```code
qdr:h12
```
（过去12小时)

```code
qdr:d3
```
（过去3天)

```code
qdr:w2
```
（过去2周)

```code
qdr:m6
```
（过去6个月)

```code
qdr:m2
```
（过去2年)
要获取所有支持的过滤器，请访问Google搜索 (opens in a new tab)，搜索一些内容，点击"工具"，添加日期过滤器并检查URL中的"tbs="。
搜索Google地点#
We can also query Google Places using this wrapper. For example:

```code
search = GoogleSerperAPIWrapper(type="places")
results = search.results("Italian restaurants in Upper East Side")
pprint.pp(results)

```

```code
{'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'},
{'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,
'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.',
'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,
'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'}]}

```
Google 搜索（Google Search）Gradio 工具（Gradio Tools）


gradio-tools – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）Gradio 工具（Gradio Tools）

gradio-tools
Hugging Face空间中有许多Gradio应用程序。此库可让您的LLM快速访问它们。
具体而言，gradio-tools是一个Python库，用于将Gradio应用程序转换为工具，可以被基于大型语言模型（LLM)的代理利用来完成其任务。例如，LLM可以使用Gradio工具来转录它在网上找到的语音记录，然后为您总结它。或者它可以使用不同的Gradio工具来对您Google Drive上的文件应用OCR，然后回答相关问题。
如果您想使用未预先构建的工具创建自己的工具，则非常容易。请参阅gradio-tools文档的此部分以获取有关如何执行此操作的信息。欢迎所有贡献！

```code
# !pip install gradio_tools

```

Using a tool#

```code
from gradio_tools.tools import StableDiffusionTool

```

```code
local_file_path = StableDiffusionTool().langchain.run("Please create a photo of a dog riding a skateboard")
local_file_path

```

```code
Loaded as API: https://gradio-client-demos-stable-diffusion.hf.space ✔

Job Status: Status.STARTING eta: None

```

```code
'/Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/examples/b61c1dd9-47e2-46f1-a47c-20d27640993d/tmp4ap48vnm.jpg'

```

```code
from PIL import Image

```

```code
im = Image.open(local_file_path)

```

```code
display(im)

```

跟代理一起使用#

```code
from langchain.agents import initialize_agent
from langchain.llms import OpenAI
from gradio_tools.tools import (StableDiffusionTool, ImageCaptioningTool, StableDiffusionPromptGeneratorTool,
TextToVideoTool)

from langchain.memory import ConversationBufferMemory

llm = OpenAI(temperature=0)
memory = ConversationBufferMemory(memory_key="chat_history")
tools = [StableDiffusionTool().langchain, ImageCaptioningTool().langchain,
StableDiffusionPromptGeneratorTool().langchain, TextToVideoTool().langchain]

agent = initialize_agent(tools, llm, memory=memory, agent="conversational-react-description", verbose=True)
output = agent.run(input=("Please create a photo of a dog riding a skateboard "
"but improve my prompt prior to using an image generator."
"Please caption the generated image and create a video for it using the improved prompt."))

```

```code
Loaded as API: https://gradio-client-demos-stable-diffusion.hf.space ✔
Loaded as API: https://taesiri-blip-2.hf.space ✔
Loaded as API: https://microsoft-promptist.hf.space ✔
Loaded as API: https://damo-vilab-modelscope-text-to-video-synthesis.hf.space ✔

> Entering new AgentExecutor chain...

Thought: Do I need to use a tool? Yes
Action: StableDiffusionPromptGenerator
Action Input: A dog riding a skateboard
Job Status: Status.STARTING eta: None

Observation: A dog riding a skateboard, digital painting, artstation, concept art, smooth, sharp focus, illustration, art by artgerm and greg rutkowski and alphonse mucha
Thought: Do I need to use a tool? Yes
Action: StableDiffusion
Action Input: A dog riding a skateboard, digital painting, artstation, concept art, smooth, sharp focus, illustration, art by artgerm and greg rutkowski and alphonse mucha
Job Status: Status.STARTING eta: None

Job Status: Status.PROCESSING eta: None

Observation: /Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/examples/2e280ce4-4974-4420-8680-450825c31601/tmpfmiz2g1c.jpg
Thought: Do I need to use a tool? Yes
Action: ImageCaptioner
Action Input: /Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/examples/2e280ce4-4974-4420-8680-450825c31601/tmpfmiz2g1c.jpg
Job Status: Status.STARTING eta: None

Observation: a painting of a dog sitting on a skateboard
Thought: Do I need to use a tool? Yes
Action: TextToVideo
Action Input: a painting of a dog sitting on a skateboard
Job Status: Status.STARTING eta: None
Due to heavy traffic on this app, the prediction will take approximately 73 seconds.For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate(damo-vilab/modelscope-text-to-video-synthesis)

Job Status: Status.IN_QUEUE eta: 73.89824726581574
Due to heavy traffic on this app, the prediction will take approximately 42 seconds.For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate(damo-vilab/modelscope-text-to-video-synthesis)

Job Status: Status.IN_QUEUE eta: 42.49370198879602

Job Status: Status.IN_QUEUE eta: 21.314297944849187

Observation: /var/folders/bm/ylzhm36n075cslb9fvvbgq640000gn/T/tmp5snj_nmzf20_cb3m.mp4
Thought: Do I need to use a tool? No
AI: Here is a video of a painting of a dog sitting on a skateboard.

> Finished chain.

```
Google SERP人类工具（Human Tools）


人类AGI工具 – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）人类工具（Human Tools）

人类AGI工具
人类具有AGI，因此当AI代理处于困惑状态时，它们可以作为工具来帮助。

```code
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,
)

```

在上面的代码中，您可以看到工具直接从命令行接收输入。您可以根据需要自定义
```code
prompt_func
```
和
```code
input_func
```
（如下所示)。

```code
agent_chain.run("When's my friend Eric's surname?")
# Answer with 'Zhu'

```

```code
> Entering new AgentExecutor chain...
我不知道Eric的姓氏，所以我需要向人类寻求帮助。
行动: 人类
行动输入："Eric的姓氏是什么？"

Eric的姓氏是什么？

```

```code
观察结果: Zhu
想法：我现在知道Eric的姓氏是Zhu。
最终答案：Eric的姓氏是Zhu。

> 完成链式结构。

```

```code
"Eric的姓氏是Zhu。"

```

配置输入函数
默认情况下，
```code
HumanInputRun
```
工具使用Python的
```code
input
```
函数从用户处获取输入。您可以自定义
```code
input_func
```
。例如，如果您想接受多行输入，则可以执行以下操作：

```code
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
)

```

```code
# Or you can directly instantiate the tool
from langchain.tools import HumanInputRun

tool = HumanInputRun(input_func=get_input)

```

```code
agent_chain = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
)

```

```code
agent_chain.run("I need help attributing a quote")

```

```code
> 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.

```

```code
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.

```

```code
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 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.

```

```code
'Julius Caesar said the quote "Veni, vidi, vici" which means "I came, I saw, I conquered".'

```
Gradio 工具（Gradio Tools）IFTTT


IFTTT Webhooks – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）IFTTT

IFTTT Webhooks
这篇笔记展示了如何使用IFTTT Webhooks。
来自https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services。 (opens in a new tab)
创建Webhook#

访问https://ifttt.com/create (opens in a new tab)

配置“If This”#

在IFTTT界面上单击“If This”按钮。

在搜索栏中搜索“Webhooks”。

选择“接收带有JSON有效负载的Web请求”的第一个选项。

选择一个与您计划连接的服务具体相关的事件名称。这将使您更容易管理Webhook URL。例如，如果您连接到Spotify，您可以使用“Spotify”作为您的事件名称。

Click the “Create Trigger” button to save your settings and create your webhook.

配置“那么”（Then That)

在IFTTT界面中点击“那么”按钮。

搜索您要连接的服务，如Spotify。

选择要从服务中执行的操作，例如“添加到播放列表”。

通过指定必要的细节来配置操作，例如播放列表名称，例如“来自AI的歌曲”。

在操作中引用Webhook接收到的JSON负载。对于Spotify场景，将
```code
JsonPayload
```
作为您的搜索查询。

单击“创建操作”按钮以保存您的操作设置。

一旦您完成操作的配置，请单击“完成”按钮以完成设置。

恭喜！您已成功将Webhook连接到所需的服务，现在您可以开始接收数据并触发操作 🎉

完成#

要获取您的Webhook URL，请访问https://ifttt.com/maker_webhooks/settings (opens in a new tab)

从那里复制IFTTT密钥值。 URL的格式为
https://maker.ifttt.com/use/YOUR_IFTTT_KEY。获取YOUR_IFTTT_KEY值。 (opens in a new tab)

```code
from langchain.tools.ifttt import IFTTTWebhook

```

```code
import os
key = os.environ["IFTTTKey"]
url = f"https://maker.ifttt.com/trigger/spotify/json/with/key/{key}"
tool = IFTTTWebhook(name="Spotify", description="Add a song to spotify playlist", url=url)

```

```code
tool.run("taylor swift")

```

```code
"Congratulations! You've fired the spotify JSON event"

```
人类工具（Human Tools）OpenWeatherMap


OpenWeatherMap – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）OpenWeatherMap

OpenWeatherMap
本教程将介绍如何使用OpenWeatherMap组件获取天气信息。
首先，您需要注册OpenWeatherMap API密钥：

前往OpenWeatherMap并注册API密钥 这里 (opens in a new tab)
安装pyowm：'pip install pyowm'

然后，我们需要设置一些环境变量：

将您的API KEY保存到OPENWEATHERMAP_API_KEY环境变量中

```code
pip install pyowm

```

```code
import os
os.environ["OPENWEATHERMAP_API_KEY"] = ""

```

```code
from langchain.utilities import OpenWeatherMapAPIWrapper

```

```code
weather = OpenWeatherMapAPIWrapper()

```

```code
weather_data = weather.run("London,GB")

```

```code
print(weather_data)

```

```code
In London,GB, the current weather is as follows:
Detailed status: overcast clouds
Wind speed: 4.63 m/s, direction: 150°
Humidity: 67%
Temperature:
- Current: 5.35°C
- High: 6.26°C
- Low: 3.49°C
- Feels like: 1.95°C
Rain: {}
Heat index: None
Cloud cover: 100%

```
IFTTTPython


Python – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）Python

Python REPL
有时，对于复杂的计算，与其让LLM直接生成答案，不如让LLM生成计算答案的代码，然后运行该代码以获得答案。为了便于执行该操作，我们提供了一个简单的Python REPL来执行命令。
该界面只会返回已打印的内容-因此，如果要使用它计算答案，请确保它打印出答案。

```code
from langchain.agents import Tool
from langchain.utilities import PythonREPL

```

```code
python_repl = PythonREPL()

```

```code
python_repl.run("print(1+1)")

```

```code
'2\n'

```

```code
# 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
)

```
OpenWeatherMapRequests


Python Requests – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）Requests

Python Requests
网络上包含许多LLM无法访问的信息。为了让LLM轻松地与该信息进行交互，我们提供了Python Requests模块的一个包装器，该包装器接收URL并从该URL获取数据。

```code
from langchain.agents import load_tools

requests_tools = load_tools(["requests_all"])

```

```code
requests_tools

```

```code
[RequestsGetTool(name='requests_get', description='A portal to the internet. Use this when you need to get specific content from a website. Input should be a  url (i.e. https://www.google.com). The output will be the text response of the GET request.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)),
RequestsPostTool(name='requests_post', description='Use this when you want to POST to a website.\n    Input should be a json string with two keys: "url" and "data".\n    The value of "url" should be a string, and the value of "data" should be a dictionary of \n    key-value pairs you want to POST to the url.\n    Be careful to always use double quotes for strings in the json string\n    The output will be the text response of the POST request.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)),
RequestsPatchTool(name='requests_patch', description='Use this when you want to PATCH to a website.\n    Input should be a json string with two keys: "url" and "data".\n    The value of "url" should be a string, and the value of "data" should be a dictionary of \n    key-value pairs you want to PATCH to the url.\n    Be careful to always use double quotes for strings in the json string\n    The output will be the text response of the PATCH request.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)),
RequestsPutTool(name='requests_put', description='Use this when you want to PUT to a website.\n    Input should be a json string with two keys: "url" and "data".\n    The value of "url" should be a string, and the value of "data" should be a dictionary of \n    key-value pairs you want to PUT to the url.\n    Be careful to always use double quotes for strings in the json string.\n    The output will be the text response of the PUT request.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)),
RequestsDeleteTool(name='requests_delete', description='A portal to the internet. Use this when you need to make a DELETE request to a URL. Input should be a specific url, and the output will be the text response of the DELETE request.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None))]

```

在工具内部
每个请求工具都包含一个
```code
requests
```
包装器。您可以直接在下面与这些包装器一起使用。

```code
# Each tool wrapps a requests wrapper
requests_tools[0].requests_wrapper

```

```code
TextRequestsWrapper(headers=None, aiosession=None)

```

```code
from langchain.utilities import TextRequestsWrapper
requests = TextRequestsWrapper()

```

```code
requests.get("https://www.google.com")

```

```code
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s information, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){window.google={kEI:\'TA9QZOa5EdTakPIPuIad-Ac\',kEXPI:\'0,1359409,6059,206,4804,2316,383,246,5,1129120,1197768,626,380097,16111,28687,22431,1361,12319,17581,4997,13228,37471,7692,2891,3926,213,7615,606,50058,8228,17728,432,3,346,1244,1,16920,2648,4,1528,2304,29062,9871,3194,13658,2980,1457,16786,5803,2554,4094,7596,1,42154,2,14022,2373,342,23024,6699,31123,4568,6258,23418,1252,5835,14967,4333,4239,3245,445,2,2,1,26632,239,7916,7321,60,2,3,15965,872,7830,1796,10008,7,1922,9779,36154,6305,2007,17765,427,20136,14,82,2730,184,13600,3692,109,2412,1548,4308,3785,15175,3888,1515,3030,5628,478,4,9706,1804,7734,2738,1853,1032,9480,2995,576,1041,5648,3722,2058,3048,2130,2365,662,476,958,87,111,5807,2,975,1167,891,3580,1439,1128,7343,426,249,517,95,1102,14,696,1270,750,400,2208,274,2776,164,89,119,204,139,129,1710,2505,320,3,631,439,2,300,1645,172,1783,784,169,642,329,401,50,479,614,238,757,535,717,102,2,739,738,44,232,22,442,961,45,214,383,567,500,487,151,120,256,253,179,673,2,102,2,10,535,123,135,1685,5206695,190,2,20,50,198,5994221,2804424,3311,141,795,19735,1,1,346,5008,7,13,10,24,31,2,39,1,5,1,16,7,2,41,247,4,9,7,9,15,4,4,121,24,23944834,4042142,1964,16672,2894,6250,15739,1726,647,409,837,1411438,146986,23612960,7,84,93,33,101,816,57,532,163,1,441,86,1,951,73,31,2,345,178,243,472,2,148,962,455,167,178,29,702,1856,288,292,805,93,137,68,416,177,292,399,55,95,2566\',kBL:\'hw1A\',kOPI:89978449};google.sn=\'webhp\';google.kHL=\'en\';})();(function(){\nvar h=this||self;function l(){return void 0!==window.google&&void 0!==window.google.kOPI&&0!==window.google.kOPI?window.google.kOPI:null};var m,n=[];function p(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||m}function q(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b}function r(a){/^http:/i.test(a)&&"https:"===window.location.protocol&&(google.ml&&google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a}\nfunction t(a,b,c,d,k){var e="";-1===b.search("&ei=")&&(e="&ei="+p(d),-1===b.search("&lei=")&&(d=q(d))&&(e+="&lei="+d));d="";var g=-1===b.search("&cshid=")&&"slh"!==a,f=[];f.push(["zx",Date.now().toString()]);h._cshid&&g&&f.push(["cshid",h._cshid]);c=c();null!=c&&f.push(["opi",c.toString()]);for(c=0;c<f.length;c++){if(0===c||0<c)d+="&";d+=f[c][0]+"="+f[c][1]}return"/"+(k||"gen_204")+"?atyp=i&ct="+String(a)+"&cad="+(b+e+d)};m=google.kEI;google.getEI=p;google.getLEI=q;google.ml=function(){return null};google.log=function(a,b,c,d,k,e){e=void 0===e?l:e;c||(c=t(a,b,e,d,k));if(c=r(c)){a=new Image;var g=n.length;n[g]=a;a.onerror=a.onload=a.onabort=function(){delete n[g]};a.src=c}};google.logUrl=function(a,b){b=void 0===b?l:b;return t("",a,b)};}).call(this);(function(){google.y={};google.sy=[];google.x=function(a,b){if(a)var c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1};google.sx=function(a){google.sy.push(a)};google.lm=[];google.plm=function(a){google.lm.push.apply(google.lm,a)};google.lq=[];google.load=function(a,b,c){google.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};google.bx=!1;google.lx=function(){};}).call(this);google.f={};(function(){\ndocument.documentElement.addEventListener("submit",function(b){var a;if(a=b.target){var c=a.getAttribute("data-submitfalse");a="1"===c||"q"===c&&!a.elements.q.value?!0:!1}else a=!1;a&&(b.preventDefault(),b.stopPropagation())},!0);document.documentElement.addEventListener("click",function(b){var a;a:{for(a=b.target;a&&a!==document.documentElement;a=a.parentElement)if("A"===a.tagName){a="1"===a.getAttribute("data-nohref");break a}a=!1}a&&b.preventDefault()},!0);}).call(this);</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}\n</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#1558d6}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}body{background:#fff;color:#000}a{color:#4b11a8;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#1558d6}a:visited{color:#4b11a8}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#f8f9fa;border:solid 1px;border-color:#dadce0 #70757a #70757a #dadce0;height:30px}.lsbb{display:block}#WqQANb a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#dadce0}.lst:focus{outline:none}</style><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){window.google.erd={jsr:1,bv:1785,de:true};\nvar h=this||self;var k,l=null!=(k=h.mei)?k:1,n,p=null!=(n=h.sdo)?n:!0,q=0,r,t=google.erd,v=t.jsr;google.ml=function(a,b,d,m,e){e=void 0===e?2:e;b&&(r=a&&a.message);if(google.dl)return google.dl(a,e,d),null;if(0>v){window.console&&console.error(a,d);if(-2===v)throw a;b=!1}else b=!a||!a.message||"Error loading script"===a.message||q>=l&&!m?!1:!0;if(!b)return null;q++;d=d||{};b=encodeURIComponent;var c="/gen_204?atyp=i&ei="+b(google.kEI);google.kEXPI&&(c+="&jexpid="+b(google.kEXPI));c+="&srcpg="+b(google.sn)+"&jsr="+b(t.jsr)+"&bver="+b(t.bv);var f=a.lineNumber;void 0!==f&&(c+="&line="+f);var g=\na.fileName;g&&(0<g.indexOf("-extension:/")&&(e=3),c+="&script="+b(g),f&&g===window.location.href&&(f=document.documentElement.outerHTML.split("\\n")[f],c+="&cad="+b(f?f.substring(0,300):"No script found.")));c+="&jsel="+e;for(var u in d)c+="&",c+=b(u),c+="=",c+=b(d[u]);c=c+"&emsg="+b(a.name+": "+a.message);c=c+"&jsst="+b(a.stack||"N/A");12288<=c.length&&(c=c.substr(0,12288));a=c;m||google.log(0,"",a);return a};window.onerror=function(a,b,d,m,e){r!==a&&(a=e instanceof Error?e:Error(a),void 0===d||"lineNumber"in a||(a.lineNumber=d),void 0===b||"fileName"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,"SyntaxError"===a.name||"SyntaxError"===a.message.substring(0,11)||-1!==a.message.indexOf("Script error")?3:0));r=null;p&&q>=l&&(window.onerror=null)};})();</script></head><body bgcolor="#fff"><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var src=\'/images/nav_logo229.png\';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}\nif (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}\n}\n})();</script><div id="mngb"><div id=gbar><nobr><b class=gb1>Search</b> <a class=gb1 href="https://www.google.com/imghp?hl=en&tab=wi">Images</a> <a class=gb1 href="https://maps.google.com/maps?hl=en&tab=wl">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=w8">Play</a> <a class=gb1 href="https://www.youtube.com/?tab=w1">YouTube</a> <a class=gb1 href="https://news.google.com/?tab=wn">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=wm">Gmail</a> <a class=gb1 href="https://drive.google.com/?tab=wo">Drive</a> <a class=gb1 style="text-decoration:none" href="https://www.google.com/intl/en/about/products?tab=wh"><u>More</u> »</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="http://www.google.com/history/optout?hl=en" class=gb4>Web History</a> | <a  href="/preferences?hl=en" class=gb4>Settings</a> | <a target=_top id=gb_70 href="https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/&ec=GAZAAQ" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div></div><center><br clear="all" id="lgpd"><div id="lga"><img alt="Google" height="92" src="/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png" style="padding:28px 0 14px" width="272" id="hplogo"><br><br></div><form action="/search" name="f"><table cellpadding="0" cellspacing="0"><tr valign="top"><td width="25%"> </td><td align="center" nowrap=""><input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden"><div class="ds" style="height:32px;margin:4px 0"><input class="lst" style="margin:0;padding:5px 8px 0 6px;vertical-align:top;color:#000" autocomplete="off" value="" title="Google Search" maxlength="2048" name="q" size="57"></div><br style="line-height:0"><span class="ds"><span class="lsbb"><input class="lsb" value="Google Search" name="btnG" type="submit"></span></span><span class="ds"><span class="lsbb"><input class="lsb" id="tsuid_1" value="I\'m Feeling Lucky" name="btnI" type="submit"><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var id=\'tsuid_1\';document.getElementById(id).onclick = function(){if (this.form.q.value){this.checked = 1;if (this.form.iflsig)this.form.iflsig.disabled = false;}\nelse top.location=\'/doodles/\';};})();</script><input value="AOEireoAAAAAZFAdXGKCXWBK5dlWxPhh8hNPQz1s9YT6" name="iflsig" type="hidden"></span></span></td><td class="fl sblc" align="left" nowrap="" width="25%"><a href="/advanced_search?hl=en&authuser=0">Advanced search</a></td></tr></table><input id="gbv" name="gbv" type="hidden" value="1"><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var a,b="1";if(document&&document.getElementById)if("undefined"!=typeof XMLHttpRequest)b="2";else if("undefined"!=typeof ActiveXObject){var c,d,e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];for(c=0;d=e[c++];)try{new ActiveXObject(d),b="2"}catch(h){}}a=b;if("2"==a&&-1==location.search.indexOf("&gbv=2")){var f=google.gbvu,g=document.getElementById("gbv");g&&(g.value=a);f&&window.setTimeout(function(){location.href=f},0)};}).call(this);</script></form><div id="gac_scont"></div><div style="font-size:83%;min-height:3.5em"><br><div id="prm"><style>.szppmdbYutt__middle-slot-promo{font-size:small;margin-bottom:32px}.szppmdbYutt__middle-slot-promo a.ZIeIlb{display:inline-block;text-decoration:none}.szppmdbYutt__middle-slot-promo img{border:none;margin-right:5px;vertical-align:middle}</style><div class="szppmdbYutt__middle-slot-promo" data-ved="0ahUKEwjmj7fr6dT-AhVULUQIHThDB38QnIcBCAQ"><a class="NKcBbd" href="https://www.google.com/url?q=https://blog.google/outreach-initiatives/diversity/asian-pacific-american-heritage-month-2023/%3Futm_source%3Dhpp%26utm_medium%3Downed%26utm_campaign%3Dapahm&source=hpp&id=19035152&ct=3&usg=AOvVaw1zrN82vzhoWl4hz1zZ4gLp&sa=X&ved=0ahUKEwjmj7fr6dT-AhVULUQIHThDB38Q8IcBCAU" rel="nofollow">Celebrate Asian Pacific American Heritage Month with Google</a></div></div></div><span id="footer"><div style="font-size:10pt"><div style="margin:19px auto;text-align:center" id="WqQANb"><a href="/intl/en/ads/">Advertising</a><a href="/services/">Business Solutions</a><a href="/intl/en/about">About Google</a></div></div><p style="font-size:8pt;color:#70757a">© 2023 - <a href="/intl/en/policies/privacy/">Privacy</a> - <a href="/intl/en/policies/terms/">Terms</a></p></span></center><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){window.google.cdo={height:757,width:1440};(function(){var a=window.innerWidth,b=window.innerHeight;if(!a||!b){var c=window.document,d="CSS1Compat"==c.compatMode?c.documentElement:c.body;a=d.clientWidth;b=d.clientHeight}a&&b&&(a!=google.cdo.width||b!=google.cdo.height)&&google.log("","","/client_204?&atyp=i&biw="+a+"&bih="+b+"&ei="+google.kEI);}).call(this);})();</script> <script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){google.xjs={ck:\'xjs.hp.vUsZk7fd8do.L.X.O\',cs:\'ACT90oF8ktm8JGoaZ23megDhHoJku7YaGw\',excm:[]};})();</script>  <script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var u=\'/xjs/_/js/k\\x3dxjs.hp.en.q0lHXBfs9JY.O/am\\x3dAAAA6AQAUABgAQ/d\\x3d1/ed\\x3d1/rs\\x3dACT90oE3ek6-fjkab6CsTH0wUEUUPhnExg/m\\x3dsb_he,d\';var amd=0;\nvar e=this||self,f=function(c){return c};var h;var n=function(c,g){this.g=g===l?c:""};n.prototype.toString=function(){return this.g+""};var l={};\nfunction p(){var c=u,g=function(){};google.lx=google.stvsc?g:function(){google.timers&&google.timers.load&&google.tick&&google.tick("load","xjsls");var a=document;var b="SCRIPT";"application/xhtml+xml"===a.contentType&&(b=b.toLowerCase());b=a.createElement(b);a=null===c?"null":void 0===c?"undefined":c;if(void 0===h){var d=null;var m=e.trustedTypes;if(m&&m.createPolicy){try{d=m.createPolicy("goog#html",{createHTML:f,createScript:f,createScriptURL:f})}catch(r){e.console&&e.console.error(r.message)}h=\nd}else h=d}a=(d=h)?d.createScriptURL(a):a;a=new n(a,l);b.src=a instanceof n&&a.constructor===n?a.g:"type_error:TrustedResourceUrl";var k,q;(k=(a=null==(q=(k=(b.ownerDocument&&b.ownerDocument.defaultView||window).document).querySelector)?void 0:q.call(k,"script[nonce]"))?a.nonce||a.getAttribute("nonce")||"":"")&&b.setAttribute("nonce",k);document.body.appendChild(b);google.psa=!0;google.lx=g};google.bx||google.lx()};google.xjsu=u;e._F_jsUrl=u;setTimeout(function(){0<amd?google.caft(function(){return p()},amd):p()},0);})();window._ = window._ || {};window._DumpException = _._DumpException = function(e){throw e;};window._s = window._s || {};_s._DumpException = _._DumpException;window._qs = window._qs || {};_qs._DumpException = _._DumpException;function _F_installCss(c){}\n(function(){google.jl={blt:\'none\',chnk:0,dw:false,dwu:true,emtn:0,end:0,ico:false,ikb:0,ine:false,injs:\'none\',injt:0,injth:0,injv2:false,lls:\'default\',pdt:0,rep:0,snet:true,strt:0,ubm:false,uwp:true};})();(function(){var pmc=\'{\\x22d\\x22:{},\\x22sb_he\\x22:{\\x22agen\\x22:true,\\x22cgen\\x22:true,\\x22client\\x22:\\x22heirloom-hp\\x22,\\x22dh\\x22:true,\\x22ds\\x22:\\x22\\x22,\\x22fl\\x22:true,\\x22host\\x22:\\x22google.com\\x22,\\x22jsonp\\x22:true,\\x22msgs\\x22:{\\x22cibl\\x22:\\x22Clear Search\\x22,\\x22dym\\x22:\\x22Did you mean:\\x22,\\x22lcky\\x22:\\x22I\\\\u0026#39;m Feeling Lucky\\x22,\\x22lml\\x22:\\x22Learn more\\x22,\\x22psrc\\x22:\\x22This search was removed from your \\\\u003Ca href\\x3d\\\\\\x22/history\\\\\\x22\\\\u003EWeb History\\\\u003C/a\\\\u003E\\x22,\\x22psrl\\x22:\\x22Remove\\x22,\\x22sbit\\x22:\\x22Search by image\\x22,\\x22srch\\x22:\\x22Google Search\\x22},\\x22ovr\\x22:{},\\x22pq\\x22:\\x22\\x22,\\x22rfs\\x22:[],\\x22sbas\\x22:\\x220 3px 8px 0 rgba(0,0,0,0.2),0 0 0 1px rgba(0,0,0,0.08)\\x22,\\x22stok\\x22:\\x22C3TIBpTor6RHJfEIn2nbidnhv50\\x22}}\';google.pmc=JSON.parse(pmc);})();</script>       </body></html>'

```
PythonSceneXplain


SceneXplain# – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）SceneXplain

SceneXplain#
SceneXplain (opens in a new tab)是可通过SceneXplain工具访问的图像字幕服务。
要使用此工具，您需要创建帐户并从网站 (opens in a new tab)获取API令牌。然后您可以实例化该工具。

```code
import os
os.environ["SCENEX_API_KEY"] = "<YOUR_API_KEY>"

```

```code
from langchain.agents import load_tools

tools = load_tools(["sceneXplain"])

```

或者直接实例化该工具。

```code
from langchain.tools import SceneXplainTool

tool = SceneXplainTool()

```

在代理中的使用#
该工具可在任何LangChain代理中使用，方法如下：

```code
from langchain.llms import OpenAI
from langchain.agents import initialize_agent
from langchain.memory import ConversationBufferMemory

llm = OpenAI(temperature=0)
memory = ConversationBufferMemory(memory_key="chat_history")
agent = initialize_agent(
tools, llm, memory=memory, agent="conversational-react-description", verbose=True
)
output = agent.run(
input=(
"What is in this image https://storage.googleapis.com/causal-diffusion.appspot.com/imagePrompts%2F0rw369i5h9t%2Foriginal.png. "
"Is it movie or a game? If it is a movie, what is the name of the movie?"
)
)

print(output)

```

```code
> Entering new AgentExecutor chain...

Thought: Do I need to use a tool? Yes
Action: Image Explainer
Action Input: https://storage.googleapis.com/causal-diffusion.appspot.com/imagePrompts%2F0rw369i5h9t%2Foriginal.png
Observation: In a charmingly whimsical scene, a young girl is seen braving the rain alongside her furry companion, the lovable Totoro. The two are depicted standing on a bustling street corner, where they are sheltered from the rain by a bright yellow umbrella. The girl, dressed in a cheerful yellow frock, holds onto the umbrella with both hands while gazing up at Totoro with an expression of wonder and delight.

Totoro, meanwhile, stands tall and proud beside his young friend, holding his own umbrella aloft to protect them both from the downpour. His furry body is rendered in rich shades of grey and white, while his large ears and wide eyes lend him an endearing charm.

In the background of the scene, a street sign can be seen jutting out from the pavement amidst a flurry of raindrops. A sign with Chinese characters adorns its surface, adding to the sense of cultural diversity and intrigue. Despite the dreary weather, there is an undeniable sense of joy and camaraderie in this heartwarming image.
Thought: Do I need to use a tool? No
AI: This image appears to be a still from the 1988 Japanese animated fantasy film My Neighbor Totoro. The film follows two young girls, Satsuki and Mei, as they explore the countryside and befriend the magical forest spirits, including the titular character Totoro.

> Finished chain.
This image appears to be a still from the 1988 Japanese animated fantasy film My Neighbor Totoro. The film follows two young girls, Satsuki and Mei, as they explore the countryside and befriend the magical forest spirits, including the titular character Totoro.

```
Requests搜索工具（Search Tools）


搜索工具 – LangChain中文网

6大核心模块（Modules)代理（Agents)工具（Tools）示例（Examples）搜索工具（Search Tools）

搜索工具
本教程展示了各种搜索工具的使用方法。

```code
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI

```

```code
llm = OpenAI(temperature=0)

```

Google Serper API Wrapper#
First, let’s try to use the Google Serper API tool.

```code
tools = load_tools(["google-serper"], llm=llm)

```

```code
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

```

```code
agent.run("What is the weather in Pomfret?")

```

```code
> 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.

```

```code
'The current temperature in Pomfret is 37°F.'

```

SerpAPI#
Now, let’s use the SerpAPI tool.

```code
tools = load_tools(["serpapi"], llm=llm)

```

```code
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

```

```code
agent.run("What is the weather in Pomfret?")

```

```code
> Entering new AgentExecutor chain...
I need to find out what the current weather is 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.

```

```code
'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.

```code
tools = load_tools(["google-search"], llm=llm)

```

```code
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

```

```code
agent.run("What is the weather in Pomfret?")

```

```code
> Entering new AgentExecutor chain...
I should look up the current weather conditions.
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.
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.

```

```code
'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.

```code
tools = load_tools(["searx-search"], searx_host="http://localhost:8888", llm=llm)

```

```code
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

```

```code
agent.run("What is the weather in Pomfret")

```

```code
> 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.

```

```code
'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%.'

```
SceneXplainSearx 搜索（Searx Search）