SearchApi
本页面介绍如何在LangChain中使用SearchApi Google搜索API。SearchApi是一个实时SERP API,用于轻松抓取SERP。
设置
- 前往 https://www.searchapi.io/ 注册一个免费账户
- 获取API密钥并将其设置为环境变量 (
SEARCHAPI_API_KEY
)
包装器
实用工具
有一个SearchApiAPIWrapper工具,它封装了这个API。要导入这个工具:
from langchain_community.utilities import SearchApiAPIWrapper
API Reference:SearchApiAPIWrapper
您可以将其用作自我询问链的一部分:
from langchain_community.utilities import SearchApiAPIWrapper
from langchain_openai import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
import os
os.environ["SEARCHAPI_API_KEY"] = ""
os.environ['OPENAI_API_KEY'] = ""
llm = OpenAI(temperature=0)
search = SearchApiAPIWrapper()
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("Who lived longer: Plato, Socrates, or Aristotle?")
输出
> Entering new AgentExecutor chain...
Yes.
Follow up: How old was Plato when he died?
Intermediate answer: eighty
Follow up: How old was Socrates when he died?
Intermediate answer: | Socrates |
| -------- |
| Born | c. 470 BC Deme Alopece, Athens |
| Died | 399 BC (aged approximately 71) Athens |
| Cause of death | Execution by forced suicide by poisoning |
| Spouse(s) | Xanthippe, Myrto |
Follow up: How old was Aristotle when he died?
Intermediate answer: 62 years
So the final answer is: Plato
> Finished chain.
'Plato'
工具
你也可以轻松地将这个包装器作为工具加载(与代理一起使用)。 你可以这样做:
from langchain.agents import load_tools
tools = load_tools(["searchapi"])
API Reference:load_tools
有关工具的更多信息,请参见此页面。