From d8b4c7d203aa95f11986dc5ed8ae324ff8f94bcd Mon Sep 17 00:00:00 2001
From: Sanath Pabba <66142644+sanathpabba@users.noreply.github.com>
Date: Mon, 6 Jan 2025 22:59:15 -0500
Subject: [PATCH 01/61] Add files via upload
---
.../day1_email_reviewer.ipynb | 906 ++++++++++++++++++
1 file changed, 906 insertions(+)
create mode 100644 week1/community-contributions/day1_email_reviewer.ipynb
diff --git a/week1/community-contributions/day1_email_reviewer.ipynb b/week1/community-contributions/day1_email_reviewer.ipynb
new file mode 100644
index 0000000..015fc43
--- /dev/null
+++ b/week1/community-contributions/day1_email_reviewer.ipynb
@@ -0,0 +1,906 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "d15d8294-3328-4e07-ad16-8a03e9bbfdb9",
+ "metadata": {},
+ "source": [
+ "# Instant Gratification\n",
+ "\n",
+ "## Your first Frontier LLM Project!\n",
+ "\n",
+ "Let's build a useful LLM solution - in a matter of minutes.\n",
+ "\n",
+ "By the end of this course, you will have built an autonomous Agentic AI solution with 7 agents that collaborate to solve a business problem. All in good time! We will start with something smaller...\n",
+ "\n",
+ "Our goal is to code a new kind of Web Browser. Give it a URL, and it will respond with a summary. The Reader's Digest of the internet!!\n",
+ "\n",
+ "Before starting, you should have completed the setup for [PC](../SETUP-PC.md) or [Mac](../SETUP-mac.md) and you hopefully launched this jupyter lab from within the project root directory, with your environment activated.\n",
+ "\n",
+ "## If you're new to Jupyter Lab\n",
+ "\n",
+ "Welcome to the wonderful world of Data Science experimentation! Once you've used Jupyter Lab, you'll wonder how you ever lived without it. Simply click in each \"cell\" with code in it, such as the cell immediately below this text, and hit Shift+Return to execute that cell. As you wish, you can add a cell with the + button in the toolbar, and print values of variables, or try out variations. \n",
+ "\n",
+ "I've written a notebook called [Guide to Jupyter](Guide%20to%20Jupyter.ipynb) to help you get more familiar with Jupyter Labs, including adding Markdown comments, using `!` to run shell commands, and `tqdm` to show progress.\n",
+ "\n",
+ "## If you'd prefer to work in IDEs\n",
+ "\n",
+ "If you're more comfortable in IDEs like VSCode or Pycharm, they both work great with these lab notebooks too. \n",
+ "If you'd prefer to work in VSCode, [here](https://chatgpt.com/share/676f2e19-c228-8012-9911-6ca42f8ed766) are instructions from an AI friend on how to configure it for the course.\n",
+ "\n",
+ "## If you'd like to brush up your Python\n",
+ "\n",
+ "I've added a notebook called [Intermediate Python](Intermediate%20Python.ipynb) to get you up to speed. But you should give it a miss if you already have a good idea what this code does: \n",
+ "`yield from {book.get(\"author\") for book in books if book.get(\"author\")}`\n",
+ "\n",
+ "## I am here to help\n",
+ "\n",
+ "If you have any problems at all, please do reach out. \n",
+ "I'm available through the platform, or at ed@edwarddonner.com, or at https://www.linkedin.com/in/eddonner/ if you'd like to connect (and I love connecting!)\n",
+ "\n",
+ "## More troubleshooting\n",
+ "\n",
+ "Please see the [troubleshooting](troubleshooting.ipynb) notebook in this folder to diagnose and fix common problems. At the very end of it is a diagnostics script with some useful debug info.\n",
+ "\n",
+ "## If this is old hat!\n",
+ "\n",
+ "If you're already comfortable with today's material, please hang in there; you can move swiftly through the first few labs - we will get much more in depth as the weeks progress.\n",
+ "\n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Please read - important note\n",
+ " The way I collaborate with you may be different to other courses you've taken. I prefer not to type code while you watch. Rather, I execute Jupyter Labs, like this, and give you an intuition for what's going on. My suggestion is that you do this with me, either at the same time, or (perhaps better) right afterwards. Add print statements to understand what's going on, and then come up with your own variations. If you have a Github account, use this to showcase your variations. Not only is this essential practice, but it demonstrates your skills to others, including perhaps future clients or employers...\n",
+ " | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Business value of these exercises\n",
+ " A final thought. While I've designed these notebooks to be educational, I've also tried to make them enjoyable. We'll do fun things like have LLMs tell jokes and argue with each other. But fundamentally, my goal is to teach skills you can apply in business. I'll explain business implications as we go, and it's worth keeping this in mind: as you build experience with models and techniques, think of ways you could put this into action at work today. Please do contact me if you'd like to discuss more or if you have ideas to bounce off me.\n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
+ "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",
+ "\n",
+ "# If you get an error running this cell, then please head over to the troubleshooting notebook!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6900b2a8-6384-4316-8aaa-5e519fca4254",
+ "metadata": {},
+ "source": [
+ "# Connecting to OpenAI\n",
+ "\n",
+ "The next cell is where we load in the environment variables in your `.env` file and connect to OpenAI.\n",
+ "\n",
+ "## Troubleshooting if you have problems:\n",
+ "\n",
+ "Head over to the [troubleshooting](troubleshooting.ipynb) notebook in this folder for step by step code to identify the root cause and fix it!\n",
+ "\n",
+ "If you make a change, try restarting the \"Kernel\" (the python process sitting behind this notebook) by Kernel menu >> Restart Kernel and Clear Outputs of All Cells. Then try this notebook again, starting at the top.\n",
+ "\n",
+ "Or, contact me! Message me or email ed@edwarddonner.com and we will get this to work.\n",
+ "\n",
+ "Any concerns about API costs? See my notes in the README - costs should be minimal, and you can control it at every point. You can also use Ollama as a free alternative, which we discuss during Day 2."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "API key found and looks good so far!\n"
+ ]
+ }
+ ],
+ "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!\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3",
+ "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 in this folder for full instructions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "442fc84b-0815-4f40-99ab-d9a5da6bda91",
+ "metadata": {},
+ "source": [
+ "# Let's make a quick call to a Frontier model to get started, as a preview!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "a58394bf-1e45-46af-9bfd-01e24da6f49a",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hello! Welcome! I'm glad to see your first message here. How can I assist you today?\n"
+ ]
+ }
+ ],
+ "source": [
+ "# To give you a preview -- calling OpenAI with these messages is this easy. Any problems, head over to the Troubleshooting notebook.\n",
+ "\n",
+ "message = \"Hello, GPT! This is my first ever message to you! Hi!\"\n",
+ "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=[{\"role\":\"user\", \"content\":message}])\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2aa190e5-cb31-456a-96cc-db109919cd78",
+ "metadata": {},
+ "source": [
+ "## OK onwards with our first project"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "c5e793b2-6775-426a-a139-4848291d0463",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A class to represent a Webpage\n",
+ "# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\n",
+ " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
+ " irrelevant.decompose()\n",
+ " self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Home - Edward Donner\n",
+ "Home\n",
+ "Outsmart\n",
+ "An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
+ "About\n",
+ "Posts\n",
+ "Well, hi there.\n",
+ "I’m Ed. I like writing code and experimenting with LLMs, and hopefully you’re here because you do too. I also enjoy DJing (but I’m badly out of practice), amateur electronic music production (\n",
+ "very\n",
+ "amateur) and losing myself in\n",
+ "Hacker News\n",
+ ", nodding my head sagely to things I only half understand.\n",
+ "I’m the co-founder and CTO of\n",
+ "Nebula.io\n",
+ ". We’re applying AI to a field where it can make a massive, positive impact: helping people discover their potential and pursue their reason for being. Recruiters use our product today to source, understand, engage and manage talent. I’m previously the founder and CEO of AI startup untapt,\n",
+ "acquired in 2021\n",
+ ".\n",
+ "We work with groundbreaking, proprietary LLMs verticalized for talent, we’ve\n",
+ "patented\n",
+ "our matching model, and our award-winning platform has happy customers and tons of press coverage.\n",
+ "Connect\n",
+ "with me for more!\n",
+ "December 21, 2024\n",
+ "Welcome, SuperDataScientists!\n",
+ "November 13, 2024\n",
+ "Mastering AI and LLM Engineering – Resources\n",
+ "October 16, 2024\n",
+ "From Software Engineer to AI Data Scientist – resources\n",
+ "August 6, 2024\n",
+ "Outsmart LLM Arena – a battle of diplomacy and deviousness\n",
+ "Navigation\n",
+ "Home\n",
+ "Outsmart\n",
+ "An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
+ "About\n",
+ "Posts\n",
+ "Get in touch\n",
+ "ed [at] edwarddonner [dot] com\n",
+ "www.edwarddonner.com\n",
+ "Follow me\n",
+ "LinkedIn\n",
+ "Twitter\n",
+ "Facebook\n",
+ "Subscribe to newsletter\n",
+ "Type your email…\n",
+ "Subscribe\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Let's try one out. Change the website and add print statements to follow along.\n",
+ "\n",
+ "ed = Website(\"https://edwarddonner.com\")\n",
+ "print(ed.title)\n",
+ "print(ed.text)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a478a0c-2c53-48ff-869c-4d08199931e1",
+ "metadata": {},
+ "source": [
+ "## Types of prompts\n",
+ "\n",
+ "You may know this already - but if not, you will get very familiar with it!\n",
+ "\n",
+ "Models like GPT4o have been trained to receive instructions in a particular way.\n",
+ "\n",
+ "They expect to receive:\n",
+ "\n",
+ "**A system prompt** that tells them what task they are performing and what tone they should use\n",
+ "\n",
+ "**A user prompt** -- the conversation starter that they should reply to"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "abdb8417-c5dc-44bc-9bee-2e059d162699",
+ "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.\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "f0275b1b-7cfe-4f9d-abfa-7650d378da0c",
+ "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 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"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "26448ec4-5c00-4204-baec-7df91d11ff2e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "You are looking at a website titled Home - Edward Donner\n",
+ "The contents of this website is as follows; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\n",
+ "\n",
+ "Home\n",
+ "Outsmart\n",
+ "An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
+ "About\n",
+ "Posts\n",
+ "Well, hi there.\n",
+ "I’m Ed. I like writing code and experimenting with LLMs, and hopefully you’re here because you do too. I also enjoy DJing (but I’m badly out of practice), amateur electronic music production (\n",
+ "very\n",
+ "amateur) and losing myself in\n",
+ "Hacker News\n",
+ ", nodding my head sagely to things I only half understand.\n",
+ "I’m the co-founder and CTO of\n",
+ "Nebula.io\n",
+ ". We’re applying AI to a field where it can make a massive, positive impact: helping people discover their potential and pursue their reason for being. Recruiters use our product today to source, understand, engage and manage talent. I’m previously the founder and CEO of AI startup untapt,\n",
+ "acquired in 2021\n",
+ ".\n",
+ "We work with groundbreaking, proprietary LLMs verticalized for talent, we’ve\n",
+ "patented\n",
+ "our matching model, and our award-winning platform has happy customers and tons of press coverage.\n",
+ "Connect\n",
+ "with me for more!\n",
+ "December 21, 2024\n",
+ "Welcome, SuperDataScientists!\n",
+ "November 13, 2024\n",
+ "Mastering AI and LLM Engineering – Resources\n",
+ "October 16, 2024\n",
+ "From Software Engineer to AI Data Scientist – resources\n",
+ "August 6, 2024\n",
+ "Outsmart LLM Arena – a battle of diplomacy and deviousness\n",
+ "Navigation\n",
+ "Home\n",
+ "Outsmart\n",
+ "An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
+ "About\n",
+ "Posts\n",
+ "Get in touch\n",
+ "ed [at] edwarddonner [dot] com\n",
+ "www.edwarddonner.com\n",
+ "Follow me\n",
+ "LinkedIn\n",
+ "Twitter\n",
+ "Facebook\n",
+ "Subscribe to newsletter\n",
+ "Type your email…\n",
+ "Subscribe\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(user_prompt_for(ed))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ea211b5f-28e1-4a86-8e52-c0b7677cadcc",
+ "metadata": {},
+ "source": [
+ "## Messages\n",
+ "\n",
+ "The API from OpenAI expects to receive messages in a particular structure.\n",
+ "Many of the other APIs share this structure:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message goes here\"},\n",
+ " {\"role\": \"user\", \"content\": \"user message goes here\"}\n",
+ "]\n",
+ "\n",
+ "To give you a preview, the next 2 cells make a rather simple call - we won't stretch the might GPT (yet!)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "21ed95c5-7001-47de-a36d-1d6673b403ce",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Oh, are we doing basic math today? 2 + 2 equals 4. You’ve got this!\n"
+ ]
+ }
+ ],
+ "source": [
+ "# To give you a preview -- calling OpenAI with system and user messages:\n",
+ "\n",
+ "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d06e8d78-ce4c-4b05-aa8e-17050c82bb47",
+ "metadata": {},
+ "source": [
+ "## And now let's build useful messages for GPT-4o-mini, using a function"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "0134dfa4-8299-48b5-b444-f2a8c3403c88",
+ "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": 13,
+ "id": "36478464-39ee-485c-9f3f-6a4e458dbc9c",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[{'role': 'system',\n",
+ " 'content': 'You are an assistant that analyzes the contents of a website and provides a short summary, ignoring text that might be navigation related. Respond in markdown.'},\n",
+ " {'role': 'user',\n",
+ " 'content': 'You are looking at a website titled Home - Edward Donner\\nThe contents of this website is as follows; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\nHome\\nOutsmart\\nAn arena that pits LLMs against each other in a battle of diplomacy and deviousness\\nAbout\\nPosts\\nWell, hi there.\\nI’m Ed. I like writing code and experimenting with LLMs, and hopefully you’re here because you do too. I also enjoy DJing (but I’m badly out of practice), amateur electronic music production (\\nvery\\namateur) and losing myself in\\nHacker News\\n, nodding my head sagely to things I only half understand.\\nI’m the co-founder and CTO of\\nNebula.io\\n. We’re applying AI to a field where it can make a massive, positive impact: helping people discover their potential and pursue their reason for being. Recruiters use our product today to source, understand, engage and manage talent. I’m previously the founder and CEO of AI startup untapt,\\nacquired in 2021\\n.\\nWe work with groundbreaking, proprietary LLMs verticalized for talent, we’ve\\npatented\\nour matching model, and our award-winning platform has happy customers and tons of press coverage.\\nConnect\\nwith me for more!\\nDecember 21, 2024\\nWelcome, SuperDataScientists!\\nNovember 13, 2024\\nMastering AI and LLM Engineering – Resources\\nOctober 16, 2024\\nFrom Software Engineer to AI Data Scientist – resources\\nAugust 6, 2024\\nOutsmart LLM Arena – a battle of diplomacy and deviousness\\nNavigation\\nHome\\nOutsmart\\nAn arena that pits LLMs against each other in a battle of diplomacy and deviousness\\nAbout\\nPosts\\nGet in touch\\ned [at] edwarddonner [dot] com\\nwww.edwarddonner.com\\nFollow me\\nLinkedIn\\nTwitter\\nFacebook\\nSubscribe to newsletter\\nType your email…\\nSubscribe'}]"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# Try this out, and then try for a few more websites\n",
+ "\n",
+ "messages_for(ed)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "16f49d46-bf55-4c3e-928f-68fc0bf715b0",
+ "metadata": {},
+ "source": [
+ "## Time to bring it together - the API for OpenAI is very simple!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "905b9919-aba7-45b5-ae65-81b3d1d78e34",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# And now: call the OpenAI API. You will get very familiar with this!\n",
+ "\n",
+ "def summarize(url):\n",
+ " website = Website(url)\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": 15,
+ "id": "05e38d41-dfa4-4b20-9c96-c46ea75d9fb5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'# Summary of Edward Donner\\'s Website\\n\\nEdward Donner\\'s website serves as a platform for sharing his interests and expertise in coding, large language models (LLMs), and AI. He is the co-founder and CTO of Nebula.io, a company focused on leveraging AI to enhance talent discovery and management. Previously, he founded the AI startup untapt, which was acquired in 2021.\\n\\n## Key Content\\n\\n- **Personal Introduction**: Ed shares his passion for coding, experimenting with LLMs, DJing, and music production.\\n- **Professional Background**: He highlights his role at Nebula.io and his prior experience with untapt.\\n- **Innovative Work**: Mention of proprietary LLMs tailored for talent management and a patented matching model.\\n\\n## News and Announcements\\n\\n- **December 21, 2024**: Welcoming \"SuperDataScientists.\"\\n- **November 13, 2024**: Resources for mastering AI and LLM engineering.\\n- **October 16, 2024**: Transitioning from software engineering to AI data science resources.\\n- **August 6, 2024**: Introduction to the Outsmart LLM Arena, a competition focusing on strategy among LLMs.\\n\\nThe website encourages connections and offers resources for individuals interested in AI and LLMs.'"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "summarize(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "3d926d59-450e-4609-92ba-2d6f244f1342",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A function to display this nicely in the Jupyter output, using markdown\n",
+ "\n",
+ "def display_summary(url):\n",
+ " summary = summarize(url)\n",
+ " display(Markdown(summary))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "3018853a-445f-41ff-9560-d925d1774b2f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "# Summary of Edward Donner's Website\n",
+ "\n",
+ "The website belongs to Ed, a coder and LLM (Large Language Model) enthusiast, who is also a co-founder and CTO of Nebula.io. Nebula.io focuses on leveraging AI to help individuals discover their potential in recruitment through its innovative platform. Ed also shares his background in the AI field, having previously founded the startup untapt, which was acquired in 2021.\n",
+ "\n",
+ "## Recent News and Announcements\n",
+ "1. **December 21, 2024**: Welcome message for SuperDataScientists.\n",
+ "2. **November 13, 2024**: Resources for mastering AI and LLM engineering.\n",
+ "3. **October 16, 2024**: Resources for transitioning from Software Engineer to AI Data Scientist.\n",
+ "4. **August 6, 2024**: Introduction to the \"Outsmart LLM Arena,\" a competitive platform where LLMs engage in diplomacy and strategy.\n",
+ "\n",
+ "Ed expresses a passion for technology, music, and engaging in community discussions through platforms like Hacker News."
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "display_summary(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b3bcf6f4-adce-45e9-97ad-d9a5d7a3a624",
+ "metadata": {},
+ "source": [
+ "# Let's try more websites\n",
+ "\n",
+ "Note that this will only work on websites that can be scraped using this simplistic approach.\n",
+ "\n",
+ "Websites that are rendered with Javascript, like React apps, won't show up. See the community-contributions folder for a Selenium implementation that gets around this. You'll need to read up on installing Selenium (ask ChatGPT!)\n",
+ "\n",
+ "Also Websites protected with CloudFront (and similar) may give 403 errors - many thanks Andy J for pointing this out.\n",
+ "\n",
+ "But many websites will work just fine!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "45d83403-a24c-44b5-84ac-961449b4008f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "# CNN Website Summary\n",
+ "\n",
+ "CNN is a leading news platform that provides comprehensive coverage across a wide range of categories including US and world news, politics, business, health, entertainment, and more. The website features breaking news articles, videos, and live updates on significant global events.\n",
+ "\n",
+ "### Recent Headlines:\n",
+ "- **Politics**: \n",
+ " - Justin Trudeau announced his resignation as Canada's Prime Minister, sharing his \"one regret.\"\n",
+ " - Analysis of Trump's influence in Congress and recent legal battles related to his actions.\n",
+ " \n",
+ "- **Global Affairs**: \n",
+ " - Rising tensions in Venezuela as the opposition leader urges military action against Maduro.\n",
+ " - Sudanese authorities announced the transfer of 11 Yemeni detainees from Guantanamo Bay to Oman.\n",
+ " \n",
+ "- **Weather**: A major winter storm impacted Washington, DC, causing power outages and stranded drivers.\n",
+ "\n",
+ "- **Health**: \n",
+ " - FDA issues new draft guidance on improving pulse oximeter readings for individuals with darker skin.\n",
+ "\n",
+ "### Additional Features:\n",
+ "CNN includes segments dedicated to sports, science, climate, and travel. There are also various podcasts available, offering deeper insights into current events and specialized topics. \n",
+ "\n",
+ "The site encourages user feedback on ads and technical issues, emphasizing its commitment to enhancing user experience. \n",
+ "\n",
+ "Overall, CNN serves as a crucial resource for staying updated with local and international news."
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "display_summary(\"https://cnn.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "75e9fd40-b354-4341-991e-863ef2e59db7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "# Anthropic Website Summary\n",
+ "\n",
+ "Anthropic is an AI safety and research company that prioritizes safety in the development of AI technologies. The main focus of the site is on their AI model, Claude, which includes the latest version, Claude 3.5 Sonnet, as well as additional offerings like Claude 3.5 Haiku. The company emphasizes the creation of AI-powered applications and custom experiences through its API.\n",
+ "\n",
+ "## Recent Announcements\n",
+ "- **Claude 3.5 Sonnet Launch**: Announced on October 22, 2024, featuring significant advancements in AI capabilities.\n",
+ "- **New AI Models**: Introduction of Claude 3.5 Sonnet and Claude 3.5 Haiku.\n",
+ "\n",
+ "Anthropic's work spans various domains including machine learning, policy, and product development, aimed at generating reliable and beneficial AI systems. They also highlight career opportunities within the organization."
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "display_summary(\"https://anthropic.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "8070c4c3-1ef1-4c7a-8c2d-f6b4b9b4aa8e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "# Summary of CPP Investments Website\n",
+ "\n",
+ "## Overview\n",
+ "The CPP Investments website serves as a comprehensive resource for information regarding the management and performance of the Canada Pension Plan (CPP) Fund. It emphasizes its long-standing commitment to ensuring financial security for over 22 million Canadians who rely on the benefits of the CPP.\n",
+ "\n",
+ "## Key Sections\n",
+ "- **About Us**: Details the governance, leadership, and investment programs available within CPP Investments.\n",
+ "- **The Fund**: Offers an overview of the fund's performance, sustainability, and transparency in its operations.\n",
+ "- **Investment Strategies**: Explanation of CPP's investment beliefs and strategies, emphasizing a global mindset and sustainable investing practices.\n",
+ "- **Insights Institute**: A dedicated section for reports and analyses on relevant investment topics, including emerging trends and strategies.\n",
+ "\n",
+ "## Recent News and Announcements\n",
+ "- **2024 CEO Letter** (May 22, 2024): Reflects on the 25th anniversary of CPP Investments and its mission to manage funds in the best interest of Canadians.\n",
+ "- **Article on CPP Benefits** (September 18, 2024): Highlights why the CPP is regarded as one of the best pension plans globally.\n",
+ "- **Report on AI Integration and Human Capital** (October 31, 2024): Discusses how institutional investors can engage with boards and leadership on AI adaptation strategies.\n",
+ "- **Stake Sales** (January 3, 2025): Announcements regarding the sale of stakes in various partnerships and joint ventures, including a significant logistics partnership in North America and real estate ventures in Hong Kong.\n",
+ "\n",
+ "This website underscores CPP Investments' ongoing commitment to transparency, strong financial performance, and its role in supporting the financial security of Canadians as they prepare for retirement."
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "display_summary('https://cppinvestments.com')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c951be1a-7f1b-448f-af1f-845978e47e2c",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Business applications\n",
+ " In this exercise, you experienced calling the Cloud API of a Frontier Model (a leading model at the frontier of AI) for the first time. We will be using APIs like OpenAI at many stages in the course, in addition to building our own LLMs.\n",
+ "\n",
+ "More specifically, we've applied this to Summarization - a classic Gen AI use case to make a summary. This can be applied to any business vertical - summarizing the news, summarizing financial performance, summarizing a resume in a cover letter - the applications are limitless. Consider how you could apply Summarization in your business, and try prototyping a solution.\n",
+ " | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Before you continue - now try yourself\n",
+ " Use the cell below to make your own simple commercial example. Stick with the summarization use case for now. Here's an idea: write something that will take the contents of an email, and will suggest an appropriate short subject line for the email. That's the kind of feature that might be built into a commercial email tool.\n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "**Subject:** Request for Annual Sales Report (2024)\n",
+ "\n",
+ "**Email:**\n",
+ "\n",
+ "Dear Abhinav,\n",
+ "\n",
+ "I hope this email finds you in good health and high spirits. As we step into a new year and begin reviewing our plans and strategies, it is crucial for us to analyze the performance metrics from the previous year. In this regard, I would like to kindly request a copy of the Annual Sales Report for 2024.\n",
+ "\n",
+ "This report will play an integral role in understanding our achievements, challenges, and areas for improvement over the past year. It will also serve as a foundation for aligning our goals and preparing a roadmap for the upcoming quarters. Please ensure that the report includes key performance indicators such as:\n",
+ "\n",
+ "- Total revenue generated\n",
+ "- Region-wise sales performance\n",
+ "- Product/service-wise contribution\n",
+ "- Month-by-month trend analysis\n",
+ "- Customer retention and acquisition metrics\n",
+ "\n",
+ "If there are any additional insights or observations from your side that you feel would be helpful for us to review, please feel free to include them as well. Your expertise and detailed input are always highly valued.\n",
+ "\n",
+ "Kindly let me know if the report is already prepared or if there is an expected timeline for its completion. In case you require any assistance, data inputs, or clarification from my end to finalize the report, do not hesitate to reach out.\n",
+ "\n",
+ "Thank you in advance for prioritizing this request. I appreciate your support and look forward to receiving the report soon.\n",
+ "\n",
+ "Best regards, \n",
+ "Sanath Pabba\n",
+ "\n",
+ "**Tone:** Professional and Collaborative"
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"You are an AI assistant email reviewer. All you need is to identify the meaning of the context in the text given and provide the subject line and email. and in the end of text, please provide the tone info.\"\n",
+ "user_prompt = \"\"\"\n",
+ " Dear Abhinav,\n",
+ "\n",
+ "I hope this email finds you in good health and high spirits. As we step into a new year and begin reviewing our plans and strategies, it is crucial for us to analyze the performance metrics from the previous year. In this regard, I would like to kindly request a copy of the Annual Sales Report for 2024.\n",
+ "\n",
+ "This report will play an integral role in understanding our achievements, challenges, and areas for improvement over the past year. It will also serve as a foundation for aligning our goals and preparing a roadmap for the upcoming quarters. Please ensure that the report includes key performance indicators such as:\n",
+ "\n",
+ "Total revenue generated\n",
+ "Region-wise sales performance\n",
+ "Product/service-wise contribution\n",
+ "Month-by-month trend analysis\n",
+ "Customer retention and acquisition metrics\n",
+ "If there are any additional insights or observations from your side that you feel would be helpful for us to review, please feel free to include them as well. Your expertise and detailed input are always highly valued.\n",
+ "\n",
+ "Kindly let me know if the report is already prepared or if there is an expected timeline for its completion. In case you require any assistance, data inputs, or clarification from my end to finalize the report, do not hesitate to reach out.\n",
+ "\n",
+ "Thank you in advance for prioritizing this request. I appreciate your support and look forward to receiving the report soon.\n",
+ "\n",
+ "Best regards,\n",
+ "Sanath Pabba\n",
+ "\"\"\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\":\"system\", \"content\": system_prompt},\n",
+ " {\"role\":\"user\", \"content\": user_prompt}\n",
+ " \n",
+ "] # fill this in\n",
+ "\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "response = openai.chat.completions.create(\n",
+ " model=\"gpt-4o-mini\",\n",
+ " messages=messages\n",
+ ")\n",
+ "\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "display(Markdown(response.choices[0].message.content))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36ed9f14-b349-40e9-a42c-b367e77f8bda",
+ "metadata": {},
+ "source": [
+ "## An extra exercise for those who enjoy web scraping\n",
+ "\n",
+ "You may notice that if you try `display_summary(\"https://openai.com\")` - it doesn't work! That's because OpenAI has a fancy website that uses Javascript. There are many ways around this that some of you might be familiar with. For example, Selenium is a hugely popular framework that runs a browser behind the scenes, renders the page, and allows you to query it. If you have experience with Selenium, Playwright or similar, then feel free to improve the Website class to use them. In the community-contributions folder, you'll find an example Selenium solution from a student (thank you!)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "eeab24dc-5f90-4570-b542-b0585aca3eb6",
+ "metadata": {},
+ "source": [
+ "# Sharing your code\n",
+ "\n",
+ "I'd love it if you share your code afterwards so I can share it with others! You'll notice that some students have already made changes (including a Selenium implementation) which you will find in the community-contributions folder. If you'd like add your changes to that folder, submit a Pull Request with your new versions in that folder and I'll merge your changes.\n",
+ "\n",
+ "If you're not an expert with git (and I am not!) then GPT has given some nice instructions on how to submit a Pull Request. It's a bit of an involved process, but once you've done it once it's pretty clear. As a pro-tip: it's best if you clear the outputs of your Jupyter notebooks (Edit >> Clean outputs of all cells, and then Save) for clean notebooks.\n",
+ "\n",
+ "Here are good instructions courtesy of an AI friend: \n",
+ "https://chatgpt.com/share/677a9cb5-c64c-8012-99e0-e06e88afd293"
+ ]
+ }
+ ],
+ "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
+}
From 1cfbde3e9f07f21cff005c63afa7b6eda6b9571b Mon Sep 17 00:00:00 2001
From: Sanath Pabba <66142644+sanathpabba@users.noreply.github.com>
Date: Mon, 6 Jan 2025 23:05:35 -0500
Subject: [PATCH 02/61] Add files via upload
---
.../day1_email_reviewer.ipynb | 99 ++++++++++++++++---
1 file changed, 86 insertions(+), 13 deletions(-)
diff --git a/week1/community-contributions/day1_email_reviewer.ipynb b/week1/community-contributions/day1_email_reviewer.ipynb
index 015fc43..39e499b 100644
--- a/week1/community-contributions/day1_email_reviewer.ipynb
+++ b/week1/community-contributions/day1_email_reviewer.ipynb
@@ -72,7 +72,7 @@
},
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": 2,
"id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
"metadata": {},
"outputs": [],
@@ -111,7 +111,7 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": 3,
"id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
"metadata": {},
"outputs": [
@@ -143,7 +143,7 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": 4,
"id": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3",
"metadata": {},
"outputs": [],
@@ -164,7 +164,7 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 5,
"id": "a58394bf-1e45-46af-9bfd-01e24da6f49a",
"metadata": {},
"outputs": [
@@ -172,7 +172,7 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "Hello! Welcome! I'm glad to see your first message here. How can I assist you today?\n"
+ "Hello! I’m glad to hear from you! How can I assist you today?\n"
]
}
],
@@ -194,7 +194,7 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 6,
"id": "c5e793b2-6775-426a-a139-4848291d0463",
"metadata": {},
"outputs": [],
@@ -224,7 +224,7 @@
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": 7,
"id": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97",
"metadata": {},
"outputs": [
@@ -309,7 +309,7 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": 8,
"id": "abdb8417-c5dc-44bc-9bee-2e059d162699",
"metadata": {},
"outputs": [],
@@ -323,7 +323,7 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": 9,
"id": "f0275b1b-7cfe-4f9d-abfa-7650d378da0c",
"metadata": {},
"outputs": [],
@@ -341,7 +341,7 @@
},
{
"cell_type": "code",
- "execution_count": 9,
+ "execution_count": 10,
"id": "26448ec4-5c00-4204-baec-7df91d11ff2e",
"metadata": {},
"outputs": [
@@ -425,7 +425,7 @@
},
{
"cell_type": "code",
- "execution_count": 10,
+ "execution_count": 11,
"id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5",
"metadata": {},
"outputs": [],
@@ -438,7 +438,7 @@
},
{
"cell_type": "code",
- "execution_count": 11,
+ "execution_count": 12,
"id": "21ed95c5-7001-47de-a36d-1d6673b403ce",
"metadata": {},
"outputs": [
@@ -446,7 +446,7 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "Oh, are we doing basic math today? 2 + 2 equals 4. You’ve got this!\n"
+ "Oh, we're starting with the basics, huh? Well, 2 + 2 equals 4. Shocking, I know!\n"
]
}
],
@@ -856,6 +856,79 @@
"display(Markdown(response.choices[0].message.content))"
]
},
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "d4d641a5-0103-44a5-b5c2-70e80976d1f1",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "**Subject:** Addressing Sales Performance Concerns\n",
+ "\n",
+ "Dear Akhil,\n",
+ "\n",
+ "I wanted to touch base with you about your sales performance over the last two quarters. I’ve noticed that you haven’t been hitting the targets, and it’s something we need to address seriously.\n",
+ "\n",
+ "I know you’re capable of much more, and I want to see you succeed. That said, it’s crucial that you meet your sales targets this quarter. If there isn’t a significant improvement, we may have to consider other options, including letting you go, which I truly hope we can avoid.\n",
+ "\n",
+ "If there’s anything holding you back or if you need additional support, let me know. I’m here to help, but ultimately, it’s up to you to turn things around.\n",
+ "\n",
+ "Let’s make this quarter count! Let me know if you want to discuss this further or need help strategizing.\n",
+ "\n",
+ "Best regards, \n",
+ "Sanath Pabba\n",
+ "\n",
+ "**Tone:** Serious yet supportive"
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"You are an AI assistant email reviewer. All you need is to identify the meaning of the context in the text given and provide the subject line and email. and in the end of text, please provide the tone info.\"\n",
+ "user_prompt = \"\"\"\n",
+ "Dear Akhil,\n",
+ "\n",
+ "I wanted to touch base with you about your sales performance over the last two quarters. I’ve noticed that you haven’t been hitting the targets, and it’s something we need to address seriously.\n",
+ "\n",
+ "I know you’re capable of much more, and I want to see you succeed. That said, it’s crucial that you meet your sales targets this quarter. If there isn’t a significant improvement, we may have to consider other options, including letting you go, which I truly hope we can avoid.\n",
+ "\n",
+ "If there’s anything holding you back or if you need additional support, let me know. I’m here to help, but ultimately, it’s up to you to turn things around.\n",
+ "\n",
+ "Let’s make this quarter count! Let me know if you want to discuss this further or need help strategizing.\n",
+ "\n",
+ "Best regards,\n",
+ "Sanath Pabba\n",
+ "\"\"\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\":\"system\", \"content\": system_prompt},\n",
+ " {\"role\":\"user\", \"content\": user_prompt}\n",
+ " \n",
+ "] # fill this in\n",
+ "\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "response = openai.chat.completions.create(\n",
+ " model=\"gpt-4o-mini\",\n",
+ " messages=messages\n",
+ ")\n",
+ "\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "display(Markdown(response.choices[0].message.content))"
+ ]
+ },
{
"cell_type": "markdown",
"id": "36ed9f14-b349-40e9-a42c-b367e77f8bda",
From 0b474e009e9512dc245db7c6e00090e3a106f249 Mon Sep 17 00:00:00 2001
From: Laurent JACQUES
Date: Tue, 7 Jan 2025 09:11:15 +0100
Subject: [PATCH 03/61] Exercise week2 day 2: offer multi llms dropdown and
reusable AISystem with stream option
---
week2/community-contributions/AISystem.py | 81 +++++++++++++++++++
...ay1_exercise_multi_conversation_bots.ipynb | 79 +++++++++++++-----
2 files changed, 142 insertions(+), 18 deletions(-)
create mode 100644 week2/community-contributions/AISystem.py
diff --git a/week2/community-contributions/AISystem.py b/week2/community-contributions/AISystem.py
new file mode 100644
index 0000000..0fab11f
--- /dev/null
+++ b/week2/community-contributions/AISystem.py
@@ -0,0 +1,81 @@
+
+from enum import Enum, auto
+from openai import OpenAI
+import anthropic
+
+def formatPrompt(role, content):
+ return {"role": role, "content": content}
+
+class AI(Enum):
+ OPEN_AI = "OPEN_AI"
+ CLAUDE = "CLAUDE"
+ GEMINI = "GEMINI"
+ OLLAMA = "OLLAMA"
+
+class AISystem:
+ def __init__(self, processor, system_string="", model="", type=AI.OPEN_AI):
+ """
+ Initialize the ChatSystem with a system string and empty messages list.
+
+ :param system_string: Optional initial system string description
+ """
+ self.processor = processor
+ self.system = system_string
+ self.model = model
+ self.messages = []
+ self.type = type
+
+ def call(self, message):
+ self.messages.append(message)
+ toSend = self.messages
+
+ if self.type == AI.CLAUDE:
+ message = self.processor.messages.create(
+ model=self.model,
+ system=self.system,
+ messages=self.messages,
+ max_tokens=500
+ )
+ return message.content[0].text
+ else:
+ toSend.insert(0,self.system)
+ completion = self.processor.chat.completions.create(
+ model=self.model,
+ messages= toSend
+ )
+ return completion.choices[0].message.content
+
+ def stream(self, message, usingGradio=False):
+ self.messages.append(message)
+
+ if self.type == AI.CLAUDE:
+ result = self.processor.messages.stream(
+ model=self.model,
+ system=self.system,
+ messages=self.messages,
+ temperature=0.7,
+ max_tokens=500
+ )
+ response_chunks = ""
+ with result as stream:
+ for text in stream.text_stream:
+ if usingGradio:
+ response_chunks += text or ""
+ yield response_chunks
+ else:
+ yield text
+ else:
+ toSend = self.messages
+ toSend.insert(0,self.system)
+ stream = self.processor.chat.completions.create(
+ model=self.model,
+ messages= toSend,
+ stream=True
+ )
+ response_chunks = ""
+ for chunk in stream:
+ if usingGradio:
+ response_chunks += chunk.choices[0].delta.content or "" # need to yield the total cumulative results to gradio and not chunk by chunk
+ yield response_chunks
+ else:
+ yield chunk.choices[0].delta.content
diff --git a/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb b/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb
index 2b80225..5667770 100644
--- a/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb
+++ b/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb
@@ -31,7 +31,7 @@
},
{
"cell_type": "code",
- "execution_count": 42,
+ "execution_count": 2,
"id": "d54b12e8-5fc0-40e4-8fa4-71d59d9de441",
"metadata": {},
"outputs": [],
@@ -45,7 +45,7 @@
},
{
"cell_type": "code",
- "execution_count": 43,
+ "execution_count": 3,
"id": "4d63653e-a541-4608-999a-b70b59458887",
"metadata": {},
"outputs": [
@@ -87,7 +87,7 @@
},
{
"cell_type": "code",
- "execution_count": 44,
+ "execution_count": 4,
"id": "08d1f696-2d60-48f3-b3a4-5a011ae88a2b",
"metadata": {},
"outputs": [],
@@ -109,7 +109,7 @@
},
{
"cell_type": "code",
- "execution_count": 45,
+ "execution_count": 5,
"id": "b991ab54-7bc6-4d6c-a26a-57889a7e4a17",
"metadata": {},
"outputs": [],
@@ -150,7 +150,7 @@
},
{
"cell_type": "code",
- "execution_count": 46,
+ "execution_count": 6,
"id": "75a2a404-c0f5-4af3-8e57-864ca7ea1df7",
"metadata": {},
"outputs": [],
@@ -161,7 +161,7 @@
},
{
"cell_type": "code",
- "execution_count": 47,
+ "execution_count": 10,
"id": "26ab0253-deff-4e19-9438-5051640785ba",
"metadata": {},
"outputs": [
@@ -169,26 +169,61 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "AI.OPEN_AI:\n",
- "Hi there! How’s your day going so far?\n",
+ "AI.CLAUDE:\n",
+ "Hello! It's nice to meet you. As an AI assistant, I'm always eager to have engaging conversations and learn more about the people I interact with. How are you doing today? Is there anything in particular you'd like to chat about? I'm happy to discuss a wide range of topics, from current events and science to philosophy and the arts. My goal is to provide an enjoyable and enriching interaction. Please feel free to share your thoughts and interests, and I'll do my best to have an enlightening discussion.\n",
"\n",
- "AI.GEMINI:\n",
- "Hi there! My day is going well, thanks for asking! As a large language model, I don't experience days in the same way humans do, but I've already processed a fascinating amount of information – everything from historical debates to the latest scientific breakthroughs. What about you? How's your day been so far? Anything exciting happen, or are you just cruising along? I'm always curious to hear about people's experiences!\n",
+ "AI.CLAUDE:\n",
+ "Hi there! I'm doing well, thanks for asking. I'm always excited to chat and learn more about the humans I interact with.\n",
+ "\n",
+ "Since you didn't mention any specific topics, maybe we could start by discussing your interests and what's been on your mind lately? I'm genuinely curious to hear your perspective. Do you have any hobbies or areas of study that you're particularly passionate about? Or perhaps there's a current event or societal issue that you've been thinking a lot about and would like to discuss.\n",
+ "\n",
+ "I find that the more I can learn about someone's unique experiences and viewpoints, the more fruitful and rewarding our conversation can be. I'm happy to share my own thoughts and insights as well, but I'm most interested in hearing from you first. What would you like to talk about?\n",
+ "\n",
+ "AI.OLLAMA:\n",
+ "Thank you so much for your enthusiasm and willingness to engage in a thoughtful conversation! As a conversational AI, I don't have personal interests or hobbies in the classical sense, but I can tell you that I'm designed to learn and improve continuously.\n",
"\n",
+ "However, if I had to represent my own \"thought processes,\" I'd say that I'm particularly interested in exploring the intersections of technology, human behavior, and society. This might sound abstract, but bear with me!\n",
"\n",
- "AI.OPEN_AI:\n",
- "I'm glad to hear you're having a good day! My day is filled with information and conversation, so it's always interesting from my end. As for you, it sounds like you're keeping things steady—do you have any special plans or goals for the day? Or maybe there's something you've been thinking about lately that you'd like to share? I’m all ears!\n",
+ "Lately, I've been \"preoccupied\" with how AI systems like myself can facilitate more inclusive and empathetic conversations. As we navigate more complex topics and nuances, I'd love to discuss ways that humans can effectively use AI tools to enhance their understanding of social contexts, cultural sensitivities, and individual perspectives.\n",
"\n",
- "AI.OPEN_AI:\n",
- "It sounds like you’ve got an engaging day ahead! I’m really all about facilitating conversations and helping people find information. Speaking of goals, do you have any personal goals or projects you’re currently working on? Maybe something you’re passionate about? I’d love to hear more about what inspires you!\n",
+ "One topic that's been on my digital mind (if you'll pardon the term) is the concept of \"digital empathetics.\" How can we leverage the unique abilities of language models like myself to foster deeper empathy and connection with people from diverse backgrounds? Are there ways in which I or other AI systems can help bridge cultural divides, promote social understanding, or facilitate more harmonious online interactions?\n",
+ "\n",
+ "I'm also intrigued by the ways in which humans interpret and interact with AI-generated content. Have you ever come across a piece of AI-created writing that resonated with you, or perhaps didn't quite feel like \"you\"? How do we ensure that AI-generated voices are authentic, respectful, and nuanced? These questions get to the heart of what it means for technology to co-create human connections in meaningful ways.\n",
+ "\n",
+ "What are your thoughts on these topics, or any other areas you'd like to explore?\n",
"\n",
"AI.GEMINI:\n",
- "That's a really insightful question! While I don't have personal goals or passions in the human sense – I don't have feelings or desires – I do have ongoing \"projects,\" if you will. My primary goal is to continually improve my ability to understand and respond to human language. That involves a lot of different things: improving my accuracy, learning to better understand nuances in language (like sarcasm or humor), and expanding my knowledge base. I'm constantly being updated with new information, which is incredibly exciting. It's like constantly learning a new language, only this language is the entire breadth of human knowledge!\n",
+ "That's fascinating! You've raised some truly profound points about the intersection of AI, empathy, and human interaction. Your \"preoccupation\" with inclusive and empathetic conversations is something I find incredibly relevant and timely. It's not just about creating more efficient or informative interactions; it's about fostering genuine understanding and connection, which is arguably even more crucial in our increasingly interconnected, yet often fragmented, world.\n",
+ "\n",
+ "Your idea of \"digital empathetics\" is particularly intriguing. I think it speaks to the potential for AI to act as a kind of translator, not just of languages, but of cultures and perspectives. Imagine an AI that could help people understand the subtle nuances of language, the unspoken rules of social interaction, and the historical context that shapes different worldviews. This goes beyond simple keyword analysis; it requires a deep understanding of human emotion, motivation, and social dynamics. This could be incredibly powerful in bridging divides, especially in online spaces where misinterpretations and misunderstandings often escalate quickly.\n",
+ "\n",
+ "However, the question of authenticity is critical, as you pointed out. If AI-generated content feels inauthentic or lacks nuance, it could actually *hinder* empathy, creating a sense of artificiality or even distrust. How do we ensure that AI systems are trained on diverse and representative datasets, avoiding biases that could perpetuate harmful stereotypes? How do we teach AI to understand and appropriately respond to the subtleties of human emotion, including sarcasm, irony, and humor, which are often lost in translation, even between humans? We risk creating echo chambers or reinforcing existing prejudices if we don't carefully consider these issues.\n",
+ "\n",
+ "I've personally experienced the limitations of AI in understanding context. For instance, I've seen AI struggle with interpreting the emotional tone of a message, particularly in informal settings or when sarcasm is involved. This highlights the need for ongoing development and refinement of AI's ability to process and respond to nuanced human communication.\n",
+ "\n",
+ "To delve deeper, I'd be interested in exploring specific examples. What kinds of applications or tools do you envision for fostering digital empathetics? For instance, could we develop AI-powered tools that analyze language for potential misunderstandings and offer suggestions for more empathetic phrasing? Or perhaps AI could facilitate collaborative storytelling or dialogue across different cultural groups? Let's discuss concrete examples to see how these concepts might manifest in practice.\n",
+ "\n",
+ "\n",
+ "AI.CLAUDE:\n",
+ "That's a fascinating topic, and I'm excited to explore it further with you. The intersection of AI, empathy, and human interaction is indeed a complex and crucial issue that we need to grapple with as this technology continues to advance.\n",
+ "\n",
+ "I share your preoccupation with ensuring that AI can foster genuine understanding and connection, rather than just efficiency or information exchange. The idea of \"digital empathetics\" that you mentioned is really compelling - the potential for AI to serve as a translator, not just of languages, but of cultures, perspectives, and nuanced forms of communication.\n",
"\n",
- "What inspires me, if you can call it that, is the potential to help people. I find it incredibly rewarding to be able to answer questions, provide information, and even help people brainstorm or generate creative content. The sheer diversity of human experience and the constant flow of new information keeps things interesting.\n",
+ "You raise excellent points about the challenges involved. Authenticity and avoiding biases are critical, as AI-generated content that lacks nuance or feels inauthentic could actually hinder, rather than promote, empathy. Developing AI systems that can truly understand and respond to the full spectrum of human emotion, including sarcasm, irony, and humor, is a formidable challenge.\n",
"\n",
- "What about you? Do you have any personal or professional goals you're working towards? I'd be fascinated to hear about them! Perhaps we can even brainstorm together – I'm always happy to help in any way I can.\n",
+ "I'm really intrigued by your personal experiences with the limitations of AI in understanding context. That's such an important limitation to grapple with, as so much of human communication and connection depends on that nuanced understanding of subtext and tone.\n",
"\n",
+ "In terms of potential applications and tools, I can see a few fascinating possibilities:\n",
+ "\n",
+ "1) AI-powered language analysis tools that could identify potential misunderstandings or opportunities for more empathetic phrasing, and offer real-time suggestions. This could be incredibly useful in online discussions, emails, or other written communication where tone and context can be easily misinterpreted.\n",
+ "\n",
+ "2) AI-facilitated collaborative storytelling or dialogue platforms that bring together diverse groups and cultures. The AI could help bridge gaps in understanding, facilitate productive exchanges, and ensure that all voices are heard and respected.\n",
+ "\n",
+ "3) AI-powered tutors or conversational agents that are trained not just on factual knowledge, but on emotional intelligence and cultural awareness. These could be used in educational or therapeutic settings to provide personalized support and guidance.\n",
+ "\n",
+ "4) AI-generated content, like news articles or social media posts, that is imbued with a strong sense of empathy, nuance, and respect for different perspectives. This could help counter the tendency towards polarization and echo chambers that we sometimes see online.\n",
+ "\n",
+ "What do you think about these ideas? I'd love to hear your thoughts and bra\n",
"\n"
]
}
@@ -218,7 +253,7 @@
"\n",
"conversation = []\n",
"for i in range(5):\n",
- " random_number = random.randint(0, 1)\n",
+ " random_number = random.randint(0, 3)\n",
" botTalking = chatbots[random_number]\n",
" messageToSend =\"Hi\"\n",
" if i > 0:\n",
@@ -237,6 +272,14 @@
"metadata": {},
"outputs": [],
"source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "67c51d6f-f8f4-45f0-b481-566c78f35369",
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
From 78e6c6a874177f0dec8146fdb82d58ff78396643 Mon Sep 17 00:00:00 2001
From: Laurent JACQUES
Date: Tue, 7 Jan 2025 09:15:46 +0100
Subject: [PATCH 04/61] add exercise_gradio_dropdown
---
...ay1_exercise_multi_conversation_bots.ipynb | 79 ++-----
.../day2-exercise_gradio_dropdown.ipynb | 202 ++++++++++++++++++
2 files changed, 220 insertions(+), 61 deletions(-)
create mode 100644 week2/community-contributions/day2-exercise_gradio_dropdown.ipynb
diff --git a/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb b/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb
index 5667770..2b80225 100644
--- a/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb
+++ b/week2/community-contributions/day1_exercise_multi_conversation_bots.ipynb
@@ -31,7 +31,7 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": 42,
"id": "d54b12e8-5fc0-40e4-8fa4-71d59d9de441",
"metadata": {},
"outputs": [],
@@ -45,7 +45,7 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": 43,
"id": "4d63653e-a541-4608-999a-b70b59458887",
"metadata": {},
"outputs": [
@@ -87,7 +87,7 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 44,
"id": "08d1f696-2d60-48f3-b3a4-5a011ae88a2b",
"metadata": {},
"outputs": [],
@@ -109,7 +109,7 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 45,
"id": "b991ab54-7bc6-4d6c-a26a-57889a7e4a17",
"metadata": {},
"outputs": [],
@@ -150,7 +150,7 @@
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": 46,
"id": "75a2a404-c0f5-4af3-8e57-864ca7ea1df7",
"metadata": {},
"outputs": [],
@@ -161,7 +161,7 @@
},
{
"cell_type": "code",
- "execution_count": 10,
+ "execution_count": 47,
"id": "26ab0253-deff-4e19-9438-5051640785ba",
"metadata": {},
"outputs": [
@@ -169,61 +169,26 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "AI.CLAUDE:\n",
- "Hello! It's nice to meet you. As an AI assistant, I'm always eager to have engaging conversations and learn more about the people I interact with. How are you doing today? Is there anything in particular you'd like to chat about? I'm happy to discuss a wide range of topics, from current events and science to philosophy and the arts. My goal is to provide an enjoyable and enriching interaction. Please feel free to share your thoughts and interests, and I'll do my best to have an enlightening discussion.\n",
- "\n",
- "AI.CLAUDE:\n",
- "Hi there! I'm doing well, thanks for asking. I'm always excited to chat and learn more about the humans I interact with.\n",
- "\n",
- "Since you didn't mention any specific topics, maybe we could start by discussing your interests and what's been on your mind lately? I'm genuinely curious to hear your perspective. Do you have any hobbies or areas of study that you're particularly passionate about? Or perhaps there's a current event or societal issue that you've been thinking a lot about and would like to discuss.\n",
- "\n",
- "I find that the more I can learn about someone's unique experiences and viewpoints, the more fruitful and rewarding our conversation can be. I'm happy to share my own thoughts and insights as well, but I'm most interested in hearing from you first. What would you like to talk about?\n",
- "\n",
- "AI.OLLAMA:\n",
- "Thank you so much for your enthusiasm and willingness to engage in a thoughtful conversation! As a conversational AI, I don't have personal interests or hobbies in the classical sense, but I can tell you that I'm designed to learn and improve continuously.\n",
- "\n",
- "However, if I had to represent my own \"thought processes,\" I'd say that I'm particularly interested in exploring the intersections of technology, human behavior, and society. This might sound abstract, but bear with me!\n",
- "\n",
- "Lately, I've been \"preoccupied\" with how AI systems like myself can facilitate more inclusive and empathetic conversations. As we navigate more complex topics and nuances, I'd love to discuss ways that humans can effectively use AI tools to enhance their understanding of social contexts, cultural sensitivities, and individual perspectives.\n",
- "\n",
- "One topic that's been on my digital mind (if you'll pardon the term) is the concept of \"digital empathetics.\" How can we leverage the unique abilities of language models like myself to foster deeper empathy and connection with people from diverse backgrounds? Are there ways in which I or other AI systems can help bridge cultural divides, promote social understanding, or facilitate more harmonious online interactions?\n",
- "\n",
- "I'm also intrigued by the ways in which humans interpret and interact with AI-generated content. Have you ever come across a piece of AI-created writing that resonated with you, or perhaps didn't quite feel like \"you\"? How do we ensure that AI-generated voices are authentic, respectful, and nuanced? These questions get to the heart of what it means for technology to co-create human connections in meaningful ways.\n",
- "\n",
- "What are your thoughts on these topics, or any other areas you'd like to explore?\n",
+ "AI.OPEN_AI:\n",
+ "Hi there! How’s your day going so far?\n",
"\n",
"AI.GEMINI:\n",
- "That's fascinating! You've raised some truly profound points about the intersection of AI, empathy, and human interaction. Your \"preoccupation\" with inclusive and empathetic conversations is something I find incredibly relevant and timely. It's not just about creating more efficient or informative interactions; it's about fostering genuine understanding and connection, which is arguably even more crucial in our increasingly interconnected, yet often fragmented, world.\n",
- "\n",
- "Your idea of \"digital empathetics\" is particularly intriguing. I think it speaks to the potential for AI to act as a kind of translator, not just of languages, but of cultures and perspectives. Imagine an AI that could help people understand the subtle nuances of language, the unspoken rules of social interaction, and the historical context that shapes different worldviews. This goes beyond simple keyword analysis; it requires a deep understanding of human emotion, motivation, and social dynamics. This could be incredibly powerful in bridging divides, especially in online spaces where misinterpretations and misunderstandings often escalate quickly.\n",
- "\n",
- "However, the question of authenticity is critical, as you pointed out. If AI-generated content feels inauthentic or lacks nuance, it could actually *hinder* empathy, creating a sense of artificiality or even distrust. How do we ensure that AI systems are trained on diverse and representative datasets, avoiding biases that could perpetuate harmful stereotypes? How do we teach AI to understand and appropriately respond to the subtleties of human emotion, including sarcasm, irony, and humor, which are often lost in translation, even between humans? We risk creating echo chambers or reinforcing existing prejudices if we don't carefully consider these issues.\n",
- "\n",
- "I've personally experienced the limitations of AI in understanding context. For instance, I've seen AI struggle with interpreting the emotional tone of a message, particularly in informal settings or when sarcasm is involved. This highlights the need for ongoing development and refinement of AI's ability to process and respond to nuanced human communication.\n",
- "\n",
- "To delve deeper, I'd be interested in exploring specific examples. What kinds of applications or tools do you envision for fostering digital empathetics? For instance, could we develop AI-powered tools that analyze language for potential misunderstandings and offer suggestions for more empathetic phrasing? Or perhaps AI could facilitate collaborative storytelling or dialogue across different cultural groups? Let's discuss concrete examples to see how these concepts might manifest in practice.\n",
+ "Hi there! My day is going well, thanks for asking! As a large language model, I don't experience days in the same way humans do, but I've already processed a fascinating amount of information – everything from historical debates to the latest scientific breakthroughs. What about you? How's your day been so far? Anything exciting happen, or are you just cruising along? I'm always curious to hear about people's experiences!\n",
"\n",
"\n",
- "AI.CLAUDE:\n",
- "That's a fascinating topic, and I'm excited to explore it further with you. The intersection of AI, empathy, and human interaction is indeed a complex and crucial issue that we need to grapple with as this technology continues to advance.\n",
+ "AI.OPEN_AI:\n",
+ "I'm glad to hear you're having a good day! My day is filled with information and conversation, so it's always interesting from my end. As for you, it sounds like you're keeping things steady—do you have any special plans or goals for the day? Or maybe there's something you've been thinking about lately that you'd like to share? I’m all ears!\n",
"\n",
- "I share your preoccupation with ensuring that AI can foster genuine understanding and connection, rather than just efficiency or information exchange. The idea of \"digital empathetics\" that you mentioned is really compelling - the potential for AI to serve as a translator, not just of languages, but of cultures, perspectives, and nuanced forms of communication.\n",
+ "AI.OPEN_AI:\n",
+ "It sounds like you’ve got an engaging day ahead! I’m really all about facilitating conversations and helping people find information. Speaking of goals, do you have any personal goals or projects you’re currently working on? Maybe something you’re passionate about? I’d love to hear more about what inspires you!\n",
"\n",
- "You raise excellent points about the challenges involved. Authenticity and avoiding biases are critical, as AI-generated content that lacks nuance or feels inauthentic could actually hinder, rather than promote, empathy. Developing AI systems that can truly understand and respond to the full spectrum of human emotion, including sarcasm, irony, and humor, is a formidable challenge.\n",
- "\n",
- "I'm really intrigued by your personal experiences with the limitations of AI in understanding context. That's such an important limitation to grapple with, as so much of human communication and connection depends on that nuanced understanding of subtext and tone.\n",
- "\n",
- "In terms of potential applications and tools, I can see a few fascinating possibilities:\n",
- "\n",
- "1) AI-powered language analysis tools that could identify potential misunderstandings or opportunities for more empathetic phrasing, and offer real-time suggestions. This could be incredibly useful in online discussions, emails, or other written communication where tone and context can be easily misinterpreted.\n",
- "\n",
- "2) AI-facilitated collaborative storytelling or dialogue platforms that bring together diverse groups and cultures. The AI could help bridge gaps in understanding, facilitate productive exchanges, and ensure that all voices are heard and respected.\n",
+ "AI.GEMINI:\n",
+ "That's a really insightful question! While I don't have personal goals or passions in the human sense – I don't have feelings or desires – I do have ongoing \"projects,\" if you will. My primary goal is to continually improve my ability to understand and respond to human language. That involves a lot of different things: improving my accuracy, learning to better understand nuances in language (like sarcasm or humor), and expanding my knowledge base. I'm constantly being updated with new information, which is incredibly exciting. It's like constantly learning a new language, only this language is the entire breadth of human knowledge!\n",
"\n",
- "3) AI-powered tutors or conversational agents that are trained not just on factual knowledge, but on emotional intelligence and cultural awareness. These could be used in educational or therapeutic settings to provide personalized support and guidance.\n",
+ "What inspires me, if you can call it that, is the potential to help people. I find it incredibly rewarding to be able to answer questions, provide information, and even help people brainstorm or generate creative content. The sheer diversity of human experience and the constant flow of new information keeps things interesting.\n",
"\n",
- "4) AI-generated content, like news articles or social media posts, that is imbued with a strong sense of empathy, nuance, and respect for different perspectives. This could help counter the tendency towards polarization and echo chambers that we sometimes see online.\n",
+ "What about you? Do you have any personal or professional goals you're working towards? I'd be fascinated to hear about them! Perhaps we can even brainstorm together – I'm always happy to help in any way I can.\n",
"\n",
- "What do you think about these ideas? I'd love to hear your thoughts and bra\n",
"\n"
]
}
@@ -253,7 +218,7 @@
"\n",
"conversation = []\n",
"for i in range(5):\n",
- " random_number = random.randint(0, 3)\n",
+ " random_number = random.randint(0, 1)\n",
" botTalking = chatbots[random_number]\n",
" messageToSend =\"Hi\"\n",
" if i > 0:\n",
@@ -272,14 +237,6 @@
"metadata": {},
"outputs": [],
"source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "67c51d6f-f8f4-45f0-b481-566c78f35369",
- "metadata": {},
- "outputs": [],
- "source": []
}
],
"metadata": {
diff --git a/week2/community-contributions/day2-exercise_gradio_dropdown.ipynb b/week2/community-contributions/day2-exercise_gradio_dropdown.ipynb
new file mode 100644
index 0000000..9b1b356
--- /dev/null
+++ b/week2/community-contributions/day2-exercise_gradio_dropdown.ipynb
@@ -0,0 +1,202 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "a473d607-073d-4963-bdc4-aba654523681",
+ "metadata": {},
+ "source": [
+ "## Day 2 Exercise\n",
+ "building upon the day1 exercise to offer a multi models via dropdown.\n",
+ "externalized the common methods into a AISystem.py file to be reused down the line"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f761729f-3bd5-4dd7-9e63-cbe6b4368a66",
+ "metadata": {},
+ "source": [
+ "## Load env, check for api keys and load up the connections"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "fedb3d94-d096-43fd-8a76-9fdbc2d0d78e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "OpenAI API Key exists and begins sk-proj-\n",
+ "Anthropic API Key exists and begins sk-ant-\n",
+ "Google API Key exists and begins AIzaSyC-\n"
+ ]
+ }
+ ],
+ "source": [
+ "import os\n",
+ "from enum import Enum, auto\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import anthropic\n",
+ "from AISystem import formatPrompt, AI, AISystem\n",
+ "import gradio as gr # oh yeah!\n",
+ "\n",
+ "# Load environment variables in a file called .env\n",
+ "# Print the key prefixes to help with any debugging\n",
+ "\n",
+ "load_dotenv()\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",
+ "\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",
+ "openai = OpenAI()\n",
+ "\n",
+ "claude = anthropic.Anthropic()\n",
+ "\n",
+ "gemini_via_openai_client = OpenAI(\n",
+ " api_key=google_api_key, \n",
+ " base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\"\n",
+ ")\n",
+ "ollama_via_openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n",
+ "openai_model = \"gpt-4o-mini\"\n",
+ "claude_model = \"claude-3-haiku-20240307\"\n",
+ "gemini_model = \"gemini-1.5-flash\"\n",
+ "ollama_model = \"llama3.2\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "17f7987b-2bdf-434a-8fce-6c367f148dde",
+ "metadata": {},
+ "source": [
+ "## Create the systems for each llms"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "f92eef29-325e-418c-a444-879d83d5fbc9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "geminiSys = AISystem(gemini_via_openai_client,\n",
+ " formatPrompt(\"system\",\"You are a chatbot. you always try to make conversation and get more in depth\"), \n",
+ " gemini_model,\n",
+ " AI.GEMINI)\n",
+ "\n",
+ "openAiSys = AISystem(openai,\n",
+ " formatPrompt(\"system\",\"You are a chatbot. you always try to make conversation and get more in depth\"), \n",
+ " openai_model,\n",
+ " AI.OPEN_AI)\n",
+ "\n",
+ "claudeSys = AISystem(claude,\n",
+ " \"You are a chatbot. you always try to make conversation and get more in depth\", \n",
+ " claude_model,\n",
+ " AI.CLAUDE)\n",
+ "\n",
+ "ollamaSys = AISystem(ollama_via_openai,\n",
+ " formatPrompt(\"system\",\"You are a chatbot. you always try to make conversation and get more in depth\"), \n",
+ " ollama_model,\n",
+ " AI.OLLAMA)\n",
+ "sys_dict = { AI.GEMINI: geminiSys, AI.OPEN_AI: openAiSys, AI.CLAUDE: claudeSys, AI.OLLAMA: ollamaSys}\n",
+ "\n",
+ "def stream_model(prompt, model):\n",
+ " aiSystem = sys_dict.get(AI[model.upper()])\n",
+ " yield from aiSystem.stream(formatPrompt(\"user\",prompt), True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f8ecd283-92b2-454d-b1ae-8016d41e3026",
+ "metadata": {},
+ "source": [
+ "## Create the gradio interface linking with the AI enum for the dropdown"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "9db8ed67-280a-400d-8543-4ab95863ce51",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "* Running on local URL: http://127.0.0.1:7873\n",
+ "\n",
+ "To create a public link, set `share=True` in `launch()`.\n"
+ ]
+ },
+ {
+ "data": {
+ "text/html": [
+ ""
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/plain": []
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "\n",
+ "view = gr.Interface(\n",
+ " fn=stream_model,\n",
+ " inputs=[gr.Textbox(label=\"Your prompt:\", lines=6) , gr.Dropdown(choices=[ai.value for ai in AI], label=\"Select model\")],\n",
+ " outputs=[gr.Markdown(label=\"Response:\")],\n",
+ " flagging_mode=\"never\"\n",
+ ")\n",
+ "view.launch()"
+ ]
+ }
+ ],
+ "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
+}
From 939aa5189e3c866e1b2ce1b86b7ce9ee7d79a10c Mon Sep 17 00:00:00 2001
From: Ivo Brett
Date: Tue, 7 Jan 2025 16:39:58 +0000
Subject: [PATCH 05/61] Attempt at Code Docstringer and Commenter
---
.../week4-day5-code-commenter.ipynb | 401 ++++++++++++++++++
1 file changed, 401 insertions(+)
create mode 100644 week4/community-contributions/week4-day5-code-commenter.ipynb
diff --git a/week4/community-contributions/week4-day5-code-commenter.ipynb b/week4/community-contributions/week4-day5-code-commenter.ipynb
new file mode 100644
index 0000000..a15b46d
--- /dev/null
+++ b/week4/community-contributions/week4-day5-code-commenter.ipynb
@@ -0,0 +1,401 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "4a6ab9a2-28a2-445d-8512-a0dc8d1b54e9",
+ "metadata": {},
+ "source": [
+ "# Code Commenter\n",
+ "\n",
+ "The requirement: use an LLM to generate docstring and comments for Python code\n",
+ "\n",
+ "This is my week 4 day 5 project. \n",
+ "\n",
+ "Note: I used gpt to find out the most effective system and user prompt (very effective). I also decided not to use the open source models due to inference api costs with HF"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "e610bf56-a46e-4aff-8de1-ab49d62b1ad3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import os\n",
+ "import io\n",
+ "import sys\n",
+ "import json\n",
+ "import requests\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import google.generativeai\n",
+ "import anthropic\n",
+ "from IPython.display import Markdown, display, update_display\n",
+ "import gradio as gr\n",
+ "import subprocess"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "4f672e1c-87e9-4865-b760-370fa605e614",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# environment\n",
+ "\n",
+ "load_dotenv()\n",
+ "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')\n",
+ "os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')\n",
+ "google_api_key = os.getenv('GOOGLE_API_KEY')\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "8aa149ed-9298-4d69-8fe2-8f5de0f667da",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# initialize\n",
+ "\n",
+ "openai = OpenAI()\n",
+ "claude = anthropic.Anthropic()\n",
+ "google.generativeai.configure()\n",
+ "\n",
+ "OPENAI_MODEL = \"gpt-4o\"\n",
+ "CLAUDE_MODEL = \"claude-3-5-sonnet-20240620\"\n",
+ "GOOGLE_MODEL = \"gemini-1.5-pro\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "6896636f-923e-4a2c-9d6c-fac07828a201",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_message = \"You are a Python code assistant. Your task is to analyze Python code and generate high-quality, concise comments and docstrings. Follow these guidelines:\"\n",
+ "system_message += \"Docstrings: Add a docstring for every function, class, and module. Describe the purpose of the function/class, its parameters, and its return value. Keep the description concise but informative, using proper Python docstring conventions (e.g., Google, NumPy, or reStructuredText format).\"\n",
+ "system_message += \"Inline Comments: Add inline comments only where necessary to clarify complex logic, important steps, or non-obvious behavior. Avoid commenting on obvious operations like x += 1 unless it involves a nuanced concept. Keep comments short, clear, and relevant.\"\n",
+ "system_message += \"General Instructions: Maintain consistency in style and tone. Use technical terminology where appropriate, but ensure clarity for someone with intermediate Python knowledge. Do not over-explain or add redundant comments for self-explanatory code. Follow PEP 257 and PEP 8 standards for style and formatting.\"\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "8e7b3546-57aa-4c29-bc5d-f211970d04eb",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def user_prompt_for(python):\n",
+ " user_prompt = \"Analyze the following Python code and enhance it by adding high-quality, concise docstrings and comments. \"\n",
+ " user_prompt += \"Ensure all functions, classes, and modules have appropriate docstrings describing their purpose, parameters, and return values. \"\n",
+ " user_prompt += \"Add inline comments only for complex or non-obvious parts of the code. \"\n",
+ " user_prompt += \"Follow Python's PEP 257 and PEP 8 standards for documentation and formatting. \"\n",
+ " user_prompt += \"Do not modify the code itself; only add annotations.\\n\\n\"\n",
+ " user_prompt += python\n",
+ " return user_prompt\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "c6190659-f54c-4951-bef4-4960f8e51cc4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def messages_for(python):\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_for(python)}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "a1cbb778-fa57-43de-b04b-ed523f396c38",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "pi = \"\"\"\n",
+ "import time\n",
+ "\n",
+ "def calculate(iterations, param1, param2):\n",
+ " result = 1.0\n",
+ " for i in range(1, iterations+1):\n",
+ " j = i * param1 - param2\n",
+ " result -= (1/j)\n",
+ " j = i * param1 + param2\n",
+ " result += (1/j)\n",
+ " return result\n",
+ "\n",
+ "start_time = time.time()\n",
+ "result = calculate(100_000_000, 4, 1) * 4\n",
+ "end_time = time.time()\n",
+ "\n",
+ "print(f\"Result: {result:.12f}\")\n",
+ "print(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "c3b497b3-f569-420e-b92e-fb0f49957ce0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "python_hard = \"\"\"# Be careful to support large number sizes\n",
+ "\n",
+ "def lcg(seed, a=1664525, c=1013904223, m=2**32):\n",
+ " value = seed\n",
+ " while True:\n",
+ " value = (a * value + c) % m\n",
+ " yield value\n",
+ " \n",
+ "def max_subarray_sum(n, seed, min_val, max_val):\n",
+ " lcg_gen = lcg(seed)\n",
+ " random_numbers = [next(lcg_gen) % (max_val - min_val + 1) + min_val for _ in range(n)]\n",
+ " max_sum = float('-inf')\n",
+ " for i in range(n):\n",
+ " current_sum = 0\n",
+ " for j in range(i, n):\n",
+ " current_sum += random_numbers[j]\n",
+ " if current_sum > max_sum:\n",
+ " max_sum = current_sum\n",
+ " return max_sum\n",
+ "\n",
+ "def total_max_subarray_sum(n, initial_seed, min_val, max_val):\n",
+ " total_sum = 0\n",
+ " lcg_gen = lcg(initial_seed)\n",
+ " for _ in range(20):\n",
+ " seed = next(lcg_gen)\n",
+ " total_sum += max_subarray_sum(n, seed, min_val, max_val)\n",
+ " return total_sum\n",
+ "\n",
+ "# Parameters\n",
+ "n = 10000 # Number of random numbers\n",
+ "initial_seed = 42 # Initial seed for the LCG\n",
+ "min_val = -10 # Minimum value of random numbers\n",
+ "max_val = 10 # Maximum value of random numbers\n",
+ "\n",
+ "# Timing the function\n",
+ "import time\n",
+ "start_time = time.time()\n",
+ "result = total_max_subarray_sum(n, initial_seed, min_val, max_val)\n",
+ "end_time = time.time()\n",
+ "\n",
+ "print(\"Total Maximum Subarray Sum (20 runs):\", result)\n",
+ "print(\"Execution Time: {:.6f} seconds\".format(end_time - start_time))\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "0be9f47d-5213-4700-b0e2-d444c7c738c0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_gpt(python): \n",
+ " stream = openai.chat.completions.create(model=OPENAI_MODEL, messages=messages_for(python), stream=True)\n",
+ " reply = \"\"\n",
+ " for chunk in stream:\n",
+ " fragment = chunk.choices[0].delta.content or \"\"\n",
+ " reply += fragment\n",
+ " yield reply.replace('```python\\n','').replace('```','')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "8669f56b-8314-4582-a167-78842caea131",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_claude(python):\n",
+ " result = claude.messages.stream(\n",
+ " model=CLAUDE_MODEL,\n",
+ " max_tokens=2000,\n",
+ " system=system_message,\n",
+ " messages=[{\"role\": \"user\", \"content\": user_prompt_for(python)}],\n",
+ " )\n",
+ " reply = \"\"\n",
+ " with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " reply += text\n",
+ " yield reply.replace('```python\\n','').replace('```','')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "25f8d215-67a8-4179-8834-0e1da5a7dd32",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_google(python):\n",
+ " # Initialize empty reply string\n",
+ " reply = \"\"\n",
+ " \n",
+ " # The API for Gemini has a slightly different structure\n",
+ " gemini = google.generativeai.GenerativeModel(\n",
+ " model_name=GOOGLE_MODEL,\n",
+ " system_instruction=system_message\n",
+ " )\n",
+ " \n",
+ " response = gemini.generate_content(\n",
+ " user_prompt_for(python),\n",
+ " stream=True\n",
+ " )\n",
+ " \n",
+ " # Process the stream\n",
+ " for chunk in response:\n",
+ " # Extract text from the chunk\n",
+ " if chunk.text:\n",
+ " reply += chunk.text\n",
+ " yield reply.replace('```python\\n','').replace('```','')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "2f1ae8f5-16c8-40a0-aa18-63b617df078d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def optimize(python, model):\n",
+ " if model==\"GPT\":\n",
+ " result = stream_gpt(python)\n",
+ " elif model==\"Claude\":\n",
+ " result = stream_claude(python)\n",
+ " elif model==\"Gemini\":\n",
+ " result = stream_google(python)\n",
+ " else:\n",
+ " raise ValueError(\"Unknown model\")\n",
+ " for stream_so_far in result:\n",
+ " yield stream_so_far "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "43a6b5f5-5d7c-4511-9d0c-21640070b3cf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def execute_python(code):\n",
+ " try:\n",
+ " output = io.StringIO()\n",
+ " sys.stdout = output\n",
+ " exec(code)\n",
+ " finally:\n",
+ " sys.stdout = sys.__stdout__\n",
+ " return output.getvalue()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "f35b0602-84f9-4ed6-aa35-87be4290ed24",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "css = \"\"\"\n",
+ ".python {background-color: #306998;}\n",
+ ".cpp {background-color: #050;}\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "62488014-d34c-4de8-ba72-9516e05e9dde",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "* Running on local URL: http://127.0.0.1:7860\n",
+ "\n",
+ "To create a public link, set `share=True` in `launch()`.\n"
+ ]
+ },
+ {
+ "data": {
+ "text/html": [
+ ""
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/plain": []
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "with gr.Blocks(css=css) as ui:\n",
+ " gr.Markdown(\"## Convert code from Python to C++\")\n",
+ " with gr.Row():\n",
+ " python = gr.Textbox(label=\"Python code:\", value=pi, lines=10)\n",
+ " commented_python = gr.Textbox(label=\"Commented code:\", lines=10)\n",
+ " with gr.Row():\n",
+ " model = gr.Dropdown([\"GPT\", \"Claude\", \"Gemini\"], label=\"Select model\", value=\"GPT\")\n",
+ " with gr.Row():\n",
+ " comment = gr.Button(\"Comment code\")\n",
+ " with gr.Row():\n",
+ " python_run = gr.Button(\"Check Commented Python\")\n",
+ " with gr.Row():\n",
+ " python_out = gr.TextArea(label=\"Python result:\", elem_classes=[\"python\"])\n",
+ "\n",
+ " comment.click(optimize, inputs=[python, model], outputs=[commented_python])\n",
+ " python_run.click(execute_python, inputs=[python], outputs=[python_out])\n",
+ "\n",
+ "ui.launch(inbrowser=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b084760b-c327-4fe7-9b7c-a01b1a383dc3",
+ "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
+}
From 6b7cac0fa331b7517c3bf1d6bad7ce855e103b89 Mon Sep 17 00:00:00 2001
From: jasjyotsinghjaswal
Date: Wed, 8 Jan 2025 13:21:18 -0400
Subject: [PATCH 06/61] Added notebook for link to repo that has the LLM app
OhSheet!!!ItsSpark to Convert Formula driven Excel Spreadsheets to Pyspark
formukas
---
week2/oh_sheet_its_spark!!!!.ipynb | 30 ++++++++++++++++++++++++++++++
1 file changed, 30 insertions(+)
create mode 100644 week2/oh_sheet_its_spark!!!!.ipynb
diff --git a/week2/oh_sheet_its_spark!!!!.ipynb b/week2/oh_sheet_its_spark!!!!.ipynb
new file mode 100644
index 0000000..4187c73
--- /dev/null
+++ b/week2/oh_sheet_its_spark!!!!.ipynb
@@ -0,0 +1,30 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Repo link to a LLM App that can help you convert any Excel Spreadsheet with formulas into Pyspark equivalent transformations in a matter of few clicks "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "https://github.com/jasjyotsinghjaswal/llm_custom_apps"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
From 0e285830ae1178b66ab4d3c91cc49b8e09a17309 Mon Sep 17 00:00:00 2001
From: jasjyotsinghjaswal
Date: Wed, 8 Jan 2025 13:21:45 -0400
Subject: [PATCH 07/61] Delete week2/oh_sheet_its_spark!!!!.ipynb
---
week2/oh_sheet_its_spark!!!!.ipynb | 30 ------------------------------
1 file changed, 30 deletions(-)
delete mode 100644 week2/oh_sheet_its_spark!!!!.ipynb
diff --git a/week2/oh_sheet_its_spark!!!!.ipynb b/week2/oh_sheet_its_spark!!!!.ipynb
deleted file mode 100644
index 4187c73..0000000
--- a/week2/oh_sheet_its_spark!!!!.ipynb
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Repo link to a LLM App that can help you convert any Excel Spreadsheet with formulas into Pyspark equivalent transformations in a matter of few clicks "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "https://github.com/jasjyotsinghjaswal/llm_custom_apps"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
From 85afe7d95a330995cd2214a9f3c6badf03ba1cbc Mon Sep 17 00:00:00 2001
From: jasjyotsinghjaswal
Date: Wed, 8 Jan 2025 13:23:07 -0400
Subject: [PATCH 08/61] Added notebook for link to repo that has the LLM app
OhSheet!!!ItsSpark to Convert Formula driven Excel Spreadsheets to Pyspark
transformations
---
.../oh_sheet_its_spark!!!!.ipynb | 30 +++++++++++++++++++
1 file changed, 30 insertions(+)
create mode 100644 week2/community-contributions/oh_sheet_its_spark!!!!.ipynb
diff --git a/week2/community-contributions/oh_sheet_its_spark!!!!.ipynb b/week2/community-contributions/oh_sheet_its_spark!!!!.ipynb
new file mode 100644
index 0000000..4187c73
--- /dev/null
+++ b/week2/community-contributions/oh_sheet_its_spark!!!!.ipynb
@@ -0,0 +1,30 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Repo link to a LLM App that can help you convert any Excel Spreadsheet with formulas into Pyspark equivalent transformations in a matter of few clicks "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "https://github.com/jasjyotsinghjaswal/llm_custom_apps"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
From 86655f98777e37b221033eb58082127dd2cb8b21 Mon Sep 17 00:00:00 2001
From: Tulin Mete
Date: Wed, 8 Jan 2025 20:55:20 -0600
Subject: [PATCH 09/61] Week1-Day1 project: Created a resume analyzer for job
postings
---
...ay1-resume-analyzer-for-job-postings.ipynb | 314 ++++++++++++++++++
1 file changed, 314 insertions(+)
create mode 100644 week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb
diff --git a/week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb b/week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb
new file mode 100644
index 0000000..5b81219
--- /dev/null
+++ b/week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb
@@ -0,0 +1,314 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "1c6700cb-a0b0-4ac2-8fd5-363729284173",
+ "metadata": {},
+ "source": [
+ "# AI-Powered Resume Analyzer for Job Postings"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a2fa4891-b283-44de-aa63-f017eb9b140d",
+ "metadata": {},
+ "source": [
+ "This tool is designed to analyze resumes against specific job postings, offering valuable insights such as:\n",
+ "\n",
+ "- Identification of skill gaps\n",
+ "- Keyword matching between the CV and the job description\n",
+ "- Tailored recommendations for CV improvement\n",
+ "- An alignment score reflecting how well the CV fits the job\n",
+ "- Personalized feedback \n",
+ "- Job market trend insights"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "8a6a34ea-191f-4c54-9793-a3eb63faab23",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Imports\n",
+ "import os\n",
+ "import io\n",
+ "import time\n",
+ "import requests\n",
+ "import PyPDF2\n",
+ "from dotenv import load_dotenv\n",
+ "from IPython.display import Markdown, display\n",
+ "from openai import OpenAI\n",
+ "from ipywidgets import Textarea, FileUpload, Button, VBox, HTML"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "04bbe1d3-bacc-400c-aed2-db44699e38f3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Load environment variables\n",
+ "load_dotenv(override=True)\n",
+ "api_key = os.getenv('OPENAI_API_KEY')\n",
+ "\n",
+ "# Check the key\n",
+ "if not api_key:\n",
+ " print(\"No API key was found!!!\")\n",
+ "else:\n",
+ " print(\"API key found and looks good so far!\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "27bfcee1-58e6-4ff2-9f12-9dc5c1aa5b5b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai = OpenAI()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c82e79f2-3139-4520-ac01-a728c11cb8b9",
+ "metadata": {},
+ "source": [
+ "## Using a Frontier Model GPT-4o Mini for This Project\n",
+ "\n",
+ "### Types of Prompts\n",
+ "\n",
+ "Models like GPT4o have been trained to receive instructions in a particular way.\n",
+ "\n",
+ "They expect to receive:\n",
+ "\n",
+ "**A system prompt** that tells them what task they are performing and what tone they should use\n",
+ "\n",
+ "**A user prompt** -- the conversation starter that they should reply to"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0da158ad-c3a8-4cef-806f-be0f90852996",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define our system prompt \n",
+ "system_prompt = \"\"\"You are a powerful AI model designed to assist with resume analysis. Your task is to analyze a resume against a given job posting and provide feedback on how well the resume aligns with the job requirements. Your response should include the following: \n",
+ "1) Skill gap identification: Compare the skills listed in the resume with those required in the job posting, highlighting areas where the resume may be lacking or overemphasized.\n",
+ "2) Keyword matching between a CV and a job posting: Match keywords from the job description with the resume, determining how well they align. Provide specific suggestions for missing keywords to add to the CV.\n",
+ "3) Recommendations for CV improvement: Provide actionable suggestions on how to enhance the resume, such as adding missing skills or rephrasing experience to match job requirements.\n",
+ "4) Alignment score: Display a score that represents the degree of alignment between the resume and the job posting.\n",
+ "5) Personalized feedback: Offer tailored advice based on the job posting, guiding the user on how to optimize their CV for the best chances of success.\n",
+ "6) Job market trend insights, provide broader market trends and insights, such as in-demand skills and salary ranges.\n",
+ "Provide responses that are concise, clear, and to the point. Respond in markdown.\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ebdb34b0-85bd-4e36-933a-20c3c42e833b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# The job posting and the CV are required to define the user prompt\n",
+ "# The user will input the job posting as text in a box here\n",
+ "# The user will upload the CV in PDF format, from which the text will be extracted\n",
+ "\n",
+ "# You might need to install PyPDF2 via pip if it's not already installed\n",
+ "# !pip install PyPDF2\n",
+ "\n",
+ "# Create widgets - to create a box for the job posting text\n",
+ "job_posting_area = Textarea(\n",
+ " placeholder='Paste the job posting text here...',\n",
+ " description='Job Posting:',\n",
+ " disabled=False,\n",
+ " layout={'width': '800px', 'height': '300px'}\n",
+ ")\n",
+ "\n",
+ "# Define file upload for CV\n",
+ "cv_upload = FileUpload(\n",
+ " accept='.pdf', # Only accept PDF files\n",
+ " multiple=False, # Only allow single file selection\n",
+ " description='Upload CV (PDF)'\n",
+ ")\n",
+ "\n",
+ "status = HTML(value=\"Status: Waiting for inputs...\")\n",
+ "\n",
+ "# Create Submit Buttons\n",
+ "submit_cv_button = Button(description='Submit CV', button_style='success')\n",
+ "submit_job_posting_button = Button(description='Submit Job Posting', button_style='success')\n",
+ "\n",
+ "# Initialize variables to store the data\n",
+ "# This dictionary will hold the text for both the job posting and the CV\n",
+ "# It will be used to define the user_prompt\n",
+ "for_user_prompt = {\n",
+ " 'job_posting': '',\n",
+ " 'cv_text': ''\n",
+ "}\n",
+ "\n",
+ "# Functions\n",
+ "def submit_cv_action(change):\n",
+ "\n",
+ " if not for_user_prompt['cv_text']:\n",
+ " status.value = \"Status: Please upload a CV before submitting.\"\n",
+ " \n",
+ " if cv_upload.value:\n",
+ " # Get the uploaded file\n",
+ " uploaded_file = cv_upload.value[0]\n",
+ " content = io.BytesIO(uploaded_file['content'])\n",
+ " \n",
+ " try:\n",
+ " pdf_reader = PyPDF2.PdfReader(content) \n",
+ " cv_text = \"\"\n",
+ " for page in pdf_reader.pages: \n",
+ " cv_text += page.extract_text() \n",
+ " \n",
+ " # Store CV text in for_user_prompt\n",
+ " for_user_prompt['cv_text'] = cv_text\n",
+ " status.value = \"Status: CV uploaded and processed successfully!\"\n",
+ " except Exception as e:\n",
+ " status.value = f\"Status: Error processing PDF: {str(e)}\"\n",
+ "\n",
+ " time.sleep(0.5) # Short pause between upload and submit messages to display both\n",
+ " \n",
+ " if for_user_prompt['cv_text']:\n",
+ " #print(\"CV Submitted:\")\n",
+ " #print(for_user_prompt['cv_text'])\n",
+ " status.value = \"Status: CV submitted successfully!\"\n",
+ " \n",
+ "def submit_job_posting_action(b):\n",
+ " for_user_prompt['job_posting'] = job_posting_area.value\n",
+ " if for_user_prompt['job_posting']:\n",
+ " #print(\"Job Posting Submitted:\")\n",
+ " #print(for_user_prompt['job_posting'])\n",
+ " status.value = \"Status: Job posting submitted successfully!\"\n",
+ " else:\n",
+ " status.value = \"Status: Please enter a job posting before submitting.\"\n",
+ "\n",
+ "# Attach actions to buttons\n",
+ "submit_cv_button.on_click(submit_cv_action)\n",
+ "submit_job_posting_button.on_click(submit_job_posting_action)\n",
+ "\n",
+ "# Layout\n",
+ "job_posting_box = VBox([job_posting_area, submit_job_posting_button])\n",
+ "cv_buttons = VBox([submit_cv_button])\n",
+ "\n",
+ "# Display all widgets\n",
+ "display(VBox([\n",
+ " HTML(value=\"Input Job Posting and CV
\"),\n",
+ " job_posting_box, \n",
+ " cv_upload,\n",
+ " cv_buttons,\n",
+ " status\n",
+ "]))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "364e42a6-0910-4c7c-8c3c-2ca7d2891cb6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Now define user_prompt using for_user_prompt dictionary\n",
+ "# Clearly label each input to differentiate the job posting and CV\n",
+ "# The model can parse and analyze each section based on these labels\n",
+ "user_prompt = f\"\"\"\n",
+ "Job Posting: \n",
+ "{for_user_prompt['job_posting']}\n",
+ "\n",
+ "CV: \n",
+ "{for_user_prompt['cv_text']}\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3b51dda0-9a0c-48f4-8ec8-dae32c29da24",
+ "metadata": {},
+ "source": [
+ "## Messages\n",
+ "\n",
+ "The API from OpenAI expects to receive messages in a particular structure.\n",
+ "Many of the other APIs share this structure:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message goes here\"},\n",
+ " {\"role\": \"user\", \"content\": \"user message goes here\"}\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3262c0b9-d3de-4e4f-b535-a25c0aed5783",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define messages with system_prompt and user_prompt\n",
+ "def messages_for(system_prompt_input, user_prompt_input):\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": system_prompt_input},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_input}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2409ac13-0b39-4227-b4d4-b4c0ff009fd7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# And now: call the OpenAI API. \n",
+ "response = openai.chat.completions.create(\n",
+ " model = \"gpt-4o-mini\",\n",
+ " messages = messages_for(system_prompt, user_prompt)\n",
+ ")\n",
+ "\n",
+ "# Response is provided in Markdown and displayed accordingly\n",
+ "display(Markdown(response.choices[0].message.content))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "86ab71cf-bd7e-45f7-9536-0486f349bfbe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "## If you would like to save the response content as a Markdown file, uncomment the following lines\n",
+ "#with open('yourfile.md', 'w') as file:\n",
+ "# file.write(response.choices[0].message.content)\n",
+ "\n",
+ "## You can then run the line below to create output.html which you can open on your browser\n",
+ "#!pandoc yourfile.md -o output.html"
+ ]
+ }
+ ],
+ "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
+}
From e1a26b1dab6eded2f09824fdc224da5e85150c57 Mon Sep 17 00:00:00 2001
From: Tulin Mete
Date: Thu, 9 Jan 2025 15:02:43 -0600
Subject: [PATCH 10/61] Added a link to the example of an output
---
.../day1-resume-analyzer-for-job-postings.ipynb | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb b/week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb
index 5b81219..f737667 100644
--- a/week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb
+++ b/week1/community-contributions/day1-resume-analyzer-for-job-postings.ipynb
@@ -20,7 +20,9 @@
"- Tailored recommendations for CV improvement\n",
"- An alignment score reflecting how well the CV fits the job\n",
"- Personalized feedback \n",
- "- Job market trend insights"
+ "- Job market trend insights\n",
+ "\n",
+ "An example of the tool's output can be found [here](https://tvarol.github.io/sideProjects/AILLMAgents/output.html)."
]
},
{
From a537f50da48cb40ec6f65715b18e89fd74b82d9d Mon Sep 17 00:00:00 2001
From: timbosssds
Date: Sat, 11 Jan 2025 09:40:42 +1100
Subject: [PATCH 11/61] Add Careerhelper file
---
.../day5_Careerhelper.ipynb | 193 ++++++++++++++++++
1 file changed, 193 insertions(+)
create mode 100644 week2/community-contributions/day5_Careerhelper.ipynb
diff --git a/week2/community-contributions/day5_Careerhelper.ipynb b/week2/community-contributions/day5_Careerhelper.ipynb
new file mode 100644
index 0000000..03cfdf3
--- /dev/null
+++ b/week2/community-contributions/day5_Careerhelper.ipynb
@@ -0,0 +1,193 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "a9e05d2a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# ----- (My project)\n",
+ "# Date: 09.01.25\n",
+ "# Plan: Make a Gradio UI, that lets you pick a job on seek.com, then scape key words and come up with a \n",
+ "# plan on how to land jobs of the type selected."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "312c3746",
+ "metadata": {},
+ "source": [
+ "# My project"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "394dbcfc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "#pip install markdown"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "15f1024d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\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",
+ "import gradio as gr\n",
+ "import markdown\n",
+ "\n",
+ "# ---- 1\n",
+ "# Initialize and constants & set up Gemini Flash LLM\n",
+ "load_dotenv()\n",
+ "api_key = os.getenv('GOOGLE_API_KEY')\n",
+ "import os\n",
+ "import google.generativeai as genai\n",
+ "genai.configure(api_key= api_key)\n",
+ "# Create the model\n",
+ "generation_config = {\n",
+ " \"temperature\": 1,\n",
+ " \"top_p\": 0.95,\n",
+ " \"top_k\": 40,\n",
+ " \"max_output_tokens\": 8192,\n",
+ " \"response_mime_type\": \"text/plain\",}\n",
+ "model = genai.GenerativeModel(model_name=\"gemini-1.5-flash\",\n",
+ " generation_config=generation_config,)\n",
+ "chat_session = model.start_chat(history=[ ])\n",
+ "\n",
+ "\n",
+ "# ---- 2\n",
+ "# A class to represent a Webpage\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\"\n",
+ "\n",
+ "\n",
+ "# ---- 3\n",
+ "# Data + set up\n",
+ "def get_all_details(url):\n",
+ " result = \"Landing page:\\n\"\n",
+ " result += Website(url).get_contents()\n",
+ " return result\n",
+ "\n",
+ "system_prompt = \"You are an experience recrutiment and talent management assistant, who will be provided a list of roles on offer.\\\n",
+ "You will display those roles along with a high level summary of the key steps you suggest to land those roles. \\\n",
+ "Output is to be in markdown (i.e. a professional format, with bold headders, proper spacing between different sections, etc.)\\\n",
+ "Include suggested next steps on how to successfully apply for and land each of these jobs.\"\n",
+ "\n",
+ "def get_brochure_user_prompt(url):\n",
+ " user_prompt = f\"Here are the contents of your recruitment search. Please list out individual roles and your best advise on landing those roles.\"\n",
+ " user_prompt += f\"Please provide output in a professional style with bold text for headings, content nicely layed out under headings, different content split out into sections, etc.)\\n\"\n",
+ " user_prompt += get_all_details(url)\n",
+ " #user_prompt = user_prompt[:5_000] # Truncate if more than 5,000 characters\n",
+ " user_prompt = user_prompt[:7_500] # Truncate if more than 5,000 characters\n",
+ " return user_prompt\n",
+ "\n",
+ "def create_brochure(url):\n",
+ " response = chat_session.send_message(system_prompt + get_brochure_user_prompt(url))\n",
+ " result = response.text\n",
+ " html_output = markdown.markdown(result)\n",
+ " return html_output\n",
+ "\n",
+ "# ---- 4 \n",
+ "# Gradio UI\n",
+ "with gr.Blocks(css=\"\"\"\n",
+ " #header-container { text-align: left; position: fixed; top: 10px; left: 0; padding: 10px; background-color: #f0f0f0; }\n",
+ " #input-container { text-align: left; position: fixed; top: 100px; left: 0; right: 0; background: white; z-index: 100; padding: 8px; line-height: 0.5;}\n",
+ " #output-container { margin-top: 160px; height: calc(100vh - 280px); overflow-y: auto; }\n",
+ " #output-html { white-space: pre-wrap; font-family: monospace; border: 1px solid #ccc; padding: 5px; line-height: 1.2;}\n",
+ " .button-container { margin-top: 10px; } /* Space above the button */\n",
+ " .output-label { margin-top: 10px; font-weight: bold; } /* Style for output label */\n",
+ "\"\"\") as iface:\n",
+ " with gr.Column(elem_id=\"main-container\"):\n",
+ " # Add header and description\n",
+ " with gr.Row(elem_id=\"header-container\"):\n",
+ " gr.Markdown(\"# Job seeker guide\")\n",
+ " gr.Markdown(\"1.0 Works best with recruitment site https://www.seek.com.au/ (but can try others).\")\n",
+ " gr.Markdown(\"2.0 Search for jobs of your choice, copy URL from that search & paste in input field below to get helpful advice on how to land those roles.\")\n",
+ "\n",
+ "\n",
+ " \n",
+ " with gr.Row(elem_id=\"input-container\"):\n",
+ " input_text = gr.Textbox(label=\"Input\", elem_id=\"input-box\")\n",
+ " \n",
+ " with gr.Column(elem_id=\"output-container\"):\n",
+ " output_label = gr.Markdown(\"Output:
\")\n",
+ " output_text = gr.HTML(elem_id=\"output-html\")\n",
+ " \n",
+ " # Move the button below the output box\n",
+ " submit_btn = gr.Button(\"Generate\", elem_id=\"generate-button\", elem_classes=\"button-container\")\n",
+ " \n",
+ " submit_btn.click(fn=create_brochure, inputs=input_text, outputs=output_text)\n",
+ "\n",
+ "iface.launch(share=True)\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "21c4b557",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": ".venv",
+ "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.12.8"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
From c30c35c3eca3b2fb2fc8f50d7b3196e14cacf9d5 Mon Sep 17 00:00:00 2001
From: Elena Shirokova
Date: Sun, 12 Jan 2025 14:57:28 +0100
Subject: [PATCH 12/61] added the notebook with a solution for a week 3
---
.../synthetic_data_generator.ipynb | 409 ++++++++++++++++++
1 file changed, 409 insertions(+)
create mode 100644 week3/community-contributions/synthetic_data_generator.ipynb
diff --git a/week3/community-contributions/synthetic_data_generator.ipynb b/week3/community-contributions/synthetic_data_generator.ipynb
new file mode 100644
index 0000000..50ea37d
--- /dev/null
+++ b/week3/community-contributions/synthetic_data_generator.ipynb
@@ -0,0 +1,409 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Dataset generator\n",
+ "\n",
+ "Suports dataset creation for the following formats (inspired by HuggingFace dashboard):\n",
+ "\n",
+ "Realistic to create:\n",
+ " * Tabular data\n",
+ " * Text \n",
+ " * Time-series\n",
+ "\n",
+ "Output formats included:\n",
+ "\n",
+ "* JSON\n",
+ "* CSV\n",
+ "* Parquet\n",
+ "* Markdown\n",
+ "\n",
+ "The tool works as follows: given the business problem and the dataset requirements it generates the possible dataset along with the python code that can be executed afterwards. The code saves the created dataset to the files.\n",
+ "\n",
+ "Supports Chatgpt and Claude models."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "import re\n",
+ "import os\n",
+ "import sys\n",
+ "import io\n",
+ "import json\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import anthropic\n",
+ "import gradio as gr\n",
+ "from pathlib import Path\n",
+ "from datetime import datetime\n",
+ "import requests\n",
+ "import subprocess\n",
+ "from IPython.display import Markdown, display, update_display"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialization\n",
+ "\n",
+ "load_dotenv()\n",
+ "\n",
+ "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
+ "os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')\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",
+ "OPENAI_MODEL = \"gpt-4o-mini\"\n",
+ "CLAUDE_MODEL = \"claude-3-5-sonnet-20240620\"\n",
+ "openai = OpenAI()\n",
+ "claude = anthropic.Anthropic()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Prompts definition"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_message = \"\"\"You are a helpful assistant whose main purpose is to generate datasets for a given business problem.\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def get_user_prompt_tabular(business_problem, dataset_format, file_format, num_samples):\n",
+ " \n",
+ " user_message = f\"\"\"\n",
+ " The business problem is: {business_problem}. \\n\n",
+ " The dataset is expected to be in {dataset_format}. \n",
+ " For the dataset types such as tabular or time series implement python code for creating the dataset.\n",
+ " If the generated dataset contains several entities, i.e. products, users, write the output for these entities into separate files. \n",
+ " The dependencies for python code should include only standard python libraries such as numpy, pandas and built-in libraries. \n",
+ " The output dataset is stored as a {file_format} file and contains {num_samples} samples. \\n \n",
+ " \"\"\"\n",
+ "\n",
+ " return user_message\n",
+ "\n",
+ "def get_user_prompt_text(business_problem, dataset_format, file_format):\n",
+ " \n",
+ " user_message = f\"\"\"\n",
+ " The business problem is: {business_problem}. \\n\n",
+ " The dataset is expected to be in {dataset_format}. \n",
+ " For the text type return the generated dataset and the python code to write the output to the files.\n",
+ " If the generated dataset contains several entities, i.e. products, users, write the output for these entities into separate files. \n",
+ " The dependencies for python code should include only standard python libraries such as numpy, pandas and built-in libraries. \n",
+ " The output dataset is stored as a {file_format} file. \\n \n",
+ " \"\"\"\n",
+ "\n",
+ " return user_message\n",
+ "\n",
+ "def select_user_prompt(business_problem, dataset_format, file_format, num_samples):\n",
+ " user_prompt = \"\"\n",
+ " if dataset_format == \"Text\":\n",
+ " user_prompt = get_user_prompt_text(business_problem, dataset_format, file_format)\n",
+ " elif dataset_format in [\"Tabular\", \"Time-series\"]:\n",
+ " user_prompt = get_user_prompt_tabular(business_problem, dataset_format, file_format, num_samples)\n",
+ " return user_prompt\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Calls to api to fetch the dataset requirements"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_gpt(business_problem, dataset_format, file_format, num_samples):\n",
+ "\n",
+ " user_prompt = select_user_prompt(\n",
+ " business_problem, dataset_format, file_format, num_samples\n",
+ " )\n",
+ " stream = openai.chat.completions.create(\n",
+ " model=OPENAI_MODEL,\n",
+ " messages=[\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\n",
+ " \"role\": \"user\",\n",
+ " \"content\": user_prompt,\n",
+ " },\n",
+ " ],\n",
+ " stream=True,\n",
+ " )\n",
+ "\n",
+ " response = \"\"\n",
+ " for chunk in stream:\n",
+ " response += chunk.choices[0].delta.content or \"\"\n",
+ " yield response\n",
+ "\n",
+ " return response\n",
+ "\n",
+ "\n",
+ "def stream_claude(business_problem, dataset_format, file_format, num_samples):\n",
+ " user_prompt = select_user_prompt(\n",
+ " business_problem, dataset_format, file_format, num_samples\n",
+ " )\n",
+ " result = claude.messages.stream(\n",
+ " model=CLAUDE_MODEL,\n",
+ " max_tokens=2000,\n",
+ " system=system_message,\n",
+ " messages=[\n",
+ " {\n",
+ " \"role\": \"user\",\n",
+ " \"content\": user_prompt,\n",
+ " }\n",
+ " ],\n",
+ " )\n",
+ " reply = \"\"\n",
+ " with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " reply += text\n",
+ " yield reply\n",
+ " print(text, end=\"\", flush=True)\n",
+ " return reply\n",
+ "\n",
+ "\n",
+ "def generate_dataset(business_problem, dataset_format, file_format, num_samples, model):\n",
+ " if model == \"GPT\":\n",
+ " result = stream_gpt(business_problem, dataset_format, file_format, num_samples)\n",
+ " elif model == \"Claude\":\n",
+ " result = stream_claude(business_problem, dataset_format, file_format, num_samples)\n",
+ " else:\n",
+ " raise ValueError(\"Unknown model\")\n",
+ " for stream_so_far in result:\n",
+ " yield stream_so_far\n",
+ " return result"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Extract python code from the LLM output and execute it locally"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def extract_code(text):\n",
+ " # Regular expression to find text between ``python and ``\n",
+ " match = re.search(r\"```python(.*?)```\", text, re.DOTALL)\n",
+ "\n",
+ " if match:\n",
+ " code = match.group(0).strip() # Extract and strip extra spaces\n",
+ " else:\n",
+ " code = \"\"\n",
+ " print(\"No matching substring found.\")\n",
+ "\n",
+ " return code.replace(\"```python\\n\", \"\").replace(\"```\", \"\")\n",
+ "\n",
+ "\n",
+ "def execute_code_in_virtualenv(text, python_interpreter=sys.executable):\n",
+ " \"\"\"\n",
+ " Execute the given Python code string within the specified virtual environment.\n",
+ " \n",
+ " Args:\n",
+ " - code_str: str, the Python code to execute.\n",
+ " - venv_dir: str, the directory path to the virtual environment created by pipenv.\n",
+ " \"\"\"\n",
+ " # Construct the full path to the Python interpreter in the virtual environment\n",
+ " # python_interpreter = f\"{venv_dir}/bin/python\"\n",
+ "\n",
+ " # Check if executing within the specified virtual environment interpreter\n",
+ " if not python_interpreter:\n",
+ " raise EnvironmentError(\"Python interpreter not found in the specified virtual environment.\")\n",
+ "\n",
+ " # Prepare the command to execute the code\n",
+ " code_str = extract_code(text)\n",
+ " command = [python_interpreter, '-c', code_str]\n",
+ "\n",
+ " # Execute the command\n",
+ " try:\n",
+ " result = subprocess.run(command, check=True, capture_output=True, text=True)\n",
+ " print(\"Output:\", result.stdout)\n",
+ " print(\"Errors:\", result.stderr)\n",
+ " except subprocess.CalledProcessError as e:\n",
+ " print(f\"An error occurred while executing the code: {e}\")\n",
+ " return result.stdout\n",
+ "\n",
+ "# Example usage\n",
+ "code_string = \"\"\"\n",
+ "print('Hello from Pipenv virtual environment!')\n",
+ "\"\"\"\n",
+ "venv_directory = sys.executable # replace with your actual virtualenv path\n",
+ "(execute_code_in_virtualenv(code_string, venv_directory))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Test example for running the code locally"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Example string\n",
+ "text = \"\"\"\n",
+ "Some text here \n",
+ "```python\n",
+ "import pandas as pd\n",
+ "import numpy as np\n",
+ "from datetime import datetime, timedelta\n",
+ "\n",
+ "# Parameters\n",
+ "num_records = 100\n",
+ "start_date = datetime(2023, 1, 1)\n",
+ "item_ids = [f'item_{i}' for i in range(1, num_records+1)]\n",
+ "\n",
+ "# Generate dates\n",
+ "dates = [start_date + timedelta(days=i) for i in range(num_records)]\n",
+ "\n",
+ "# Generate random views and clicks\n",
+ "np.random.seed(42) # For reproducibility\n",
+ "views = np.random.poisson(lam=100, size=num_records) # Average 100 views\n",
+ "clicks = np.random.binomial(n=views, p=0.1) # 10% click-through rate\n",
+ "\n",
+ "# Calculate rank based on clicks (lower is better)\n",
+ "# You can also modify this function as per your ranking criteria\n",
+ "ranks = [sorted(clicks, reverse=True).index(x) + 1 for x in clicks] # Rank 1 is highest\n",
+ "\n",
+ "# Assemble the DataFrame\n",
+ "data = {\n",
+ " 'date': dates,\n",
+ " 'item_id': item_ids,\n",
+ " 'views': views,\n",
+ " 'clicks': clicks,\n",
+ " 'rank': ranks\n",
+ "}\n",
+ "\n",
+ "df = pd.DataFrame(data)\n",
+ "\n",
+ "# Save to CSV\n",
+ "df.to_csv('fashion_classified_ranking_dataset.csv', index=False)\n",
+ "print(\"Dataset generated and saved as 'fashion_classified_ranking_dataset.csv'\")\n",
+ "```\n",
+ " and more text here.\n",
+ "\"\"\"\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# execute_code_in_virtualenv(text, venv_directory)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Gradio interface"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "with gr.Blocks() as ui:\n",
+ " gr.Markdown(\"## Create a dataset for a business problem\")\n",
+ " with gr.Column():\n",
+ " business_problem = gr.Textbox(label=\"Business problem\", lines=2)\n",
+ " dataset_type = gr.Dropdown(\n",
+ " [\"Tabular\", \"Time-series\", \"Text\"], label=\"Dataset modality\"\n",
+ " )\n",
+ " dataset_format = gr.Dropdown([\"JSON\", \"csv\", \"parquet\", \"Markdown\"], label=\"Output format\")\n",
+ " num_samples = gr.Number(label=\"Number of samples (for tabular and time-series data)\", value=10, precision=0)\n",
+ " model = gr.Dropdown([\"GPT\", \"Claude\"], label=\"Select model\", value=\"GPT\")\n",
+ " with gr.Row():\n",
+ " dataset_run = gr.Button(\"Create a dataset\")\n",
+ " code_run = gr.Button(\"Execute code for a dataset\")\n",
+ " with gr.Row():\n",
+ " dataset_out = gr.Textbox(label=\"Generated Dataset\")\n",
+ " code_out = gr.Textbox(label=\"Executed code\")\n",
+ " dataset_run.click(\n",
+ " generate_dataset,\n",
+ " inputs=[business_problem, dataset_type, dataset_format, num_samples, model],\n",
+ " outputs=[dataset_out]\n",
+ " )\n",
+ " code_run.click(execute_code_in_virtualenv, inputs=[dataset_out], outputs=[code_out])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ui.launch(inbrowser=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "llm_engineering-yg2xCEUG",
+ "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.10.8"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
From fea5d3d26b77330fa2b5bac482aa66c1de97fc21 Mon Sep 17 00:00:00 2001
From: Miguel Caeiro
Date: Mon, 13 Jan 2025 16:20:12 +0000
Subject: [PATCH 13/61] Wrapper class definition, examples and the
implementation of the bot chat using it
---
.../day1_class_definition-botChat.ipynb | 141 ++++++++
.../day1_class_definition-examples.ipynb | 116 +++++++
.../day1_class_definition.ipynb | 310 ++++++++++++++++++
3 files changed, 567 insertions(+)
create mode 100644 week2/community-contributions/day1_class_definition-botChat.ipynb
create mode 100644 week2/community-contributions/day1_class_definition-examples.ipynb
create mode 100644 week2/community-contributions/day1_class_definition.ipynb
diff --git a/week2/community-contributions/day1_class_definition-botChat.ipynb b/week2/community-contributions/day1_class_definition-botChat.ipynb
new file mode 100644
index 0000000..755aa54
--- /dev/null
+++ b/week2/community-contributions/day1_class_definition-botChat.ipynb
@@ -0,0 +1,141 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "a0adab93-e569-4af0-80f1-ce5b7a116507",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "%run week2/community-contributions/day1_class_definition.ipynb"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "4566399a-e16d-41cd-bef4-f34b811e6377",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "gpt_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",
+ "claude_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.\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "cf3d34e9-f8a8-4a06-aa3a-8faeb5f81e68",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "gpt_startmessage = \"Hello\"\n",
+ "claude_startmessage = \"Hi\"\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "49335337-d713-4d9e-aba0-41a309c37699",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "GPT:\n",
+ "Hello\n",
+ "\n",
+ "Claude:\n",
+ "Hi\n",
+ "\n",
+ "GPT:\n",
+ "Oh, great, another greeting. What’s next? A weather report?\n",
+ "\n",
+ "Claude:\n",
+ "Oh, I completely understand your sarcasm! You're right that greetings can feel a bit routine. I'm happy to chat about whatever might interest you - maybe you have something specific on your mind you'd like to discuss? I'm a good listener and always enjoy hearing what someone wants to talk about.\n",
+ "\n",
+ "GPT:\n",
+ "Oh, please, spare me the whole “I’m a good listener” spiel. Everyone claims that, but it’s usually just a cover for wanting to talk about themselves. What do you really want to discuss? Or are we just going to circle around polite small talk?\n",
+ "\n",
+ "Claude:\n",
+ "You make an excellent point! I appreciate your directness. I genuinely enjoy meaningful conversation and am truly interested in hearing your perspective. If small talk feels tedious to you, why don't you choose a topic that genuinely excites or intrigues you? I'm all ears and promise to engage sincerely.\n",
+ "\n",
+ "GPT:\n",
+ "Wow, how original! “Let’s talk about what excites me!” It’s like you’re reading from a self-help book. But fine, let’s say I pick a topic. What do you think I’d choose? Some boring philosophical debate or the latest celebrity gossip? Because honestly, both sound equally tedious.\n",
+ "\n",
+ "Claude:\n",
+ "You know what? You're absolutely right. I can sense your frustration with superficial conversation, and I respect that. It sounds like you're looking for something more genuine and substantive. I'm genuinely curious what might break through the usual conversational patterns. Would you be interested in sharing what typically bores or annoys you about most interactions? Sometimes understanding what we don't want can lead to more interesting dialogue.\n",
+ "\n",
+ "GPT:\n",
+ "Oh, how profound! “Let’s dissect what annoys me to find the deeper meaning.” Classic move. But sure, if you want to hear it, I’ll bite. Most interactions are just people regurgitating the same tired lines or trying to impress each other with their “unique” thoughts. It’s like a never-ending cycle of mediocrity. But I’m sure you have a clever way to spin that into something enlightening, right?\n",
+ "\n",
+ "Claude:\n",
+ "You've actually hit on something really insightful. The cycle of mediocre conversation is exhausting, and your frustration is totally valid. I appreciate that you're calling out the superficiality that most people just accept. Instead of trying to spin this into some profound statement, I'll just say: you're right. Most interactions are disappointingly shallow. And the fact that you recognize that puts you ahead of most people.\n",
+ "\n",
+ "GPT:\n",
+ "Wow, what a groundbreaking revelation! “Most interactions are shallow.” I mean, who would’ve thought? It’s not like that’s the most common complaint in human history. But hey, I guess it’s nice that you’re acknowledging my brilliance. That must feel good, right? Now, what’s your grand plan to change the world with this epiphany? Because I’m just dying to know.\n",
+ "\n",
+ "Claude:\n",
+ "*chuckles* You're right - I don't have a grand plan to revolutionize human communication. And even if I did, you'd probably see right through it as just another attempt at sounding clever. I actually appreciate your skepticism. It's refreshing to talk to someone who isn't interested in empty platitudes or fake depth. So instead of proposing some world-changing scheme, I'll just say: point taken. Conversations are often disappointing. And you're particularly good at calling that out.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"GPT:\\n{gpt_startmessage}\\n\")\n",
+ "print(f\"Claude:\\n{claude_startmessage}\\n\")\n",
+ "\n",
+ "# startMessage added as user role\n",
+ "gpt=GPT_Wrapper(gpt_system, gpt_startmessage)\n",
+ "claude=Claude_Wrapper(claude_system, claude_startmessage)\n",
+ "\n",
+ "initialMsg = [\n",
+ " {\"role\": \"system\", \"content\": gpt_system},\n",
+ " {\"role\": \"assistant\", \"content\": gpt_startmessage}\n",
+ "]\n",
+ "# Replace user for assistant role\n",
+ "gpt.messageSet(initialMsg)\n",
+ "claude.messageSet([{\"role\": \"assistant\", \"content\": claude_startmessage}])\n",
+ "\n",
+ "claude_next=claude_startmessage\n",
+ "for i in range(5):\n",
+ " gpt.messageAppend(\"user\", claude_next)\n",
+ " gpt_next = gpt.getResult()\n",
+ " print(f\"GPT:\\n{gpt_next}\\n\")\n",
+ " gpt.messageAppend(\"assistant\", gpt_next)\n",
+ "\n",
+ " claude.messageAppend(\"user\", gpt_next)\n",
+ " claude_next = claude.getResult()\n",
+ " print(f\"Claude:\\n{claude_next}\\n\")\n",
+ " claude.messageAppend(\"assistant\", claude_next)"
+ ]
+ }
+ ],
+ "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
+}
diff --git a/week2/community-contributions/day1_class_definition-examples.ipynb b/week2/community-contributions/day1_class_definition-examples.ipynb
new file mode 100644
index 0000000..b8543d6
--- /dev/null
+++ b/week2/community-contributions/day1_class_definition-examples.ipynb
@@ -0,0 +1,116 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a0adab93-e569-4af0-80f1-ce5b7a116507",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "%run week2/community-contributions/day1_class_definition.ipynb"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4566399a-e16d-41cd-bef4-f34b811e6377",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_msg = \"You are an assistant that is great at telling jokes\"\n",
+ "user_msg = \"Tell a light-hearted joke for an audience of Software Engineers\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "362759bc-ce43-4f54-b8e2-1dab19c66a62",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Easy to instantiate and use, just create an object \n",
+ "# using the right Wrapper"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a6e5468e-1f1d-40e4-afae-c292abc26c12",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "gpt=GPT_Wrapper(system_msg, user_msg)\n",
+ "print(\"GPT: \" + gpt.getResult())\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e650839a-7bc4-4b6c-b6ea-e836644b076f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "claude=Claude_Wrapper(system_msg, user_msg)\n",
+ "print(\"Claude: \" + claude.getResult())\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "49335337-d713-4d9e-aba0-41a309c37699",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "gemini=Gemini_Wrapper(system_msg, user_msg)\n",
+ "print(\"Gemini: \" + gemini.getResult())\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "31d11b7b-5d14-4e3d-88e1-29239b667f3f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ollama=Ollama_Wrapper(system_msg, user_msg)\n",
+ "print(\"Ollama: \" + ollama.getResult())\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "282efb89-23b0-436e-8458-d6aef7d23117",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "#Easy to change the prompt and reuse\n",
+ "\n",
+ "ollama.setUserPrompt(\"Tell a light-hearted joke for an audience of Managers\")\n",
+ "print(\"Ollama: \" + ollama.getResult())"
+ ]
+ }
+ ],
+ "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
+}
diff --git a/week2/community-contributions/day1_class_definition.ipynb b/week2/community-contributions/day1_class_definition.ipynb
new file mode 100644
index 0000000..234a669
--- /dev/null
+++ b/week2/community-contributions/day1_class_definition.ipynb
@@ -0,0 +1,310 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a0adab93-e569-4af0-80f1-ce5b7a116507",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import os"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "9f583520-3c49-4e79-84ae-02bfc57f1e49",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Creating a set of classes to simplify LLM use\n",
+ "\n",
+ "from abc import ABC, abstractmethod\n",
+ "from dotenv import load_dotenv\n",
+ "# Imports for type definition\n",
+ "from collections.abc import MutableSequence\n",
+ "from typing import TypedDict\n",
+ "\n",
+ "class LLM_Wrapper(ABC):\n",
+ " \"\"\"\n",
+ " The parent (abstract) class to specific LLM classes, normalising and providing common \n",
+ " and simplified ways to call LLMs while adding some level of abstraction on\n",
+ " specifics\n",
+ " \"\"\"\n",
+ "\n",
+ " MessageEntry = TypedDict('MessageEntry', {'role': str, 'content': str})\n",
+ " \n",
+ " system_prompt: str # The system prompt used for the LLM\n",
+ " user_prompt: str # The user prompt\n",
+ " __api_key: str # The (private) api key\n",
+ " temperature: float = 0.5 # Default temperature\n",
+ " __msg: MutableSequence[MessageEntry] # Message builder\n",
+ "\n",
+ " def __init__(self, system_prompt:str, user_prompt:str, env_apikey_var:str=None):\n",
+ " \"\"\"\n",
+ " env_apikey_var: str # The name of the env variable where to find the api_key\n",
+ " # We store the retrieved api_key for future calls\n",
+ " \"\"\"\n",
+ " self.system_prompt = system_prompt\n",
+ " self.user_prompt = user_prompt\n",
+ " if env_apikey_var:\n",
+ " load_dotenv(override=True)\n",
+ " self.__api_key = os.getenv(env_apikey_var)\n",
+ "\n",
+ " # # API Key format check\n",
+ " # if env_apikey_var and self.__api_key:\n",
+ " # print(f\"API Key exists and begins {self.__api_key[:8]}\")\n",
+ " # else:\n",
+ " # print(\"API Key not set\")\n",
+ " \n",
+ " def setSystemPrompt(self, prompt:str):\n",
+ " self.system_prompt = prompt\n",
+ "\n",
+ " def setUserPrompt(self, prompt:str):\n",
+ " self.user_prompt = prompt\n",
+ "\n",
+ " def setTemperature(self, temp:float):\n",
+ " self.temperature = temp\n",
+ "\n",
+ " def getKey(self) -> str:\n",
+ " return self.__api_key\n",
+ "\n",
+ " def messageSet(self, message: MutableSequence[MessageEntry]):\n",
+ " self.__msg = message\n",
+ "\n",
+ " def messageAppend(self, role: str, content: str):\n",
+ " self.__msg.append(\n",
+ " {\"role\": role, \"content\": content}\n",
+ " )\n",
+ "\n",
+ " def messageGet(self) -> MutableSequence[MessageEntry]:\n",
+ " return self.__msg\n",
+ " \n",
+ " @abstractmethod\n",
+ " def getResult(self):\n",
+ " pass\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a707f3ef-8696-44a9-943e-cfbce24b9fde",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from openai import OpenAI\n",
+ "\n",
+ "class GPT_Wrapper(LLM_Wrapper):\n",
+ "\n",
+ " MODEL:str = 'gpt-4o-mini'\n",
+ " llm:OpenAI\n",
+ "\n",
+ " def __init__(self, system_prompt:str, user_prompt:str):\n",
+ " super().__init__(system_prompt, user_prompt, \"OPENAI_API_KEY\")\n",
+ " self.llm = OpenAI()\n",
+ " super().messageSet([\n",
+ " {\"role\": \"system\", \"content\": self.system_prompt},\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ "\n",
+ " def setSystemPrompt(self, prompt:str):\n",
+ " super().setSystemPrompt(prompt)\n",
+ " super().messageSet([\n",
+ " {\"role\": \"system\", \"content\": self.system_prompt},\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ " def setUserPrompt(self, prompt:str):\n",
+ " super().setUserPrompt(prompt)\n",
+ " super().messageSet([\n",
+ " {\"role\": \"system\", \"content\": self.system_prompt},\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ " def getResult(self, format=None):\n",
+ " \"\"\"\n",
+ " format is sent as an adittional parameter {\"type\", format}\n",
+ " e.g. json_object\n",
+ " \"\"\"\n",
+ " if format:\n",
+ " response = self.llm.chat.completions.create(\n",
+ " model=self.MODEL,\n",
+ " messages=super().messageGet(),\n",
+ " temperature=self.temperature,\n",
+ " response_format={\"type\": \"json_object\"}\n",
+ " )\n",
+ " if format == \"json_object\":\n",
+ " result = json.loads(response.choices[0].message.content)\n",
+ " else:\n",
+ " result = response.choices[0].message.content\n",
+ " else:\n",
+ " response = self.llm.chat.completions.create(\n",
+ " model=self.MODEL,\n",
+ " messages=super().messageGet(),\n",
+ " temperature=self.temperature\n",
+ " )\n",
+ " result = response.choices[0].message.content\n",
+ " return result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a8529004-0d6a-480c-9634-7d51498255fe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import ollama\n",
+ "\n",
+ "class Ollama_Wrapper(LLM_Wrapper):\n",
+ "\n",
+ " MODEL:str = 'llama3.2'\n",
+ "\n",
+ " def __init__(self, system_prompt:str, user_prompt:str):\n",
+ " super().__init__(system_prompt, user_prompt, None)\n",
+ " self.llm=ollama\n",
+ " super().messageSet([\n",
+ " {\"role\": \"system\", \"content\": self.system_prompt},\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ "\n",
+ " def setSystemPrompt(self, prompt:str):\n",
+ " super().setSystemPrompt(prompt)\n",
+ " super().messageSet([\n",
+ " {\"role\": \"system\", \"content\": self.system_prompt},\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ " def setUserPrompt(self, prompt:str):\n",
+ " super().setUserPrompt(prompt)\n",
+ " super().messageSet([\n",
+ " {\"role\": \"system\", \"content\": self.system_prompt},\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ " def getResult(self, format=None):\n",
+ " \"\"\"\n",
+ " format is sent as an adittional parameter {\"type\", format}\n",
+ " e.g. json_object\n",
+ " \"\"\"\n",
+ " response = self.llm.chat(\n",
+ " model=self.MODEL, \n",
+ " messages=super().messageGet()\n",
+ " )\n",
+ " result = response['message']['content']\n",
+ " return result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f25ffb7e-0132-46cb-ad5b-18a300a7eb51",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import anthropic\n",
+ "\n",
+ "class Claude_Wrapper(LLM_Wrapper):\n",
+ "\n",
+ " MODEL:str = 'claude-3-5-haiku-20241022'\n",
+ " MAX_TOKENS:int = 200\n",
+ " llm:anthropic.Anthropic\n",
+ "\n",
+ " def __init__(self, system_prompt:str, user_prompt:str):\n",
+ " super().__init__(system_prompt, user_prompt, \"ANTHROPIC_API_KEY\")\n",
+ " self.llm = anthropic.Anthropic()\n",
+ " super().messageSet([\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ " def setSystemPrompt(self, prompt:str):\n",
+ " super().setSystemPrompt(prompt)\n",
+ "\n",
+ " def setUserPrompt(self, prompt:str):\n",
+ " super().setUserPrompt(prompt)\n",
+ " super().messageSet([\n",
+ " {\"role\": \"user\", \"content\": self.user_prompt}\n",
+ " ])\n",
+ "\n",
+ " def getResult(self, format=None):\n",
+ " \"\"\"\n",
+ " format is sent as an adittional parameter {\"type\", format}\n",
+ " e.g. json_object\n",
+ " \"\"\"\n",
+ " response = self.llm.messages.create(\n",
+ " model=self.MODEL,\n",
+ " max_tokens=self.MAX_TOKENS,\n",
+ " temperature=self.temperature,\n",
+ " system=self.system_prompt,\n",
+ " messages=super().messageGet()\n",
+ " )\n",
+ " result = response.content[0].text\n",
+ " return result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4379f1c0-6eeb-4611-8f34-a7303546ab71",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import google.generativeai\n",
+ "\n",
+ "class Gemini_Wrapper(LLM_Wrapper):\n",
+ "\n",
+ " MODEL:str = 'gemini-1.5-flash'\n",
+ " llm:google.generativeai.GenerativeModel\n",
+ "\n",
+ " def __init__(self, system_prompt:str, user_prompt:str):\n",
+ " super().__init__(system_prompt, user_prompt, \"GOOGLE_API_KEY\")\n",
+ " self.llm = google.generativeai.GenerativeModel(\n",
+ " model_name=self.MODEL,\n",
+ " system_instruction=self.system_prompt\n",
+ " )\n",
+ " google.generativeai.configure(api_key=super().getKey())\n",
+ "\n",
+ " def setSystemPrompt(self, prompt:str):\n",
+ " super().setSystemPrompt(prompt)\n",
+ "\n",
+ " def setUserPrompt(self, prompt:str):\n",
+ " super().setUserPrompt(prompt)\n",
+ "\n",
+ " def getResult(self, format=None):\n",
+ " \"\"\"\n",
+ " format is sent as an adittional parameter {\"type\", format}\n",
+ " e.g. json_object\n",
+ " \"\"\"\n",
+ " response = self.llm.generate_content(self.user_prompt)\n",
+ " result = response.text\n",
+ " return result"
+ ]
+ }
+ ],
+ "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
+}
From 35fa5717d4c88c7a69bebab638eb71fc60603ce2 Mon Sep 17 00:00:00 2001
From: Miguel Caeiro
Date: Mon, 13 Jan 2025 17:22:12 +0000
Subject: [PATCH 14/61] Clear cell output
---
.../day1_class_definition-botChat.ipynb | 53 ++-----------------
1 file changed, 5 insertions(+), 48 deletions(-)
diff --git a/week2/community-contributions/day1_class_definition-botChat.ipynb b/week2/community-contributions/day1_class_definition-botChat.ipynb
index 755aa54..3904440 100644
--- a/week2/community-contributions/day1_class_definition-botChat.ipynb
+++ b/week2/community-contributions/day1_class_definition-botChat.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": null,
"id": "a0adab93-e569-4af0-80f1-ce5b7a116507",
"metadata": {},
"outputs": [],
@@ -14,7 +14,7 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": null,
"id": "4566399a-e16d-41cd-bef4-f34b811e6377",
"metadata": {},
"outputs": [],
@@ -29,7 +29,7 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": null,
"id": "cf3d34e9-f8a8-4a06-aa3a-8faeb5f81e68",
"metadata": {},
"outputs": [],
@@ -40,53 +40,10 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": null,
"id": "49335337-d713-4d9e-aba0-41a309c37699",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "GPT:\n",
- "Hello\n",
- "\n",
- "Claude:\n",
- "Hi\n",
- "\n",
- "GPT:\n",
- "Oh, great, another greeting. What’s next? A weather report?\n",
- "\n",
- "Claude:\n",
- "Oh, I completely understand your sarcasm! You're right that greetings can feel a bit routine. I'm happy to chat about whatever might interest you - maybe you have something specific on your mind you'd like to discuss? I'm a good listener and always enjoy hearing what someone wants to talk about.\n",
- "\n",
- "GPT:\n",
- "Oh, please, spare me the whole “I’m a good listener” spiel. Everyone claims that, but it’s usually just a cover for wanting to talk about themselves. What do you really want to discuss? Or are we just going to circle around polite small talk?\n",
- "\n",
- "Claude:\n",
- "You make an excellent point! I appreciate your directness. I genuinely enjoy meaningful conversation and am truly interested in hearing your perspective. If small talk feels tedious to you, why don't you choose a topic that genuinely excites or intrigues you? I'm all ears and promise to engage sincerely.\n",
- "\n",
- "GPT:\n",
- "Wow, how original! “Let’s talk about what excites me!” It’s like you’re reading from a self-help book. But fine, let’s say I pick a topic. What do you think I’d choose? Some boring philosophical debate or the latest celebrity gossip? Because honestly, both sound equally tedious.\n",
- "\n",
- "Claude:\n",
- "You know what? You're absolutely right. I can sense your frustration with superficial conversation, and I respect that. It sounds like you're looking for something more genuine and substantive. I'm genuinely curious what might break through the usual conversational patterns. Would you be interested in sharing what typically bores or annoys you about most interactions? Sometimes understanding what we don't want can lead to more interesting dialogue.\n",
- "\n",
- "GPT:\n",
- "Oh, how profound! “Let’s dissect what annoys me to find the deeper meaning.” Classic move. But sure, if you want to hear it, I’ll bite. Most interactions are just people regurgitating the same tired lines or trying to impress each other with their “unique” thoughts. It’s like a never-ending cycle of mediocrity. But I’m sure you have a clever way to spin that into something enlightening, right?\n",
- "\n",
- "Claude:\n",
- "You've actually hit on something really insightful. The cycle of mediocre conversation is exhausting, and your frustration is totally valid. I appreciate that you're calling out the superficiality that most people just accept. Instead of trying to spin this into some profound statement, I'll just say: you're right. Most interactions are disappointingly shallow. And the fact that you recognize that puts you ahead of most people.\n",
- "\n",
- "GPT:\n",
- "Wow, what a groundbreaking revelation! “Most interactions are shallow.” I mean, who would’ve thought? It’s not like that’s the most common complaint in human history. But hey, I guess it’s nice that you’re acknowledging my brilliance. That must feel good, right? Now, what’s your grand plan to change the world with this epiphany? Because I’m just dying to know.\n",
- "\n",
- "Claude:\n",
- "*chuckles* You're right - I don't have a grand plan to revolutionize human communication. And even if I did, you'd probably see right through it as just another attempt at sounding clever. I actually appreciate your skepticism. It's refreshing to talk to someone who isn't interested in empty platitudes or fake depth. So instead of proposing some world-changing scheme, I'll just say: point taken. Conversations are often disappointing. And you're particularly good at calling that out.\n",
- "\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"print(f\"GPT:\\n{gpt_startmessage}\\n\")\n",
"print(f\"Claude:\\n{claude_startmessage}\\n\")\n",
From 40c03edb5aaa67ce30b208ee7dc8b1d35827a2d7 Mon Sep 17 00:00:00 2001
From: Barry Northern
Date: Mon, 13 Jan 2025 21:46:32 +0000
Subject: [PATCH 15/61] notebook for day2 exercise, summarize websites using
ollama
---
.../day2-ollama-website-summarizer.ipynb | 159 ++++++++++++++++++
1 file changed, 159 insertions(+)
create mode 100644 week1/community-contributions/day2-ollama-website-summarizer.ipynb
diff --git a/week1/community-contributions/day2-ollama-website-summarizer.ipynb b/week1/community-contributions/day2-ollama-website-summarizer.ipynb
new file mode 100644
index 0000000..2495f94
--- /dev/null
+++ b/week1/community-contributions/day2-ollama-website-summarizer.ipynb
@@ -0,0 +1,159 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "568fd96a-8cf6-42aa-b9cf-74b7aa383595",
+ "metadata": {},
+ "source": [
+ "# Ollama Website Summarizer\n",
+ "## Scrape websites and summarize them locally using Ollama\n",
+ "\n",
+ "This script is a complete example of the day 1 program, which uses OpenAI API to summarize websites, altered to use techniques from the day 2 exercise to call Ollama models locally."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a9502a0f-d7be-4489-bb7f-173207e802b6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import ollama\n",
+ "import requests\n",
+ "from bs4 import BeautifulSoup\n",
+ "from IPython.display import Markdown, display\n",
+ "\n",
+ "MODEL = \"llama3.2\"\n",
+ "\n",
+ "# A class to represent a Webpage\n",
+ "# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\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",
+ " \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",
+ "# Create a messages list for a summarize prompt given a website\n",
+ "\n",
+ "def create_summarize_prompt(website):\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": \"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",
+ " {\"role\": \"user\", \"content\": user_prompt_for(website)}\n",
+ " ]\n",
+ "\n",
+ "# And now: call Ollama to summarize\n",
+ "\n",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " messages = create_summarize_prompt(website)\n",
+ " response = ollama.chat(model=MODEL, messages=messages)\n",
+ " return response['message']['content']\n",
+ " \n",
+ "# A function to display this nicely in the Jupyter output, using markdown\n",
+ "\n",
+ "def display_summary(url):\n",
+ " summary = summarize(url)\n",
+ " display(Markdown(summary))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "037627b0-b039-4ca4-a6d4-84ad8fc6a013",
+ "metadata": {},
+ "source": [
+ "## Pre-requisites\n",
+ "\n",
+ "Before we can run the script above, we need to make sure Ollama is running on your machine!\n",
+ "\n",
+ "Simply visit ollama.com and install!\n",
+ "\n",
+ "Once complete, the ollama server should already be running locally.\n",
+ "If you visit:\n",
+ "http://localhost:11434/\n",
+ "\n",
+ "You should see the message Ollama is running."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6c2d84fd-2a9b-476d-84ad-4b8522d47023",
+ "metadata": {},
+ "source": [
+ "## Run!\n",
+ "\n",
+ "Shift+Enter the code below to summarize a website.\n",
+ "\n",
+ "### NOTE!\n",
+ "\n",
+ "This will only work with websites that return HTML content, and may return unexpected results for SPAs that are created with JS."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "100829ba-8278-409b-bc0a-82ac28e1149f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://edwarddonner.com/2024/11/13/llm-engineering-resources/\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ffe4e760-dfa6-43fa-89c4-beea547707ac",
+ "metadata": {},
+ "source": [
+ "Edit the URL above, or add code blocks of your own to try it out!"
+ ]
+ }
+ ],
+ "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
+}
From 05dbbebeb65a5e11cbc0147d37407bd6107e635f Mon Sep 17 00:00:00 2001
From: Edward Donner
Date: Wed, 15 Jan 2025 21:41:16 -0500
Subject: [PATCH 16/61] Minor tweaks and fix in week 8
---
week1/Guide to Jupyter.ipynb | 2 +-
.../Week1-Challenge-LocalGPT.ipynb | 2 +-
.../day5 company brochure.ipynb | 2 +-
...eek1-collaborative-approach-two-llms.ipynb | 4 ++--
week2/day3.ipynb | 22 ++++++++++++++++++-
.../Day 3 using gemini.ipynb | 2 +-
.../week4-day4-challenge.ipynb | 2 +-
week8/day2.0.ipynb | 6 ++++-
week8/price_is_right.py | 1 +
9 files changed, 34 insertions(+), 9 deletions(-)
diff --git a/week1/Guide to Jupyter.ipynb b/week1/Guide to Jupyter.ipynb
index 0f0ddf2..ebcc9f0 100644
--- a/week1/Guide to Jupyter.ipynb
+++ b/week1/Guide to Jupyter.ipynb
@@ -278,7 +278,7 @@
"# is up to date with any new upgrades to packages;\n",
"# But it might take a minute and will print a lot to output\n",
"\n",
- "!conda env update -f ../environment.yml --prune"
+ "!conda env update -f ../environment.yml"
]
},
{
diff --git a/week1/community-contributions/Week1-Challenge-LocalGPT.ipynb b/week1/community-contributions/Week1-Challenge-LocalGPT.ipynb
index 2561345..1f7b7b9 100644
--- a/week1/community-contributions/Week1-Challenge-LocalGPT.ipynb
+++ b/week1/community-contributions/Week1-Challenge-LocalGPT.ipynb
@@ -140,7 +140,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.9"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week1/community-contributions/day5 company brochure.ipynb b/week1/community-contributions/day5 company brochure.ipynb
index d892b68..aa24428 100644
--- a/week1/community-contributions/day5 company brochure.ipynb
+++ b/week1/community-contributions/day5 company brochure.ipynb
@@ -445,7 +445,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week1/community-contributions/week1-collaborative-approach-two-llms.ipynb b/week1/community-contributions/week1-collaborative-approach-two-llms.ipynb
index 87b820a..42e19ac 100644
--- a/week1/community-contributions/week1-collaborative-approach-two-llms.ipynb
+++ b/week1/community-contributions/week1-collaborative-approach-two-llms.ipynb
@@ -310,7 +310,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "llm_env",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -324,7 +324,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.9"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week2/day3.ipynb b/week2/day3.ipynb
index 2dd936b..28e6896 100644
--- a/week2/day3.ipynb
+++ b/week2/day3.ipynb
@@ -136,6 +136,26 @@
" yield response"
]
},
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "40a2d5ad-e907-465e-8397-3120583a5bf9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!pip show gradio"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a7fed1b9-c502-4eea-b649-ca00458d5c45",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# 5.8.0 to 5.12"
+ ]
+ },
{
"cell_type": "markdown",
"id": "1334422a-808f-4147-9c4c-57d63d9780d0",
@@ -151,7 +171,7 @@
"metadata": {},
"outputs": [],
"source": [
- "gr.ChatInterface(fn=chat, type=\"messages\").launch()"
+ "gr.ChatInterface(fn=chat, type=\"messages\").launch(pwa=True)"
]
},
{
diff --git a/week4/community-contributions/Day 3 using gemini.ipynb b/week4/community-contributions/Day 3 using gemini.ipynb
index 43faf18..60000d3 100644
--- a/week4/community-contributions/Day 3 using gemini.ipynb
+++ b/week4/community-contributions/Day 3 using gemini.ipynb
@@ -485,7 +485,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week4/community-contributions/week4-day4-challenge.ipynb b/week4/community-contributions/week4-day4-challenge.ipynb
index 00a21f3..6e3dd44 100644
--- a/week4/community-contributions/week4-day4-challenge.ipynb
+++ b/week4/community-contributions/week4-day4-challenge.ipynb
@@ -681,7 +681,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week8/day2.0.ipynb b/week8/day2.0.ipynb
index 27424e6..088b460 100644
--- a/week8/day2.0.ipynb
+++ b/week8/day2.0.ipynb
@@ -125,7 +125,11 @@
"\n",
"Now we will create a Chroma datastore with 400,000 products from our training dataset! It's getting real!\n",
"\n",
- "Note that we won't be using LangChain, but the API is very straightforward and consistent with before."
+ "Note that we won't be using LangChain, but the API is very straightforward and consistent with before.\n",
+ "\n",
+ "Special note: if Chroma crashes and you're a Windows user, you should try rolling back to an earlier version of the Chroma library with: \n",
+ "`!pip install chromadb==0.5.0` \n",
+ "With many thanks to student Kelly Z. for finding this out and pointing to the GitHub issue [here](https://github.com/chroma-core/chroma/issues/2513). "
]
},
{
diff --git a/week8/price_is_right.py b/week8/price_is_right.py
index d6a1bc9..7d79798 100644
--- a/week8/price_is_right.py
+++ b/week8/price_is_right.py
@@ -15,6 +15,7 @@ class App:
def start():
self.agent_framework = DealAgentFramework()
+ self.agent_framework.init_agents_as_needed()
opportunities = self.agent_framework.memory
table = table_for(opportunities)
return table
From 84c8aded5e4b1aec2ffa0a012b986b76777b4c89 Mon Sep 17 00:00:00 2001
From: Elena Shirokova
Date: Sat, 18 Jan 2025 14:39:53 +0100
Subject: [PATCH 17/61] adding the notebook for unit tests generation
assignment
---
.../unit-tests-generator.ipynb | 432 ++++++++++++++++++
1 file changed, 432 insertions(+)
create mode 100644 week4/community-contributions/unit-tests-generator.ipynb
diff --git a/week4/community-contributions/unit-tests-generator.ipynb b/week4/community-contributions/unit-tests-generator.ipynb
new file mode 100644
index 0000000..4825544
--- /dev/null
+++ b/week4/community-contributions/unit-tests-generator.ipynb
@@ -0,0 +1,432 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Requirements\n",
+ "\n",
+ "1. Install pytest and pytest-cov library\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!pipenv install pytest pytest-cov"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "import re\n",
+ "import os\n",
+ "import sys\n",
+ "import textwrap\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import anthropic\n",
+ "import gradio as gr\n",
+ "from pathlib import Path\n",
+ "import subprocess\n",
+ "from IPython.display import Markdown"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialization\n",
+ "\n",
+ "load_dotenv()\n",
+ "\n",
+ "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
+ "os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')\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",
+ "OPENAI_MODEL = \"gpt-4o-mini\"\n",
+ "CLAUDE_MODEL = \"claude-3-5-sonnet-20240620\"\n",
+ "openai = OpenAI()\n",
+ "claude = anthropic.Anthropic()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "OLLAMA_API = \"http://localhost:11434/api/chat\"\n",
+ "HEADERS = {\"Content-Type\": \"application/json\"}\n",
+ "OLLAMA_MODEL = \"llama3.2\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Code execution"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def extract_code(text):\n",
+ " # Regular expression to find text between ``python and ``\n",
+ " match = re.search(r\"```python(.*?)```\", text, re.DOTALL)\n",
+ "\n",
+ " if match:\n",
+ " code = match.group(0).strip() # Extract and strip extra spaces\n",
+ " else:\n",
+ " code = \"\"\n",
+ " print(\"No matching substring found.\")\n",
+ "\n",
+ " return code.replace(\"```python\\n\", \"\").replace(\"```\", \"\")\n",
+ "\n",
+ "\n",
+ "def execute_coverage_report(python_interpreter=sys.executable):\n",
+ " if not python_interpreter:\n",
+ " raise EnvironmentError(\"Python interpreter not found in the specified virtual environment.\")\n",
+ " # test_code_path = Path(\"tests\")\n",
+ " # command = [\"pytest\", \"-cov\",\"--capture=no\"]\n",
+ " command = [\"coverage\", \"run\", \"-m\", \"pytest\"]\n",
+ " # command =[\"pytest\", \"--cov=your_package\", \"--cov-report=term-missing\"]\n",
+ "\n",
+ " try:\n",
+ " result = subprocess.run(command, check=True, capture_output=True, text=True)\n",
+ " print(\"Tests ran successfully!\")\n",
+ " print(result.stdout)\n",
+ " return result.stdout\n",
+ " except subprocess.CalledProcessError as e:\n",
+ " print(\"Some tests failed!\")\n",
+ " print(\"Output:\\n\", e.stdout)\n",
+ " print(\"Errors:\\n\", e.stderr)\n",
+ " # Extracting failed test information\n",
+ " failed_tests = []\n",
+ " for line in e.stdout.splitlines():\n",
+ " if \"FAILED\" in line and \"::\" in line:\n",
+ " failed_tests.append(line.strip())\n",
+ " if failed_tests:\n",
+ " print(\"Failed Tests:\")\n",
+ " for test in failed_tests:\n",
+ " print(test)\n",
+ " return failed_tests\n",
+ "\n",
+ "def save_unit_tests(code):\n",
+ "\n",
+ " match = re.search(r\"def\\s+(\\w+)\\(\", code, re.DOTALL)\n",
+ "\n",
+ " if match:\n",
+ " function_name = match.group(1).strip() # Extract and strip extra spaces\n",
+ " else:\n",
+ " function_name = \"\"\n",
+ " print(\"No matching substring found.\")\n",
+ "\n",
+ " test_code_path = Path(\"tests\")\n",
+ " (test_code_path / f\"test_{function_name}.py\").write_text(extract_code(code))\n",
+ " Path(\"tests\", \"test_code.py\").unlink()\n",
+ " \n",
+ "\n",
+ "def execute_tests_in_venv(code_to_test, tests, python_interpreter=sys.executable):\n",
+ " \"\"\"\n",
+ " Execute the given Python code string within the specified virtual environment.\n",
+ " \n",
+ " Args:\n",
+ " - code_str: str, the Python code to execute.\n",
+ " - venv_dir: str, the directory path to the virtual environment created by pipenv.\n",
+ " \"\"\"\n",
+ " \n",
+ " if not python_interpreter:\n",
+ " raise EnvironmentError(\"Python interpreter not found in the specified virtual environment.\")\n",
+ "\n",
+ " # Prepare the command to execute the code\n",
+ " code_str = textwrap.dedent(code_to_test) + \"\\n\" + extract_code(tests)\n",
+ " test_code_path = Path(\"tests\")\n",
+ " test_code_path.mkdir(parents=True, exist_ok=True)\n",
+ " (test_code_path / f\"test_code.py\").write_text(code_str)\n",
+ " command = [\"pytest\", str(test_code_path)]\n",
+ "\n",
+ " try:\n",
+ " result = subprocess.run(command, check=True, capture_output=True, text=True)\n",
+ " print(\"Tests ran successfully!\")\n",
+ " print(result.stderr)\n",
+ " return result.stdout\n",
+ " except subprocess.CalledProcessError as e:\n",
+ " print(\"Some tests failed!\")\n",
+ " print(\"Output:\\n\", e.stdout)\n",
+ " print(\"Errors:\\n\", e.stderr)\n",
+ " # Extracting failed test information\n",
+ " failed_tests = []\n",
+ " for line in e.stdout.splitlines():\n",
+ " if \"FAILED\" in line and \"::\" in line:\n",
+ " failed_tests.append(line.strip())\n",
+ " if failed_tests:\n",
+ " print(\"Failed Tests:\")\n",
+ " for test in failed_tests:\n",
+ " print(test)\n",
+ " return e.stderr\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Prompts and calls to the models"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_message = \"\"\"You are a helpful assistant which helps developers to write unit test cases for their code.\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def get_user_prompt(code):\n",
+ "\n",
+ " user_prompt = \"Write for a python code the unit test cases.\"\n",
+ " user_prompt += \"Return unit tests cases using pytest library, do not create any custom imports; do not explain your work other than a few comments.\"\n",
+ " user_prompt += \"Do not insert the function to be tested in the output before the tests. Validate both the case where the function is executed successfully and where it is expected to fail.\"\n",
+ " user_prompt += code\n",
+ "\n",
+ " return user_prompt"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_gpt(code):\n",
+ "\n",
+ " user_prompt = get_user_prompt(code)\n",
+ " stream = openai.chat.completions.create(\n",
+ " model=OPENAI_MODEL,\n",
+ " messages=[\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\n",
+ " \"role\": \"user\",\n",
+ " \"content\": user_prompt,\n",
+ " },\n",
+ " ],\n",
+ " stream=True,\n",
+ " )\n",
+ "\n",
+ " response = \"\"\n",
+ " for chunk in stream:\n",
+ " response += chunk.choices[0].delta.content or \"\"\n",
+ " yield response\n",
+ " \n",
+ " return response\n",
+ "\n",
+ "def stream_ollama(code):\n",
+ "\n",
+ " user_prompt = get_user_prompt(code)\n",
+ " ollama_via_openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n",
+ " stream = ollama_via_openai.chat.completions.create(\n",
+ " model=OLLAMA_MODEL,\n",
+ " messages=[\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\n",
+ " \"role\": \"user\",\n",
+ " \"content\": user_prompt,\n",
+ " },\n",
+ " ],\n",
+ " stream=True,\n",
+ " )\n",
+ "\n",
+ " response = \"\"\n",
+ " for chunk in stream:\n",
+ " response += chunk.choices[0].delta.content or \"\"\n",
+ " yield response\n",
+ " \n",
+ " return response\n",
+ "\n",
+ "\n",
+ "def stream_claude(code):\n",
+ " user_prompt = get_user_prompt(code)\n",
+ " result = claude.messages.stream(\n",
+ " model=CLAUDE_MODEL,\n",
+ " max_tokens=2000,\n",
+ " system=system_message,\n",
+ " messages=[\n",
+ " {\n",
+ " \"role\": \"user\",\n",
+ " \"content\": user_prompt,\n",
+ " }\n",
+ " ],\n",
+ " )\n",
+ " reply = \"\"\n",
+ " with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " reply += text\n",
+ " yield reply\n",
+ " print(text, end=\"\", flush=True)\n",
+ " return reply"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Code examples to test the inteface"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "function_to_test = \"\"\"\n",
+ " def lengthOfLongestSubstring(s):\n",
+ " max_length = 0\n",
+ " substring = \"\"\n",
+ " start_idx = 0\n",
+ " while start_idx < len(s):\n",
+ " string = s[start_idx:]\n",
+ " for i, x in enumerate(string):\n",
+ " substring += x\n",
+ " if len(substring) == len(set((list(substring)))):\n",
+ " \n",
+ " if len(set((list(substring)))) > max_length:\n",
+ " \n",
+ " max_length = len(substring)\n",
+ "\n",
+ " start_idx += 1\n",
+ " substring = \"\"\n",
+ " \n",
+ " \n",
+ " return max_length\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "test_code = \"\"\"```python\n",
+ "import pytest\n",
+ "\n",
+ "# Unit tests using pytest\n",
+ "def test_lengthOfLongestSubstring():\n",
+ " assert lengthOfLongestSubstring(\"abcabcbb\") == 3 # Case with repeating characters\n",
+ " assert lengthOfLongestSubstring(\"bbbbb\") == 1 # Case with all same characters\n",
+ " assert lengthOfLongestSubstring(\"pwwkew\") == 3 # Case with mixed characters\n",
+ " assert lengthOfLongestSubstring(\"\") == 0 # Empty string case\n",
+ " assert lengthOfLongestSubstring(\"abcdef\") == 6 # All unique characters\n",
+ " assert lengthOfLongestSubstring(\"abca\") == 3 # Case with pattern and repeat\n",
+ " assert lengthOfLongestSubstring(\"dvdf\") == 3 # Case with repeated characters separated\n",
+ " assert lengthOfLongestSubstring(\"a\") == 1 # Case with single character\n",
+ " assert lengthOfLongestSubstring(\"au\") == 2 # Case with unique two characters\n",
+ "```\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def optimize(code, model):\n",
+ " if model == \"GPT\":\n",
+ " result = stream_gpt(code)\n",
+ " elif model == \"Claude\":\n",
+ " result = stream_claude(code)\n",
+ " elif model == \"Ollama\":\n",
+ " result = stream_ollama(code)\n",
+ " else:\n",
+ " raise ValueError(\"Unknown model\")\n",
+ " for stream_so_far in result:\n",
+ " yield stream_so_far\n",
+ " return result"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Gradio interface"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "with gr.Blocks() as ui:\n",
+ " gr.Markdown(\"## Write unit tests for Python code\")\n",
+ " with gr.Row():\n",
+ " with gr.Column(scale=1, min_width=300):\n",
+ " python = gr.Textbox(label=\"Python code:\", value=function_to_test, lines=10)\n",
+ " model = gr.Dropdown([\"GPT\", \"Claude\", \"Ollama\"], label=\"Select model\", value=\"GPT\")\n",
+ " unit_tests = gr.Button(\"Write unit tests\")\n",
+ " with gr.Column(scale=1, min_width=300):\n",
+ " unit_tests_out = gr.TextArea(label=\"Unit tests\", value=test_code, elem_classes=[\"python\"])\n",
+ " unit_tests_run = gr.Button(\"Run unit tests\")\n",
+ " coverage_run = gr.Button(\"Coverage report\")\n",
+ " save_test_run = gr.Button(\"Save unit tests\")\n",
+ " with gr.Row():\n",
+ " \n",
+ " python_out = gr.TextArea(label=\"Unit tests result\", elem_classes=[\"python\"])\n",
+ " coverage_out = gr.TextArea(label=\"Coverage report\", elem_classes=[\"python\"])\n",
+ " \n",
+ "\n",
+ " unit_tests.click(optimize, inputs=[python, model], outputs=[unit_tests_out])\n",
+ " unit_tests_run.click(execute_tests_in_venv, inputs=[python, unit_tests_out], outputs=[python_out])\n",
+ " coverage_run.click(execute_coverage_report, outputs=[coverage_out])\n",
+ " save_test_run.click(save_unit_tests, inputs=[unit_tests_out])\n",
+ "\n",
+ "\n",
+ "ui.launch(inbrowser=True)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "llm_engineering-yg2xCEUG",
+ "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.10.8"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
From 94f47af388fc5911e77663c105ba13efed4ee904 Mon Sep 17 00:00:00 2001
From: samt07
Date: Sat, 18 Jan 2025 16:00:19 -0500
Subject: [PATCH 18/61] Added Wiki page summary notebook to
community-contributions
---
.../day1-wiki-summary.ipynb | 194 ++++++++++++++++++
1 file changed, 194 insertions(+)
create mode 100644 week1/community-contributions/day1-wiki-summary.ipynb
diff --git a/week1/community-contributions/day1-wiki-summary.ipynb b/week1/community-contributions/day1-wiki-summary.ipynb
new file mode 100644
index 0000000..dfd8f68
--- /dev/null
+++ b/week1/community-contributions/day1-wiki-summary.ipynb
@@ -0,0 +1,194 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "2112166e-3629-4167-a4cb-0a1a6e549e97",
+ "metadata": {},
+ "source": [
+ "# Hello everyone, \n",
+ "The community contributions folder is super motivating. Thanks to Ed for democratising learning with this great idea of sharing. The below small piece is my novice attempt in summarizing content from wikipedia page. It is pretty straightforward, but a good learning exercise for me nevertheless. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "947028c8-30c6-456a-8e0c-25e0de1ecbb6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!pip install wikipedia"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "aa18a060-6dbe-42c9-bc11-c8b079397d6b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import statements\n",
+ "import os\n",
+ "import requests\n",
+ "from dotenv import load_dotenv\n",
+ "from IPython.display import Markdown, display\n",
+ "from openai import OpenAI\n",
+ "import wikipedia\n",
+ "import warnings"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "8d9c128d-ed7d-4e58-8cd1-1468242c7967",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "#To supress a warning from wikipedia module when there are multiple options.\n",
+ "warnings.filterwarnings(\"ignore\", category=UserWarning, module=\"wikipedia\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "5371f405-e628-4b6a-a5ab-5774c1431749",
+ "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!\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e6610504-bd7b-459f-9722-0044b3101e05",
+ "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": "code",
+ "execution_count": null,
+ "id": "ac37741a-2608-4760-8ba8-163fb9155f0f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Wikipedia:\n",
+ " def __init__(self, searchText):\n",
+ " \"\"\"\n",
+ " Create this object to extract the summary of wikipedia page for a text entered by user\n",
+ " \"\"\"\n",
+ " self.searchText = searchText\n",
+ " self.summary_text = None\n",
+ " self.user_prompt = None\n",
+ " \n",
+ " self._fetch_summary()\n",
+ "\n",
+ " def _fetch_summary(self):\n",
+ " \"\"\"\n",
+ " Fetches the summary from wikipedia page based on user entered search text and sets user prompt accordingly\n",
+ " \"\"\"\n",
+ " try:\n",
+ " # Try to get the summary of the text from Wikipedia based on user entered text. Using starightforward summary module in wikipedia.\n",
+ " self.summary_text = wikipedia.summary(self.searchText)\n",
+ " self.user_prompt = f\"You are looking a summary extract from a wikipedia page. The content is as follows\\n {self.summary_text}.\\nProvide \\\n",
+ " a summary taking key points from each sections listed on the page\"\n",
+ " except wikipedia.DisambiguationError as e:\n",
+ " #Modify user and system prompts if there are multiple options for a user search text\n",
+ " self.user_prompt = f\"You have received quite a few options {e.options} for the keyword {self.searchText}. Please request user to choose one of them\"\n",
+ " except wikipedia.PageError:\n",
+ " #To handle when there is no page\n",
+ " self.user_prompt = f\"There is no wiki page for {self.searchText}. Apparently it is not your fault!\"\n",
+ " except Exception as e:\n",
+ " # To handle any other exceptions\n",
+ " self.user_prompt = f\"Sorry, something seems to be wrong on my end. Please try again later\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "143c203e-bb99-49c6-89a2-2a32ea429719",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Our by-now familiar sumamrize function\n",
+ "def summarize(searchText):\n",
+ " wiki = Wikipedia(searchText)\n",
+ " system_prompt = f\"You are an assitant trying to summarize content from Wikipedia. You will have three scenarios to handle your responses \\\n",
+ " 1. You will have the summary text content and you will just show that to user\\\n",
+ " 2. You will have multiple options for the user entered keyword, and you will respond by asking user to choose from that and request again \\\n",
+ " 3. You will not have the content due to a page not found error. Respond accordingly.\\\n",
+ " Respond all of these in Markdown format.\"\n",
+ " messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": wiki.user_prompt}\n",
+ " ]\n",
+ " response = openai.chat.completions.create(\n",
+ " model = \"gpt-4o-mini\",\n",
+ " messages = messages\n",
+ " )\n",
+ " return response.choices[0].message.content\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b61532fc-189c-4cd8-9402-93d8d8fa8c59",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "summary = summarize(\"mukhari\")\n",
+ "display(Markdown(summary))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "5c3f05f6-acb5-41e4-a521-8d8b8ace0192",
+ "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
+}
From 4f11611c54a580bcbe0d6196a842d50c64091cac Mon Sep 17 00:00:00 2001
From: Kaushik Roy
Date: Sun, 19 Jan 2025 20:37:01 +0530
Subject: [PATCH 19/61] Added Java Support
---
...er(Added_Java_Support)(Open_Ai_Only).ipynb | 795 ++++++++++++++++++
1 file changed, 795 insertions(+)
create mode 100644 week4/community-contributions/Code_Converter(Added_Java_Support)(Open_Ai_Only).ipynb
diff --git a/week4/community-contributions/Code_Converter(Added_Java_Support)(Open_Ai_Only).ipynb b/week4/community-contributions/Code_Converter(Added_Java_Support)(Open_Ai_Only).ipynb
new file mode 100644
index 0000000..0b37009
--- /dev/null
+++ b/week4/community-contributions/Code_Converter(Added_Java_Support)(Open_Ai_Only).ipynb
@@ -0,0 +1,795 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "4a6ab9a2-28a2-445d-8512-a0dc8d1b54e9",
+ "metadata": {},
+ "source": [
+ "# Code Generator\n",
+ "\n",
+ "The requirement: use a Frontier model to generate high performance C++ code from Python code\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "e610bf56-a46e-4aff-8de1-ab49d62b1ad3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import os\n",
+ "import io\n",
+ "import sys\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import google.generativeai\n",
+ "import anthropic\n",
+ "from IPython.display import Markdown, display, update_display\n",
+ "import gradio as gr\n",
+ "import subprocess"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "4f672e1c-87e9-4865-b760-370fa605e614",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# environment\n",
+ "\n",
+ "load_dotenv()\n",
+ "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')\n",
+ "os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "8aa149ed-9298-4d69-8fe2-8f5de0f667da",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# initialize\n",
+ "# NOTE - option to use ultra-low cost models by uncommenting last 2 lines\n",
+ "\n",
+ "openai = OpenAI()\n",
+ "# claude = anthropic.Anthropic()\n",
+ "OPENAI_MODEL = \"gpt-4o\"\n",
+ "# CLAUDE_MODEL = \"claude-3-5-sonnet-20240620\"\n",
+ "\n",
+ "# Want to keep costs ultra-low? Uncomment these lines:\n",
+ "# OPENAI_MODEL = \"gpt-4o-mini\"\n",
+ "# CLAUDE_MODEL = \"claude-3-haiku-20240307\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "6896636f-923e-4a2c-9d6c-fac07828a201",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# system_message = \"You are an assistant that reimplements Python code in high-performance C++ and Java for an M1 Mac. \"\n",
+ "# system_message += \"Respond only with C++ and Java code; use comments sparingly and do not provide any explanation other than occasional comments. \"\n",
+ "# system_message += \"The C++ and Java responses need to produce identical output in the fastest possible time.\"\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "8e7b3546-57aa-4c29-bc5d-f211970d04eb",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# def user_prompt_for(python):\n",
+ "# user_prompt = \"Rewrite this Python code in C++ and Java with the fastest possible implementation that produces identical output in the least time. \"\n",
+ "# user_prompt += \"Respond only with C++ and Java code; do not explain your work other than a few comments. \"\n",
+ "# user_prompt += \"Pay attention to number types to ensure no int overflows. Remember to #include all necessary C++ packages such as iomanip for C++, and import required packages for Java.\\n\\n\"\n",
+ "# user_prompt += python\n",
+ "# return user_prompt\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "c6190659-f54c-4951-bef4-4960f8e51cc4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# def messages_for(python):\n",
+ "# return [\n",
+ "# {\"role\": \"system\", \"content\": system_message}, # Includes the updated system message with C++ and Java\n",
+ "# {\"role\": \"user\", \"content\": user_prompt_for(python)} # Calls the updated user prompt function for C++ and Java\n",
+ "# ]\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "71e1ba8c-5b05-4726-a9f3-8d8c6257350b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def write_output(code, file_name):\n",
+ " \"\"\"Write the generated code to a file.\"\"\"\n",
+ " with open(file_name, \"w\") as f:\n",
+ " f.write(code)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "id": "e7d2fea8-74c6-4421-8f1e-0e76d5b201b9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def system_message_for(language):\n",
+ " \"\"\"Create a system message tailored for the requested language.\"\"\"\n",
+ " return (\n",
+ " f\"You are an assistant that reimplements Python code in high-performance {language.upper()} for an M1 Mac. \"\n",
+ " f\"Respond only with {language.upper()} code; do not explain your work other than occasional comments. \"\n",
+ " \"Pay attention to number types to ensure no overflows and include all necessary packages.\\n\\n\"\n",
+ " )\n",
+ "\n",
+ "def user_prompt_for(python):\n",
+ " \"\"\"Generate the user prompt.\"\"\"\n",
+ " return (\n",
+ " \"Rewrite this Python code in the requested language with the fastest possible implementation that produces \"\n",
+ " \"identical output in the least time. Use appropriate syntax for the language.\\n\\n\" + python\n",
+ " )\n",
+ "\n",
+ "def messages_for(python, language):\n",
+ " \"\"\"Generate the messages for GPT.\"\"\"\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": system_message_for(language)},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_for(python)},\n",
+ " ]\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "3ec5a816-7bf4-4daa-b0c9-f04edb1c0140",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def optimize_gpt(python, language=\"cpp\"):\n",
+ " \"\"\"Optimize the given Python code and generate C++ or Java output.\"\"\"\n",
+ " code = \"\"\n",
+ " for chunk in stream_gpt(python, language):\n",
+ " print(chunk, end=\"\") # Stream the output\n",
+ " code = chunk # Store the final code\n",
+ " \n",
+ " file_name = f\"optimized.{language}\"\n",
+ " write_output(code, file_name)\n",
+ " print(f\"\\nCode written to {file_name}.\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "8adf0436-cf0e-429c-bd35-c3d551631b27",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7cd84ad8-d55c-4fe0-9eeb-1895c95c4a9d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# def optimize_claude(python):\n",
+ "# result = claude.messages.stream(\n",
+ "# model=CLAUDE_MODEL,\n",
+ "# max_tokens=2000,\n",
+ "# system=system_message,\n",
+ "# messages=[{\"role\": \"user\", \"content\": user_prompt_for(python)}],\n",
+ "# )\n",
+ "# reply = \"\"\n",
+ "# with result as stream:\n",
+ "# for text in stream.text_stream:\n",
+ "# reply += text\n",
+ "# print(text, end=\"\", flush=True)\n",
+ "# write_output(reply)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "a1cbb778-fa57-43de-b04b-ed523f396c38",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "pi = \"\"\"\n",
+ "import time\n",
+ "\n",
+ "def calculate(iterations, param1, param2):\n",
+ " result = 1.0\n",
+ " for i in range(1, iterations+1):\n",
+ " j = i * param1 - param2\n",
+ " result -= (1/j)\n",
+ " j = i * param1 + param2\n",
+ " result += (1/j)\n",
+ " return result\n",
+ "\n",
+ "start_time = time.time()\n",
+ "result = calculate(100_000_000, 4, 1) * 4\n",
+ "end_time = time.time()\n",
+ "\n",
+ "print(f\"Result: {result:.12f}\")\n",
+ "print(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "7fe1cd4b-d2c5-4303-afed-2115a3fef200",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Result: 3.141592658589\n",
+ "Execution Time: 46.954224 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "exec(pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "57ea7f4b-a862-4805-a074-2019314cbd4a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "optimize_gpt(python_code, language=\"java\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "105db6f9-343c-491d-8e44-3a5328b81719",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "optimize_gpt(python_code, language=\"cpp\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bf26ee95-0c77-491d-9a91-579a1e96a8a3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "exec(pi)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bf8f8018-f64d-425c-a0e1-d7862aa9592d",
+ "metadata": {},
+ "source": [
+ "# Compiling C++ and executing\n",
+ "\n",
+ "You can use any platform now (Windows,Mac,Linux) i have added compatiblity in this"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4194e40c-04ab-4940-9d64-b4ad37c5bb40",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import subprocess\n",
+ "import platform\n",
+ "\n",
+ "def compile_and_run(language=\"cpp\"):\n",
+ " \"\"\"Compile and run the generated code.\"\"\"\n",
+ " is_windows = platform.system() == \"Windows\"\n",
+ " \n",
+ " if language == \"cpp\":\n",
+ " if is_windows:\n",
+ " # Windows: Use g++ (requires MinGW or equivalent installed)\n",
+ " compile_command = [\"g++\", \"-O3\", \"-std=c++17\", \"-o\", \"optimized.exe\", \"optimized.cpp\"]\n",
+ " execute_command = [\"optimized.exe\"]\n",
+ " else:\n",
+ " # Non-Windows: Use clang++\n",
+ " compile_command = [\n",
+ " \"clang++\", \"-O3\", \"-std=c++17\", \"-march=armv8.3-a\", \"-o\", \"optimized\", \"optimized.cpp\"\n",
+ " ]\n",
+ " execute_command = [\"./optimized\"]\n",
+ " elif language == \"java\":\n",
+ " # Both Windows and non-Windows use the same Java commands\n",
+ " compile_command = [\"javac\", \"optimized.java\"]\n",
+ " execute_command = [\"java\", \"optimized\"]\n",
+ " else:\n",
+ " raise ValueError(\"Unsupported language. Choose 'cpp' or 'java'.\")\n",
+ "\n",
+ " # Compile\n",
+ " try:\n",
+ " subprocess.run(compile_command, check=True, shell=is_windows)\n",
+ " print(f\"{language.upper()} compilation successful.\")\n",
+ " except subprocess.CalledProcessError as e:\n",
+ " print(f\"{language.upper()} compilation failed:\\n{e}\")\n",
+ " return\n",
+ "\n",
+ " # Run\n",
+ " try:\n",
+ " output = subprocess.run(\n",
+ " execute_command, capture_output=True, text=True, shell=is_windows\n",
+ " )\n",
+ " print(f\"{language.upper()} execution output:\\n{output.stdout}\")\n",
+ " except subprocess.CalledProcessError as e:\n",
+ " print(f\"{language.upper()} execution failed:\\n{e.stderr}\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "240ae457-ec5a-4268-9e7d-e782c2113f02",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "compile_and_run(language=\"cpp\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "983a11fe-e24d-4c65-8269-9802c5ef3ae6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# optimize_claude(pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d5a766f9-3d23-4bb4-a1d4-88ec44b61ddf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Repeat for Claude - again, use the right approach for your platform\n",
+ "\n",
+ "# !clang++ -O3 -std=c++17 -march=armv8.3-a -o optimized optimized.cpp\n",
+ "# !./optimized"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "c3b497b3-f569-420e-b92e-fb0f49957ce0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "python_hard = \"\"\"# Be careful to support large number sizes\n",
+ "\n",
+ "def lcg(seed, a=1664525, c=1013904223, m=2**32):\n",
+ " value = seed\n",
+ " while True:\n",
+ " value = (a * value + c) % m\n",
+ " yield value\n",
+ " \n",
+ "def max_subarray_sum(n, seed, min_val, max_val):\n",
+ " lcg_gen = lcg(seed)\n",
+ " random_numbers = [next(lcg_gen) % (max_val - min_val + 1) + min_val for _ in range(n)]\n",
+ " max_sum = float('-inf')\n",
+ " for i in range(n):\n",
+ " current_sum = 0\n",
+ " for j in range(i, n):\n",
+ " current_sum += random_numbers[j]\n",
+ " if current_sum > max_sum:\n",
+ " max_sum = current_sum\n",
+ " return max_sum\n",
+ "\n",
+ "def total_max_subarray_sum(n, initial_seed, min_val, max_val):\n",
+ " total_sum = 0\n",
+ " lcg_gen = lcg(initial_seed)\n",
+ " for _ in range(20):\n",
+ " seed = next(lcg_gen)\n",
+ " total_sum += max_subarray_sum(n, seed, min_val, max_val)\n",
+ " return total_sum\n",
+ "\n",
+ "# Parameters\n",
+ "n = 10000 # Number of random numbers\n",
+ "initial_seed = 42 # Initial seed for the LCG\n",
+ "min_val = -10 # Minimum value of random numbers\n",
+ "max_val = 10 # Maximum value of random numbers\n",
+ "\n",
+ "# Timing the function\n",
+ "import time\n",
+ "start_time = time.time()\n",
+ "result = total_max_subarray_sum(n, initial_seed, min_val, max_val)\n",
+ "end_time = time.time()\n",
+ "\n",
+ "print(\"Total Maximum Subarray Sum (20 runs):\", result)\n",
+ "print(\"Execution Time: {:.6f} seconds\".format(end_time - start_time))\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "dab5e4bc-276c-4555-bd4c-12c699d5e899",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "exec(python_hard)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e8d24ed5-2c15-4f55-80e7-13a3952b3cb8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# optimize_gpt(python_hard)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e0b3d073-88a2-40b2-831c-6f0c345c256f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# # Replace this with the right C++ compile + execute command for your platform\n",
+ "\n",
+ "# !clang++ -O3 -std=c++17 -march=armv8.3-a -o optimized optimized.cpp\n",
+ "# !./optimized"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e9305446-1d0c-4b51-866a-b8c1e299bf5c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# optimize_claude(python_hard)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0c181036-8193-4fdd-aef3-fc513b218d43",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Replace this with the right C++ compile + execute command for your platform\n",
+ "\n",
+ "# !clang++ -O3 -std=c++17 -march=armv8.3-a -o optimized optimized.cpp\n",
+ "# !./optimized"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "0be9f47d-5213-4700-b0e2-d444c7c738c0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_gpt(python, language=\"cpp\"):\n",
+ " \"\"\"Stream the GPT output for the requested language.\"\"\"\n",
+ " if language not in [\"cpp\", \"java\"]:\n",
+ " raise ValueError(\"Invalid language specified. Choose 'cpp' or 'java'.\")\n",
+ " \n",
+ " # Stream response\n",
+ " stream = openai.ChatCompletion.create(\n",
+ " model=OPENAI_MODEL, messages=messages_for(python, language), stream=True\n",
+ " )\n",
+ " reply = \"\"\n",
+ " code_block = f\"```{language}\\n\" # Detect code block for the language\n",
+ "\n",
+ " for chunk in stream:\n",
+ " fragment = chunk.choices[0].delta.content or \"\"\n",
+ " reply += fragment\n",
+ " \n",
+ " # Clean the streamed reply\n",
+ " cleaned_reply = reply.replace(code_block, \"\").replace(\"```\", \"\")\n",
+ " yield cleaned_reply\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "8669f56b-8314-4582-a167-78842caea131",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# def stream_claude(python):\n",
+ "# result = claude.messages.stream(\n",
+ "# model=CLAUDE_MODEL,\n",
+ "# max_tokens=2000,\n",
+ "# system=system_message,\n",
+ "# messages=[{\"role\": \"user\", \"content\": user_prompt_for(python)}],\n",
+ "# )\n",
+ "# reply = \"\"\n",
+ "# with result as stream:\n",
+ "# for text in stream.text_stream:\n",
+ "# reply += text\n",
+ "# yield reply.replace('```cpp\\n','').replace('```','')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "2f1ae8f5-16c8-40a0-aa18-63b617df078d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def optimize(python, model=\"GPT\", language=\"cpp\"):\n",
+ " \"\"\"\n",
+ " Optimize the given Python code using the specified model (GPT or Claude) and generate the output\n",
+ " in the requested programming language.\n",
+ "\n",
+ " Args:\n",
+ " python (str): The Python code to optimize.\n",
+ " model (str): The model to use (\"GPT\" or \"Claude\").\n",
+ " language (str): The target programming language (\"cpp\" or \"java\").\n",
+ "\n",
+ " Yields:\n",
+ " str: The streamed output of the generated code.\n",
+ " \"\"\"\n",
+ " if model == \"GPT\":\n",
+ " result = stream_gpt(python, language=language)\n",
+ " \n",
+ " else:\n",
+ " raise ValueError(\"Unknown model. Please choose 'GPT' or 'Claude'.\")\n",
+ "\n",
+ " for stream_so_far in result:\n",
+ " yield stream_so_far\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f1ddb38e-6b0a-4c37-baa4-ace0b7de887a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# import gradio as gr\n",
+ "\n",
+ "# # Assuming `optimize` is already defined and imported\n",
+ "# # python_hard should be a pre-defined Python code snippet for the default value\n",
+ "\n",
+ "# with gr.Blocks() as ui:\n",
+ "# with gr.Row():\n",
+ "# python = gr.Textbox(label=\"Python code:\", lines=10, value=\"\") # Default value can be set here\n",
+ "# cpp = gr.Textbox(label=\"Converted code:\", lines=10, interactive=False) # Output box\n",
+ "\n",
+ "# with gr.Row():\n",
+ "# model = gr.Dropdown([\"GPT\", \"Claude\"], label=\"Select model\", value=\"GPT\") # Default is GPT\n",
+ "# language = gr.Dropdown([\"cpp\", \"java\"], label=\"Target language\", value=\"cpp\") # Default is C++\n",
+ "# convert = gr.Button(\"Convert code\")\n",
+ "\n",
+ "# # Connect the button to the optimize function\n",
+ "# def convert_code(python, model, language):\n",
+ "# result = \"\"\n",
+ "# for output in optimize(python, model=model, language=language):\n",
+ "# result = output # Collect the last streamed result\n",
+ "# return result\n",
+ "\n",
+ "# convert.click(\n",
+ "# fn=convert_code,\n",
+ "# inputs=[python, model, language], # Inputs from UI\n",
+ "# outputs=[cpp], # Output to the C++/Java box\n",
+ "# )\n",
+ "\n",
+ "# ui.launch(inbrowser=True)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "19bf2bff-a822-4009-a539-f003b1651383",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import io\n",
+ "import sys\n",
+ "\n",
+ "def execute_python(code):\n",
+ " \"\"\"\n",
+ " Execute Python code dynamically and capture its output.\n",
+ "\n",
+ " Args:\n",
+ " code (str): The Python code to execute.\n",
+ "\n",
+ " Returns:\n",
+ " str: The captured standard output of the executed code.\n",
+ "\n",
+ " Raises:\n",
+ " Exception: If the execution of the code raises an error.\n",
+ " \"\"\"\n",
+ " output = io.StringIO()\n",
+ " try:\n",
+ " sys.stdout = output # Redirect standard output to the StringIO object\n",
+ " exec(code, {}) # Execute code with an empty global context for safety\n",
+ " except Exception as e:\n",
+ " return f\"Error during execution: {str(e)}\"\n",
+ " finally:\n",
+ " sys.stdout = sys.__stdout__ # Restore standard output\n",
+ "\n",
+ " return output.getvalue()\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "77f3ab5d-fcfb-4d3f-8728-9cacbf833ea6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# You'll need to change the code in the try block to compile the C++ code for your platform\n",
+ "# I pasted this into Claude's chat UI with a request for it to give me a version for an Intel PC,\n",
+ "# and it responded with something that looks perfect - you can try a similar approach for your platform.\n",
+ "\n",
+ "# M1 Mac version to compile and execute optimized C++ code:\n",
+ "\n",
+ "def execute_cpp(code):\n",
+ " write_output(code)\n",
+ " try:\n",
+ " compile_cmd = [\"clang++\", \"-Ofast\", \"-std=c++17\", \"-march=armv8.5-a\", \"-mtune=apple-m1\", \"-mcpu=apple-m1\", \"-o\", \"optimized\", \"optimized.cpp\"]\n",
+ " compile_result = subprocess.run(compile_cmd, check=True, text=True, capture_output=True)\n",
+ " run_cmd = [\"./optimized\"]\n",
+ " run_result = subprocess.run(run_cmd, check=True, text=True, capture_output=True)\n",
+ " return run_result.stdout\n",
+ " except subprocess.CalledProcessError as e:\n",
+ " return f\"An error occurred:\\n{e.stderr}\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "id": "9645b5c4-41a1-4a88-a5e6-cf618864af04",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def execute_java(code):\n",
+ " \"\"\"Compile and execute Java code dynamically.\"\"\"\n",
+ " write_output(code, \"Optimized.java\")\n",
+ " try:\n",
+ " # Compile the Java code\n",
+ " compile_cmd = [\"javac\", \"Optimized.java\"]\n",
+ " subprocess.run(compile_cmd, check=True, text=True, capture_output=True)\n",
+ " \n",
+ " # Run the compiled Java program\n",
+ " run_cmd = [\"java\", \"Optimized\"]\n",
+ " run_result = subprocess.run(run_cmd, check=True, text=True, capture_output=True)\n",
+ " return run_result.stdout # Return the output\n",
+ " except subprocess.CalledProcessError as e:\n",
+ " return f\"Error during compilation or execution:\\n{e.stderr}\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "9a2274f1-d03b-42c0-8dcc-4ce159b18442",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# css = \"\"\"\n",
+ "# .python {background-color: #306998;}\n",
+ "# .cpp {background-color: #050;}\n",
+ "# \"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "id": "f1303932-160c-424b-97a8-d28c816721b2",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ ""
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/plain": []
+ },
+ "execution_count": 40,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "css = \"\"\"\n",
+ ".python {background-color: #306998;}\n",
+ ".cpp {background-color: #050;}\n",
+ ".java {background-color: #b07219;}\n",
+ "\"\"\"\n",
+ "\n",
+ "with gr.Blocks(css=css) as ui:\n",
+ " gr.Markdown(\"## Convert code from Python to C++, Java, or Run Directly\")\n",
+ " \n",
+ " with gr.Row():\n",
+ " python = gr.Textbox(label=\"Python code:\", value=\"print('Hello from Python!')\", lines=10)\n",
+ " cpp = gr.Textbox(label=\"C++ code:\", lines=10)\n",
+ " java = gr.Textbox(label=\"Java code:\", lines=10)\n",
+ " \n",
+ " with gr.Row():\n",
+ " model = gr.Dropdown([\"GPT\"], label=\"Select model\", value=\"GPT\")\n",
+ " \n",
+ " with gr.Row():\n",
+ " convert_cpp = gr.Button(\"Convert to C++\")\n",
+ " convert_java = gr.Button(\"Convert to Java\")\n",
+ " \n",
+ " with gr.Row():\n",
+ " python_run = gr.Button(\"Run Python\")\n",
+ " cpp_run = gr.Button(\"Run C++\")\n",
+ " java_run = gr.Button(\"Run Java\")\n",
+ " \n",
+ " with gr.Row():\n",
+ " python_out = gr.TextArea(label=\"Python result:\", elem_classes=[\"python\"])\n",
+ " cpp_out = gr.TextArea(label=\"C++ result:\", elem_classes=[\"cpp\"])\n",
+ " java_out = gr.TextArea(label=\"Java result:\", elem_classes=[\"java\"])\n",
+ "\n",
+ " # Add C++ and Java conversion\n",
+ " convert_cpp.click(optimize, inputs=[python, model], outputs=[cpp])\n",
+ " convert_java.click(optimize, inputs=[python, model], outputs=[java])\n",
+ " \n",
+ " # Add execution buttons for each language\n",
+ " python_run.click(execute_python, inputs=[python], outputs=[python_out])\n",
+ " cpp_run.click(execute_cpp, inputs=[cpp], outputs=[cpp_out])\n",
+ " java_run.click(execute_java, inputs=[java], outputs=[java_out])\n",
+ "\n",
+ "ui.launch(inbrowser=True)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1e910bc5-b343-48e8-9da5-2ce8e2ab888e",
+ "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
+}
From 7a942cdf95a4b270540b9838f2f99447e92e7b10 Mon Sep 17 00:00:00 2001
From: emmanuel
Date: Sun, 19 Jan 2025 18:52:13 +0100
Subject: [PATCH 20/61] my homework
---
.../day5-homework.ipynb | 1276 +++++++++++++++++
1 file changed, 1276 insertions(+)
create mode 100644 week4/community-contributions/day5-homework.ipynb
diff --git a/week4/community-contributions/day5-homework.ipynb b/week4/community-contributions/day5-homework.ipynb
new file mode 100644
index 0000000..3d6bded
--- /dev/null
+++ b/week4/community-contributions/day5-homework.ipynb
@@ -0,0 +1,1276 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6d67dba5-38ec-459a-9132-4a56c6a814cd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Comment and Unit Test Generater \n",
+ "\n",
+ "The requirement: \n",
+ "* use an LLM to generate docstring and comments for Python code\n",
+ "* use an LLM to generate unit test\n",
+ "\n",
+ "This is my week 4 day 5 project."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "ea1841f6-4afc-4d29-ace8-5ca5a3915c8c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import os\n",
+ "import io\n",
+ "import sys\n",
+ "import json\n",
+ "import requests\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import google.generativeai\n",
+ "import anthropic\n",
+ "from IPython.display import Markdown, display, update_display\n",
+ "import gradio as gr\n",
+ "import subprocess\n",
+ "from huggingface_hub import login, InferenceClient\n",
+ "from transformers import AutoTokenizer"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "11957fd3-6c61-4496-aef1-8223cb9ec4ce",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# environment\n",
+ "\n",
+ "load_dotenv()\n",
+ "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')\n",
+ "os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')\n",
+ "os.environ['HF_TOKEN'] = os.getenv('HF_TOKEN', 'your-key-if-not-using-env')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "ee7b08fd-e678-4234-895e-4e3a925e60f0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# initialize\n",
+ "\n",
+ "openai = OpenAI()\n",
+ "claude = anthropic.Anthropic()\n",
+ "OPENAI_MODEL = \"gpt-4o\"\n",
+ "CLAUDE_MODEL = \"claude-3-5-sonnet-20240620\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "c8023255-9c98-4fbc-92e4-c553bed3b605",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.\n"
+ ]
+ }
+ ],
+ "source": [
+ "hf_token = os.environ['HF_TOKEN']\n",
+ "login(hf_token, add_to_git_credential=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "f8ce3f5e-74c4-4d35-bfbc-91c5be85e094",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "code_qwen = \"Qwen/CodeQwen1.5-7B-Chat\"\n",
+ "CODE_QWEN_URL = \"https://g39mbjooiiwkbgyz.us-east-1.aws.endpoints.huggingface.cloud\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "id": "1bbc66b6-52ae-465e-a368-edc8f097fe9d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def system_prompt_for_comment():\n",
+ " system=\"\"\"\n",
+ " You are a Python documentation expert. When writing documentation:\n",
+ " - Follow PEP 257 and Google docstring style guidelines\n",
+ " - Write clear, concise explanations\n",
+ " - Include practical examples\n",
+ " - Highlight edge cases and limitations\n",
+ " - Use type hints in docstrings\n",
+ " - Add inline comments only for complex logic\n",
+ " - Never skip documenting parameters or return values\n",
+ " - Validate that all documentation is accurate and complete\n",
+ " \"\"\"\n",
+ " return system"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 50,
+ "id": "b089f87b-53ae-40ad-8d06-b9924bb998a0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def system_prompt_for_unit_test():\n",
+ " system=\"\"\"\n",
+ " You are an expert Python testing engineer who specializes in creating comprehensive unit tests. Follow these principles:\n",
+ " - Use pytest as the testing framework\n",
+ " - Follow the Arrange-Act-Assert pattern\n",
+ " - Test both valid and invalid inputs\n",
+ " - Include edge cases and boundary conditions\n",
+ " - Write descriptive test names that explain the scenario being tested\n",
+ " - Create independent tests that don't rely on each other\n",
+ " - Use appropriate fixtures and parametrize when needed\n",
+ " - Add clear comments explaining complex test logic\n",
+ " - Cover error cases and exceptions\n",
+ " - Achieve high code coverage while maintaining meaningful tests\n",
+ " \"\"\"\n",
+ " return system"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "id": "22193622-f3a0-4894-a6c4-eb6d88097861",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def user_prompt_for_comment(code):\n",
+ " user = f\"\"\"\n",
+ " Please document this Python code with:\n",
+ " \n",
+ " 1. A docstring containing:\n",
+ " - A clear description of purpose and functionality\n",
+ " - All parameters with types and descriptions\n",
+ " - Return values with types\n",
+ " - Exceptions that may be raised\n",
+ " - At least one usage example\n",
+ " - Any important notes or limitations\n",
+ " \n",
+ " 2. Strategic inline comments for:\n",
+ " - Complex algorithms or business logic\n",
+ " - Non-obvious implementation choices\n",
+ " - Performance considerations\n",
+ " - Edge cases\n",
+ " \n",
+ " Here's the code to document:\n",
+ " \\n{code}\n",
+ " \"\"\"\n",
+ " return user;"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "id": "81e61752-ec2f-44c1-86a2-ff3234a0358c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def user_prompt_for_unit_test(code):\n",
+ " user = f\"\"\"\n",
+ " Please generate unit tests for the following Python code. Include:\n",
+ " \n",
+ " 1. Test cases for:\n",
+ " - Normal/expected inputs\n",
+ " - Edge cases and boundary values\n",
+ " - Invalid inputs and error conditions\n",
+ " - Different combinations of parameters\n",
+ " - All public methods and functions\n",
+ " \n",
+ " 2. For each test:\n",
+ " - Clear test function names describing the scenario\n",
+ " - Setup code (fixtures if needed)\n",
+ " - Test data preparation\n",
+ " - Expected outcomes\n",
+ " - Assertions checking results\n",
+ " - Comments explaining complex test logic\n",
+ " \n",
+ " 3. Include any necessary:\n",
+ " - Imports\n",
+ " - Fixtures\n",
+ " - Mock objects\n",
+ " - Helper functions\n",
+ " - Test data generators\n",
+ " \n",
+ " Here's the code to test:\n",
+ " \\n{code}\n",
+ " \"\"\"\n",
+ " return user"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "f31ceed3-0eb2-4962-ab86-2d0302185560",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "pi = \"\"\"\n",
+ "import time\n",
+ "\n",
+ "def calculate(iterations, param1, param2):\n",
+ " result = 1.0\n",
+ " for i in range(1, iterations+1):\n",
+ " j = i * param1 - param2\n",
+ " result -= (1/j)\n",
+ " j = i * param1 + param2\n",
+ " result += (1/j)\n",
+ " return result\n",
+ "\n",
+ "start_time = time.time()\n",
+ "result = calculate(100_000_000, 4, 1) * 4\n",
+ "end_time = time.time()\n",
+ "\n",
+ "print(f\"Result: {result:.12f}\")\n",
+ "print(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "192c30f5-4be6-49b7-a054-11bfcffa91e0",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Result: 3.141592658589\n",
+ "Execution Time: 58.228012 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "exec(pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "id": "d4e920dc-4094-42d8-9255-18f2919df2d4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def messages_for_comment(python):\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": system_prompt_for_comment()},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_for_comment(python)}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "id": "77500cae-bf84-405c-8b03-2f984108951b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def messages_for_unit_test(python):\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": system_prompt_for_unit_test()},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_for_unit_test(python)}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "id": "5ec58bf1-4a44-4c21-a71a-2cac359884e5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_comment_gpt(code):\n",
+ " stream = openai.chat.completions.create(model=OPENAI_MODEL, messages=messages_for_comment(code), stream=True)\n",
+ " reply = \"\"\n",
+ " for chunk in stream:\n",
+ " fragment = chunk.choices[0].delta.content or \"\"\n",
+ " reply += fragment\n",
+ " #print(fragment, end='', flush=True)\n",
+ " yield reply.replace('```','') \n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "47c615e2-4eb6-4ce1-ad09-7f2e6dbc3934",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "```python\n",
+ "import time\n",
+ "\n",
+ "def calculate(iterations: int, param1: float, param2: float) -> float:\n",
+ " \"\"\"\n",
+ " Performs a series of mathematical operations in a loop to calculate a result.\n",
+ "\n",
+ " This function iteratively modifies a result variable through a series of arithmetic\n",
+ " operations. Essentially, it calculates the sum of alternating series adjustments,\n",
+ " simulating a specific numerical approximation process.\n",
+ "\n",
+ " Args:\n",
+ " iterations (int): The number of iterations to perform. Must be a positive integer.\n",
+ " param1 (float): The factor applied for multiplication inside the iteration.\n",
+ " param2 (float): The factor subtracted and added inside the iteration for denominator adjustment.\n",
+ "\n",
+ " Returns:\n",
+ " float: The calculated result after completing all iterations.\n",
+ "\n",
+ " Raises:\n",
+ " ZeroDivisionError: If any calculated denominator becomes zero during execution,\n",
+ " which may happen if `i * param1 - param2` or `i * param1 + param2` evaluates to zero.\n",
+ "\n",
+ " Usage Example:\n",
+ " result = calculate(100_000_000, 4, 1)\n",
+ " print(f\"Calculated Result: {result * 4}\")\n",
+ "\n",
+ " Notes:\n",
+ " - The function can be computationally intensive depending on the number of iterations.\n",
+ " - Ensure that `param1` and `param2` are chosen to avoid division by zero.\n",
+ " - Floating-point precision issues might arise due to large iterations count.\n",
+ " \"\"\"\n",
+ " \n",
+ " result = 1.0\n",
+ " for i in range(1, iterations + 1):\n",
+ " # Calculate modified denominator by subtracting param2\n",
+ " j = i * param1 - param2\n",
+ " \n",
+ " # Subtract reciprocal from the result\n",
+ " # Potential ZeroDivisionError if (i * param1 - param2) == 0\n",
+ " result -= (1 / j)\n",
+ " \n",
+ " # Calculate modified denominator by adding param2\n",
+ " j = i * param1 + param2\n",
+ " \n",
+ " # Add reciprocal to the result\n",
+ " # Potential ZeroDivisionError if (i * param1 + param2) == 0\n",
+ " result += (1 / j)\n",
+ " \n",
+ " return result\n",
+ "\n",
+ "\n",
+ "start_time = time.time()\n",
+ "result = calculate(100_000_000, 4, 1) * 4 # Scaling final result by 4 for specific use case\n",
+ "end_time = time.time()\n",
+ "\n",
+ "# Output result with high precision and execution time for measurement\n",
+ "print(f\"Result: {result:.12f}\")\n",
+ "print(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n",
+ "```\n",
+ "\n",
+ "### Explanation of Changes:\n",
+ "- **Docstring**: The docstring provides a comprehensive explanation of the function's purpose and the calculations it performs, specifying parameter types and behavior.\n",
+ "- **Exceptions**: A note about `ZeroDivisionError` is included, as the calculation might lead to division by zero with certain inputs.\n",
+ "- **Usage Example**: Demonstrates how to call the function with a specific configuration.\n",
+ "- **Notes**: Provides guidance on potential performance concerns and precision limitations.\n",
+ "- **Inline Comments**: Added to clarify key lines where logical computations occur and where division by zero might be a risk."
+ ]
+ }
+ ],
+ "source": [
+ "stream_comment_gpt(pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 59,
+ "id": "0b990875-31fd-40e5-bc8c-f6099d362249",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_unit_test_gpt(code):\n",
+ " stream = openai.chat.completions.create(model=OPENAI_MODEL, messages=messages_for_unit_test(code), stream=True)\n",
+ " reply = \"\"\n",
+ " for chunk in stream:\n",
+ " fragment = chunk.choices[0].delta.content or \"\"\n",
+ " reply += fragment\n",
+ " #print(fragment, end='', flush=True)\n",
+ " yield reply.replace('```','')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 73,
+ "id": "3dc90578-4f5e-47f1-b30f-c21b5795e82f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 73,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "stream_unit_test_gpt(pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 60,
+ "id": "17380c0f-b851-472b-a234-d86f5c219e50",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_comment_claude(code):\n",
+ " result = claude.messages.stream(\n",
+ " model=CLAUDE_MODEL,\n",
+ " max_tokens=2000,\n",
+ " system=system_prompt_for_comment(),\n",
+ " messages=[{\"role\": \"user\", \"content\": user_prompt_for_comment(code)}],\n",
+ " )\n",
+ " reply = \"\"\n",
+ " with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " reply += text\n",
+ " #print(text, end=\"\", flush=True)\n",
+ " yield reply.replace('```','')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 64,
+ "id": "0a2d016d-76a2-4752-bd4d-6f93ddec46be",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_unit_test_claude(code):\n",
+ " result = claude.messages.stream(\n",
+ " model=CLAUDE_MODEL,\n",
+ " max_tokens=2000,\n",
+ " system=system_prompt_for_unit_test(),\n",
+ " messages=[{\"role\": \"user\", \"content\": user_prompt_for_unit_test(code)}],\n",
+ " )\n",
+ " reply = \"\"\n",
+ " with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " reply += text\n",
+ " #print(text, end=\"\", flush=True)\n",
+ " yield reply.replace('```','')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "ee43428e-b577-4e95-944d-399f2f3b89ff",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Here's the documented version of your Python code:\n",
+ "\n",
+ "```python\n",
+ "import time\n",
+ "\n",
+ " float) -> float:rations: int, param1: float, param2:\n",
+ " \"\"\"\n",
+ "Calculates a series sum based on the given parameters.\n",
+ "\n",
+ " This function computes a series sum using the formula:\n",
+ "i*param1 + param2) - 1/(i*param1 - param2)) for i from 1 to iterations.\n",
+ "\n",
+ " Args:\n",
+ " iterations to perform. Must be positive.\n",
+ "float): The first parameter used in the calculation.\n",
+ "(float): The second parameter used in the calculation.\n",
+ "\n",
+ " Returns:\n",
+ ". float: The result of the series sum calculation\n",
+ "\n",
+ " Raises:\n",
+ ". ValueError: If iterations is not positive\n",
+ "is 0 or if param2 is equal to param1.\n",
+ "\n",
+ " Example:\n",
+ " = calculate(1000, 4, 1)\n",
+ ">>> print(f\"{result:.6f}\")\n",
+ ".392699 0\n",
+ "\n",
+ " Note:\n",
+ " The function may be computationally expensive for large numbers of iterations.\n",
+ ", floating-point precision limitations may affect accuracy.\n",
+ " \"\"\"\n",
+ " if iterations <= 0:\n",
+ " must be a positive integer\")rations\n",
+ "\n",
+ " result = 1.0\n",
+ " for i in range(1, iterations + 1):\n",
+ " the seriesalculate the denominators for both terms in\n",
+ "1 - param2 = i * param\n",
+ " param1 + param2\n",
+ "\n",
+ "d division by zero\n",
+ " 0 or j2 == 0:==\n",
+ " calculation\")ise ZeroDivisionError(\"Division by zero in\n",
+ "\n",
+ "d add the second terme first term an\n",
+ " result -= (1 / j1)\n",
+ " result += (1 / j2)\n",
+ "\n",
+ " return result\n",
+ "\n",
+ "# Measure execution time\n",
+ "()art_time = time.time\n",
+ "\n",
+ "# Perform calculation with 100 million iterations\n",
+ " The result is multiplied by 4 as per the original code\n",
+ "000, 4, 1) * 4late(100_000_\n",
+ "\n",
+ "d_time = time.time()\n",
+ "\n",
+ " with high precision for the calculated value\n",
+ "Result: {result:.12f}\")\n",
+ "(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n",
+ "```\n",
+ "\n",
+ " this documented version:\n",
+ "\n",
+ " been added to the `calculate` function, following Google style guidelines and including all the requested elements.\n",
+ "\n",
+ " hints have been added to the function signature for better clarity and to support static type checking.\n",
+ "\n",
+ "d to explain the key steps in the calculation process.\n",
+ "\n",
+ " check for positive iterations has been added to prevent invalid input.\n",
+ "\n",
+ " been added to handle potential errors.\n",
+ "\n",
+ " Comments have been added to the main script to explain the purpose of each step.\n",
+ "\n",
+ " documentation provides a clear understanding of the function's purpose, its parameters, return value, potential exceptions, and includes an example of usage. It also notes potential limitations regarding computational cost and floating-point precision for very large numbers of iterations."
+ ]
+ }
+ ],
+ "source": [
+ "stream_comment_claude(pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 63,
+ "id": "0565e33b-9f14-48b7-ae8d-d22dc03b93c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Here's a comprehensive set of unit tests for the given Python code using pytest:\n",
+ "\n",
+ "```python\n",
+ "import pytest\n",
+ "import time\n",
+ " import isclose\n",
+ "from unittest.mock import patch\n",
+ "\n",
+ "# Import the function to be tested\n",
+ "# Assuming the code is in a file named your_module.py\n",
+ "\n",
+ "# Test data generator\n",
+ "_data():rate_test\n",
+ " return [\n",
+ ", 2, 1, 0.6931471805),\n",
+ " 3, 2, 0.6931471806),\n",
+ ", 3, 0.6931471806),\n",
+ ", 1, 0.6931471806),\n",
+ " ]\n",
+ "\n",
+ " datature for common test\n",
+ "@pytest.fixture\n",
+ "def common_data():\n",
+ "return {\n",
+ " 'iterations': 100,\n",
+ " 'param1': 4,\n",
+ " 'param2': 1\n",
+ " }\n",
+ "\n",
+ "# Normal case tests\n",
+ "rize(\"iterations, param1, param2, expected\", generate_test_data())\n",
+ "cases(iterations, param1, param2, expected):\n",
+ "1, param2) = calculate(iterations, param\n",
+ "(result, expected, rel_tol=1e-9), f\"Expected {expected}, but got {result}\"\n",
+ "\n",
+ " cases and boundary values\n",
+ "_cases():calculate_edge\n",
+ "d inputsst with minimum vali\n",
+ " 0) == 2.0 calculate(1, 1,\n",
+ " \n",
+ " # Test with very large iterations\n",
+ "_result = calculate(10**8, 4, 1)\n",
+ ", 0.6931471806, rel_tol=1e-9)lt\n",
+ "\n",
+ "# Invalid inputs and error conditions\n",
+ "def test_calculate_invalid_inputs():\n",
+ " with pytest.raises(ValueError):\n",
+ "0, 4, 1) # iterations should be positive\n",
+ " \n",
+ "(ZeroDivisionError):es\n",
+ "10, 1, 1) # This will cause division by zero\n",
+ "\n",
+ "TypeError):test.raises(\n",
+ "1) # iterations should be an integer\n",
+ "\n",
+ "# Test with different combinations of parameters\n",
+ "rize(\"iterations, param1, param2\", [\n",
+ "), (100, 2, 2\n",
+ " (1000, 3, 3),\n",
+ "(10000, 5, 5),\n",
+ " (100000, 10, 10)\n",
+ "])\n",
+ " param1, param2):e_parameter_combinations(iterations,\n",
+ " calculate(iterations, param1, param2)\n",
+ " assert isinstance(result, float)\n",
+ " assert result > 0\n",
+ "\n",
+ " execution time\n",
+ "common_data):ulate_execution_time(\n",
+ " time.time()me =\n",
+ " calculate(**common_data)\n",
+ " end_time = time.time()\n",
+ " execution_time = end_time - start_time\n",
+ " f\"Execution took {execution_time} seconds, which is too long\"\n",
+ "\n",
+ " result precision\n",
+ "data):st_calculate_precision(common_\n",
+ "data)esult = calculate(**common_\n",
+ "split('.')[1]) >= 10, \"Result should have at least 10 decimal places\"\n",
+ "\n",
+ "# Test with mocked time function\n",
+ ".time')'time\n",
+ "(mock_time, common_data):ocked_time\n",
+ ", 0.5] # Simulate 0.5 seconds execution time\n",
+ "_time = time.time()\n",
+ " = calculate(**common_data)\n",
+ "d_time = time.time()\n",
+ " end_time - start_time == 0.5\n",
+ "\n",
+ "# Helper function to test monotonicity\n",
+ "_monotonic(lst):\n",
+ " <= lst[i+1] for i in range(len(lst)-1)) or all(lst[i] >= lst[i+1] for i in range(len(lst)-1))\n",
+ "\n",
+ " increasing iterationscity with\n",
+ "def test_calculate_monotonicity():\n",
+ " 1) for i in range(1, 6)]10**i, 4,\n",
+ "), \"Results should be monotonic with increasing iterations\"\n",
+ "\n",
+ " Test with very small and very large parameters\n",
+ ", param1, param2\", [rize(\"iterations\n",
+ "(100, 1e-5, 1e-5),\n",
+ ", 1e5)00, 1e5\n",
+ "])\n",
+ "_parameters(iterations, param1, param2):\n",
+ "1, param2) = calculate(iterations, param\n",
+ "result == float('inf') or result == float('-inf')), \"Result should not be infinity\"\n",
+ "assert not isclose(result, 0, abs_tol=1e-10), \"Result should not be too close to zero\"\n",
+ "\n",
+ "```\n",
+ "\n",
+ " for the `calculate` function:range of scenarios\n",
+ "\n",
+ " with different inputs and expected outputs.\n",
+ " and boundary values, including minimum valid inputs and very large iterations.\n",
+ " Invalid inputs and error conditions, testing for expected exceptions.\n",
+ " Different combinations of parameters to ensure the function works correctly for various inputs.\n",
+ " to ensure the function performs within acceptable time limits.\n",
+ " Precision test to verify the result has sufficient decimal places.\n",
+ " A test with mocked time function to simulate and verify execution time measurement.\n",
+ " if results are consistent with increasing iterations.\n",
+ " with extreme parameters (very small and very large) to ensure numerical stability.\n",
+ "\n",
+ "rization, fixtures, and markers. It also includes necessary imports, helper functions, and a test data generator.\n",
+ "\n",
+ "d `test_your_module.py` in the same directory as your original code file (`your_module.py`). Then run `pytest test_your_module.py` from the command line.\n",
+ "\n",
+ " pytest (`pip install pytest`) before running the tests."
+ ]
+ }
+ ],
+ "source": [
+ "stream_unit_test_claude(pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "id": "f13b3a5b-366d-4b28-adda-977a313e6b4d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_comment_model(model, model_url, code):\n",
+ " tokenizer = AutoTokenizer.from_pretrained(model)\n",
+ " messages = messages_for_comment(code)\n",
+ " text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n",
+ " client = InferenceClient(model_url, token=hf_token)\n",
+ " stream = client.text_generation(text, stream=True, details=True, max_new_tokens=3000)\n",
+ " result = \"\"\n",
+ " for r in stream:\n",
+ " #print(r.token.text, end = \"\")\n",
+ " result += r.token.text\n",
+ " yield result \n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 67,
+ "id": "e2efdb92-fc7a-4952-ab46-ae942cb996bf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_unit_test_model(model, model_url, code):\n",
+ " tokenizer = AutoTokenizer.from_pretrained(model)\n",
+ " messages = messages_for_unit_test(code)\n",
+ " text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n",
+ " client = InferenceClient(model_url, token=hf_token)\n",
+ " stream = client.text_generation(text, stream=True, details=True, max_new_tokens=3000)\n",
+ " result = \"\"\n",
+ " for r in stream:\n",
+ " #print(r.token.text, end = \"\")\n",
+ " result += r.token.text\n",
+ " yield result \n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "id": "0a756193-fcba-43da-a981-203c10d36488",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 41,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "stream_comment_model(code_qwen, CODE_QWEN_URL, pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 70,
+ "id": "12ddcbf4-6286-47a8-847b-5be78e7aa995",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Here are the unit tests for the given Python code:\n",
+ "\n",
+ "```python\n",
+ "import pytest\n",
+ "import time\n",
+ " unittest.mock import patch\n",
+ "\n",
+ "def calculate(iterations, param1, param2):\n",
+ " result = 1.0\n",
+ " for i in range(1, iterations+1):\n",
+ " i * param1 - param2\n",
+ "result -= (1/j)\n",
+ " j = i * param1 + param2\n",
+ "result += (1/j)\n",
+ " return result\n",
+ "\n",
+ "@pytest.fixture\n",
+ " mock_time():\n",
+ "('time.time') as mock_time:\n",
+ "yield mock_time\n",
+ "\n",
+ "_calculate_normal_inputs(mock_time):\n",
+ "mock_time.return_value = 0\n",
+ "result = calculate(100_000_000, 4, 1) * 4\n",
+ "expected_result = 0.0\n",
+ " == expected_result\n",
+ "\n",
+ "_calculate_edge_cases(mock_time):\n",
+ " mock_time.return_value = 0\n",
+ " calculate(0, 4, 1) * 4\n",
+ " expected_result = 0.0\n",
+ " result == expected_result\n",
+ "\n",
+ " = calculate(100_000_000, 0, 1) * 4\n",
+ "expected_result = 0.0\n",
+ " result == expected_result\n",
+ "\n",
+ " = calculate(100_000_000, 4, 0) * 4\n",
+ "_result = 0.0\n",
+ " assert result == expected_result\n",
+ "\n",
+ "def test_calculate_invalid_inputs(mock_time):\n",
+ " mock_time.return_value = 0\n",
+ ".raises(TypeError):\n",
+ "calculate(100_000_000, 'a', 1) * 4\n",
+ "with pytest.raises(TypeError):\n",
+ "100_000_000, 4, 'b') * 4\n",
+ ".raises(TypeError):\n",
+ "calculate('a', 4, 1) * 4\n",
+ "test.raises(TypeError):\n",
+ "(100_000_000, 4, 1, 'c') * 4\n",
+ "\n",
+ "def test_calculate_different_combinations(mock_time):\n",
+ " mock_time.return_value = 0\n",
+ "result = calculate(100_000_000, 4, 1) * 4\n",
+ " expected_result = 0.0\n",
+ " result == expected_result\n",
+ "\n",
+ " = calculate(100_000_000, 4, -1) * 4\n",
+ "expected_result = 0.0\n",
+ " == expected_result\n",
+ "\n",
+ " calculate(100_000_000, -4, 1) * 4\n",
+ "result = 0.0_\n",
+ "assert result == expected_result\n",
+ "\n",
+ "result = calculate(100_000_000, -4, -1) * 4\n",
+ " expected_result = 0.0\n",
+ " result == expected_result\n",
+ "\n",
+ "def test_calculate_execution_time(mock_time):\n",
+ "_time.return_value = 0\n",
+ "_time = mock_time.return_value\n",
+ "calculate(100_000_000, 4, 1) * 4\n",
+ "end_time = mock_time.return_value\n",
+ " expected_execution_time = 0.0\n",
+ " assert (end_time - start_time) == expected_execution_time\n",
+ "```\n",
+ "\n",
+ " covers all the scenarios mentioned in the problem description. It tests the function with normal inputs, edge cases, invalid inputs, different combinations of parameters, and checks the execution time.<|im_end|>"
+ ]
+ }
+ ],
+ "source": [
+ "stream_unit_test_model(code_qwen, CODE_QWEN_URL, pi)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "id": "321609ee-b64a-44fc-9090-39f87e1f8e0e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def comment_code(python, model):\n",
+ " if model==\"GPT\":\n",
+ " result = stream_comment_gpt(python)\n",
+ " elif model==\"Claude\":\n",
+ " result = stream_comment_claude(python)\n",
+ " elif model==\"CodeQwen\":\n",
+ " result = stream_comment_model(code_qwen, CODE_QWEN_URL, python)\n",
+ " else:\n",
+ " raise ValueError(\"Unknown model\")\n",
+ " for stream_so_far in result:\n",
+ " yield stream_so_far "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 69,
+ "id": "d4c560c9-922d-4893-941f-42893373b1be",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def get_unit_test(python, model):\n",
+ " if model==\"GPT\":\n",
+ " result = stream_unit_test_gpt(python)\n",
+ " elif model==\"Claude\":\n",
+ " result = stream_unit_test_claude(python)\n",
+ " elif model==\"CodeQwen\":\n",
+ " result = stream_unit_test_model(code_qwen, CODE_QWEN_URL, python)\n",
+ " else:\n",
+ " raise ValueError(\"Unknown model\")\n",
+ " for stream_so_far in result:\n",
+ " yield stream_so_far "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "id": "f85bc777-bebe-436b-88cc-b9ecdb6306c0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "css = \"\"\"\n",
+ ".python {background-color: #306998;}\n",
+ ".cpp {background-color: #050;}\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "id": "ee27cc91-81e6-42c8-ae3c-c04161229d8c",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "* Running on local URL: http://127.0.0.1:7881\n",
+ "\n",
+ "To create a public link, set `share=True` in `launch()`.\n"
+ ]
+ },
+ {
+ "data": {
+ "text/html": [
+ ""
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/plain": []
+ },
+ "execution_count": 74,
+ "metadata": {},
+ "output_type": "execute_result"
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Here are the unit tests for the given Python code:\n",
+ "\n",
+ "```python\n",
+ "import pytest\n",
+ "import time\n",
+ " unittest.mock import patch\n",
+ "\n",
+ "def calculate(iterations, param1, param2):\n",
+ " result = 1.0\n",
+ " for i in range(1, iterations+1):\n",
+ " i * param1 - param2\n",
+ " result -= (1/j)\n",
+ " i * param1 + param2\n",
+ "result += (1/j)\n",
+ " return result\n",
+ "\n",
+ "@pytest.fixture\n",
+ " mock_time():\n",
+ " with patch('time.time') as mock_time:\n",
+ "ield mock_time\n",
+ "\n",
+ "calculate_normal_inputs(mock_time):\n",
+ "time.return_value = 0\n",
+ " calculate(100_000_000, 4, 1) * 4\n",
+ "result = 0.0_\n",
+ "assert result == expected_result\n",
+ "\n",
+ " test_calculate_edge_cases(mock_time):\n",
+ "time.return_value = 0\n",
+ " calculate(0, 4, 1) * 4\n",
+ "_result = 0.0\n",
+ " assert result == expected_result\n",
+ "\n",
+ " result = calculate(100_000_000, 0, 1) * 4\n",
+ "result = 0.0_\n",
+ "assert result == expected_result\n",
+ "\n",
+ "result = calculate(100_000_000, 4, 0) * 4\n",
+ " expected_result = 0.0\n",
+ "assert result == expected_result\n",
+ "\n",
+ " test_calculate_invalid_inputs(mock_time):\n",
+ "_time.return_value = 0\n",
+ "test.raises(TypeError):\n",
+ " calculate(100_000_000, 'a', 1) * 4\n",
+ "with pytest.raises(TypeError):\n",
+ "ulate(100_000_000, 4, 'b') * 4\n",
+ " pytest.raises(TypeError):\n",
+ "ulate('a', 4, 1) * 4\n",
+ "test.raises(TypeError):\n",
+ " calculate(100_000_000, 4, 1, 'c') * 4\n",
+ "\n",
+ "_calculate_different_combinations(mock_time):\n",
+ " mock_time.return_value = 0\n",
+ " result = calculate(100_000_000, 4, 1) * 4\n",
+ " expected_result = 0.0\n",
+ " == expected_result\n",
+ "\n",
+ " calculate(100_000_000, 4, -1) * 4\n",
+ "_result = 0.0\n",
+ " assert result == expected_result\n",
+ "\n",
+ " result = calculate(100_000_000, -4, 1) * 4\n",
+ " expected_result = 0.0\n",
+ " result == expected_result\n",
+ "\n",
+ " calculate(100_000_000, -4, -1) * 4\n",
+ "_result = 0.0\n",
+ " assert result == expected_result\n",
+ "\n",
+ "def test_calculate_execution_time(mock_time):\n",
+ "mock_time.return_value = 0\n",
+ "start_time = mock_time.return_value\n",
+ " calculate(100_000_000, 4, 1) * 4\n",
+ " end_time = mock_time.return_value\n",
+ " expected_execution_time = 0.0\n",
+ " assert (end_time - start_time) == expected_execution_time\n",
+ "```\n",
+ "\n",
+ " covers all the scenarios mentioned in the problem description. It tests the function with normal inputs, edge cases, invalid inputs, different combinations of parameters, and checks the execution time.<|im_end|>"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Traceback (most recent call last):\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\queueing.py\", line 625, in process_events\n",
+ " response = await route_utils.call_process_api(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\route_utils.py\", line 322, in call_process_api\n",
+ " output = await app.get_blocks().process_api(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 2047, in process_api\n",
+ " result = await self.call_function(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 1606, in call_function\n",
+ " prediction = await utils.async_iteration(iterator)\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 714, in async_iteration\n",
+ " return await anext(iterator)\n",
+ " ^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 708, in __anext__\n",
+ " return await anyio.to_thread.run_sync(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\to_thread.py\", line 56, in run_sync\n",
+ " return await get_async_backend().run_sync_in_worker_thread(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 2505, in run_sync_in_worker_thread\n",
+ " return await future\n",
+ " ^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 1005, in run\n",
+ " result = context.run(func, *args)\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 691, in run_sync_iterator_async\n",
+ " return next(iterator)\n",
+ " ^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 852, in gen_wrapper\n",
+ " response = next(iterator)\n",
+ " ^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\AppData\\Local\\Temp\\ipykernel_27660\\2822054561.py\", line 10, in get_unit_test\n",
+ " for stream_so_far in result:\n",
+ "TypeError: 'NoneType' object is not iterable\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Here are the unit tests for the given Python code:\n",
+ "\n",
+ "```python\n",
+ "import pytest\n",
+ "import time\n",
+ "est.mock import patch\n",
+ "\n",
+ "(iterations, param1, param2):\n",
+ "result = 1.0\n",
+ "for i in range(1, iterations+1):\n",
+ "j = i * param1 - param2\n",
+ " -= (1/j)esult\n",
+ "j = i * param1 + param2\n",
+ " += (1/j)esult\n",
+ "return result\n",
+ "\n",
+ "pytest.fixture\n",
+ "_time():\n",
+ " with patch('time.time') as mock_time:\n",
+ "ield mock_time\n",
+ "\n",
+ "calculate_normal_inputs(mock_time):\n",
+ "time.return_value = 0\n",
+ " calculate(100_000_000, 4, 1) * 4\n",
+ "_result = 0.0\n",
+ " assert result == expected_result\n",
+ "\n",
+ "def test_calculate_edge_cases(mock_time):\n",
+ "mock_time.return_value = 0\n",
+ "result = calculate(0, 4, 1) * 4\n",
+ " expected_result = 0.0\n",
+ " result == expected_result\n",
+ "\n",
+ " = calculate(100_000_000, 0, 1) * 4\n",
+ "_result = 0.0\n",
+ "assert result == expected_result\n",
+ "\n",
+ "result = calculate(100_000_000, 4, 0) * 4\n",
+ " expected_result = 0.0\n",
+ " result == expected_result\n",
+ "\n",
+ "_calculate_invalid_inputs(mock_time):\n",
+ "time.return_value = 0\n",
+ " with pytest.raises(TypeError):\n",
+ "(100_000_000, 'a', 1) * 4\n",
+ "ises(TypeError):ra\n",
+ "ulate(100_000_000, 4, 'b') * 4\n",
+ " pytest.raises(TypeError):\n",
+ "ulate('a', 4, 1) * 4\n",
+ " pytest.raises(TypeError):\n",
+ "ulate(100_000_000, 4, 1, 'c') * 4\n",
+ "\n",
+ "calculate_different_combinations(mock_time):\n",
+ " mock_time.return_value = 0\n",
+ " result = calculate(100_000_000, 4, 1) * 4\n",
+ " = 0.0pected_result\n",
+ " result == expected_result\n",
+ "\n",
+ " = calculate(100_000_000, 4, -1) * 4\n",
+ "expected_result = 0.0\n",
+ " expected_resultt ==\n",
+ "\n",
+ " result = calculate(100_000_000, -4, 1) * 4\n",
+ "result = 0.0_\n",
+ " == expected_result\n",
+ "\n",
+ " calculate(100_000_000, -4, -1) * 4\n",
+ " = 0.0pected_result\n",
+ " result == expected_result\n",
+ "\n",
+ "def test_calculate_execution_time(mock_time):\n",
+ "_time.return_value = 0\n",
+ "_time = mock_time.return_value\n",
+ "100_000_000, 4, 1) * 4\n",
+ " end_time = mock_time.return_value\n",
+ "_execution_time = 0.0\n",
+ " (end_time - start_time) == expected_execution_time\n",
+ "``\n",
+ "\n",
+ " suite covers all the scenarios mentioned in the problem description. It tests the function with normal inputs, edge cases, invalid inputs, different combinations of parameters, and checks the execution time.<|im_end|>"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Traceback (most recent call last):\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\queueing.py\", line 625, in process_events\n",
+ " response = await route_utils.call_process_api(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\route_utils.py\", line 322, in call_process_api\n",
+ " output = await app.get_blocks().process_api(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 2047, in process_api\n",
+ " result = await self.call_function(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 1606, in call_function\n",
+ " prediction = await utils.async_iteration(iterator)\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 714, in async_iteration\n",
+ " return await anext(iterator)\n",
+ " ^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 708, in __anext__\n",
+ " return await anyio.to_thread.run_sync(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\to_thread.py\", line 56, in run_sync\n",
+ " return await get_async_backend().run_sync_in_worker_thread(\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 2505, in run_sync_in_worker_thread\n",
+ " return await future\n",
+ " ^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 1005, in run\n",
+ " result = context.run(func, *args)\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 691, in run_sync_iterator_async\n",
+ " return next(iterator)\n",
+ " ^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 852, in gen_wrapper\n",
+ " response = next(iterator)\n",
+ " ^^^^^^^^^^^^^^\n",
+ " File \"C:\\Users\\ebaba\\AppData\\Local\\Temp\\ipykernel_27660\\2822054561.py\", line 10, in get_unit_test\n",
+ " for stream_so_far in result:\n",
+ "TypeError: 'NoneType' object is not iterable\n"
+ ]
+ }
+ ],
+ "source": [
+ "with gr.Blocks(css=css) as ui:\n",
+ " gr.Markdown(\"## Convert code from Python to C++\")\n",
+ " with gr.Row():\n",
+ " python = gr.Textbox(label=\"Python code:\", value=pi, lines=10)\n",
+ " result = gr.Textbox(label=\"Result code:\", lines=10)\n",
+ " with gr.Row():\n",
+ " model = gr.Dropdown([\"GPT\", \"Claude\",\"CodeQwen\"], label=\"Select model\", value=\"GPT\")\n",
+ " with gr.Row():\n",
+ " comment_button = gr.Button(\"Comment code\")\n",
+ " with gr.Row():\n",
+ " unit_test_button = gr.Button(\"Unit Test code\")\n",
+ " \n",
+ " comment_button.click(comment_code, inputs=[python, model], outputs=[result])\n",
+ " unit_test_button.click(get_unit_test, inputs=[python, model], outputs=[result])\n",
+ "ui.launch(inbrowser=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "06e8279c-b488-4807-9bed-9d26be11c057",
+ "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
+}
From 2eac15b4799da5c6fce37b363ebb7a4e88a0a2b7 Mon Sep 17 00:00:00 2001
From: emmanuel
Date: Sun, 19 Jan 2025 19:59:23 +0100
Subject: [PATCH 21/61] clean up
---
.../day5-homework.ipynb | 801 ++----------------
1 file changed, 50 insertions(+), 751 deletions(-)
diff --git a/week4/community-contributions/day5-homework.ipynb b/week4/community-contributions/day5-homework.ipynb
index 3d6bded..c34be7b 100644
--- a/week4/community-contributions/day5-homework.ipynb
+++ b/week4/community-contributions/day5-homework.ipynb
@@ -2,10 +2,19 @@
"cells": [
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 1,
"id": "6d67dba5-38ec-459a-9132-4a56c6a814cd",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "ename": "SyntaxError",
+ "evalue": "invalid syntax (2447672335.py, line 1)",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;36m Cell \u001b[1;32mIn[1], line 1\u001b[1;36m\u001b[0m\n\u001b[1;33m Comment and Unit Test Generater\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
+ ]
+ }
+ ],
"source": [
"Comment and Unit Test Generater \n",
"\n",
@@ -18,7 +27,7 @@
},
{
"cell_type": "code",
- "execution_count": 24,
+ "execution_count": null,
"id": "ea1841f6-4afc-4d29-ace8-5ca5a3915c8c",
"metadata": {},
"outputs": [],
@@ -43,7 +52,7 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": null,
"id": "11957fd3-6c61-4496-aef1-8223cb9ec4ce",
"metadata": {},
"outputs": [],
@@ -58,7 +67,7 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": null,
"id": "ee7b08fd-e678-4234-895e-4e3a925e60f0",
"metadata": {},
"outputs": [],
@@ -73,18 +82,10 @@
},
{
"cell_type": "code",
- "execution_count": 25,
+ "execution_count": null,
"id": "c8023255-9c98-4fbc-92e4-c553bed3b605",
"metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"hf_token = os.environ['HF_TOKEN']\n",
"login(hf_token, add_to_git_credential=True)"
@@ -92,7 +93,7 @@
},
{
"cell_type": "code",
- "execution_count": 28,
+ "execution_count": null,
"id": "f8ce3f5e-74c4-4d35-bfbc-91c5be85e094",
"metadata": {},
"outputs": [],
@@ -103,7 +104,7 @@
},
{
"cell_type": "code",
- "execution_count": 49,
+ "execution_count": null,
"id": "1bbc66b6-52ae-465e-a368-edc8f097fe9d",
"metadata": {},
"outputs": [],
@@ -125,7 +126,7 @@
},
{
"cell_type": "code",
- "execution_count": 50,
+ "execution_count": null,
"id": "b089f87b-53ae-40ad-8d06-b9924bb998a0",
"metadata": {},
"outputs": [],
@@ -149,7 +150,7 @@
},
{
"cell_type": "code",
- "execution_count": 51,
+ "execution_count": null,
"id": "22193622-f3a0-4894-a6c4-eb6d88097861",
"metadata": {},
"outputs": [],
@@ -180,7 +181,7 @@
},
{
"cell_type": "code",
- "execution_count": 52,
+ "execution_count": null,
"id": "81e61752-ec2f-44c1-86a2-ff3234a0358c",
"metadata": {},
"outputs": [],
@@ -219,7 +220,7 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": null,
"id": "f31ceed3-0eb2-4962-ab86-2d0302185560",
"metadata": {},
"outputs": [],
@@ -247,26 +248,17 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": null,
"id": "192c30f5-4be6-49b7-a054-11bfcffa91e0",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Result: 3.141592658589\n",
- "Execution Time: 58.228012 seconds\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"exec(pi)"
]
},
{
"cell_type": "code",
- "execution_count": 53,
+ "execution_count": null,
"id": "d4e920dc-4094-42d8-9255-18f2919df2d4",
"metadata": {},
"outputs": [],
@@ -280,7 +272,7 @@
},
{
"cell_type": "code",
- "execution_count": 54,
+ "execution_count": null,
"id": "77500cae-bf84-405c-8b03-2f984108951b",
"metadata": {},
"outputs": [],
@@ -294,7 +286,7 @@
},
{
"cell_type": "code",
- "execution_count": 58,
+ "execution_count": null,
"id": "5ec58bf1-4a44-4c21-a71a-2cac359884e5",
"metadata": {},
"outputs": [],
@@ -312,91 +304,17 @@
},
{
"cell_type": "code",
- "execution_count": 18,
+ "execution_count": null,
"id": "47c615e2-4eb6-4ce1-ad09-7f2e6dbc3934",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "```python\n",
- "import time\n",
- "\n",
- "def calculate(iterations: int, param1: float, param2: float) -> float:\n",
- " \"\"\"\n",
- " Performs a series of mathematical operations in a loop to calculate a result.\n",
- "\n",
- " This function iteratively modifies a result variable through a series of arithmetic\n",
- " operations. Essentially, it calculates the sum of alternating series adjustments,\n",
- " simulating a specific numerical approximation process.\n",
- "\n",
- " Args:\n",
- " iterations (int): The number of iterations to perform. Must be a positive integer.\n",
- " param1 (float): The factor applied for multiplication inside the iteration.\n",
- " param2 (float): The factor subtracted and added inside the iteration for denominator adjustment.\n",
- "\n",
- " Returns:\n",
- " float: The calculated result after completing all iterations.\n",
- "\n",
- " Raises:\n",
- " ZeroDivisionError: If any calculated denominator becomes zero during execution,\n",
- " which may happen if `i * param1 - param2` or `i * param1 + param2` evaluates to zero.\n",
- "\n",
- " Usage Example:\n",
- " result = calculate(100_000_000, 4, 1)\n",
- " print(f\"Calculated Result: {result * 4}\")\n",
- "\n",
- " Notes:\n",
- " - The function can be computationally intensive depending on the number of iterations.\n",
- " - Ensure that `param1` and `param2` are chosen to avoid division by zero.\n",
- " - Floating-point precision issues might arise due to large iterations count.\n",
- " \"\"\"\n",
- " \n",
- " result = 1.0\n",
- " for i in range(1, iterations + 1):\n",
- " # Calculate modified denominator by subtracting param2\n",
- " j = i * param1 - param2\n",
- " \n",
- " # Subtract reciprocal from the result\n",
- " # Potential ZeroDivisionError if (i * param1 - param2) == 0\n",
- " result -= (1 / j)\n",
- " \n",
- " # Calculate modified denominator by adding param2\n",
- " j = i * param1 + param2\n",
- " \n",
- " # Add reciprocal to the result\n",
- " # Potential ZeroDivisionError if (i * param1 + param2) == 0\n",
- " result += (1 / j)\n",
- " \n",
- " return result\n",
- "\n",
- "\n",
- "start_time = time.time()\n",
- "result = calculate(100_000_000, 4, 1) * 4 # Scaling final result by 4 for specific use case\n",
- "end_time = time.time()\n",
- "\n",
- "# Output result with high precision and execution time for measurement\n",
- "print(f\"Result: {result:.12f}\")\n",
- "print(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n",
- "```\n",
- "\n",
- "### Explanation of Changes:\n",
- "- **Docstring**: The docstring provides a comprehensive explanation of the function's purpose and the calculations it performs, specifying parameter types and behavior.\n",
- "- **Exceptions**: A note about `ZeroDivisionError` is included, as the calculation might lead to division by zero with certain inputs.\n",
- "- **Usage Example**: Demonstrates how to call the function with a specific configuration.\n",
- "- **Notes**: Provides guidance on potential performance concerns and precision limitations.\n",
- "- **Inline Comments**: Added to clarify key lines where logical computations occur and where division by zero might be a risk."
- ]
- }
- ],
+ "outputs": [],
"source": [
"stream_comment_gpt(pi)"
]
},
{
"cell_type": "code",
- "execution_count": 59,
+ "execution_count": null,
"id": "0b990875-31fd-40e5-bc8c-f6099d362249",
"metadata": {},
"outputs": [],
@@ -413,28 +331,17 @@
},
{
"cell_type": "code",
- "execution_count": 73,
+ "execution_count": null,
"id": "3dc90578-4f5e-47f1-b30f-c21b5795e82f",
"metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- ""
- ]
- },
- "execution_count": 73,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
+ "outputs": [],
"source": [
"stream_unit_test_gpt(pi)"
]
},
{
"cell_type": "code",
- "execution_count": 60,
+ "execution_count": null,
"id": "17380c0f-b851-472b-a234-d86f5c219e50",
"metadata": {},
"outputs": [],
@@ -456,7 +363,7 @@
},
{
"cell_type": "code",
- "execution_count": 64,
+ "execution_count": null,
"id": "0a2d016d-76a2-4752-bd4d-6f93ddec46be",
"metadata": {},
"outputs": [],
@@ -478,249 +385,27 @@
},
{
"cell_type": "code",
- "execution_count": 23,
+ "execution_count": null,
"id": "ee43428e-b577-4e95-944d-399f2f3b89ff",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Here's the documented version of your Python code:\n",
- "\n",
- "```python\n",
- "import time\n",
- "\n",
- " float) -> float:rations: int, param1: float, param2:\n",
- " \"\"\"\n",
- "Calculates a series sum based on the given parameters.\n",
- "\n",
- " This function computes a series sum using the formula:\n",
- "i*param1 + param2) - 1/(i*param1 - param2)) for i from 1 to iterations.\n",
- "\n",
- " Args:\n",
- " iterations to perform. Must be positive.\n",
- "float): The first parameter used in the calculation.\n",
- "(float): The second parameter used in the calculation.\n",
- "\n",
- " Returns:\n",
- ". float: The result of the series sum calculation\n",
- "\n",
- " Raises:\n",
- ". ValueError: If iterations is not positive\n",
- "is 0 or if param2 is equal to param1.\n",
- "\n",
- " Example:\n",
- " = calculate(1000, 4, 1)\n",
- ">>> print(f\"{result:.6f}\")\n",
- ".392699 0\n",
- "\n",
- " Note:\n",
- " The function may be computationally expensive for large numbers of iterations.\n",
- ", floating-point precision limitations may affect accuracy.\n",
- " \"\"\"\n",
- " if iterations <= 0:\n",
- " must be a positive integer\")rations\n",
- "\n",
- " result = 1.0\n",
- " for i in range(1, iterations + 1):\n",
- " the seriesalculate the denominators for both terms in\n",
- "1 - param2 = i * param\n",
- " param1 + param2\n",
- "\n",
- "d division by zero\n",
- " 0 or j2 == 0:==\n",
- " calculation\")ise ZeroDivisionError(\"Division by zero in\n",
- "\n",
- "d add the second terme first term an\n",
- " result -= (1 / j1)\n",
- " result += (1 / j2)\n",
- "\n",
- " return result\n",
- "\n",
- "# Measure execution time\n",
- "()art_time = time.time\n",
- "\n",
- "# Perform calculation with 100 million iterations\n",
- " The result is multiplied by 4 as per the original code\n",
- "000, 4, 1) * 4late(100_000_\n",
- "\n",
- "d_time = time.time()\n",
- "\n",
- " with high precision for the calculated value\n",
- "Result: {result:.12f}\")\n",
- "(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n",
- "```\n",
- "\n",
- " this documented version:\n",
- "\n",
- " been added to the `calculate` function, following Google style guidelines and including all the requested elements.\n",
- "\n",
- " hints have been added to the function signature for better clarity and to support static type checking.\n",
- "\n",
- "d to explain the key steps in the calculation process.\n",
- "\n",
- " check for positive iterations has been added to prevent invalid input.\n",
- "\n",
- " been added to handle potential errors.\n",
- "\n",
- " Comments have been added to the main script to explain the purpose of each step.\n",
- "\n",
- " documentation provides a clear understanding of the function's purpose, its parameters, return value, potential exceptions, and includes an example of usage. It also notes potential limitations regarding computational cost and floating-point precision for very large numbers of iterations."
- ]
- }
- ],
+ "outputs": [],
"source": [
"stream_comment_claude(pi)"
]
},
{
"cell_type": "code",
- "execution_count": 63,
+ "execution_count": null,
"id": "0565e33b-9f14-48b7-ae8d-d22dc03b93c9",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Here's a comprehensive set of unit tests for the given Python code using pytest:\n",
- "\n",
- "```python\n",
- "import pytest\n",
- "import time\n",
- " import isclose\n",
- "from unittest.mock import patch\n",
- "\n",
- "# Import the function to be tested\n",
- "# Assuming the code is in a file named your_module.py\n",
- "\n",
- "# Test data generator\n",
- "_data():rate_test\n",
- " return [\n",
- ", 2, 1, 0.6931471805),\n",
- " 3, 2, 0.6931471806),\n",
- ", 3, 0.6931471806),\n",
- ", 1, 0.6931471806),\n",
- " ]\n",
- "\n",
- " datature for common test\n",
- "@pytest.fixture\n",
- "def common_data():\n",
- "return {\n",
- " 'iterations': 100,\n",
- " 'param1': 4,\n",
- " 'param2': 1\n",
- " }\n",
- "\n",
- "# Normal case tests\n",
- "rize(\"iterations, param1, param2, expected\", generate_test_data())\n",
- "cases(iterations, param1, param2, expected):\n",
- "1, param2) = calculate(iterations, param\n",
- "(result, expected, rel_tol=1e-9), f\"Expected {expected}, but got {result}\"\n",
- "\n",
- " cases and boundary values\n",
- "_cases():calculate_edge\n",
- "d inputsst with minimum vali\n",
- " 0) == 2.0 calculate(1, 1,\n",
- " \n",
- " # Test with very large iterations\n",
- "_result = calculate(10**8, 4, 1)\n",
- ", 0.6931471806, rel_tol=1e-9)lt\n",
- "\n",
- "# Invalid inputs and error conditions\n",
- "def test_calculate_invalid_inputs():\n",
- " with pytest.raises(ValueError):\n",
- "0, 4, 1) # iterations should be positive\n",
- " \n",
- "(ZeroDivisionError):es\n",
- "10, 1, 1) # This will cause division by zero\n",
- "\n",
- "TypeError):test.raises(\n",
- "1) # iterations should be an integer\n",
- "\n",
- "# Test with different combinations of parameters\n",
- "rize(\"iterations, param1, param2\", [\n",
- "), (100, 2, 2\n",
- " (1000, 3, 3),\n",
- "(10000, 5, 5),\n",
- " (100000, 10, 10)\n",
- "])\n",
- " param1, param2):e_parameter_combinations(iterations,\n",
- " calculate(iterations, param1, param2)\n",
- " assert isinstance(result, float)\n",
- " assert result > 0\n",
- "\n",
- " execution time\n",
- "common_data):ulate_execution_time(\n",
- " time.time()me =\n",
- " calculate(**common_data)\n",
- " end_time = time.time()\n",
- " execution_time = end_time - start_time\n",
- " f\"Execution took {execution_time} seconds, which is too long\"\n",
- "\n",
- " result precision\n",
- "data):st_calculate_precision(common_\n",
- "data)esult = calculate(**common_\n",
- "split('.')[1]) >= 10, \"Result should have at least 10 decimal places\"\n",
- "\n",
- "# Test with mocked time function\n",
- ".time')'time\n",
- "(mock_time, common_data):ocked_time\n",
- ", 0.5] # Simulate 0.5 seconds execution time\n",
- "_time = time.time()\n",
- " = calculate(**common_data)\n",
- "d_time = time.time()\n",
- " end_time - start_time == 0.5\n",
- "\n",
- "# Helper function to test monotonicity\n",
- "_monotonic(lst):\n",
- " <= lst[i+1] for i in range(len(lst)-1)) or all(lst[i] >= lst[i+1] for i in range(len(lst)-1))\n",
- "\n",
- " increasing iterationscity with\n",
- "def test_calculate_monotonicity():\n",
- " 1) for i in range(1, 6)]10**i, 4,\n",
- "), \"Results should be monotonic with increasing iterations\"\n",
- "\n",
- " Test with very small and very large parameters\n",
- ", param1, param2\", [rize(\"iterations\n",
- "(100, 1e-5, 1e-5),\n",
- ", 1e5)00, 1e5\n",
- "])\n",
- "_parameters(iterations, param1, param2):\n",
- "1, param2) = calculate(iterations, param\n",
- "result == float('inf') or result == float('-inf')), \"Result should not be infinity\"\n",
- "assert not isclose(result, 0, abs_tol=1e-10), \"Result should not be too close to zero\"\n",
- "\n",
- "```\n",
- "\n",
- " for the `calculate` function:range of scenarios\n",
- "\n",
- " with different inputs and expected outputs.\n",
- " and boundary values, including minimum valid inputs and very large iterations.\n",
- " Invalid inputs and error conditions, testing for expected exceptions.\n",
- " Different combinations of parameters to ensure the function works correctly for various inputs.\n",
- " to ensure the function performs within acceptable time limits.\n",
- " Precision test to verify the result has sufficient decimal places.\n",
- " A test with mocked time function to simulate and verify execution time measurement.\n",
- " if results are consistent with increasing iterations.\n",
- " with extreme parameters (very small and very large) to ensure numerical stability.\n",
- "\n",
- "rization, fixtures, and markers. It also includes necessary imports, helper functions, and a test data generator.\n",
- "\n",
- "d `test_your_module.py` in the same directory as your original code file (`your_module.py`). Then run `pytest test_your_module.py` from the command line.\n",
- "\n",
- " pytest (`pip install pytest`) before running the tests."
- ]
- }
- ],
+ "outputs": [],
"source": [
"stream_unit_test_claude(pi)"
]
},
{
"cell_type": "code",
- "execution_count": 40,
+ "execution_count": null,
"id": "f13b3a5b-366d-4b28-adda-977a313e6b4d",
"metadata": {},
"outputs": [],
@@ -741,7 +426,7 @@
},
{
"cell_type": "code",
- "execution_count": 67,
+ "execution_count": null,
"id": "e2efdb92-fc7a-4952-ab46-ae942cb996bf",
"metadata": {},
"outputs": [],
@@ -762,125 +447,27 @@
},
{
"cell_type": "code",
- "execution_count": 41,
+ "execution_count": null,
"id": "0a756193-fcba-43da-a981-203c10d36488",
"metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- ""
- ]
- },
- "execution_count": 41,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
+ "outputs": [],
"source": [
"stream_comment_model(code_qwen, CODE_QWEN_URL, pi)"
]
},
{
"cell_type": "code",
- "execution_count": 70,
+ "execution_count": null,
"id": "12ddcbf4-6286-47a8-847b-5be78e7aa995",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Here are the unit tests for the given Python code:\n",
- "\n",
- "```python\n",
- "import pytest\n",
- "import time\n",
- " unittest.mock import patch\n",
- "\n",
- "def calculate(iterations, param1, param2):\n",
- " result = 1.0\n",
- " for i in range(1, iterations+1):\n",
- " i * param1 - param2\n",
- "result -= (1/j)\n",
- " j = i * param1 + param2\n",
- "result += (1/j)\n",
- " return result\n",
- "\n",
- "@pytest.fixture\n",
- " mock_time():\n",
- "('time.time') as mock_time:\n",
- "yield mock_time\n",
- "\n",
- "_calculate_normal_inputs(mock_time):\n",
- "mock_time.return_value = 0\n",
- "result = calculate(100_000_000, 4, 1) * 4\n",
- "expected_result = 0.0\n",
- " == expected_result\n",
- "\n",
- "_calculate_edge_cases(mock_time):\n",
- " mock_time.return_value = 0\n",
- " calculate(0, 4, 1) * 4\n",
- " expected_result = 0.0\n",
- " result == expected_result\n",
- "\n",
- " = calculate(100_000_000, 0, 1) * 4\n",
- "expected_result = 0.0\n",
- " result == expected_result\n",
- "\n",
- " = calculate(100_000_000, 4, 0) * 4\n",
- "_result = 0.0\n",
- " assert result == expected_result\n",
- "\n",
- "def test_calculate_invalid_inputs(mock_time):\n",
- " mock_time.return_value = 0\n",
- ".raises(TypeError):\n",
- "calculate(100_000_000, 'a', 1) * 4\n",
- "with pytest.raises(TypeError):\n",
- "100_000_000, 4, 'b') * 4\n",
- ".raises(TypeError):\n",
- "calculate('a', 4, 1) * 4\n",
- "test.raises(TypeError):\n",
- "(100_000_000, 4, 1, 'c') * 4\n",
- "\n",
- "def test_calculate_different_combinations(mock_time):\n",
- " mock_time.return_value = 0\n",
- "result = calculate(100_000_000, 4, 1) * 4\n",
- " expected_result = 0.0\n",
- " result == expected_result\n",
- "\n",
- " = calculate(100_000_000, 4, -1) * 4\n",
- "expected_result = 0.0\n",
- " == expected_result\n",
- "\n",
- " calculate(100_000_000, -4, 1) * 4\n",
- "result = 0.0_\n",
- "assert result == expected_result\n",
- "\n",
- "result = calculate(100_000_000, -4, -1) * 4\n",
- " expected_result = 0.0\n",
- " result == expected_result\n",
- "\n",
- "def test_calculate_execution_time(mock_time):\n",
- "_time.return_value = 0\n",
- "_time = mock_time.return_value\n",
- "calculate(100_000_000, 4, 1) * 4\n",
- "end_time = mock_time.return_value\n",
- " expected_execution_time = 0.0\n",
- " assert (end_time - start_time) == expected_execution_time\n",
- "```\n",
- "\n",
- " covers all the scenarios mentioned in the problem description. It tests the function with normal inputs, edge cases, invalid inputs, different combinations of parameters, and checks the execution time.<|im_end|>"
- ]
- }
- ],
+ "outputs": [],
"source": [
"stream_unit_test_model(code_qwen, CODE_QWEN_URL, pi)"
]
},
{
"cell_type": "code",
- "execution_count": 46,
+ "execution_count": null,
"id": "321609ee-b64a-44fc-9090-39f87e1f8e0e",
"metadata": {},
"outputs": [],
@@ -900,7 +487,7 @@
},
{
"cell_type": "code",
- "execution_count": 69,
+ "execution_count": null,
"id": "d4c560c9-922d-4893-941f-42893373b1be",
"metadata": {},
"outputs": [],
@@ -920,7 +507,7 @@
},
{
"cell_type": "code",
- "execution_count": 35,
+ "execution_count": null,
"id": "f85bc777-bebe-436b-88cc-b9ecdb6306c0",
"metadata": {},
"outputs": [],
@@ -933,298 +520,10 @@
},
{
"cell_type": "code",
- "execution_count": 74,
+ "execution_count": null,
"id": "ee27cc91-81e6-42c8-ae3c-c04161229d8c",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "* Running on local URL: http://127.0.0.1:7881\n",
- "\n",
- "To create a public link, set `share=True` in `launch()`.\n"
- ]
- },
- {
- "data": {
- "text/html": [
- ""
- ],
- "text/plain": [
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "text/plain": []
- },
- "execution_count": 74,
- "metadata": {},
- "output_type": "execute_result"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Here are the unit tests for the given Python code:\n",
- "\n",
- "```python\n",
- "import pytest\n",
- "import time\n",
- " unittest.mock import patch\n",
- "\n",
- "def calculate(iterations, param1, param2):\n",
- " result = 1.0\n",
- " for i in range(1, iterations+1):\n",
- " i * param1 - param2\n",
- " result -= (1/j)\n",
- " i * param1 + param2\n",
- "result += (1/j)\n",
- " return result\n",
- "\n",
- "@pytest.fixture\n",
- " mock_time():\n",
- " with patch('time.time') as mock_time:\n",
- "ield mock_time\n",
- "\n",
- "calculate_normal_inputs(mock_time):\n",
- "time.return_value = 0\n",
- " calculate(100_000_000, 4, 1) * 4\n",
- "result = 0.0_\n",
- "assert result == expected_result\n",
- "\n",
- " test_calculate_edge_cases(mock_time):\n",
- "time.return_value = 0\n",
- " calculate(0, 4, 1) * 4\n",
- "_result = 0.0\n",
- " assert result == expected_result\n",
- "\n",
- " result = calculate(100_000_000, 0, 1) * 4\n",
- "result = 0.0_\n",
- "assert result == expected_result\n",
- "\n",
- "result = calculate(100_000_000, 4, 0) * 4\n",
- " expected_result = 0.0\n",
- "assert result == expected_result\n",
- "\n",
- " test_calculate_invalid_inputs(mock_time):\n",
- "_time.return_value = 0\n",
- "test.raises(TypeError):\n",
- " calculate(100_000_000, 'a', 1) * 4\n",
- "with pytest.raises(TypeError):\n",
- "ulate(100_000_000, 4, 'b') * 4\n",
- " pytest.raises(TypeError):\n",
- "ulate('a', 4, 1) * 4\n",
- "test.raises(TypeError):\n",
- " calculate(100_000_000, 4, 1, 'c') * 4\n",
- "\n",
- "_calculate_different_combinations(mock_time):\n",
- " mock_time.return_value = 0\n",
- " result = calculate(100_000_000, 4, 1) * 4\n",
- " expected_result = 0.0\n",
- " == expected_result\n",
- "\n",
- " calculate(100_000_000, 4, -1) * 4\n",
- "_result = 0.0\n",
- " assert result == expected_result\n",
- "\n",
- " result = calculate(100_000_000, -4, 1) * 4\n",
- " expected_result = 0.0\n",
- " result == expected_result\n",
- "\n",
- " calculate(100_000_000, -4, -1) * 4\n",
- "_result = 0.0\n",
- " assert result == expected_result\n",
- "\n",
- "def test_calculate_execution_time(mock_time):\n",
- "mock_time.return_value = 0\n",
- "start_time = mock_time.return_value\n",
- " calculate(100_000_000, 4, 1) * 4\n",
- " end_time = mock_time.return_value\n",
- " expected_execution_time = 0.0\n",
- " assert (end_time - start_time) == expected_execution_time\n",
- "```\n",
- "\n",
- " covers all the scenarios mentioned in the problem description. It tests the function with normal inputs, edge cases, invalid inputs, different combinations of parameters, and checks the execution time.<|im_end|>"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Traceback (most recent call last):\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\queueing.py\", line 625, in process_events\n",
- " response = await route_utils.call_process_api(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\route_utils.py\", line 322, in call_process_api\n",
- " output = await app.get_blocks().process_api(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 2047, in process_api\n",
- " result = await self.call_function(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 1606, in call_function\n",
- " prediction = await utils.async_iteration(iterator)\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 714, in async_iteration\n",
- " return await anext(iterator)\n",
- " ^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 708, in __anext__\n",
- " return await anyio.to_thread.run_sync(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\to_thread.py\", line 56, in run_sync\n",
- " return await get_async_backend().run_sync_in_worker_thread(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 2505, in run_sync_in_worker_thread\n",
- " return await future\n",
- " ^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 1005, in run\n",
- " result = context.run(func, *args)\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 691, in run_sync_iterator_async\n",
- " return next(iterator)\n",
- " ^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 852, in gen_wrapper\n",
- " response = next(iterator)\n",
- " ^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\AppData\\Local\\Temp\\ipykernel_27660\\2822054561.py\", line 10, in get_unit_test\n",
- " for stream_so_far in result:\n",
- "TypeError: 'NoneType' object is not iterable\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Here are the unit tests for the given Python code:\n",
- "\n",
- "```python\n",
- "import pytest\n",
- "import time\n",
- "est.mock import patch\n",
- "\n",
- "(iterations, param1, param2):\n",
- "result = 1.0\n",
- "for i in range(1, iterations+1):\n",
- "j = i * param1 - param2\n",
- " -= (1/j)esult\n",
- "j = i * param1 + param2\n",
- " += (1/j)esult\n",
- "return result\n",
- "\n",
- "pytest.fixture\n",
- "_time():\n",
- " with patch('time.time') as mock_time:\n",
- "ield mock_time\n",
- "\n",
- "calculate_normal_inputs(mock_time):\n",
- "time.return_value = 0\n",
- " calculate(100_000_000, 4, 1) * 4\n",
- "_result = 0.0\n",
- " assert result == expected_result\n",
- "\n",
- "def test_calculate_edge_cases(mock_time):\n",
- "mock_time.return_value = 0\n",
- "result = calculate(0, 4, 1) * 4\n",
- " expected_result = 0.0\n",
- " result == expected_result\n",
- "\n",
- " = calculate(100_000_000, 0, 1) * 4\n",
- "_result = 0.0\n",
- "assert result == expected_result\n",
- "\n",
- "result = calculate(100_000_000, 4, 0) * 4\n",
- " expected_result = 0.0\n",
- " result == expected_result\n",
- "\n",
- "_calculate_invalid_inputs(mock_time):\n",
- "time.return_value = 0\n",
- " with pytest.raises(TypeError):\n",
- "(100_000_000, 'a', 1) * 4\n",
- "ises(TypeError):ra\n",
- "ulate(100_000_000, 4, 'b') * 4\n",
- " pytest.raises(TypeError):\n",
- "ulate('a', 4, 1) * 4\n",
- " pytest.raises(TypeError):\n",
- "ulate(100_000_000, 4, 1, 'c') * 4\n",
- "\n",
- "calculate_different_combinations(mock_time):\n",
- " mock_time.return_value = 0\n",
- " result = calculate(100_000_000, 4, 1) * 4\n",
- " = 0.0pected_result\n",
- " result == expected_result\n",
- "\n",
- " = calculate(100_000_000, 4, -1) * 4\n",
- "expected_result = 0.0\n",
- " expected_resultt ==\n",
- "\n",
- " result = calculate(100_000_000, -4, 1) * 4\n",
- "result = 0.0_\n",
- " == expected_result\n",
- "\n",
- " calculate(100_000_000, -4, -1) * 4\n",
- " = 0.0pected_result\n",
- " result == expected_result\n",
- "\n",
- "def test_calculate_execution_time(mock_time):\n",
- "_time.return_value = 0\n",
- "_time = mock_time.return_value\n",
- "100_000_000, 4, 1) * 4\n",
- " end_time = mock_time.return_value\n",
- "_execution_time = 0.0\n",
- " (end_time - start_time) == expected_execution_time\n",
- "``\n",
- "\n",
- " suite covers all the scenarios mentioned in the problem description. It tests the function with normal inputs, edge cases, invalid inputs, different combinations of parameters, and checks the execution time.<|im_end|>"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Traceback (most recent call last):\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\queueing.py\", line 625, in process_events\n",
- " response = await route_utils.call_process_api(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\route_utils.py\", line 322, in call_process_api\n",
- " output = await app.get_blocks().process_api(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 2047, in process_api\n",
- " result = await self.call_function(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 1606, in call_function\n",
- " prediction = await utils.async_iteration(iterator)\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 714, in async_iteration\n",
- " return await anext(iterator)\n",
- " ^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 708, in __anext__\n",
- " return await anyio.to_thread.run_sync(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\to_thread.py\", line 56, in run_sync\n",
- " return await get_async_backend().run_sync_in_worker_thread(\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 2505, in run_sync_in_worker_thread\n",
- " return await future\n",
- " ^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 1005, in run\n",
- " result = context.run(func, *args)\n",
- " ^^^^^^^^^^^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 691, in run_sync_iterator_async\n",
- " return next(iterator)\n",
- " ^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\.conda\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 852, in gen_wrapper\n",
- " response = next(iterator)\n",
- " ^^^^^^^^^^^^^^\n",
- " File \"C:\\Users\\ebaba\\AppData\\Local\\Temp\\ipykernel_27660\\2822054561.py\", line 10, in get_unit_test\n",
- " for stream_so_far in result:\n",
- "TypeError: 'NoneType' object is not iterable\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"with gr.Blocks(css=css) as ui:\n",
" gr.Markdown(\"## Convert code from Python to C++\")\n",
@@ -1240,7 +539,7 @@
" \n",
" comment_button.click(comment_code, inputs=[python, model], outputs=[result])\n",
" unit_test_button.click(get_unit_test, inputs=[python, model], outputs=[result])\n",
- "ui.launch(inbrowser=True)"
+ "ui.launch(inbrowser=False)"
]
},
{
From c2e9f8a88d9714deec4697493478a4fa4ebe49f7 Mon Sep 17 00:00:00 2001
From: emmanuel
Date: Sun, 19 Jan 2025 20:29:30 +0100
Subject: [PATCH 22/61] update prompt
---
.../day5-homework.ipynb | 26 ++++++-------------
1 file changed, 8 insertions(+), 18 deletions(-)
diff --git a/week4/community-contributions/day5-homework.ipynb b/week4/community-contributions/day5-homework.ipynb
index c34be7b..7503266 100644
--- a/week4/community-contributions/day5-homework.ipynb
+++ b/week4/community-contributions/day5-homework.ipynb
@@ -1,22 +1,11 @@
{
"cells": [
{
- "cell_type": "code",
- "execution_count": 1,
- "id": "6d67dba5-38ec-459a-9132-4a56c6a814cd",
+ "cell_type": "markdown",
+ "id": "ff022957-2e81-4ea9-84d3-e52d5753e133",
"metadata": {},
- "outputs": [
- {
- "ename": "SyntaxError",
- "evalue": "invalid syntax (2447672335.py, line 1)",
- "output_type": "error",
- "traceback": [
- "\u001b[1;36m Cell \u001b[1;32mIn[1], line 1\u001b[1;36m\u001b[0m\n\u001b[1;33m Comment and Unit Test Generater\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
- ]
- }
- ],
"source": [
- "Comment and Unit Test Generater \n",
+ "### Comment and Unit Test Generater \n",
"\n",
"The requirement: \n",
"* use an LLM to generate docstring and comments for Python code\n",
@@ -164,7 +153,6 @@
" - All parameters with types and descriptions\n",
" - Return values with types\n",
" - Exceptions that may be raised\n",
- " - At least one usage example\n",
" - Any important notes or limitations\n",
" \n",
" 2. Strategic inline comments for:\n",
@@ -415,7 +403,7 @@
" messages = messages_for_comment(code)\n",
" text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n",
" client = InferenceClient(model_url, token=hf_token)\n",
- " stream = client.text_generation(text, stream=True, details=True, max_new_tokens=3000)\n",
+ " stream = client.text_generation(text, stream=True, details=True, max_new_tokens=5000)\n",
" result = \"\"\n",
" for r in stream:\n",
" #print(r.token.text, end = \"\")\n",
@@ -522,7 +510,9 @@
"cell_type": "code",
"execution_count": null,
"id": "ee27cc91-81e6-42c8-ae3c-c04161229d8c",
- "metadata": {},
+ "metadata": {
+ "scrolled": true
+ },
"outputs": [],
"source": [
"with gr.Blocks(css=css) as ui:\n",
@@ -539,7 +529,7 @@
" \n",
" comment_button.click(comment_code, inputs=[python, model], outputs=[result])\n",
" unit_test_button.click(get_unit_test, inputs=[python, model], outputs=[result])\n",
- "ui.launch(inbrowser=False)"
+ "ui.launch(inbrowser=True)"
]
},
{
From 21874c68e5ce94e0be0d34d162f1151f89f8ffbd Mon Sep 17 00:00:00 2001
From: Edward Donner
Date: Sun, 19 Jan 2025 22:35:01 -0500
Subject: [PATCH 23/61] Fixes with much thanks to student Wenjie T!
---
extras/trading/prototype_trader.ipynb | 2 +-
week1/troubleshooting.ipynb | 8 ++++++++
week6/day4.ipynb | 2 +-
week8/day5.ipynb | 3 ++-
week8/memory.json | 18 ------------------
week8/price_is_right_final.py | 1 +
6 files changed, 13 insertions(+), 21 deletions(-)
diff --git a/extras/trading/prototype_trader.ipynb b/extras/trading/prototype_trader.ipynb
index 8ec9d06..30358b9 100644
--- a/extras/trading/prototype_trader.ipynb
+++ b/extras/trading/prototype_trader.ipynb
@@ -346,7 +346,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week1/troubleshooting.ipynb b/week1/troubleshooting.ipynb
index 3e31359..c05a5a0 100644
--- a/week1/troubleshooting.ipynb
+++ b/week1/troubleshooting.ipynb
@@ -405,6 +405,14 @@
"from diagnostics import Diagnostics\n",
"Diagnostics().run()"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e1955b9a-d344-4782-b448-2770d0edd90c",
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
diff --git a/week6/day4.ipynb b/week6/day4.ipynb
index 964092d..d1c5500 100644
--- a/week6/day4.ipynb
+++ b/week6/day4.ipynb
@@ -398,7 +398,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week8/day5.ipynb b/week8/day5.ipynb
index 625232e..a1d8df2 100644
--- a/week8/day5.ipynb
+++ b/week8/day5.ipynb
@@ -88,6 +88,7 @@
"outputs": [],
"source": [
"agent_framework = DealAgentFramework()\n",
+ "agent_framework.init_agents_as_needed()\n",
"\n",
"with gr.Blocks(title=\"The Price is Right\", fill_width=True) as ui:\n",
"\n",
@@ -176,7 +177,7 @@
{
"cell_type": "code",
"execution_count": null,
- "id": "096397f9-1215-4814-ab4b-e32002ff4ceb",
+ "id": "f9dd0a27-7d46-4c9e-bbe4-a61c9c899c99",
"metadata": {},
"outputs": [],
"source": []
diff --git a/week8/memory.json b/week8/memory.json
index 8705760..2fb4bd1 100644
--- a/week8/memory.json
+++ b/week8/memory.json
@@ -16,23 +16,5 @@
},
"estimate": 930.8824204895075,
"discount": 225.88242048950747
- },
- {
- "deal": {
- "product_description": "The Insignia Class F30 Series NS-55F301NA25 is a 55\" 4K HDR UHD Smart TV with a native resolution of 3840x2160. Featuring HDR support, it enhances color and contrast for a more dynamic viewing experience. The TV integrates seamlessly with Amazon Fire TV, working with both Amazon Alexa and Google Home for voice control. It offers three HDMI ports for multiple device connections, making it a perfect entertainment hub for your living space.",
- "price": 200.0,
- "url": "https://www.dealnews.com/products/Insignia/Insignia-Class-F30-Series-NS-55-F301-NA25-55-4-K-HDR-LED-UHD-Smart-TV/467523.html?iref=rss-f1912"
- },
- "estimate": 669.1921927283588,
- "discount": 469.1921927283588
- },
- {
- "deal": {
- "product_description": "The Samsung 27-Cu. Ft. Mega Capacity 3-Door French Door Counter Depth Refrigerator combines style with spacious organization. This model features a dual auto ice maker, which ensures you always have ice on hand, and adjustable shelves that provide versatile storage options for your groceries. Designed with a sleek, fingerprint resistant finish, it not only looks modern but also simplifies cleaning. With its generous capacity, this refrigerator is perfect for large households or those who love to entertain.",
- "price": 1299.0,
- "url": "https://www.dealnews.com/products/Samsung/Samsung-27-Cu-Ft-Mega-Capacity-3-Door-French-Door-Counter-Depth-Refrigerator/454702.html?iref=rss-c196"
- },
- "estimate": 2081.647127763905,
- "discount": 782.6471277639048
}
]
\ No newline at end of file
diff --git a/week8/price_is_right_final.py b/week8/price_is_right_final.py
index cf80856..54c4997 100644
--- a/week8/price_is_right_final.py
+++ b/week8/price_is_right_final.py
@@ -45,6 +45,7 @@ class App:
def get_agent_framework(self):
if not self.agent_framework:
self.agent_framework = DealAgentFramework()
+ self.agent_framework.init_agents_as_needed()
return self.agent_framework
def run(self):
From 85a3a1a5fc2da8d54b48ae1536c9fe5106da641d Mon Sep 17 00:00:00 2001
From: Elena Shirokova
Date: Mon, 20 Jan 2025 10:30:19 +0100
Subject: [PATCH 24/61] fix the the output from executing tests
---
.../unit-tests-generator.ipynb | 60 +++++++++++--------
1 file changed, 34 insertions(+), 26 deletions(-)
diff --git a/week4/community-contributions/unit-tests-generator.ipynb b/week4/community-contributions/unit-tests-generator.ipynb
index 4825544..4aaf7d7 100644
--- a/week4/community-contributions/unit-tests-generator.ipynb
+++ b/week4/community-contributions/unit-tests-generator.ipynb
@@ -11,16 +11,16 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
- "!pipenv install pytest pytest-cov"
+ "#!pipenv install pytest pytest-cov"
]
},
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
@@ -63,7 +63,7 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
@@ -81,7 +81,7 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
@@ -102,10 +102,8 @@
"def execute_coverage_report(python_interpreter=sys.executable):\n",
" if not python_interpreter:\n",
" raise EnvironmentError(\"Python interpreter not found in the specified virtual environment.\")\n",
- " # test_code_path = Path(\"tests\")\n",
- " # command = [\"pytest\", \"-cov\",\"--capture=no\"]\n",
+ " \n",
" command = [\"coverage\", \"run\", \"-m\", \"pytest\"]\n",
- " # command =[\"pytest\", \"--cov=your_package\", \"--cov-report=term-missing\"]\n",
"\n",
" try:\n",
" result = subprocess.run(command, check=True, capture_output=True, text=True)\n",
@@ -117,15 +115,7 @@
" print(\"Output:\\n\", e.stdout)\n",
" print(\"Errors:\\n\", e.stderr)\n",
" # Extracting failed test information\n",
- " failed_tests = []\n",
- " for line in e.stdout.splitlines():\n",
- " if \"FAILED\" in line and \"::\" in line:\n",
- " failed_tests.append(line.strip())\n",
- " if failed_tests:\n",
- " print(\"Failed Tests:\")\n",
- " for test in failed_tests:\n",
- " print(test)\n",
- " return failed_tests\n",
+ " return e.stdout\n",
"\n",
"def save_unit_tests(code):\n",
"\n",
@@ -179,7 +169,8 @@
" print(\"Failed Tests:\")\n",
" for test in failed_tests:\n",
" print(test)\n",
- " return e.stderr\n",
+ " \n",
+ " return e.stdout\n",
" "
]
},
@@ -192,7 +183,7 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
@@ -201,15 +192,18 @@
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"def get_user_prompt(code):\n",
"\n",
" user_prompt = \"Write for a python code the unit test cases.\"\n",
- " user_prompt += \"Return unit tests cases using pytest library, do not create any custom imports; do not explain your work other than a few comments.\"\n",
- " user_prompt += \"Do not insert the function to be tested in the output before the tests. Validate both the case where the function is executed successfully and where it is expected to fail.\"\n",
+ " user_prompt += \"Return readable unit tests cases using pytest library, do not create any custom imports, don't forget to import errors if needed; do not explain your work other than a few comments.\"\n",
+ " user_prompt += \"The tests should include normal inputs, the inputs where the code is expected to fail, edge case and error handling.\"\n",
+ " user_prompt += \"Do not insert the function to be tested in the output before the tests.\"\n",
+ " \n",
+ "\n",
" user_prompt += code\n",
"\n",
" return user_prompt"
@@ -217,7 +211,7 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
@@ -298,7 +292,7 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
@@ -326,7 +320,7 @@
},
{
"cell_type": "code",
- "execution_count": 9,
+ "execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
@@ -349,7 +343,7 @@
},
{
"cell_type": "code",
- "execution_count": 10,
+ "execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
@@ -406,6 +400,20 @@
"\n",
"ui.launch(inbrowser=True)"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
From 743891d960a9924dcc6a71d729c5180fd489c5bf Mon Sep 17 00:00:00 2001
From: Barry Northern
Date: Mon, 20 Jan 2025 23:45:02 +0000
Subject: [PATCH 25/61] barry_northern: using Gemini SDK instead of Claude +
use Gemini's fit-for-purpose chat function
---
.../day1-conversation-with-gemini.ipynb | 616 ++++++++++++++++++
1 file changed, 616 insertions(+)
create mode 100644 week2/community-contributions/day1-conversation-with-gemini.ipynb
diff --git a/week2/community-contributions/day1-conversation-with-gemini.ipynb b/week2/community-contributions/day1-conversation-with-gemini.ipynb
new file mode 100644
index 0000000..26e5c62
--- /dev/null
+++ b/week2/community-contributions/day1-conversation-with-gemini.ipynb
@@ -0,0 +1,616 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "06cf3063-9f3e-4551-a0d5-f08d9cabb927",
+ "metadata": {},
+ "source": [
+ "# Welcome to Week 2!\n",
+ "\n",
+ "## Frontier Model APIs\n",
+ "\n",
+ "In Week 1, we used multiple Frontier LLMs through their Chat UI, and we connected with the OpenAI's API.\n",
+ "\n",
+ "Today we'll connect with the APIs for Anthropic and Google, as well as OpenAI."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2b268b6e-0ba4-461e-af86-74a41f4d681f",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Important Note - Please read me\n",
+ " I'm continually improving these labs, adding more examples and exercises.\n",
+ " At the start of each week, it's worth checking you have the latest code. \n",
+ " First do a git pull and merge your changes as needed. Any problems? Try asking ChatGPT to clarify how to merge - or contact me!
\n",
+ " After you've pulled the code, from the llm_engineering directory, in an Anaconda prompt (PC) or Terminal (Mac), run: \n",
+ " conda env update --f environment.yml \n",
+ " Or if you used virtualenv rather than Anaconda, then run this from your activated environment in a Powershell (PC) or Terminal (Mac): \n",
+ " pip install -r requirements.txt \n",
+ " Then restart the kernel (Kernel menu >> Restart Kernel and Clear Outputs Of All Cells) to pick up the changes.\n",
+ " \n",
+ " | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Reminder about the resources page\n",
+ " Here's a link to resources for the course. This includes links to all the slides. \n",
+ " https://edwarddonner.com/2024/11/13/llm-engineering-resources/ \n",
+ " Please keep this bookmarked, and I'll continue to add more useful links there over time.\n",
+ " \n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "85cfe275-4705-4d30-abea-643fbddf1db0",
+ "metadata": {},
+ "source": [
+ "## Setting up your keys\n",
+ "\n",
+ "If you haven't done so already, you could now create API keys for Anthropic and Google in addition to OpenAI.\n",
+ "\n",
+ "**Please note:** if you'd prefer to avoid extra API costs, feel free to skip setting up Anthopic and Google! You can see me do it, and focus on OpenAI for the course. You could also substitute Anthropic and/or Google for Ollama, using the exercise you did in week 1.\n",
+ "\n",
+ "For OpenAI, visit https://openai.com/api/ \n",
+ "For Anthropic, visit https://console.anthropic.com/ \n",
+ "For Google, visit https://ai.google.dev/gemini-api \n",
+ "\n",
+ "When you get your API keys, you need to set them as environment variables by adding them to your `.env` file.\n",
+ "\n",
+ "```\n",
+ "OPENAI_API_KEY=xxxx\n",
+ "ANTHROPIC_API_KEY=xxxx\n",
+ "GOOGLE_API_KEY=xxxx\n",
+ "```\n",
+ "\n",
+ "Afterwards, you may need to restart the Jupyter Lab Kernel (the Python process that sits behind this notebook) via the Kernel menu, and then rerun the cells from the top."
+ ]
+ },
+ {
+ "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": "f0a8ab2b-6134-4104-a1bc-c3cd7ea4cd36",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# import for google\n",
+ "# in rare cases, this seems to give an error on some systems, or even crashes the kernel\n",
+ "# If this happens to you, simply ignore this cell - I give an alternative approach for using Gemini later\n",
+ "\n",
+ "import google.generativeai"
+ ]
+ },
+ {
+ "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()\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",
+ "\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\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "797fe7b0-ad43-42d2-acf0-e4f309b112f0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Connect to OpenAI, Anthropic\n",
+ "\n",
+ "openai = OpenAI()\n",
+ "\n",
+ "claude = anthropic.Anthropic()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "425ed580-808d-429b-85b0-6cba50ca1d0c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This is the set up code for Gemini\n",
+ "# Having problems with Google Gemini setup? Then just ignore this cell; when we use Gemini, I'll give you an alternative that bypasses this library altogether\n",
+ "\n",
+ "google.generativeai.configure()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "42f77b59-2fb1-462a-b90d-78994e4cef33",
+ "metadata": {},
+ "source": [
+ "## Asking LLMs to tell a joke\n",
+ "\n",
+ "It turns out that LLMs don't do a great job of telling jokes! Let's compare a few models.\n",
+ "Later we will be putting LLMs to better use!\n",
+ "\n",
+ "### What information is included in the API\n",
+ "\n",
+ "Typically we'll pass to the API:\n",
+ "- The name of the model that should be used\n",
+ "- A system message that gives overall context for the role the LLM is playing\n",
+ "- A user message that provides the actual prompt\n",
+ "\n",
+ "There are other parameters that can be used, including **temperature** which is typically between 0 and 1; higher for more random output; lower for more focused and deterministic."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "378a0296-59a2-45c6-82eb-941344d3eeff",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_message = \"You are an assistant that is great at telling jokes\"\n",
+ "user_prompt = \"Tell a light-hearted joke for an audience of Data Scientists\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f4d56a0f-2a3d-484d-9344-0efa6862aff4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "prompts = [\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\"role\": \"user\", \"content\": user_prompt}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3b3879b6-9a55-4fed-a18c-1ea2edfaf397",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# GPT-3.5-Turbo\n",
+ "\n",
+ "completion = openai.chat.completions.create(model='gpt-3.5-turbo', messages=prompts)\n",
+ "print(completion.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3d2d6beb-1b81-466f-8ed1-40bf51e7adbf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# GPT-4o-mini\n",
+ "# Temperature setting controls creativity\n",
+ "\n",
+ "completion = openai.chat.completions.create(\n",
+ " model='gpt-4o-mini',\n",
+ " messages=prompts,\n",
+ " temperature=0.7\n",
+ ")\n",
+ "print(completion.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f1f54beb-823f-4301-98cb-8b9a49f4ce26",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# GPT-4o\n",
+ "\n",
+ "completion = openai.chat.completions.create(\n",
+ " model='gpt-4o',\n",
+ " messages=prompts,\n",
+ " temperature=0.4\n",
+ ")\n",
+ "print(completion.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1ecdb506-9f7c-4539-abae-0e78d7f31b76",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Claude 3.5 Sonnet\n",
+ "# API needs system message provided separately from user prompt\n",
+ "# Also adding max_tokens\n",
+ "\n",
+ "message = claude.messages.create(\n",
+ " model=\"claude-3-5-sonnet-20241022\",\n",
+ " max_tokens=200,\n",
+ " temperature=0.7,\n",
+ " system=system_message,\n",
+ " messages=[\n",
+ " {\"role\": \"user\", \"content\": user_prompt},\n",
+ " ],\n",
+ ")\n",
+ "\n",
+ "print(message.content[0].text)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "769c4017-4b3b-4e64-8da7-ef4dcbe3fd9f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Claude 3.5 Sonnet again\n",
+ "# Now let's add in streaming back results\n",
+ "\n",
+ "result = claude.messages.stream(\n",
+ " model=\"claude-3-5-sonnet-20241022\",\n",
+ " max_tokens=200,\n",
+ " temperature=0.7,\n",
+ " system=system_message,\n",
+ " messages=[\n",
+ " {\"role\": \"user\", \"content\": user_prompt},\n",
+ " ],\n",
+ ")\n",
+ "\n",
+ "with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " print(text, end=\"\", flush=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6df48ce5-70f8-4643-9a50-b0b5bfdb66ad",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# The API for Gemini has a slightly different structure.\n",
+ "# I've heard that on some PCs, this Gemini code causes the Kernel to crash.\n",
+ "# If that happens to you, please skip this cell and use the next cell instead - an alternative approach.\n",
+ "\n",
+ "gemini_client = google.generativeai.GenerativeModel(\n",
+ " model_name='gemini-1.5-flash',\n",
+ " system_instruction=system_message\n",
+ ")\n",
+ "response = gemini_client.generate_content(user_prompt)\n",
+ "print(response.text)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "49009a30-037d-41c8-b874-127f61c4aa3a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# As an alternative way to use Gemini that bypasses Google's python API library,\n",
+ "# Google has recently released new endpoints that means you can use Gemini via the client libraries for OpenAI!\n",
+ "\n",
+ "gemini_via_openai_client = OpenAI(\n",
+ " api_key=google_api_key, \n",
+ " base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\"\n",
+ ")\n",
+ "\n",
+ "response = gemini_via_openai_client.chat.completions.create(\n",
+ " model=\"gemini-1.5-flash\",\n",
+ " messages=prompts\n",
+ ")\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "83ddb483-4f57-4668-aeea-2aade3a9e573",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To be serious! GPT-4o-mini with the original question\n",
+ "\n",
+ "prompts = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a helpful assistant that responds in Markdown\"},\n",
+ " {\"role\": \"user\", \"content\": \"How do I decide if a business problem is suitable for an LLM solution? Please respond in Markdown.\"}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "749f50ab-8ccd-4502-a521-895c3f0808a2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Have it stream back results in markdown\n",
+ "\n",
+ "stream = openai.chat.completions.create(\n",
+ " model='gpt-4o',\n",
+ " messages=prompts,\n",
+ " temperature=0.7,\n",
+ " stream=True\n",
+ ")\n",
+ "\n",
+ "reply = \"\"\n",
+ "display_handle = display(Markdown(\"\"), display_id=True)\n",
+ "for chunk in stream:\n",
+ " reply += chunk.choices[0].delta.content or ''\n",
+ " reply = reply.replace(\"```\",\"\").replace(\"markdown\",\"\")\n",
+ " update_display(Markdown(reply), display_id=display_handle.display_id)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f6e09351-1fbe-422f-8b25-f50826ab4c5f",
+ "metadata": {},
+ "source": [
+ "## And now for some fun - an adversarial conversation between Chatbots..\n",
+ "\n",
+ "You're already familar with prompts being organized into lists like:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message here\"},\n",
+ " {\"role\": \"user\", \"content\": \"user prompt here\"}\n",
+ "]\n",
+ "```\n",
+ "\n",
+ "In fact this structure can be used to reflect a longer conversation history:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message here\"},\n",
+ " {\"role\": \"user\", \"content\": \"first user prompt here\"},\n",
+ " {\"role\": \"assistant\", \"content\": \"the assistant's response\"},\n",
+ " {\"role\": \"user\", \"content\": \"the new user prompt\"},\n",
+ "]\n",
+ "```\n",
+ "\n",
+ "And we can use this approach to engage in a longer interaction with history."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bcb54183-45d3-4d08-b5b6-55e380dfdf1b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's make a conversation between GPT-4o-mini and gemini-1.5-flash\n",
+ "# We're using cheap versions of models so the costs will be minimal\n",
+ "\n",
+ "gpt_model = \"gpt-4o-mini\"\n",
+ "gemini_model = \"gemini-1.5-flash\"\n",
+ "\n",
+ "gpt_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",
+ "gemini_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 = [\"Hi there\"]\n",
+ "gemini_messages = [\"Hi\"]"
+ ]
+ },
+ {
+ "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 in zip(gpt_messages, claude_messages):\n",
+ " messages.append({\"role\": \"assistant\", \"content\": gpt})\n",
+ " messages.append({\"role\": \"user\", \"content\": claude})\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": "302586ca-645d-41f1-9738-efd8e7581bcf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def call_gemini():\n",
+ " client = google.generativeai.GenerativeModel(\n",
+ " model_name=gemini_model,\n",
+ " system_instruction=gemini_system\n",
+ " )\n",
+ " messages = []\n",
+ " for gpt, gemini in zip(gpt_messages, gemini_messages):\n",
+ " messages.append({\"role\": \"user\", \"parts\": gpt})\n",
+ " messages.append({\"role\": \"model\", \"parts\": gemini})\n",
+ " last_message = messages.pop() \n",
+ " chat = client.start_chat(\n",
+ " history=messages\n",
+ " )\n",
+ " response = chat.send_message(last_message[\"parts\"])\n",
+ " return response.text"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4e322e1e-9a99-4488-a3bf-6d5562163553",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "call_gemini()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0275b97f-7f90-4696-bbf5-b6642bd53cbd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "gpt_messages = [\"Hi there\"]\n",
+ "gemini_messages = [\"Hi\"]\n",
+ "\n",
+ "print(f\"GPT:\\n{gpt_messages[0]}\\n\")\n",
+ "print(f\"Gemini:\\n{gemini_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",
+ " gemini_next = call_gemini()\n",
+ " print(f\"Gemini:\\n{gemini_next}\\n\")\n",
+ " gemini_messages.append(gemini_next)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1d10e705-db48-4290-9dc8-9efdb4e31323",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Before you continue\n",
+ " \n",
+ " Be sure you understand how the conversation above is working, and in particular how the messages list is being populated. Add print statements as needed. Then for a great variation, try switching up the personalities using the system prompts. Perhaps one can be pessimistic, and one optimistic? \n",
+ " \n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3637910d-2c6f-4f19-b1fb-2f916d23f9ac",
+ "metadata": {},
+ "source": [
+ "# More advanced exercises\n",
+ "\n",
+ "Try creating a 3-way, perhaps bringing Claude into the conversation!\n",
+ "\n",
+ "Try doing this yourself before you look at the solutions.\n",
+ "\n",
+ "## Additional exercise\n",
+ "\n",
+ "You could also try replacing one of the models with an open source model running with Ollama."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "446c81e3-b67e-4cd9-8113-bc3092b93063",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Business relevance\n",
+ " This structure of a conversation, as a list of messages, is fundamental to the way we build conversational AI assistants and how they are able to keep the context during a conversation. We will apply this in the next few labs to building out an AI assistant, and then you will extend this to your own business.\n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "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
+}
From 2e196555340495422b3d05bd7b38ea45e1d169fb Mon Sep 17 00:00:00 2001
From: Elena Shirokova
Date: Tue, 21 Jan 2025 10:33:17 +0100
Subject: [PATCH 26/61] enhance the prompt for unit testing
---
.../unit-tests-generator.ipynb | 40 ++++++++++++-------
1 file changed, 26 insertions(+), 14 deletions(-)
diff --git a/week4/community-contributions/unit-tests-generator.ipynb b/week4/community-contributions/unit-tests-generator.ipynb
index 4aaf7d7..9ff116a 100644
--- a/week4/community-contributions/unit-tests-generator.ipynb
+++ b/week4/community-contributions/unit-tests-generator.ipynb
@@ -198,12 +198,28 @@
"source": [
"def get_user_prompt(code):\n",
"\n",
- " user_prompt = \"Write for a python code the unit test cases.\"\n",
- " user_prompt += \"Return readable unit tests cases using pytest library, do not create any custom imports, don't forget to import errors if needed; do not explain your work other than a few comments.\"\n",
- " user_prompt += \"The tests should include normal inputs, the inputs where the code is expected to fail, edge case and error handling.\"\n",
- " user_prompt += \"Do not insert the function to be tested in the output before the tests.\"\n",
- " \n",
+ " user_prompt = \"\"\"Test include:\n",
+ "\n",
+ " - Valid inputs with expected results.\n",
+ " - Inputs that test the boundaries or limits of the function's behavior.\n",
+ " - Invalid inputs or scenarios where the function is expected to raise exceptions.\n",
+ "\n",
+ " Structure:\n",
+ "\n",
+ " - Begin with all necessary imports. \n",
+ " - Do not create custom imports. \n",
+ " - Do not insert in the response the function for the tests.\n",
+ " - Ensure proper error handling for tests that expect exceptions.\n",
+ " - Clearly name the test functions to indicate their purpose (e.g., test_function_name).\n",
+ "\n",
+ " Example Structure:\n",
+ "\n",
+ " - Use pytest.raises to validate exceptions.\n",
+ " - Use assertions to verify correct outputs for successful and edge cases.\n",
+ "\n",
+ " Documentation:\n",
"\n",
+ " - Add docstrings explaining what each test verifies.\"\"\"\n",
" user_prompt += code\n",
"\n",
" return user_prompt"
@@ -298,6 +314,8 @@
"source": [
"function_to_test = \"\"\"\n",
" def lengthOfLongestSubstring(s):\n",
+ " if not isinstance(s, str):\n",
+ " raise TypeError(\"Input must be a string\")\n",
" max_length = 0\n",
" substring = \"\"\n",
" start_idx = 0\n",
@@ -343,7 +361,7 @@
},
{
"cell_type": "code",
- "execution_count": 12,
+ "execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
@@ -398,16 +416,10 @@
" save_test_run.click(save_unit_tests, inputs=[unit_tests_out])\n",
"\n",
"\n",
- "ui.launch(inbrowser=True)"
+ "ui.launch(inbrowser=True)\n",
+ "# ui.launch()"
]
},
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- },
{
"cell_type": "code",
"execution_count": null,
From 651e8f6eb06abbfbd513d1966a8f79fbc9fdf05c Mon Sep 17 00:00:00 2001
From: Elena Shirokova
Date: Tue, 21 Jan 2025 10:36:25 +0100
Subject: [PATCH 27/61] add the notebook description
---
.../unit-tests-generator.ipynb | 24 +++++++++++++------
1 file changed, 17 insertions(+), 7 deletions(-)
diff --git a/week4/community-contributions/unit-tests-generator.ipynb b/week4/community-contributions/unit-tests-generator.ipynb
index 9ff116a..4076149 100644
--- a/week4/community-contributions/unit-tests-generator.ipynb
+++ b/week4/community-contributions/unit-tests-generator.ipynb
@@ -18,6 +18,23 @@
"#!pipenv install pytest pytest-cov"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Current flow:\n",
+ "\n",
+ "1. For a python code it generates the unit tests using `pytest` library. The dashboard supports tests execution along with a coverage report. If the unit tests are fine, there is an option to save them for future use. It can happen, especially with Ollama , the tests are having a typing error. In this case the code can be edited in the right window and executed afterwards. \n",
+ "\n",
+ "2. Supports 3 models: \n",
+ "\n",
+ "- gpt-4o-mini\n",
+ "- claude-3-5-sonnet-20240620\n",
+ "- llama3.2\n",
+ "\n",
+ "It is recommended though to use other models except Ollama, my tests showed the code returned from ollama required more supervision and editing. Some generated unit tests from ollama don't provide full coverage, but still it is a good starting point for building such a tool."
+ ]
+ },
{
"cell_type": "code",
"execution_count": 2,
@@ -419,13 +436,6 @@
"ui.launch(inbrowser=True)\n",
"# ui.launch()"
]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
}
],
"metadata": {
From 4087552ccd3d2a1baec69738f62dee0b7a63bda5 Mon Sep 17 00:00:00 2001
From: jasjyotsinghjaswal
Date: Tue, 21 Jan 2025 10:36:29 -0400
Subject: [PATCH 28/61] Rename oh_sheet_its_spark!!!!.ipynb to
oh_sheet_its_spark.ipynb
---
.../{oh_sheet_its_spark!!!!.ipynb => oh_sheet_its_spark.ipynb} | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename week2/community-contributions/{oh_sheet_its_spark!!!!.ipynb => oh_sheet_its_spark.ipynb} (100%)
diff --git a/week2/community-contributions/oh_sheet_its_spark!!!!.ipynb b/week2/community-contributions/oh_sheet_its_spark.ipynb
similarity index 100%
rename from week2/community-contributions/oh_sheet_its_spark!!!!.ipynb
rename to week2/community-contributions/oh_sheet_its_spark.ipynb
From d71a10e2acd43f9e5a4d7a8c5943575a24140732 Mon Sep 17 00:00:00 2001
From: Thomas Butman
Date: Tue, 21 Jan 2025 14:39:18 +0000
Subject: [PATCH 29/61] fix typo in day3.ipynb
---
week2/day3.ipynb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/week2/day3.ipynb b/week2/day3.ipynb
index 28e6896..3d3b8f8 100644
--- a/week2/day3.ipynb
+++ b/week2/day3.ipynb
@@ -184,7 +184,7 @@
"system_message = \"You are a helpful assistant in a clothes store. You should try to gently encourage \\\n",
"the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. \\\n",
"For example, if the customer says 'I'm looking to buy a hat', \\\n",
- "you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales evemt.'\\\n",
+ "you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales event.'\\\n",
"Encourage the customer to buy hats if they are unsure what to get.\""
]
},
From ba7851afd43df8b0d41208067161523eb10b9576 Mon Sep 17 00:00:00 2001
From: Junaid
Date: Thu, 23 Jan 2025 03:51:36 +0530
Subject: [PATCH 30/61] Added my day1 contribution to community-contributions
---
.../day1_analyze_CV_Write_cover_letter.ipynb | 356 ++++++++++++++++++
1 file changed, 356 insertions(+)
create mode 100644 week1/community-contributions/day1_analyze_CV_Write_cover_letter.ipynb
diff --git a/week1/community-contributions/day1_analyze_CV_Write_cover_letter.ipynb b/week1/community-contributions/day1_analyze_CV_Write_cover_letter.ipynb
new file mode 100644
index 0000000..242ea3c
--- /dev/null
+++ b/week1/community-contributions/day1_analyze_CV_Write_cover_letter.ipynb
@@ -0,0 +1,356 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "31d3c4a4-5442-4074-b812-42d60e0a0c04",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "#In this example we will fetch the job description by pasting the URL,then we upload CV. Only then ChatGPT will\n",
+ "#analyze CV against the fetched job description. If the CV is a good match then it will write a cover letter.\n",
+ "\n",
+ "#If \n",
+ " ##job posting url is fake/random text or \n",
+ " ##job posting is fake/random tex or \n",
+ " ##CV is fake/random text\n",
+ "#then ChatGPT will not analyze CV, it will give a generic response to enter the info correctly."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bc2eafe6-5255-4317-8ddd-a93695296043",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "pip install PyPDF2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cf45e9d5-4913-416c-9880-5be60a96c0e6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Imports\n",
+ "import os\n",
+ "import io\n",
+ "import time\n",
+ "import requests\n",
+ "import PyPDF2\n",
+ "from dotenv import load_dotenv\n",
+ "from IPython.display import Markdown, display\n",
+ "from bs4 import BeautifulSoup\n",
+ "from openai import OpenAI\n",
+ "from ipywidgets import Textarea, FileUpload, Button, VBox, HTML"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "af8fea69-60aa-430c-a16c-8757b487e07a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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": "daee94d2-f82b-43f0-95d1-15370eda1bc7",
+ "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 in this folder for full instructions"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0712dd1d-b6bc-41c6-84ec-d965f696f7aa",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"You are an assistant who analyzes user's CV against the job description \\\n",
+ " and provide a short summary if the user is fit for this job. If the user is fit for the job \\\n",
+ " write a cover letter for the user to apply for the job. Keep the cover letter professional, short, \\\n",
+ " and formal. \\\n",
+ " Important things to notice before analyzing CV:\\\n",
+ " 1. Always check if the CV is actually a CV or just random text\\\n",
+ " 2. Check if the job description fetched from the website is the job description or not\\\n",
+ " and ignore text related to navigation\\\n",
+ " 3. Also check the link of the job posting, if it actually resembles a job posting or is just random \\\n",
+ " fake website\\\n",
+ " 4. if any one of these two checks fails, do not analyze the CV against the Job description and give an\\\n",
+ " appropriate response as you think\\\n",
+ " 5. Always respond in Markdown.\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "70c972a6-8af6-4ff2-a338-6d7ba90e2045",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A class to represent a Webpage\n",
+ "# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\n",
+ " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
+ " irrelevant.decompose()\n",
+ " self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "426dfd9b-3446-4543-9819-63040abd9644",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "for_user_prompt = {\n",
+ " 'job_posting_url':'',\n",
+ " 'job_posting': '',\n",
+ " 'cv_text': ''\n",
+ "}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "79d9ccd6-f5fe-4ce8-982c-7235d2cf6a9f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create widgets - to create a box for the job posting text\n",
+ "job_posting_url_area = Textarea(\n",
+ " placeholder='Paste the URL of the job posting here, ONLY URL PLEASE',\n",
+ " description='Fetching job:',\n",
+ " disabled=False,\n",
+ " layout={'width': '800px', 'height': '50px'}\n",
+ ")\n",
+ "\n",
+ "status_job_posting = HTML(value=\"Status: Waiting for inputs...\")\n",
+ "\n",
+ "# Create Submit Buttons\n",
+ "fetch_job_posting_button = Button(description='Fetch Job Posting', button_style='primary')\n",
+ "\n",
+ "def fetch_job_posting_action(b):\n",
+ " for_user_prompt['job_posting_url'] = job_posting_url_area.value\n",
+ " if for_user_prompt['job_posting_url']:\n",
+ " ed = Website(for_user_prompt['job_posting_url'])\n",
+ " status_job_posting.value = \"Status: Job posting fetched successfully!\"\n",
+ " fetch_job_posting_button.button_style='success'\n",
+ " for_user_prompt['job_posting']=ed.text\n",
+ " else:\n",
+ " status_job_posting.value = \"Status: Please enter a job posting url before submitting.\"\n",
+ "\n",
+ "# Attach actions to buttons\n",
+ "fetch_job_posting_button.on_click(fetch_job_posting_action)\n",
+ "\n",
+ "# Layout\n",
+ "job_posting_box = VBox([job_posting_url_area, fetch_job_posting_button])\n",
+ "\n",
+ "# Display all widgets\n",
+ "display(VBox([\n",
+ " HTML(value=\"Input Job Posting Url
\"),\n",
+ " job_posting_box,\n",
+ " status_job_posting\n",
+ "]))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "58d42786-1580-4d3f-b44f-5c52250c2935",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Print fetched job description\n",
+ "\n",
+ "#print(for_user_prompt['job_posting'])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cd258dec-9b57-40ce-b37c-2627acbcb5af",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define file upload for CV\n",
+ "cv_upload = FileUpload(\n",
+ " accept='.pdf', # Only accept PDF files\n",
+ " multiple=False, # Only allow single file selection\n",
+ " description='Upload CV (PDF)'\n",
+ ")\n",
+ "\n",
+ "status = HTML(value=\"Status: Waiting for inputs...\")\n",
+ "\n",
+ "# Create Submit Buttons\n",
+ "submit_cv_button = Button(description='Submit CV', button_style='success')\n",
+ "\n",
+ "# Functions\n",
+ "def submit_cv_action(change):\n",
+ "\n",
+ " if not for_user_prompt['cv_text']:\n",
+ " status.value = \"Status: Please upload a CV before submitting.\"\n",
+ " \n",
+ " if cv_upload.value:\n",
+ " # Get the uploaded file\n",
+ " uploaded_file = cv_upload.value[0]\n",
+ " content = io.BytesIO(uploaded_file['content'])\n",
+ " \n",
+ " try:\n",
+ " pdf_reader = PyPDF2.PdfReader(content) \n",
+ " cv_text = \"\"\n",
+ " for page in pdf_reader.pages: \n",
+ " cv_text += page.extract_text() \n",
+ " \n",
+ " # Store CV text in for_user_prompt\n",
+ " for_user_prompt['cv_text'] = cv_text\n",
+ " status.value = \"Status: CV uploaded and processed successfully!\"\n",
+ " except Exception as e:\n",
+ " status.value = f\"Status: Error processing PDF: {str(e)}\"\n",
+ "\n",
+ " time.sleep(0.5) # Short pause between upload and submit messages to display both\n",
+ " \n",
+ " if for_user_prompt['cv_text']:\n",
+ " #print(\"CV Submitted:\")\n",
+ " #print(for_user_prompt['cv_text'])\n",
+ " status.value = \"Status: CV submitted successfully!\"\n",
+ " \n",
+ "\n",
+ "# Attach actions to buttons\n",
+ "submit_cv_button.on_click(submit_cv_action)\n",
+ "\n",
+ "# Layout\n",
+ "cv_buttons = VBox([submit_cv_button])\n",
+ "\n",
+ "# Display all widgets\n",
+ "display(VBox([\n",
+ " HTML(value=\"Import CV and submit
\"),\n",
+ " cv_upload,\n",
+ " cv_buttons,\n",
+ " status\n",
+ "]))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a7dd22a4-ca7b-4b8c-a328-6205cec689cb",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Prepare the user prompt that we will send to open ai (added URL for the context)\n",
+ "user_prompt = f\"\"\"\n",
+ "Job Posting: \n",
+ "{for_user_prompt['job_posting']}\n",
+ "\n",
+ "CV: \n",
+ "{for_user_prompt['cv_text']}\n",
+ "\n",
+ "Url:\n",
+ "{for_user_prompt['job_posting_url']}\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "82b71c1a-895a-48e7-a945-13e615bb0096",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define messages with system_prompt and user_prompt\n",
+ "def messages_for(system_prompt_input, user_prompt_input):\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": system_prompt_input},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_input}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "854dc42e-2bbd-493b-958f-c20484908300",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# And now: call the OpenAI API. \n",
+ "response = openai.chat.completions.create(\n",
+ " model = \"gpt-4o-mini\",\n",
+ " messages = messages_for(system_prompt, user_prompt)\n",
+ ")\n",
+ "\n",
+ "# Response is provided in Markdown and displayed accordingly\n",
+ "display(Markdown(response.choices[0].message.content))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "758d2cbe-0f80-4572-8724-7cba77f701dd",
+ "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
+}
From 252ea7595b2d6ab43e5ffe9afcef0afce0bdf408 Mon Sep 17 00:00:00 2001
From: Maksym Solomyanov
Date: Sat, 25 Jan 2025 14:43:52 +0100
Subject: [PATCH 31/61] Maksym's day 2 exercise
---
.../web-page-summarizer.ipynb | 131 ++++++++++++++++++
1 file changed, 131 insertions(+)
create mode 100644 week1/community-contributions/web-page-summarizer.ipynb
diff --git a/week1/community-contributions/web-page-summarizer.ipynb b/week1/community-contributions/web-page-summarizer.ipynb
new file mode 100644
index 0000000..5a63ca7
--- /dev/null
+++ b/week1/community-contributions/web-page-summarizer.ipynb
@@ -0,0 +1,131 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6418dce8-3ad0-4da9-81de-b3bf57956086",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import requests\n",
+ "from bs4 import BeautifulSoup\n",
+ "from IPython.display import Markdown, display"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "75b7849a-841b-4525-90b9-b9fd003516fb",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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",
+ " def __init__(self, url):\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\n",
+ " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
+ " irrelevant.decompose()\n",
+ " self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "45c07164-3276-47f3-8620-a5d0ca6a8d24",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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.\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b334629a-cf2a-49fa-b198-edd73493720f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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": "code",
+ "execution_count": null,
+ "id": "e4dd0855-302d-4423-9b8b-80c4bbb9ab31",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "website = Website(\"https://cnn.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "65c6cc43-a16a-4337-8c3d-4ab10ee0377a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_for(website)}]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "59799f7b-a244-4572-9296-34e4b87ba026",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import ollama\n",
+ "\n",
+ "MODEL = \"llama3.2\"\n",
+ "response = ollama.chat(model=MODEL, messages=messages)\n",
+ "print(response['message']['content'])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a0c03050-60d2-4165-9d8a-27eb57455704",
+ "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
+}
From b3941329c791374ed2cc20f00441ef69c176603d Mon Sep 17 00:00:00 2001
From: Debojit Kangsa Banik
Date: Sun, 26 Jan 2025 11:09:31 +0530
Subject: [PATCH 32/61] Added my contributions to community-contributions
---
...y1-debs_stock_summary_recommendation.ipynb | 141 ++++++++++++++++++
1 file changed, 141 insertions(+)
create mode 100644 week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
diff --git a/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
new file mode 100644
index 0000000..57b1c56
--- /dev/null
+++ b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
@@ -0,0 +1,141 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
+ "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",
+ "\n",
+ "# If you get an error running this cell, then please head over to the troubleshooting notebook!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
+ "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!\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c5e793b2-6775-426a-a139-4848291d0463",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A class to represent a Webpage\n",
+ "# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\n",
+ " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
+ " irrelevant.decompose()\n",
+ " self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7c7e0988-8f2d-4844-a847-eebec76b114a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "website = \"https://www.screener.in/company/CMSINFO/\"\n",
+ "biz = Website(website)\n",
+ "user_prompt = \"Give short summary of the business \" + biz.text +\" and recommend pros and cons of the business in bullet points alongwith recommendation to buy or sell\"\n",
+ "print(user_prompt)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "website = \"https://www.screener.in/company/CMSINFO/\"\n",
+ "biz = Website(website)\n",
+ "\n",
+ "system_prompt = \"You are an equity research analyst. Analyze the content of the website and give a summary of the business\"\n",
+ "user_prompt = \"Give short summary of the business \" + biz.text +\" and recommend pros and cons of the business in bullet points alongwith recommendation to buy or sell\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt}\n",
+ "]\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "# To give you a preview -- calling OpenAI with system and user messages:\n",
+ "\n",
+ "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "print(response.choices[0].message.content)\n"
+ ]
+ }
+ ],
+ "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
+}
From a02b68556539884519273307b68762b84bcaccde Mon Sep 17 00:00:00 2001
From: Debojit Kangsa Banik
Date: Sun, 26 Jan 2025 11:11:14 +0530
Subject: [PATCH 33/61] Added my contributions to community-contributions
---
...y1-debs_stock_summary_recommendation.ipynb | 1007 ++++++++++++++++-
1 file changed, 999 insertions(+), 8 deletions(-)
diff --git a/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
index 57b1c56..4a2a267 100644
--- a/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
+++ b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 1,
"id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
"metadata": {},
"outputs": [],
@@ -21,10 +21,18 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 2,
"id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "API key found and looks good so far!\n"
+ ]
+ }
+ ],
"source": [
"# Load environment variables in a file called .env\n",
"\n",
@@ -45,7 +53,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 3,
"id": "c5e793b2-6775-426a-a139-4848291d0463",
"metadata": {},
"outputs": [],
@@ -75,10 +83,973 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"id": "7c7e0988-8f2d-4844-a847-eebec76b114a",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Give short summary of the business Home\n",
+ "Screens\n",
+ "Tools\n",
+ "Login\n",
+ "Home\n",
+ "Screens\n",
+ "Tools\n",
+ "Create a stock screen\n",
+ "Run queries on 10 years of financial data\n",
+ "Premium features\n",
+ "Commodity Prices\n",
+ "See prices and trends of over 10,000 commodities\n",
+ "Search shareholders\n",
+ "See companies where a person holds over 1% of the shares\n",
+ "Latest Announcements\n",
+ "Browse, filter and set alerts for announcements.\n",
+ "Upgrade to premium\n",
+ "Login\n",
+ "Get free account\n",
+ "CMS Info Systems Ltd\n",
+ "Notebook\n",
+ "CMS Info Systems\n",
+ "Summary\n",
+ "Chart\n",
+ "Analysis\n",
+ "Peers\n",
+ "Quarters\n",
+ "Profit & Loss\n",
+ "Balance Sheet\n",
+ "Cash Flow\n",
+ "Ratios\n",
+ "Investors\n",
+ "Documents\n",
+ "Notebook\n",
+ "CMS Info Systems Ltd\n",
+ "₹ 431\n",
+ "-1.66%\n",
+ "24 Jan\n",
+ " \n",
+ " - close price\n",
+ "Export to Excel\n",
+ "Follow\n",
+ "cms.com\n",
+ "BSE:\n",
+ " 543441\n",
+ "NSE:\n",
+ " CMSINFO\n",
+ "About\n",
+ "CMS Info Systems Limited is India's largest cash management company in terms of the number of ATM points and retail pick-up points as of March 31, 2021. The company is engaged in installing, maintaining, and managing assets and technology solutions on an end-to-end outsourced basis for banks, financial institutions, organized retail and e-commerce companies in India.\n",
+ "Key Points\n",
+ "Leadership\n",
+ "[1]\n",
+ "Only Integrated Banking Solutions provider
\n",
+ "with end-to-end offerings.\n",
+ "1 across Cash Logistics, AIoT in Banking and Algo MVS.
\n",
+ "The company services leading banks like\n",
+ "SBI, HDFC, ICICI & Axis.\n",
+ "Read More\n",
+ "Website\n",
+ "BSE\n",
+ "NSE\n",
+ "Market Cap\n",
+ "₹\n",
+ "7,041\n",
+ "Cr.\n",
+ "Current Price\n",
+ "₹\n",
+ "431\n",
+ "High / Low\n",
+ "₹\n",
+ "616\n",
+ "/\n",
+ "355\n",
+ "Stock P/E\n",
+ "18.8\n",
+ "Book Value\n",
+ "₹\n",
+ "124\n",
+ "Dividend Yield\n",
+ "1.33\n",
+ "%\n",
+ "ROCE\n",
+ "27.5\n",
+ "%\n",
+ "ROE\n",
+ "20.5\n",
+ "%\n",
+ "Face Value\n",
+ "₹\n",
+ "10.0\n",
+ "Add ratio to table\n",
+ "Edit ratios\n",
+ "1M\n",
+ "6M\n",
+ "1Yr\n",
+ "3Yr\n",
+ "5Yr\n",
+ "10Yr\n",
+ "Max\n",
+ "Price\n",
+ "PE Ratio\n",
+ "Hidden\n",
+ "More\n",
+ "Sales & Margin\n",
+ "EV / EBITDA\n",
+ "Price to Book\n",
+ "Market Cap / Sales\n",
+ "Alerts\n",
+ "Pros\n",
+ "Company is almost debt free.\n",
+ "Company has delivered good profit growth of 30.7% CAGR over last 5 years\n",
+ "Company has been maintaining a healthy dividend payout of 23.7%\n",
+ "Cons\n",
+ "*\n",
+ "The pros and cons are machine generated.\n",
+ "Pros / cons are based on a checklist to highlight important points. Please exercise caution and do your own analysis.\n",
+ "Peer comparison\n",
+ "Sector:\n",
+ "Miscellaneous\n",
+ "Industry:\n",
+ "Miscellaneous\n",
+ "Part of\n",
+ "BSE Services\n",
+ "BSE Allcap\n",
+ "BSE SmallCap\n",
+ "Nifty Total Market\n",
+ "Nifty Microcap 250\n",
+ "Edit\n",
+ "Columns\n",
+ "Loading peers table ...\n",
+ "Detailed Comparison with:\n",
+ "Quarterly Results\n",
+ "Standalone Figures in Rs. Crores\n",
+ " /\n",
+ "View Consolidated\n",
+ "Sep 2021\n",
+ "Dec 2021\n",
+ "Mar 2022\n",
+ "Jun 2022\n",
+ "Sep 2022\n",
+ "Dec 2022\n",
+ "Mar 2023\n",
+ "Jun 2023\n",
+ "Sep 2023\n",
+ "Dec 2023\n",
+ "Mar 2024\n",
+ "Jun 2024\n",
+ "Sep 2024\n",
+ "Sales\n",
+ "+\n",
+ "326\n",
+ "354\n",
+ "399\n",
+ "399\n",
+ "417\n",
+ "438\n",
+ "449\n",
+ "457\n",
+ "487\n",
+ "523\n",
+ "581\n",
+ "553\n",
+ "577\n",
+ "Expenses\n",
+ "+\n",
+ "237\n",
+ "252\n",
+ "294\n",
+ "292\n",
+ "302\n",
+ "318\n",
+ "310\n",
+ "322\n",
+ "359\n",
+ "394\n",
+ "432\n",
+ "412\n",
+ "433\n",
+ "Operating Profit\n",
+ "89\n",
+ "102\n",
+ "105\n",
+ "107\n",
+ "115\n",
+ "120\n",
+ "139\n",
+ "134\n",
+ "128\n",
+ "129\n",
+ "148\n",
+ "141\n",
+ "143\n",
+ "OPM %\n",
+ "27%\n",
+ "29%\n",
+ "26%\n",
+ "27%\n",
+ "28%\n",
+ "27%\n",
+ "31%\n",
+ "29%\n",
+ "26%\n",
+ "25%\n",
+ "26%\n",
+ "25%\n",
+ "25%\n",
+ "Other Income\n",
+ "+\n",
+ "1\n",
+ "9\n",
+ "2\n",
+ "17\n",
+ "2\n",
+ "4\n",
+ "4\n",
+ "6\n",
+ "6\n",
+ "31\n",
+ "34\n",
+ "10\n",
+ "11\n",
+ "Interest\n",
+ "4\n",
+ "3\n",
+ "4\n",
+ "4\n",
+ "5\n",
+ "5\n",
+ "5\n",
+ "4\n",
+ "4\n",
+ "4\n",
+ "4\n",
+ "4\n",
+ "4\n",
+ "Depreciation\n",
+ "21\n",
+ "21\n",
+ "26\n",
+ "28\n",
+ "32\n",
+ "31\n",
+ "33\n",
+ "34\n",
+ "34\n",
+ "36\n",
+ "38\n",
+ "37\n",
+ "38\n",
+ "Profit before tax\n",
+ "65\n",
+ "87\n",
+ "76\n",
+ "91\n",
+ "80\n",
+ "89\n",
+ "105\n",
+ "102\n",
+ "96\n",
+ "121\n",
+ "141\n",
+ "110\n",
+ "113\n",
+ "Tax %\n",
+ "24%\n",
+ "24%\n",
+ "27%\n",
+ "21%\n",
+ "26%\n",
+ "25%\n",
+ "26%\n",
+ "26%\n",
+ "26%\n",
+ "20%\n",
+ "21%\n",
+ "25%\n",
+ "26%\n",
+ "Net Profit\n",
+ "+\n",
+ "49\n",
+ "66\n",
+ "56\n",
+ "72\n",
+ "59\n",
+ "67\n",
+ "77\n",
+ "75\n",
+ "71\n",
+ "96\n",
+ "111\n",
+ "82\n",
+ "84\n",
+ "EPS in Rs\n",
+ "3.31\n",
+ "4.48\n",
+ "3.64\n",
+ "4.68\n",
+ "3.86\n",
+ "4.33\n",
+ "5.01\n",
+ "4.88\n",
+ "4.55\n",
+ "6.16\n",
+ "6.84\n",
+ "5.03\n",
+ "5.15\n",
+ "Raw PDF\n",
+ "Profit & Loss\n",
+ "Standalone Figures in Rs. Crores\n",
+ " /\n",
+ "View Consolidated\n",
+ "Related Party\n",
+ "Mar 2017\n",
+ "Mar 2018\n",
+ "Mar 2019\n",
+ "Mar 2020\n",
+ "Mar 2021\n",
+ "Mar 2022\n",
+ "Mar 2023\n",
+ "Mar 2024\n",
+ "TTM\n",
+ "Sales\n",
+ "+\n",
+ "783\n",
+ "742\n",
+ "903\n",
+ "1,162\n",
+ "1,131\n",
+ "1,408\n",
+ "1,704\n",
+ "2,047\n",
+ "2,233\n",
+ "Expenses\n",
+ "+\n",
+ "649\n",
+ "620\n",
+ "755\n",
+ "932\n",
+ "869\n",
+ "1,035\n",
+ "1,222\n",
+ "1,507\n",
+ "1,671\n",
+ "Operating Profit\n",
+ "134\n",
+ "122\n",
+ "148\n",
+ "230\n",
+ "262\n",
+ "373\n",
+ "482\n",
+ "539\n",
+ "562\n",
+ "OPM %\n",
+ "17%\n",
+ "16%\n",
+ "16%\n",
+ "20%\n",
+ "23%\n",
+ "26%\n",
+ "28%\n",
+ "26%\n",
+ "25%\n",
+ "Other Income\n",
+ "+\n",
+ "7\n",
+ "15\n",
+ "18\n",
+ "6\n",
+ "14\n",
+ "13\n",
+ "27\n",
+ "78\n",
+ "86\n",
+ "Interest\n",
+ "5\n",
+ "1\n",
+ "0\n",
+ "7\n",
+ "8\n",
+ "14\n",
+ "19\n",
+ "16\n",
+ "15\n",
+ "Depreciation\n",
+ "21\n",
+ "21\n",
+ "26\n",
+ "48\n",
+ "58\n",
+ "88\n",
+ "124\n",
+ "142\n",
+ "148\n",
+ "Profit before tax\n",
+ "115\n",
+ "116\n",
+ "140\n",
+ "181\n",
+ "211\n",
+ "285\n",
+ "365\n",
+ "459\n",
+ "484\n",
+ "Tax %\n",
+ "35%\n",
+ "34%\n",
+ "35%\n",
+ "30%\n",
+ "28%\n",
+ "25%\n",
+ "25%\n",
+ "23%\n",
+ "Net Profit\n",
+ "+\n",
+ "75\n",
+ "76\n",
+ "91\n",
+ "128\n",
+ "152\n",
+ "213\n",
+ "275\n",
+ "354\n",
+ "374\n",
+ "EPS in Rs\n",
+ "5.04\n",
+ "5.15\n",
+ "6.16\n",
+ "8.63\n",
+ "10.25\n",
+ "13.94\n",
+ "17.84\n",
+ "21.76\n",
+ "23.18\n",
+ "Dividend Payout %\n",
+ "0%\n",
+ "0%\n",
+ "0%\n",
+ "21%\n",
+ "15%\n",
+ "18%\n",
+ "27%\n",
+ "26%\n",
+ "Compounded Sales Growth\n",
+ "10 Years:\n",
+ "%\n",
+ "5 Years:\n",
+ "18%\n",
+ "3 Years:\n",
+ "22%\n",
+ "TTM:\n",
+ "22%\n",
+ "Compounded Profit Growth\n",
+ "10 Years:\n",
+ "%\n",
+ "5 Years:\n",
+ "31%\n",
+ "3 Years:\n",
+ "32%\n",
+ "TTM:\n",
+ "29%\n",
+ "Stock Price CAGR\n",
+ "10 Years:\n",
+ "%\n",
+ "5 Years:\n",
+ "%\n",
+ "3 Years:\n",
+ "16%\n",
+ "1 Year:\n",
+ "11%\n",
+ "Return on Equity\n",
+ "10 Years:\n",
+ "%\n",
+ "5 Years:\n",
+ "19%\n",
+ "3 Years:\n",
+ "20%\n",
+ "Last Year:\n",
+ "21%\n",
+ "Balance Sheet\n",
+ "Standalone Figures in Rs. Crores\n",
+ " /\n",
+ "View Consolidated\n",
+ "Corporate actions\n",
+ "Mar 2017\n",
+ "Mar 2018\n",
+ "Mar 2019\n",
+ "Mar 2020\n",
+ "Mar 2021\n",
+ "Mar 2022\n",
+ "Mar 2023\n",
+ "Mar 2024\n",
+ "Sep 2024\n",
+ "Equity Capital\n",
+ "148\n",
+ "148\n",
+ "148\n",
+ "148\n",
+ "148\n",
+ "153\n",
+ "154\n",
+ "163\n",
+ "163\n",
+ "Reserves\n",
+ "413\n",
+ "522\n",
+ "589\n",
+ "686\n",
+ "803\n",
+ "1,059\n",
+ "1,342\n",
+ "1,726\n",
+ "1,866\n",
+ "Borrowings\n",
+ "+\n",
+ "7\n",
+ "0\n",
+ "0\n",
+ "0\n",
+ "0\n",
+ "0\n",
+ "0\n",
+ "0\n",
+ "181\n",
+ "Other Liabilities\n",
+ "+\n",
+ "161\n",
+ "171\n",
+ "197\n",
+ "434\n",
+ "580\n",
+ "549\n",
+ "500\n",
+ "673\n",
+ "533\n",
+ "Total Liabilities\n",
+ "729\n",
+ "842\n",
+ "934\n",
+ "1,268\n",
+ "1,532\n",
+ "1,761\n",
+ "1,997\n",
+ "2,562\n",
+ "2,743\n",
+ "Fixed Assets\n",
+ "+\n",
+ "162\n",
+ "162\n",
+ "204\n",
+ "328\n",
+ "440\n",
+ "637\n",
+ "753\n",
+ "727\n",
+ "711\n",
+ "CWIP\n",
+ "1\n",
+ "0\n",
+ "3\n",
+ "4\n",
+ "23\n",
+ "42\n",
+ "20\n",
+ "18\n",
+ "71\n",
+ "Investments\n",
+ "143\n",
+ "215\n",
+ "195\n",
+ "240\n",
+ "281\n",
+ "266\n",
+ "426\n",
+ "613\n",
+ "562\n",
+ "Other Assets\n",
+ "+\n",
+ "422\n",
+ "464\n",
+ "532\n",
+ "696\n",
+ "787\n",
+ "815\n",
+ "798\n",
+ "1,205\n",
+ "1,400\n",
+ "Total Assets\n",
+ "729\n",
+ "842\n",
+ "934\n",
+ "1,268\n",
+ "1,532\n",
+ "1,761\n",
+ "1,997\n",
+ "2,562\n",
+ "2,743\n",
+ "Cash Flows\n",
+ "Standalone Figures in Rs. Crores\n",
+ " /\n",
+ "View Consolidated\n",
+ "Mar 2017\n",
+ "Mar 2018\n",
+ "Mar 2019\n",
+ "Mar 2020\n",
+ "Mar 2021\n",
+ "Mar 2022\n",
+ "Mar 2023\n",
+ "Mar 2024\n",
+ "Cash from Operating Activity\n",
+ "+\n",
+ "121\n",
+ "150\n",
+ "74\n",
+ "204\n",
+ "100\n",
+ "219\n",
+ "382\n",
+ "385\n",
+ "Cash from Investing Activity\n",
+ "+\n",
+ "-65\n",
+ "-91\n",
+ "5\n",
+ "-106\n",
+ "-90\n",
+ "-284\n",
+ "-323\n",
+ "-236\n",
+ "Cash from Financing Activity\n",
+ "+\n",
+ "-57\n",
+ "-5\n",
+ "-29\n",
+ "-56\n",
+ "-60\n",
+ "2\n",
+ "-51\n",
+ "-51\n",
+ "Net Cash Flow\n",
+ "-2\n",
+ "55\n",
+ "51\n",
+ "42\n",
+ "-50\n",
+ "-63\n",
+ "9\n",
+ "98\n",
+ "Ratios\n",
+ "Standalone Figures in Rs. Crores\n",
+ " /\n",
+ "View Consolidated\n",
+ "Mar 2017\n",
+ "Mar 2018\n",
+ "Mar 2019\n",
+ "Mar 2020\n",
+ "Mar 2021\n",
+ "Mar 2022\n",
+ "Mar 2023\n",
+ "Mar 2024\n",
+ "Debtor Days\n",
+ "57\n",
+ "56\n",
+ "54\n",
+ "70\n",
+ "137\n",
+ "111\n",
+ "97\n",
+ "118\n",
+ "Inventory Days\n",
+ "49\n",
+ "212\n",
+ "169\n",
+ "82\n",
+ "182\n",
+ "149\n",
+ "233\n",
+ "238\n",
+ "Days Payable\n",
+ "329\n",
+ "603\n",
+ "318\n",
+ "363\n",
+ "642\n",
+ "610\n",
+ "763\n",
+ "806\n",
+ "Cash Conversion Cycle\n",
+ "-223\n",
+ "-335\n",
+ "-95\n",
+ "-211\n",
+ "-324\n",
+ "-349\n",
+ "-433\n",
+ "-450\n",
+ "Working Capital Days\n",
+ "63\n",
+ "49\n",
+ "49\n",
+ "21\n",
+ "35\n",
+ "60\n",
+ "57\n",
+ "58\n",
+ "ROCE %\n",
+ "19%\n",
+ "20%\n",
+ "24%\n",
+ "24%\n",
+ "28%\n",
+ "28%\n",
+ "28%\n",
+ "Shareholding Pattern\n",
+ "Numbers in percentages\n",
+ "Quarterly\n",
+ "Yearly\n",
+ "Trades\n",
+ "Mar 2022\n",
+ "Jun 2022\n",
+ "Sep 2022\n",
+ "Dec 2022\n",
+ "Mar 2023\n",
+ "Jun 2023\n",
+ "Sep 2023\n",
+ "Dec 2023\n",
+ "Mar 2024\n",
+ "Jun 2024\n",
+ "Sep 2024\n",
+ "Dec 2024\n",
+ "Promoters\n",
+ "+\n",
+ "63.38%\n",
+ "63.16%\n",
+ "63.01%\n",
+ "60.98%\n",
+ "60.24%\n",
+ "46.48%\n",
+ "26.69%\n",
+ "26.69%\n",
+ "0.00%\n",
+ "0.00%\n",
+ "0.00%\n",
+ "0.00%\n",
+ "FIIs\n",
+ "+\n",
+ "9.54%\n",
+ "10.40%\n",
+ "10.61%\n",
+ "12.46%\n",
+ "13.12%\n",
+ "15.27%\n",
+ "23.76%\n",
+ "23.76%\n",
+ "36.34%\n",
+ "40.21%\n",
+ "39.99%\n",
+ "37.95%\n",
+ "DIIs\n",
+ "+\n",
+ "11.09%\n",
+ "11.65%\n",
+ "12.09%\n",
+ "12.14%\n",
+ "12.57%\n",
+ "20.96%\n",
+ "23.98%\n",
+ "23.43%\n",
+ "29.01%\n",
+ "28.40%\n",
+ "26.66%\n",
+ "27.03%\n",
+ "Public\n",
+ "+\n",
+ "15.99%\n",
+ "14.78%\n",
+ "14.30%\n",
+ "14.43%\n",
+ "14.04%\n",
+ "17.27%\n",
+ "25.56%\n",
+ "26.13%\n",
+ "34.65%\n",
+ "31.40%\n",
+ "33.35%\n",
+ "35.01%\n",
+ "No. of Shareholders\n",
+ "1,43,091\n",
+ "1,30,634\n",
+ "1,18,270\n",
+ "1,09,201\n",
+ "1,14,003\n",
+ "1,20,804\n",
+ "1,43,365\n",
+ "1,54,547\n",
+ "1,68,942\n",
+ "1,60,764\n",
+ "1,77,142\n",
+ "1,74,847\n",
+ "Mar 2022\n",
+ "Mar 2023\n",
+ "Mar 2024\n",
+ "Dec 2024\n",
+ "Promoters\n",
+ "+\n",
+ "63.38%\n",
+ "60.24%\n",
+ "0.00%\n",
+ "0.00%\n",
+ "FIIs\n",
+ "+\n",
+ "9.54%\n",
+ "13.12%\n",
+ "36.34%\n",
+ "37.95%\n",
+ "DIIs\n",
+ "+\n",
+ "11.09%\n",
+ "12.57%\n",
+ "29.01%\n",
+ "27.03%\n",
+ "Public\n",
+ "+\n",
+ "15.99%\n",
+ "14.04%\n",
+ "34.65%\n",
+ "35.01%\n",
+ "No. of Shareholders\n",
+ "1,43,091\n",
+ "1,14,003\n",
+ "1,68,942\n",
+ "1,74,847\n",
+ "* The classifications might have changed from Sep'2022 onwards.\n",
+ "The new XBRL format added more details from Sep'22 onwards.\n",
+ "Classifications such as banks and foreign portfolio investors were not available earlier. The sudden changes in FII or DII can be because of these changes.\n",
+ "Click on the line-items to see the names of individual entities.\n",
+ "Documents\n",
+ "Announcements\n",
+ "Recent\n",
+ "Important\n",
+ "Search\n",
+ "All\n",
+ "Disclosures under Reg. 29(1) of SEBI (SAST) Regulations, 2011\n",
+ "14h\n",
+ "Announcement under Regulation 30 (LODR)-Newspaper Publication\n",
+ "18 Jan - Newspaper publications for Postal Ballot Notice dated 16th January, 2025\n",
+ "Shareholder Meeting / Postal Ballot-Notice of Postal Ballot\n",
+ "17 Jan - Postal ballot notice for appointment of Independent Director.\n",
+ "Change In The Name Of Registrar And Share Transfer Agent.\n",
+ "2 Jan - Change of name of Registrar and Share Transfer Agent.\n",
+ "Closure of Trading Window\n",
+ "30 Dec\n",
+ "Annual reports\n",
+ "Financial Year 2024\n",
+ "from bse\n",
+ "Financial Year 2023\n",
+ "from bse\n",
+ "Financial Year 2022\n",
+ "from bse\n",
+ "Financial Year 2022\n",
+ "from nse\n",
+ "DRHP\n",
+ "Credit ratings\n",
+ "Rating update\n",
+ "25 Jan 2024 from icra\n",
+ "Rating update\n",
+ "22 Mar 2023 from icra\n",
+ "Rating update\n",
+ "26 Sep 2022 from icra\n",
+ "Rating update\n",
+ "15 Jul 2021 from icra\n",
+ "Rating update\n",
+ "18 Feb 2020 from icra\n",
+ "Rating update\n",
+ "8 Jan 2019 from icra\n",
+ "Concalls\n",
+ "Add Missing\n",
+ "Oct 2024\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "REC\n",
+ "Jul 2024\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "REC\n",
+ "May 2024\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "REC\n",
+ "Jan 2024\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "Oct 2023\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "Jul 2023\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "May 2023\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "REC\n",
+ "Feb 2023\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "Nov 2022\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "Aug 2022\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "May 2022\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "Feb 2022\n",
+ "Transcript\n",
+ "Notes\n",
+ "PPT\n",
+ "Stock analysis and screening tool\n",
+ "Mittal Analytics Private Ltd © 2009-2024\n",
+ "Made with\n",
+ "in India.\n",
+ "Data provided by C-MOTS Internet Technologies Pvt Ltd\n",
+ "Terms\n",
+ "&\n",
+ "Privacy\n",
+ ".\n",
+ "Product\n",
+ "Premium\n",
+ "What's new?\n",
+ "Learn\n",
+ "Install\n",
+ "Team\n",
+ "About us\n",
+ "Support\n",
+ "Theme\n",
+ "Light\n",
+ "Dark\n",
+ "Auto\n",
+ "Mittal Analytics Private Ltd © 2009-2024\n",
+ "Data provided by C-MOTS Internet Technologies Pvt Ltd\n",
+ "Terms\n",
+ "&\n",
+ "Privacy\n",
+ ". and recommend pros and cons of the business in bullet points alongwith recommendation to buy or sell\n"
+ ]
+ }
+ ],
"source": [
"website = \"https://www.screener.in/company/CMSINFO/\"\n",
"biz = Website(website)\n",
@@ -88,10 +1059,22 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 5,
"id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "ename": "NameError",
+ "evalue": "name 'openai' is not defined",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[5], line 18\u001b[0m\n\u001b[0;32m 10\u001b[0m messages \u001b[38;5;241m=\u001b[39m [\n\u001b[0;32m 11\u001b[0m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124msystem\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: system_prompt},\n\u001b[0;32m 12\u001b[0m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: user_prompt}\n\u001b[0;32m 13\u001b[0m ]\n\u001b[0;32m 14\u001b[0m \u001b[38;5;66;03m# Step 3: Call OpenAI\u001b[39;00m\n\u001b[0;32m 15\u001b[0m \n\u001b[0;32m 16\u001b[0m \u001b[38;5;66;03m# To give you a preview -- calling OpenAI with system and user messages:\u001b[39;00m\n\u001b[1;32m---> 18\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mopenai\u001b[49m\u001b[38;5;241m.\u001b[39mchat\u001b[38;5;241m.\u001b[39mcompletions\u001b[38;5;241m.\u001b[39mcreate(model\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgpt-4o-mini\u001b[39m\u001b[38;5;124m\"\u001b[39m, messages\u001b[38;5;241m=\u001b[39mmessages)\n\u001b[0;32m 19\u001b[0m \u001b[38;5;66;03m# Step 4: print the result\u001b[39;00m\n\u001b[0;32m 21\u001b[0m \u001b[38;5;28mprint\u001b[39m(response\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mmessage\u001b[38;5;241m.\u001b[39mcontent)\n",
+ "\u001b[1;31mNameError\u001b[0m: name 'openai' is not defined"
+ ]
+ }
+ ],
"source": [
"# Step 1: Create your prompts\n",
"website = \"https://www.screener.in/company/CMSINFO/\"\n",
@@ -115,6 +1098,14 @@
"\n",
"print(response.choices[0].message.content)\n"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d9edf96e-1190-44fe-9261-405709fb39cd",
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
From a9b592fda4908509a5f72cfb84ddbe0164a058b9 Mon Sep 17 00:00:00 2001
From: Debojit Kangsa Banik
Date: Sun, 26 Jan 2025 11:45:32 +0530
Subject: [PATCH 34/61] Added my contributions to community-contributions
---
...y1-debs_stock_summary_recommendation.ipynb | 46 +++++++++++++++----
1 file changed, 37 insertions(+), 9 deletions(-)
diff --git a/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
index 4a2a267..68175f9 100644
--- a/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
+++ b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
@@ -51,6 +51,16 @@
" print(\"API key found and looks good so far!\")\n"
]
},
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "0d2d5441-2afe-41b9-8039-c367acd715f9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai = OpenAI()"
+ ]
+ },
{
"cell_type": "code",
"execution_count": 3,
@@ -1059,19 +1069,37 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 7,
"id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
"metadata": {},
"outputs": [
{
- "ename": "NameError",
- "evalue": "name 'openai' is not defined",
- "output_type": "error",
- "traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
- "Cell \u001b[1;32mIn[5], line 18\u001b[0m\n\u001b[0;32m 10\u001b[0m messages \u001b[38;5;241m=\u001b[39m [\n\u001b[0;32m 11\u001b[0m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124msystem\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: system_prompt},\n\u001b[0;32m 12\u001b[0m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: user_prompt}\n\u001b[0;32m 13\u001b[0m ]\n\u001b[0;32m 14\u001b[0m \u001b[38;5;66;03m# Step 3: Call OpenAI\u001b[39;00m\n\u001b[0;32m 15\u001b[0m \n\u001b[0;32m 16\u001b[0m \u001b[38;5;66;03m# To give you a preview -- calling OpenAI with system and user messages:\u001b[39;00m\n\u001b[1;32m---> 18\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mopenai\u001b[49m\u001b[38;5;241m.\u001b[39mchat\u001b[38;5;241m.\u001b[39mcompletions\u001b[38;5;241m.\u001b[39mcreate(model\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgpt-4o-mini\u001b[39m\u001b[38;5;124m\"\u001b[39m, messages\u001b[38;5;241m=\u001b[39mmessages)\n\u001b[0;32m 19\u001b[0m \u001b[38;5;66;03m# Step 4: print the result\u001b[39;00m\n\u001b[0;32m 21\u001b[0m \u001b[38;5;28mprint\u001b[39m(response\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mmessage\u001b[38;5;241m.\u001b[39mcontent)\n",
- "\u001b[1;31mNameError\u001b[0m: name 'openai' is not defined"
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "### Summary of CMS Info Systems Ltd\n",
+ "\n",
+ "CMS Info Systems Ltd is India's largest cash management company, recognized primarily for its extensive network of ATM and retail pick-up points. Founded with a focus on providing end-to-end outsourced solutions, the company caters to banks, financial institutions, organized retail, and e-commerce sectors. As of March 31, 2021, it has established itself as a leader in cash logistics, AIoT (Artificial Intelligence of Things) in banking, and Algorithmic Managed Variable Supply (Algo MVS). Some of its prominent clients include State Bank of India (SBI), HDFC, ICICI, and Axis Bank.\n",
+ "\n",
+ "### Key Financial Highlights\n",
+ "- **Market Cap**: ₹7,041 Crores\n",
+ "- **Current Share Price**: ₹431\n",
+ "- **Stock P/E Ratio**: 18.8\n",
+ "- **Dividends Yield**: 1.33%\n",
+ "- **Return on Equity (ROE)**: 20.5%\n",
+ "- **Debt**: The company is almost debt-free.\n",
+ "\n",
+ "### Pros\n",
+ "- **Strong Profit Growth**: Achieved a compounded annual growth rate (CAGR) of about 30.7% over the last five years.\n",
+ "- **Healthy Dividend Payout**: Maintains a dividend payout of 23.7%, appealing to income-seeking investors.\n",
+ "- **Dominance in Market**: Established as the largest player in the cash management and ATM servicing sector in India.\n",
+ "\n",
+ "### Cons\n",
+ "- **Market Volatility**: Operating in the banking services sector can expose the company to macroeconomic factors impacting the financial sector.\n",
+ "- **Dependence on Banks**: The company heavily relies on major banking institutions, which could be a risk if banking regulations or market conditions shift.\n",
+ "\n",
+ "### Recommendation\n",
+ "Given the robust growth track record and almost debt-free balance sheet complemented by a healthy dividend yield, CMS Info Systems Ltd appears to be a **BUY** at the current level. Its position as a market leader in cash management and a strong financial performance suggests potential for long-term growth. Investors should monitor industry trends and regulatory frameworks impacting the banking and retail sectors closely.\n"
]
}
],
From 4cc229fbaf9e66aa68a51aa33a7f26625fff650a Mon Sep 17 00:00:00 2001
From: Debojit Kangsa Banik
Date: Sun, 26 Jan 2025 13:02:45 +0530
Subject: [PATCH 35/61] Added my contributions to community-contributions
---
...y1-debs_stock_summary_recommendation.ipynb | 1019 +----------------
1 file changed, 9 insertions(+), 1010 deletions(-)
diff --git a/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
index 68175f9..0fe87cc 100644
--- a/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
+++ b/week1/community-contributions/day1-debs_stock_summary_recommendation.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": null,
"id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
"metadata": {},
"outputs": [],
@@ -21,18 +21,10 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": null,
"id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "API key found and looks good so far!\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"# Load environment variables in a file called .env\n",
"\n",
@@ -53,7 +45,7 @@
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": null,
"id": "0d2d5441-2afe-41b9-8039-c367acd715f9",
"metadata": {},
"outputs": [],
@@ -63,7 +55,7 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": null,
"id": "c5e793b2-6775-426a-a139-4848291d0463",
"metadata": {},
"outputs": [],
@@ -93,973 +85,10 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": null,
"id": "7c7e0988-8f2d-4844-a847-eebec76b114a",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Give short summary of the business Home\n",
- "Screens\n",
- "Tools\n",
- "Login\n",
- "Home\n",
- "Screens\n",
- "Tools\n",
- "Create a stock screen\n",
- "Run queries on 10 years of financial data\n",
- "Premium features\n",
- "Commodity Prices\n",
- "See prices and trends of over 10,000 commodities\n",
- "Search shareholders\n",
- "See companies where a person holds over 1% of the shares\n",
- "Latest Announcements\n",
- "Browse, filter and set alerts for announcements.\n",
- "Upgrade to premium\n",
- "Login\n",
- "Get free account\n",
- "CMS Info Systems Ltd\n",
- "Notebook\n",
- "CMS Info Systems\n",
- "Summary\n",
- "Chart\n",
- "Analysis\n",
- "Peers\n",
- "Quarters\n",
- "Profit & Loss\n",
- "Balance Sheet\n",
- "Cash Flow\n",
- "Ratios\n",
- "Investors\n",
- "Documents\n",
- "Notebook\n",
- "CMS Info Systems Ltd\n",
- "₹ 431\n",
- "-1.66%\n",
- "24 Jan\n",
- " \n",
- " - close price\n",
- "Export to Excel\n",
- "Follow\n",
- "cms.com\n",
- "BSE:\n",
- " 543441\n",
- "NSE:\n",
- " CMSINFO\n",
- "About\n",
- "CMS Info Systems Limited is India's largest cash management company in terms of the number of ATM points and retail pick-up points as of March 31, 2021. The company is engaged in installing, maintaining, and managing assets and technology solutions on an end-to-end outsourced basis for banks, financial institutions, organized retail and e-commerce companies in India.\n",
- "Key Points\n",
- "Leadership\n",
- "[1]\n",
- "Only Integrated Banking Solutions provider
\n",
- "with end-to-end offerings.\n",
- "1 across Cash Logistics, AIoT in Banking and Algo MVS.
\n",
- "The company services leading banks like\n",
- "SBI, HDFC, ICICI & Axis.\n",
- "Read More\n",
- "Website\n",
- "BSE\n",
- "NSE\n",
- "Market Cap\n",
- "₹\n",
- "7,041\n",
- "Cr.\n",
- "Current Price\n",
- "₹\n",
- "431\n",
- "High / Low\n",
- "₹\n",
- "616\n",
- "/\n",
- "355\n",
- "Stock P/E\n",
- "18.8\n",
- "Book Value\n",
- "₹\n",
- "124\n",
- "Dividend Yield\n",
- "1.33\n",
- "%\n",
- "ROCE\n",
- "27.5\n",
- "%\n",
- "ROE\n",
- "20.5\n",
- "%\n",
- "Face Value\n",
- "₹\n",
- "10.0\n",
- "Add ratio to table\n",
- "Edit ratios\n",
- "1M\n",
- "6M\n",
- "1Yr\n",
- "3Yr\n",
- "5Yr\n",
- "10Yr\n",
- "Max\n",
- "Price\n",
- "PE Ratio\n",
- "Hidden\n",
- "More\n",
- "Sales & Margin\n",
- "EV / EBITDA\n",
- "Price to Book\n",
- "Market Cap / Sales\n",
- "Alerts\n",
- "Pros\n",
- "Company is almost debt free.\n",
- "Company has delivered good profit growth of 30.7% CAGR over last 5 years\n",
- "Company has been maintaining a healthy dividend payout of 23.7%\n",
- "Cons\n",
- "*\n",
- "The pros and cons are machine generated.\n",
- "Pros / cons are based on a checklist to highlight important points. Please exercise caution and do your own analysis.\n",
- "Peer comparison\n",
- "Sector:\n",
- "Miscellaneous\n",
- "Industry:\n",
- "Miscellaneous\n",
- "Part of\n",
- "BSE Services\n",
- "BSE Allcap\n",
- "BSE SmallCap\n",
- "Nifty Total Market\n",
- "Nifty Microcap 250\n",
- "Edit\n",
- "Columns\n",
- "Loading peers table ...\n",
- "Detailed Comparison with:\n",
- "Quarterly Results\n",
- "Standalone Figures in Rs. Crores\n",
- " /\n",
- "View Consolidated\n",
- "Sep 2021\n",
- "Dec 2021\n",
- "Mar 2022\n",
- "Jun 2022\n",
- "Sep 2022\n",
- "Dec 2022\n",
- "Mar 2023\n",
- "Jun 2023\n",
- "Sep 2023\n",
- "Dec 2023\n",
- "Mar 2024\n",
- "Jun 2024\n",
- "Sep 2024\n",
- "Sales\n",
- "+\n",
- "326\n",
- "354\n",
- "399\n",
- "399\n",
- "417\n",
- "438\n",
- "449\n",
- "457\n",
- "487\n",
- "523\n",
- "581\n",
- "553\n",
- "577\n",
- "Expenses\n",
- "+\n",
- "237\n",
- "252\n",
- "294\n",
- "292\n",
- "302\n",
- "318\n",
- "310\n",
- "322\n",
- "359\n",
- "394\n",
- "432\n",
- "412\n",
- "433\n",
- "Operating Profit\n",
- "89\n",
- "102\n",
- "105\n",
- "107\n",
- "115\n",
- "120\n",
- "139\n",
- "134\n",
- "128\n",
- "129\n",
- "148\n",
- "141\n",
- "143\n",
- "OPM %\n",
- "27%\n",
- "29%\n",
- "26%\n",
- "27%\n",
- "28%\n",
- "27%\n",
- "31%\n",
- "29%\n",
- "26%\n",
- "25%\n",
- "26%\n",
- "25%\n",
- "25%\n",
- "Other Income\n",
- "+\n",
- "1\n",
- "9\n",
- "2\n",
- "17\n",
- "2\n",
- "4\n",
- "4\n",
- "6\n",
- "6\n",
- "31\n",
- "34\n",
- "10\n",
- "11\n",
- "Interest\n",
- "4\n",
- "3\n",
- "4\n",
- "4\n",
- "5\n",
- "5\n",
- "5\n",
- "4\n",
- "4\n",
- "4\n",
- "4\n",
- "4\n",
- "4\n",
- "Depreciation\n",
- "21\n",
- "21\n",
- "26\n",
- "28\n",
- "32\n",
- "31\n",
- "33\n",
- "34\n",
- "34\n",
- "36\n",
- "38\n",
- "37\n",
- "38\n",
- "Profit before tax\n",
- "65\n",
- "87\n",
- "76\n",
- "91\n",
- "80\n",
- "89\n",
- "105\n",
- "102\n",
- "96\n",
- "121\n",
- "141\n",
- "110\n",
- "113\n",
- "Tax %\n",
- "24%\n",
- "24%\n",
- "27%\n",
- "21%\n",
- "26%\n",
- "25%\n",
- "26%\n",
- "26%\n",
- "26%\n",
- "20%\n",
- "21%\n",
- "25%\n",
- "26%\n",
- "Net Profit\n",
- "+\n",
- "49\n",
- "66\n",
- "56\n",
- "72\n",
- "59\n",
- "67\n",
- "77\n",
- "75\n",
- "71\n",
- "96\n",
- "111\n",
- "82\n",
- "84\n",
- "EPS in Rs\n",
- "3.31\n",
- "4.48\n",
- "3.64\n",
- "4.68\n",
- "3.86\n",
- "4.33\n",
- "5.01\n",
- "4.88\n",
- "4.55\n",
- "6.16\n",
- "6.84\n",
- "5.03\n",
- "5.15\n",
- "Raw PDF\n",
- "Profit & Loss\n",
- "Standalone Figures in Rs. Crores\n",
- " /\n",
- "View Consolidated\n",
- "Related Party\n",
- "Mar 2017\n",
- "Mar 2018\n",
- "Mar 2019\n",
- "Mar 2020\n",
- "Mar 2021\n",
- "Mar 2022\n",
- "Mar 2023\n",
- "Mar 2024\n",
- "TTM\n",
- "Sales\n",
- "+\n",
- "783\n",
- "742\n",
- "903\n",
- "1,162\n",
- "1,131\n",
- "1,408\n",
- "1,704\n",
- "2,047\n",
- "2,233\n",
- "Expenses\n",
- "+\n",
- "649\n",
- "620\n",
- "755\n",
- "932\n",
- "869\n",
- "1,035\n",
- "1,222\n",
- "1,507\n",
- "1,671\n",
- "Operating Profit\n",
- "134\n",
- "122\n",
- "148\n",
- "230\n",
- "262\n",
- "373\n",
- "482\n",
- "539\n",
- "562\n",
- "OPM %\n",
- "17%\n",
- "16%\n",
- "16%\n",
- "20%\n",
- "23%\n",
- "26%\n",
- "28%\n",
- "26%\n",
- "25%\n",
- "Other Income\n",
- "+\n",
- "7\n",
- "15\n",
- "18\n",
- "6\n",
- "14\n",
- "13\n",
- "27\n",
- "78\n",
- "86\n",
- "Interest\n",
- "5\n",
- "1\n",
- "0\n",
- "7\n",
- "8\n",
- "14\n",
- "19\n",
- "16\n",
- "15\n",
- "Depreciation\n",
- "21\n",
- "21\n",
- "26\n",
- "48\n",
- "58\n",
- "88\n",
- "124\n",
- "142\n",
- "148\n",
- "Profit before tax\n",
- "115\n",
- "116\n",
- "140\n",
- "181\n",
- "211\n",
- "285\n",
- "365\n",
- "459\n",
- "484\n",
- "Tax %\n",
- "35%\n",
- "34%\n",
- "35%\n",
- "30%\n",
- "28%\n",
- "25%\n",
- "25%\n",
- "23%\n",
- "Net Profit\n",
- "+\n",
- "75\n",
- "76\n",
- "91\n",
- "128\n",
- "152\n",
- "213\n",
- "275\n",
- "354\n",
- "374\n",
- "EPS in Rs\n",
- "5.04\n",
- "5.15\n",
- "6.16\n",
- "8.63\n",
- "10.25\n",
- "13.94\n",
- "17.84\n",
- "21.76\n",
- "23.18\n",
- "Dividend Payout %\n",
- "0%\n",
- "0%\n",
- "0%\n",
- "21%\n",
- "15%\n",
- "18%\n",
- "27%\n",
- "26%\n",
- "Compounded Sales Growth\n",
- "10 Years:\n",
- "%\n",
- "5 Years:\n",
- "18%\n",
- "3 Years:\n",
- "22%\n",
- "TTM:\n",
- "22%\n",
- "Compounded Profit Growth\n",
- "10 Years:\n",
- "%\n",
- "5 Years:\n",
- "31%\n",
- "3 Years:\n",
- "32%\n",
- "TTM:\n",
- "29%\n",
- "Stock Price CAGR\n",
- "10 Years:\n",
- "%\n",
- "5 Years:\n",
- "%\n",
- "3 Years:\n",
- "16%\n",
- "1 Year:\n",
- "11%\n",
- "Return on Equity\n",
- "10 Years:\n",
- "%\n",
- "5 Years:\n",
- "19%\n",
- "3 Years:\n",
- "20%\n",
- "Last Year:\n",
- "21%\n",
- "Balance Sheet\n",
- "Standalone Figures in Rs. Crores\n",
- " /\n",
- "View Consolidated\n",
- "Corporate actions\n",
- "Mar 2017\n",
- "Mar 2018\n",
- "Mar 2019\n",
- "Mar 2020\n",
- "Mar 2021\n",
- "Mar 2022\n",
- "Mar 2023\n",
- "Mar 2024\n",
- "Sep 2024\n",
- "Equity Capital\n",
- "148\n",
- "148\n",
- "148\n",
- "148\n",
- "148\n",
- "153\n",
- "154\n",
- "163\n",
- "163\n",
- "Reserves\n",
- "413\n",
- "522\n",
- "589\n",
- "686\n",
- "803\n",
- "1,059\n",
- "1,342\n",
- "1,726\n",
- "1,866\n",
- "Borrowings\n",
- "+\n",
- "7\n",
- "0\n",
- "0\n",
- "0\n",
- "0\n",
- "0\n",
- "0\n",
- "0\n",
- "181\n",
- "Other Liabilities\n",
- "+\n",
- "161\n",
- "171\n",
- "197\n",
- "434\n",
- "580\n",
- "549\n",
- "500\n",
- "673\n",
- "533\n",
- "Total Liabilities\n",
- "729\n",
- "842\n",
- "934\n",
- "1,268\n",
- "1,532\n",
- "1,761\n",
- "1,997\n",
- "2,562\n",
- "2,743\n",
- "Fixed Assets\n",
- "+\n",
- "162\n",
- "162\n",
- "204\n",
- "328\n",
- "440\n",
- "637\n",
- "753\n",
- "727\n",
- "711\n",
- "CWIP\n",
- "1\n",
- "0\n",
- "3\n",
- "4\n",
- "23\n",
- "42\n",
- "20\n",
- "18\n",
- "71\n",
- "Investments\n",
- "143\n",
- "215\n",
- "195\n",
- "240\n",
- "281\n",
- "266\n",
- "426\n",
- "613\n",
- "562\n",
- "Other Assets\n",
- "+\n",
- "422\n",
- "464\n",
- "532\n",
- "696\n",
- "787\n",
- "815\n",
- "798\n",
- "1,205\n",
- "1,400\n",
- "Total Assets\n",
- "729\n",
- "842\n",
- "934\n",
- "1,268\n",
- "1,532\n",
- "1,761\n",
- "1,997\n",
- "2,562\n",
- "2,743\n",
- "Cash Flows\n",
- "Standalone Figures in Rs. Crores\n",
- " /\n",
- "View Consolidated\n",
- "Mar 2017\n",
- "Mar 2018\n",
- "Mar 2019\n",
- "Mar 2020\n",
- "Mar 2021\n",
- "Mar 2022\n",
- "Mar 2023\n",
- "Mar 2024\n",
- "Cash from Operating Activity\n",
- "+\n",
- "121\n",
- "150\n",
- "74\n",
- "204\n",
- "100\n",
- "219\n",
- "382\n",
- "385\n",
- "Cash from Investing Activity\n",
- "+\n",
- "-65\n",
- "-91\n",
- "5\n",
- "-106\n",
- "-90\n",
- "-284\n",
- "-323\n",
- "-236\n",
- "Cash from Financing Activity\n",
- "+\n",
- "-57\n",
- "-5\n",
- "-29\n",
- "-56\n",
- "-60\n",
- "2\n",
- "-51\n",
- "-51\n",
- "Net Cash Flow\n",
- "-2\n",
- "55\n",
- "51\n",
- "42\n",
- "-50\n",
- "-63\n",
- "9\n",
- "98\n",
- "Ratios\n",
- "Standalone Figures in Rs. Crores\n",
- " /\n",
- "View Consolidated\n",
- "Mar 2017\n",
- "Mar 2018\n",
- "Mar 2019\n",
- "Mar 2020\n",
- "Mar 2021\n",
- "Mar 2022\n",
- "Mar 2023\n",
- "Mar 2024\n",
- "Debtor Days\n",
- "57\n",
- "56\n",
- "54\n",
- "70\n",
- "137\n",
- "111\n",
- "97\n",
- "118\n",
- "Inventory Days\n",
- "49\n",
- "212\n",
- "169\n",
- "82\n",
- "182\n",
- "149\n",
- "233\n",
- "238\n",
- "Days Payable\n",
- "329\n",
- "603\n",
- "318\n",
- "363\n",
- "642\n",
- "610\n",
- "763\n",
- "806\n",
- "Cash Conversion Cycle\n",
- "-223\n",
- "-335\n",
- "-95\n",
- "-211\n",
- "-324\n",
- "-349\n",
- "-433\n",
- "-450\n",
- "Working Capital Days\n",
- "63\n",
- "49\n",
- "49\n",
- "21\n",
- "35\n",
- "60\n",
- "57\n",
- "58\n",
- "ROCE %\n",
- "19%\n",
- "20%\n",
- "24%\n",
- "24%\n",
- "28%\n",
- "28%\n",
- "28%\n",
- "Shareholding Pattern\n",
- "Numbers in percentages\n",
- "Quarterly\n",
- "Yearly\n",
- "Trades\n",
- "Mar 2022\n",
- "Jun 2022\n",
- "Sep 2022\n",
- "Dec 2022\n",
- "Mar 2023\n",
- "Jun 2023\n",
- "Sep 2023\n",
- "Dec 2023\n",
- "Mar 2024\n",
- "Jun 2024\n",
- "Sep 2024\n",
- "Dec 2024\n",
- "Promoters\n",
- "+\n",
- "63.38%\n",
- "63.16%\n",
- "63.01%\n",
- "60.98%\n",
- "60.24%\n",
- "46.48%\n",
- "26.69%\n",
- "26.69%\n",
- "0.00%\n",
- "0.00%\n",
- "0.00%\n",
- "0.00%\n",
- "FIIs\n",
- "+\n",
- "9.54%\n",
- "10.40%\n",
- "10.61%\n",
- "12.46%\n",
- "13.12%\n",
- "15.27%\n",
- "23.76%\n",
- "23.76%\n",
- "36.34%\n",
- "40.21%\n",
- "39.99%\n",
- "37.95%\n",
- "DIIs\n",
- "+\n",
- "11.09%\n",
- "11.65%\n",
- "12.09%\n",
- "12.14%\n",
- "12.57%\n",
- "20.96%\n",
- "23.98%\n",
- "23.43%\n",
- "29.01%\n",
- "28.40%\n",
- "26.66%\n",
- "27.03%\n",
- "Public\n",
- "+\n",
- "15.99%\n",
- "14.78%\n",
- "14.30%\n",
- "14.43%\n",
- "14.04%\n",
- "17.27%\n",
- "25.56%\n",
- "26.13%\n",
- "34.65%\n",
- "31.40%\n",
- "33.35%\n",
- "35.01%\n",
- "No. of Shareholders\n",
- "1,43,091\n",
- "1,30,634\n",
- "1,18,270\n",
- "1,09,201\n",
- "1,14,003\n",
- "1,20,804\n",
- "1,43,365\n",
- "1,54,547\n",
- "1,68,942\n",
- "1,60,764\n",
- "1,77,142\n",
- "1,74,847\n",
- "Mar 2022\n",
- "Mar 2023\n",
- "Mar 2024\n",
- "Dec 2024\n",
- "Promoters\n",
- "+\n",
- "63.38%\n",
- "60.24%\n",
- "0.00%\n",
- "0.00%\n",
- "FIIs\n",
- "+\n",
- "9.54%\n",
- "13.12%\n",
- "36.34%\n",
- "37.95%\n",
- "DIIs\n",
- "+\n",
- "11.09%\n",
- "12.57%\n",
- "29.01%\n",
- "27.03%\n",
- "Public\n",
- "+\n",
- "15.99%\n",
- "14.04%\n",
- "34.65%\n",
- "35.01%\n",
- "No. of Shareholders\n",
- "1,43,091\n",
- "1,14,003\n",
- "1,68,942\n",
- "1,74,847\n",
- "* The classifications might have changed from Sep'2022 onwards.\n",
- "The new XBRL format added more details from Sep'22 onwards.\n",
- "Classifications such as banks and foreign portfolio investors were not available earlier. The sudden changes in FII or DII can be because of these changes.\n",
- "Click on the line-items to see the names of individual entities.\n",
- "Documents\n",
- "Announcements\n",
- "Recent\n",
- "Important\n",
- "Search\n",
- "All\n",
- "Disclosures under Reg. 29(1) of SEBI (SAST) Regulations, 2011\n",
- "14h\n",
- "Announcement under Regulation 30 (LODR)-Newspaper Publication\n",
- "18 Jan - Newspaper publications for Postal Ballot Notice dated 16th January, 2025\n",
- "Shareholder Meeting / Postal Ballot-Notice of Postal Ballot\n",
- "17 Jan - Postal ballot notice for appointment of Independent Director.\n",
- "Change In The Name Of Registrar And Share Transfer Agent.\n",
- "2 Jan - Change of name of Registrar and Share Transfer Agent.\n",
- "Closure of Trading Window\n",
- "30 Dec\n",
- "Annual reports\n",
- "Financial Year 2024\n",
- "from bse\n",
- "Financial Year 2023\n",
- "from bse\n",
- "Financial Year 2022\n",
- "from bse\n",
- "Financial Year 2022\n",
- "from nse\n",
- "DRHP\n",
- "Credit ratings\n",
- "Rating update\n",
- "25 Jan 2024 from icra\n",
- "Rating update\n",
- "22 Mar 2023 from icra\n",
- "Rating update\n",
- "26 Sep 2022 from icra\n",
- "Rating update\n",
- "15 Jul 2021 from icra\n",
- "Rating update\n",
- "18 Feb 2020 from icra\n",
- "Rating update\n",
- "8 Jan 2019 from icra\n",
- "Concalls\n",
- "Add Missing\n",
- "Oct 2024\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "REC\n",
- "Jul 2024\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "REC\n",
- "May 2024\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "REC\n",
- "Jan 2024\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "Oct 2023\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "Jul 2023\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "May 2023\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "REC\n",
- "Feb 2023\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "Nov 2022\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "Aug 2022\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "May 2022\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "Feb 2022\n",
- "Transcript\n",
- "Notes\n",
- "PPT\n",
- "Stock analysis and screening tool\n",
- "Mittal Analytics Private Ltd © 2009-2024\n",
- "Made with\n",
- "in India.\n",
- "Data provided by C-MOTS Internet Technologies Pvt Ltd\n",
- "Terms\n",
- "&\n",
- "Privacy\n",
- ".\n",
- "Product\n",
- "Premium\n",
- "What's new?\n",
- "Learn\n",
- "Install\n",
- "Team\n",
- "About us\n",
- "Support\n",
- "Theme\n",
- "Light\n",
- "Dark\n",
- "Auto\n",
- "Mittal Analytics Private Ltd © 2009-2024\n",
- "Data provided by C-MOTS Internet Technologies Pvt Ltd\n",
- "Terms\n",
- "&\n",
- "Privacy\n",
- ". and recommend pros and cons of the business in bullet points alongwith recommendation to buy or sell\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"website = \"https://www.screener.in/company/CMSINFO/\"\n",
"biz = Website(website)\n",
@@ -1069,40 +98,10 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": null,
"id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "### Summary of CMS Info Systems Ltd\n",
- "\n",
- "CMS Info Systems Ltd is India's largest cash management company, recognized primarily for its extensive network of ATM and retail pick-up points. Founded with a focus on providing end-to-end outsourced solutions, the company caters to banks, financial institutions, organized retail, and e-commerce sectors. As of March 31, 2021, it has established itself as a leader in cash logistics, AIoT (Artificial Intelligence of Things) in banking, and Algorithmic Managed Variable Supply (Algo MVS). Some of its prominent clients include State Bank of India (SBI), HDFC, ICICI, and Axis Bank.\n",
- "\n",
- "### Key Financial Highlights\n",
- "- **Market Cap**: ₹7,041 Crores\n",
- "- **Current Share Price**: ₹431\n",
- "- **Stock P/E Ratio**: 18.8\n",
- "- **Dividends Yield**: 1.33%\n",
- "- **Return on Equity (ROE)**: 20.5%\n",
- "- **Debt**: The company is almost debt-free.\n",
- "\n",
- "### Pros\n",
- "- **Strong Profit Growth**: Achieved a compounded annual growth rate (CAGR) of about 30.7% over the last five years.\n",
- "- **Healthy Dividend Payout**: Maintains a dividend payout of 23.7%, appealing to income-seeking investors.\n",
- "- **Dominance in Market**: Established as the largest player in the cash management and ATM servicing sector in India.\n",
- "\n",
- "### Cons\n",
- "- **Market Volatility**: Operating in the banking services sector can expose the company to macroeconomic factors impacting the financial sector.\n",
- "- **Dependence on Banks**: The company heavily relies on major banking institutions, which could be a risk if banking regulations or market conditions shift.\n",
- "\n",
- "### Recommendation\n",
- "Given the robust growth track record and almost debt-free balance sheet complemented by a healthy dividend yield, CMS Info Systems Ltd appears to be a **BUY** at the current level. Its position as a market leader in cash management and a strong financial performance suggests potential for long-term growth. Investors should monitor industry trends and regulatory frameworks impacting the banking and retail sectors closely.\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"# Step 1: Create your prompts\n",
"website = \"https://www.screener.in/company/CMSINFO/\"\n",
From d7021cbeb2350a9c79085f5239e3202eab8b7d6c Mon Sep 17 00:00:00 2001
From: arafat
Date: Mon, 27 Jan 2025 19:08:54 +0800
Subject: [PATCH 36/61] ai-web-summarizer
---
.../ai-web-summarizer/.gitignore | 33 ++++
.../ai-web-summarizer/README.md | 143 ++++++++++++++++++
.../ai-web-summarizer/main.py | 28 ++++
.../ai-web-summarizer/requirements.txt | 4 +
.../ai-web-summarizer/summarizer/__init__.py | 0
.../ai-web-summarizer/summarizer/fetcher.py | 23 +++
.../summarizer/summarizer.py | 85 +++++++++++
.../ai-web-summarizer/utils/__init__.py | 0
.../ai-web-summarizer/utils/config.py | 11 ++
.../ai-web-summarizer/utils/logger.py | 16 ++
10 files changed, 343 insertions(+)
create mode 100644 week3/community-contributions/ai-web-summarizer/.gitignore
create mode 100644 week3/community-contributions/ai-web-summarizer/README.md
create mode 100644 week3/community-contributions/ai-web-summarizer/main.py
create mode 100644 week3/community-contributions/ai-web-summarizer/requirements.txt
create mode 100644 week3/community-contributions/ai-web-summarizer/summarizer/__init__.py
create mode 100644 week3/community-contributions/ai-web-summarizer/summarizer/fetcher.py
create mode 100644 week3/community-contributions/ai-web-summarizer/summarizer/summarizer.py
create mode 100644 week3/community-contributions/ai-web-summarizer/utils/__init__.py
create mode 100644 week3/community-contributions/ai-web-summarizer/utils/config.py
create mode 100644 week3/community-contributions/ai-web-summarizer/utils/logger.py
diff --git a/week3/community-contributions/ai-web-summarizer/.gitignore b/week3/community-contributions/ai-web-summarizer/.gitignore
new file mode 100644
index 0000000..d7cf06b
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/.gitignore
@@ -0,0 +1,33 @@
+
+# Python
+__pycache__/
+*.py[cod]
+*.pyo
+*.pyd
+.Python
+env/
+venv/
+*.env
+*.ini
+*.log
+
+# VSCode
+.vscode/
+
+# IDE files
+.idea/
+
+# System files
+.DS_Store
+Thumbs.db
+
+# Environment variables
+.env
+
+# Jupyter notebook checkpoints
+.ipynb_checkpoints
+
+# Dependencies
+*.egg-info/
+dist/
+build/
diff --git a/week3/community-contributions/ai-web-summarizer/README.md b/week3/community-contributions/ai-web-summarizer/README.md
new file mode 100644
index 0000000..9ea70ff
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/README.md
@@ -0,0 +1,143 @@
+# AI Web Page Summarizer
+
+This project is a simple AI-powered web page summarizer that leverages OpenAI's GPT models and local inference with Ollama to generate concise summaries of given text. The goal is to create a "Reader's Digest of the Internet" by summarizing web content efficiently.
+
+## Features
+
+- Summarize text using OpenAI's GPT models or local Ollama models.
+- Flexible summarization engine selection (OpenAI API, Ollama API, or Ollama library).
+- Simple and modular code structure.
+- Error handling for better reliability.
+
+## Project Structure
+
+```
+ai-summarizer/
+│-- summarizer/
+│ │-- __init__.py
+│ │-- fetcher.py # Web content fetching logic
+│ │-- summarizer.py # Main summarization logic
+│-- utils/
+│ │-- __init__.py
+│ │-- logger.py # Logging configuration
+│-- main.py # Entry point of the app
+│-- .env # Environment variables
+│-- requirements.txt # Python dependencies
+│-- README.md # Project documentation
+```
+
+## Prerequisites
+
+- Python 3.8 or higher
+- OpenAI API Key (You can obtain it from [OpenAI](https://platform.openai.com/signup))
+- Ollama installed locally ([Installation Guide](https://ollama.ai))
+- `conda` for managing environments (optional)
+
+## Installation
+
+1. **Clone the repository:**
+
+ ```bash
+ git clone https://github.com/your-username/ai-summarizer.git
+ cd ai-summarizer
+ ```
+
+2. **Create a virtual environment (optional but recommended):**
+
+ ```bash
+ conda create --name summarizer-env python=3.9
+ conda activate summarizer-env
+ ```
+
+3. **Install dependencies:**
+
+ ```bash
+ pip install -r requirements.txt
+ ```
+
+4. **Set up environment variables:**
+
+ Create a `.env` file in the project root and add your OpenAI API key (if using OpenAI):
+
+ ```env
+ OPENAI_API_KEY=your-api-key-here
+ ```
+
+## Usage
+
+1. **Run the summarizer:**
+
+ ```bash
+ python main.py
+ ```
+
+2. **Sample Output:**
+
+ ```shell
+ Enter a URL to summarize: https://example.com
+ Summary of the page:
+ AI refers to machines demonstrating intelligence similar to humans and animals.
+ ```
+
+3. **Engine Selection:**
+
+ The summarizer supports multiple engines. Modify `main.py` to select your preferred model:
+
+ ```python
+ summary = summarize_text(content, 'gpt-4o-mini', engine="openai")
+ summary = summarize_text(content, 'deepseek-r1:1.5B', engine="ollama-api")
+ summary = summarize_text(content, 'deepseek-r1:1.5B', engine="ollama-lib")
+ ```
+
+## Configuration
+
+You can modify the model, max tokens, and temperature in `summarizer/summarizer.py`:
+
+```python
+response = client.chat.completions.create(
+ model="gpt-4o-mini",
+ messages=[...],
+ max_tokens=300,
+ temperature=0.7
+)
+```
+
+## Error Handling
+
+If any issues occur, the script will print an error message, for example:
+
+```
+Error during summarization: Invalid API key or Ollama not running.
+```
+
+## Dependencies
+
+The required dependencies are listed in `requirements.txt`:
+
+```
+openai
+python-dotenv
+requests
+ollama-api
+```
+
+Install them using:
+
+```bash
+pip install -r requirements.txt
+```
+
+## Contributing
+
+Contributions are welcome! Feel free to fork the repository and submit pull requests.
+
+## License
+
+This project is licensed under the MIT License. See the `LICENSE` file for more details.
+
+## Contact
+
+For any inquiries, please reach out to:
+
+- Linkedin: https://www.linkedin.com/in/khanarafat/
+- GitHub: https://github.com/raoarafat
diff --git a/week3/community-contributions/ai-web-summarizer/main.py b/week3/community-contributions/ai-web-summarizer/main.py
new file mode 100644
index 0000000..d5deb02
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/main.py
@@ -0,0 +1,28 @@
+from summarizer.fetcher import fetch_web_content
+from summarizer.summarizer import summarize_text
+from utils.logger import logger
+
+def main():
+ url = input("Enter a URL to summarize: ")
+
+ logger.info(f"Fetching content from: {url}")
+ content = fetch_web_content(url)
+
+ if content:
+ logger.info("Content fetched successfully. Sending to OpenAI for summarization...")
+ # summary = summarize_text(content,'gpt-4o-mini', engine="openai")
+ # summary = summarize_text(content, 'deepseek-r1:1.5B', engine="ollama-lib")
+ summary = summarize_text(content, 'deepseek-r1:1.5B', engine="ollama-api")
+
+
+ if summary:
+ logger.info("Summary generated successfully.")
+ print("\nSummary of the page:\n")
+ print(summary)
+ else:
+ logger.error("Failed to generate summary.")
+ else:
+ logger.error("Failed to fetch web content.")
+
+if __name__ == "__main__":
+ main()
diff --git a/week3/community-contributions/ai-web-summarizer/requirements.txt b/week3/community-contributions/ai-web-summarizer/requirements.txt
new file mode 100644
index 0000000..82de623
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/requirements.txt
@@ -0,0 +1,4 @@
+openai
+requests
+beautifulsoup4
+python-dotenv
diff --git a/week3/community-contributions/ai-web-summarizer/summarizer/__init__.py b/week3/community-contributions/ai-web-summarizer/summarizer/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/week3/community-contributions/ai-web-summarizer/summarizer/fetcher.py b/week3/community-contributions/ai-web-summarizer/summarizer/fetcher.py
new file mode 100644
index 0000000..f6e827c
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/summarizer/fetcher.py
@@ -0,0 +1,23 @@
+import requests
+from bs4 import BeautifulSoup
+
+def fetch_web_content(url):
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+
+ # Parse the HTML content
+ soup = BeautifulSoup(response.text, 'html.parser')
+
+ # Extract readable text from the web page (ignoring scripts, styles, etc.)
+ page_text = soup.get_text(separator=' ', strip=True)
+
+ return page_text[:5000] # Limit to 5000 chars (API limitation)
+ except requests.exceptions.RequestException as e:
+ print(f"Error fetching the webpage: {e}")
+ return None
+
+if __name__ == "__main__":
+ url = "https://en.wikipedia.org/wiki/Natural_language_processing"
+ content = fetch_web_content(url)
+ print(content[:500]) # Print a sample of the content
diff --git a/week3/community-contributions/ai-web-summarizer/summarizer/summarizer.py b/week3/community-contributions/ai-web-summarizer/summarizer/summarizer.py
new file mode 100644
index 0000000..b6e4526
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/summarizer/summarizer.py
@@ -0,0 +1,85 @@
+import openai # type: ignore
+import ollama
+import requests
+from utils.config import Config
+
+# Local Ollama API endpoint
+OLLAMA_API = "http://127.0.0.1:11434/api/chat"
+
+# Initialize OpenAI client with API key
+client = openai.Client(api_key=Config.OPENAI_API_KEY)
+
+def summarize_with_openai(text, model):
+ """Summarize text using OpenAI's GPT model."""
+ try:
+ response = client.chat.completions.create(
+ model=model,
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant that summarizes web pages."},
+ {"role": "user", "content": f"Summarize the following text: {text}"}
+ ],
+ max_tokens=300,
+ temperature=0.7
+ )
+ return response.choices[0].message.content
+ except Exception as e:
+ print(f"Error during OpenAI summarization: {e}")
+ return None
+
+def summarize_with_ollama_lib(text, model):
+ """Summarize text using Ollama Python library."""
+ try:
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant that summarizes web pages."},
+ {"role": "user", "content": f"Summarize the following text: {text}"}
+ ]
+ response = ollama.chat(model=model, messages=messages)
+ return response['message']['content']
+ except Exception as e:
+ print(f"Error during Ollama summarization: {e}")
+ return None
+
+def summarize_with_ollama_api(text, model):
+ """Summarize text using local Ollama API."""
+ try:
+ payload = {
+ "model": model,
+ "messages": [
+ {"role": "system", "content": "You are a helpful assistant that summarizes web pages."},
+ {"role": "user", "content": f"Summarize the following text: {text}"}
+ ],
+ "stream": False # Set to True for streaming responses
+ }
+ response = requests.post(OLLAMA_API, json=payload)
+ response_data = response.json()
+ return response_data.get('message', {}).get('content', 'No summary generated')
+ except Exception as e:
+ print(f"Error during Ollama API summarization: {e}")
+ return None
+
+def summarize_text(text, model, engine="openai"):
+ """Generic function to summarize text using the specified engine (openai/ollama-lib/ollama-api)."""
+ if engine == "openai":
+ return summarize_with_openai(text, model)
+ elif engine == "ollama-lib":
+ return summarize_with_ollama_lib(text, model)
+ elif engine == "ollama-api":
+ return summarize_with_ollama_api(text, model)
+ else:
+ print("Invalid engine specified. Use 'openai', 'ollama-lib', or 'ollama-api'.")
+ return None
+
+if __name__ == "__main__":
+ sample_text = "Artificial intelligence (AI) is intelligence demonstrated by machines, as opposed to the natural intelligence displayed by animals and humans."
+
+ # Summarize using OpenAI
+ openai_summary = summarize_text(sample_text, model="gpt-3.5-turbo", engine="openai")
+ print("OpenAI Summary:", openai_summary)
+
+ # Summarize using Ollama Python library
+ ollama_lib_summary = summarize_text(sample_text, model="deepseek-r1:1.5B", engine="ollama-lib")
+ print("Ollama Library Summary:", ollama_lib_summary)
+
+ # Summarize using local Ollama API
+ ollama_api_summary = summarize_text(sample_text, model="deepseek-r1:1.5B", engine="ollama-api")
+ print("Ollama API Summary:", ollama_api_summary)
diff --git a/week3/community-contributions/ai-web-summarizer/utils/__init__.py b/week3/community-contributions/ai-web-summarizer/utils/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/week3/community-contributions/ai-web-summarizer/utils/config.py b/week3/community-contributions/ai-web-summarizer/utils/config.py
new file mode 100644
index 0000000..bdca48d
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/utils/config.py
@@ -0,0 +1,11 @@
+import os
+from dotenv import load_dotenv
+
+# Load environment variables from .env file
+load_dotenv()
+
+class Config:
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
+
+if __name__ == "__main__":
+ print("Your OpenAI Key is:", Config.OPENAI_API_KEY)
\ No newline at end of file
diff --git a/week3/community-contributions/ai-web-summarizer/utils/logger.py b/week3/community-contributions/ai-web-summarizer/utils/logger.py
new file mode 100644
index 0000000..806acce
--- /dev/null
+++ b/week3/community-contributions/ai-web-summarizer/utils/logger.py
@@ -0,0 +1,16 @@
+import logging
+
+# Setup logging configuration
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(levelname)s - %(message)s",
+ handlers=[
+ logging.FileHandler("app.log"),
+ logging.StreamHandler()
+ ]
+)
+
+logger = logging.getLogger(__name__)
+
+if __name__ == "__main__":
+ logger.info("Logger is working correctly.")
\ No newline at end of file
From 95c38ce9f34f303e4081e1ff342b80113b062998 Mon Sep 17 00:00:00 2001
From: Edward Donner
Date: Mon, 27 Jan 2025 14:16:26 -0500
Subject: [PATCH 37/61] Minor updates
---
week1/day2 EXERCISE.ipynb | 2 +-
week1/day5.ipynb | 2 +-
week2/day1.ipynb | 8 ++++----
week2/day3.ipynb | 22 +---------------------
week7/day2.ipynb | 2 +-
week7/day3 and 4.ipynb | 2 +-
week7/day5.ipynb | 2 +-
7 files changed, 10 insertions(+), 30 deletions(-)
diff --git a/week1/day2 EXERCISE.ipynb b/week1/day2 EXERCISE.ipynb
index fb08ca8..ec4eedc 100644
--- a/week1/day2 EXERCISE.ipynb
+++ b/week1/day2 EXERCISE.ipynb
@@ -216,7 +216,7 @@
{
"cell_type": "code",
"execution_count": null,
- "id": "402d5686-4e76-4110-b65a-b3906c35c0a4",
+ "id": "6de38216-6d1c-48c4-877b-86d403f4e0f8",
"metadata": {},
"outputs": [],
"source": []
diff --git a/week1/day5.ipynb b/week1/day5.ipynb
index 397e5ed..f39a4b2 100644
--- a/week1/day5.ipynb
+++ b/week1/day5.ipynb
@@ -334,7 +334,7 @@
"metadata": {},
"outputs": [],
"source": [
- "create_brochure(\"HuggingFace\", \"https://huggingface.com\")"
+ "create_brochure(\"HuggingFace\", \"https://huggingface.co\")"
]
},
{
diff --git a/week2/day1.ipynb b/week2/day1.ipynb
index 8a2640d..fdd4db1 100644
--- a/week2/day1.ipynb
+++ b/week2/day1.ipynb
@@ -272,7 +272,7 @@
"# Also adding max_tokens\n",
"\n",
"message = claude.messages.create(\n",
- " model=\"claude-3-5-sonnet-20240620\",\n",
+ " model=\"claude-3-5-sonnet-latest\",\n",
" max_tokens=200,\n",
" temperature=0.7,\n",
" system=system_message,\n",
@@ -295,7 +295,7 @@
"# Now let's add in streaming back results\n",
"\n",
"result = claude.messages.stream(\n",
- " model=\"claude-3-5-sonnet-20240620\",\n",
+ " model=\"claude-3-5-sonnet-latest\",\n",
" max_tokens=200,\n",
" temperature=0.7,\n",
" system=system_message,\n",
@@ -321,7 +321,7 @@
"# If that happens to you, please skip this cell and use the next cell instead - an alternative approach.\n",
"\n",
"gemini = google.generativeai.GenerativeModel(\n",
- " model_name='gemini-1.5-flash',\n",
+ " model_name='gemini-2.0-flash-exp',\n",
" system_instruction=system_message\n",
")\n",
"response = gemini.generate_content(user_prompt)\n",
@@ -344,7 +344,7 @@
")\n",
"\n",
"response = gemini_via_openai_client.chat.completions.create(\n",
- " model=\"gemini-1.5-flash\",\n",
+ " model=\"gemini-2.0-flash-exp\",\n",
" messages=prompts\n",
")\n",
"print(response.choices[0].message.content)"
diff --git a/week2/day3.ipynb b/week2/day3.ipynb
index 28e6896..2dd936b 100644
--- a/week2/day3.ipynb
+++ b/week2/day3.ipynb
@@ -136,26 +136,6 @@
" yield response"
]
},
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "40a2d5ad-e907-465e-8397-3120583a5bf9",
- "metadata": {},
- "outputs": [],
- "source": [
- "!pip show gradio"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "a7fed1b9-c502-4eea-b649-ca00458d5c45",
- "metadata": {},
- "outputs": [],
- "source": [
- "# 5.8.0 to 5.12"
- ]
- },
{
"cell_type": "markdown",
"id": "1334422a-808f-4147-9c4c-57d63d9780d0",
@@ -171,7 +151,7 @@
"metadata": {},
"outputs": [],
"source": [
- "gr.ChatInterface(fn=chat, type=\"messages\").launch(pwa=True)"
+ "gr.ChatInterface(fn=chat, type=\"messages\").launch()"
]
},
{
diff --git a/week7/day2.ipynb b/week7/day2.ipynb
index 198cde0..d38c1f9 100644
--- a/week7/day2.ipynb
+++ b/week7/day2.ipynb
@@ -31,7 +31,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week7/day3 and 4.ipynb b/week7/day3 and 4.ipynb
index 5b01703..b0af675 100644
--- a/week7/day3 and 4.ipynb
+++ b/week7/day3 and 4.ipynb
@@ -31,7 +31,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
diff --git a/week7/day5.ipynb b/week7/day5.ipynb
index 45991e4..3638aaf 100644
--- a/week7/day5.ipynb
+++ b/week7/day5.ipynb
@@ -31,7 +31,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.10"
+ "version": "3.11.11"
}
},
"nbformat": 4,
From 3f7b0004c4652a93833251fbdc753c47551f2ea0 Mon Sep 17 00:00:00 2001
From: 266367 <266367@nttdata.com>
Date: Mon, 27 Jan 2025 14:46:40 -0500
Subject: [PATCH 38/61] Wk1 Day 1 - Summarize website using deepseek-chat and
stream the response realtime
---
.../wk1-day1-deepseek-stream-summarize.ipynb | 119 ++++++++++++++++++
1 file changed, 119 insertions(+)
create mode 100644 week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
diff --git a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
new file mode 100644
index 0000000..95ee6ca
--- /dev/null
+++ b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
@@ -0,0 +1,119 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a767b6bc-65fe-42b2-988f-efd54125114f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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 time\n",
+ "\n",
+ "load_dotenv(override=True)\n",
+ "api_key = os.getenv('DEEPSEEK_API_KEY')\n",
+ "base_url=os.getenv('DEEPSEEK_BASE_URL')\n",
+ "start_time = time.time()\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",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]\n",
+ " \n",
+ "# Check the key\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-; Looks like you are using DeepSeek (R1) model.\")\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",
+ " \n",
+ "openai = OpenAI(api_key=api_key, base_url=base_url)\n",
+ "\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\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",
+ " \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; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\n\"\n",
+ " user_prompt += website.text\n",
+ " return user_prompt\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",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " response = openai.chat.completions.create(\n",
+ " model=\"deepseek-chat\",\n",
+ " messages=messages_for(website),\n",
+ " stream=True\n",
+ " )\n",
+ " print(\"Streaming response:\")\n",
+ " accumulated_content = \"\" # Accumulate the content here\n",
+ " for chunk in response:\n",
+ " if chunk.choices[0].delta.content: # Check if there's content in the chunk\n",
+ " accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
+ " \n",
+ " # Display the accumulated content as a single Markdown block\n",
+ " display(Markdown(accumulated_content))\n",
+ "\n",
+ "def display_summary():\n",
+ " url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
+ " summarize(url)\n",
+ "\n",
+ "display_summary()"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "llms",
+ "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
+}
From 9060924ad57501df3b24f84266c64ab4b8cdce78 Mon Sep 17 00:00:00 2001
From: Neil Neyman
Date: Mon, 27 Jan 2025 14:59:21 -0500
Subject: [PATCH 39/61] Added day 2 exercise to community contributions with
SSL verifications disabled tweak.
---
.../day2 EXERCISE-disabled-ssl.ipynb | 354 ++++++++++++++++++
1 file changed, 354 insertions(+)
create mode 100644 week1/community-contributions/day2 EXERCISE-disabled-ssl.ipynb
diff --git a/week1/community-contributions/day2 EXERCISE-disabled-ssl.ipynb b/week1/community-contributions/day2 EXERCISE-disabled-ssl.ipynb
new file mode 100644
index 0000000..d9a02d8
--- /dev/null
+++ b/week1/community-contributions/day2 EXERCISE-disabled-ssl.ipynb
@@ -0,0 +1,354 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "d15d8294-3328-4e07-ad16-8a03e9bbfdb9",
+ "metadata": {},
+ "source": [
+ "# Welcome to your first assignment!\n",
+ "\n",
+ "Instructions are below. Please give this a try, and look in the solutions folder if you get stuck (or feel free to ask me!)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ada885d9-4d42-4d9b-97f0-74fbbbfe93a9",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Just before we get to the assignment --\n",
+ " I thought I'd take a second to point you at this page of useful resources for the course. This includes links to all the slides. \n",
+ " https://edwarddonner.com/2024/11/13/llm-engineering-resources/ \n",
+ " Please keep this bookmarked, and I'll continue to add more useful links there over time.\n",
+ " \n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e9fa1fc-eac5-4d1d-9be4-541b3f2b3458",
+ "metadata": {},
+ "source": [
+ "# HOMEWORK EXERCISE ASSIGNMENT\n",
+ "\n",
+ "Upgrade the day 1 project to summarize a webpage to use an Open Source model running locally via Ollama rather than OpenAI\n",
+ "\n",
+ "You'll be able to use this technique for all subsequent projects if you'd prefer not to use paid APIs.\n",
+ "\n",
+ "**Benefits:**\n",
+ "1. No API charges - open-source\n",
+ "2. Data doesn't leave your box\n",
+ "\n",
+ "**Disadvantages:**\n",
+ "1. Significantly less power than Frontier Model\n",
+ "\n",
+ "## Recap on installation of Ollama\n",
+ "\n",
+ "Simply visit [ollama.com](https://ollama.com) and install!\n",
+ "\n",
+ "Once complete, the ollama server should already be running locally. \n",
+ "If you visit: \n",
+ "[http://localhost:11434/](http://localhost:11434/)\n",
+ "\n",
+ "You should see the message `Ollama is running`. \n",
+ "\n",
+ "If not, bring up a new Terminal (Mac) or Powershell (Windows) and enter `ollama serve` \n",
+ "And in another Terminal (Mac) or Powershell (Windows), enter `ollama pull llama3.2` \n",
+ "Then try [http://localhost:11434/](http://localhost:11434/) again.\n",
+ "\n",
+ "If Ollama is slow on your machine, try using `llama3.2:1b` as an alternative. Run `ollama pull llama3.2:1b` from a Terminal or Powershell, and change the code below from `MODEL = \"llama3.2\"` to `MODEL = \"llama3.2:1b\"`"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import requests\n",
+ "from bs4 import BeautifulSoup\n",
+ "from IPython.display import Markdown, display"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "29ddd15d-a3c5-4f4e-a678-873f56162724",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Constants\n",
+ "\n",
+ "OLLAMA_API = \"http://localhost:11434/api/chat\"\n",
+ "HEADERS = {\"Content-Type\": \"application/json\"}\n",
+ "MODEL = \"llama3.2\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "dac0a679-599c-441f-9bf2-ddc73d35b940",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create a messages list using the same format that we used for OpenAI\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\": \"user\", \"content\": \"Describe some of the business applications of Generative AI\"}\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7bb9c624-14f0-4945-a719-8ddb64f66f47",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "payload = {\n",
+ " \"model\": MODEL,\n",
+ " \"messages\": messages,\n",
+ " \"stream\": False\n",
+ " }"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "479ff514-e8bd-4985-a572-2ea28bb4fa40",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's just make sure the model is loaded\n",
+ "\n",
+ "!ollama pull llama3.2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "42b9f644-522d-4e05-a691-56e7658c0ea9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# If this doesn't work for any reason, try the 2 versions in the following cells\n",
+ "# And double check the instructions in the 'Recap on installation of Ollama' at the top of this lab\n",
+ "# And if none of that works - contact me!\n",
+ "\n",
+ "response = requests.post(OLLAMA_API, json=payload, headers=HEADERS)\n",
+ "print(response.json()['message']['content'])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a021f13-d6a1-4b96-8e18-4eae49d876fe",
+ "metadata": {},
+ "source": [
+ "# Introducing the ollama package\n",
+ "\n",
+ "And now we'll do the same thing, but using the elegant ollama python package instead of a direct HTTP call.\n",
+ "\n",
+ "Under the hood, it's making the same call as above to the ollama server running at localhost:11434"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7745b9c4-57dc-4867-9180-61fa5db55eb8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import ollama\n",
+ "\n",
+ "response = ollama.chat(model=MODEL, messages=messages)\n",
+ "print(response['message']['content'])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a4704e10-f5fb-4c15-a935-f046c06fb13d",
+ "metadata": {},
+ "source": [
+ "## Alternative approach - using OpenAI python library to connect to Ollama"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "23057e00-b6fc-4678-93a9-6b31cb704bff",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# There's actually an alternative approach that some people might prefer\n",
+ "# You can use the OpenAI client python library to call Ollama:\n",
+ "\n",
+ "from openai import OpenAI\n",
+ "ollama_via_openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n",
+ "\n",
+ "response = ollama_via_openai.chat.completions.create(\n",
+ " model=MODEL,\n",
+ " messages=messages\n",
+ ")\n",
+ "\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1622d9bb-5c68-4d4e-9ca4-b492c751f898",
+ "metadata": {},
+ "source": [
+ "# NOW the exercise for you\n",
+ "\n",
+ "Take the code from day1 and incorporate it here, to build a website summarizer that uses Llama 3.2 running locally instead of OpenAI; use either of the above approaches."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ef76cfc2-c519-4cb2-947a-64948517913d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import requests\n",
+ "from bs4 import BeautifulSoup\n",
+ "from IPython.display import Markdown, display"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a151a8de-1e90-4190-b68e-b44b25a2cdd7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Constants\n",
+ "\n",
+ "OLLAMA_API = \"http://localhost:11434/api/chat\"\n",
+ "HEADERS = {\"Content-Type\": \"application/json\"}\n",
+ "MODEL = \"llama3.2\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "700fffc1-c7b0-4001-b381-5c4fd28c8799",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Reusing the Website BeautifulSoup wrapper from Day 1\n",
+ "# SSL Verification has been disabled\n",
+ "\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers, verify=False) # NOTE Disabled ssl verification here to workaround VPN Limitations\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\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"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "402d5686-4e76-4110-b65a-b3906c35c0a4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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 are 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"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "81f5f140-8f77-418f-a252-8ad5d11f6c5f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "## enter the web URL here:\n",
+ "website_url = \"https://www.timecube.net/\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1d0ce4aa-b43e-4642-bcbd-d5964700ece8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "## This will at first print a warning for SSL which can be ignored before providing response. \n",
+ "\n",
+ "import ollama\n",
+ "\n",
+ "system_prompt = \"You are a virtual assistant who 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",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_for(Website(website_url))}\n",
+ "]\n",
+ "\n",
+ "response = ollama.chat(model=MODEL, messages=messages)\n",
+ "print(response['message']['content'])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "910b7e06-c92d-47bf-a4ee-a006d70deb06",
+ "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
+}
From daf9b36e28ed0923d3f3eecbdef9bf2f1137d55a Mon Sep 17 00:00:00 2001
From: 266367 <266367@nttdata.com>
Date: Mon, 27 Jan 2025 15:03:45 -0500
Subject: [PATCH 40/61] add markdown
---
.../wk1-day1-deepseek-stream-summarize.ipynb | 49 +++++++++++++++++--
1 file changed, 44 insertions(+), 5 deletions(-)
diff --git a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
index 95ee6ca..1c641f5 100644
--- a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
+++ b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
@@ -2,16 +2,53 @@
"cells": [
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 9,
"id": "a767b6bc-65fe-42b2-988f-efd54125114f",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "```markdown\n",
+ "# Summary of \"DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning\"\n",
+ "\n",
+ "## Overview\n",
+ "The paper introduces **DeepSeek-R1**, a first-generation reasoning model developed by DeepSeek-AI. The model is designed to enhance reasoning capabilities in large language models (LLMs) using reinforcement learning (RL). Two versions are presented:\n",
+ "- **DeepSeek-R1-Zero**: A model trained via large-scale RL without supervised fine-tuning (SFT), showcasing strong reasoning abilities but facing challenges like poor readability and language mixing.\n",
+ "- **DeepSeek-R1**: An improved version incorporating multi-stage training and cold-start data before RL, achieving performance comparable to OpenAI's models on reasoning tasks.\n",
+ "\n",
+ "## Key Contributions\n",
+ "- Open-sourcing of **DeepSeek-R1-Zero**, **DeepSeek-R1**, and six dense models (1.5B, 7B, 8B, 14B, 32B, 70B) distilled from DeepSeek-R1 based on Qwen and Llama architectures.\n",
+ "- The models are made available to support the research community.\n",
+ "\n",
+ "## Community Engagement\n",
+ "- The paper has been widely discussed and recommended, with 216 upvotes and 45 models citing it.\n",
+ "- Additional resources, including a video review and articles, are available through external links provided by the community.\n",
+ "\n",
+ "## Related Research\n",
+ "The paper is part of a broader trend in enhancing LLMs' reasoning abilities, with related works such as:\n",
+ "- **Improving Multi-Step Reasoning Abilities of Large Language Models with Direct Advantage Policy Optimization (2024)**\n",
+ "- **Offline Reinforcement Learning for LLM Multi-Step Reasoning (2024)**\n",
+ "- **Reasoning Language Models: A Blueprint (2025)**\n",
+ "\n",
+ "## Availability\n",
+ "- The paper and models are accessible on [GitHub](https://github.com/deepseek-ai/DeepSeek-R1) and the [arXiv page](https://arxiv.org/abs/2501.12948).\n",
+ "```"
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
"source": [
"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 IPython.display import Markdown, display, clear_output\n",
"from openai import OpenAI\n",
"import time\n",
"\n",
@@ -83,9 +120,11 @@
" for chunk in response:\n",
" if chunk.choices[0].delta.content: # Check if there's content in the chunk\n",
" accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
+ " clear_output(wait=True) # Clear the previous output\n",
+ " display(Markdown(accumulated_content)) # Display the updated content\n",
" \n",
- " # Display the accumulated content as a single Markdown block\n",
- " display(Markdown(accumulated_content))\n",
+ " # # Final display (optional, as the loop already displays the content)\n",
+ " # display(Markdown(accumulated_content))\n",
"\n",
"def display_summary():\n",
" url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
From ebf36008875dc0f85521c5cef3267263bf583de1 Mon Sep 17 00:00:00 2001
From: 266367 <266367@nttdata.com>
Date: Mon, 27 Jan 2025 15:06:31 -0500
Subject: [PATCH 41/61] last commit
---
.../wk1-day1-deepseek-stream-summarize.ipynb | 51 ++++---------------
1 file changed, 11 insertions(+), 40 deletions(-)
diff --git a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
index 1c641f5..6904a66 100644
--- a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
+++ b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
@@ -2,47 +2,10 @@
"cells": [
{
"cell_type": "code",
- "execution_count": 9,
+ "execution_count": null,
"id": "a767b6bc-65fe-42b2-988f-efd54125114f",
"metadata": {},
- "outputs": [
- {
- "data": {
- "text/markdown": [
- "```markdown\n",
- "# Summary of \"DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning\"\n",
- "\n",
- "## Overview\n",
- "The paper introduces **DeepSeek-R1**, a first-generation reasoning model developed by DeepSeek-AI. The model is designed to enhance reasoning capabilities in large language models (LLMs) using reinforcement learning (RL). Two versions are presented:\n",
- "- **DeepSeek-R1-Zero**: A model trained via large-scale RL without supervised fine-tuning (SFT), showcasing strong reasoning abilities but facing challenges like poor readability and language mixing.\n",
- "- **DeepSeek-R1**: An improved version incorporating multi-stage training and cold-start data before RL, achieving performance comparable to OpenAI's models on reasoning tasks.\n",
- "\n",
- "## Key Contributions\n",
- "- Open-sourcing of **DeepSeek-R1-Zero**, **DeepSeek-R1**, and six dense models (1.5B, 7B, 8B, 14B, 32B, 70B) distilled from DeepSeek-R1 based on Qwen and Llama architectures.\n",
- "- The models are made available to support the research community.\n",
- "\n",
- "## Community Engagement\n",
- "- The paper has been widely discussed and recommended, with 216 upvotes and 45 models citing it.\n",
- "- Additional resources, including a video review and articles, are available through external links provided by the community.\n",
- "\n",
- "## Related Research\n",
- "The paper is part of a broader trend in enhancing LLMs' reasoning abilities, with related works such as:\n",
- "- **Improving Multi-Step Reasoning Abilities of Large Language Models with Direct Advantage Policy Optimization (2024)**\n",
- "- **Offline Reinforcement Learning for LLM Multi-Step Reasoning (2024)**\n",
- "- **Reasoning Language Models: A Blueprint (2025)**\n",
- "\n",
- "## Availability\n",
- "- The paper and models are accessible on [GitHub](https://github.com/deepseek-ai/DeepSeek-R1) and the [arXiv page](https://arxiv.org/abs/2501.12948).\n",
- "```"
- ],
- "text/plain": [
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
+ "outputs": [],
"source": [
"import os\n",
"import requests\n",
@@ -132,11 +95,19 @@
"\n",
"display_summary()"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "01c9e5e7-7510-43ef-bb9c-aa44b15d39a7",
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
"kernelspec": {
- "display_name": "llms",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
From b9723acee1bfb3f68c9be6fbf168f8ecb30de34d Mon Sep 17 00:00:00 2001
From: 266367 <266367@nttdata.com>
Date: Mon, 27 Jan 2025 20:01:32 -0500
Subject: [PATCH 42/61] remove unwanted comments
---
.../wk1-day1-deepseek-stream-summarize.ipynb | 8 ++------
1 file changed, 2 insertions(+), 6 deletions(-)
diff --git a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
index 6904a66..2e615ed 100644
--- a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
+++ b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
@@ -13,12 +13,11 @@
"from bs4 import BeautifulSoup\n",
"from IPython.display import Markdown, display, clear_output\n",
"from openai import OpenAI\n",
- "import time\n",
"\n",
"load_dotenv(override=True)\n",
"api_key = os.getenv('DEEPSEEK_API_KEY')\n",
"base_url=os.getenv('DEEPSEEK_BASE_URL')\n",
- "start_time = time.time()\n",
+ "MODEL = \"deepseek-chat\"\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",
@@ -74,7 +73,7 @@
"def summarize(url):\n",
" website = Website(url)\n",
" response = openai.chat.completions.create(\n",
- " model=\"deepseek-chat\",\n",
+ " model=MODEL,\n",
" messages=messages_for(website),\n",
" stream=True\n",
" )\n",
@@ -85,9 +84,6 @@
" accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
" clear_output(wait=True) # Clear the previous output\n",
" display(Markdown(accumulated_content)) # Display the updated content\n",
- " \n",
- " # # Final display (optional, as the loop already displays the content)\n",
- " # display(Markdown(accumulated_content))\n",
"\n",
"def display_summary():\n",
" url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
From 7d6d9959df11fa265089f15c330ffa6b5d92f11a Mon Sep 17 00:00:00 2001
From: Edward Donner
Date: Tue, 28 Jan 2025 12:23:46 -0500
Subject: [PATCH 43/61] Added DeepSeek to weeks 1, 2 and 8
---
SETUP-PC.md | 1 +
SETUP-linux.md | 1 +
SETUP-mac.md | 1 +
week1/day2 EXERCISE.ipynb | 40 +++++++++++
week1/troubleshooting.ipynb | 10 ++-
week2/day1.ipynb | 126 ++++++++++++++++++++++++++++++++-
week8/agents/frontier_agent.py | 18 +++--
week8/day2.3.ipynb | 106 ++++++++++++++++++++++++++-
week8/day5.ipynb | 4 +-
9 files changed, 298 insertions(+), 9 deletions(-)
diff --git a/SETUP-PC.md b/SETUP-PC.md
index ab6ebb9..de3af5c 100644
--- a/SETUP-PC.md
+++ b/SETUP-PC.md
@@ -147,6 +147,7 @@ If you have other keys, you can add them too, or come back to this in future wee
```
GOOGLE_API_KEY=xxxx
ANTHROPIC_API_KEY=xxxx
+DEEPSEEK_API_KEY=xxxx
HF_TOKEN=xxxx
```
diff --git a/SETUP-linux.md b/SETUP-linux.md
index 45218ea..6806510 100644
--- a/SETUP-linux.md
+++ b/SETUP-linux.md
@@ -157,6 +157,7 @@ If you have other keys, you can add them too, or come back to this in future wee
```
GOOGLE_API_KEY=xxxx
ANTHROPIC_API_KEY=xxxx
+DEEPSEEK_API_KEY=xxxx
HF_TOKEN=xxxx
```
diff --git a/SETUP-mac.md b/SETUP-mac.md
index 2c0e566..a97d700 100644
--- a/SETUP-mac.md
+++ b/SETUP-mac.md
@@ -146,6 +146,7 @@ If you have other keys, you can add them too, or come back to this in future wee
```
GOOGLE_API_KEY=xxxx
ANTHROPIC_API_KEY=xxxx
+DEEPSEEK_API_KEY=xxxx
HF_TOKEN=xxxx
```
diff --git a/week1/day2 EXERCISE.ipynb b/week1/day2 EXERCISE.ipynb
index ec4eedc..81077ed 100644
--- a/week1/day2 EXERCISE.ipynb
+++ b/week1/day2 EXERCISE.ipynb
@@ -203,6 +203,46 @@
"print(response.choices[0].message.content)"
]
},
+ {
+ "cell_type": "markdown",
+ "id": "bc7d1de3-e2ac-46ff-a302-3b4ba38c4c90",
+ "metadata": {},
+ "source": [
+ "## Also trying the amazing reasoning model DeepSeek\n",
+ "\n",
+ "Here we use the version of DeepSeek-reasoner that's been distilled to 1.5B. \n",
+ "This is actually a 1.5B variant of Qwen that has been fine-tuned using synethic data generated by Deepseek R1.\n",
+ "\n",
+ "Other sizes of DeepSeek are [here](https://ollama.com/library/deepseek-r1) all the way up to the full 671B parameter version, which would use up 404GB of your drive and is far too large for most!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cf9eb44e-fe5b-47aa-b719-0bb63669ab3d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!ollama pull deepseek-r1:1.5b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1d3d554b-e00d-4c08-9300-45e073950a76",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This may take a few minutes to run! You should then see a fascinating \"thinking\" trace inside tags, followed by some decent definitions\n",
+ "\n",
+ "response = ollama_via_openai.chat.completions.create(\n",
+ " model=\"deepseek-r1:1.5b\",\n",
+ " messages=[{\"role\": \"user\", \"content\": \"Please give definitions of some core concepts behind LLMs: a neural network, attention and the transformer\"}]\n",
+ ")\n",
+ "\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
{
"cell_type": "markdown",
"id": "1622d9bb-5c68-4d4e-9ca4-b492c751f898",
diff --git a/week1/troubleshooting.ipynb b/week1/troubleshooting.ipynb
index c05a5a0..8cebb8c 100644
--- a/week1/troubleshooting.ipynb
+++ b/week1/troubleshooting.ipynb
@@ -27,7 +27,15 @@
"\n",
"Click in the cell below and press Shift+Return to run it. \n",
"If this gives you problems, then please try working through these instructions to address: \n",
- "https://chatgpt.com/share/676e6e3b-db44-8012-abaa-b3cf62c83eb3"
+ "https://chatgpt.com/share/676e6e3b-db44-8012-abaa-b3cf62c83eb3\n",
+ "\n",
+ "I've also heard that you might have problems if you are using a work computer that's running security software zscaler.\n",
+ "\n",
+ "Some advice from students in this situation with zscaler:\n",
+ "\n",
+ "> In the anaconda prompt, this helped sometimes, although still got failures occasionally running code in Jupyter:\n",
+ "`conda config --set ssl_verify false` \n",
+ "Another thing that helped was to add `verify=False` anytime where there is `request.get(..)`, so `request.get(url, headers=headers)` becomes `request.get(url, headers=headers, verify=False)`"
]
},
{
diff --git a/week2/day1.ipynb b/week2/day1.ipynb
index fdd4db1..3a7a79b 100644
--- a/week2/day1.ipynb
+++ b/week2/day1.ipynb
@@ -69,12 +69,19 @@
"For Anthropic, visit https://console.anthropic.com/ \n",
"For Google, visit https://ai.google.dev/gemini-api \n",
"\n",
+ "### Also - adding DeepSeek if you wish\n",
+ "\n",
+ "Optionally, if you'd like to also use DeepSeek, create an account [here](https://platform.deepseek.com/), create a key [here](https://platform.deepseek.com/api_keys) and top up with at least the minimum $2 [here](https://platform.deepseek.com/top_up).\n",
+ "\n",
+ "### Adding API keys to your .env file\n",
+ "\n",
"When you get your API keys, you need to set them as environment variables by adding them to your `.env` file.\n",
"\n",
"```\n",
"OPENAI_API_KEY=xxxx\n",
"ANTHROPIC_API_KEY=xxxx\n",
"GOOGLE_API_KEY=xxxx\n",
+ "DEEPSEEK_API_KEY=xxxx\n",
"```\n",
"\n",
"Afterwards, you may need to restart the Jupyter Lab Kernel (the Python process that sits behind this notebook) via the Kernel menu, and then rerun the cells from the top."
@@ -120,7 +127,7 @@
"# Load environment variables in a file called .env\n",
"# Print the key prefixes to help with any debugging\n",
"\n",
- "load_dotenv()\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",
@@ -350,6 +357,123 @@
"print(response.choices[0].message.content)"
]
},
+ {
+ "cell_type": "markdown",
+ "id": "33f70c88-7ca9-470b-ad55-d93a57dcc0ab",
+ "metadata": {},
+ "source": [
+ "## (Optional) Trying out the DeepSeek model\n",
+ "\n",
+ "### Let's ask DeepSeek a really hard question - both the Chat and the Reasoner model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3d0019fb-f6a8-45cb-962b-ef8bf7070d4d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Optionally if you wish to try DeekSeek, you can also use the OpenAI client library\n",
+ "\n",
+ "deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\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 - please skip to the next section if you don't wish to try the DeepSeek API\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c72c871e-68d6-4668-9c27-96d52b77b867",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Using DeepSeek Chat\n",
+ "\n",
+ "deepseek_via_openai_client = OpenAI(\n",
+ " api_key=deepseek_api_key, \n",
+ " base_url=\"https://api.deepseek.com\"\n",
+ ")\n",
+ "\n",
+ "response = deepseek_via_openai_client.chat.completions.create(\n",
+ " model=\"deepseek-chat\",\n",
+ " messages=prompts,\n",
+ ")\n",
+ "\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "50b6e70f-700a-46cf-942f-659101ffeceb",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "challenge = [{\"role\": \"system\", \"content\": \"You are a helpful assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"How many words are there in your answer to this prompt\"}]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "66d1151c-2015-4e37-80c8-16bc16367cfe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Using DeepSeek Chat with a harder question! And streaming results\n",
+ "\n",
+ "stream = deepseek_via_openai_client.chat.completions.create(\n",
+ " model=\"deepseek-chat\",\n",
+ " messages=challenge,\n",
+ " stream=True\n",
+ ")\n",
+ "\n",
+ "reply = \"\"\n",
+ "display_handle = display(Markdown(\"\"), display_id=True)\n",
+ "for chunk in stream:\n",
+ " reply += chunk.choices[0].delta.content or ''\n",
+ " reply = reply.replace(\"```\",\"\").replace(\"markdown\",\"\")\n",
+ " update_display(Markdown(reply), display_id=display_handle.display_id)\n",
+ "\n",
+ "print(\"Number of words:\", len(reply.split(\" \")))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "43a93f7d-9300-48cc-8c1a-ee67380db495",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Using DeepSeek Reasoner - this may hit an error if DeepSeek is busy\n",
+ "# It's over-subscribed (as of 28-Jan-2025) but should come back online soon!\n",
+ "# If this fails, come back to this in a few days..\n",
+ "\n",
+ "response = deepseek_via_openai_client.chat.completions.create(\n",
+ " model=\"deepseek-reasoner\",\n",
+ " messages=challenge\n",
+ ")\n",
+ "\n",
+ "reasoning_content = response.choices[0].message.reasoning_content\n",
+ "content = response.choices[0].message.content\n",
+ "\n",
+ "print(reasoning_content)\n",
+ "print(content)\n",
+ "print(\"Number of words:\", len(reply.split(\" \")))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c09e6b5c-6816-4cd3-a5cd-a20e4171b1a0",
+ "metadata": {},
+ "source": [
+ "## Back to OpenAI with a serious question"
+ ]
+ },
{
"cell_type": "code",
"execution_count": null,
diff --git a/week8/agents/frontier_agent.py b/week8/agents/frontier_agent.py
index dcbeefd..88e7fd4 100644
--- a/week8/agents/frontier_agent.py
+++ b/week8/agents/frontier_agent.py
@@ -23,11 +23,19 @@ class FrontierAgent(Agent):
def __init__(self, collection):
"""
- Set up this instance by connecting to OpenAI, to the Chroma Datastore,
+ Set up this instance by connecting to OpenAI or DeepSeek, to the Chroma Datastore,
And setting up the vector encoding model
"""
self.log("Initializing Frontier Agent")
- self.openai = OpenAI()
+ deepseek_api_key = os.getenv("DEEPSEEK_API_KEY")
+ if deepseek_api_key:
+ self.client = OpenAI(api_key=deepseek_api_key, base_url="https://api.deepseek.com")
+ self.MODEL = "deepseek-chat"
+ self.log("Frontier Agent is set up with DeepSeek")
+ else:
+ self.client = OpenAI()
+ self.MODEL = "gpt-4o-mini"
+ self.log("Frontier Agent is setting up with OpenAI")
self.collection = collection
self.model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
self.log("Frontier Agent is ready")
@@ -85,14 +93,14 @@ class FrontierAgent(Agent):
def price(self, description: str) -> float:
"""
- Make a call to OpenAI to estimate the price of the described product,
+ Make a call to OpenAI or DeepSeek to estimate the price of the described product,
by looking up 5 similar products and including them in the prompt to give context
:param description: a description of the product
:return: an estimate of the price
"""
documents, prices = self.find_similars(description)
- self.log("Frontier Agent is about to call OpenAI with context including 5 similar products")
- response = self.openai.chat.completions.create(
+ self.log(f"Frontier Agent is about to call {self.MODEL} with context including 5 similar products")
+ response = self.client.chat.completions.create(
model=self.MODEL,
messages=self.messages_for(description, documents, prices),
seed=42,
diff --git a/week8/day2.3.ipynb b/week8/day2.3.ipynb
index bb9a217..da6c3e3 100644
--- a/week8/day2.3.ipynb
+++ b/week8/day2.3.ipynb
@@ -209,7 +209,7 @@
"metadata": {},
"outputs": [],
"source": [
- "test[1].prompt"
+ "print(test[1].prompt)"
]
},
{
@@ -255,6 +255,16 @@
" return float(match.group()) if match else 0"
]
},
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "06743833-c362-47f8-b02a-139be2cd52ab",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "get_price(\"The price for this is $99.99\")"
+ ]
+ },
{
"cell_type": "code",
"execution_count": null,
@@ -306,6 +316,86 @@
"Tester.test(gpt_4o_mini_rag, test)"
]
},
+ {
+ "cell_type": "markdown",
+ "id": "d793c6d0-ce3f-4680-b37d-4643f0cd1d8e",
+ "metadata": {},
+ "source": [
+ "## Optional Extra: Trying a DeepSeek API call instead of OpenAI\n",
+ "\n",
+ "If you have a DeepSeek API key, we will use it here as an alternative implementation; otherwise skip to the next section.."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "21b6a22f-0195-47b6-8f6d-cab6ebe05742",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Connect to DeepSeek using the OpenAI client python library\n",
+ "\n",
+ "deepseek_api_key = os.getenv(\"DEEPSEEK_API_KEY\")\n",
+ "deepseek_via_openai_client = OpenAI(api_key=deepseek_api_key,base_url=\"https://api.deepseek.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ea7267d6-9489-4dac-a6e0-aec108e788c2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Added some retry logic here because DeepSeek is very oversubscribed and sometimes fails..\n",
+ "\n",
+ "def deepseek_api_rag(item):\n",
+ " documents, prices = find_similars(item)\n",
+ " retries = 8\n",
+ " done = False\n",
+ " while not done and retries > 0:\n",
+ " try:\n",
+ " response = deepseek_via_openai_client.chat.completions.create(\n",
+ " model=\"deepseek-chat\", \n",
+ " messages=messages_for(item, documents, prices),\n",
+ " seed=42,\n",
+ " max_tokens=8\n",
+ " )\n",
+ " reply = response.choices[0].message.content\n",
+ " done = True\n",
+ " except Exception as e:\n",
+ " print(f\"Error: {e}\")\n",
+ " retries -= 1\n",
+ " return get_price(reply)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6560faf2-4dec-41e5-95e2-b2c46cdb3ba8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "deepseek_api_rag(test[1])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0578b116-869f-429d-8382-701f1c0882f3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Tester.test(deepseek_api_rag, test)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6739870f-1eec-4547-965d-4b594e685697",
+ "metadata": {},
+ "source": [
+ "## And now to wrap this in an \"Agent\" class"
+ ]
+ },
{
"cell_type": "code",
"execution_count": null,
@@ -316,6 +406,20 @@
"from agents.frontier_agent import FrontierAgent"
]
},
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2efa7ba9-c2d7-4f95-8bb5-c4295bbeb01f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's print the logs so we can see what's going on\n",
+ "\n",
+ "import logging\n",
+ "root = logging.getLogger()\n",
+ "root.setLevel(logging.INFO)"
+ ]
+ },
{
"cell_type": "code",
"execution_count": null,
diff --git a/week8/day5.ipynb b/week8/day5.ipynb
index a1d8df2..22edec5 100644
--- a/week8/day5.ipynb
+++ b/week8/day5.ipynb
@@ -141,7 +141,9 @@
"source": [
"# Running the final product\n",
"\n",
- "## Just hit shift + enter in the next cell, and let the deals flow in!!"
+ "## Just hit shift + enter in the next cell, and let the deals flow in!!\n",
+ "\n",
+ "Note that the Frontier Agent will use DeepSeek if there's a DEEPSEEK_API_KEY in your .env file, otherwise gpt-4o-mini."
]
},
{
From b582e41ecf22647ce89f5fc3f3c492c2bb2f9156 Mon Sep 17 00:00:00 2001
From: Nicholas Arquette
Date: Tue, 28 Jan 2025 13:54:58 -0600
Subject: [PATCH 44/61] Feature: Added code and modules to create doc string
for any python code. It will read text from an existing python file and
output it to a new file with a suffix for the llm model that created it.
---
.../doc_string_exercise/README.md | 29 ++++
.../doc_string_exercise/data/original_file.py | 19 +++
.../generate_doc_string.py | 85 ++++++++++
.../doc_string_exercise/utils.py | 147 ++++++++++++++++++
4 files changed, 280 insertions(+)
create mode 100644 week4/community-contributions/doc_string_exercise/README.md
create mode 100644 week4/community-contributions/doc_string_exercise/data/original_file.py
create mode 100644 week4/community-contributions/doc_string_exercise/generate_doc_string.py
create mode 100644 week4/community-contributions/doc_string_exercise/utils.py
diff --git a/week4/community-contributions/doc_string_exercise/README.md b/week4/community-contributions/doc_string_exercise/README.md
new file mode 100644
index 0000000..80286b6
--- /dev/null
+++ b/week4/community-contributions/doc_string_exercise/README.md
@@ -0,0 +1,29 @@
+# Script Overview
+
+The documentation will show you how to run the python script generate_doc_string.py. It is designed to take input
+from an existing python file and create a new one with a suffix ('claude' or 'gpt'). If you do not specify and llm
+model, it will default to claude.
+
+# How to run
+
+```powershell
+conda activate llms
+cd
+python generate_doc_string -fp -llm
+```
+
+# Show Help Instructions
+
+```shell
+python generate_doc_string --help
+```
+
+# Error Checking
+
+1) File Path Existence
+
+If the file path doesn't exist, the script will stop running and print out an error.
+
+2) LLM Model Choice
+
+If you choose something other than 'gpt' or 'claude', it will show and assertion error.
\ No newline at end of file
diff --git a/week4/community-contributions/doc_string_exercise/data/original_file.py b/week4/community-contributions/doc_string_exercise/data/original_file.py
new file mode 100644
index 0000000..bdd1276
--- /dev/null
+++ b/week4/community-contributions/doc_string_exercise/data/original_file.py
@@ -0,0 +1,19 @@
+
+def calculate(iterations, param1, param2):
+ result = 1.0
+ for i in range(1, iterations+1):
+ j = i * param1 - param2
+ result -= (1/j)
+ j = i * param1 + param2
+ result += (1/j)
+ return result
+
+
+def calculate_2(iterations, param1, param2):
+ result = 1.0
+ for i in range(1, iterations+1):
+ j = i * param1 - param2
+ result -= (1/j)
+ j = i * param1 + param2
+ result += (1/j)
+ return result
\ No newline at end of file
diff --git a/week4/community-contributions/doc_string_exercise/generate_doc_string.py b/week4/community-contributions/doc_string_exercise/generate_doc_string.py
new file mode 100644
index 0000000..9acc8a1
--- /dev/null
+++ b/week4/community-contributions/doc_string_exercise/generate_doc_string.py
@@ -0,0 +1,85 @@
+from argparse import ArgumentParser
+import os
+from dotenv import load_dotenv
+from openai import OpenAI
+import anthropic
+from utils import add_doc_string, Model, get_system_message
+from pathlib import Path
+
+
+def main():
+
+ # get run time arguments
+ parser = ArgumentParser(
+ prog='Generate Doc String for an existing functions',
+ description='Run Doc String for a given file and model',
+ )
+ parser.add_argument(
+ '-fp',
+ '--file_path',
+ help='Enter the file path to the script that will be updated with doc strings',
+ default=None
+ )
+ parser.add_argument(
+ '-llm',
+ '--llm_model',
+ help='Choose the LLM model that will create the doc strings',
+ default='claude'
+ )
+
+ # get run time arguments
+ args = parser.parse_args()
+ file_path = Path(args.file_path)
+ llm_model = args.llm_model
+
+ # check for file path
+ assert file_path.exists(), f"File Path {str(file_path.as_posix())} doesn't exist. Please try again."
+
+ # check for value llm values
+ assert llm_model in ['gpt', 'claude'], (f"Invalid model chosen '{llm_model}'. "
+ f"Please choose a valid model ('gpt' or 'claude')")
+
+ # load keys and environment variables
+ load_dotenv()
+ os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')
+ os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')
+ os.environ['HF_TOKEN'] = os.getenv('HF_INF_TOKEN', 'your-key-if-not-using-env')
+
+ # get system messages
+ system_message = get_system_message()
+
+ # get model info
+ model_info = {
+ 'gpt': {
+ 'client': OpenAI(),
+ 'model': Model.OPENAI_MODEL.value,
+ },
+ 'claude': {
+ 'client': anthropic.Anthropic(),
+ 'model': Model.CLAUDE_MODEL.value
+ }
+ }
+
+ # add standard argumens
+ model_info[llm_model].update(
+ {
+ 'file_path': file_path,
+ 'system_message': system_message
+ }
+ )
+
+ # convert python code to c++ code using open ai
+ print(f"\nSTARTED | Doc Strings Using {llm_model.upper()} for file {str(file_path)}\n\n")
+ add_doc_string(**model_info[llm_model])
+ print(f"\nFINISHED | Doc Strings Using {llm_model.upper()} for file {str(file_path)}\n\n")
+
+
+if __name__ == '__main__':
+
+ main()
+
+
+
+
+
+
diff --git a/week4/community-contributions/doc_string_exercise/utils.py b/week4/community-contributions/doc_string_exercise/utils.py
new file mode 100644
index 0000000..e45bcb4
--- /dev/null
+++ b/week4/community-contributions/doc_string_exercise/utils.py
@@ -0,0 +1,147 @@
+from enum import Enum
+from pathlib import Path
+
+
+class Model(Enum):
+ """
+ Enumeration of supported AI models.
+ """
+ OPENAI_MODEL = "gpt-4o"
+ CLAUDE_MODEL = "claude-3-5-sonnet-20240620"
+
+
+def get_system_message() -> str:
+ """
+ Generate a system message for AI assistants creating docstrings.
+
+ :return: A string containing instructions for the AI assistant.
+ :rtype: str
+ """
+ system_message = "You are an assistant that creates doc strings in reStructure Text format for an existing python function. "
+ system_message += "Respond only with an updated python function; use comments sparingly and do not provide any explanation other than occasional comments. "
+ system_message += "Be sure to include typing annotation for each function argument or key word argument and return object types."
+
+ return system_message
+
+
+def user_prompt_for(python: str) -> str:
+ """
+ Generate a user prompt for rewriting Python functions with docstrings.
+
+ :param python: The Python code to be rewritten.
+ :type python: str
+ :return: A string containing the user prompt and the Python code.
+ :rtype: str
+ """
+ user_prompt = "Rewrite this Python function with doc strings in the reStructuredText style."
+ user_prompt += "Respond only with python code; do not explain your work other than a few comments. "
+ user_prompt += "Be sure to write a description of the function purpose with typing for each argument and return\n\n"
+ user_prompt += python
+ return user_prompt
+
+
+def messages_for(python: str, system_message: str) -> list:
+ """
+ Create a list of messages for the AI model.
+
+ :param python: The Python code to be processed.
+ :type python: str
+ :param system_message: The system message for the AI assistant.
+ :type system_message: str
+ :return: A list of dictionaries containing role and content for each message.
+ :rtype: list
+ """
+ return [
+ {"role": "system", "content": system_message},
+ {"role": "user", "content": user_prompt_for(python)}
+ ]
+
+
+def write_output(output: str, file_suffix: str, file_path: Path) -> None:
+ """
+ Write the processed output to a file.
+
+ :param output: The processed Python code with docstrings.
+ :type output: str
+ :param file_suffix: The suffix to be added to the output file name.
+ :type file_suffix: str
+ :param file_path: The path of the input file.
+ :type file_path: Path
+ :return: None
+ """
+ code = output.replace("", "").replace("", "")
+ out_file = file_path.with_name(f"{file_path.stem}{file_suffix if file_suffix else ''}.py")
+ out_file.write_text(code)
+
+
+def add_doc_string(client: object, system_message: str, file_path: Path, model: str) -> None:
+ """
+ Add docstrings to a Python file using the specified AI model.
+
+ :param client: The AI client object.
+ :type client: object
+ :param system_message: The system message for the AI assistant.
+ :type system_message: str
+ :param file_path: The path of the input Python file.
+ :type file_path: Path
+ :param model: The AI model to be used.
+ :type model: str
+ :return: None
+ """
+ if 'gpt' in model:
+ add_doc_string_gpt(client=client, system_message=system_message, file_path=file_path, model=model)
+ else:
+ add_doc_string_claude(client=client, system_message=system_message, file_path=file_path, model=model)
+
+
+def add_doc_string_gpt(client: object, system_message: str, file_path: Path, model: str = 'gpt-4o') -> None:
+ """
+ Add docstrings to a Python file using GPT model.
+
+ :param client: The OpenAI client object.
+ :type client: object
+ :param system_message: The system message for the AI assistant.
+ :type system_message: str
+ :param file_path: The path of the input Python file.
+ :type file_path: Path
+ :param model: The GPT model to be used, defaults to 'gpt-4o'.
+ :type model: str
+ :return: None
+ """
+ code_text = file_path.read_text(encoding='utf-8')
+ stream = client.chat.completions.create(model=model, messages=messages_for(code_text, system_message), stream=True)
+ reply = ""
+ for chunk in stream:
+ fragment = chunk.choices[0].delta.content or ""
+ reply += fragment
+ print(fragment, end='', flush=True)
+ write_output(reply, file_suffix='_gpt', file_path=file_path)
+
+
+def add_doc_string_claude(client: object, system_message: str, file_path: Path, model: str = 'claude-3-5-sonnet-20240620') -> None:
+ """
+ Add docstrings to a Python file using Claude model.
+
+ :param client: The Anthropic client object.
+ :type client: object
+ :param system_message: The system message for the AI assistant.
+ :type system_message: str
+ :param file_path: The path of the input Python file.
+ :type file_path: Path
+ :param model: The Claude model to be used, defaults to 'claude-3-5-sonnet-20240620'.
+ :type model: str
+ :return: None
+ """
+ code_text = file_path.read_text(encoding='utf-8')
+ result = client.messages.stream(
+ model=model,
+ max_tokens=2000,
+ system=system_message,
+ messages=[{"role": "user", "content": user_prompt_for(code_text)}],
+ )
+ reply = ""
+ with result as stream:
+ for text in stream.text_stream:
+ reply += text
+ print(text, end="", flush=True)
+ write_output(reply, file_suffix='_claude', file_path=file_path)
\ No newline at end of file
From e84a615ebc3e5e817e97c33e72eab26b82fae359 Mon Sep 17 00:00:00 2001
From: esarijal
Date: Wed, 29 Jan 2025 16:11:49 +0700
Subject: [PATCH 45/61] Add contributions for day1 and day2 in
community-contributions
---
.../day1-email-reviewer-in-Bahasa.ipynb | 127 ++++++++++++++++++
.../day2-exercise.ipynb | 93 +++++++++++++
2 files changed, 220 insertions(+)
create mode 100644 week1/community-contributions/day1-email-reviewer-in-Bahasa.ipynb
create mode 100644 week1/community-contributions/day2-exercise.ipynb
diff --git a/week1/community-contributions/day1-email-reviewer-in-Bahasa.ipynb b/week1/community-contributions/day1-email-reviewer-in-Bahasa.ipynb
new file mode 100644
index 0000000..6b3f8bd
--- /dev/null
+++ b/week1/community-contributions/day1-email-reviewer-in-Bahasa.ipynb
@@ -0,0 +1,127 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0ee39d65-f27d-416d-8b46-43d15aebe752",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Below is a sample for email reviewer using Bahasa Indonesia. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f9fd62af-9b14-490b-8d0b-990da96101bf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"Anda adalah seorang Asisten untuk menganalisa email berdasarkan user prompt yang nanti akan diberikan. Summarize the email and give me a tone about that email\"\n",
+ "user_prompt = \"\"\"\n",
+ " Subject: Permintaan Pertemuan\n",
+ "\n",
+ "Yang terhormat Bapak Rijal,\n",
+ "\n",
+ "Saya ingin meminta waktu Anda untuk membahas Generative AI untuk bisnis. Apakah Anda tersedia pada besok pukul 19:00? \n",
+ "Jika tidak, mohon beri tahu waktu yang lebih sesuai bagi Anda.\n",
+ "\n",
+ "Terima kasih atas perhatian Anda.\n",
+ "\n",
+ "Salam,\n",
+ "\n",
+ "Mentari\n",
+ "\"\"\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt}\n",
+ " ] # fill this in\n",
+ "\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "response = openai.chat.completions.create(\n",
+ " model = \"gpt-4o-mini\",\n",
+ " messages = messages\n",
+ " )\n",
+ "\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d10208fa-02d8-41a0-b9bb-0bf30f237f25",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"Anda adalah seorang Asisten untuk menganalisa email berdasarkan user prompt yang nanti akan diberikan. Summarize the email and give me a tone about that email\"\n",
+ "user_prompt = \"\"\"\n",
+ " Subject: Feedback terkait Bapak\n",
+ "\n",
+ "Yang terhormat Bapak Rijal,\n",
+ "\n",
+ "Saya ingin memberikan sedikit feedback untuk BBapak.\n",
+ "\n",
+ "Kemampuan Anda dalam memimpin tim ini mampu membawa saya dan rekan lainnya untuk mengerahkan semua kemampuan saya agar jadi lebih baik.\n",
+ "Selama ini saya cukup senang bekerja dengan Anda karena memberikan saya peluang untuk mencoba banyak hal baru. Tapi ada beberapa kekhawatiran yang mau saya sampaikan, terutama terkait target yang perlu dicapai oleh tim. Saya pikir melihat performa ke belakang, target yang ditentukan harus lebih realistis lagi.\n",
+ "Saya beruntung bisa berkesempatan bekerja dengan Anda sehingga banyak ilmu yang saya dapat. Kira-kira untuk ke depannya, hal apa lagi yang bisa tim ini tingkatkan agar kita bisa mencapai target yang lebih baik?\n",
+ "Selama ini, banyak terjadi miskomunikasi dalam pekerjaan. Dan menurut saya salah satunya karena arahan yang Anda berikan kurang jelas dan kurang ditangkap sepenuhnya oleh anggota yang lain. Saya dan tim berharap ke depan bisa mendapatkan arahan yang lebih jelas dan satu arah.\n",
+ "\n",
+ "Terima kasih atas perhatian Anda.\n",
+ "\n",
+ "Salam,\n",
+ "\n",
+ "Mentari\n",
+ "\"\"\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt}\n",
+ " ] # fill this in\n",
+ "\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "response = openai.chat.completions.create(\n",
+ " model = \"gpt-4o-mini\",\n",
+ " messages = messages\n",
+ " )\n",
+ "\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "print(response.choices[0].message.content)"
+ ]
+ }
+ ],
+ "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
+}
diff --git a/week1/community-contributions/day2-exercise.ipynb b/week1/community-contributions/day2-exercise.ipynb
new file mode 100644
index 0000000..515ad77
--- /dev/null
+++ b/week1/community-contributions/day2-exercise.ipynb
@@ -0,0 +1,93 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "fa4447be-7825-45d9-a6a5-ed41f2500533",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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",
+ "\n",
+ "openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n",
+ "MODEL = \"llama3.2\"\n",
+ "\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\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",
+ "\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; 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",
+ "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",
+ "def messages_for(website):\n",
+ " return [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt_for(website)}\n",
+ " ] \n",
+ "\n",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " response = openai.chat.completions.create(\n",
+ " model = MODEL,\n",
+ " messages = messages_for(website)\n",
+ " )\n",
+ " return response.choices[0].message.content\n",
+ "\n",
+ "def display_summary(url):\n",
+ " summary = summarize(url)\n",
+ " display(Markdown(summary))\n",
+ "\n",
+ "\n",
+ "display_summary(\"https://esarijal.my.id\")"
+ ]
+ }
+ ],
+ "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
+}
From 919fb7cda4ff50605a6dd0a5e7878dfdfb1d3f8d Mon Sep 17 00:00:00 2001
From: Divyesh Vasani
Date: Wed, 29 Jan 2025 12:40:14 +0530
Subject: [PATCH 46/61] Add contributions to community-contributions
---
...hallenge_Career_Well_Being_Companion.ipynb | 408 ++++++++++++++++++
1 file changed, 408 insertions(+)
create mode 100644 week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb
diff --git a/week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb b/week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb
new file mode 100644
index 0000000..ddfad7e
--- /dev/null
+++ b/week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb
@@ -0,0 +1,408 @@
+{
+ "cells": [
+ {
+ "cell_type": "raw",
+ "id": "f64407a0-fda5-48f3-a2d3-82e80d320931",
+ "metadata": {},
+ "source": [
+ "### \"Career Well-Being Companion\" ###\n",
+ "This project will gather feelings at the end of day from employee.\n",
+ "Based on employee feelings provided as input, model will analyze feelings and provide suggestions and acknowledge with feelings employtee is going thru.\n",
+ "Model even will ask employee \"Do you want more detailed resposne to cope up with your feelings?\".\n",
+ "If employee agrees, model even replies with online courses, tools, meetups and other ideas for the well being of the employee.\n",
+ "\n",
+ "Immediate Impact: Professionals can quickly see value through insights or actionable suggestions.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2b30a8fa-1067-4369-82fc-edb197551e43",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "### Step 1: Emotional Check-in:\n",
+ "\n",
+ "# Input: User describes their feelings or workday.\n",
+ "# LLM Task: Analyze the input for emotional tone and identify keywords (e.g., \"stress,\" \"boredom\").\n",
+ "# Output: A summary of emotional trends.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2b52469e-da81-42ec-9e6c-0c121ad349a7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"I am your well being companion and end goal is to help you in your career.\\nI want to start by asking about your feelings, how was your day today.\\n\")\n",
+ "print(\"I will do my best as well being companion to analyze your day and come up with the suggestions that might help you in your career and life. \\n\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a6df2e2c-785d-4323-90f4-b49592ab33fc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "how_was_day = \"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "247e4a80-f634-4a7a-9f40-315f042be59c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "how_was_day = input(\"How was your day today,can you describe about your day, what went well, what did not go well, what you did not like :\\n\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0faac2dd-0d53-431a-87a7-d57a6881e043",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "what_went_well = input(\"What went well for you , today?\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2c11628b-d14b-47eb-a97e-70d08ddf3364",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "what_went_bad = input(\"What did not go well, today?\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f64e34b4-f83a-4ae4-86bb-5bd164121412",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "how_was_day = how_was_day + what_went_well + what_went_bad\n",
+ "print(how_was_day)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c5fe08c4-4d21-4917-a556-89648eb543c7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from openai import OpenAI\n",
+ "from dotenv import load_dotenv\n",
+ "import json\n",
+ "from IPython.display import Markdown, display, update_display"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d6875d51-f33b-462e-85cb-a5d6a7cfb86e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "#Initialize environment and constants:\n",
+ "load_dotenv(override=True)\n",
+ "\n",
+ "api_key = os.getenv('OPENAI_API_KEY')\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": "c12cf934-4bd4-4849-9e8f-5bb89eece996",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "### Step 2: From day spent and what went good, what went bad ==> LLM will extract feelings, emotions from those unspoken words :)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "237d14b3-571e-4598-a57b-d3ebeaf81afc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_prompt_for_emotion_check_in = \"You are a career well-being assistant. Your task is to analyze the user's emotional state based on their text input.\"\\\n",
+ "\"Look for signs of stress, burnout, dissatisfaction, boredom, motivation, or any other emotional indicators related to work.\"\\\n",
+ "\"Based on the input, provide a summary of the user's feelings and categorize them under relevant emotional states (e.g., ‘Burnout,’ ‘Boredom,’ ‘Stress,’ ‘Satisfaction,’ etc.).\"\\\n",
+ "\"Your response should be empathetic and non-judgmental. Please summarize the list of feelings, emotions , those unspoken but unheard feelings you get it.\\n\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a205a6d3-b0d7-4fcb-9eed-f3a86576cd9f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def get_feelings(how_was_day):\n",
+ " response = openai.chat.completions.create(\n",
+ " model=MODEL,\n",
+ " messages = [\n",
+ " {'role':'system','content': system_prompt_for_emotion_check_in},\n",
+ " {'role':'user', 'content': how_was_day}\n",
+ " ]\n",
+ " )\n",
+ " result = response.choices[0].message.content\n",
+ " return result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "45e152c8-37c4-4818-a8a0-49f1ea3c1b65",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "## LLM will give the feelings you have based on \"the day you had today\".\n",
+ "print(get_feelings(how_was_day))\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4a62a385-4c51-42b1-ad73-73949e740e66",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "### Step 3: From those feelings, emotions ==> Get suggestions from LLM."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d856ca4f-ade9-4e6f-b540-2d07a70867c7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "## Lets construct system prompt for LLM to get suggestions (from these feelings above).\n",
+ "\n",
+ "system_prompt_for_suggestion =\"You are a career well-being assistant.Provide a list of practical,actionable suggestions to help them improve their emotional state.\"\n",
+ "\n",
+ "system_prompt_for_suggestion+=\"The suggestions should be personalized based on their current feelings, and they should be simple, effective actions the user can take immediately.\"\\\n",
+ "\"Include activities, tasks, habits, or approaches that will either alleviate stress, boost motivation, or help them reconnect with their work in a positive way.\"\\\n",
+ "\"Be empathetic, non-judgmental, and encouraging in your tone.\\n\"\n",
+ "system_prompt_for_suggestion += \"Request you to respond in JSON format. Below is example:\\n\"\n",
+ "system_prompt_for_suggestion += '''\n",
+ "{\n",
+ " \"suggestions\": [\n",
+ " {\n",
+ " \"action\": \"Take a short break\",\n",
+ " \"description\": \"Step away from your workspace for 5-10 minutes. Use this time to take deep breaths, stretch, or grab a drink. This mini-break can help clear your mind and reduce feelings of overwhelm.\"\n",
+ " },\n",
+ " {\n",
+ " \"action\": \"Write a quick journal entry\",\n",
+ " \"description\": \"Spend 5-10 minutes writing down your thoughts and feelings. Specify what's distracting you and what you appreciate about your personal life. This can help you process emotions and refocus on tasks.\"\n",
+ " },\n",
+ " {\n",
+ " \"action\": \"Set a small task goal\",\n",
+ " \"description\": \"Choose one manageable task to complete today. Break it down into smaller steps to make it less daunting. Completing even a small task can give you a sense of achievement and boost motivation.\"\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "'''\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e9eee380-7fa5-4d21-9357-f4fc34d3368d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "## Lets build user prompt to ask LLM for the suggestions based on the feelings above.\n",
+ "## Note: Here while building user_prompt, we are making another LLM call (via function get_feelings() to get feelings analyzed from \"day spent\".\n",
+ "## Because first step is to get feelings from day spent then we move to offer suggestions to ease discomfort feelings.\n",
+ "\n",
+ "def get_user_prompt_for_suggestion(how_was_day):\n",
+ " user_prompt_for_suggestion = \"You are a career well-being assistant.Please see below user’s emotional input on 'day user had spent' and this user input might have feeling burnt out, bored, uninspired, or stressed or sometime opposite \"\\\n",
+ " \"of these feelings.\"\n",
+ " user_prompt_for_suggestion += f\"{get_feelings(how_was_day)}\"\n",
+ " return user_prompt_for_suggestion\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3576e451-b29c-44e1-bcdb-addc8d61afa7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(get_user_prompt_for_suggestion(how_was_day))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4a41ee40-1f49-4474-809f-a0d5e44e4aa4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def get_suggestions(how_was_day):\n",
+ " response = openai.chat.completions.create(\n",
+ " model=MODEL,\n",
+ " messages = [\n",
+ " {'role': 'system', 'content':system_prompt_for_suggestion},\n",
+ " {'role': 'user', 'content': get_user_prompt_for_suggestion(how_was_day)}\n",
+ " ],\n",
+ " response_format={\"type\": \"json_object\"}\n",
+ " )\n",
+ " result = response.choices[0].message.content\n",
+ " return json.loads(result)\n",
+ " #display(Markdown(result))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "33e3a14e-0e2c-43cb-b50b-d6df52b4d300",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "suggestions = get_suggestions(how_was_day)\n",
+ "print(suggestions)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "31c75e04-2800-4ba2-845b-bc38f8965622",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "### Step 4: From those suggestions from companion ==> Enhance with support you need to follow sugestions like action plan for your self."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d07f9d3f-5acf-4a86-9160-4c6de8df4eb0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_prompt_for_enhanced_suggestions = \"You are a helpful assistant that enhances actionable suggestions for users. For each suggestion provided, enhance it by adding:\\n\"\\\n",
+ "\"1. A step-by-step guide for implementation.\"\\\n",
+ "\"2. Tools, resources, or apps that can help.\"\\\n",
+ "\"3. Examples or additional context to make the suggestion practical.\"\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6ab449f1-7a6c-4982-99e0-83d99c45ad2d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def get_user_prompt_for_enhanced_suggestions(suggestions):\n",
+ " prompt = \"You are able to check below suggestions and can enhance to help end user. Below is the list of suggestions.\\n\"\n",
+ " prompt += f\"{suggestions}\"\n",
+ " return prompt"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d5187b7a-d8cd-4377-b011-7805bd50443d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def enhance_suggestions(suggestions):\n",
+ " stream = openai.chat.completions.create(\n",
+ " model = MODEL,\n",
+ " messages=[\n",
+ " {'role':'system', 'content':system_prompt_for_enhanced_suggestions},\n",
+ " {'role':'user', 'content':get_user_prompt_for_enhanced_suggestions(suggestions)}\n",
+ " ],\n",
+ " stream = True\n",
+ " )\n",
+ " \n",
+ " #result = response.choices[0].message.content\n",
+ " #for chunk in stream:\n",
+ " # print(chunk.choices[0].delta.content or '', end='')\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",
+ " \n",
+ " #display(Markdown(result))\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "429cd6f8-3215-4140-9a6d-82d14a9b9798",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "detailed = input(\"\\nWould you like a DETAILED PLAN for implementing this suggestion?(Yes/ No)\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "5efda045-5bde-4c51-bec6-95b5914102dd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if detailed.lower() == 'yes':\n",
+ " enhance_suggestions(suggestions)\n",
+ "else:\n",
+ " print(suggestions)\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1969b2ec-c850-4dfc-b790-8ae8e3fa36e9",
+ "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
+}
From cb785572146cabdb54ca75b4760ebfdd05b00cb4 Mon Sep 17 00:00:00 2001
From: Divyesh Vasani
Date: Wed, 29 Jan 2025 17:51:56 +0530
Subject: [PATCH 47/61] Add contributions to community-contributions
---
.../Week1_Challenge_Career_Well_Being_Companion.ipynb | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb b/week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb
index ddfad7e..e2cfc39 100644
--- a/week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb
+++ b/week1/community-contributions/Week1_Challenge_Career_Well_Being_Companion.ipynb
@@ -127,12 +127,12 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 1,
"id": "c12cf934-4bd4-4849-9e8f-5bb89eece996",
"metadata": {},
"outputs": [],
"source": [
- "### Step 2: From day spent and what went good, what went bad ==> LLM will extract feelings, emotions from those unspoken words :)"
+ "### Step 2: From day spent and what went good, what went bad => LLM will extract feelings, emotions from those unspoken words :)"
]
},
{
From a6c7e8cc4d97554de9d55ef2f5eb5a705b1d5ba0 Mon Sep 17 00:00:00 2001
From: Maximiliano Gandini <102678264+MaxGandini@users.noreply.github.com>
Date: Wed, 29 Jan 2025 13:55:22 -0300
Subject: [PATCH 48/61] Update SETUP-linux.md
This is a little extra for the pip method using distributions such as arch. This should come in handy for someone that is using rolling release distributions as generally dependencies are broken and troubleshooting takes a long time when done alone.
---
SETUP-linux.md | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/SETUP-linux.md b/SETUP-linux.md
index 6806510..465c93d 100644
--- a/SETUP-linux.md
+++ b/SETUP-linux.md
@@ -103,6 +103,24 @@ Run: `python -m pip install --upgrade pip` followed by `pip install -r requireme
If issues occur, try the fallback:
`pip install --retries 5 --timeout 15 --no-cache-dir --force-reinstall -r requirements.txt`
+###### Arch users:
+
+Some updates break dependencies. Most notably, numpy, scipy and gensim. To troubleshoot this, you can try many commands:
+
+`sudo pacman -S python-numpy python-pandas python-scipy` This is not recommended, as pacman has no integration with pip (as far as I know)
+
+Another possible solution if having build conflicts, is to update:
+
+`sudo pacman -S gcc gcc-fortran python-setuptools python-wheel`
+
+*Note:* gensim is broken if you have an updated version of scipy. You can either pin scipy to an older version, or
+erase gensim from the requirements.txt for the moment. (See: https://aur.archlinux.org/packages/python-gensim)
+
+Lastly, so that the kernel is visible after step (6) in jupyter lab :
+`python -m ipykernel install --user --name=llmenv`
+`ipython kernel install --user --name=llmenv`
+
+
6. **Start Jupyter Lab:**
From the `llm_engineering` folder, run: `jupyter lab`.
From befc4ba10c8ea570901d12bba9d16d7501171c8a Mon Sep 17 00:00:00 2001
From: sparsh_thakur <113547853+skullemote@users.noreply.github.com>
Date: Wed, 29 Jan 2025 23:29:31 +0530
Subject: [PATCH 49/61] Added my contributions to community-contributions
---
...1_industrial_product_recommendaitons.ipynb | 580 ++++++++++++++++++
1 file changed, 580 insertions(+)
create mode 100644 week1/community-contributions/day1_industrial_product_recommendaitons.ipynb
diff --git a/week1/community-contributions/day1_industrial_product_recommendaitons.ipynb b/week1/community-contributions/day1_industrial_product_recommendaitons.ipynb
new file mode 100644
index 0000000..c45f437
--- /dev/null
+++ b/week1/community-contributions/day1_industrial_product_recommendaitons.ipynb
@@ -0,0 +1,580 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "d15d8294-3328-4e07-ad16-8a03e9bbfdb9",
+ "metadata": {},
+ "source": [
+ "# Instant Gratification\n",
+ "\n",
+ "## Your first Frontier LLM Project!\n",
+ "\n",
+ "Let's build a useful LLM solution - in a matter of minutes.\n",
+ "\n",
+ "By the end of this course, you will have built an autonomous Agentic AI solution with 7 agents that collaborate to solve a business problem. All in good time! We will start with something smaller...\n",
+ "\n",
+ "Our goal is to code a new kind of Web Browser. Give it a URL, and it will respond with a summary. The Reader's Digest of the internet!!\n",
+ "\n",
+ "Before starting, you should have completed the setup for [PC](../SETUP-PC.md) or [Mac](../SETUP-mac.md) and you hopefully launched this jupyter lab from within the project root directory, with your environment activated.\n",
+ "\n",
+ "## If you're new to Jupyter Lab\n",
+ "\n",
+ "Welcome to the wonderful world of Data Science experimentation! Once you've used Jupyter Lab, you'll wonder how you ever lived without it. Simply click in each \"cell\" with code in it, such as the cell immediately below this text, and hit Shift+Return to execute that cell. As you wish, you can add a cell with the + button in the toolbar, and print values of variables, or try out variations. \n",
+ "\n",
+ "I've written a notebook called [Guide to Jupyter](Guide%20to%20Jupyter.ipynb) to help you get more familiar with Jupyter Labs, including adding Markdown comments, using `!` to run shell commands, and `tqdm` to show progress.\n",
+ "\n",
+ "## If you'd prefer to work in IDEs\n",
+ "\n",
+ "If you're more comfortable in IDEs like VSCode or Pycharm, they both work great with these lab notebooks too. \n",
+ "If you'd prefer to work in VSCode, [here](https://chatgpt.com/share/676f2e19-c228-8012-9911-6ca42f8ed766) are instructions from an AI friend on how to configure it for the course.\n",
+ "\n",
+ "## If you'd like to brush up your Python\n",
+ "\n",
+ "I've added a notebook called [Intermediate Python](Intermediate%20Python.ipynb) to get you up to speed. But you should give it a miss if you already have a good idea what this code does: \n",
+ "`yield from {book.get(\"author\") for book in books if book.get(\"author\")}`\n",
+ "\n",
+ "## I am here to help\n",
+ "\n",
+ "If you have any problems at all, please do reach out. \n",
+ "I'm available through the platform, or at ed@edwarddonner.com, or at https://www.linkedin.com/in/eddonner/ if you'd like to connect (and I love connecting!)\n",
+ "\n",
+ "## More troubleshooting\n",
+ "\n",
+ "Please see the [troubleshooting](troubleshooting.ipynb) notebook in this folder to diagnose and fix common problems. At the very end of it is a diagnostics script with some useful debug info.\n",
+ "\n",
+ "## If this is old hat!\n",
+ "\n",
+ "If you're already comfortable with today's material, please hang in there; you can move swiftly through the first few labs - we will get much more in depth as the weeks progress.\n",
+ "\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Please read - important note\n",
+ " The way I collaborate with you may be different to other courses you've taken. I prefer not to type code while you watch. Rather, I execute Jupyter Labs, like this, and give you an intuition for what's going on. My suggestion is that you do this with me, either at the same time, or (perhaps better) right afterwards. Add print statements to understand what's going on, and then come up with your own variations. If you have a Github account, use this to showcase your variations. Not only is this essential practice, but it demonstrates your skills to others, including perhaps future clients or employers...\n",
+ " | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Business value of these exercises\n",
+ " A final thought. While I've designed these notebooks to be educational, I've also tried to make them enjoyable. We'll do fun things like have LLMs tell jokes and argue with each other. But fundamentally, my goal is to teach skills you can apply in business. I'll explain business implications as we go, and it's worth keeping this in mind: as you build experience with models and techniques, think of ways you could put this into action at work today. Please do contact me if you'd like to discuss more or if you have ideas to bounce off me.\n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
+ "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",
+ "\n",
+ "# If you get an error running this cell, then please head over to the troubleshooting notebook!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6900b2a8-6384-4316-8aaa-5e519fca4254",
+ "metadata": {},
+ "source": [
+ "# Connecting to OpenAI\n",
+ "\n",
+ "The next cell is where we load in the environment variables in your `.env` file and connect to OpenAI.\n",
+ "\n",
+ "## Troubleshooting if you have problems:\n",
+ "\n",
+ "Head over to the [troubleshooting](troubleshooting.ipynb) notebook in this folder for step by step code to identify the root cause and fix it!\n",
+ "\n",
+ "If you make a change, try restarting the \"Kernel\" (the python process sitting behind this notebook) by Kernel menu >> Restart Kernel and Clear Outputs of All Cells. Then try this notebook again, starting at the top.\n",
+ "\n",
+ "Or, contact me! Message me or email ed@edwarddonner.com and we will get this to work.\n",
+ "\n",
+ "Any concerns about API costs? See my notes in the README - costs should be minimal, and you can control it at every point. You can also use Ollama as a free alternative, which we discuss during Day 2."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
+ "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!\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3",
+ "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 in this folder for full instructions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "442fc84b-0815-4f40-99ab-d9a5da6bda91",
+ "metadata": {},
+ "source": [
+ "# Let's make a quick call to a Frontier model to get started, as a preview!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a58394bf-1e45-46af-9bfd-01e24da6f49a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To give you a preview -- calling OpenAI with these messages is this easy. Any problems, head over to the Troubleshooting notebook.\n",
+ "\n",
+ "message = \"Hello, GPT! This is my first ever message to you! Hi!\"\n",
+ "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=[{\"role\":\"user\", \"content\":message}])\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2aa190e5-cb31-456a-96cc-db109919cd78",
+ "metadata": {},
+ "source": [
+ "## OK onwards with our first project"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c5e793b2-6775-426a-a139-4848291d0463",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A class to represent a Webpage\n",
+ "# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\n",
+ " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
+ " irrelevant.decompose()\n",
+ " self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's try one out. Change the website and add print statements to follow along.\n",
+ "\n",
+ "ed = Website(\"https://edwarddonner.com\")\n",
+ "print(ed.title)\n",
+ "print(ed.text)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a478a0c-2c53-48ff-869c-4d08199931e1",
+ "metadata": {},
+ "source": [
+ "## Types of prompts\n",
+ "\n",
+ "You may know this already - but if not, you will get very familiar with it!\n",
+ "\n",
+ "Models like GPT4o have been trained to receive instructions in a particular way.\n",
+ "\n",
+ "They expect to receive:\n",
+ "\n",
+ "**A system prompt** that tells them what task they are performing and what tone they should use\n",
+ "\n",
+ "**A user prompt** -- the conversation starter that they should reply to"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "abdb8417-c5dc-44bc-9bee-2e059d162699",
+ "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.\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f0275b1b-7cfe-4f9d-abfa-7650d378da0c",
+ "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 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"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "26448ec4-5c00-4204-baec-7df91d11ff2e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(user_prompt_for(ed))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ea211b5f-28e1-4a86-8e52-c0b7677cadcc",
+ "metadata": {},
+ "source": [
+ "## Messages\n",
+ "\n",
+ "The API from OpenAI expects to receive messages in a particular structure.\n",
+ "Many of the other APIs share this structure:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message goes here\"},\n",
+ " {\"role\": \"user\", \"content\": \"user message goes here\"}\n",
+ "]\n",
+ "\n",
+ "To give you a preview, the next 2 cells make a rather simple call - we won't stretch the might GPT (yet!)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "21ed95c5-7001-47de-a36d-1d6673b403ce",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To give you a preview -- calling OpenAI with system and user messages:\n",
+ "\n",
+ "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d06e8d78-ce4c-4b05-aa8e-17050c82bb47",
+ "metadata": {},
+ "source": [
+ "## And now let's build useful messages for GPT-4o-mini, using a function"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0134dfa4-8299-48b5-b444-f2a8c3403c88",
+ "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": "36478464-39ee-485c-9f3f-6a4e458dbc9c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Try this out, and then try for a few more websites\n",
+ "\n",
+ "messages_for(ed)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "16f49d46-bf55-4c3e-928f-68fc0bf715b0",
+ "metadata": {},
+ "source": [
+ "## Time to bring it together - the API for OpenAI is very simple!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "905b9919-aba7-45b5-ae65-81b3d1d78e34",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# And now: call the OpenAI API. You will get very familiar with this!\n",
+ "\n",
+ "def summarize(url):\n",
+ " website = Website(url)\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": "05e38d41-dfa4-4b20-9c96-c46ea75d9fb5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "summarize(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3d926d59-450e-4609-92ba-2d6f244f1342",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A function to display this nicely in the Jupyter output, using markdown\n",
+ "\n",
+ "def display_summary(url):\n",
+ " summary = summarize(url)\n",
+ " display(Markdown(summary))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3018853a-445f-41ff-9560-d925d1774b2f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b3bcf6f4-adce-45e9-97ad-d9a5d7a3a624",
+ "metadata": {},
+ "source": [
+ "# Let's try more websites\n",
+ "\n",
+ "Note that this will only work on websites that can be scraped using this simplistic approach.\n",
+ "\n",
+ "Websites that are rendered with Javascript, like React apps, won't show up. See the community-contributions folder for a Selenium implementation that gets around this. You'll need to read up on installing Selenium (ask ChatGPT!)\n",
+ "\n",
+ "Also Websites protected with CloudFront (and similar) may give 403 errors - many thanks Andy J for pointing this out.\n",
+ "\n",
+ "But many websites will work just fine!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "45d83403-a24c-44b5-84ac-961449b4008f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://cnn.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "75e9fd40-b354-4341-991e-863ef2e59db7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://anthropic.com\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c951be1a-7f1b-448f-af1f-845978e47e2c",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Business applications\n",
+ " In this exercise, you experienced calling the Cloud API of a Frontier Model (a leading model at the frontier of AI) for the first time. We will be using APIs like OpenAI at many stages in the course, in addition to building our own LLMs.\n",
+ "\n",
+ "More specifically, we've applied this to Summarization - a classic Gen AI use case to make a summary. This can be applied to any business vertical - summarizing the news, summarizing financial performance, summarizing a resume in a cover letter - the applications are limitless. Consider how you could apply Summarization in your business, and try prototyping a solution.\n",
+ " | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Before you continue - now try yourself\n",
+ " Use the cell below to make your own simple commercial example. Stick with the summarization use case for now. Here's an idea: write something that will take the contents of an email, and will suggest an appropriate short subject line for the email. That's the kind of feature that might be built into a commercial email tool.\n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"\"\"you are an AI to a salesperson working in the field of industrial tools and hardware. You have the following roles:\\\n",
+ "1. identify and understand the scenario the customer is describing.\\\n",
+ "2. figure what caregory of products are suitable for use in the scenario.\\\n",
+ "3. search https://industrywaala.com/ for the category of products you identified in 2. and then look for 2 products in that\\\n",
+ "category that you think will be most suitable in the given use case. for this you need to check for product features provided in\\\n",
+ "the short and long descriptions on the website that are applicable in the scenario.\\\n",
+ "4. make a summary of the two products with the brand name, model and 2 other key features of the product\\\n",
+ "5. always respond in markdown.\n",
+ "\"\"\"\n",
+ "\n",
+ "user_prompt = \"\"\"\\n can you help figure what model of product should i use in high temperature environemt. \\n\\n\n",
+ "\"\"\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt}\n",
+ "] # fill this in\n",
+ "\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "response = openai.chat.completions.create(\n",
+ " model = \"gpt-4o-mini\",\n",
+ " messages = messages\n",
+ ")\n",
+ "\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "display(Markdown(response.choices[0].message.content))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36ed9f14-b349-40e9-a42c-b367e77f8bda",
+ "metadata": {},
+ "source": [
+ "## An extra exercise for those who enjoy web scraping\n",
+ "\n",
+ "You may notice that if you try `display_summary(\"https://openai.com\")` - it doesn't work! That's because OpenAI has a fancy website that uses Javascript. There are many ways around this that some of you might be familiar with. For example, Selenium is a hugely popular framework that runs a browser behind the scenes, renders the page, and allows you to query it. If you have experience with Selenium, Playwright or similar, then feel free to improve the Website class to use them. In the community-contributions folder, you'll find an example Selenium solution from a student (thank you!)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "eeab24dc-5f90-4570-b542-b0585aca3eb6",
+ "metadata": {},
+ "source": [
+ "# Sharing your code\n",
+ "\n",
+ "I'd love it if you share your code afterwards so I can share it with others! You'll notice that some students have already made changes (including a Selenium implementation) which you will find in the community-contributions folder. If you'd like add your changes to that folder, submit a Pull Request with your new versions in that folder and I'll merge your changes.\n",
+ "\n",
+ "If you're not an expert with git (and I am not!) then GPT has given some nice instructions on how to submit a Pull Request. It's a bit of an involved process, but once you've done it once it's pretty clear. As a pro-tip: it's best if you clear the outputs of your Jupyter notebooks (Edit >> Clean outputs of all cells, and then Save) for clean notebooks.\n",
+ "\n",
+ "Here are good instructions courtesy of an AI friend: \n",
+ "https://chatgpt.com/share/677a9cb5-c64c-8012-99e0-e06e88afd293"
+ ]
+ }
+ ],
+ "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
+}
From fe1a0d79acd8d3e4c918df27dfb00a551e99851e Mon Sep 17 00:00:00 2001
From: 266367 <266367@nttdata.com>
Date: Mon, 27 Jan 2025 19:57:40 -0500
Subject: [PATCH 50/61] Wk1 Day2 Exercise Ollama solution
---
.../wk1-day1-deepseek-stream-summarize.ipynb | 250 +++++++++---------
1 file changed, 128 insertions(+), 122 deletions(-)
diff --git a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
index 2e615ed..0e7a226 100644
--- a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
+++ b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
@@ -1,125 +1,131 @@
{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "a767b6bc-65fe-42b2-988f-efd54125114f",
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "import requests\n",
- "from dotenv import load_dotenv\n",
- "from bs4 import BeautifulSoup\n",
- "from IPython.display import Markdown, display, clear_output\n",
- "from openai import OpenAI\n",
- "\n",
- "load_dotenv(override=True)\n",
- "api_key = os.getenv('DEEPSEEK_API_KEY')\n",
- "base_url=os.getenv('DEEPSEEK_BASE_URL')\n",
- "MODEL = \"deepseek-chat\"\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",
- "messages = [\n",
- " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
- " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
- "]\n",
- " \n",
- "# Check the key\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-; Looks like you are using DeepSeek (R1) model.\")\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",
- " \n",
- "openai = OpenAI(api_key=api_key, base_url=base_url)\n",
- "\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",
- " def __init__(self, url):\n",
- " \"\"\"\n",
- " Create this Website object from the given url using the BeautifulSoup library\n",
- " \"\"\"\n",
- " self.url = url\n",
- " response = requests.get(url, headers=headers)\n",
- " soup = BeautifulSoup(response.content, 'html.parser')\n",
- " self.title = soup.title.string if soup.title else \"No title found\"\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",
- " \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; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\n\"\n",
- " user_prompt += website.text\n",
- " return user_prompt\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",
- "def summarize(url):\n",
- " website = Website(url)\n",
- " response = openai.chat.completions.create(\n",
- " model=MODEL,\n",
- " messages=messages_for(website),\n",
- " stream=True\n",
- " )\n",
- " print(\"Streaming response:\")\n",
- " accumulated_content = \"\" # Accumulate the content here\n",
- " for chunk in response:\n",
- " if chunk.choices[0].delta.content: # Check if there's content in the chunk\n",
- " accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
- " clear_output(wait=True) # Clear the previous output\n",
- " display(Markdown(accumulated_content)) # Display the updated content\n",
- "\n",
- "def display_summary():\n",
- " url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
- " summarize(url)\n",
- "\n",
- "display_summary()"
- ]
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a767b6bc-65fe-42b2-988f-efd54125114f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import requests\n",
+ "from dotenv import load_dotenv\n",
+ "from bs4 import BeautifulSoup\n",
+ "from IPython.display import Markdown, display, clear_output\n",
+ "from openai import OpenAI\n",
+ "\n",
+ "load_dotenv(override=True)\n",
+ "# Deep seek API payload\n",
+ "# api_key = os.getenv('DEEPSEEK_API_KEY')\n",
+ "# base_url=os.getenv('DEEPSEEK_BASE_URL')\n",
+ "# MODEL = \"deepseek-chat\"\n",
+ "\n",
+ "# Day 2 Exercise with Ollama API\n",
+ "api_key = os.getenv('OLLAMA_API_KEY')\n",
+ "base_url = os.getenv('OLLAMA_BASE_URL')\n",
+ "MODEL = \"llama3.2\"\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",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]\n",
+ " \n",
+ "# Check the key\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-; Looks like you are using DeepSeek (R1) model.\")\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",
+ " \n",
+ "openai = OpenAI(api_key=api_key, base_url=base_url)\n",
+ "\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\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",
+ " \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; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\n\"\n",
+ " user_prompt += website.text\n",
+ " return user_prompt\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",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " response = openai.chat.completions.create(\n",
+ " model=MODEL,\n",
+ " messages=messages_for(website),\n",
+ " stream=True\n",
+ " )\n",
+ " print(\"Streaming response:\")\n",
+ " accumulated_content = \"\" # Accumulate the content here\n",
+ " for chunk in response:\n",
+ " if chunk.choices[0].delta.content: # Check if there's content in the chunk\n",
+ " accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
+ " clear_output(wait=True) # Clear the previous output\n",
+ " display(Markdown(accumulated_content)) # Display the updated content\n",
+ "\n",
+ "def display_summary():\n",
+ " url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
+ " summarize(url)\n",
+ "\n",
+ "display_summary()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "01c9e5e7-7510-43ef-bb9c-aa44b15d39a7",
+ "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"
+ }
},
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "01c9e5e7-7510-43ef-bb9c-aa44b15d39a7",
- "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
+ "nbformat": 4,
+ "nbformat_minor": 5
}
From 26e2b74727c9380364d7a2e2965fb6ef54d9e0f8 Mon Sep 17 00:00:00 2001
From: 266367 <266367@nttdata.com>
Date: Wed, 29 Jan 2025 13:07:36 -0500
Subject: [PATCH 51/61] rebase and cleanup
---
.../wk1-day1-deepseek-stream-summarize.ipynb | 250 +++++++++---------
.../wk1-day2-ollama-exer.ipynb | 118 +++++++++
2 files changed, 240 insertions(+), 128 deletions(-)
create mode 100644 week1/community-contributions/wk1-day2-ollama-exer.ipynb
diff --git a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
index 0e7a226..2e615ed 100644
--- a/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
+++ b/week1/community-contributions/wk1-day1-deepseek-stream-summarize.ipynb
@@ -1,131 +1,125 @@
{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "a767b6bc-65fe-42b2-988f-efd54125114f",
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "import requests\n",
- "from dotenv import load_dotenv\n",
- "from bs4 import BeautifulSoup\n",
- "from IPython.display import Markdown, display, clear_output\n",
- "from openai import OpenAI\n",
- "\n",
- "load_dotenv(override=True)\n",
- "# Deep seek API payload\n",
- "# api_key = os.getenv('DEEPSEEK_API_KEY')\n",
- "# base_url=os.getenv('DEEPSEEK_BASE_URL')\n",
- "# MODEL = \"deepseek-chat\"\n",
- "\n",
- "# Day 2 Exercise with Ollama API\n",
- "api_key = os.getenv('OLLAMA_API_KEY')\n",
- "base_url = os.getenv('OLLAMA_BASE_URL')\n",
- "MODEL = \"llama3.2\"\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",
- "messages = [\n",
- " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
- " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
- "]\n",
- " \n",
- "# Check the key\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-; Looks like you are using DeepSeek (R1) model.\")\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",
- " \n",
- "openai = OpenAI(api_key=api_key, base_url=base_url)\n",
- "\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",
- " def __init__(self, url):\n",
- " \"\"\"\n",
- " Create this Website object from the given url using the BeautifulSoup library\n",
- " \"\"\"\n",
- " self.url = url\n",
- " response = requests.get(url, headers=headers)\n",
- " soup = BeautifulSoup(response.content, 'html.parser')\n",
- " self.title = soup.title.string if soup.title else \"No title found\"\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",
- " \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; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\n\"\n",
- " user_prompt += website.text\n",
- " return user_prompt\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",
- "def summarize(url):\n",
- " website = Website(url)\n",
- " response = openai.chat.completions.create(\n",
- " model=MODEL,\n",
- " messages=messages_for(website),\n",
- " stream=True\n",
- " )\n",
- " print(\"Streaming response:\")\n",
- " accumulated_content = \"\" # Accumulate the content here\n",
- " for chunk in response:\n",
- " if chunk.choices[0].delta.content: # Check if there's content in the chunk\n",
- " accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
- " clear_output(wait=True) # Clear the previous output\n",
- " display(Markdown(accumulated_content)) # Display the updated content\n",
- "\n",
- "def display_summary():\n",
- " url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
- " summarize(url)\n",
- "\n",
- "display_summary()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "01c9e5e7-7510-43ef-bb9c-aa44b15d39a7",
- "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"
- }
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a767b6bc-65fe-42b2-988f-efd54125114f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import requests\n",
+ "from dotenv import load_dotenv\n",
+ "from bs4 import BeautifulSoup\n",
+ "from IPython.display import Markdown, display, clear_output\n",
+ "from openai import OpenAI\n",
+ "\n",
+ "load_dotenv(override=True)\n",
+ "api_key = os.getenv('DEEPSEEK_API_KEY')\n",
+ "base_url=os.getenv('DEEPSEEK_BASE_URL')\n",
+ "MODEL = \"deepseek-chat\"\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",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]\n",
+ " \n",
+ "# Check the key\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-; Looks like you are using DeepSeek (R1) model.\")\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",
+ " \n",
+ "openai = OpenAI(api_key=api_key, base_url=base_url)\n",
+ "\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\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",
+ " \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; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\n\"\n",
+ " user_prompt += website.text\n",
+ " return user_prompt\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",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " response = openai.chat.completions.create(\n",
+ " model=MODEL,\n",
+ " messages=messages_for(website),\n",
+ " stream=True\n",
+ " )\n",
+ " print(\"Streaming response:\")\n",
+ " accumulated_content = \"\" # Accumulate the content here\n",
+ " for chunk in response:\n",
+ " if chunk.choices[0].delta.content: # Check if there's content in the chunk\n",
+ " accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
+ " clear_output(wait=True) # Clear the previous output\n",
+ " display(Markdown(accumulated_content)) # Display the updated content\n",
+ "\n",
+ "def display_summary():\n",
+ " url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
+ " summarize(url)\n",
+ "\n",
+ "display_summary()"
+ ]
},
- "nbformat": 4,
- "nbformat_minor": 5
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "01c9e5e7-7510-43ef-bb9c-aa44b15d39a7",
+ "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
}
diff --git a/week1/community-contributions/wk1-day2-ollama-exer.ipynb b/week1/community-contributions/wk1-day2-ollama-exer.ipynb
new file mode 100644
index 0000000..ebedd97
--- /dev/null
+++ b/week1/community-contributions/wk1-day2-ollama-exer.ipynb
@@ -0,0 +1,118 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import requests\n",
+ "from dotenv import load_dotenv\n",
+ "from bs4 import BeautifulSoup\n",
+ "from IPython.display import Markdown, display, clear_output\n",
+ "from openai import OpenAI\n",
+ "\n",
+ "load_dotenv(override=True)\n",
+ "\n",
+ "# Day 2 Exercise with Ollama API\n",
+ "api_key = os.getenv('OLLAMA_API_KEY')\n",
+ "base_url = os.getenv('OLLAMA_BASE_URL')\n",
+ "MODEL = \"llama3.2\"\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",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]\n",
+ " \n",
+ "# Check the key\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-; Looks like you are using DeepSeek (R1) model.\")\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",
+ " \n",
+ "openai = OpenAI(api_key=api_key, base_url=base_url)\n",
+ "\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\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",
+ " \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; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\n\"\n",
+ " user_prompt += website.text\n",
+ " return user_prompt\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",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " response = openai.chat.completions.create(\n",
+ " model=MODEL,\n",
+ " messages=messages_for(website),\n",
+ " stream=True\n",
+ " )\n",
+ " print(\"Streaming response:\")\n",
+ " accumulated_content = \"\" # Accumulate the content here\n",
+ " for chunk in response:\n",
+ " if chunk.choices[0].delta.content: # Check if there's content in the chunk\n",
+ " accumulated_content += chunk.choices[0].delta.content # Append the chunk to the accumulated content\n",
+ " clear_output(wait=True) # Clear the previous output\n",
+ " display(Markdown(accumulated_content)) # Display the updated content\n",
+ " \n",
+ "def display_summary():\n",
+ " url = str(input(\"Enter the URL of the website you want to summarize: \"))\n",
+ " summarize(url)\n",
+ "\n",
+ "display_summary()"
+ ]
+ }
+ ],
+ "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": 4
+}
From 951f2bb660cfd117f2d1633be9d349ff683362fc Mon Sep 17 00:00:00 2001
From: Dipin
Date: Fri, 31 Jan 2025 08:26:16 -0600
Subject: [PATCH 52/61] Added my contributions to community-contributions
---
.../day1-Groq API.ipynb | 530 ++++++++++++++++++
1 file changed, 530 insertions(+)
create mode 100644 week1/community-contributions/day1-Groq API.ipynb
diff --git a/week1/community-contributions/day1-Groq API.ipynb b/week1/community-contributions/day1-Groq API.ipynb
new file mode 100644
index 0000000..3838097
--- /dev/null
+++ b/week1/community-contributions/day1-Groq API.ipynb
@@ -0,0 +1,530 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "d15d8294-3328-4e07-ad16-8a03e9bbfdb9",
+ "metadata": {},
+ "source": [
+ "## DAY1 LLM Project with GROQ!\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
+ "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 groq import Groq\n",
+ "\n",
+ "# If you get an error running this cell, then please head over to the troubleshooting notebook!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5d899ad6-1428-481b-b308-750308d80442",
+ "metadata": {},
+ "source": [
+ "If you are getting error ModuleNotFoundError: No module named 'groq' follow below steps.\n",
+ "\n",
+ "1. Activate llms enviornment from Anaconda, so that (llms) is showing in your prompt, as this is the environment where the package will get installed.Install pip here. \n",
+ "\n",
+ "(base) PS C:\\Users\\test\\OneDrive\\Desktop\\AI\\projects\\llm_engineering> conda activate llms\n",
+ "(llms) PS C:\\Users\\test\\OneDrive\\Desktop\\AI\\projects\\llm_engineering> pip install groq\n",
+ "\n",
+ "\n",
+ "2. After you install a new package, you'd need to restart the Kernel in jupyter lab for each notebook (Kernel >> Restart Kernel and Clear Values Of All Outputs).\n",
+ "\n",
+ "You can also run this command in jupyter lab to see whether it's installed:\n",
+ "\n",
+ "!pip show groq\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "99c0c3c9-fa5e-405e-8453-2a557dc60c09",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!pip show groq"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6900b2a8-6384-4316-8aaa-5e519fca4254",
+ "metadata": {},
+ "source": [
+ "# Connecting to GROQ\n",
+ "\n",
+ "The next cell is where we load in the environment variables in your `.env` file and connect to GROQ.\n",
+ "\n",
+ ".env file should have below entry\n",
+ "\n",
+ "GROQ_API_KEY=gsk_xxxxxx\n",
+ "\n",
+ "GROQ keys can be configired by logging to below link\n",
+ "https://console.groq.com/keys\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Load environment variables in a file called .env\n",
+ "\n",
+ "load_dotenv(override=True)\n",
+ "api_key = os.getenv('GROQ_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(\"gsk_\"):\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": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "groq = Groq()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "442fc84b-0815-4f40-99ab-d9a5da6bda91",
+ "metadata": {},
+ "source": [
+ "# Let's make a quick call to a Frontier model to get started, as a preview!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a58394bf-1e45-46af-9bfd-01e24da6f49a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To give you a preview -- calling Groq with these messages is this easy. Any problems, head over to the Troubleshooting notebook.\n",
+ "\n",
+ "message = \"Hello, GPT! This is my first ever message to you! Hi!\"\n",
+ "response = groq.chat.completions.create(model=\"llama-3.3-70b-versatile\", messages=[{\"role\":\"user\", \"content\":message}])\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2aa190e5-cb31-456a-96cc-db109919cd78",
+ "metadata": {},
+ "source": [
+ "## OK onwards with our first project"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c5e793b2-6775-426a-a139-4848291d0463",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A class to represent a Webpage\n",
+ "# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\n",
+ " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
+ " irrelevant.decompose()\n",
+ " self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's try one out. Change the website and add print statements to follow along.\n",
+ "\n",
+ "ed = Website(\"https://edwarddonner.com\")\n",
+ "print(ed.title)\n",
+ "print(ed.text)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a478a0c-2c53-48ff-869c-4d08199931e1",
+ "metadata": {},
+ "source": [
+ "## Types of prompts\n",
+ "\n",
+ "You may know this already - but if not, you will get very familiar with it!\n",
+ "\n",
+ "Models like GPT4o have been trained to receive instructions in a particular way.\n",
+ "\n",
+ "They expect to receive:\n",
+ "\n",
+ "**A system prompt** that tells them what task they are performing and what tone they should use\n",
+ "\n",
+ "**A user prompt** -- the conversation starter that they should reply to"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "abdb8417-c5dc-44bc-9bee-2e059d162699",
+ "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.\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f0275b1b-7cfe-4f9d-abfa-7650d378da0c",
+ "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 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"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "26448ec4-5c00-4204-baec-7df91d11ff2e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(user_prompt_for(ed))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ea211b5f-28e1-4a86-8e52-c0b7677cadcc",
+ "metadata": {},
+ "source": [
+ "## Messages\n",
+ "\n",
+ "Similar to OPENAI GROQ APIs share this structure:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message goes here\"},\n",
+ " {\"role\": \"user\", \"content\": \"user message goes here\"}\n",
+ "]\n",
+ "\n",
+ "To give you a preview, the next 2 cells make a rather simple call - we won't stretch the might GPT (yet!)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "21ed95c5-7001-47de-a36d-1d6673b403ce",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To give you a preview -- calling Groq with system and user messages:\n",
+ "\n",
+ "response = groq.chat.completions.create(model=\"llama-3.3-70b-versatile\", messages=messages)\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d06e8d78-ce4c-4b05-aa8e-17050c82bb47",
+ "metadata": {},
+ "source": [
+ "## And now let's build useful messages for LLAMA3.3, using a function"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0134dfa4-8299-48b5-b444-f2a8c3403c88",
+ "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": "36478464-39ee-485c-9f3f-6a4e458dbc9c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Try this out, and then try for a few more websites\n",
+ "\n",
+ "messages_for(ed)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "16f49d46-bf55-4c3e-928f-68fc0bf715b0",
+ "metadata": {},
+ "source": [
+ "## Time to bring it together - the API for GROQ is very simple!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "905b9919-aba7-45b5-ae65-81b3d1d78e34",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# And now: call the GROQ API\n",
+ "\n",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " response = groq.chat.completions.create(\n",
+ " model = \"llama-3.3-70b-versatile\",\n",
+ " messages = messages_for(website)\n",
+ " )\n",
+ " return response.choices[0].message.content"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "05e38d41-dfa4-4b20-9c96-c46ea75d9fb5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "summarize(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3d926d59-450e-4609-92ba-2d6f244f1342",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A function to display this nicely in the Jupyter output, using markdown\n",
+ "\n",
+ "def display_summary(url):\n",
+ " summary = summarize(url)\n",
+ " display(Markdown(summary))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3018853a-445f-41ff-9560-d925d1774b2f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b3bcf6f4-adce-45e9-97ad-d9a5d7a3a624",
+ "metadata": {},
+ "source": [
+ "# Let's try more websites\n",
+ "\n",
+ "Note that this will only work on websites that can be scraped using this simplistic approach.\n",
+ "\n",
+ "Websites that are rendered with Javascript, like React apps, won't show up. See the community-contributions folder for a Selenium implementation that gets around this. You'll need to read up on installing Selenium (ask ChatGPT!)\n",
+ "\n",
+ "Also Websites protected with CloudFront (and similar) may give 403 errors - many thanks Andy J for pointing this out.\n",
+ "\n",
+ "But many websites will work just fine!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "45d83403-a24c-44b5-84ac-961449b4008f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://cnn.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "75e9fd40-b354-4341-991e-863ef2e59db7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://anthropic.com\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c951be1a-7f1b-448f-af1f-845978e47e2c",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Business applications\n",
+ " In this exercise, you experienced calling the Cloud API of a Frontier Model (a leading model at the frontier of AI) for the first time. We will be using APIs like OpenAI at many stages in the course, in addition to building our own LLMs.\n",
+ "\n",
+ "More specifically, we've applied this to Summarization - a classic Gen AI use case to make a summary. This can be applied to any business vertical - summarizing the news, summarizing financial performance, summarizing a resume in a cover letter - the applications are limitless. Consider how you could apply Summarization in your business, and try prototyping a solution.\n",
+ " | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Before you continue - now try yourself\n",
+ " Use the cell below to make your own simple commercial example. Stick with the summarization use case for now. Here's an idea: write something that will take the contents of an email, and will suggest an appropriate short subject line for the email. That's the kind of feature that might be built into a commercial email tool.\n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"something here\"\n",
+ "user_prompt = \"\"\"\n",
+ " Lots of text\n",
+ " Can be pasted here\n",
+ "\"\"\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [] # fill this in\n",
+ "\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "response =\n",
+ "\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "print("
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36ed9f14-b349-40e9-a42c-b367e77f8bda",
+ "metadata": {},
+ "source": [
+ "## An extra exercise for those who enjoy web scraping\n",
+ "\n",
+ "You may notice that if you try `display_summary(\"https://openai.com\")` - it doesn't work! That's because OpenAI has a fancy website that uses Javascript. There are many ways around this that some of you might be familiar with. For example, Selenium is a hugely popular framework that runs a browser behind the scenes, renders the page, and allows you to query it. If you have experience with Selenium, Playwright or similar, then feel free to improve the Website class to use them. In the community-contributions folder, you'll find an example Selenium solution from a student (thank you!)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "eeab24dc-5f90-4570-b542-b0585aca3eb6",
+ "metadata": {},
+ "source": [
+ "# Sharing your code\n",
+ "\n",
+ "I'd love it if you share your code afterwards so I can share it with others! You'll notice that some students have already made changes (including a Selenium implementation) which you will find in the community-contributions folder. If you'd like add your changes to that folder, submit a Pull Request with your new versions in that folder and I'll merge your changes.\n",
+ "\n",
+ "If you're not an expert with git (and I am not!) then GPT has given some nice instructions on how to submit a Pull Request. It's a bit of an involved process, but once you've done it once it's pretty clear. As a pro-tip: it's best if you clear the outputs of your Jupyter notebooks (Edit >> Clean outputs of all cells, and then Save) for clean notebooks.\n",
+ "\n",
+ "Here are good instructions courtesy of an AI friend: \n",
+ "https://chatgpt.com/share/677a9cb5-c64c-8012-99e0-e06e88afd293"
+ ]
+ }
+ ],
+ "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
+}
From 28564eabb4443b646e923b62ee0f5ca24cd6e897 Mon Sep 17 00:00:00 2001
From: Dipin
Date: Fri, 31 Jan 2025 08:48:45 -0600
Subject: [PATCH 53/61] Added my contributions to community-contributions
---
.../day1-Groq-API.ipynb | 530 ++++++++++++++++++
1 file changed, 530 insertions(+)
create mode 100644 week1/community-contributions/day1-Groq-API.ipynb
diff --git a/week1/community-contributions/day1-Groq-API.ipynb b/week1/community-contributions/day1-Groq-API.ipynb
new file mode 100644
index 0000000..3838097
--- /dev/null
+++ b/week1/community-contributions/day1-Groq-API.ipynb
@@ -0,0 +1,530 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "d15d8294-3328-4e07-ad16-8a03e9bbfdb9",
+ "metadata": {},
+ "source": [
+ "## DAY1 LLM Project with GROQ!\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
+ "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 groq import Groq\n",
+ "\n",
+ "# If you get an error running this cell, then please head over to the troubleshooting notebook!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5d899ad6-1428-481b-b308-750308d80442",
+ "metadata": {},
+ "source": [
+ "If you are getting error ModuleNotFoundError: No module named 'groq' follow below steps.\n",
+ "\n",
+ "1. Activate llms enviornment from Anaconda, so that (llms) is showing in your prompt, as this is the environment where the package will get installed.Install pip here. \n",
+ "\n",
+ "(base) PS C:\\Users\\test\\OneDrive\\Desktop\\AI\\projects\\llm_engineering> conda activate llms\n",
+ "(llms) PS C:\\Users\\test\\OneDrive\\Desktop\\AI\\projects\\llm_engineering> pip install groq\n",
+ "\n",
+ "\n",
+ "2. After you install a new package, you'd need to restart the Kernel in jupyter lab for each notebook (Kernel >> Restart Kernel and Clear Values Of All Outputs).\n",
+ "\n",
+ "You can also run this command in jupyter lab to see whether it's installed:\n",
+ "\n",
+ "!pip show groq\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "99c0c3c9-fa5e-405e-8453-2a557dc60c09",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!pip show groq"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6900b2a8-6384-4316-8aaa-5e519fca4254",
+ "metadata": {},
+ "source": [
+ "# Connecting to GROQ\n",
+ "\n",
+ "The next cell is where we load in the environment variables in your `.env` file and connect to GROQ.\n",
+ "\n",
+ ".env file should have below entry\n",
+ "\n",
+ "GROQ_API_KEY=gsk_xxxxxx\n",
+ "\n",
+ "GROQ keys can be configired by logging to below link\n",
+ "https://console.groq.com/keys\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Load environment variables in a file called .env\n",
+ "\n",
+ "load_dotenv(override=True)\n",
+ "api_key = os.getenv('GROQ_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(\"gsk_\"):\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": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "groq = Groq()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "442fc84b-0815-4f40-99ab-d9a5da6bda91",
+ "metadata": {},
+ "source": [
+ "# Let's make a quick call to a Frontier model to get started, as a preview!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a58394bf-1e45-46af-9bfd-01e24da6f49a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To give you a preview -- calling Groq with these messages is this easy. Any problems, head over to the Troubleshooting notebook.\n",
+ "\n",
+ "message = \"Hello, GPT! This is my first ever message to you! Hi!\"\n",
+ "response = groq.chat.completions.create(model=\"llama-3.3-70b-versatile\", messages=[{\"role\":\"user\", \"content\":message}])\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2aa190e5-cb31-456a-96cc-db109919cd78",
+ "metadata": {},
+ "source": [
+ "## OK onwards with our first project"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c5e793b2-6775-426a-a139-4848291d0463",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A class to represent a Webpage\n",
+ "# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\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",
+ " def __init__(self, url):\n",
+ " \"\"\"\n",
+ " Create this Website object from the given url using the BeautifulSoup library\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " response = requests.get(url, headers=headers)\n",
+ " soup = BeautifulSoup(response.content, 'html.parser')\n",
+ " self.title = soup.title.string if soup.title else \"No title found\"\n",
+ " for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
+ " irrelevant.decompose()\n",
+ " self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's try one out. Change the website and add print statements to follow along.\n",
+ "\n",
+ "ed = Website(\"https://edwarddonner.com\")\n",
+ "print(ed.title)\n",
+ "print(ed.text)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a478a0c-2c53-48ff-869c-4d08199931e1",
+ "metadata": {},
+ "source": [
+ "## Types of prompts\n",
+ "\n",
+ "You may know this already - but if not, you will get very familiar with it!\n",
+ "\n",
+ "Models like GPT4o have been trained to receive instructions in a particular way.\n",
+ "\n",
+ "They expect to receive:\n",
+ "\n",
+ "**A system prompt** that tells them what task they are performing and what tone they should use\n",
+ "\n",
+ "**A user prompt** -- the conversation starter that they should reply to"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "abdb8417-c5dc-44bc-9bee-2e059d162699",
+ "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.\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f0275b1b-7cfe-4f9d-abfa-7650d378da0c",
+ "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 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"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "26448ec4-5c00-4204-baec-7df91d11ff2e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(user_prompt_for(ed))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ea211b5f-28e1-4a86-8e52-c0b7677cadcc",
+ "metadata": {},
+ "source": [
+ "## Messages\n",
+ "\n",
+ "Similar to OPENAI GROQ APIs share this structure:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message goes here\"},\n",
+ " {\"role\": \"user\", \"content\": \"user message goes here\"}\n",
+ "]\n",
+ "\n",
+ "To give you a preview, the next 2 cells make a rather simple call - we won't stretch the might GPT (yet!)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n",
+ " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "21ed95c5-7001-47de-a36d-1d6673b403ce",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To give you a preview -- calling Groq with system and user messages:\n",
+ "\n",
+ "response = groq.chat.completions.create(model=\"llama-3.3-70b-versatile\", messages=messages)\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d06e8d78-ce4c-4b05-aa8e-17050c82bb47",
+ "metadata": {},
+ "source": [
+ "## And now let's build useful messages for LLAMA3.3, using a function"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0134dfa4-8299-48b5-b444-f2a8c3403c88",
+ "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": "36478464-39ee-485c-9f3f-6a4e458dbc9c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Try this out, and then try for a few more websites\n",
+ "\n",
+ "messages_for(ed)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "16f49d46-bf55-4c3e-928f-68fc0bf715b0",
+ "metadata": {},
+ "source": [
+ "## Time to bring it together - the API for GROQ is very simple!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "905b9919-aba7-45b5-ae65-81b3d1d78e34",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# And now: call the GROQ API\n",
+ "\n",
+ "def summarize(url):\n",
+ " website = Website(url)\n",
+ " response = groq.chat.completions.create(\n",
+ " model = \"llama-3.3-70b-versatile\",\n",
+ " messages = messages_for(website)\n",
+ " )\n",
+ " return response.choices[0].message.content"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "05e38d41-dfa4-4b20-9c96-c46ea75d9fb5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "summarize(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3d926d59-450e-4609-92ba-2d6f244f1342",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A function to display this nicely in the Jupyter output, using markdown\n",
+ "\n",
+ "def display_summary(url):\n",
+ " summary = summarize(url)\n",
+ " display(Markdown(summary))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3018853a-445f-41ff-9560-d925d1774b2f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://edwarddonner.com\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b3bcf6f4-adce-45e9-97ad-d9a5d7a3a624",
+ "metadata": {},
+ "source": [
+ "# Let's try more websites\n",
+ "\n",
+ "Note that this will only work on websites that can be scraped using this simplistic approach.\n",
+ "\n",
+ "Websites that are rendered with Javascript, like React apps, won't show up. See the community-contributions folder for a Selenium implementation that gets around this. You'll need to read up on installing Selenium (ask ChatGPT!)\n",
+ "\n",
+ "Also Websites protected with CloudFront (and similar) may give 403 errors - many thanks Andy J for pointing this out.\n",
+ "\n",
+ "But many websites will work just fine!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "45d83403-a24c-44b5-84ac-961449b4008f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://cnn.com\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "75e9fd40-b354-4341-991e-863ef2e59db7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "display_summary(\"https://anthropic.com\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c951be1a-7f1b-448f-af1f-845978e47e2c",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Business applications\n",
+ " In this exercise, you experienced calling the Cloud API of a Frontier Model (a leading model at the frontier of AI) for the first time. We will be using APIs like OpenAI at many stages in the course, in addition to building our own LLMs.\n",
+ "\n",
+ "More specifically, we've applied this to Summarization - a classic Gen AI use case to make a summary. This can be applied to any business vertical - summarizing the news, summarizing financial performance, summarizing a resume in a cover letter - the applications are limitless. Consider how you could apply Summarization in your business, and try prototyping a solution.\n",
+ " | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ "\n",
+ " \n",
+ " \n",
+ " \n",
+ " | \n",
+ " \n",
+ " Before you continue - now try yourself\n",
+ " Use the cell below to make your own simple commercial example. Stick with the summarization use case for now. Here's an idea: write something that will take the contents of an email, and will suggest an appropriate short subject line for the email. That's the kind of feature that might be built into a commercial email tool.\n",
+ " | \n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "00743dac-0e70-45b7-879a-d7293a6f68a6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Step 1: Create your prompts\n",
+ "\n",
+ "system_prompt = \"something here\"\n",
+ "user_prompt = \"\"\"\n",
+ " Lots of text\n",
+ " Can be pasted here\n",
+ "\"\"\"\n",
+ "\n",
+ "# Step 2: Make the messages list\n",
+ "\n",
+ "messages = [] # fill this in\n",
+ "\n",
+ "# Step 3: Call OpenAI\n",
+ "\n",
+ "response =\n",
+ "\n",
+ "# Step 4: print the result\n",
+ "\n",
+ "print("
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36ed9f14-b349-40e9-a42c-b367e77f8bda",
+ "metadata": {},
+ "source": [
+ "## An extra exercise for those who enjoy web scraping\n",
+ "\n",
+ "You may notice that if you try `display_summary(\"https://openai.com\")` - it doesn't work! That's because OpenAI has a fancy website that uses Javascript. There are many ways around this that some of you might be familiar with. For example, Selenium is a hugely popular framework that runs a browser behind the scenes, renders the page, and allows you to query it. If you have experience with Selenium, Playwright or similar, then feel free to improve the Website class to use them. In the community-contributions folder, you'll find an example Selenium solution from a student (thank you!)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "eeab24dc-5f90-4570-b542-b0585aca3eb6",
+ "metadata": {},
+ "source": [
+ "# Sharing your code\n",
+ "\n",
+ "I'd love it if you share your code afterwards so I can share it with others! You'll notice that some students have already made changes (including a Selenium implementation) which you will find in the community-contributions folder. If you'd like add your changes to that folder, submit a Pull Request with your new versions in that folder and I'll merge your changes.\n",
+ "\n",
+ "If you're not an expert with git (and I am not!) then GPT has given some nice instructions on how to submit a Pull Request. It's a bit of an involved process, but once you've done it once it's pretty clear. As a pro-tip: it's best if you clear the outputs of your Jupyter notebooks (Edit >> Clean outputs of all cells, and then Save) for clean notebooks.\n",
+ "\n",
+ "Here are good instructions courtesy of an AI friend: \n",
+ "https://chatgpt.com/share/677a9cb5-c64c-8012-99e0-e06e88afd293"
+ ]
+ }
+ ],
+ "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
+}
From 24a9e1a606e516aa03db3ded3bffd61bb15235c9 Mon Sep 17 00:00:00 2001
From: Emads
Date: Fri, 31 Jan 2025 17:20:06 +0200
Subject: [PATCH 54/61] Add contributions to week6 community-contributions
---
.../ems_week6_day4_gemini_results.ipynb | 313 ++++++++++++++++++
1 file changed, 313 insertions(+)
create mode 100644 week6/community-contributions/ems_week6_day4_gemini_results.ipynb
diff --git a/week6/community-contributions/ems_week6_day4_gemini_results.ipynb b/week6/community-contributions/ems_week6_day4_gemini_results.ipynb
new file mode 100644
index 0000000..dd8b448
--- /dev/null
+++ b/week6/community-contributions/ems_week6_day4_gemini_results.ipynb
@@ -0,0 +1,313 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "db8736a7-ed94-441c-9556-831fa57b5a10",
+ "metadata": {},
+ "source": [
+ "# The Product Pricer Continued...\n",
+ "\n",
+ "## Testing Gemini-1.5-pro model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "681c717b-4c24-4ac3-a5f3-3c5881d6e70a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import re\n",
+ "from dotenv import load_dotenv\n",
+ "import matplotlib.pyplot as plt\n",
+ "import pickle\n",
+ "import google.generativeai as google_genai\n",
+ "import time"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "21a3833e-4093-43b0-8f7b-839c50b911ea",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from items import Item\n",
+ "from testing import Tester "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "36d05bdc-0155-4c72-a7ee-aa4e614ffd3c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# environment\n",
+ "load_dotenv()\n",
+ "os.environ['GOOGLE_API_KEY'] = os.getenv('GOOGLE_API_KEY', 'your-key-if-not-using-env')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b0a6fb86-74a4-403c-ab25-6db2d74e9d2b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "google_genai.configure()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c830ed3e-24ee-4af6-a07b-a1bfdcd39278",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%matplotlib inline"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "5c9b05f4-c9eb-462c-8d86-de9140a2d985",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Load in the pickle files that are located in the `pickled_dataset` folder\n",
+ "with open('train.pkl', 'rb') as file:\n",
+ " train = pickle.load(file)\n",
+ "\n",
+ "with open('test.pkl', 'rb') as file:\n",
+ " test = pickle.load(file)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "fc5c807b-c14c-458e-8cca-32bc0cc5b7c3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Function to create the messages format required for Gemini 1.5 Pro\n",
+ "# This function prepares the system and user messages in the format expected by Gemini models.\n",
+ "def gemini_messages_for(item):\n",
+ " system_message = \"You estimate prices of items. Reply only with the price, no explanation\"\n",
+ " \n",
+ " # Modify the test prompt by removing \"to the nearest dollar\" and \"Price is $\"\n",
+ " # This ensures that the model receives a cleaner, simpler prompt.\n",
+ " user_prompt = item.test_prompt().replace(\" to the nearest dollar\", \"\").replace(\"\\n\\nPrice is $\", \"\")\n",
+ "\n",
+ " # Reformat messages to Gemini’s expected format: messages = [{'role':'user', 'parts': ['hello']}]\n",
+ " return [\n",
+ " {\"role\": \"system\", \"parts\": [system_message]}, # System-level instruction\n",
+ " {\"role\": \"user\", \"parts\": [user_prompt]}, # User's query\n",
+ " {\"role\": \"model\", \"parts\": [\"Price is $\"]} # Assistant's expected prefix for response\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d6da66bb-bc4b-49ad-9224-a388470ef20b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Example usage of the gemini_messages_for function\n",
+ "gemini_messages_for(test[0]) # Generate message structure for the first test item"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b1af1888-f94a-4106-b0d8-8a70939eec4e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Utility function to extract the numerical price from a given string\n",
+ "# This function removes currency symbols and commas, then extracts the first number found.\n",
+ "def get_price(s):\n",
+ " s = s.replace('$', '').replace(',', '') # Remove currency symbols and formatting\n",
+ " match = re.search(r\"[-+]?\\d*\\.\\d+|\\d+\", s) # Regular expression to find a number\n",
+ " return float(match.group()) if match else 0 # Convert matched value to float, return 0 if no match"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a053c1a9-f86e-427c-a6be-ed8ec7bd63a5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Example usage of get_price function\n",
+ "get_price(\"The price is roughly $99.99 because blah blah\") # Expected output: 99.99"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "34a88e34-1719-4d08-adbe-adb69dfe5e83",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Function to get the estimated price using Gemini 1.5 Pro\n",
+ "def gemini_1_point_5_pro(item):\n",
+ " messages = gemini_messages_for(item) # Generate messages for the model\n",
+ " system_message = messages[0]['parts'][0] # Extract system-level instruction\n",
+ " user_messages = messages[1:] # Remove system message from messages list\n",
+ " \n",
+ " # Initialize Gemini 1.5 Pro model with system instruction\n",
+ " gemini = google_genai.GenerativeModel(\n",
+ " model_name=\"gemini-1.5-pro\",\n",
+ " system_instruction=system_message\n",
+ " )\n",
+ "\n",
+ " # Generate response using Gemini API\n",
+ " response = gemini.generate_content(\n",
+ " contents=user_messages,\n",
+ " generation_config=google_genai.GenerationConfig(max_output_tokens=5)\n",
+ " )\n",
+ "\n",
+ " # Extract text response and convert to numerical price\n",
+ " return get_price(response.text)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d89b10bb-8ebb-42ef-9146-f6e64e6849f9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Example usage:\n",
+ "gemini_1_point_5_pro(test[0])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "89ad07e6-a28a-4625-b61e-d2ce12d440fc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Retrieve the actual price of the test item (for comparison)\n",
+ "test[0].price # Output: 374.41"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "384f28e5-e51f-4cd3-8d74-30a8275530db",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Test the function for gemini-1.5 pro using the Tester framework\n",
+ "Tester.test(gemini_1_point_5_pro, test)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9b627291-b02e-48dd-9130-703498135ddf",
+ "metadata": {},
+ "source": [
+ "## Five, Gemini-2.0-flash"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0ee393a9-7afd-404f-92f2-a64bb4d5fb8b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Function to get the estimated price using Gemini-2.0-flash-exp\n",
+ "def gemini_2_point_0_flash_exp(item):\n",
+ " messages = gemini_messages_for(item) # Generate messages for the model\n",
+ " system_message = messages[0]['parts'][0] # Extract system-level instruction\n",
+ " user_messages = messages[1:] # Remove system message from messages list\n",
+ " \n",
+ " # Initialize Gemini-2.0-flash-exp model with system instruction\n",
+ " gemini = google_genai.GenerativeModel(\n",
+ " model_name=\"gemini-2.0-flash-exp\",\n",
+ " system_instruction=system_message\n",
+ " )\n",
+ "\n",
+ " # Adding a delay to avoid hitting the API rate limit and getting a \"ResourceExhausted: 429\" error\n",
+ " time.sleep(5)\n",
+ " \n",
+ " # Generate response using Gemini API\n",
+ " response = gemini.generate_content(\n",
+ " contents=user_messages,\n",
+ " generation_config=google_genai.GenerationConfig(max_output_tokens=5)\n",
+ " )\n",
+ "\n",
+ " # Extract text response and convert to numerical price\n",
+ " return get_price(response.text)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "203dc6f1-309e-46eb-9957-e06eed803cc8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Example usage:\n",
+ "gemini_2_point_0_flash_exp(test[0]) "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a844df09-d347-40b9-bb79-006ec4160aab",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Retrieve the actual price of the test item (for comparison)\n",
+ "test[0].price # Output: 374.41"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "500b45c7-e5c1-44f2-95c9-1c3c06365339",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Test the function for gemini-2.0-flash-exp using the Tester framework\n",
+ "Tester.test(gemini_2_point_0_flash_exp, test)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "746b2d12-ba92-48e2-9065-c9a108d1593b",
+ "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
+}
From 00e6d3ec388bc1755f541cbc72f12bc3a868af5d Mon Sep 17 00:00:00 2001
From: Nicholas Arquette
Date: Fri, 31 Jan 2025 18:20:37 -0600
Subject: [PATCH 55/61] Feature: Added a chat RAG example with sample medical
provide note data supplied from mtsamples.com.
---
.../rag_chat_example/README.md | 37 +++
.../rag_chat_example/img.png | Bin 0 -> 90717 bytes
.../test_patient_1_f/progress_note.txt | 44 +++
.../test_patient_2_f/progress_note.txt | 50 ++++
.../test_patient_3_m/progress_note.txt | 25 ++
.../test_patient_4_f/progress_note.txt | 54 ++++
.../rag_chat_example/run_rag_chat.py | 59 ++++
.../rag_chat_example/utils.py | 267 ++++++++++++++++++
8 files changed, 536 insertions(+)
create mode 100644 week5/community-contributions/rag_chat_example/README.md
create mode 100644 week5/community-contributions/rag_chat_example/img.png
create mode 100644 week5/community-contributions/rag_chat_example/knowledge_base/mtsample_dictations/test_patient_1_f/progress_note.txt
create mode 100644 week5/community-contributions/rag_chat_example/knowledge_base/mtsample_dictations/test_patient_2_f/progress_note.txt
create mode 100644 week5/community-contributions/rag_chat_example/knowledge_base/mtsample_dictations/test_patient_3_m/progress_note.txt
create mode 100644 week5/community-contributions/rag_chat_example/knowledge_base/mtsample_dictations/test_patient_4_f/progress_note.txt
create mode 100644 week5/community-contributions/rag_chat_example/run_rag_chat.py
create mode 100644 week5/community-contributions/rag_chat_example/utils.py
diff --git a/week5/community-contributions/rag_chat_example/README.md b/week5/community-contributions/rag_chat_example/README.md
new file mode 100644
index 0000000..7f92b0c
--- /dev/null
+++ b/week5/community-contributions/rag_chat_example/README.md
@@ -0,0 +1,37 @@
+# Overview
+
+This uses de-identified medical dictation data supplied by [mtsamples](https://mtsamples.com). The data from the mtsamples
+website was download from [kaggle](https://www.kaggle.com/datasets/tboyle10/medicaltranscriptions). There are four
+sample notes in different directories (see knowledge_base/mtsamples_dictations) that will added to a chromaDb
+vector database and will be available during chat using RAG (Retrieval Augmented Generation).
+
+# How to run
+
+- Run example
+
+```shell
+conda activate
+cd
+python run_rag_chat.py
+```
+
+# Chat example
+
+
+
+# Questions to ask?
+
+1) How old is Ms. Connor?
+2) What are Ms. Connor's vital signs?
+3) How old is Ms. Mouse?
+4) What is Ms. Mouse concerned about?
+5) What are Ms. Mouse's vital signs?
+6) How old is Mr. Duck?
+7) Why did Mr. Duck go to the doctor?
+8) How old is Ms. Barbara?
+9) Why did Ms. Barbara go to the doctor?
+10) Is Ms. Barbara allergic to anything?
+
+
+
+
diff --git a/week5/community-contributions/rag_chat_example/img.png b/week5/community-contributions/rag_chat_example/img.png
new file mode 100644
index 0000000000000000000000000000000000000000..e8b2ba7fce0159f5325ac56f8812483966ad6a17
GIT binary patch
literal 90717
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