google-serper: async + full json results + support for Google Images, Places and News (#4078)

* implemented arun, results, and aresults. Reuses aiosession if
available.
* helper tools GoogleSerperRun and GoogleSerperResults
* support for Google Images, Places and News (examples given) and
filtering based on time (e.g. past hour)
* updated docs
fix_agent_callbacks
rogerserper 1 year ago committed by GitHub
parent cdea47491d
commit b1446bea5f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -9,9 +9,9 @@
"\n",
"LangChain provides async support for Agents by leveraging the [asyncio](https://docs.python.org/3/library/asyncio.html) library.\n",
"\n",
"Async methods are currently supported for the following `Tools`: [`SerpAPIWrapper`](https://github.com/hwchase17/langchain/blob/master/langchain/serpapi.py) and [`LLMMathChain`](https://github.com/hwchase17/langchain/blob/master/langchain/chains/llm_math/base.py). Async support for other agent tools are on the roadmap.\n",
"Async methods are currently supported for the following `Tools`: [`GoogleSerperAPIWrapper`](https://github.com/hwchase17/langchain/blob/master/langchain/utilities/google_serper.py), [`SerpAPIWrapper`](https://github.com/hwchase17/langchain/blob/master/langchain/serpapi.py) and [`LLMMathChain`](https://github.com/hwchase17/langchain/blob/master/langchain/chains/llm_math/base.py). Async support for other agent tools are on the roadmap.\n",
"\n",
"For `Tool`s that have a `coroutine` implemented (the two mentioned above), the `AgentExecutor` will `await` them directly. Otherwise, the `AgentExecutor` will call the `Tool`'s `func` via `asyncio.get_event_loop().run_in_executor` to avoid blocking the main runloop.\n",
"For `Tool`s that have a `coroutine` implemented (the three mentioned above), the `AgentExecutor` will `await` them directly. Otherwise, the `AgentExecutor` will call the `Tool`'s `func` via `asyncio.get_event_loop().run_in_executor` to avoid blocking the main runloop.\n",
"\n",
"You can use `arun` to call an `AgentExecutor` asynchronously."
]
@ -28,10 +28,14 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 5,
"id": "da5df06c-af6f-4572-b9f5-0ab971c16487",
"metadata": {
"tags": []
"tags": [],
"ExecuteTime": {
"end_time": "2023-05-04T01:27:22.755025Z",
"start_time": "2023-05-04T01:27:22.754041Z"
}
},
"outputs": [],
"source": [
@ -56,10 +60,14 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 3,
"id": "fd4c294e-b1d6-44b8-b32e-2765c017e503",
"metadata": {
"tags": []
"tags": [],
"ExecuteTime": {
"end_time": "2023-05-04T01:15:35.466212Z",
"start_time": "2023-05-04T01:14:05.452245Z"
}
},
"outputs": [
{
@ -68,106 +76,98 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Search\n",
"Action Input: \"US Open men's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mRafael Nadal defeated Daniil Medvedev in the final, 75, 63, 57, 46, 64 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out the age of the winner\n",
"Action: Search\n",
"Action Input: \"Rafael Nadal age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m36 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now need to calculate his age raised to the 0.334 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who won the US Open men's final in 2019?\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mRafael Nadal defeated Daniil Medvedev in the final, 75, 63, 57, 46, 64 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 75, 63, 57, 46, 64. Bianca Andreescu won the women's singles title, defeating Serena Williams in straight sets in the final, becoming the first Canadian to win a Grand Slam singles ... Rafael Nadal won his 19th career Grand Slam title, and his fourth US Open crown, by surviving an all-time comback effort from Daniil ... Rafael Nadal beats Daniil Medvedev in US Open final to claim 19th major title. World No2 claims 7-5, 6-3, 5-7, 4-6, 6-4 victory over Russian ... Rafael Nadal defeated Daniil Medvedev in the men's singles final of the U.S. Open on Sunday. Rafael Nadal survived. The 33-year-old defeated Daniil Medvedev in the final of the 2019 U.S. Open to earn his 19th Grand Slam title Sunday ... NEW YORK -- Rafael Nadal defeated Daniil Medvedev in an epic five-set match, 7-5, 6-3, 5-7, 4-6, 6-4 to win the men's singles title at the ... Nadal previously won the U.S. Open three times, most recently in 2017. Ahead of the match, Nadal said he was “super happy to be back in the ... Watch the full match between Daniil Medvedev and Rafael ... Duration: 4:47:32. Posted: Mar 20, 2020. US Open 2019: Rafael Nadal beats Daniil Medvedev · Updated: Sep. 08, 2019, 11:11 p.m. |; Published: Sep · Published: Sep. 08, 2019, 10:06 p.m.. 26. US Open ...\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know that Rafael Nadal won the US Open men's final in 2019 and he is 33 years old.\n",
"Action: Calculator\n",
"Action Input: 36^0.334\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 3.3098250249682484\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484.\u001b[0m\n",
"Action Input: 33^0.334\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 3.215019829667466\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer.\n",
"Final Answer: Rafael Nadal won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.215019829667466.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mOlivia Wilde started dating Harry Styles after ending her years-long engagement to Jason Sudeikis — see their relationship timeline.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Harry Styles' age.\n",
"Action: Search\n",
"Action Input: \"Harry Styles age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m29 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 29 raised to the 0.23 power.\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mSudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Harry Styles' age.\n",
"Action: Google Serper\n",
"Action Input: \"Harry Styles age\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m29 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 29 raised to the 0.23 power.\n",
"Action: Calculator\n",
"Action Input: 29^0.23\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.169459462491557\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: Harry Styles, Olivia Wilde's boyfriend, is 29 years old and his age raised to the 0.23 power is 2.169459462491557.\u001b[0m\n",
"Action Input: 29^0.23\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.169459462491557\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer.\n",
"Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Formula 1 Grand Prix Winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mMichael Schumacher (top left) and Lewis Hamilton (top right) have each won the championship a record seven times during their careers, while Sebastian Vettel ( ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out the age of the winner\n",
"Action: Search\n",
"Action Input: \"Michael Schumacher age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m54 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate the age raised to the 0.23 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who won the most recent grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"who won the most recent formula 1 grand prix\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mMax Verstappen won his first Formula 1 world title on Sunday after the championship was decided by a last-lap overtake of his rival Lewis Hamilton in the Abu Dhabi Grand Prix. Dec 12, 2021\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Max Verstappen's age\n",
"Action: Google Serper\n",
"Action Input: \"Max Verstappen age\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m25 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 25 raised to the 0.23 power\n",
"Action: Calculator\n",
"Action Input: 54^0.23\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.502940725307012\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Michael Schumacher, aged 54, raised to the 0.23 power is 2.502940725307012.\u001b[0m\n",
"Action Input: 25^0.23\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.096651272316035\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer\n",
"Final Answer: Max Verstappen, aged 25, won the most recent Formula 1 grand prix and his age raised to the 0.23 power is 2.096651272316035.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Search\n",
"Action Input: \"US Open women's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mBianca Andreescu\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out her age\n",
"Action: Search\n",
"Action Input: \"Bianca Andreescu age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m22 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate her age raised to the 0.34 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Google Serper\n",
"Action Input: \"US Open women's final 2019 winner\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mWHAT HAPPENED: #SheTheNorth? She the champion. Nineteen-year-old Canadian Bianca Andreescu sealed her first Grand Slam title on Saturday, downing 23-time major champion Serena Williams in the 2019 US Open women's singles final, 6-3, 7-5. Sep 7, 2019\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now need to calculate her age raised to the 0.34 power.\n",
"Action: Calculator\n",
"Action Input: 22^0.34\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.8603798598506933\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Bianca Andreescu, aged 22, won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.86.\u001b[0m\n",
"Action Input: 19^0.34\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.7212987634680084\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer.\n",
"Final Answer: Nineteen-year-old Canadian Bianca Andreescu won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.7212987634680084.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Search\n",
"Action Input: \"Who is Beyonce's husband?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mJay-Z\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Jay-Z's age\n",
"Action: Search\n",
"Action Input: \"How old is Jay-Z?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m53 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 53 raised to the 0.19 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who is Beyonce's husband?\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mJay-Z\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Jay-Z's age\n",
"Action: Google Serper\n",
"Action Input: \"How old is Jay-Z?\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m53 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 53 raised to the 0.19 power\n",
"Action: Calculator\n",
"Action Input: 53^0.19\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.12624064206896\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896.\u001b[0m\n",
"Action Input: 53^0.19\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.12624064206896\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer\n",
"Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Serial executed in 52.47 seconds.\n"
"\u001B[1m> Finished chain.\u001B[0m\n",
"Serial executed in 89.97 seconds.\n"
]
}
],
"source": [
"llm = OpenAI(temperature=0)\n",
"tools = load_tools([\"llm-math\", \"serpapi\"], llm=llm)\n",
"tools = load_tools([\"google-serper\", \"llm-math\"], llm=llm)\n",
"agent = initialize_agent(\n",
" tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True\n",
")\n",
@ -181,10 +181,14 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 4,
"id": "076d7b85-45ec-465d-8b31-c2ad119c3438",
"metadata": {
"tags": []
"tags": [],
"ExecuteTime": {
"end_time": "2023-05-04T01:26:59.737657Z",
"start_time": "2023-05-04T01:26:42.182078Z"
}
},
"outputs": [
{
@ -193,96 +197,84 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Search\n",
"Action Input: \"US Open women's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mBianca Andreescu\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Search\n",
"Action Input: \"US Open men's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mRafael Nadal defeated Daniil Medvedev in the final, 75, 63, 57, 46, 64 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out who won the grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Formula 1 Grand Prix Winner\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Search\n",
"Action Input: \"Who is Beyonce's husband?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mOlivia Wilde started dating Harry Styles after ending her years-long engagement to Jason Sudeikis — see their relationship timeline.\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who is Beyonce's husband?\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who won the most recent formula 1 grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"most recent formula 1 grand prix winner\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who won the US Open men's final in 2019?\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Google Serper\n",
"Action Input: \"US Open women's final 2019 winner\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mSudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[33;1m\u001b[1;3mJay-Z\u001b[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mJay-Z\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[33;1m\u001b[1;3mMichael Schumacher (top left) and Lewis Hamilton (top right) have each won the championship a record seven times during their careers, while Sebastian Vettel ( ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out her age\n",
"Action: Search\n",
"Action Input: \"Bianca Andreescu age\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out Jay-Z's age\n",
"Action: Search\n",
"Action Input: \"How old is Jay-Z?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m53 years\u001b[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mRafael Nadal defeated Daniil Medvedev in the final, 75, 63, 57, 46, 64 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 75, 63, 57, 46, 64. Bianca Andreescu won the women's singles title, defeating Serena Williams in straight sets in the final, becoming the first Canadian to win a Grand Slam singles ... Rafael Nadal won his 19th career Grand Slam title, and his fourth US Open crown, by surviving an all-time comback effort from Daniil ... Rafael Nadal beats Daniil Medvedev in US Open final to claim 19th major title. World No2 claims 7-5, 6-3, 5-7, 4-6, 6-4 victory over Russian ... Rafael Nadal defeated Daniil Medvedev in the men's singles final of the U.S. Open on Sunday. Rafael Nadal survived. The 33-year-old defeated Daniil Medvedev in the final of the 2019 U.S. Open to earn his 19th Grand Slam title Sunday ... NEW YORK -- Rafael Nadal defeated Daniil Medvedev in an epic five-set match, 7-5, 6-3, 5-7, 4-6, 6-4 to win the men's singles title at the ... Nadal previously won the U.S. Open three times, most recently in 2017. Ahead of the match, Nadal said he was “super happy to be back in the ... Watch the full match between Daniil Medvedev and Rafael ... Duration: 4:47:32. Posted: Mar 20, 2020. US Open 2019: Rafael Nadal beats Daniil Medvedev · Updated: Sep. 08, 2019, 11:11 p.m. |; Published: Sep · Published: Sep. 08, 2019, 10:06 p.m.. 26. US Open ...\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[33;1m\u001b[1;3m22 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Harry Styles' age.\n",
"Action: Search\n",
"Action Input: \"Harry Styles age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m29 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate her age raised to the 0.34 power\n",
"Action: Calculator\n",
"Action Input: 22^0.34\u001b[0m\u001b[32;1m\u001b[1;3m I need to calculate 53 raised to the 0.19 power\n",
"Observation: \u001B[36;1m\u001B[1;3mWHAT HAPPENED: #SheTheNorth? She the champion. Nineteen-year-old Canadian Bianca Andreescu sealed her first Grand Slam title on Saturday, downing 23-time major champion Serena Williams in the 2019 US Open women's singles final, 6-3, 7-5. Sep 7, 2019\u001B[0m\n",
"Thought:\n",
"Observation: \u001B[36;1m\u001B[1;3mLewis Hamilton holds the record for the most race wins in Formula One history, with 103 wins to date. Michael Schumacher, the previous record holder, ... Michael Schumacher (top left) and Lewis Hamilton (top right) have each won the championship a record seven times during their careers, while Sebastian Vettel ( ... Grand Prix, Date, Winner, Car, Laps, Time. Bahrain, 05 Mar 2023, Max Verstappen VER, Red Bull Racing Honda RBPT, 57, 1:33:56.736. Saudi Arabia, 19 Mar 2023 ... The Red Bull driver Max Verstappen of the Netherlands celebrated winning his first Formula 1 world title at the Abu Dhabi Grand Prix. Perez wins sprint as Verstappen, Russell clash. Red Bull's Sergio Perez won the first sprint of the 2023 Formula One season after catching and passing Charles ... The most successful driver in the history of F1 is Lewis Hamilton. The man from Stevenage has won 103 Grands Prix throughout his illustrious career and is still ... Lewis Hamilton: 103. Max Verstappen: 37. Michael Schumacher: 91. Fernando Alonso: 32. Max Verstappen and Sergio Perez will race in a very different-looking Red Bull this weekend after the team unveiled a striking special livery for the Miami GP. Lewis Hamilton holds the record of most victories with 103, ahead of Michael Schumacher (91) and Sebastian Vettel (53). Schumacher also holds the record for the ... Lewis Hamilton holds the record for the most race wins in Formula One history, with 103 wins to date. Michael Schumacher, the previous record holder, is second ...\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Harry Styles' age.\n",
"Action: Google Serper\n",
"Action Input: \"Harry Styles age\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out Jay-Z's age\n",
"Action: Google Serper\n",
"Action Input: \"How old is Jay-Z?\"\u001B[0m\u001B[32;1m\u001B[1;3m I now know that Rafael Nadal won the US Open men's final in 2019 and he is 33 years old.\n",
"Action: Calculator\n",
"Action Input: 53^0.19\u001b[0m\u001b[32;1m\u001b[1;3m I need to calculate 29 raised to the 0.23 power.\n",
"Action Input: 33^0.334\u001B[0m\u001B[32;1m\u001B[1;3m I now need to calculate her age raised to the 0.34 power.\n",
"Action: Calculator\n",
"Action Input: 29^0.23\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out the age of the winner\n",
"Action: Search\n",
"Action Input: \"Rafael Nadal age\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out the age of the winner\n",
"Action: Search\n",
"Action Input: \"Michael Schumacher age\"\u001b[0m\n",
"Observation: \n",
"Observation: \u001b[33;1m\u001b[1;3m36 years\u001b[0m\n",
"Thought:\u001b[33;1m\u001b[1;3m54 years\u001b[0m\n",
"Thought:\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.8603798598506933\u001b[0m\n",
"Action Input: 19^0.34\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m29 years\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.169459462491557\u001b[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m53 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m Max Verstappen won the most recent Formula 1 grand prix.\n",
"Action: Calculator\n",
"Action Input: Max Verstappen's age (23) raised to the 0.23 power\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.7212987634680084\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.12624064206896\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate the age raised to the 0.334 power\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 3.215019829667466\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 29 raised to the 0.23 power.\n",
"Action: Calculator\n",
"Action Input: 36^0.334\u001b[0m\u001b[32;1m\u001b[1;3m I now need to calculate the age raised to the 0.23 power\n",
"Action Input: 29^0.23\u001B[0m\u001B[32;1m\u001B[1;3m I need to calculate 53 raised to the 0.19 power\n",
"Action: Calculator\n",
"Action Input: 54^0.23\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Action Input: 53^0.19\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.0568252837687546\u001B[0m\n",
"Thought:\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.169459462491557\u001B[0m\n",
"Thought:\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 3.3098250249682484\u001b[0m\n",
"Thought:\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.502940725307012\u001b[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.12624064206896\u001B[0m\n",
"Thought:\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Concurrent executed in 14.49 seconds.\n"
"\u001B[1m> Finished chain.\u001B[0m\n",
"Concurrent executed in 17.52 seconds.\n"
]
}
],
"source": [
"llm = OpenAI(temperature=0)\n",
"tools = load_tools([\"llm-math\", \"serpapi\"], llm=llm)\n",
"tools = load_tools([\"google-serper\",\"llm-math\"], llm=llm)\n",
"agent = initialize_agent(\n",
" tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True\n",
")\n",

@ -12,21 +12,34 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 11,
"outputs": [],
"source": [
"import os\n",
"import pprint\n",
"os.environ[\"SERPER_API_KEY\"] = \"\""
],
"metadata": {
"collapsed": false
"collapsed": false,
"pycharm": {
"is_executing": true
},
"ExecuteTime": {
"end_time": "2023-05-04T00:56:29.336521Z",
"start_time": "2023-05-04T00:56:29.334173Z"
}
}
},
{
"cell_type": "code",
"execution_count": 2,
"id": "54bf5afd",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-04T00:54:07.676293Z",
"start_time": "2023-05-04T00:54:06.665742Z"
}
},
"outputs": [],
"source": [
"from langchain.utilities import GoogleSerperAPIWrapper"
@ -36,7 +49,12 @@
"cell_type": "code",
"execution_count": 3,
"id": "31f8f382",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-04T00:54:08.324245Z",
"start_time": "2023-05-04T00:54:08.321577Z"
}
},
"outputs": [],
"source": [
"search = GoogleSerperAPIWrapper()"
@ -46,7 +64,12 @@
"cell_type": "code",
"execution_count": 4,
"id": "25ce0225",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-04T00:54:11.399847Z",
"start_time": "2023-05-04T00:54:09.335597Z"
}
},
"outputs": [
{
"data": {
@ -72,13 +95,17 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 5,
"outputs": [],
"source": [
"os.environ['OPENAI_API_KEY'] = \"\""
],
"metadata": {
"collapsed": false
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:14.311773Z",
"start_time": "2023-05-04T00:54:14.304389Z"
}
}
},
{
@ -133,6 +160,693 @@
"metadata": {
"collapsed": false
}
},
{
"cell_type": "markdown",
"source": [
"## Obtaining results with metadata\n",
"If you would also like to obtain the results in a structured way including metadata. For this we will be using the `results` method of the wrapper."
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 6,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Apple Inc.',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'search'},\n",
" 'knowledgeGraph': {'title': 'Apple',\n",
" 'type': 'Technology company',\n",
" 'website': 'http://www.apple.com/',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwGQRv5TjjkycpctY66mOg_e2-npacrmjAb6_jAWhzlzkFE3OTjxyzbA&s=0',\n",
" 'description': 'Apple Inc. is an American multinational '\n",
" 'technology company headquartered in '\n",
" 'Cupertino, California. Apple is the '\n",
" \"world's largest technology company by \"\n",
" 'revenue, with US$394.3 billion in 2022 '\n",
" 'revenue. As of March 2023, Apple is the '\n",
" \"world's biggest...\",\n",
" 'descriptionSource': 'Wikipedia',\n",
" 'descriptionLink': 'https://en.wikipedia.org/wiki/Apple_Inc.',\n",
" 'attributes': {'Customer service': '1 (800) 275-2273',\n",
" 'CEO': 'Tim Cook (Aug 24, 2011)',\n",
" 'Headquarters': 'Cupertino, CA',\n",
" 'Founded': 'April 1, 1976, Los Altos, CA',\n",
" 'Founders': 'Steve Jobs, Steve Wozniak, '\n",
" 'Ronald Wayne, and more',\n",
" 'Products': 'iPhone, iPad, Apple TV, and '\n",
" 'more'}},\n",
" 'organic': [{'title': 'Apple',\n",
" 'link': 'https://www.apple.com/',\n",
" 'snippet': 'Discover the innovative world of Apple and shop '\n",
" 'everything iPhone, iPad, Apple Watch, Mac, and Apple '\n",
" 'TV, plus explore accessories, entertainment, ...',\n",
" 'sitelinks': [{'title': 'Support',\n",
" 'link': 'https://support.apple.com/'},\n",
" {'title': 'iPhone',\n",
" 'link': 'https://www.apple.com/iphone/'},\n",
" {'title': 'Site Map',\n",
" 'link': 'https://www.apple.com/sitemap/'},\n",
" {'title': 'Business',\n",
" 'link': 'https://www.apple.com/business/'},\n",
" {'title': 'Mac',\n",
" 'link': 'https://www.apple.com/mac/'},\n",
" {'title': 'Watch',\n",
" 'link': 'https://www.apple.com/watch/'}],\n",
" 'position': 1},\n",
" {'title': 'Apple Inc. - Wikipedia',\n",
" 'link': 'https://en.wikipedia.org/wiki/Apple_Inc.',\n",
" 'snippet': 'Apple Inc. is an American multinational technology '\n",
" 'company headquartered in Cupertino, California. '\n",
" \"Apple is the world's largest technology company by \"\n",
" 'revenue, ...',\n",
" 'attributes': {'Products': 'AirPods; Apple Watch; iPad; iPhone; '\n",
" 'Mac; Full list',\n",
" 'Founders': 'Steve Jobs; Steve Wozniak; Ronald '\n",
" 'Wayne; Mike Markkula'},\n",
" 'sitelinks': [{'title': 'History',\n",
" 'link': 'https://en.wikipedia.org/wiki/History_of_Apple_Inc.'},\n",
" {'title': 'Timeline of Apple Inc. products',\n",
" 'link': 'https://en.wikipedia.org/wiki/Timeline_of_Apple_Inc._products'},\n",
" {'title': 'Litigation involving Apple Inc.',\n",
" 'link': 'https://en.wikipedia.org/wiki/Litigation_involving_Apple_Inc.'},\n",
" {'title': 'Apple Store',\n",
" 'link': 'https://en.wikipedia.org/wiki/Apple_Store'}],\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvmB5fT1LjqpZx02UM7IJq0Buoqt0DZs_y0dqwxwSWyP4PIN9FaxuTea0&s',\n",
" 'position': 2},\n",
" {'title': 'Apple Inc. | History, Products, Headquarters, & Facts '\n",
" '| Britannica',\n",
" 'link': 'https://www.britannica.com/topic/Apple-Inc',\n",
" 'snippet': 'Apple Inc., formerly Apple Computer, Inc., American '\n",
" 'manufacturer of personal computers, smartphones, '\n",
" 'tablet computers, computer peripherals, and computer '\n",
" '...',\n",
" 'attributes': {'Related People': 'Steve Jobs Steve Wozniak Jony '\n",
" 'Ive Tim Cook Angela Ahrendts',\n",
" 'Date': '1976 - present'},\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3liELlhrMz3Wpsox29U8jJ3L8qETR0hBWHXbFnwjwQc34zwZvFELst2E&s',\n",
" 'position': 3},\n",
" {'title': 'AAPL: Apple Inc Stock Price Quote - NASDAQ GS - '\n",
" 'Bloomberg.com',\n",
" 'link': 'https://www.bloomberg.com/quote/AAPL:US',\n",
" 'snippet': 'AAPL:USNASDAQ GS. Apple Inc. COMPANY INFO ; Open. '\n",
" '170.09 ; Prev Close. 169.59 ; Volume. 48,425,696 ; '\n",
" 'Market Cap. 2.667T ; Day Range. 167.54170.35.',\n",
" 'position': 4},\n",
" {'title': 'Apple Inc. (AAPL) Company Profile & Facts - Yahoo '\n",
" 'Finance',\n",
" 'link': 'https://finance.yahoo.com/quote/AAPL/profile/',\n",
" 'snippet': 'Apple Inc. designs, manufactures, and markets '\n",
" 'smartphones, personal computers, tablets, wearables, '\n",
" 'and accessories worldwide. The company offers '\n",
" 'iPhone, a line ...',\n",
" 'position': 5},\n",
" {'title': 'Apple Inc. (AAPL) Stock Price, News, Quote & History - '\n",
" 'Yahoo Finance',\n",
" 'link': 'https://finance.yahoo.com/quote/AAPL',\n",
" 'snippet': 'Find the latest Apple Inc. (AAPL) stock quote, '\n",
" 'history, news and other vital information to help '\n",
" 'you with your stock trading and investing.',\n",
" 'position': 6}],\n",
" 'peopleAlsoAsk': [{'question': 'What does Apple Inc do?',\n",
" 'snippet': 'Apple Inc. (Apple) designs, manufactures and '\n",
" 'markets smartphones, personal\\n'\n",
" 'computers, tablets, wearables and accessories '\n",
" 'and sells a range of related\\n'\n",
" 'services.',\n",
" 'title': 'AAPL.O - | Stock Price & Latest News - Reuters',\n",
" 'link': 'https://www.reuters.com/markets/companies/AAPL.O/'},\n",
" {'question': 'What is the full form of Apple Inc?',\n",
" 'snippet': '(formerly Apple Computer Inc.) is an American '\n",
" 'computer and consumer electronics\\n'\n",
" 'company famous for creating the iPhone, iPad '\n",
" 'and Macintosh computers.',\n",
" 'title': 'What is Apple? An products and history overview '\n",
" '- TechTarget',\n",
" 'link': 'https://www.techtarget.com/whatis/definition/Apple'},\n",
" {'question': 'What is Apple Inc iPhone?',\n",
" 'snippet': 'Apple Inc (Apple) designs, manufactures, and '\n",
" 'markets smartphones, tablets,\\n'\n",
" 'personal computers, and wearable devices. The '\n",
" 'company also offers software\\n'\n",
" 'applications and related services, '\n",
" 'accessories, and third-party digital content.\\n'\n",
" \"Apple's product portfolio includes iPhone, \"\n",
" 'iPad, Mac, iPod, Apple Watch, and\\n'\n",
" 'Apple TV.',\n",
" 'title': 'Apple Inc Company Profile - Apple Inc Overview - '\n",
" 'GlobalData',\n",
" 'link': 'https://www.globaldata.com/company-profile/apple-inc/'},\n",
" {'question': 'Who runs Apple Inc?',\n",
" 'snippet': 'Timothy Donald Cook (born November 1, 1960) is '\n",
" 'an American business executive\\n'\n",
" 'who has been the chief executive officer of '\n",
" 'Apple Inc. since 2011. Cook\\n'\n",
" \"previously served as the company's chief \"\n",
" 'operating officer under its co-founder\\n'\n",
" 'Steve Jobs. He is the first CEO of any Fortune '\n",
" '500 company who is openly gay.',\n",
" 'title': 'Tim Cook - Wikipedia',\n",
" 'link': 'https://en.wikipedia.org/wiki/Tim_Cook'}],\n",
" 'relatedSearches': [{'query': 'Who invented the iPhone'},\n",
" {'query': 'Apple iPhone'},\n",
" {'query': 'History of Apple company PDF'},\n",
" {'query': 'Apple company history'},\n",
" {'query': 'Apple company introduction'},\n",
" {'query': 'Apple India'},\n",
" {'query': 'What does Apple Inc own'},\n",
" {'query': 'Apple Inc After Steve'},\n",
" {'query': 'Apple Watch'},\n",
" {'query': 'Apple App Store'}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper()\n",
"results = search.results(\"Apple Inc.\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"is_executing": true
},
"ExecuteTime": {
"end_time": "2023-05-04T00:54:22.863413Z",
"start_time": "2023-05-04T00:54:20.827395Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Searching for Google Images\n",
"We can also query Google Images using this wrapper. For example:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 7,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Lion',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'images'},\n",
" 'images': [{'title': 'Lion - Wikipedia',\n",
" 'imageUrl': 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/1200px-Lion_waiting_in_Namibia.jpg',\n",
" 'imageWidth': 1200,\n",
" 'imageHeight': 900,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRye79ROKwjfb6017jr0iu8Bz2E1KKuHg-A4qINJaspyxkZrkw&s',\n",
" 'thumbnailWidth': 259,\n",
" 'thumbnailHeight': 194,\n",
" 'source': 'Wikipedia',\n",
" 'domain': 'en.wikipedia.org',\n",
" 'link': 'https://en.wikipedia.org/wiki/Lion',\n",
" 'position': 1},\n",
" {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica',\n",
" 'imageUrl': 'https://cdn.britannica.com/55/2155-050-604F5A4A/lion.jpg',\n",
" 'imageWidth': 754,\n",
" 'imageHeight': 752,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3fnDub1GSojI0hJ-ZGS8Tv-hkNNloXh98DOwXZoZ_nUs3GWSd&s',\n",
" 'thumbnailWidth': 225,\n",
" 'thumbnailHeight': 224,\n",
" 'source': 'Encyclopedia Britannica',\n",
" 'domain': 'www.britannica.com',\n",
" 'link': 'https://www.britannica.com/animal/lion',\n",
" 'position': 2},\n",
" {'title': 'African lion, facts and photos',\n",
" 'imageUrl': 'https://i.natgeofe.com/n/487a0d69-8202-406f-a6a0-939ed3704693/african-lion.JPG',\n",
" 'imageWidth': 3072,\n",
" 'imageHeight': 2043,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPlTarrtDbyTiEm-VI_PML9VtOTVPuDXJ5ybDf_lN11H2mShk&s',\n",
" 'thumbnailWidth': 275,\n",
" 'thumbnailHeight': 183,\n",
" 'source': 'National Geographic',\n",
" 'domain': 'www.nationalgeographic.com',\n",
" 'link': 'https://www.nationalgeographic.com/animals/mammals/facts/african-lion',\n",
" 'position': 3},\n",
" {'title': 'Saint Louis Zoo | African Lion',\n",
" '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',\n",
" 'imageWidth': 1200,\n",
" 'imageHeight': 1200,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTlewcJ5SwC7yKup6ByaOjTnAFDeoOiMxyJTQaph2W_I3dnks4&s',\n",
" 'thumbnailWidth': 225,\n",
" 'thumbnailHeight': 225,\n",
" 'source': 'St. Louis Zoo',\n",
" 'domain': 'stlzoo.org',\n",
" 'link': 'https://stlzoo.org/animals/mammals/carnivores/lion',\n",
" 'position': 4},\n",
" {'title': 'How to Draw a Realistic Lion like an Artist - Studio '\n",
" 'Wildlife',\n",
" 'imageUrl': 'https://studiowildlife.com/wp-content/uploads/2021/10/245528858_183911853822648_6669060845725210519_n.jpg',\n",
" 'imageWidth': 1431,\n",
" 'imageHeight': 2048,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmn5HayVj3wqoBDQacnUtzaDPZzYHSLKUlIEcni6VB8w0mVeA&s',\n",
" 'thumbnailWidth': 188,\n",
" 'thumbnailHeight': 269,\n",
" 'source': 'Studio Wildlife',\n",
" 'domain': 'studiowildlife.com',\n",
" 'link': 'https://studiowildlife.com/how-to-draw-a-realistic-lion-like-an-artist/',\n",
" 'position': 5},\n",
" {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica',\n",
" 'imageUrl': 'https://cdn.britannica.com/29/150929-050-547070A1/lion-Kenya-Masai-Mara-National-Reserve.jpg',\n",
" 'imageWidth': 1600,\n",
" 'imageHeight': 1085,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCqaKY_THr0IBZN8c-2VApnnbuvKmnsWjfrwKoWHFR9w3eN5o&s',\n",
" 'thumbnailWidth': 273,\n",
" 'thumbnailHeight': 185,\n",
" 'source': 'Encyclopedia Britannica',\n",
" 'domain': 'www.britannica.com',\n",
" 'link': 'https://www.britannica.com/animal/lion',\n",
" 'position': 6},\n",
" {'title': \"Where do lions live? Facts about lions' habitats and \"\n",
" 'other cool facts',\n",
" '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',\n",
" 'imageWidth': 1365,\n",
" 'imageHeight': 768,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTc_4vCHscgvFvYy3PSrtIOE81kNLAfhDK8F3mfOuotL0kUkbs&s',\n",
" 'thumbnailWidth': 299,\n",
" 'thumbnailHeight': 168,\n",
" 'source': 'USA Today',\n",
" 'domain': 'www.usatoday.com',\n",
" 'link': 'https://www.usatoday.com/story/news/2023/01/08/where-do-lions-live-habitat/10927718002/',\n",
" 'position': 7},\n",
" {'title': 'Lion',\n",
" 'imageUrl': 'https://i.natgeofe.com/k/1d33938b-3d02-4773-91e3-70b113c3b8c7/lion-male-roar_square.jpg',\n",
" 'imageWidth': 3072,\n",
" 'imageHeight': 3072,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQqLfnBrBLcTiyTZynHH3FGbBtX2bd1ScwpcuOLnksTyS9-4GM&s',\n",
" 'thumbnailWidth': 225,\n",
" 'thumbnailHeight': 225,\n",
" 'source': 'National Geographic Kids',\n",
" 'domain': 'kids.nationalgeographic.com',\n",
" 'link': 'https://kids.nationalgeographic.com/animals/mammals/facts/lion',\n",
" 'position': 8},\n",
" {'title': \"Lion | Smithsonian's National Zoo\",\n",
" 'imageUrl': 'https://nationalzoo.si.edu/sites/default/files/styles/1400_scale/public/animals/exhibit/africanlion-005.jpg?itok=6wA745g_',\n",
" 'imageWidth': 1400,\n",
" 'imageHeight': 845,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgB3z_D4dMEOWJ7lajJk4XaQSL4DdUvIRj4UXZ0YoE5fGuWuo&s',\n",
" 'thumbnailWidth': 289,\n",
" 'thumbnailHeight': 174,\n",
" 'source': \"Smithsonian's National Zoo\",\n",
" 'domain': 'nationalzoo.si.edu',\n",
" 'link': 'https://nationalzoo.si.edu/animals/lion',\n",
" 'position': 9},\n",
" {'title': \"Zoo's New Male Lion Explores Habitat for the First Time \"\n",
" '- Virginia Zoo',\n",
" 'imageUrl': 'https://virginiazoo.org/wp-content/uploads/2022/04/ZOO_0056-scaled.jpg',\n",
" 'imageWidth': 2560,\n",
" 'imageHeight': 2141,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDCG7XvXRCwpe_-Vy5mpvrQpVl5q2qwgnDklQhrJpQzObQGz4&s',\n",
" 'thumbnailWidth': 246,\n",
" 'thumbnailHeight': 205,\n",
" 'source': 'Virginia Zoo',\n",
" 'domain': 'virginiazoo.org',\n",
" 'link': 'https://virginiazoo.org/zoos-new-male-lion-explores-habitat-for-thefirst-time/',\n",
" 'position': 10}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"images\")\n",
"results = search.results(\"Lion\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:27.879867Z",
"start_time": "2023-05-04T00:54:26.380022Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Searching for Google News\n",
"We can also query Google News using this wrapper. For example:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 8,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Tesla Inc.',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'news'},\n",
" 'news': [{'title': 'ISS recommends Tesla investors vote against re-election '\n",
" 'of Robyn Denholm',\n",
" 'link': 'https://www.reuters.com/business/autos-transportation/iss-recommends-tesla-investors-vote-against-re-election-robyn-denholm-2023-05-04/',\n",
" 'snippet': 'Proxy advisory firm ISS on Wednesday recommended Tesla '\n",
" 'investors vote against re-election of board chair Robyn '\n",
" 'Denholm, citing \"concerns on...',\n",
" 'date': '5 mins ago',\n",
" 'source': 'Reuters',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcROdETe_GUyp1e8RHNhaRM8Z_vfxCvdfinZwzL1bT1ZGSYaGTeOojIdBoLevA&s',\n",
" 'position': 1},\n",
" {'title': 'Global companies by market cap: Tesla fell most in April',\n",
" 'link': 'https://www.reuters.com/markets/global-companies-by-market-cap-tesla-fell-most-april-2023-05-02/',\n",
" 'snippet': 'Tesla Inc was the biggest loser among top companies by '\n",
" 'market capitalisation in April, hit by disappointing '\n",
" 'quarterly earnings after it...',\n",
" 'date': '1 day ago',\n",
" 'source': 'Reuters',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ4u4CP8aOdGyRFH6o4PkXi-_eZDeY96vLSag5gDjhKMYf98YBER2cZPbkStQ&s',\n",
" 'position': 2},\n",
" {'title': 'Tesla Wanted an EV Price War. Ford Showed Up.',\n",
" 'link': 'https://www.bloomberg.com/opinion/articles/2023-05-03/tesla-wanted-an-ev-price-war-ford-showed-up',\n",
" 'snippet': 'The legacy automaker is paring back the cost of its '\n",
" 'Mustang Mach-E model after Tesla discounted its '\n",
" 'competing EVs, portending tighter...',\n",
" 'date': '6 hours ago',\n",
" 'source': 'Bloomberg.com',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_3Eo4VI0H-nTeIbYc5DaQn5ep7YrWnmhx6pv8XddFgNF5zRC9gEpHfDq8yQ&s',\n",
" 'position': 3},\n",
" {'title': 'Joby Aviation to get investment from Tesla shareholder '\n",
" 'Baillie Gifford',\n",
" 'link': 'https://finance.yahoo.com/news/joby-aviation-investment-tesla-shareholder-204450712.html',\n",
" 'snippet': 'This comes days after Joby clinched a $55 million '\n",
" 'contract extension to deliver up to nine air taxis to '\n",
" 'the U.S. Air Force,...',\n",
" 'date': '4 hours ago',\n",
" 'source': 'Yahoo Finance',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQO0uVn297LI-xryrPNqJ-apUOulj4ohM-xkN4OfmvMOYh1CPdUEBbYx6hviw&s',\n",
" 'position': 4},\n",
" {'title': 'Tesla resumes U.S. orders for a Model 3 version at lower '\n",
" 'price, range',\n",
" 'link': 'https://finance.yahoo.com/news/tesla-resumes-us-orders-model-045736115.html',\n",
" 'snippet': '(Reuters) -Tesla Inc has resumed taking orders for its '\n",
" 'Model 3 long-range vehicle in the United States, the '\n",
" \"company's website showed late on...\",\n",
" 'date': '19 hours ago',\n",
" 'source': 'Yahoo Finance',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIZetJ62sQefPfbQ9KKDt6iH7Mc0ylT5t_hpgeeuUkHhJuAx2FOJ4ZTRVDFg&s',\n",
" 'position': 5},\n",
" {'title': 'The Tesla Model 3 Long Range AWD Is Now Available in the '\n",
" 'U.S. With 325 Miles of Range',\n",
" 'link': 'https://www.notateslaapp.com/news/1393/tesla-reopens-orders-for-model-3-long-range-after-months-of-unavailability',\n",
" 'snippet': 'Tesla has reopened orders for the Model 3 Long Range '\n",
" 'RWD, which has been unavailable for months due to high '\n",
" 'demand.',\n",
" 'date': '7 hours ago',\n",
" 'source': 'Not a Tesla App',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSecrgxZpRj18xIJY-nDHljyP-A4ejEkswa9eq77qhMNrScnVIqe34uql5U4w&s',\n",
" 'position': 6},\n",
" {'title': 'Tesla Cybertruck alpha prototype spotted at the Fremont '\n",
" 'factory in new pics and videos',\n",
" '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/',\n",
" 'snippet': 'A Tesla Cybertruck alpha prototype goes to Fremont, '\n",
" 'California for another round of testing before going to '\n",
" 'production later this year (pics...',\n",
" 'date': '14 hours ago',\n",
" 'source': 'Tesla Oracle',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRO7M5ZLQE-Zo4-_5dv9hNAQZ3wSqfvYCuKqzxHG-M6CgLpwPMMG_ssebdcMg&s',\n",
" 'position': 7},\n",
" {'title': 'Tesla putting facility in new part of country - Austin '\n",
" 'Business Journal',\n",
" 'link': 'https://www.bizjournals.com/austin/news/2023/05/02/tesla-leases-building-seattle-area.html',\n",
" 'snippet': 'Check out what Puget Sound Business Journal has to '\n",
" \"report about the Austin-based company's real estate \"\n",
" 'footprint in the Pacific Northwest.',\n",
" 'date': '22 hours ago',\n",
" 'source': 'The Business Journals',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9kIEHWz1FcHKDUtGQBS0AjmkqtyuBkQvD8kyIY3kpaPrgYaN7I_H2zoOJsA&s',\n",
" 'position': 8},\n",
" {'title': 'Tesla (TSLA) Resumes Orders for Model 3 Long Range After '\n",
" 'Backlog',\n",
" 'link': 'https://www.bloomberg.com/news/articles/2023-05-03/tesla-resumes-orders-for-popular-model-3-long-range-at-47-240',\n",
" 'snippet': 'Tesla Inc. has resumed taking orders for its Model 3 '\n",
" 'Long Range edition with a starting price of $47240, '\n",
" 'according to its website.',\n",
" 'date': '5 hours ago',\n",
" 'source': 'Bloomberg.com',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTWWIC4VpMTfRvSyqiomODOoLg0xhoBf-Tc1qweKnSuaiTk-Y1wMJZM3jct0w&s',\n",
" 'position': 9}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"news\")\n",
"results = search.results(\"Tesla Inc.\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:34.984087Z",
"start_time": "2023-05-04T00:54:33.369231Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"If you want to only receive news articles published in the last hour, you can do the following:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 9,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Tesla Inc.',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'news',\n",
" 'tbs': 'qdr:h'},\n",
" 'news': [{'title': 'Oklahoma Gov. Stitt sees growing foreign interest in '\n",
" 'investments in ...',\n",
" 'link': 'https://www.reuters.com/world/us/oklahoma-gov-stitt-sees-growing-foreign-interest-investments-state-2023-05-04/',\n",
" 'snippet': 'T)), a battery supplier to electric vehicle maker Tesla '\n",
" 'Inc (TSLA.O), said on Sunday it is considering building '\n",
" 'a battery plant in Oklahoma, its third in...',\n",
" 'date': '53 mins ago',\n",
" 'source': 'Reuters',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSTcsXeenqmEKdiekvUgAmqIPR4nlAmgjTkBqLpza-lLfjX1CwB84MoNVj0Q&s',\n",
" 'position': 1},\n",
" {'title': 'Ryder lanza solución llave en mano para vehículos '\n",
" 'eléctricos en EU',\n",
" 'link': 'https://www.tyt.com.mx/nota/ryder-lanza-solucion-llave-en-mano-para-vehiculos-electricos-en-eu',\n",
" 'snippet': 'Ryder System Inc. presentó RyderElectric+ TM como su '\n",
" 'nueva solución llave en mano ... Ryder también tiene '\n",
" 'reservados los semirremolques Tesla y continúa...',\n",
" 'date': '56 mins ago',\n",
" 'source': 'Revista Transportes y Turismo',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJhXTQQtjSUZf9YPM235WQhFU5_d7lEA76zB8DGwZfixcgf1_dhPJyKA1Nbw&s',\n",
" 'position': 2},\n",
" {'title': '\"I think people can get by with $999 million,\" Bernie '\n",
" 'Sanders tells American Billionaires.',\n",
" '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/',\n",
" 'snippet': 'The report noted that in 2007 and 2011, Amazon.com Inc. '\n",
" 'founder Jeff Bezos “did not pay a dime in federal ... '\n",
" 'If you want to bet on Musk, check out Tesla.',\n",
" 'date': '11 mins ago',\n",
" 'source': 'THE BHARAT EXPRESS NEWS',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_X9qqSwVFBBdos2CK5ky5IWIE3aJPCQeRYR9O1Jz4t-MjaEYBuwK7AU3AJQ&s',\n",
" 'position': 3}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"news\", tbs=\"qdr:h\")\n",
"results = search.results(\"Tesla Inc.\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:41.786864Z",
"start_time": "2023-05-04T00:54:40.691905Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"Some examples of the `tbs` parameter:\n",
"\n",
"`qdr:h` (past hour)\n",
"`qdr:d` (past day)\n",
"`qdr:w` (past week)\n",
"`qdr:m` (past month)\n",
"`qdr:y` (past year)\n",
"\n",
"You can specify intermediate time periods by adding a number:\n",
"`qdr:h12` (past 12 hours)\n",
"`qdr:d3` (past 3 days)\n",
"`qdr:w2` (past 2 weeks)\n",
"`qdr:m6` (past 6 months)\n",
"`qdr:m2` (past 2 years)\n",
"\n",
"For all supported filters simply go to [Google Search](https://google.com), search for something, click on \"Tools\", add your date filter and check the URL for \"tbs=\".\n"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "markdown",
"source": [
"## Searching for Google Places\n",
"We can also query Google Places using this wrapper. For example:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 10,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Italian restaurants in Upper East Side',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'places'},\n",
" 'places': [{'position': 1,\n",
" 'title': \"L'Osteria\",\n",
" 'address': '1219 Lexington Ave',\n",
" 'latitude': 40.777154599999996,\n",
" 'longitude': -73.9571363,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNjU7BWEq_aYQANBCbX52Kb0lDpd_lFIx5onw40=w92-h92-n-k-no',\n",
" 'rating': 4.7,\n",
" 'ratingCount': 91,\n",
" 'category': 'Italian'},\n",
" {'position': 2,\n",
" 'title': \"Tony's Di Napoli\",\n",
" 'address': '1081 3rd Ave',\n",
" 'latitude': 40.7643567,\n",
" 'longitude': -73.9642373,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNbNv6jZkJ9nyVi60__8c1DQbe_eEbugRAhIYye=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 2265,\n",
" 'category': 'Italian'},\n",
" {'position': 3,\n",
" 'title': 'Caravaggio',\n",
" 'address': '23 E 74th St',\n",
" 'latitude': 40.773412799999996,\n",
" 'longitude': -73.96473379999999,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPDGchokDvppoLfmVEo6X_bWd3Fz0HyxIHTEe9V=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 276,\n",
" 'category': 'Italian'},\n",
" {'position': 4,\n",
" 'title': 'Luna Rossa',\n",
" 'address': '347 E 85th St',\n",
" 'latitude': 40.776593999999996,\n",
" 'longitude': -73.950351,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNPCpCPuqPAb1Mv6_fOP7cjb8Wu1rbqbk2sMBlh=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 140,\n",
" 'category': 'Italian'},\n",
" {'position': 5,\n",
" 'title': \"Paola's\",\n",
" 'address': '1361 Lexington Ave',\n",
" 'latitude': 40.7822019,\n",
" 'longitude': -73.9534096,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPJr2Vcx-B6K-GNQa4koOTffggTePz8TKRTnWi3=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 344,\n",
" 'category': 'Italian'},\n",
" {'position': 6,\n",
" 'title': 'Come Prima',\n",
" 'address': '903 Madison Ave',\n",
" 'latitude': 40.772124999999996,\n",
" 'longitude': -73.965012,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNrX19G0NVdtDyMovCQ-M-m0c_gLmIxrWDQAAbz=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 176,\n",
" 'category': 'Italian'},\n",
" {'position': 7,\n",
" 'title': 'Botte UES',\n",
" 'address': '1606 1st Ave.',\n",
" 'latitude': 40.7750785,\n",
" 'longitude': -73.9504801,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPPN5GXxfH3NDacBc0Pt3uGAInd9OChS5isz9RF=w92-h92-n-k-no',\n",
" 'rating': 4.4,\n",
" 'ratingCount': 152,\n",
" 'category': 'Italian'},\n",
" {'position': 8,\n",
" 'title': 'Piccola Cucina Uptown',\n",
" 'address': '106 E 60th St',\n",
" 'latitude': 40.7632468,\n",
" 'longitude': -73.9689825,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPifIgzOCD5SjgzzqBzGkdZCBp0MQsK5k7M7znn=w92-h92-n-k-no',\n",
" 'rating': 4.6,\n",
" 'ratingCount': 941,\n",
" 'category': 'Italian'},\n",
" {'position': 9,\n",
" 'title': 'Pinocchio Restaurant',\n",
" 'address': '300 E 92nd St',\n",
" 'latitude': 40.781453299999995,\n",
" 'longitude': -73.9486788,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNtxlIyEEJHtDtFtTR9nB38S8A2VyMu-mVVz72A=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 113,\n",
" 'category': 'Italian'},\n",
" {'position': 10,\n",
" 'title': 'Barbaresco',\n",
" 'address': '843 Lexington Ave #1',\n",
" 'latitude': 40.7654332,\n",
" 'longitude': -73.9656873,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipMb9FbPuXF_r9g5QseOHmReejxSHgSahPMPJ9-8=w92-h92-n-k-no',\n",
" 'rating': 4.3,\n",
" 'ratingCount': 122,\n",
" 'locationHint': 'In The Touraine',\n",
" 'category': 'Italian'}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"places\")\n",
"results = search.results(\"Italian restaurants in Upper East Side\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:56:07.271164Z",
"start_time": "2023-05-04T00:56:05.645847Z"
}
}
}
],
"metadata": {

@ -17,6 +17,7 @@ from langchain.tools.base import BaseTool
from langchain.tools.bing_search.tool import BingSearchRun
from langchain.tools.ddg_search.tool import DuckDuckGoSearchRun
from langchain.tools.google_search.tool import GoogleSearchResults, GoogleSearchRun
from langchain.tools.google_serper.tool import GoogleSerperResults, GoogleSerperRun
from langchain.tools.human.tool import HumanInputRun
from langchain.tools.python.tool import PythonREPLTool
from langchain.tools.requests.tool import (
@ -190,11 +191,11 @@ def _get_arxiv(**kwargs: Any) -> BaseTool:
def _get_google_serper(**kwargs: Any) -> BaseTool:
return Tool(
name="Serper Search",
func=GoogleSerperAPIWrapper(**kwargs).run,
description="A low-cost Google Search API. Useful for when you need to answer questions about current events. Input should be a search query.",
)
return GoogleSerperRun(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
def _get_google_serper_results_json(**kwargs: Any) -> BaseTool:
return GoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
def _get_google_search_results_json(**kwargs: Any) -> BaseTool:
@ -257,7 +258,11 @@ _EXTRA_OPTIONAL_TOOLS: Dict[str, Tuple[Callable[[KwArg(Any)], BaseTool], List[st
),
"bing-search": (_get_bing_search, ["bing_subscription_key", "bing_search_url"]),
"ddg-search": (_get_ddg_search, []),
"google-serper": (_get_google_serper, ["serper_api_key"]),
"google-serper": (_get_google_serper, ["serper_api_key", "aiosession"]),
"google-serper-results-json": (
_get_google_serper_results_json,
["serper_api_key", "aiosession"],
),
"serpapi": (_get_serpapi, ["serpapi_api_key", "aiosession"]),
"searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]),
"wikipedia": (_get_wikipedia, ["top_k_results", "lang"]),

@ -12,6 +12,7 @@ from langchain.tools.file_management.read import ReadFileTool
from langchain.tools.file_management.write import WriteFileTool
from langchain.tools.google_places.tool import GooglePlacesTool
from langchain.tools.google_search.tool import GoogleSearchResults, GoogleSearchRun
from langchain.tools.google_serper.tool import GoogleSerperResults, GoogleSerperRun
from langchain.tools.human.tool import HumanInputRun
from langchain.tools.ifttt import IFTTTWebhook
from langchain.tools.openapi.utils.api_models import APIOperation
@ -57,6 +58,8 @@ __all__ = [
"GooglePlacesTool",
"GoogleSearchResults",
"GoogleSearchRun",
"GoogleSerperResults",
"GoogleSerperRun",
"HumanInputRun",
"IFTTTWebhook",
"ListDirectoryTool",

@ -0,0 +1,6 @@
from langchain.tools.google_serper.tool import GoogleSerperResults, GoogleSerperRun
"""Google Serper API Toolkit."""
"""Tool for the Serer.dev Google Search API."""
__all__ = ["GoogleSerperRun", "GoogleSerperResults"]

@ -0,0 +1,70 @@
"""Tool for the Serper.dev Google Search API."""
from typing import Optional
from pydantic.fields import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.google_serper import GoogleSerperAPIWrapper
class GoogleSerperRun(BaseTool):
"""Tool that adds the capability to query the Serper.dev Google search API."""
name = "Google Serper"
description = (
"A low-cost Google Search API."
"Useful for when you need to answer questions about current events."
"Input should be a search query."
)
api_wrapper: GoogleSerperAPIWrapper
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
return str(self.api_wrapper.run(query))
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool asynchronously."""
return (await self.api_wrapper.arun(query)).__str__()
class GoogleSerperResults(BaseTool):
"""Tool that has capability to query the Serper.dev Google Search API
and get back json."""
name = "Google Serrper Results JSON"
description = (
"A low-cost Google Search API."
"Useful for when you need to answer questions about current events."
"Input should be a search query. Output is a JSON object of the query results"
)
api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper)
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
return str(self.api_wrapper.results(query))
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool asynchronously."""
return (await self.api_wrapper.aresults(query)).__str__()

@ -1,6 +1,7 @@
"""Util that calls Google Search using the Serper.dev API."""
from typing import Dict, Optional
from typing import Any, Dict, Optional
import aiohttp
import requests
from pydantic.class_validators import root_validator
from pydantic.main import BaseModel
@ -27,7 +28,15 @@ class GoogleSerperAPIWrapper(BaseModel):
k: int = 10
gl: str = "us"
hl: str = "en"
type: str = "search" # search, images, places, news
tbs: Optional[str] = None
serper_api_key: Optional[str] = None
aiosession: Optional[aiohttp.ClientSession] = None
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
@ -39,9 +48,56 @@ class GoogleSerperAPIWrapper(BaseModel):
return values
def run(self, query: str) -> str:
def results(self, query: str, **kwargs: Any) -> Dict:
"""Run query through GoogleSearch."""
return self._google_serper_search_results(
query,
gl=self.gl,
hl=self.hl,
num=self.k,
tbs=self.tbs,
search_type=self.type,
**kwargs,
)
def run(self, query: str, **kwargs: Any) -> str:
"""Run query through GoogleSearch and parse result."""
results = self._google_serper_search_results(query, gl=self.gl, hl=self.hl)
results = self._google_serper_search_results(
query,
gl=self.gl,
hl=self.hl,
num=self.k,
tbs=self.tbs,
search_type=self.type,
**kwargs,
)
return self._parse_results(results)
async def aresults(self, query: str, **kwargs: Any) -> Dict:
"""Run query through GoogleSearch."""
results = await self._async_google_serper_search_results(
query,
gl=self.gl,
hl=self.hl,
num=self.k,
search_type=self.type,
tbs=self.tbs,
**kwargs,
)
return results
async def arun(self, query: str, **kwargs: Any) -> str:
"""Run query through GoogleSearch and parse result async."""
results = await self._async_google_serper_search_results(
query,
gl=self.gl,
hl=self.hl,
num=self.k,
search_type=self.type,
tbs=self.tbs,
**kwargs,
)
return self._parse_results(results)
@ -80,15 +136,47 @@ class GoogleSerperAPIWrapper(BaseModel):
return " ".join(snippets)
def _google_serper_search_results(self, search_term: str, gl: str, hl: str) -> dict:
def _google_serper_search_results(
self, search_term: str, search_type: str = "search", **kwargs: Any
) -> dict:
headers = {
"X-API-KEY": self.serper_api_key or "",
"Content-Type": "application/json",
}
params = {"q": search_term, "gl": gl, "hl": hl}
params = {
"q": search_term,
**{key: value for key, value in kwargs.items() if value is not None},
}
response = requests.post(
"https://google.serper.dev/search", headers=headers, params=params
f"https://google.serper.dev/{search_type}", headers=headers, params=params
)
response.raise_for_status()
search_results = response.json()
return search_results
async def _async_google_serper_search_results(
self, search_term: str, search_type: str = "search", **kwargs: Any
) -> dict:
headers = {
"X-API-KEY": self.serper_api_key or "",
"Content-Type": "application/json",
}
url = f"https://google.serper.dev/{search_type}"
params = {
"q": search_term,
**{key: value for key, value in kwargs.items() if value is not None},
}
if not self.aiosession:
async with aiohttp.ClientSession() as session:
async with session.post(
url, params=params, headers=headers, raise_for_status=False
) as response:
search_results = await response.json()
else:
async with self.aiosession.post(
url, params=params, headers=headers, raise_for_status=True
) as response:
search_results = await response.json()
return search_results

@ -1,4 +1,6 @@
"""Integration test for Serper.dev's Google Search API Wrapper."""
import pytest
from langchain.utilities.google_serper import GoogleSerperAPIWrapper
@ -7,3 +9,26 @@ def test_call() -> None:
search = GoogleSerperAPIWrapper()
output = search.run("What was Obama's first name?")
assert "Barack Hussein Obama II" in output
async def test_results() -> None:
"""Test that call gives the correct answer."""
search = GoogleSerperAPIWrapper()
output = search.results("What was Obama's first name?")
assert "Barack Hussein Obama II" in output["answerBox"]["answer"]
@pytest.mark.asyncio
async def test_async_call() -> None:
"""Test that call gives the correct answer."""
search = GoogleSerperAPIWrapper()
output = await search.arun("What was Obama's first name?")
assert "Barack Hussein Obama II" in output
@pytest.mark.asyncio
async def test_async_results() -> None:
"""Test that call gives the correct answer."""
search = GoogleSerperAPIWrapper()
output = await search.aresults("What was Obama's first name?")
assert "Barack Hussein Obama II" in output["answerBox"]["answer"]

@ -22,6 +22,8 @@ _EXPECTED = [
"GooglePlacesTool",
"GoogleSearchResults",
"GoogleSearchRun",
"GoogleSerperResults",
"GoogleSerperRun",
"HumanInputRun",
"IFTTTWebhook",
"ListDirectoryTool",

Loading…
Cancel
Save