---
title: Google Search Tool
---

The Google Search integration in AG2 allows users to perform real-time web searches within the AG2 framework. This is especially useful for retrieving up-to-date information that may not be available in static datasets.

## Installation

To get started with the `Google Search` integration in AG2, follow these steps:

Install AG2 with the `google-search` extra.
Since our examples also use `openai` and `gemini`, install them as well:

```bash
pip install -U ag2[openai,gemini,google-search]
```
> **Note:** If you have been using `autogen` or `ag2`, all you need to do is upgrade it using:
> ```bash
> pip install -U autogen[openai,gemini,google-search]
> ```
> or
> ```bash
> pip install -U ag2[openai,gemini,google-search]
> ```
> as `autogen` and `ag2` are aliases for the same PyPI package.

You're all set! Now you can start using Google Search with AG2.

## Imports


```python
import os

import autogen
from autogen import AssistantAgent, LLMConfig
from autogen.tools.experimental import GoogleSearchTool
```

## Using GoogleSearchTool with Gemini GenAI

The [`GoogleSearchTool`](/docs/api-reference/autogen/tools/experimental/GoogleSearchTool) enables search functionalities in AG2 and can be configured to use Gemini GenAI for an enhanced search experience. This section covers agent configuration and tool initialization.

### Agent Configuration

```python
llm_config = LLMConfig(path="OAI_CONFIG_LIST").where(model="gemini-2.0-flash")

assistant = AssistantAgent(
    name="assistant",
    llm_config=llm_config,
)
```

### GoogleSearchTool Initialization

For Gemini GenAI, you can use the GenAI prebuilt Google Search tool by setting `use_internal_llm_tool_if_available` to `True`.

> **Note:** You cannot combine other tools with the prebuilt Google Search tool. If you need multiple tools, refer to the AG2 implementation section.

```python
gs_tool = GoogleSearchTool(
    use_internal_llm_tool_if_available=True,
)
# Once initialized, register the tool with the assistant
gs_tool.register_for_llm(assistant)
```

### Start the Conversation

With the setup complete, you can now use the assistant to fetch live web search results.

```python
response = assistant.run(
    message="What happened with stock prices after deepseek was launched, please search the web.",
    tools=assistant.tools,
    max_turns=2,
    user_input=False,
)

# Iterate through the chat automatically with console output
response.process()
````

### Output
```console
user (to assistant):

What happened with stock prices after deepseek was launched, please search the web.

--------------------------------------------------------------------------------
assistant (to user):

The launch of DeepSeek R1 in late January 2025 had a significant, albeit temporary, impact on the stock market, particularly affecting technology companies with large AI footprints. Here's a breakdown of what happened:

**Initial Market Reaction (Late January 2025):**

*   **Stock Market Sell-off:** The release of DeepSeek's R1 model triggered a stock market sell-off, with the Nasdaq dropping 3.1% on January 28, 2025.
*   **Nvidia's Losses:** Nvidia experienced a significant plunge, with shares dropping nearly 17% and losing approximately $600 billion in market capitalization. This was reported as the largest single-day loss in US history for a company. Some sources say the market cap loss was $593 billion.
*   **Other Tech Companies Affected:** Other major tech companies, including Microsoft, Broadcom, and Alphabet, also saw their stock prices decline. Siemens Energy in Europe also dropped.
*   **Overall Market Impact:** It's estimated that the DeepSeek announcement wiped out nearly $1 trillion in market value across US exchanges.

**Reasons for the Impact:**

*   **Cost Efficiency:** DeepSeek's R1 model was reported to be on par with leading proprietary models like GPT-4 but was trained at a significantly lower cost (around $6 million).
*   **Open-Source Nature:** The open-source nature of DeepSeek R1 challenged the assumption that AI development requires massive capital investment and expensive hardware.
*   **Competition:** DeepSeek's emergence as a strong competitor to companies like OpenAI raised concerns about market dominance and the future of AI development.

**Subsequent Recovery and Shifts:**

*   **Stock Recovery:** The Nasdaq and S&P 500 rebounded shortly after the initial sell-off, with Nvidia's stock surging nearly 9% the next day.
...
TERMINATE
````

## GoogleSearchTool with AG2 Google Search implementation

For all other LLM providers or if you need to combine Google Search with other tools, follow this section to configure AG2’s implementation.

### Setup Google Search Engine and API Key
1. Create a Google Custom Search Engine (CSE):
   - [Go to Google Programmable Search Engine](https://programmablesearchengine.google.com/about/)
   - Click `Get Started` and create a search engine.
   - Under `Sites to Search`, select `Search the entire web` if you want global search.
   - Copy the **Search Engine ID** from the CSE dashboard  (`cx` parameter from the url)
2. Get a Google API Key:
   - Go to [Google Cloud Console](https://console.cloud.google.com/)
   - Create a new project.
   - Navigate to **APIs & Services > Library**, search for **Custom Search API** and enable it.
   - Go to **APIs & Services > Credentials**, click on **Create Credentials > API key** and copy it.
3. Export engine ID and api key
    ```bash
    export GOOGLE_SEARCH_ENGINE_ID="your_engine_id"
    export GOOGLE_SEARCH_API_KEY="your_api_key"
    ```

### Agent Configuration

```python
llm_config = LLMConfig(path="OAI_CONFIG_LIST").where(model="gpt-5-nano")

assistant = AssistantAgent(
    name="assistant",
    llm_config=llm_config,
)
```

### GoogleSearchTool Initialization

Create [`GoogleSearchTool`](/docs/api-reference/autogen/tools/experimental/GoogleSearchTool) with your `search_api_key` and `search_engine_id`.

```python
search_api_key = os.getenv("GOOGLE_SEARCH_API_KEY")
search_engine_id = os.getenv("GOOGLE_SEARCH_ENGINE_ID")

assert search_api_key is not None, "Please set GOOGLE_SEARCH_API_KEY environment variable"
assert search_engine_id is not None, "Please set GOOGLE_SEARCH_ENGINE_ID environment variable"

gs_tool = GoogleSearchTool(
    search_api_key=search_api_key,
    search_engine_id=search_engine_id,
)
# Once initialized, register the tool with the assistant:
gs_tool.register_for_llm(assistant)
```

### Start the Conversation

With the setup complete, you can now use the assistant to fetch live web search results.

```python
response = assistant.run(
    message="What happened with stock prices after deepseek was launched, please search the web.",
    tools=assistant.tools,
    max_turns=2,
    user_input=False,
)

# Iterate through the chat automatically with console output
response.process()
```

### Output
```console
user (to assistant):

What happened with stock prices after deepseek was launched, please search the web.

--------------------------------------------------------------------------------
assistant (to user):

***** Suggested tool call (call_JbyyhzRwX4Z4nWEkNuGSlrJ8): google_search *****
Arguments:
{"query":"DeepSeek stock prices after launch","num_results":5}
******************************************************************************

--------------------------------------------------------------------------------

>>>>>>>> EXECUTING FUNCTION google_search...
Call ID: call_JbyyhzRwX4Z4nWEkNuGSlrJ8
Input arguments: {'query': 'DeepSeek stock prices after launch', 'num_results': 5}
/Users/robert/projects/ag2/autogen/agentchat/conversable_agent.py:3002: UserWarning: Function 'google_search' is being overridden.
  warnings.warn(f"Function '{tool_sig['function']['name']}' is being overridden.", UserWarning)
user (to assistant):

***** Response from calling tool (call_JbyyhzRwX4Z4nWEkNuGSlrJ8) *****
[{'title': 'DeepSeek sparks AI stock selloff; Nvidia posts record market-cap ...', 'link': 'https://www.reuters.com/technology/chinas-deepseek-sets-off-ai-market-rout-2025-01-27/', 'snippet': 'Jan 27, 2025 ... Its researchers wrote in a paper last month that DeepSeek-V3 model, launched on Jan. ... Nvidia shares were up 2.5% in after-hours trading on\xa0...'}, {'title': 'What is DeepSeek - and why is everyone talking about it?', 'link': 'https://www.bbc.com/news/articles/c5yv5976z9po', 'snippet': 'Feb 4, 2025 ... DeepSeek, a Chinese artificial intelligence (AI) startup, made headlines worldwide after it topped app download charts and caused US tech\xa0...'}, {'title': 'Inside the Deepseek stock-market selloff - Raconteur', 'link': 'https://www.raconteur.net/technology/inside-the-deepseek-stock-market-selloff', 'snippet': 'Jan 31, 2025 ... Last week, Deepseek, a Chinese AI startup, launched its R1 ... The tech-heavy Nasdaq index dropped more than 3% after the launch.'}, {'title': 'A shocking Chinese AI advancement called DeepSeek is sending ...', 'link': 'https://www.cnn.com/2025/01/27/tech/deepseek-stocks-ai-china/index.html', 'snippet': 'Jan 27, 2025 ... US stocks dropped sharply Monday — and chipmaker Nvidia lost nearly $600 billion in market value — after a surprise advancement from a Chinese\xa0...'}, {'title': "'Sputnik moment': $1tn wiped off US stocks after Chinese firm ...", 'link': 'https://www.theguardian.com/business/2025/jan/27/tech-shares-asia-europe-fall-china-ai-deepseek', 'snippet': "Jan 27, 2025 ... Nvidia's fall was the biggest in US stock market history. The DeepSeek AI assistant also topped the Apple app store in the US and UK over the\xa0..."}]
**********************************************************************

--------------------------------------------------------------------------------
assistant (to user):

After the launch of DeepSeek, several significant trends occurred in the stock market:

1. **Stock Market Reaction**: Following the launch, there was a notable selloff in the U.S. tech sector, particularly affecting companies like Nvidia. Reports indicate that Nvidia lost nearly $600 billion in market value, marking one of the largest declines in U.S. stock market history.

2. **Tech Index Drops**: The tech-heavy Nasdaq index dropped more than 3% as a direct response to DeepSeek's launch.

3. **Overall Market Impact**: The launch was seen as a critical moment, with the total market cap of US tech shares declining by approximately $1 trillion.

4. **Market Sentiment**: The launch of DeepSeek was associated with a significant shift in market sentiment regarding AI technologies, prompting many investors to reassess their positions in tech stocks.

For further details, you can refer to articles from Reuters, BBC, CNN, and The Guardian for in-depth coverage of these developments.

You can find the articles at the following links:
- [Reuters](https://www.reuters.com/technology/chinas-deepseek-sets-off-ai-market-rout-2025-01-27/)
- [BBC](https://www.bbc.com/news/articles/c5yv5976z9po)
- [CNN](https://www.cnn.com/2025/01/27/tech/deepseek-stocks-ai-china/index.html)
- [The Guardian](https://www.theguardian.com/business/2025/jan/27/tech-shares-asia-europe-fall-china-ai-deepseek)

TERMINATE
```
