{ "cells": [ { "cell_type": "markdown", "id": "fe12c203-e6a6-452c-a655-afb8a03a4ff5", "metadata": {}, "source": [ "# End of week 1 exercise\n", "\n", "To demonstrate your familiarity with OpenAI API, and also Ollama, build a tool that takes a technical question, \n", "and responds with an explanation. This is a tool that you will be able to use yourself during the course!" ] }, { "cell_type": "code", "execution_count": null, "id": "c1070317-3ed9-4659-abe3-828943230e03", "metadata": {}, "outputs": [], "source": [ "# imports\n", "import os\n", "import requests\n", "import json\n", "from typing import List\n", "from dotenv import load_dotenv\n", "from bs4 import BeautifulSoup\n", "from IPython.display import Markdown, display, update_display\n", "from openai import OpenAI\n" ] }, { "cell_type": "code", "execution_count": null, "id": "4a456906-915a-4bfd-bb9d-57e505c5093f", "metadata": {}, "outputs": [], "source": [ "# constants\n", "\n", "MODEL_GPT = 'gpt-4o-mini'\n", "MODEL_LLAMA = 'llama3.2'" ] }, { "cell_type": "code", "execution_count": null, "id": "a8d7923c-5f28-4c30-8556-342d7c8497c1", "metadata": {}, "outputs": [], "source": [ "# set up environment\n", "# Initialize and constants\n", "\n", "load_dotenv()\n", "api_key = os.getenv('OPENAI_API_KEY')\n", "\n", "if api_key and api_key.startswith('sk-proj-') and len(api_key)>10:\n", " print(\"API key looks good so far\")\n", "else:\n", " print(\"There might be a problem with your API key? Please visit the troubleshooting notebook!\")\n", " \n", "MODEL = 'gpt-4o-mini'\n", "openai = OpenAI()" ] }, { "cell_type": "code", "execution_count": null, "id": "38f13b72-eb43-4dbb-b80f-34f1625b6db8", "metadata": {}, "outputs": [], "source": [ "# A class to represent a Webpage\n", "\n", "class Website:\n", " \"\"\"\n", " A utility class to represent a Website that we have scraped, now with links\n", " \"\"\"\n", "\n", " def __init__(self, url):\n", " self.url = url\n", " response = requests.get(url)\n", " self.body = response.content\n", " soup = BeautifulSoup(self.body, 'html.parser')\n", " self.title = soup.title.string if soup.title else \"No title found\"\n", " if soup.body:\n", " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n", " irrelevant.decompose()\n", " self.text = soup.body.get_text(separator=\"\\n\", strip=True)\n", " else:\n", " self.text = \"\"\n", " links = [link.get('href') for link in soup.find_all('a')]\n", " self.links = [link for link in links if link]\n", "\n", " def get_contents(self):\n", " return f\"Webpage Title:\\n{self.title}\\nWebpage Contents:\\n{self.text}\\n\\n\"" ] }, { "cell_type": "code", "execution_count": null, "id": "1d853b19-28d7-49fe-a2af-b53b080b37bf", "metadata": {}, "outputs": [], "source": [ "ed=Website(\"https://www.edwarddonner.com\")\n", "ed.links" ] }, { "cell_type": "code", "execution_count": null, "id": "a64ccffe-06c5-49d9-ae06-067b6052f1ec", "metadata": {}, "outputs": [], "source": [ "#multi shots prmopting \n", "#shot 1) you should respond in JSON... \n", "#shot 2) you should also respond in multi colored text\n", "\n", "link_system_prompt = \"You are provided with a list of links found on a webpage. \\\n", "You are able to decide which of the links would be most relevant to include in a brochure about the company, \\\n", "such as links to an About page, or a Company page, or Careers/Jobs pages.\\n\"\n", "link_system_prompt += \"You should respond in yellow text.\"\n", "link_system_prompt += \"You should respond in JSON as in this example:\"\n", "link_system_prompt += \"\"\"\n", "{\n", " \"links\": [\n", " {\"type\": \"about page\", \"url\": \"https://full.url/goes/here/about\"},\n", " {\"type\": \"careers page\": \"url\": \"https://another.full.url/careers\"}\n", " ]\n", "}\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "id": "38c058d0-d326-40dd-9925-1644288865b1", "metadata": {}, "outputs": [], "source": [ "print(link_system_prompt)" ] }, { "cell_type": "code", "execution_count": null, "id": "ea606951-a65a-4075-a473-58e4cddaf096", "metadata": {}, "outputs": [], "source": [ "def get_links_user_prompt(website):\n", " user_prompt = f\"Here is the list of links on the website of {website.url} - \"\n", " user_prompt += \"please decide which of these are relevant web links for a brochure about the company, respond with the full https URL in JSON format. \\\n", "Do not include Terms of Service, Privacy, email links.\\n\"\n", " user_prompt += \"print output in yellow text\\n\"\n", " user_prompt += \"Links (some might be relative links):\\n\"\n", " user_prompt += \"\\n\".join(website.links)\n", " return user_prompt" ] }, { "cell_type": "code", "execution_count": null, "id": "96893ce7-865e-47e5-b637-2fab13305d5c", "metadata": {}, "outputs": [], "source": [ "print(get_links_user_prompt(ed))" ] }, { "cell_type": "code", "execution_count": null, "id": "716b214d-497e-49fb-a0de-5bf4edb0f6bd", "metadata": {}, "outputs": [], "source": [ "def get_links(url):\n", " website = Website(url)\n", " response = openai.chat.completions.create(\n", " model=MODEL,\n", " messages=[\n", " {\"role\": \"system\", \"content\": link_system_prompt},\n", " {\"role\": \"user\", \"content\": get_links_user_prompt(website)}\n", " ],\n", " response_format={\"type\": \"json_object\"}\n", " )\n", " result = response.choices[0].message.content\n", " return json.loads(result)" ] }, { "cell_type": "code", "execution_count": null, "id": "553b3d1c-4956-42d9-bd86-abaf764e3b5e", "metadata": {}, "outputs": [], "source": [ "anthropic = Website(\"https://edwarddonner.com\")\n", "anthropic.links" ] }, { "cell_type": "code", "execution_count": null, "id": "0d7b198d-a39f-4553-9432-0aaa8abbb0ec", "metadata": {}, "outputs": [], "source": [ "get_links(\"https://edwarddonner.com\")" ] }, { "cell_type": "code", "execution_count": null, "id": "9d160a9e-a129-4d4f-be34-4ccc4e570c03", "metadata": {}, "outputs": [], "source": [ "#make a brouchore now\n", "def get_all_details(url):\n", " result = \"Landing page:\\n\"\n", " result += Website(url).get_contents()\n", " links = get_links(url)\n", " print(\"Found links:\", links)\n", " for link in links[\"links\"]:\n", " result += f\"\\n\\n{link['type']}\\n\"\n", " result += Website(link[\"url\"]).get_contents()\n", " return result" ] }, { "cell_type": "code", "execution_count": null, "id": "6ce3de06-f228-4f8c-ad65-522b25c1dcf5", "metadata": {}, "outputs": [], "source": [ "print(get_all_details(\"https://edwarddonner.com\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "7c019742-9586-4061-96ff-912af9802bb5", "metadata": {}, "outputs": [], "source": [ "system_prompt = \"You are an assistant that analyzes the contents of several relevant pages from a company website \\\n", "and creates a short brochure about the company for prospective customers, investors and recruits. Respond in markdown.\\\n", "Include details of company culture, customers and careers/jobs if you have the information.\\\n", "Output should be displayed in mindmap diagram format.\\\n", "Also output should be in Hindi lanaguage.\"\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "8152a14f-91e8-4abc-89c7-6062934611fa", "metadata": {}, "outputs": [], "source": [ "def get_brochure_user_prompt(company_name, url):\n", " user_prompt = f\"You are looking at a company called: {company_name}\\n\"\n", " user_prompt += f\"Here are the contents of its landing page and other relevant pages; use this information to build a short brochure of the company in markdown.\\n\"\n", " user_prompt += get_all_details(url)\n", " user_prompt = user_prompt[:20_000] # Truncate if more than 20,000 characters\n", " return user_prompt" ] }, { "cell_type": "code", "execution_count": null, "id": "009ab063-eb0e-4d6e-b833-406277a0c70f", "metadata": {}, "outputs": [], "source": [ "get_brochure_user_prompt(\"Edward Donner\", \"https://edwarddonner.com\") " ] }, { "cell_type": "code", "execution_count": null, "id": "bcccadb8-11d6-4ddd-a24f-6ac1c2101419", "metadata": {}, "outputs": [], "source": [ "def create_brochure(company_name, url):\n", " response = openai.chat.completions.create(\n", " model=MODEL,\n", " messages=[\n", " {\"role\": \"system\", \"content\": system_prompt},\n", " {\"role\": \"user\", \"content\": get_brochure_user_prompt(company_name, url)}\n", " ],\n", " )\n", " result = response.choices[0].message.content\n", " display(Markdown(result))" ] }, { "cell_type": "code", "execution_count": null, "id": "3606b154-8d28-49ca-8028-c064f196fe20", "metadata": {}, "outputs": [], "source": [ "create_brochure(\"Anthropic\", \"https://anthropic.com\")" ] }, { "cell_type": "code", "execution_count": null, "id": "757b9f43-9c23-477b-9928-d6bbbf0394bb", "metadata": {}, "outputs": [], "source": [ "#stream brochure\n", "def stream_brochure(company_name, url):\n", " stream = openai.chat.completions.create(\n", " model=MODEL,\n", " messages=[\n", " {\"role\": \"system\", \"content\": system_prompt},\n", " {\"role\": \"user\", \"content\": get_brochure_user_prompt(company_name, url)}\n", " ],\n", " stream=True\n", " )\n", " \n", " response = \"\"\n", " display_handle = display(Markdown(\"\"), display_id=True)\n", " for chunk in stream:\n", " response += chunk.choices[0].delta.content or ''\n", " response = response.replace(\"```\",\"\").replace(\"markdown\", \"\")\n", " update_display(Markdown(response), display_id=display_handle.display_id)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ea4408f4-dbdc-4168-a843-034b9620fb38", "metadata": {}, "outputs": [], "source": [ "stream_brochure(\"HuggingFace\", \"https://huggingface.com\")" ] }, { "cell_type": "code", "execution_count": null, "id": "256765bb-a307-4fe0-9582-f03403a25e8d", "metadata": {}, "outputs": [], "source": [ "#define new system prompt for the question below\n", "\n", "system_prompt = \"Output should be in both English and Hindi lanaguage.\"" ] }, { "cell_type": "code", "execution_count": null, "id": "3f0d0137-52b0-47a8-81a8-11a90a010798", "metadata": {}, "outputs": [], "source": [ "# here is the question; type over this to ask something new , i.e. user_prompt\n", "\n", "user_prompt = question = \"\"\"\n", "Please explain what this code does and why:\n", "yield from {book.get(\"author\") for book in books if book.get(\"author\")}\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "id": "60ce7000-a4a5-4cce-a261-e75ef45063b4", "metadata": {}, "outputs": [], "source": [ "# Get gpt-4o-mini to answer, with streaming\n", "#stream result\n", "def stream_code_explanation():\n", " stream = openai.chat.completions.create(\n", " model=MODEL,\n", " messages=[\n", " {\"role\": \"system\", \"content\": system_prompt},\n", " {\"role\": \"user\", \"content\": user_prompt}\n", " ],\n", " stream=True\n", " )\n", " \n", " response = \"\"\n", " display_handle = display(Markdown(\"\"), display_id=True)\n", " for chunk in stream:\n", " response += chunk.choices[0].delta.content or ''\n", " response = response.replace(\"```\",\"\").replace(\"markdown\", \"\")\n", " update_display(Markdown(response), display_id=display_handle.display_id)" ] }, { "cell_type": "code", "execution_count": null, "id": "a7c79f95-6a4f-48b1-afed-42848e5d5975", "metadata": {}, "outputs": [], "source": [ "stream_code_explanation()" ] }, { "cell_type": "code", "execution_count": null, "id": "350eb627-23a3-4215-82be-e5b8f99280e2", "metadata": {}, "outputs": [], "source": [ "OLLAMA_API = \"http://localhost:11434/api/chat\"\n", "HEADERS = {\"Content-Type\": \"application/json\"}" ] }, { "cell_type": "code", "execution_count": null, "id": "652739e1-6edd-4b9d-8a44-8ea8191f45a4", "metadata": {}, "outputs": [], "source": [ "# Create a messages list using the same format that we used for OpenAI\n", "messages = [\n", " {\"role\": \"user\", \"content\": \"Please explain what this code does and why: yield from {book.get(\\\"author\\\") for book in books if book.get(\\\"author\\\")}\"}\n", "]" ] }, { "cell_type": "code", "execution_count": null, "id": "0d1b895b-1ba2-4ea2-95a5-fe7a798a4157", "metadata": {}, "outputs": [], "source": [ "payload = {\n", " \"model\": MODEL_LLAMA,\n", " \"messages\": messages,\n", " \"stream\": False\n", " }" ] }, { "cell_type": "code", "execution_count": null, "id": "8f7c8ea8-4082-4ad0-8751-3301adcf6538", "metadata": {}, "outputs": [], "source": [ "# Get Llama 3.2 to answer\n", "response = requests.post(OLLAMA_API, json=payload, headers=HEADERS)\n", "print(response.json()['message']['content'])" ] }, { "cell_type": "code", "execution_count": null, "id": "fd9b22dd-cc77-4f1d-80ca-da45fe122dab", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.10" } }, "nbformat": 4, "nbformat_minor": 5 }