mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-06 18:05:25 +03:00
Adds Google Search integration with [Serper](https://serper.dev) a low-cost alternative to SerpAPI (10x cheaper + generous free tier). Includes documentation, tests and examples. Hopefully I am not missing anything. Developers can sign up for a free account at [serper.dev](https://serper.dev) and obtain an api key. ## Usage ```python from langchain.utilities import GoogleSerperAPIWrapper from langchain.llms.openai import OpenAI from langchain.agents import initialize_agent, Tool 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 ) ] self_ask_with_search = initialize_agent(tools, llm, agent="self-ask-with-search", verbose=True) self_ask_with_search.run("What is the hometown of the reigning men's U.S. Open champion?") ``` ### Output ``` 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' ```
3.6 KiB
3.6 KiB
In [ ]:
import os
os.environ["SERPER_API_KEY"] = ""In [2]:
from langchain.utilities import GoogleSerperAPIWrapperIn [3]:
search = GoogleSerperAPIWrapper()In [4]:
search.run("Obama's first name?")Out [4]:
'Barack Hussein Obama II'
In [ ]:
os.environ['OPENAI_API_KEY'] = ""In [5]:
from langchain.utilities import GoogleSerperAPIWrapper
from langchain.llms.openai import OpenAI
from langchain.agents import initialize_agent, Tool
llm = OpenAI(temperature=0)
search = GoogleSerperAPIWrapper()
tools = [
Tool(
name="Intermediate Answer",
func=search.run
)
]
self_ask_with_search = initialize_agent(tools, llm, agent="self-ask-with-search", verbose=True)
self_ask_with_search.run("What is the hometown of the reigning men's U.S. Open champion?")Out [5]:
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m Yes. Follow up: Who is the reigning men's U.S. Open champion?[0m Intermediate answer: [36;1m[1;3mCurrent champions Carlos Alcaraz, 2022 men's singles champion.[0m [32;1m[1;3mFollow up: Where is Carlos Alcaraz from?[0m Intermediate answer: [36;1m[1;3mEl Palmar, Spain[0m [32;1m[1;3mSo the final answer is: El Palmar, Spain[0m [1m> Finished chain.[0m
'El Palmar, Spain'