Files
LLM_Engineering_OLD/week1/community-contributions/day1-dotabuff-summarization.ipynb

272 lines
8.4 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "032a76d2-a112-4c49-bd32-fe6c87f6ec19",
"metadata": {},
"source": [
"## Dota Game Assistant\n",
"\n",
"This script retrieves and summarizes information about a specified hero from `dotabuff.com` website"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04b24159-55d1-4eaf-bc19-474cec71cc3b",
"metadata": {},
"outputs": [],
"source": [
"!pip install selenium\n",
"!pip install webdriver-manager"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "14d26510-6613-4c1a-a346-159d906d111c",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"import os\n",
"import requests\n",
"from dotenv import load_dotenv\n",
"from bs4 import BeautifulSoup\n",
"from IPython.display import Markdown, display\n",
"from openai import OpenAI"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f9c8ea1e-8881-4f50-953d-ca7f462d8a32",
"metadata": {},
"outputs": [],
"source": [
"# Load environment variables in a file called .env\n",
"\n",
"load_dotenv(override=True)\n",
"api_key = os.getenv('OPENAI_API_KEY')\n",
"\n",
"# Check the key\n",
"\n",
"if not api_key:\n",
" print(\"No API key was found - please head over to the troubleshooting notebook in this folder to identify & fix!\")\n",
"elif not api_key.startswith(\"sk-proj-\"):\n",
" print(\"An API key was found, but it doesn't start sk-proj-; please check you're using the right key - see troubleshooting notebook\")\n",
"elif api_key.strip() != api_key:\n",
" print(\"An API key was found, but it looks like it might have space or tab characters at the start or end - please remove them - see troubleshooting notebook\")\n",
"else:\n",
" print(\"API key found and looks good so far!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "02febcac-9a21-4322-b2ea-748972312165",
"metadata": {},
"outputs": [],
"source": [
"openai = OpenAI()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bb7dd822-962e-4b34-a743-c14809764e4a",
"metadata": {},
"outputs": [],
"source": [
"# A class to represent a Webpage\n",
"\n",
"# Some websites need you to use proper headers when fetching them:\n",
"headers = {\n",
" \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\"\n",
"}\n",
"\n",
"from selenium import webdriver\n",
"from selenium.webdriver.chrome.service import Service\n",
"from selenium.webdriver.chrome.options import Options\n",
"from selenium.webdriver.common.by import By\n",
"from selenium.webdriver.support.ui import WebDriverWait\n",
"from selenium.webdriver.support import expected_conditions as EC\n",
"from webdriver_manager.chrome import ChromeDriverManager\n",
"from bs4 import BeautifulSoup\n",
"\n",
"class Website:\n",
" def __init__(self, url, wait_time=10):\n",
" \"\"\"\n",
" Create this Website object from the given URL using Selenium and BeautifulSoup.\n",
" Uses headless Chrome to load JavaScript content.\n",
" \"\"\"\n",
" self.url = url\n",
"\n",
" # Configure headless Chrome\n",
" options = Options()\n",
" options.headless = True\n",
" options.add_argument(\"--disable-gpu\")\n",
" options.add_argument(\"--no-sandbox\")\n",
"\n",
" # Start the driver\n",
" service = Service(ChromeDriverManager().install())\n",
" driver = webdriver.Chrome(service=service, options=options)\n",
"\n",
" try:\n",
" driver.get(url)\n",
"\n",
" # Wait until body is loaded (you can tweak the wait condition)\n",
" WebDriverWait(driver, wait_time).until(\n",
" EC.presence_of_element_located((By.TAG_NAME, \"body\"))\n",
" )\n",
"\n",
" html = driver.page_source\n",
" soup = BeautifulSoup(html, \"html.parser\")\n",
"\n",
" self.title = soup.title.string.strip() if soup.title else \"No title found\"\n",
"\n",
" # Remove unwanted tags\n",
" for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
" irrelevant.decompose()\n",
"\n",
" self.text = soup.body.get_text(separator=\"\\n\", strip=True)\n",
"\n",
" finally:\n",
" driver.quit()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9d833fbb-0115-4d99-a4e9-464f27900eab",
"metadata": {},
"outputs": [],
"source": [
"class DotaWebsite:\n",
" def __init__(self, hero):\n",
" web = Website(\"https://www.dotabuff.com/heroes\" + \"/\" + hero)\n",
" self.title = web.title\n",
" self.text = web.text"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a0a42c2b-c837-4d1b-b8f8-b2dbb8592a1a",
"metadata": {},
"outputs": [],
"source": [
"system_prompt = \"You are an game assistant that analyzes the contents of a website \\\n",
"and provides a short summary about facet selection, ability building, item building, best versus and worst versus, ignoring text that might be navigation related. \\\n",
"Respond in markdown.\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7c05843d-6373-4a76-8cca-9c716a6ca13a",
"metadata": {},
"outputs": [],
"source": [
"# A function that writes a User Prompt that asks for summaries of websites:\n",
"\n",
"def user_prompt_for(website):\n",
" user_prompt = f\"You are looking at a website titled {website.title}\"\n",
" user_prompt += \"\\nThe contents of this website is as follows; \\\n",
"please provide a short summary of provides a short summary about facet selection, ability building, item building, best versus and worst versus in markdown. \\\n",
"If it includes news or announcements, then summarize these too.\\n\\n\"\n",
" user_prompt += website.text\n",
" return user_prompt"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0145eee1-39e2-4f00-89ec-7acc6e375972",
"metadata": {},
"outputs": [],
"source": [
"# See how this function creates exactly the format above\n",
"\n",
"def messages_for(website):\n",
" return [\n",
" {\"role\": \"system\", \"content\": system_prompt},\n",
" {\"role\": \"user\", \"content\": user_prompt_for(website)}\n",
" ]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "76f389c0-572a-476b-9b4e-719c0ef10abb",
"metadata": {},
"outputs": [],
"source": [
"# And now: call the OpenAI API. You will get very familiar with this!\n",
"\n",
"def summarize(hero):\n",
" website = DotaWebsite(hero)\n",
" response = openai.chat.completions.create(\n",
" model = \"gpt-4o-mini\",\n",
" messages = messages_for(website)\n",
" )\n",
" return response.choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fcb046b7-52a9-49ff-b7bc-d8f6c279df4c",
"metadata": {},
"outputs": [],
"source": [
"# A function to display this nicely in the Jupyter output, using markdown\n",
"\n",
"def display_summary(hero):\n",
" summary = summarize(hero)\n",
" display(Markdown(summary))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9befb685-2912-41a9-b2d9-ae33001494c0",
"metadata": {},
"outputs": [],
"source": [
"display_summary(\"axe\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bf1bb1d9-0351-44fc-8ebf-91aa47a81b42",
"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.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}