DEV Community

Cover image for Google Search with Langchain
Roshan Sanjeewa Wijesena
Roshan Sanjeewa Wijesena

Posted on • Edited on

Google Search with Langchain

Do you ever want to hook google search API into your GenAI application? you don't need to pay for wrapper services like serpapi, We have langchain wrapper langchain-google-communityfor Google search API and its free.

  1. You need to get Google API Key - https://developers.google.com/custom-search/v1/introduction(https://developers.google.com/custom-search/v1/introduction)

  2. Install below python packages in your env

!pip install langchain
!pip install -U langchain-google-community
Enter fullscreen mode Exit fullscreen mode

3 Set your google api key

import os
os.environ["GOOGLE_API_KEY"] = "<YOUR_API_KEY>"
Enter fullscreen mode Exit fullscreen mode

4 Below code will help you to search google

from langchain_google_community import GoogleSearchAPIWrapper
from langchain_core.tools import Tool
import os

import inspect

# Get the constructor of GoogleSearchAPIWrapper
constructor = inspect.signature(GoogleSearchAPIWrapper)

# Print the number of parameters it expects
print(f"Number of parameters expected: {len(constructor.parameters)}")

api_key = os.environ.get("GOOGLE_API_KEY")

search = GoogleSearchAPIWrapper()

# Create a Tool object using the GoogleSearchAPIWrapper instance
tool = Tool(
    name="Google Search",
    description="Search Google for recent results.",
    func=search.run,
)

# Use the tool to perform a search
results = tool.run("What is the capital of France?")

print(results)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)