pythongoogle-geminiweb-search

How can I use web search with Gemini models in the google-generativeai package?


I'm trying to utilize the google-generativeai Python package to call various Gemini models and also equip them with web search functionality. I can do something similar with OpenAI models and the openai package like this:

from openai import OpenAI

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

That web_search_preview tool is what enables the OpenAI model to make web requests while answering your prompt. I assume that Gemini models have similar functionality, but I've been unable to find any documentation on it so far, and vibe coding hasn't helped either. Here's what I have so far:

from google.generativeai import configure, GenerativeModel

configure(api_key="...")
model = GenerativeModel("models/gemini-2.0-flash")
response = model.generate_content(
    "...",
    generation_config={"temperature": 0.1},
    # is there some tools option I can specify to enable web search?

)

Solution

  • I figured it out. Here's a code snippet using the newer library and issuing a prompt that uses web search:

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