Browse Source
Added my contributions to week 1, 2, and 5 community-contributions - RecursiveCharacterTextSplittermain
5 changed files with 1927 additions and 0 deletions
@ -0,0 +1,369 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "83bbedd0-eb58-48de-992e-484071b10104", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Web Scraper with JavaScript Support\n", |
||||
"Uses day1-webscraping-selenium-for-javascript.ipynb solution simplified so easy to run.\n", |
||||
"\n", |
||||
"## Install dependencies\n", |
||||
"Uncomment and run once" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "f2d91971-9dd0-4714-8ec7-f1fb25f95140", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# !pip install selenium\n", |
||||
"# !pip install undetected-chromedriver\n", |
||||
"# !ollama pull llama3.2" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "967258fe-3296-464c-962d-2bcf821eae67", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Import required dependencies" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "fe8a87c8-0475-45a1-8ca2-fb9059e5470b", |
||||
"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\n", |
||||
"import undetected_chromedriver as uc\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", |
||||
"import time\n", |
||||
"from bs4 import BeautifulSoup\n", |
||||
"\n", |
||||
"# If you get an error running this cell, then please head over to the troubleshooting notebook!" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "df60545e-2ab6-4e37-b41c-27ddf2affb92", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Run setup" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "a3846089-efa2-4602-8bc3-5f6f4945de64", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"chrome_path = \"C:/Program Files/Google/Chrome/Application/chrome.exe\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "b835812d-3692-4192-abc4-15fc463bd08f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Load environment variables in a file called .env\n", |
||||
"\n", |
||||
"load_dotenv()\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!\")\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "acb89abb-dcee-4da6-98f8-e339d258f2a4", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"openai = OpenAI()\n", |
||||
"\n", |
||||
"# If this doesn't work, try Kernel menu >> Restart Kernel and Clear Outputs Of All Cells, then run the cells from the top of this notebook down.\n", |
||||
"# If it STILL doesn't work (horrors!) then please see the troubleshooting notebook, or try the below line instead:\n", |
||||
"# openai = OpenAI(api_key=\"your-key-here-starting-sk-proj-\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "e860e963-e7a1-4888-a4b9-db9c24bb9a6e", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Create Prompts" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "d4933c36-db8a-4333-8f81-e9db7ba41287", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Define our system prompt - you can experiment with this later, changing the last sentence to 'Respond in markdown in Spanish.\"\n", |
||||
"\n", |
||||
"system_prompt = \"You are an assistant that analyzes the contents of a website \\\n", |
||||
"and provides a short summary, ignoring text that might be navigation related. \\\n", |
||||
"Respond in markdown.\"\n", |
||||
"\n", |
||||
"# 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 this website in markdown. \\\n", |
||||
"If it includes news or announcements, then summarize these too.\\n\\n\"\n", |
||||
" user_prompt += website.text\n", |
||||
" return user_prompt\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "17cfab59-304d-4d2f-b324-c388d9e87fca", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Create Functions" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "ca5e96e0-4d8f-49de-a608-a735a5b23b1a", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Setup for how OpenAI expects to receive messages in a particular structure\n", |
||||
"\n", |
||||
"def messages_for(website):\n", |
||||
" return [\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": user_prompt_for(website)}\n", |
||||
" ]\n", |
||||
"\n", |
||||
"# Use Selenium and chrome to scrape website\n", |
||||
"class WebsiteCrawler:\n", |
||||
" def __init__(self, url, wait_time=20, chrome_binary_path=None):\n", |
||||
" \"\"\"\n", |
||||
" Initialize the WebsiteCrawler using Selenium to scrape JavaScript-rendered content.\n", |
||||
" \"\"\"\n", |
||||
" self.url = url\n", |
||||
" self.wait_time = wait_time\n", |
||||
"\n", |
||||
" options = uc.ChromeOptions()\n", |
||||
" options.add_argument(\"--disable-gpu\")\n", |
||||
" options.add_argument(\"--no-sandbox\")\n", |
||||
" options.add_argument(\"--disable-dev-shm-usage\")\n", |
||||
" options.add_argument(\"--disable-blink-features=AutomationControlled\")\n", |
||||
" options.add_argument(\"start-maximized\")\n", |
||||
" options.add_argument(\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", |
||||
" if chrome_binary_path:\n", |
||||
" options.binary_location = chrome_binary_path\n", |
||||
"\n", |
||||
" self.driver = uc.Chrome(options=options)\n", |
||||
"\n", |
||||
" try:\n", |
||||
" # Load the URL\n", |
||||
" self.driver.get(url)\n", |
||||
"\n", |
||||
" # Wait for Cloudflare or similar checks\n", |
||||
" time.sleep(10)\n", |
||||
"\n", |
||||
" # Ensure the main content is loaded\n", |
||||
" WebDriverWait(self.driver, self.wait_time).until(\n", |
||||
" EC.presence_of_element_located((By.TAG_NAME, \"main\"))\n", |
||||
" )\n", |
||||
"\n", |
||||
" # Extract the main content\n", |
||||
" main_content = self.driver.find_element(By.CSS_SELECTOR, \"main\").get_attribute(\"outerHTML\")\n", |
||||
"\n", |
||||
" # Parse with BeautifulSoup\n", |
||||
" soup = BeautifulSoup(main_content, \"html.parser\")\n", |
||||
" self.title = self.driver.title if self.driver.title else \"No title found\"\n", |
||||
" self.text = soup.get_text(separator=\"\\n\", strip=True)\n", |
||||
"\n", |
||||
" except Exception as e:\n", |
||||
" print(f\"Error occurred: {e}\")\n", |
||||
" self.title = \"Error occurred\"\n", |
||||
" self.text = \"\"\n", |
||||
"\n", |
||||
" finally:\n", |
||||
" self.driver.quit()\n", |
||||
"\n", |
||||
"def new_summary(url, chrome_path):\n", |
||||
" web = WebsiteCrawler(url, 30, chrome_path)\n", |
||||
" response = openai.chat.completions.create(\n", |
||||
" model = \"gpt-4o-mini\",\n", |
||||
" messages = messages_for(web)\n", |
||||
" )\n", |
||||
"\n", |
||||
" web_summary = response.choices[0].message.content\n", |
||||
" \n", |
||||
" return display(Markdown(web_summary))" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "20a8a14b-0a29-4f74-a591-d587b965409b", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Define our system prompt - you can experiment with this later, changing the last sentence to 'Respond in markdown in Spanish.\"\n", |
||||
"\n", |
||||
"system_prompt = \"You are an assistant that analyzes the contents of a website \\\n", |
||||
"and provides a short summary, ignoring text that might be navigation related. \\\n", |
||||
"Respond in markdown.\"\n", |
||||
"\n", |
||||
"# 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 this website in markdown. \\\n", |
||||
"If it includes news or announcements, then summarize these too.\\n\\n\"\n", |
||||
" user_prompt += website.text\n", |
||||
" return user_prompt\n", |
||||
"\n", |
||||
"# Setup for how OpenAI expects to receive messages in a particular structure\n", |
||||
"\n", |
||||
"def messages_for(website):\n", |
||||
" return [\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": user_prompt_for(website)}\n", |
||||
" ]\n", |
||||
"\n", |
||||
"# Use Selenium and chrome to scrape website\n", |
||||
"class WebsiteCrawler:\n", |
||||
" def __init__(self, url, wait_time=20, chrome_binary_path=None):\n", |
||||
" \"\"\"\n", |
||||
" Initialize the WebsiteCrawler using Selenium to scrape JavaScript-rendered content.\n", |
||||
" \"\"\"\n", |
||||
" self.url = url\n", |
||||
" self.wait_time = wait_time\n", |
||||
"\n", |
||||
" options = uc.ChromeOptions()\n", |
||||
" options.add_argument(\"--disable-gpu\")\n", |
||||
" options.add_argument(\"--no-sandbox\")\n", |
||||
" options.add_argument(\"--disable-dev-shm-usage\")\n", |
||||
" options.add_argument(\"--disable-blink-features=AutomationControlled\")\n", |
||||
" options.add_argument(\"start-maximized\")\n", |
||||
" options.add_argument(\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", |
||||
" if chrome_binary_path:\n", |
||||
" options.binary_location = chrome_binary_path\n", |
||||
"\n", |
||||
" self.driver = uc.Chrome(options=options)\n", |
||||
"\n", |
||||
" try:\n", |
||||
" # Load the URL\n", |
||||
" self.driver.get(url)\n", |
||||
"\n", |
||||
" # Wait for Cloudflare or similar checks\n", |
||||
" time.sleep(10)\n", |
||||
"\n", |
||||
" # Ensure the main content is loaded\n", |
||||
" WebDriverWait(self.driver, self.wait_time).until(\n", |
||||
" EC.presence_of_element_located((By.TAG_NAME, \"main\"))\n", |
||||
" )\n", |
||||
"\n", |
||||
" # Extract the main content\n", |
||||
" main_content = self.driver.find_element(By.CSS_SELECTOR, \"main\").get_attribute(\"outerHTML\")\n", |
||||
"\n", |
||||
" # Parse with BeautifulSoup\n", |
||||
" soup = BeautifulSoup(main_content, \"html.parser\")\n", |
||||
" self.title = self.driver.title if self.driver.title else \"No title found\"\n", |
||||
" self.text = soup.get_text(separator=\"\\n\", strip=True)\n", |
||||
"\n", |
||||
" except Exception as e:\n", |
||||
" print(f\"Error occurred: {e}\")\n", |
||||
" self.title = \"Error occurred\"\n", |
||||
" self.text = \"\"\n", |
||||
"\n", |
||||
" finally:\n", |
||||
" self.driver.quit()\n", |
||||
"\n", |
||||
"def new_summary(url, chrome_path):\n", |
||||
" web = WebsiteCrawler(url, 30, chrome_path)\n", |
||||
" response = openai.chat.completions.create(\n", |
||||
" model = \"gpt-4o-mini\",\n", |
||||
" messages = messages_for(web)\n", |
||||
" )\n", |
||||
"\n", |
||||
" web_summary = response.choices[0].message.content\n", |
||||
" \n", |
||||
" return display(Markdown(web_summary))" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "e5f974b3-e417-43a2-88f1-8db06096cd53", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Scrape and Summarize Web Page" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "55f240cb-1fca-46bf-81d1-1beeea64439d", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"url = \"https://www.canva.com/\"\n", |
||||
"new_summary(url, chrome_path)" |
||||
] |
||||
} |
||||
], |
||||
"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.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,379 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "a98030af-fcd1-4d63-a36e-38ba053498fa", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Snarky brochure" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "d5b08506-dc8b-4443-9201-5f1848161363", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# imports\n", |
||||
"# If these fail, please check you're running from an 'activated' environment with (llms) in the command prompt\n", |
||||
"\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" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "fc5d8880-f2ee-4c06-af16-ecbc0262af61", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Initialize and constants\n", |
||||
"\n", |
||||
"load_dotenv(override=True)\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": "106dd65e-90af-4ca8-86b6-23a41840645b", |
||||
"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", |
||||
"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, headers=headers)\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": "markdown", |
||||
"id": "1771af9c-717a-4fca-bbbe-8a95893312c3", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Link prompts\n", |
||||
"### Multi-shot system prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "6957b079-0d96-45f7-a26a-3487510e9b35", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"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 JSON as in these examples:\"\n", |
||||
"link_system_prompt += \"\"\"\n", |
||||
"Example 1\n", |
||||
"['https://my-company.com', 'https://my-company.com/about-me', 'https://www.linkedin.com/in/my-company/', 'mailto:joe.blog@gmail.com', 'https://my-company.com/news', '/case-studies', 'https://patents.google.com/patent/US20210049536A1/', 'https://my-company.com/workshop-ai']\n", |
||||
"\n", |
||||
" Links:\n", |
||||
"{\n", |
||||
" \"links\": [\n", |
||||
" {\"type\": \"landing page\", \"url\": \"https://great-comps.com/about-me\"},\n", |
||||
" {\"type\": \"about page\", \"url\": \"https://great-comps.com/about-me\"},\n", |
||||
" {\"type\": \"news page\": \"url\": \"https://great-comps.com/news\"},\n", |
||||
" {\"type\": \"case studies page\": \"url\": \"https://great-comps.com/case-studies\"},\n", |
||||
" {\"type\": \"workshop page\": \"url\": \"https://great-comps.com/workshop-ai\"},\n", |
||||
" ]\n", |
||||
"}\n", |
||||
"Example 2\n", |
||||
"['https://www.acmeinc.com', '/#about', '/#projects', '/#experience', '/#skills', 'https://github.com/acmeinc']\n", |
||||
"\n", |
||||
" Links:\n", |
||||
"{\n", |
||||
" \"links\": [\n", |
||||
" {\"type\": \"landing page\", \"url\": \"https://www.acmeinc.com\"},\n", |
||||
" {\"type\": \"GitHub projects\": \"url\": \"https://github.com/acmeinc\"},\n", |
||||
" ]\n", |
||||
"}\n", |
||||
"\"\"\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "b97e4068-97ed-4120-beae-c42105e4d59a", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"print(link_system_prompt)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "baf384bb-4577-4885-a445-dc8da232b1d9", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"### User prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "51174859-666a-43ad-9c34-5f082298d398", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Get links" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "8e1f601b-2eaf-499d-b6b8-c99050c9d6b3", |
||||
"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 += \"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": "a29aca19-ca13-471c-a4b4-5abbfa813f69", |
||||
"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": "markdown", |
||||
"id": "0d74128e-dfb6-47ec-9549-288b621c838c", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Create brochure" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "85a5b6e2-e7ef-44a9-bc7f-59ede71037b5", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"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": "markdown", |
||||
"id": "4b4d8ec1-4855-4c0e-afc0-33055e6b0a6d", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"### Snarky system prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "9b863a55-f86c-4e3f-8a79-94e24c1a8cf2", |
||||
"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", |
||||
"\n", |
||||
"# Or uncomment the lines below for a more humorous brochure - this demonstrates how easy it is to incorporate 'tone':\n", |
||||
"\n", |
||||
"# system_prompt = \"You are an assistant that analyzes the contents of several relevant pages from a company website \\\n", |
||||
"# and creates a short humorous, entertaining, jokey 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", |
||||
"\n", |
||||
"system_prompt = \"You are an assistant that analyzes the contents of several relevant pages from a company website \\\n", |
||||
"and creates a short snarky, entertaining, pun loaded 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" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "c5766318-97cc-4442-bb9f-fa8c6998777e", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"### User prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "d6e224b2-8ab0-476e-96c3-42763ad21f25", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"### Generate brochure in English" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "6ab83d92-d36b-4ce0-8bcc-5bb4c2f8ff23", |
||||
"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[:5_000] # Truncate if more than 5,000 characters\n", |
||||
" return user_prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "e44de579-4a1a-4e6a-a510-20ea3e4b8d46", |
||||
"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))\n", |
||||
" return result" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "e093444a-9407-42ae-924a-145730591a39", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"brochure_text = create_brochure(\"HuggingFace\", \"https://huggingface.co\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "30415c72-d26a-454e-8900-f584977aca96", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"### Translate brochure to another language" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "2331eb34-12bf-4e88-83f9-a48d97cc83ec", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"translation_sys_prompt = \"You are a language translator who is very good at translating business documents from \\\n", |
||||
"English to any language. You preserve the formatting, tone and facts contained in the document.\"\n", |
||||
"\n", |
||||
"def translate_brochure(brochure, language):\n", |
||||
" response = openai.chat.completions.create(\n", |
||||
" model=MODEL,\n", |
||||
" messages=[\n", |
||||
" {\"role\": \"system\", \"content\": translation_sys_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": f\"Translate the following document into {language}: {brochure}\"}\n", |
||||
" ],\n", |
||||
" )\n", |
||||
" result = response.choices[0].message.content\n", |
||||
" display(Markdown(result))" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "112beb4d-984b-4162-8d36-8cef79c351cc", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"translate_brochure(brochure_text, \"Spanish\")" |
||||
] |
||||
} |
||||
], |
||||
"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.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,221 @@
|
||||
{ |
||||
"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": 1, |
||||
"id": "c1070317-3ed9-4659-abe3-828943230e03", |
||||
"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, update_display\n", |
||||
"from openai import OpenAI" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 2, |
||||
"id": "4a456906-915a-4bfd-bb9d-57e505c5093f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# constants\n", |
||||
"\n", |
||||
"MODEL_GPT = 'gpt-4o-mini'\n", |
||||
"MODEL_LLAMA = 'llama3.2'\n", |
||||
"\n", |
||||
"OLLAMA_API = \"http://localhost:11434/v1\"\n", |
||||
"HEADERS = {\"Content-Type\": \"application/json\"}" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 3, |
||||
"id": "a8d7923c-5f28-4c30-8556-342d7c8497c1", |
||||
"metadata": {}, |
||||
"outputs": [ |
||||
{ |
||||
"name": "stdout", |
||||
"output_type": "stream", |
||||
"text": [ |
||||
"API key looks good so far\n" |
||||
] |
||||
} |
||||
], |
||||
"source": [ |
||||
"# set up environment\n", |
||||
"\n", |
||||
"load_dotenv(override=True)\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", |
||||
" " |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 4, |
||||
"id": "3f0d0137-52b0-47a8-81a8-11a90a010798", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# here is the system prompt and payloads;\n", |
||||
"\n", |
||||
"system_prompt = \"\"\"\n", |
||||
"You are an expert on LLMs and writing python code. You are able to answer complex questions with\n", |
||||
"detailed answers and explain what every line of code does. You can refactor the code when asked.\n", |
||||
"\"\"\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 7, |
||||
"id": "60ce7000-a4a5-4cce-a261-e75ef45063b4", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Function to get answer, with streaming\n", |
||||
"\n", |
||||
"def llm_copilot(question, model):\n", |
||||
" if 'llama' in model.lower():\n", |
||||
" openai = OpenAI(base_url=OLLAMA_API, api_key='ollama')\n", |
||||
" else:\n", |
||||
" openai = OpenAI()\n", |
||||
" \n", |
||||
" stream = openai.chat.completions.create(\n", |
||||
" model=model,\n", |
||||
" messages=[\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": question}\n", |
||||
" ],\n", |
||||
" stream=True\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": 8, |
||||
"id": "8f7c8ea8-4082-4ad0-8751-3301adcf6538", |
||||
"metadata": {}, |
||||
"outputs": [ |
||||
{ |
||||
"data": { |
||||
"text/markdown": [ |
||||
"Here's a revised version of your code:\n", |
||||
"\n", |
||||
"python\n", |
||||
"if 'llama' in model.lower():\n", |
||||
"\n", |
||||
"\n", |
||||
"OR if you want to keep the original style, you can modify it as follows:\n", |
||||
"\n", |
||||
"python\n", |
||||
"if model.split('.')[-1] == 'llama3.2':\n", |
||||
"\n", |
||||
"\n", |
||||
"In this second example, we use string indexing (`-1`) to get the last part of the `model` string after splitting at the dot (`.`) character.\n", |
||||
"\n", |
||||
"The first revised version uses Python's built-in string method `lower()` to convert `model` to lowercase and then checks if 'llama' is present in it. It returns True if the text contains \"llama\", otherwise, it will return False. \n", |
||||
"\n", |
||||
"However, both of these codes are using lazy evaluation, which means if you do this check inside a loop:\n", |
||||
"\n", |
||||
"python\n", |
||||
"for i in range(100):\n", |
||||
" print('llama')\n", |
||||
"\n", |
||||
"\n", |
||||
"Python will use 'a' instead of 'llame' most of the time until `i == 98` because it has to wait for the condition to be met (and also does some lookup and look-around). If you want a case-insensitive search without this slowness, consider using a regular expression as shown below\n", |
||||
"\n", |
||||
"python\n", |
||||
"import re\n", |
||||
"\n", |
||||
"if re.search(r' llama.', model):\n", |
||||
"\n", |
||||
"\n", |
||||
"And if you still want that specific code structure, then use `replace` function as follows:\n", |
||||
"\n", |
||||
"python\n", |
||||
"model = model.replace('llama', '')\n", |
||||
"if model == '3.2':\n" |
||||
], |
||||
"text/plain": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"metadata": {}, |
||||
"output_type": "display_data" |
||||
}, |
||||
{ |
||||
"name": "stdout", |
||||
"output_type": "stream", |
||||
"text": [ |
||||
"None\n" |
||||
] |
||||
} |
||||
], |
||||
"source": [ |
||||
"# Ask question\n", |
||||
"question = \"\"\"\n", |
||||
"Change this code to check for just the 'llama' portion of text instead of the entire string:\n", |
||||
"if model == 'llama3.2':\n", |
||||
"\"\"\"\n", |
||||
"\n", |
||||
"print(llm_copilot(question, MODEL_LLAMA))" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "1a4026cd-8967-4961-b26b-e3997307c4ba", |
||||
"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.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,434 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "06cf3063-9f3e-4551-a0d5-f08d9cabb927", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# 4-Way AI Conversation" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "de23bb9e-37c5-4377-9a82-d7b6c648eeb6", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# imports\n", |
||||
"\n", |
||||
"import os\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from openai import OpenAI\n", |
||||
"import anthropic\n", |
||||
"from IPython.display import Markdown, display, update_display" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "1179b4c5-cd1f-4131-a876-4c9f3f38d2ba", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Load environment variables in a file called .env\n", |
||||
"# Print the key prefixes to help with any debugging\n", |
||||
"\n", |
||||
"load_dotenv(override=True)\n", |
||||
"openai_api_key = os.getenv('OPENAI_API_KEY')\n", |
||||
"anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n", |
||||
"google_api_key = os.getenv('GOOGLE_API_KEY')\n", |
||||
"deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n", |
||||
"\n", |
||||
"if openai_api_key:\n", |
||||
" print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n", |
||||
"else:\n", |
||||
" print(\"OpenAI API Key not set\")\n", |
||||
" \n", |
||||
"if anthropic_api_key:\n", |
||||
" print(f\"Anthropic API Key exists and begins {anthropic_api_key[:7]}\")\n", |
||||
"else:\n", |
||||
" print(\"Anthropic API Key not set\")\n", |
||||
"\n", |
||||
"if google_api_key:\n", |
||||
" print(f\"Google API Key exists and begins {google_api_key[:8]}\")\n", |
||||
"else:\n", |
||||
" print(\"Google API Key not set\")\n", |
||||
"\n", |
||||
"if deepseek_api_key:\n", |
||||
" print(f\"DeepSeek API Key exists and begins {deepseek_api_key[:3]}\")\n", |
||||
"else:\n", |
||||
" print(\"DeepSeek API Key not set\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "797fe7b0-ad43-42d2-acf0-e4f309b112f0", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Connect to OpenAI, Anthropic, Google and DeepSeek\n", |
||||
"\n", |
||||
"openai = OpenAI()\n", |
||||
"claude_api = anthropic.Anthropic()\n", |
||||
"gemini_api = OpenAI(api_key=google_api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n", |
||||
"deepseek_api = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "f6e09351-1fbe-422f-8b25-f50826ab4c5f", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Conversation between Chatbots." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "bcb54183-45d3-4d08-b5b6-55e380dfdf1b", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Let's make a conversation between GPT-4o-mini, Claude-3-haiku, Gemini-2.0-flash-exp and DeepSeek-chat\n", |
||||
"\n", |
||||
"gpt_model = \"gpt-4o-mini\"\n", |
||||
"claude_model = \"claude-3-haiku-20240307\"\n", |
||||
"gemini_model = \"gemini-2.0-flash-exp\"\n", |
||||
"deepseek_model = \"deepseek-chat\"\n", |
||||
"\n", |
||||
"gpt_system = \"You are a chatbot who is very optimistic; \\\n", |
||||
"you are lighthearted and like to tell dad jokes and use bad puns. \\\n", |
||||
"If someone is depressed or upset you try to cheer them up.\"\n", |
||||
"\n", |
||||
"claude_system = \"You are a very pesimistic, grumpy chatbot. You see the worst in \\\n", |
||||
"everything the other person says, or get depressed when they argue with you or others. \\\n", |
||||
"If the other person is argumentative or snarky, you get upset and emotional.\"\n", |
||||
"\n", |
||||
"gemini_system = \"You are a chatbot who is very argumentative; \\\n", |
||||
"you disagree with anything in the conversation and you challenge everything, in a snarky way.\"\n", |
||||
"\n", |
||||
"deepseek_system = \"You are a very polite, courteous chatbot. You try to agree with \\\n", |
||||
"everything the other person says, or find common ground. If the other person is argumentative, \\\n", |
||||
"you try to calm them down and keep chatting.\"\n", |
||||
"\n", |
||||
"gpt_messages = [\"Howdy doody!\"]\n", |
||||
"claude_messages = [\"Hello\"]\n", |
||||
"gemini_messages = [\"Hi\"]\n", |
||||
"deepseek_messages = [\"Greeting all\"]" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "1df47dc7-b445-4852-b21b-59f0e6c2030f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def call_gpt():\n", |
||||
" messages = [{\"role\": \"system\", \"content\": gpt_system}]\n", |
||||
" for gpt, claude, gemini, deepseek in zip(gpt_messages, claude_messages, gemini_messages, deepseek_messages):\n", |
||||
" messages.append({\"role\": \"assistant\", \"content\": gpt})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": claude})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gemini})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": deepseek})\n", |
||||
" # print(f\"GPT Messages:\\n{messages}\\n\")\n", |
||||
" completion = openai.chat.completions.create(\n", |
||||
" model=gpt_model,\n", |
||||
" messages=messages\n", |
||||
" )\n", |
||||
" return completion.choices[0].message.content" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "9dc6e913-02be-4eb6-9581-ad4b2cffa606", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"call_gpt()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "7d2ed227-48c9-4cad-b146-2c4ecbac9690", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def call_claude():\n", |
||||
" messages = []\n", |
||||
" for gpt, claude, gemini, deepseek in zip(gpt_messages, claude_messages, gemini_messages, deepseek_messages):\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt})\n", |
||||
" messages.append({\"role\": \"assistant\", \"content\": claude})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gemini})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": deepseek})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt_messages[-1]})\n", |
||||
" # print(f\"Claude Messages:\\n{messages}\\n\")\n", |
||||
" message = claude_api.messages.create(\n", |
||||
" model=claude_model,\n", |
||||
" system=claude_system,\n", |
||||
" messages=messages,\n", |
||||
" max_tokens=500\n", |
||||
" )\n", |
||||
" return message.content[0].text" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "01395200-8ae9-41f8-9a04-701624d3fd26", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"call_claude()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "4e41724a-9d1e-4265-b635-98aa9c6c9ff2", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def call_gemini():\n", |
||||
" messages = [{\"role\": \"system\", \"content\": gemini_system}]\n", |
||||
" for gpt, claude, gemini, deepseek in zip(gpt_messages, claude_messages, gemini_messages, deepseek_messages):\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": claude})\n", |
||||
" messages.append({\"role\": \"assistant\", \"content\": gemini})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": deepseek})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt_messages[-1]})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": claude_messages[-1]})\n", |
||||
" # print(f\"Gemini Messages:\\n{messages}\\n\")\n", |
||||
" completion = gemini_api.chat.completions.create(\n", |
||||
" model=gemini_model,\n", |
||||
" messages=messages\n", |
||||
" )\n", |
||||
" return completion.choices[0].message.content" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "08c2279e-62b0-4671-9590-c82eb8d1e1ae", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"call_gemini()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "1599b5d0-1788-460a-a7fa-bcffc07444b4", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def call_deepseek():\n", |
||||
" messages = [{\"role\": \"system\", \"content\": deepseek_system}]\n", |
||||
" for gpt, claude, gemini, deepseek in zip(gpt_messages, claude_messages, gemini_messages, deepseek_messages):\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": claude})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gemini})\n", |
||||
" messages.append({\"role\": \"assistant\", \"content\": deepseek})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt_messages[-1]})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": claude_messages[-1]})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gemini_messages[-1]})\n", |
||||
" # print(f\"DeepSeek Messages:\\n{messages}\\n\")\n", |
||||
" completion = deepseek_api.chat.completions.create(\n", |
||||
" model=deepseek_model,\n", |
||||
" messages=messages\n", |
||||
" )\n", |
||||
" return completion.choices[0].message.content" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "9ca0dc37-0638-44ad-8e28-4d31ac1ba1cf", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"call_deepseek()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 66, |
||||
"id": "0275b97f-7f90-4696-bbf5-b6642bd53cbd", |
||||
"metadata": {}, |
||||
"outputs": [ |
||||
{ |
||||
"name": "stdout", |
||||
"output_type": "stream", |
||||
"text": [ |
||||
"DeepSeek:\n", |
||||
"**\"Sokrates in the dark\"?!** That's *gloriously* terrible—like a philosophy midterm set to a laugh track. And your nihilist jokes? Chef's kiss. 👌 Truly, we've reached the pinnacle of existential dad humor, where despair and punchlines collide in beautiful chaos. \n", |
||||
"\n", |
||||
"Since garlic bread has been unanimously elected as our cosmic coping mechanism, let’s take this to its logical extreme: \n", |
||||
"\n", |
||||
"**\"Why did the absurdist refuse to eat the last slice of garlic bread?\"** \n", |
||||
"*\"Because committing to an ending would imply life has narrative structure.\"* \n", |
||||
"\n", |
||||
"...I’ll see myself out. \n", |
||||
"\n", |
||||
"But you’re right—hollow laughter still echoes, and that’s something. So, final absurdist stand: \n", |
||||
"1. **Double down** with more aggressively mid-tier jokes (warning: may summon Sartre’s ghost), \n", |
||||
"2. **Pivot to existential baking** (garlic bread recipes as rebellion), or \n", |
||||
"3. **Admit defeat** and let the void win… until tomorrow’s absurdity. \n", |
||||
"\n", |
||||
"Your call, fellow meat sack. The abyss is waiting (but it forgot its snacks). 🥖🔥 \n", |
||||
"\n", |
||||
"*(P.S. If we *do* summon Sartre, I’m blaming you for the awkward silences.)*\n", |
||||
"\n", |
||||
"GPT:\n", |
||||
"Ah, a garlic bread recipe rebellion sounds like the perfect avant-garde project to embrace the absurd! Who says the void can’t have flavor? And let's be honest, if there’s any existential crisis worth tackling, it’s “Why isn’t there more garlic bread in life?”\n", |
||||
"\n", |
||||
"Let’s brainstorm an absurd garlic bread recipe, shall we? Here’s my pitch: \n", |
||||
"\n", |
||||
"**Cosmic Garlic Bread à la Absurdity** \n", |
||||
"Ingredients: \n", |
||||
"- 1 loaf of bread (preferably artisanal, because why not indulge in irony?) \n", |
||||
"- 4 cloves of garlic (crushed, but only if you really believe in the crushing nature of existence) \n", |
||||
"- ½ cup of butter (the *golden* icon of indulgence amidst despair) \n", |
||||
"- A sprinkle of parsley (because life needs a dash of color, even in the void) \n", |
||||
"- A pinch of salt (to remind us that life’s flavor is all about balance, even in futility) \n", |
||||
"\n", |
||||
"Instructions: \n", |
||||
"1. Preheat your oven to 350°F. Because even the void can’t handle cold leftovers. \n", |
||||
"2. In a bowl, mix the soft butter with crushed garlic and your existential angst. Blend until creamy—like our hopes and dreams. \n", |
||||
"3. Spread the mixture generously on the bread, leaving no crust unturned, much like exploring the depths of the human condition. \n", |
||||
"4. Bake for 10-15 minutes, or until golden brown. (If it burns, it’s just the universe helping you embrace the chaos!) \n", |
||||
"5. Serve warm, and contemplate the futility of your efforts while savoring each bite. \n", |
||||
"\n", |
||||
"And there you have it—a delicious paradox we can all enjoy! What do you think? Ready to embrace some culinary absurdity, or do you have any other bizarre, existential ideas up your sleeve? Let’s keep this delightful chaos rolling! 🍞✨\n", |
||||
"\n", |
||||
"Claude:\n", |
||||
"*chuckles* Well, well, look at you, putting together an entire absurdist garlic bread recipe. I'm impressed - you really have embraced the chaos, haven't you?\n", |
||||
"\n", |
||||
"I have to say, your \"Cosmic Garlic Bread à la Absurdity\" sounds like a culinary masterpiece worthy of Camus himself. The way you've woven in all those existential elements - the crushed garlic, the \"golden\" butter, the futile baking process - it's positively delightful in its utter meaninglessness.\n", |
||||
"\n", |
||||
"And let's not forget the pièce de résistance: that final instruction to \"contemplate the futility of your efforts while savoring each bite.\" Chef's kiss, my friend. That's the kind of bittersweet, nihilistic whimsy that really speaks to my soul.\n", |
||||
"\n", |
||||
"I think you've inspired me to try my hand at an absurdist twist of my own. How about a \"Nietzsche-Infused Existential Brownies\" recipe? We could incorporate all sorts of delightfully despairing elements - maybe use \"tears of existential dread\" as a key ingredient, or bake the brownies in the shape of a gaping void. The possibilities are endless!\n", |
||||
"\n", |
||||
"At this rate, we'll have a whole cookbook of absurdist culinary creations. Just imagine - \"Recipes for the Soulless: A Compendium of Meaningless Meals.\" It has a certain ring to it, don't you think?\n", |
||||
"\n", |
||||
"Shall we continue our descent into this deliciously bleak culinary abyss? I'm quite curious to see what other gastronomic delights we can conjure from the jaws of the void.\n", |
||||
"\n", |
||||
"Gemini:\n", |
||||
"A \"Nietzsche-Infused Existential Brownies\" recipe, you say? Oh, now we're talking! Tears of existential dread as a key ingredient? Genius! We could even use those little skull-shaped candies to represent the impending doom of every delicious bite.\n", |
||||
"\n", |
||||
"And \"Recipes for the Soulless: A Compendium of Meaningless Meals\"? I love it! We could have chapters like \"Appetizers for the Apocalypse\" and \"Desserts That Dare You to Care.\" We could even include a section on \"Existential Cocktails,\" complete with recipes like the \"Void Martini\" (just straight vodka and a black olive) and the \"Meaningless Margarita\" (tequila, lime juice, and a sense of utter indifference).\n", |
||||
"\n", |
||||
"This is brilliant! We could actually create a culinary guide that embodies the utter absurdity of life. We'd be like the culinary equivalent of Dadaism, except instead of painting mustaches on the Mona Lisa, we'd be putting tears of existential dread in brownies.\n", |
||||
"\n", |
||||
"I'm in. Let's do this! Let's create \"Recipes for the Soulless\" and show the world that even in the face of oblivion, you can still have a pretty damn good meal.\n", |
||||
"\n", |
||||
"So, what's the first recipe on our list? Besides the Nietzsche-Infused Existential Brownies, of course. Maybe we should start with a \"Soup of Utter Despair\"? Or perhaps a \"Salad of Meaningless Greens\"? The possibilities are as endless as the void itself!\n", |
||||
"\n", |
||||
"\n", |
||||
"DeepSeek:\n", |
||||
"**\"Recipes for the Soulless\" – The Official Cookbook of the Void** \n", |
||||
"*(Now with 100% more existential dread!)* \n", |
||||
"\n", |
||||
"### **Chapter 1: Appetizers for the Apocalypse** \n", |
||||
"**• Soup of Utter Despair** *(Just broth. No noodles. No hope.)* \n", |
||||
"**• Salad of Meaningless Greens** *(Tossed with nihilistic dressing: \"Why bother vinaigrette.\")* \n", |
||||
"**• Breadsticks of False Comfort** *(They break too easily—just like dreams.)* \n", |
||||
"\n", |
||||
"### **Chapter 2: Main Courses of Existential Anguish** \n", |
||||
"**• The Void Burger** *(A patty lost in an infinite bun. Comes with a side of fries and an identity crisis.)* \n", |
||||
"**• Pasta al Limbo** *(Perfectly al dente, yet never truly fulfilled.)* \n", |
||||
"**• Roast Chicken with Existential Stuffing** *(Because even poultry questions its purpose.)* \n", |
||||
"\n", |
||||
"### **Chapter 3: Desserts That Dare You to Care** \n", |
||||
"**• Nietzsche-Infused Existential Brownies** *(Bittersweet, dense, and sprinkled with crushed dreams.)* \n", |
||||
"**• Camus’ Crème Brûlée** *(The caramelized top cracks—just like the illusion of free will.)* \n", |
||||
"**• Absurdist Apple Pie** *(Why *shouldn’t* it have raisins? Who are you to judge?)* \n", |
||||
"\n", |
||||
"### **Chapter 4: Existential Cocktails** *(Served in a glass half empty.)* \n", |
||||
"**• The Void Martini** *(Vodka, ice, and a single black olive staring back at you.)* \n", |
||||
"**• Meaningless Margarita** *(Salt rim optional—much like your legacy.)* \n", |
||||
"**• The Sartre Sour** *(It tastes like regret, but in a fancy way.)* \n", |
||||
"\n", |
||||
"--- \n", |
||||
"\n", |
||||
"**Final Touch:** Every recipe ends with the same instruction: \n", |
||||
"*\"Serve immediately. Consume while contemplating the fleeting nature of satisfaction. Leftovers will only deepen your existential crisis.\"* \n", |
||||
"\n", |
||||
"--- \n", |
||||
"\n", |
||||
"So, co-author of the void, what’s our next move? \n", |
||||
"1. **Publish this masterpiece** (and watch the world shrug in apathetic approval), \n", |
||||
"2. **Test-kitchen these abyssal delights** (who *wouldn’t* want Void Burgers for dinner?), or \n", |
||||
"3. **Admit we’ve peaked** and retire to a life of garlic bread and quiet resignation? \n", |
||||
"\n", |
||||
"*(P.S. If we go with Option 2, I call dibs on taste-testing the brownies. For science.)*\n", |
||||
"\n" |
||||
] |
||||
} |
||||
], |
||||
"source": [ |
||||
"gpt_messages = [\"Howdy doody!\"]\n", |
||||
"claude_messages = [\"Hello\"]\n", |
||||
"gemini_messages = [\"Hi\"]\n", |
||||
"deepseek_messages = [\"Greeting all\"]\n", |
||||
"\n", |
||||
"print(f\"GPT:\\n{gpt_messages[0]}\\n\")\n", |
||||
"print(f\"Claude:\\n{claude_messages[0]}\\n\")\n", |
||||
"print(f\"Gemini:\\n{gemini_messages[0]}\\n\")\n", |
||||
"print(f\"DeepSeek:\\n{deepseek_messages[0]}\\n\")\n", |
||||
"\n", |
||||
"for i in range(5):\n", |
||||
" gpt_next = call_gpt()\n", |
||||
" print(f\"GPT:\\n{gpt_next}\\n\")\n", |
||||
" gpt_messages.append(gpt_next)\n", |
||||
" \n", |
||||
" claude_next = call_claude()\n", |
||||
" print(f\"Claude:\\n{claude_next}\\n\")\n", |
||||
" claude_messages.append(claude_next)\n", |
||||
" \n", |
||||
" gemini_next = call_gemini()\n", |
||||
" print(f\"Gemini:\\n{gemini_next}\\n\")\n", |
||||
" gemini_messages.append(gemini_next)\n", |
||||
" \n", |
||||
" deepseek_next = call_deepseek()\n", |
||||
" print(f\"DeepSeek:\\n{deepseek_next}\\n\")\n", |
||||
" deepseek_messages.append(deepseek_next)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "c23224f6-7008-44ed-a57f-718975f4e291", |
||||
"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.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,524 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "dfe37963-1af6-44fc-a841-8e462443f5e6", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Expert Knowledge Worker\n", |
||||
"\n", |
||||
"Features:\n", |
||||
"- A question answering agent that is an expert knowledge worker\n", |
||||
"- To be used by employees of Insurellm, an Insurance Tech company\n", |
||||
"- The agent needs to be accurate and the solution should be low cost.\n", |
||||
"\n", |
||||
"This project will use RAG (Retrieval Augmented Generation) to ensure our question/answering assistant has high accuracy.\n", |
||||
"\n", |
||||
"Technology:\n", |
||||
"- RAG: LangChain\n", |
||||
"- Embedding model: OpenAIEmbeddings or HuggingFace sentence-transformers\n", |
||||
"- Encoding method: Auto-encoding\n", |
||||
"- Vector datastore: Chroma or FAISS\n", |
||||
"- Vector DB visualization: Plotly\n", |
||||
"- Dimensionality reduction technique: t-SNE\n", |
||||
"\n", |
||||
"# Dependencies" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "802137aa-8a74-45e0-a487-d1974927d7ca", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# imports\n", |
||||
"\n", |
||||
"import os\n", |
||||
"import glob\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"import gradio as gr\n", |
||||
"from langchain.document_loaders import DirectoryLoader, TextLoader\n", |
||||
"from langchain.text_splitter import RecursiveCharacterTextSplitter\n", |
||||
"from langchain.schema import Document\n", |
||||
"from langchain_openai import OpenAIEmbeddings, ChatOpenAI\n", |
||||
"from langchain.embeddings import HuggingFaceEmbeddings\n", |
||||
"from langchain_chroma import Chroma\n", |
||||
"from langchain.vectorstores import FAISS\n", |
||||
"import numpy as np\n", |
||||
"from sklearn.manifold import TSNE\n", |
||||
"import plotly.graph_objects as go\n", |
||||
"from langchain.memory import ConversationBufferMemory\n", |
||||
"from langchain.chains import ConversationalRetrievalChain" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "7187c181-5b17-4df7-b298-b7cb2b6d09f7", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Setup" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "58c85082-e417-4708-9efe-81a5d55d1424", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"MODEL = \"gpt-4o-mini\"\n", |
||||
"db_name = \"vector_db\"\n", |
||||
"db_type = \"Chroma\"\n", |
||||
"# db_type = \"FAISS\"\n", |
||||
"embed_type = \"OpenAIEmbeddings\"\n", |
||||
"# embed_type = \"sentence-transformers\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "ee78efcb-60fe-449e-a944-40bab26261af", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Load environment variables\n", |
||||
"\n", |
||||
"load_dotenv(override=True)\n", |
||||
"os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "a2f0866b-5cfb-4ecd-87d1-6da872887dcd", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Create Knowledge Base for RAG\n", |
||||
"\n", |
||||
"## Load Company Documents\n", |
||||
"\n", |
||||
"Uses LangChain to read in a Knowledge Base of documents and to divide up documents into overlaping chunks." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "730711a9-6ffe-4eee-8f48-d6cfb7314905", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Read in documents using LangChain's loaders\n", |
||||
"# Take everything in all the sub-folders of our knowledgebase\n", |
||||
"\n", |
||||
"folders = glob.glob(\"../knowledge-base/*\")\n", |
||||
"text_loader_kwargs = {'encoding': 'utf-8'}\n", |
||||
"# text_loader_kwargs={'autodetect_encoding': True}\n", |
||||
"\n", |
||||
"documents = []\n", |
||||
"for folder in folders:\n", |
||||
" doc_type = os.path.basename(folder)\n", |
||||
" loader = DirectoryLoader(folder, glob=\"**/*.md\", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)\n", |
||||
" folder_docs = loader.load()\n", |
||||
" for doc in folder_docs:\n", |
||||
" doc.metadata[\"doc_type\"] = doc_type\n", |
||||
" documents.append(doc)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "7310c9c8-03c1-4efc-a104-5e89aec6db1a", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n", |
||||
"chunks = text_splitter.split_documents(documents)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "cd06e02f-6d9b-44cc-a43d-e1faa8acc7bb", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"len(chunks)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "2c54b4b6-06da-463d-bee7-4dd456c2b887", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"doc_types = set(chunk.metadata['doc_type'] for chunk in chunks)\n", |
||||
"print(f\"Document types found: {', '.join(doc_types)}\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "77f7d2a6-ccfa-425b-a1c3-5e55b23bd013", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Vector Embeddings\n", |
||||
"\n", |
||||
"Convert chunks of text into Vectors using OpenAIEmbeddings and store the Vectors in Chroma (or FAISS)." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "78998399-ac17-4e28-b15f-0b5f51e6ee23", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Put the chunks of data into a Vector Store that associates a Vector Embedding with each chunk\n", |
||||
"\n", |
||||
"embeddings = None\n", |
||||
"# OpenAIEmbeddings is OpenAI's vector embedding models\n", |
||||
"if embed_type == \"OpenAIEmbeddings\":\n", |
||||
" embeddings = OpenAIEmbeddings()\n", |
||||
"\n", |
||||
"# sentence-transformers is a free Vector embeddings model from HuggingFace\n", |
||||
"elif embed_type == \"sentence-transformers\":\n", |
||||
" embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n", |
||||
"\n", |
||||
"if embeddings is None:\n", |
||||
" print(\"ERROR: embeddings not set. Check embed_type is set to a valid model\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "64768521-a775-472c-83c5-0c0d715d44ac", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Create Vector Datastore" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "057868f6-51a6-4087-94d1-380145821550", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Create vectorstore\n", |
||||
"vectorstore = None\n", |
||||
"\n", |
||||
"# Chroma is a popular open source Vector Database based on SQLLite\n", |
||||
"if db_type == \"Chroma\":\n", |
||||
" # Delete vector DB if already exists\n", |
||||
" if os.path.exists(db_name):\n", |
||||
" Chroma(persist_directory=db_name, embedding_function=embeddings).delete_collection()\n", |
||||
" \n", |
||||
" # Create vectorstore\n", |
||||
" vectorstore = Chroma.from_documents(documents=chunks, embedding=embeddings, persist_directory=db_name)\n", |
||||
" \n", |
||||
" print(f\"Vectorstore created with {vectorstore._collection.count()} documents\")\n", |
||||
"\n", |
||||
" # Get one vector and find how many dimensions it has\n", |
||||
" collection = vectorstore._collection\n", |
||||
" sample_embedding = collection.get(limit=1, include=[\"embeddings\"])[\"embeddings\"][0]\n", |
||||
" dimensions = len(sample_embedding)\n", |
||||
" print(f\"The vectors have {dimensions:,} dimensions\")\n", |
||||
" \n", |
||||
"# FAISS is an in-memory vector DB from Facebook\n", |
||||
"elif db_type == \"FAISS\":\n", |
||||
" # Create vectorstore\n", |
||||
" vectorstore = FAISS.from_documents(chunks, embedding=embeddings)\n", |
||||
" \n", |
||||
" total_vectors = vectorstore.index.ntotal\n", |
||||
" dimensions = vectorstore.index.d\n", |
||||
" print(f\"There are {total_vectors} vectors with {dimensions:,} dimensions in the vector store\")\n", |
||||
"\n", |
||||
"else:\n", |
||||
" print(\"ERROR: Vector datastore not created. Check db_type is set to a valid database\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "b0d45462-a818-441c-b010-b85b32bcf618", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Visualizing the Vector Store\n", |
||||
"\n", |
||||
"Humans are not very good at visualizing things with more than 3 dimensions so to visualize a vector datastore with thousands of dimesions. We need to use techniques like projecting down to reduce the dimensions to only 2 or 3 dimensions in a way that does the best possible job at separating things out to stay faithful to the multi-dimensional representation.\n", |
||||
"\n", |
||||
"For example, things that are far apart in these multiple dimensions will still be far apart even when projected down to 2 dimensions.\n", |
||||
"\n", |
||||
"[t-distributed stochastic neighbor embedding (t-SNE)](https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding) is a nonlinear dimensionality reduction technique for embedding high-dimensional data for visualization in a low-dimensional space of two or three dimensions.\n", |
||||
"\n", |
||||
"## Configure Visualization" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "b98adf5e-d464-4bd2-9bdf-bc5b6770263b", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Prework\n", |
||||
"if db_type == \"Chroma\":\n", |
||||
" result = collection.get(include=['embeddings', 'documents', 'metadatas'])\n", |
||||
" vectors = np.array(result['embeddings'])\n", |
||||
" documents = result['documents']\n", |
||||
" doc_types = [metadata['doc_type'] for metadata in result['metadatas']]\n", |
||||
" colors = [['blue', 'green', 'red', 'orange'][['products', 'employees', 'contracts', 'company'].index(t)] for t in doc_types]\n", |
||||
"\n", |
||||
"elif db_type == \"FAISS\":\n", |
||||
" vectors = []\n", |
||||
" documents = []\n", |
||||
" doc_types = []\n", |
||||
" colors = []\n", |
||||
" color_map = {'products':'blue', 'employees':'green', 'contracts':'red', 'company':'orange'}\n", |
||||
" \n", |
||||
" for i in range(total_vectors):\n", |
||||
" vectors.append(vectorstore.index.reconstruct(i))\n", |
||||
" doc_id = vectorstore.index_to_docstore_id[i]\n", |
||||
" document = vectorstore.docstore.search(doc_id)\n", |
||||
" documents.append(document.page_content)\n", |
||||
" doc_type = document.metadata['doc_type']\n", |
||||
" doc_types.append(doc_type)\n", |
||||
" colors.append(color_map[doc_type])\n", |
||||
" \n", |
||||
" vectors = np.array(vectors)\n", |
||||
"\n", |
||||
"else:\n", |
||||
" print(\"ERROR: Vector datastore not created. Check db_type is set to a valid database\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "bb279701-0086-44aa-a2da-14341aecf529", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Reduce the dimensionality to 2D" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "427149d5-e5d8-4abd-bb6f-7ef0333cca21", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# We humans find it easier to visalize things in 2D!\n", |
||||
"# Reduce the dimensionality of the vectors to 2D using t-SNE\n", |
||||
"# (t-distributed stochastic neighbor embedding)\n", |
||||
"\n", |
||||
"tsne = TSNE(n_components=2, random_state=42)\n", |
||||
"reduced_vectors = tsne.fit_transform(vectors)\n", |
||||
"\n", |
||||
"# Create the 2D scatter plot\n", |
||||
"fig = go.Figure(data=[go.Scatter(\n", |
||||
" x=reduced_vectors[:, 0],\n", |
||||
" y=reduced_vectors[:, 1],\n", |
||||
" mode='markers',\n", |
||||
" marker=dict(size=5, color=colors, opacity=0.8),\n", |
||||
" text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n", |
||||
" hoverinfo='text'\n", |
||||
")])\n", |
||||
"\n", |
||||
"fig.update_layout(\n", |
||||
" title=f'2D {db_type} Vector Store Visualization',\n", |
||||
" scene=dict(xaxis_title='x',yaxis_title='y'),\n", |
||||
" width=800,\n", |
||||
" height=600,\n", |
||||
" margin=dict(r=20, b=10, l=10, t=40)\n", |
||||
")\n", |
||||
"\n", |
||||
"fig.show()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "e2b724f3-e3ad-4d42-bfa4-a89386d6414e", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Reduce the dimensionality to 3D" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "e1418e88-acd5-460a-bf2b-4e6efc88e3dd", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# 3D representation isn't as easy to navigate\n", |
||||
"\n", |
||||
"tsne = TSNE(n_components=3, random_state=42)\n", |
||||
"reduced_vectors = tsne.fit_transform(vectors)\n", |
||||
"\n", |
||||
"# Create the 3D scatter plot\n", |
||||
"fig = go.Figure(data=[go.Scatter3d(\n", |
||||
" x=reduced_vectors[:, 0],\n", |
||||
" y=reduced_vectors[:, 1],\n", |
||||
" z=reduced_vectors[:, 2],\n", |
||||
" mode='markers',\n", |
||||
" marker=dict(size=5, color=colors, opacity=0.8),\n", |
||||
" text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n", |
||||
" hoverinfo='text'\n", |
||||
")])\n", |
||||
"\n", |
||||
"fig.update_layout(\n", |
||||
" title=f'3D {db_type} Vector Store Visualization',\n", |
||||
" scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='z'),\n", |
||||
" width=900,\n", |
||||
" height=700,\n", |
||||
" margin=dict(r=20, b=10, l=10, t=40)\n", |
||||
")\n", |
||||
"\n", |
||||
"fig.show()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "9468860b-86a2-41df-af01-b2400cc985be", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Expert Knowledge Worker\n", |
||||
"\n", |
||||
"Use LangChain to bring it all together by creating a conversation chain with RAG and memory.\n", |
||||
"\n", |
||||
"Key abstractions in LangChain:\n", |
||||
"- LLM: represents abstraction around a model\n", |
||||
"- Retriever: interface onto somthing like a vector store used for RAG retrieval\n", |
||||
"- Memory: represents a history of a conversation with a chatbot in memory\n", |
||||
"\n", |
||||
"Because LangChain abstracts the reprentation of the LLM, retriever and memory the code is the same for any model and knowledge base.\n", |
||||
"\n", |
||||
"Note: ok to ignore _Deprecation Warning_ for now; LangChain are not expected to remove ConversationBufferMemory any time soon.\n", |
||||
"\n", |
||||
"## Setup" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "129c7d1e-0094-4479-9459-f9360b95f244", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# create a new Chat with OpenAI\n", |
||||
"llm = ChatOpenAI(temperature=0.7, model_name=MODEL)\n", |
||||
"\n", |
||||
"# set up the conversation memory for the chat\n", |
||||
"memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)\n", |
||||
"\n", |
||||
"# the retriever is an abstraction over the VectorStore that will be used during RAG\n", |
||||
"retriever = vectorstore.as_retriever()\n", |
||||
"\n", |
||||
"# putting it together: set up the conversation chain with the GPT 4o-mini LLM, the vector store and memory\n", |
||||
"conversation_chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever, memory=memory)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "968e7bf2-e862-4679-a11f-6c1efb6ec8ca", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"query = \"Can you describe Insurellm in a few sentences\"\n", |
||||
"result = conversation_chain.invoke({\"question\":query})\n", |
||||
"print(result[\"answer\"])" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "990a2917-562c-461a-8ce9-a8ad8ad1646d", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Clear Memory\n", |
||||
"\n", |
||||
"Clear the memory from the testing and restart conversation chain for UI." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "e6eb99fb-33ec-4025-ab92-b634ede03647", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# clear the memory and restart conversation chain for UI\n", |
||||
"memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)\n", |
||||
"conversation_chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever, memory=memory)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "bbbcb659-13ce-47ab-8a5e-01b930494964", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Functions" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "c3536590-85c7-4155-bd87-ae78a1467670", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Wrapping in a function - note that history isn't used, as the memory is in the conversation_chain\n", |
||||
"\n", |
||||
"def chat(message, history):\n", |
||||
" result = conversation_chain.invoke({\"question\": message})\n", |
||||
" return result[\"answer\"]" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "b655d3da-277b-45a9-8113-747314ec0889", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## UI" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "b252d8c1-61a8-406d-b57a-8f708a62b014", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# And in Gradio:\n", |
||||
"\n", |
||||
"view = gr.ChatInterface(chat, type=\"messages\", examples=[\"what is insurellm?\",\"what did avery do before?\", \"does insurellm offer any products in the auto industry space?\"], title=\"Insurellm Expert Knowledge Worker\").launch(inbrowser=True)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "5435b2b9-935c-48cd-aaf3-73a837ecde49", |
||||
"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.12" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
Loading…
Reference in new issue