This example demonstrates how to use the Gemini API with a custom search provider to ground generation results.
This example uses the following Google Cloud services:
- Google Gemini (with custom Search Grounding): The LLM being grounded
- Google Cloud Functions: To create a custom search provider
- Google Cloud API Gateway: To expose the Cloud Function as a managed and protected API
In addition, the example uses one of the following search engines for web search:
First, clone the repository. This example will be easiest to run on the Google Cloud Shell
git clone https://github.com/anihm136/gemini-search-grounding.git
The search directory contains a simple search service that can be deployed to Google Cloud. This service uses a third-party search provider (e.g., Brave) to perform searches.
To deploy the service, first open search/args.sh in your editor and set the appropriate parameter values. Then, run the deploy script:
cd search
./deploy.shThis script will:
- Enable the necessary Google Cloud services.
- Create a service account and assign permissions.
- Deploy a Cloud Function that wraps the search provider.
- Deploy an API Gateway to expose the Cloud Function as a protected API.
To create an API key to access your new search API, follow the instructions here
At the end of the script, it will output the SEARCH_ENDPOINT value. You will need this value in the next step.
The main.py script shows how to use the custom search service with the Gemini API.
Before running the script, you need to update the following variables in main.py with the values from the previous step:
SEARCH_ENDPOINT: The URL of the API GatewaySEARCH_API_KEY: The API key you created
Once you have updated the variables, you can run the script:
uv sync
. .venv/bin/activate
python main.pyThis will send a request to the Gemini API, which will use the custom search service to ground the generation results.