2025, Nov 26 13:00

How to Enable Web Search in Gemini's Python SDK using google.genai and the GoogleSearch tool

Learn how to enable web search in Gemini's Python SDK using the google.genai client and GoogleSearch tool via GenerateContentConfig, with working code example.

Enable web search in Gemini models with the Python SDK

Adding web search to an LLM workflow is straightforward with OpenAI tooling, but doing the same with Gemini can be confusing if you start with the older Python package. The key is to use the newer client and explicitly supply the search tool. Below is a concise walkthrough with working code.

What many developers try first

With OpenAI, web search can be toggled via a tool in the request. A minimal example looks like this:

from openai import OpenAI
oa = OpenAI(api_key="...")
reply = oa.responses.create(
    model="gpt-4o-mini",
    input=[
        {"role": "system", "content": "..."},
        {"role": "user", "content": "..."},
    ],
    tools=[{"type": "web_search_preview"}],
)

Trying to replicate this pattern with the google-generativeai package often leads to a dead end when you look for a tools switch for search:

from google.generativeai import configure, GenerativeModel
configure(api_key="...")
gm = GenerativeModel("models/gemini-2.0-flash")
res = gm.generate_content(
    "...",
    generation_config={"temperature": 0.1},
    # where to enable web search?
)

What’s actually going on

Web search for Gemini is exposed via a tool in the newer client, not via the generation_config in the older package. The functionality surfaces when you use the updated library and pass a GoogleSearch tool in the request configuration.

The fix: use the newer client and add the GoogleSearch tool

Switch to the google.genai client and include the GoogleSearch tool in the GenerateContentConfig. Here is a minimal prompt that uses web search:

from google.genai import Client
from google.genai.types import GenerateContentConfig, GoogleSearch
gcli = Client(api_key="...")
out = gcli.models.generate_content(
    model="gemini-2.5-pro-preview-06-05",
    contents="...",
    config=GenerateContentConfig(
        temperature=0.1,
        tools=[GoogleSearch],
    ),
)

Why this matters

If you rely on live information retrieval, the distinction between packages determines whether your model can actually search the web at inference time. Using the correct client and passing the proper tool is the difference between a static answer and one grounded in fresh results.

Takeaways

If you need web search with Gemini in Python, call the newer client and explicitly provide GoogleSearch via the request config. Keep your generation settings as needed; the critical piece is the tools parameter. This small change keeps your pipeline simple while enabling search-backed responses.