diff --git a/examples/third_party/Web_search_with_google_api_bring_your_own_browser_tool.ipynb b/examples/third_party/Web_search_with_google_api_bring_your_own_browser_tool.ipynb new file mode 100644 index 0000000000..166ec80e47 --- /dev/null +++ b/examples/third_party/Web_search_with_google_api_bring_your_own_browser_tool.ipynb @@ -0,0 +1,640 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "7f59879cabc55a5e", + "metadata": {}, + "source": [ + "## Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization\n", + "\n", + "**Disclaimer: This cookbook is for educational purposes only. Ensure that you comply with all applicable laws and service terms when using web search and scraping technologies. This cookbook will restrict the search to openai.com domain to retrieve the public information to illustrate the concepts.**\n", + "\n", + "Large Language Models (LLMs) such as GPT-4o have a knowledge cutoff date, which means they lack information about events that occurred after that point. In scenarios where the most recent data is essential, it's necessary to provide LLMs with access to current web information to ensure accurate and relevant responses.\n", + "\n", + "In this guide, we will build a Bring Your Own Browser (BYOB) tool using Python to overcome this limitation. Our goal is to create a system that provides up-to-date answers in your application, including the most recent developments such as the latest product launches by OpenAI. By integrating web search capabilities with an LLM, we'll enable the model to generate responses based on the latest information available online.\n", + "\n", + "While you can use any publicly available search APIs, we'll utilize Google's Custom Search API to perform web searches. The retrieved information from the search results will be processed and passed to the LLM to generate the final response through Retrieval-Augmented Generation (RAG).\n", + "\n", + "**Bring Your Own Browser (BYOB)** tools allow users to perform web browsing tasks programmatically. In this notebook, we'll create a BYOB tool that:\n", + "\n", + "**#1. Set Up a Search Engine:** Use a public search API, such as Google's Custom Search API, to perform web searches and obtain a list of relevant search results. \n", + "\n", + "**#2. Build a Search Dictionary:** Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information. \n", + "\n", + "**#3. Generate a RAG Response:** Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user's query.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "1e95055b8cec006e", + "metadata": {}, + "source": [ + "### Use Case \n", + "In this cookbook, we'll take the example of a user who wants to list recent product launches by OpenAI in chronological order. Because the current GPT-4o model has a knowledge cutoff date, it is not expected that the model will know about recent product launches such as the o1-preview model launched in September 2024. \n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "d1ecc3b9dc1840d", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:07:34.124609Z", + "start_time": "2024-09-23T18:07:29.838089Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "OpenAI has had several notable product launches and updates in the past couple of years. Here’s a chronological list of some significant ones:\n", + "\n", + "1. **ChatGPT (November 2022)**: OpenAI launched an AI chatbot called ChatGPT, which is based on GPT-3.5. This chatbot became widely popular due to its impressive capabilities in understanding and generating human-like text.\n", + "\n", + "2. **GPT-4 (March 2023)**: OpenAI released GPT-4, the latest version of their Generative Pre-trained Transformer model. It brought improvements in both performance and accuracy over its predecessors.\n", + "\n", + "3. **DALL-E 2 (April 2022)**: The second version of DALL-E, an AI model that can generate images from textual descriptions, was launched with enhanced image resolution and more robust capabilities.\n", + "\n", + "4. **Whisper (September 2022)**: Whisper, an automatic speech recognition (ASR) system, was introduced. This model can handle multiple languages and is useful for transcribing and understanding spoken language.\n", + "\n", + "These are some of the key product launches from OpenAI in the past couple of years. Keep in mind the technology landscape is continually evolving, and new developments can occur.\n" + ] + } + ], + "source": [ + "from openai import OpenAI\n", + "\n", + "client = OpenAI()\n", + "\n", + "search_query = \"List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years\"\n", + "\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"gpt-4o\",\n", + " messages=[\n", + " {\"role\": \"system\", \"content\": \"You are a helpful agent.\"},\n", + " {\"role\": \"user\", \"content\": search_query}]\n", + ").choices[0].message.content\n", + "\n", + "print(response)" + ] + }, + { + "cell_type": "markdown", + "id": "d4e80aeaa52c8dc", + "metadata": {}, + "source": [ + "Given the knowledge cutoff, as expected the model does not know about the recent product launches by OpenAI." + ] + }, + { + "cell_type": "markdown", + "id": "9d34362ceef5a331", + "metadata": {}, + "source": [ + "### Setting up a BYOB tool\n", + "To provide the model with recent events information, we'll follow these steps:\n", + "\n", + "##### Step 1: Set Up a Search Engine to Provide Web Search Results\n", + "##### Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages\n", + "##### Step 3: Pass the information to the model to generate a RAG Response to the User Query \n", + "\n", + "\n", + "Before we begin, ensure you have the following: **Python 3.12 or later** installed on your machine. You will also need a Google Custom Search API key and Custom Search Engine ID (CSE ID). Necessary Python packages installed: `requests`, `beautifulsoup4`, `openai`. And ensure the OPENAI_API_KEY is set up as an environment variable." + ] + }, + { + "cell_type": "markdown", + "id": "1a766088c001c30b", + "metadata": {}, + "source": [ + "#### Step 1: Set Up a Search Engine to Provide Web Search Results\n", + "You can use any publicly available web search APIs to perform this task. We will configure a custom search engine using Google's Custom Search API. This engine will fetch a list of relevant web pages based on the user's query, focusing on obtaining the most recent and pertinent results. \n", + "\n", + "**a. Configure Search API key and Function:** Acquire a Google API key and a Custom Search Engine ID (CSE ID) from the Google Developers Console. You can navigate to this [Programmable Search Engine Link](https://developers.google.com/custom-search/v1/overview) to set up an API key as well as Custom Search Engine ID (CSE ID). \n", + "\n", + "The `search` function below sets up the search based on search term, the API and CSE ID keys, as well as number of search results to return. We'll introduce a parameter `site_filter` to restrict the output to only `openai.com`\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "7df836efe1589633", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:08:59.171800Z", + "start_time": "2024-09-23T18:08:59.164245Z" + } + }, + "outputs": [], + "source": [ + "import requests # For making HTTP requests to APIs and websites\n", + "\n", + "def search(search_item, api_key, cse_id, search_depth=10, site_filter=None):\n", + " service_url = 'https://www.googleapis.com/customsearch/v1'\n", + "\n", + " params = {\n", + " 'q': search_item,\n", + " 'key': api_key,\n", + " 'cx': cse_id,\n", + " 'num': search_depth\n", + " }\n", + "\n", + " try:\n", + " response = requests.get(service_url, params=params)\n", + " response.raise_for_status()\n", + " results = response.json()\n", + "\n", + " # Check if 'items' exists in the results\n", + " if 'items' in results:\n", + " if site_filter is not None:\n", + " \n", + " # Filter results to include only those with site_filter in the link\n", + " filtered_results = [result for result in results['items'] if site_filter in result['link']]\n", + "\n", + " if filtered_results:\n", + " return filtered_results\n", + " else:\n", + " print(f\"No results with {site_filter} found.\")\n", + " return []\n", + " else:\n", + " if 'items' in results:\n", + " return results['items']\n", + " else:\n", + " print(\"No search results found.\")\n", + " return []\n", + "\n", + " except requests.exceptions.RequestException as e:\n", + " print(f\"An error occurred during the search: {e}\")\n", + " return []\n" + ] + }, + { + "cell_type": "markdown", + "id": "dcee6754a2e6cd24", + "metadata": {}, + "source": [ + "**b. Identify the search terms for search engine:** Before we can retrieve specific results from a 3rd Party API, we may need to use Query Expansion to identify specific terms our browser search API should retrieve. **Query expansion** is a process where we broaden the original user query by adding related terms, synonyms, or variations. This technique is essential because search engines, like Google's Custom Search API, are often better at matching a range of related terms rather than just the natural language prompt used by a user. \n", + "\n", + "For example, searching with only the raw query `\"List the latest OpenAI product launches in chronological order from latest to oldest in the past 2 years\"` may return fewer and less relevant results than a more specific and direct search on a succinct phrase such as `\"Latest OpenAI product launches\"`. In the code below, we will use the user's original `search_query` to produce a more specific search term to use with the Google API to retrieve the results. " + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "3752702114df8160", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:09:00.816893Z", + "start_time": "2024-09-23T18:09:00.150843Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Latest OpenAI product launches\n" + ] + } + ], + "source": [ + "search_term = client.chat.completions.create(\n", + " model=\"gpt-4o\",\n", + " messages=[\n", + " {\"role\": \"system\", \"content\": \"Provide a google search term based on search query provided below in 3-4 words\"},\n", + " {\"role\": \"user\", \"content\": search_query}]\n", + ").choices[0].message.content\n", + "\n", + "print(search_term)" + ] + }, + { + "cell_type": "markdown", + "id": "62b7194aedbc3a21", + "metadata": {}, + "source": [ + "**c. Invoke the search function:** Now that we have the search term, we will invoke the search function to retrieve the results from Google search API. The results only have the link of the web page and a snippet at this point. In the next step, we will retrieve more information from the webpage and summarize it in a dictionary to pass to the model." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "891e924b15957206", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:09:03.324177Z", + "start_time": "2024-09-23T18:09:02.671631Z" + } + }, + "outputs": [], + "source": [ + "from dotenv import load_dotenv\n", + "import os\n", + "\n", + "load_dotenv('.env')\n", + "\n", + "api_key = os.getenv('API_KEY')\n", + "cse_id = os.getenv('CSE_ID')\n", + "\n", + "search_items = search(search_item=search_term, api_key=api_key, cse_id=cse_id, search_depth=10, site_filter=\"https://openai.com\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "ceedee1eb3ffec85", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:09:04.544840Z", + "start_time": "2024-09-23T18:09:04.542750Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Link: https://openai.com/news/\n", + "Snippet: Overview ; Product. Sep 12, 2024. Introducing OpenAI o1 ; Product. Jul 25, 2024. SearchGPT is a prototype of new AI search features ; Research. Jul 18, 2024. GPT- ...\n", + "\n", + "Link: https://openai.com/index/new-models-and-developer-products-announced-at-devday/\n", + "Snippet: Nov 6, 2023 ... GPT-4 Turbo with 128K context · We released the first version of GPT-4 in March and made GPT-4 generally available to all developers in July.\n", + "\n", + "Link: https://openai.com/news/product/\n", + "Snippet: Discover the latest product advancements from OpenAI and the ways they're being used by individuals and businesses.\n", + "\n", + "Link: https://openai.com/\n", + "Snippet: A new series of AI models designed to spend more time thinking before they respond. Learn more · (opens in a new window) ...\n", + "\n", + "Link: https://openai.com/index/sora/\n", + "Snippet: Feb 15, 2024 ... We plan to include C2PA metadata(opens in a new window) in the future if we deploy the model in an OpenAI product. In addition to us developing ...\n", + "\n", + "Link: https://openai.com/o1/\n", + "Snippet: We've developed a new series of AI models designed to spend more time thinking before they respond. Here is the latest news on o1 research, product and ...\n", + "\n", + "Link: https://openai.com/index/introducing-gpts/\n", + "Snippet: Nov 6, 2023 ... We plan to offer GPTs to more users soon. Learn more about our OpenAI DevDay announcements for new models and developer products.\n", + "\n", + "Link: https://openai.com/api/\n", + "Snippet: The most powerful platform for building AI products ... Build and scale AI experiences powered by industry-leading models and tools. Start building (opens in a ...\n", + "\n" + ] + } + ], + "source": [ + "for item in search_items:\n", + " print(f\"Link: {item['link']}\")\n", + " print(f\"Snippet: {item['snippet']}\\n\")" + ] + }, + { + "cell_type": "markdown", + "id": "c2f754f92866307e", + "metadata": {}, + "source": [ + "#### Step 2: Build a Search Dictionary with Titles, URLs, and Summaries of Web Pages\n", + "After obtaining the search results, we'll extract and organize the relevant information, so it can be passed to the LLM for final output. \n", + "\n", + "**a. Scrape Web Page Content:** For each URL in the search results, retrieve the web page to extract textual content while filtering out non-relevant data like scripts and advertisements as demonstrated in function `retrieve_content`. \n", + "\n", + "**b. Summarize Content:** Use an LLM to generate concise summaries of the scraped content, focusing on information pertinent to the user's query. Model can be provided the original search text, so it can focus on summarizing the content for the search intent as outlined in function `summarize_content`. \n", + " \n", + "**c. Create a Structured Dictionary:** Organize the data into a dictionary or a DataFrame containing the title, link, and summary for each web page. This structure can be passed on to the LLM to generate the summary with the appropriate citations. \n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "f4981ca230333116", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:09:16.847793Z", + "start_time": "2024-09-23T18:09:16.616732Z" + } + }, + "outputs": [], + "source": [ + "import requests\n", + "from bs4 import BeautifulSoup\n", + "\n", + "TRUNCATE_SCRAPED_TEXT = 50000 # Adjust based on your model's context window\n", + "SEARCH_DEPTH = 5\n", + "\n", + "def retrieve_content(url, max_tokens=TRUNCATE_SCRAPED_TEXT):\n", + " try:\n", + " headers = {'User-Agent': 'Mozilla/5.0'}\n", + " response = requests.get(url, headers=headers, timeout=10)\n", + " response.raise_for_status()\n", + "\n", + " soup = BeautifulSoup(response.content, 'html.parser')\n", + " for script_or_style in soup(['script', 'style']):\n", + " script_or_style.decompose()\n", + "\n", + " text = soup.get_text(separator=' ', strip=True)\n", + " characters = max_tokens * 4 # Approximate conversion\n", + " text = text[:characters]\n", + " return text\n", + " except requests.exceptions.RequestException as e:\n", + " print(f\"Failed to retrieve {url}: {e}\")\n", + " return None\n", + " \n", + "def summarize_content(content, search_term, character_limit=500):\n", + " prompt = (\n", + " f\"You are an AI assistant tasked with summarizing content relevant to '{search_term}'. \"\n", + " f\"Please provide a concise summary in {character_limit} characters or less.\"\n", + " )\n", + " try:\n", + " response = client.chat.completions.create(\n", + " model=\"gpt-4o-mini\",\n", + " messages=[\n", + " {\"role\": \"system\", \"content\": prompt},\n", + " {\"role\": \"user\", \"content\": content}]\n", + " )\n", + " summary = response.choices[0].message.content\n", + " return summary\n", + " except Exception as e:\n", + " print(f\"An error occurred during summarization: {e}\")\n", + " return None\n", + "\n", + "def get_search_results(search_items, character_limit=500):\n", + " # Generate a summary of search results for the given search term\n", + " results_list = []\n", + " for idx, item in enumerate(search_items, start=1):\n", + " url = item.get('link')\n", + " \n", + " snippet = item.get('snippet', '')\n", + " web_content = retrieve_content(url, TRUNCATE_SCRAPED_TEXT)\n", + " \n", + " if web_content is None:\n", + " print(f\"Error: skipped URL: {url}\")\n", + " else:\n", + " summary = summarize_content(web_content, search_term, character_limit)\n", + " result_dict = {\n", + " 'order': idx,\n", + " 'link': url,\n", + " 'title': snippet,\n", + " 'Summary': summary\n", + " }\n", + " results_list.append(result_dict)\n", + " return results_list" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "6b9afc6c933a6a67", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:09:36.415639Z", + "start_time": "2024-09-23T18:09:17.743365Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Search order: 1\n", + "Link: https://openai.com/news/\n", + "Snippet: Overview ; Product. Sep 12, 2024. Introducing OpenAI o1 ; Product. Jul 25, 2024. SearchGPT is a prototype of new AI search features ; Research. Jul 18, 2024. GPT- ...\n", + "Summary: OpenAI recently launched several notable products in 2024, including OpenAI o1 and SearchGPT, a prototype for enhanced AI search capabilities. Additionally, GPT-4o mini was introduced, enhancing cost-efficient intelligence. The organization also rolled out OpenAI for Nonprofits and ChatGPT Edu to support various sectors. Improvements in data analysis within ChatGPT and enhancements to the fine-tuning API were also announced. These updates reflect OpenAI's ongoing commitment to advancing AI technologies across different fields.\n", + "--------------------------------------------------------------------------------\n", + "Search order: 2\n", + "Link: https://openai.com/index/new-models-and-developer-products-announced-at-devday/\n", + "Snippet: Nov 6, 2023 ... GPT-4 Turbo with 128K context · We released the first version of GPT-4 in March and made GPT-4 generally available to all developers in July.\n", + "Summary: OpenAI's recent DevDay revealed several new products and model updates, including the launch of GPT-4 Turbo with a 128K context window, new pricing, and enhanced multimodal capabilities. Key features include the new Assistants API for developing specialized AI applications, improved function calling, and advanced capabilities like text-to-speech and DALL·E 3 integration. Additionally, OpenAI introduced a Copyright Shield for legal protection and Whisper v3 for improved speech recognition. Pricing reductions and rate limit increases were also announced across several models.\n", + "--------------------------------------------------------------------------------\n", + "Search order: 3\n", + "Link: https://openai.com/news/product/\n", + "Snippet: Discover the latest product advancements from OpenAI and the ways they're being used by individuals and businesses.\n", + "Summary: As of September 2024, OpenAI has launched several significant products, including OpenAI o1, a versatile AI tool, and SearchGPT, a prototype aimed at enhancing AI-driven search capabilities. Earlier, in May 2024, they introduced OpenAI for Education, emphasizing AI's integration into educational settings. Upcoming enhancements to existing products like GPT-4, DALL·E 3, and ChatGPT are also in focus, continuing OpenAI's mission to innovate across various sectors with cutting-edge AI technologies.\n", + "--------------------------------------------------------------------------------\n", + "Search order: 4\n", + "Link: https://openai.com/\n", + "Snippet: A new series of AI models designed to spend more time thinking before they respond. Learn more · (opens in a new window) ...\n", + "Summary: OpenAI has recently launched several innovative products, including the OpenAI o1 and o1-mini models which focus on enhanced reasoning capabilities. The partnership with Apple aims to integrate ChatGPT into Apple’s user experience. OpenAI also debuted \"Sora,\" a video generation tool from text prompts, and made significant upgrades to the ChatGPT Enterprise with new compliance tools. The introduction of structured outputs in the API and enhanced data analysis features are also notable advancements, further expanding the utility of AI in various domains.\n", + "--------------------------------------------------------------------------------\n", + "Search order: 5\n", + "Link: https://openai.com/index/sora/\n", + "Snippet: Feb 15, 2024 ... We plan to include C2PA metadata(opens in a new window) in the future if we deploy the model in an OpenAI product. In addition to us developing ...\n", + "Summary: OpenAI has launched Sora, an innovative AI model capable of generating high-quality text-to-video content. Sora can create videos up to one minute long, simulating complex scenes with motion and character interactions based on user prompts. The model uses advanced diffusion techniques, akin to its predecessors in the GPT and DALL·E families, enabling it to understand and animate real-world physics and nuances. OpenAI is working with external artists and domain experts to ensure safety and accuracy, while gathering feedback for future enhancements before wider release.\n", + "--------------------------------------------------------------------------------\n", + "Search order: 6\n", + "Link: https://openai.com/o1/\n", + "Snippet: We've developed a new series of AI models designed to spend more time thinking before they respond. Here is the latest news on o1 research, product and ...\n", + "Summary: OpenAI has introduced the o1 series, a new set of AI models aimed at improving response deliberation. This innovation allows models to \"think\" more before generating replies. The o1 models can be accessed via ChatGPT Plus and through APIs. Other recent advancements include updates to GPT-4, GPT-4o mini, and DALL·E 3. OpenAI continues to focus on enhancing product offerings for individual, team, and enterprise use, reflecting its commitment to research and safety in AI technologies.\n", + "--------------------------------------------------------------------------------\n", + "Search order: 7\n", + "Link: https://openai.com/index/introducing-gpts/\n", + "Snippet: Nov 6, 2023 ... We plan to offer GPTs to more users soon. Learn more about our OpenAI DevDay announcements for new models and developer products.\n", + "Summary: On November 6, 2023, OpenAI launched \"GPTs,\" allowing users to create customized versions of ChatGPT tailored to specific tasks without needing coding skills. These custom GPTs can assist in various activities, from learning games to workplace tasks. The upcoming GPT Store will feature creations from users, making them searchable and shareable. Enterprise users can develop internal-only versions, enhancing workplace productivity. Additionally, ChatGPT Plus users benefit from an improved interface that consolidates features like DALL·E and data analysis.\n", + "--------------------------------------------------------------------------------\n", + "Search order: 8\n", + "Link: https://openai.com/api/\n", + "Snippet: The most powerful platform for building AI products ... Build and scale AI experiences powered by industry-leading models and tools. Start building (opens in a ...\n", + "Summary: OpenAI has launched several notable products, including GPT-4o and GPT-4o mini, designed for complex and lightweight tasks respectively, both featuring a 128k context length. New models like OpenAI o1-preview and o1-mini enhance reasoning capabilities. The API platform offers various tools for building AI applications, including Chat Completions, Assistants, and Batch APIs. Enhanced customization options include Fine-tuning and a Custom Model Program. OpenAI's enterprise features emphasize security, compliance, and dedicated support, facilitating widespread innovative applications across sectors.\n", + "--------------------------------------------------------------------------------\n" + ] + } + ], + "source": [ + "results = get_search_results(search_items)\n", + "\n", + "for result in results:\n", + " print(f\"Search order: {result['order']}\")\n", + " print(f\"Link: {result['link']}\")\n", + " print(f\"Snippet: {result['title']}\")\n", + " print(f\"Summary: {result['Summary']}\")\n", + " print('-' * 80)" + ] + }, + { + "cell_type": "markdown", + "id": "c0603ea9003f7c1d", + "metadata": {}, + "source": [ + "We retrieved the most recent results. (Note these will vary depending on when you execute this script.) " + ] + }, + { + "cell_type": "markdown", + "id": "3f81cf3fd1a942c3", + "metadata": {}, + "source": [ + "#### Step 3: Pass the information to the model to generate a RAG Response to the User Query\n", + "With the search data organized in a JSON data structure, we will pass this information to the LLM with the original user query to generate the final response. Now, the LLM response includes information beyond its original knowledge cutoff, providing current insights." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "2894a01ce6c44d36", + "metadata": { + "ExecuteTime": { + "end_time": "2024-09-23T18:17:27.936015Z", + "start_time": "2024-09-23T18:17:09.751583Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Based on the search results provided, here is a chronological list of the latest OpenAI product launches from the past two years, ordered from the most recent to the oldest:\n", + "\n", + "1. **September 12, 2024**: **OpenAI o1**\n", + " - A versatile AI tool designed to enhance reasoning capabilities.\n", + " - Source: [OpenAI News](https://openai.com/news/)\n", + "\n", + "2. **July 25, 2024**: **SearchGPT**\n", + " - A prototype aimed at enhancing AI-driven search capabilities.\n", + " - Source: [OpenAI News](https://openai.com/news/)\n", + "\n", + "3. **July 18, 2024**: **GPT-4o mini**\n", + " - A cost-efficient intelligence model.\n", + " - Source: [OpenAI News](https://openai.com/news/)\n", + "\n", + "4. **May 2024**: **OpenAI for Education**\n", + " - Focuses on integrating AI into educational settings.\n", + " - Source: [OpenAI News](https://openai.com/news/product/)\n", + "\n", + "5. **February 15, 2024**: **Sora**\n", + " - An AI model capable of generating high-quality text-to-video content.\n", + " - Source: [OpenAI Sora](https://openai.com/index/sora/)\n", + "\n", + "6. **November 6, 2023**: **GPT-4 Turbo**\n", + " - Features a 128K context window and enhanced multimodal capabilities.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "\n", + "7. **November 6, 2023**: **GPTs**\n", + " - Allows users to create customized versions of ChatGPT tailored to specific tasks.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/introducing-gpts/)\n", + "\n", + "8. **March 2023**: **GPT-4**\n", + " - The first version of GPT-4 was released.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "\n", + "9. **July 2023**: **GPT-4 General Availability**\n", + " - GPT-4 was made generally available to all developers.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "\n", + "10. **2023**: **Whisper v3**\n", + " - An improved speech recognition model.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "\n", + "11. **2023**: **DALL·E 3 Integration**\n", + " - Enhanced capabilities for generating images from text prompts.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "\n", + "12. **2023**: **Assistants API**\n", + " - For developing specialized AI applications.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "\n", + "13. **2023**: **Copyright Shield**\n", + " - Legal protection for AI-generated content.\n", + " - Source: [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "\n", + "14. **2023**: **OpenAI for Nonprofits**\n", + " - Support for various sectors through AI.\n", + " - Source: [OpenAI News](https://openai.com/news/)\n", + "\n", + "15. **2023**: **ChatGPT Edu**\n", + " - Aimed at educational support.\n", + " - Source: [OpenAI News](https://openai.com/news/)\n", + "\n", + "16. **2023**: **ChatGPT Enterprise**\n", + " - New compliance tools and enhanced data analysis features.\n", + " - Source: [OpenAI](https://openai.com/)\n", + "\n", + "17. **2023**: **OpenAI o1-mini**\n", + " - A lightweight version of the OpenAI o1 model.\n", + " - Source: [OpenAI](https://openai.com/)\n", + "\n", + "18. **2023**: **OpenAI o1-preview**\n", + " - An early version of the OpenAI o1 model.\n", + " - Source: [OpenAI](https://openai.com/api/)\n", + "\n", + "19. **2023**: **Custom Model Program**\n", + " - Enhanced customization options for AI models.\n", + " - Source: [OpenAI](https://openai.com/api/)\n", + "\n", + "20. **2023**: **Fine-tuning API Enhancements**\n", + " - Improvements to the fine-tuning API.\n", + " - Source: [OpenAI News](https://openai.com/news/)\n", + "\n", + "### Sources:\n", + "- [OpenAI News](https://openai.com/news/)\n", + "- [OpenAI DevDay](https://openai.com/index/new-models-and-developer-products-announced-at-devday/)\n", + "- [OpenAI Sora](https://openai.com/index/sora/)\n", + "- [OpenAI API](https://openai.com/api/)\n", + "- [OpenAI](https://openai.com/)\n" + ] + } + ], + "source": [ + "import json \n", + "\n", + "final_prompt = (\n", + " f\"The user will provide a dictionary of search results in JSON format for search query {search_term} Based on on the search results provided by the user, provide a detailed response to this query: **'{search_query}'**. Make sure to cite all the sources at the end of your answer.\"\n", + ")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"gpt-4o\",\n", + " messages=[\n", + " {\"role\": \"system\", \"content\": final_prompt},\n", + " {\"role\": \"user\", \"content\": json.dumps(results)}],\n", + " temperature=0\n", + "\n", + ")\n", + "summary = response.choices[0].message.content\n", + "\n", + "print(summary)" + ] + }, + { + "cell_type": "markdown", + "id": "8b6beba8859f1bc7", + "metadata": {}, + "source": [ + "### Conclusion\n", + " \n", + "Large Language Models (LLMs) have a knowledge cutoff and may not be aware of recent events. To provide them with the latest information, you can build a Bring Your Own Browser (BYOB) tool using Python. This tool retrieves current web data and feeds it to the LLM, enabling up-to-date responses.\n", + "\n", + "The process involves three main steps:\n", + "\n", + "**#1 Set Up a Search Engine:** Use a public search API, like Google's Custom Search API, to perform web searches and obtain a list of relevant search results. \n", + "\n", + "**#2 Build a Search Dictionary:** Collect the title, URL, and a summary of each web page from the search results to create a structured dictionary of information. \n", + "\n", + "**#3. Generate a RAG Response:** Implement Retrieval-Augmented Generation (RAG) by passing the gathered information to the LLM, which then generates a final response to the user's query.\n", + "\n", + "By following these steps, you enhance the LLMs ability to provide up-to-date answers in your application that include the most recent developments, such as the latest product launches by OpenAI." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/registry.yaml b/registry.yaml index 9afac240d3..33d712fbbb 100644 --- a/registry.yaml +++ b/registry.yaml @@ -1598,3 +1598,11 @@ tags: - completions - reasoning + +- title: Building a Bring Your Own Browser (BYOB) Tool for Web Browsing and Summarization + path: examples/third_party/Web_search_with_google_api_bring_your_own_browser_tool.ipynb + date: 2024-09-26 + authors: + - msingh-openai + tags: + - web-browsing