Skip to main content
Open on GitHub

Serper - Google 搜索 API

本页面介绍了如何在LangChain中使用Serper Google搜索API。Serper是一个低成本的Google搜索API,可用于从Google搜索中添加答案框、知识图谱和自然搜索结果数据。 它分为两部分:设置,然后是对特定Google Serper包装器的引用。

设置

  • 前往 serper.dev 注册一个免费账户
  • 获取API密钥并将其设置为环境变量 (SERPER_API_KEY)

包装器

实用工具

存在一个GoogleSerperAPIWrapper工具,它封装了这个API。要导入这个工具:

from langchain_community.utilities import GoogleSerperAPIWrapper

您可以将其用作自我询问链的一部分:

from langchain_community.utilities import GoogleSerperAPIWrapper
from langchain_openai import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType

import os

os.environ["SERPER_API_KEY"] = ""
os.environ['OPENAI_API_KEY'] = ""

llm = OpenAI(temperature=0)
search = GoogleSerperAPIWrapper()
tools = [
Tool(
name="Intermediate Answer",
func=search.run,
description="useful for when you need to ask with search"
)
]

self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True)
self_ask_with_search.run("What is the hometown of the reigning men's U.S. Open champion?")

输出

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

> Finished chain.

'El Palmar, Spain'

有关此包装器的更详细演练,请参阅此笔记本

工具

你也可以轻松地将这个包装器作为工具加载(与代理一起使用)。 你可以这样做:

from langchain.agents import load_tools
tools = load_tools(["google-serper"])
API Reference:load_tools

有关工具的更多信息,请参见此页面


这个页面有帮助吗?