Integrating Google Search with Gemini

My current solution is to use the GoogleGenAi package, which has built-in search for its models but there are some requirements when using it:
https://ai.google.dev/gemini-api/docs/grounding?hl=en&lang=javascript
https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-search-suggestions

code:
import { GoogleGenAI } from "@google/genai";
const googleSearch = ai.defineTool({
  name: 'googleSearch',
  description: 'Searches the web for information',
  inputSchema: z.object({
    query: z.string().describe('the query to search the web for'),
  }),
  outputSchema: z.string(),
},
  async (input) => {
    const google = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY! });

    const response = await google.models.generateContent({
      model: 'gemini-2.0-flash',
      contents: [input.query],
      config: {
        tools: [{ googleSearch: {} }],
      },
    });

    console.log("Search tool was used: ", response.text);
    console.log("Search tool Grounding Chunks: ", response.candidates?.[0]?.groundingMetadata?.groundingChunks);

    if (response.text === undefined) return 'No response from google';
    return response.text;
  }
);
Was this page helpful?