Skip to main content
本笔记本介绍如何使用 SerpApi 组件搜索网络。 此处注册 SerpApi 账号,每月可获得 250 次免费搜索。注册后,您可以在控制台找到您的 API 密钥。 然后在 .env 文件中将环境变量 SERPAPI_API_KEY 设置为您的 API 密钥。
import os
os.environ["SERPAPI_API_KEY"] = SERPAPI_API_KEY
from langchain_community.utilities import SerpAPIWrapper
search = SerpAPIWrapper()
search.run("Obama's first name?")
'Barack Hussein Obama II'

自定义参数

您也可以使用任意参数自定义 SerpAPI 封装器。例如,在下面的示例中,我们将使用 bing 代替 google
params = {
    "engine": "bing",
    "gl": "us",
    "hl": "en",
}
search = SerpAPIWrapper(params=params)
search.run("Obama's first name?")
'Barack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American presi…New content will be added above the current area of focus upon selectionBarack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American president of the United States. He previously served as a U.S. senator from Illinois from 2005 to 2008 and as an Illinois state senator from 1997 to 2004, and previously worked as a civil rights lawyer before entering politics.Wikipediabarackobama.com'
from langchain.tools import tool

# You can create the tool to pass to an agent
@tool
def web_search(query: str) -> str:
    """Search the web for information."""
    return search.run(query)