In this tutorial, we will explore how to use web search in OpenAI API.
By default, the ChatGPT API does not provide the latest web search results. It limits its usefulness for many topics or queries of interest. To solve this issue, we can integrate Google's Custom Search API with ChatGPT.
By using Google's Custom Search API, we can get real-time search results. Refer the steps below how to get an API key from the Google Developers Console and creating a custom search engine.
-
Get Custom Search JSON API Key
- Visit the Google Developers Console.
- Create a new project or select an existing one.
- Enable the Custom Search JSON API for your project.
- Go to the API credentials section and create an API key.
-
Create a Custom Search Engine (CSE)
- Go to the Programmable Search Engine control panel.
- Click on "Add" to create a new search engine.
- Specify name and select the "Search the entire web" option.
- Click on "Create" to finalize it.
The following python code queries the Google Custom Search API for real-time information and then sends the results to ChatGPT to generate a summary.
Please make sure to install the required libraries using the command - pip install requests openai
.
import requests from openai import OpenAI import os def execute_search_query(search_term, search_api_key, search_engine_id): """Calls the Google Custom Search API with parameters favoring recent results.""" parameters = { "key": search_api_key, "cx": search_engine_id, "q": search_term, "sort": "date", } response = requests.get( "https://www.googleapis.com/customsearch/v1", params=parameters, verify=False ) response.raise_for_status() return response.json() def generate_summary(search_term, model="gpt-4o", search_data={}): """Generates a summary of the latest information based on detailed search results.""" aggregated_details = "" if 'items' in search_data: details_list = [] for entry in search_data['items']: title = entry.get('title', 'No Title') snippet = entry.get('snippet', 'No snippet available') link = entry.get('link', 'No link available') details = ( f"Title: {title}\n" f"Snippet: {snippet}\n" f"Link: {link}\n" ) details_list.append(details) aggregated_details = "\n".join(details_list) prompt_text = ( f"User Query: {search_term}\n" f"Search Results:\n{aggregated_details}" ) ai_client = OpenAI() completion = ai_client.chat.completions.create( model=model, messages=[ { "role": "system", "content": ( "You are a knowledgeable AI assistant. Summarize the latest and most detailed information " "from the provided search results. Always prioritize latest information and relevance." ) }, {"role": "user", "content": prompt_text} ], ) return completion.choices[0].message.content.strip() # OpenAI API key os.environ['OPENAI_API_KEY'] = "ENTER_YOUR_OPENAI_API_KEY" # Google Custom Search API google_api_key = "ENTER_YOUR_GOOGLE_API_KEY" google_cx = "SEARCH_ENGINE_ID" # Define your search query query_text = "latest US inflation rate" search_results = execute_search_query(query_text, google_api_key, google_cx) # Generate a summary based on the search results instructions = "Provide the latest US inflation rate and a brief explanation for its change." summary = generate_summary(instructions, model="o3-mini", search_data=search_results) print("\nGenerated Summary:\n", summary)
Generated Summary:
The most recent data shows that the U.S. inflation rate was 2.9% in December 2024. This modest increase from the previous month is generally linked to continued upward pressure on prices coming from factors such as ongoing supply-chain constraints, higher energy costs.
Gemini 2.0 Flash by default supports real-time search and offers a daily limit that is five times higher than that of the Google Custom Search JSON API. It also provides free large language model capability for up to 1.5k requests per day.
Please make sure to install the google genai library - pip install google-genai
.
from google import genai import os os.environ["API_KEY"] = 'ENTER_YOUR_API_KEY' client = genai.Client(api_key=os.environ["API_KEY"]) MODEL = 'gemini-2.0-flash' search_tool = {'google_search': {}} chat = client.chats.create(model=MODEL, config={'tools': [search_tool]}) r = chat.send_message('Provide the latest US inflation rate and a brief explanation for its change.') response = r.candidates[0].content.parts[0].text print(response)
The latest US inflation rate is 2.9% for December 2024, up from 2.7% in November. This increase was partly driven by low base effects from the previous year, especially for energy, and an increase in energy costs.
Share Share Tweet