85 changed files with 13308 additions and 49 deletions
@ -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": 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 :)" |
||||
] |
||||
}, |
||||
{ |
||||
"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 |
||||
} |
@ -0,0 +1,126 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "d25b0aef-3e5e-4026-90ee-2b373bf262b7", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Step 0: Import libraries and load environment variables\n", |
||||
"import os\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from IPython.display import Markdown, display\n", |
||||
"from openai import OpenAI\n", |
||||
"\n", |
||||
"load_dotenv(override=True)\n", |
||||
"api_key = os.getenv(\"OPENAI_API_KEY\")\n", |
||||
"\n", |
||||
"if not api_key:\n", |
||||
" print(\"No API key was found!\")\n", |
||||
"elif not api_key.startswith(\"sk-proj-\"):\n", |
||||
" print(\"An API key was found, but it does not start with 'sk-proj-'! Please ensure you are using the right key.\")\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.\")\n", |
||||
"else:\n", |
||||
" print(\"API key found and looks good so far!\")\n", |
||||
"\n", |
||||
"# Step 1: Create prompts\n", |
||||
"print(\"[INFO] Creating system prompt ...\")\n", |
||||
"system_prompt = \"You are an assistant that analyzes the contents of \\\n", |
||||
" email texts and suggests short subject lines for the email based \\\n", |
||||
" on the requested tone and language. Respond in markdown.\"\n", |
||||
"\n", |
||||
"print(\"[INFO] Creating user prompt ...\")\n", |
||||
"user_prompt = \"\"\"\n", |
||||
" The text below is an e-mail text for which you are required to \\\n", |
||||
" provide subject lines. Please provide two snarky, two funny, and \\\n", |
||||
" two formal short subject lines for the email text. Each of the six \\\n", |
||||
" subject lines should be presented in both English and French \\\n", |
||||
" languages, making a total of 12 subject lines. Please provide your \\\n", |
||||
" answer in markdown.\\\n", |
||||
" \n", |
||||
" \\n\\n\n", |
||||
" \n", |
||||
" Welcome to arXiv!\n", |
||||
"\n", |
||||
" Thank you for creating an account and joining the arXiv community. We look\n", |
||||
" forward to receiving your contribution.\n", |
||||
"\n", |
||||
" Help Pages\n", |
||||
" An overview on how to navigate and use arXiv can be found here:\n", |
||||
" https://arxiv.org/help\n", |
||||
" https://arxiv.org/about\n", |
||||
"\n", |
||||
" If you would like to know more about the submission process, please go here:\n", |
||||
" https://arxiv.org/help/submit\n", |
||||
"\n", |
||||
" Before Submitting to arXiv\n", |
||||
" The arXiv.org e-print archive is fully automated and processes nearly\n", |
||||
" 1,000 new submissions per day. To help us keep the process running smoothly\n", |
||||
" and efficiently please check your submission carefully for mistakes, typos\n", |
||||
" and layout issues. Once you have submitted your work please check your account\n", |
||||
" frequently for verification messages and other communication from arXiv.\n", |
||||
"\n", |
||||
" Contacting arXiv\n", |
||||
" We have provided extensive help pages to guide you through the process and\n", |
||||
" to answer the most common questions. If you have problems with the submission\n", |
||||
" process please contact us here:\n", |
||||
" https://arxiv.org/help/contact\n", |
||||
" We aim to assist submitters within one business day, but during times of high\n", |
||||
" volume or maintenance work we may be slightly delayed in our response.\n", |
||||
"\n", |
||||
" Thank you for your cooperation.\n", |
||||
"\"\"\"\n", |
||||
"\n", |
||||
"# Step 2: Make messages list\n", |
||||
"print(\"[INFO] Making messages list ...\")\n", |
||||
"messages = [\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": user_prompt}\n", |
||||
"]\n", |
||||
"\n", |
||||
"# Step 3: Call OpenAI\n", |
||||
"print(\"[INFO] Calling OpenAI ...\")\n", |
||||
"openai = OpenAI()\n", |
||||
"response = openai.chat.completions.create(\n", |
||||
" model=\"gpt-4o-mini\",\n", |
||||
" messages=messages\n", |
||||
" )\n", |
||||
"\n", |
||||
"# Step 4: Print result\n", |
||||
"print(\"[INFO] Print result ...\")\n", |
||||
"display(Markdown(response.choices[0].message.content))\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "b0a6676e-fb43-4725-9389-2acd74c13c4e", |
||||
"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.12.8" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -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": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#181;\">Business applications</h2>\n", |
||||
" <span style=\"color:#181;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>\n", |
||||
"\n", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Before you continue - now try yourself</h2>\n", |
||||
" <span style=\"color:#900;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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 |
||||
} |
@ -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": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#181;\">Business applications</h2>\n", |
||||
" <span style=\"color:#181;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>\n", |
||||
"\n", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Before you continue - now try yourself</h2>\n", |
||||
" <span style=\"color:#900;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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 |
||||
} |
@ -0,0 +1,159 @@
|
||||
{ |
||||
"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": "0d2d5441-2afe-41b9-8039-c367acd715f9", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"openai = OpenAI()" |
||||
] |
||||
}, |
||||
{ |
||||
"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" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "d9edf96e-1190-44fe-9261-405709fb39cd", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [] |
||||
} |
||||
], |
||||
"metadata": { |
||||
"kernelspec": { |
||||
"display_name": "Python 3 (ipykernel)", |
||||
"language": "python", |
||||
"name": "python3" |
||||
}, |
||||
"language_info": { |
||||
"codemirror_mode": { |
||||
"name": "ipython", |
||||
"version": 3 |
||||
}, |
||||
"file_extension": ".py", |
||||
"mimetype": "text/x-python", |
||||
"name": "python", |
||||
"nbconvert_exporter": "python", |
||||
"pygments_lexer": "ipython3", |
||||
"version": "3.11.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,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 |
||||
} |
@ -0,0 +1,316 @@
|
||||
{ |
||||
"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\n", |
||||
"\n", |
||||
"An example of the tool's output can be found [here](https://tvarol.github.io/sideProjects/AILLMAgents/output.html)." |
||||
] |
||||
}, |
||||
{ |
||||
"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=\"<b>Status:</b> 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 = \"<b>Status:</b> 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 = \"<b>Status:</b> CV uploaded and processed successfully!\"\n", |
||||
" except Exception as e:\n", |
||||
" status.value = f\"<b>Status:</b> 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 = \"<b>Status:</b> 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 = \"<b>Status:</b> Job posting submitted successfully!\"\n", |
||||
" else:\n", |
||||
" status.value = \"<b>Status:</b> 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=\"<h3>Input Job Posting and CV</h3>\"),\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 |
||||
} |
@ -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 |
||||
} |
@ -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=\"<b>Status:</b> 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 = \"<b>Status:</b> 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 = \"<b>Status:</b> 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=\"<h2>Input Job Posting Url</h2>\"),\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=\"<b>Status:</b> 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 = \"<b>Status:</b> 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 = \"<b>Status:</b> CV uploaded and processed successfully!\"\n", |
||||
" except Exception as e:\n", |
||||
" status.value = f\"<b>Status:</b> 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 = \"<b>Status:</b> 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=\"<h2>Import CV and submit</h2>\"),\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 |
||||
} |
@ -0,0 +1,979 @@
|
||||
{ |
||||
"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", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Please read - important note</h2>\n", |
||||
" <span style=\"color:#900;\">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...</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>\n", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#181;\">Business value of these exercises</h2>\n", |
||||
" <span style=\"color:#181;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 2, |
||||
"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": 3, |
||||
"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": 4, |
||||
"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": 5, |
||||
"id": "a58394bf-1e45-46af-9bfd-01e24da6f49a", |
||||
"metadata": {}, |
||||
"outputs": [ |
||||
{ |
||||
"name": "stdout", |
||||
"output_type": "stream", |
||||
"text": [ |
||||
"Hello! I’m glad to hear from you! 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": 6, |
||||
"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": 7, |
||||
"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": 8, |
||||
"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": 9, |
||||
"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": 10, |
||||
"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": 11, |
||||
"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": 12, |
||||
"id": "21ed95c5-7001-47de-a36d-1d6673b403ce", |
||||
"metadata": {}, |
||||
"outputs": [ |
||||
{ |
||||
"name": "stdout", |
||||
"output_type": "stream", |
||||
"text": [ |
||||
"Oh, we're starting with the basics, huh? Well, 2 + 2 equals 4. Shocking, I know!\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": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"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": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"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": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"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": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"metadata": {}, |
||||
"output_type": "display_data" |
||||
} |
||||
], |
||||
"source": [ |
||||
"display_summary('https://cppinvestments.com')" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "c951be1a-7f1b-448f-af1f-845978e47e2c", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#181;\">Business applications</h2>\n", |
||||
" <span style=\"color:#181;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>\n", |
||||
"\n", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Before you continue - now try yourself</h2>\n", |
||||
" <span style=\"color:#900;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"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": "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": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"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", |
||||
"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 |
||||
} |
@ -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", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Please read - important note</h2>\n", |
||||
" <span style=\"color:#900;\">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...</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>\n", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#181;\">Business value of these exercises</h2>\n", |
||||
" <span style=\"color:#181;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#181;\">Business applications</h2>\n", |
||||
" <span style=\"color:#181;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>\n", |
||||
"\n", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Before you continue - now try yourself</h2>\n", |
||||
" <span style=\"color:#900;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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 |
||||
} |
@ -0,0 +1,170 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 8, |
||||
"id": "6ba7c60a-c338-49a1-b1ba-46b7c20e33cb", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"import openai\n", |
||||
"import os\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from openai import OpenAI\n", |
||||
"from IPython.display import Markdown, display" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 2, |
||||
"id": "4acb4062-17b2-43b1-8b74-aefaa9599463", |
||||
"metadata": {}, |
||||
"outputs": [ |
||||
{ |
||||
"name": "stdout", |
||||
"output_type": "stream", |
||||
"text": [ |
||||
"API key found and looks good so far!\n" |
||||
] |
||||
} |
||||
], |
||||
"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": 5, |
||||
"id": "56f011b2-b759-4ad6-9d01-870fbcb8ade1", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def generate_quiz(topic):\n", |
||||
" prompt = f\"Generate a multiple-choice quiz with 5 questions on the topic: {topic}. Include the correct answer for each question.\"\n", |
||||
" \n", |
||||
" messages = [\n", |
||||
" {\"role\": \"system\", \"content\": \"You are a quiz generator. Create a multiple-choice quiz with 5 questions and provide the correct answers.Respond in markdown.\"},\n", |
||||
" {\"role\": \"user\", \"content\": prompt}\n", |
||||
" ]\n", |
||||
" \n", |
||||
" response = openai.chat.completions.create(\n", |
||||
" model=\"gpt-4\",\n", |
||||
" messages=messages,\n", |
||||
" max_tokens=300\n", |
||||
" )\n", |
||||
" \n", |
||||
" return response.choices[0].message.content" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 10, |
||||
"id": "1cf977e7-b04b-49e7-8b0a-d0ab2800c234", |
||||
"metadata": {}, |
||||
"outputs": [ |
||||
{ |
||||
"data": { |
||||
"text/markdown": [ |
||||
"**Question 1:** What is Python?\n", |
||||
"\n", |
||||
"**Choice A:** A type of snake\n", |
||||
"**Choice B:** A medical term\n", |
||||
"**Choice C:** A drilling tool\n", |
||||
"**Choice D:** A high-level programming language\n", |
||||
"\n", |
||||
"Correct Answer: **Choice D:** A high-level programming language\n", |
||||
"\n", |
||||
"**Question 2:** In Python, what keyword is used to create a function?\n", |
||||
"\n", |
||||
"**Choice A:** func\n", |
||||
"**Choice B:** def\n", |
||||
"**Choice C:** function\n", |
||||
"**Choice D:** create\n", |
||||
"\n", |
||||
"Correct Answer: **Choice B:** def\n", |
||||
"\n", |
||||
"**Question 3:** What is the correct syntax to output \"Hello World\" in Python?\n", |
||||
"\n", |
||||
"**Choice A:** printf(\"Hello World\")\n", |
||||
"**Choice B:** println(\"Hello World\")\n", |
||||
"**Choice C:** echo(\"Hello World\")\n", |
||||
"**Choice D:** print(\"Hello World\")\n", |
||||
"\n", |
||||
"Correct Answer: **Choice D:** print(\"Hello World\")\n", |
||||
"\n", |
||||
"**Question 4:** How would you create a variable \"x\" that equals 5 in Python?\n", |
||||
"\n", |
||||
"**Choice A:** var x = 5\n", |
||||
"**Choice B:** x := 5\n", |
||||
"**Choice C:** x = 5\n", |
||||
"**Choice D:** x : 5\n", |
||||
"\n", |
||||
"Correct Answer: **Choice C:** x = 5\n", |
||||
"\n", |
||||
"**Question 5:** How do you create a comment in Python?\n", |
||||
"\n", |
||||
"**Choice A:** // This is a comment\n", |
||||
"**Choice B:** # This is a comment\n", |
||||
"**Choice C:** <!-- This is a comment -->\n", |
||||
"**Choice D:** /* This is a comment */\n", |
||||
"\n", |
||||
"Correct Answer" |
||||
], |
||||
"text/plain": [ |
||||
"<IPython.core.display.Markdown object>" |
||||
] |
||||
}, |
||||
"metadata": {}, |
||||
"output_type": "display_data" |
||||
} |
||||
], |
||||
"source": [ |
||||
"# Example usage\n", |
||||
"topic = \"Python programming\"\n", |
||||
"quiz = generate_quiz(topic)\n", |
||||
"display(Markdown(quiz))" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "70990d7c-6061-43c6-b3c9-9146a3c51c3e", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [] |
||||
} |
||||
], |
||||
"metadata": { |
||||
"kernelspec": { |
||||
"display_name": "Python 3 (ipykernel)", |
||||
"language": "python", |
||||
"name": "python3" |
||||
}, |
||||
"language_info": { |
||||
"codemirror_mode": { |
||||
"name": "ipython", |
||||
"version": 3 |
||||
}, |
||||
"file_extension": ".py", |
||||
"mimetype": "text/x-python", |
||||
"name": "python", |
||||
"nbconvert_exporter": "python", |
||||
"pygments_lexer": "ipython3", |
||||
"version": "3.11.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,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": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../resources.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#f71;\">Just before we get to the assignment --</h2>\n", |
||||
" <span style=\"color:#f71;\">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.<br/>\n", |
||||
" <a href=\"https://edwarddonner.com/2024/11/13/llm-engineering-resources/\">https://edwarddonner.com/2024/11/13/llm-engineering-resources/</a><br/>\n", |
||||
" Please keep this bookmarked, and I'll continue to add more useful links there over time.\n", |
||||
" </span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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 |
||||
} |
@ -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 |
||||
} |
@ -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 |
||||
} |
Binary file not shown.
@ -0,0 +1,308 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "it1JLoxrSqO1", |
||||
"metadata": { |
||||
"id": "it1JLoxrSqO1" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"!pip install openai python-docx python-dotenv" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "950a084a-7f92-4669-af62-f07cb121da56", |
||||
"metadata": { |
||||
"id": "950a084a-7f92-4669-af62-f07cb121da56" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"import os\n", |
||||
"import json\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from IPython.display import Markdown, display, update_display\n", |
||||
"from openai import OpenAI\n", |
||||
"from docx import Document" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "ab9f734f-ed6f-44f6-accb-594f9ca4843d", |
||||
"metadata": { |
||||
"id": "ab9f734f-ed6f-44f6-accb-594f9ca4843d" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"class ReqDoc:\n", |
||||
" def __init__(self, file_path):\n", |
||||
" self.file_path = file_path\n", |
||||
"\n", |
||||
" def extract(self):\n", |
||||
" \"\"\"\n", |
||||
" Reads the content of a .docx file and returns the paragraphs as a list of strings.\n", |
||||
" \"\"\"\n", |
||||
" try:\n", |
||||
" # Check if the file exists\n", |
||||
" if not os.path.exists(self.file_path):\n", |
||||
" raise FileNotFoundError(f\"The file {self.file_path} was not found.\")\n", |
||||
"\n", |
||||
" # Attempt to open and read the document\n", |
||||
" doc = Document(self.file_path)\n", |
||||
" text = \"\\n\".join([paragraph.text for paragraph in doc.paragraphs])\n", |
||||
" return text\n", |
||||
"\n", |
||||
" except FileNotFoundError as fnf_error:\n", |
||||
" print(fnf_error)\n", |
||||
" return None\n", |
||||
" except Exception as e:\n", |
||||
" print(f\"An error occurred: {e}\")\n", |
||||
" return None\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "008f485a-5718-48f6-b408-06eb6d59d7f9", |
||||
"metadata": { |
||||
"id": "008f485a-5718-48f6-b408-06eb6d59d7f9" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Initialize and constants\n", |
||||
"load_dotenv(override=True)\n", |
||||
"api_key = os.getenv('OPENAI_API_KEY')\n", |
||||
"\n", |
||||
"if api_key and api_key.startswith('sk-proj') and len(api_key)>10:\n", |
||||
" print(\"API key looks good!\")\n", |
||||
"else:\n", |
||||
" print(\"There might be a problem with your API key. Please check!\")\n", |
||||
" \n", |
||||
"MODEL = 'gpt-4o-mini'\n", |
||||
"openai = OpenAI()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "b6110ff3-74bc-430a-8051-7d86a216f0fb", |
||||
"metadata": { |
||||
"id": "b6110ff3-74bc-430a-8051-7d86a216f0fb" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#Set up system prompt for extracting just the requirements from the document\n", |
||||
"\n", |
||||
"req_doc_system_prompt = \"You are provided with a complete requirements specifications document. \\\n", |
||||
"You are able to decide which content from that document are related to actual requirements, identify each requirement as \\\n", |
||||
"functional or non-functional and list them all.\\n\"\n", |
||||
"req_doc_system_prompt += \"If the document is empty or do not contain requirements or if you cannot extract them, please respond as such.\\\n", |
||||
"Do not make up your own requirements. \\n\"\n", |
||||
"req_doc_system_prompt += \"You should respond in JSON as in this example:\"\n", |
||||
"req_doc_system_prompt += \"\"\"\n", |
||||
"{\n", |
||||
" \"requirements\": [\n", |
||||
" {\"RequirementNo\": \"FR-01\", \"Requirement Description\": \"description of this functional requirement goes here\"},\n", |
||||
" {\"RequirementNo\": \"FR-02\": \"Requirement Description\": \"description of this functional requirement goes here\"},\n", |
||||
" {\"RequirementNo\": \"NFR-01\": \"Requirement Description\": \"description of this non-functional requirement goes here\"},\n", |
||||
" {\"RequirementNo\": \"NFR-02\": \"Requirement Description\": \"description of this non-functional requirement goes here\"}\n", |
||||
" ]\n", |
||||
"}\n", |
||||
"\"\"\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "20460e45-c1b7-4dc4-ab07-932235c19895", |
||||
"metadata": { |
||||
"id": "20460e45-c1b7-4dc4-ab07-932235c19895" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#Set up user prompt, sending in the requirements doc as input and calling the ReqDoc.extract function. Key to note here is the explicit instructions to\n", |
||||
"#respond in JSON format.\n", |
||||
"\n", |
||||
"def req_doc_user_prompt(doc):\n", |
||||
" user_prompt = \"Here is the contents from a requirement document.\\n\"\n", |
||||
" user_prompt += f\"{doc.extract()} \\n\"\n", |
||||
" user_prompt += \"Please scan through the document and extract only the actual requirements. For example, ignore sections or \\\n", |
||||
"paragraphs such as Approvers, table of contents and similar sections which are not really requirements.\\\n", |
||||
"You must respond in a JSON format\"\n", |
||||
" user_prompt += \"If the content is empty, respond that there are no valid requirements you could extract and ask for a proper document.\\n\"\n", |
||||
" user_prompt = user_prompt[:25_000] # Truncate if more than 25,000 characters\n", |
||||
" return user_prompt\n", |
||||
"\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "3a9f0f84-69a0-4971-a545-5bb40c2f9891", |
||||
"metadata": { |
||||
"id": "3a9f0f84-69a0-4971-a545-5bb40c2f9891" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#Function to call chatgpt-4o-mini model with the user and system prompts set above and returning the json formatted result obtained from chatgpt\n", |
||||
"\n", |
||||
"def get_requirements(doc):\n", |
||||
" reqdoc = ReqDoc(doc)\n", |
||||
" response = openai.chat.completions.create(\n", |
||||
" model=MODEL,\n", |
||||
" messages=[\n", |
||||
" {\"role\": \"system\", \"content\": req_doc_system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": req_doc_user_prompt(reqdoc)}\n", |
||||
" ],\n", |
||||
" response_format={\"type\": \"json_object\"}\n", |
||||
" )\n", |
||||
" result = response.choices[0].message.content\n", |
||||
" return json.loads(result)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "f9bb04ef-78d3-4e0f-9ed1-59a961a0663e", |
||||
"metadata": { |
||||
"id": "f9bb04ef-78d3-4e0f-9ed1-59a961a0663e" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#Uncomment and run this if you want to see the extracted requriements in json format.\n", |
||||
"#get_requirements(\"reqdoc.docx\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "1fe8618c-1dfe-4030-bad8-405731294c93", |
||||
"metadata": { |
||||
"id": "1fe8618c-1dfe-4030-bad8-405731294c93" |
||||
}, |
||||
"source": [ |
||||
"### Next, we will make another call to gpt-4o-mini" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "db2c1eb3-7740-43a4-9c0b-37b7e70c739b", |
||||
"metadata": { |
||||
"id": "db2c1eb3-7740-43a4-9c0b-37b7e70c739b" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#Set up system prompt to ask for test cases in table format\n", |
||||
"\n", |
||||
"system_prompt = \"You are an assitant that receives a list of functional and non functional requirements in JSON format. You are the expert in generating unit test cases for each requirement. \\\n", |
||||
"You will create as many different test cases as needed for each requirement and produce a result in a table. Order the table by requirement No. Provide clear details on test case pass criteria. \\\n", |
||||
"The table will contain the following columns. \\\n", |
||||
"1.S No\\\n", |
||||
"2.Requirement No\\\n", |
||||
"3.Requirement Description\\\n", |
||||
"4.Test Case ID\\\n", |
||||
"5.Test case summary\\\n", |
||||
"6.Test case description\\\n", |
||||
"7.Success criteria \\n\"\n", |
||||
"system_prompt += \"If you are provided with an empty list, ask for a proper requirement doc\\n\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "c4cd2bdf-e1bd-43ff-85fa-760ba39ed8c5", |
||||
"metadata": { |
||||
"id": "c4cd2bdf-e1bd-43ff-85fa-760ba39ed8c5" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Set up user prompt passing in the req doc file. This in turn will call the get_requirements function, which will make a call to chatgpt.\n", |
||||
"\n", |
||||
"def get_testcase_user_prompt(reqdoc):\n", |
||||
" user_prompt = \"You are looking at the following list of requirements. \\n\"\n", |
||||
" user_prompt += f\"{get_requirements(reqdoc)}\\n\"\n", |
||||
" user_prompt += \"Prepare unit test cases for each of these requirements in a table and send that table as response. \\n\"\n", |
||||
" user_prompt += user_prompt[:25000]\n", |
||||
" return user_prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "59d859e2-e5bb-4bd6-ab59-5ad967d5d2e0", |
||||
"metadata": { |
||||
"id": "59d859e2-e5bb-4bd6-ab59-5ad967d5d2e0" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#This is the 2nd call to chatgpt to get test cases. display(Markdown) will take care of producing a neatly formatted table output.\n", |
||||
"def create_testcase_doc(reqdoc):\n", |
||||
" stream = openai.chat.completions.create(\n", |
||||
" model=MODEL,\n", |
||||
" messages=[\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": get_testcase_user_prompt(reqdoc)}\n", |
||||
" ],\n", |
||||
" stream=True\n", |
||||
" )\n", |
||||
" response = \"\"\n", |
||||
" display_handle = display(Markdown(\"\"), display_id=True)\n", |
||||
" for chunk in stream:\n", |
||||
" response += chunk.choices[0].delta.content or ''\n", |
||||
" response = response.replace(\"```\",\"\").replace(\"markdown\", \"\")\n", |
||||
" update_display(Markdown(response), display_id=display_handle.display_id)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "0612d662-7047-4620-aa1c-2eb1c3d715cb", |
||||
"metadata": { |
||||
"id": "0612d662-7047-4620-aa1c-2eb1c3d715cb" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#The final piece of code. Provide the uploaded requirements filename below.\n", |
||||
"file_path = r\"reqdoc.docx\"\n", |
||||
"#print(file_path)\n", |
||||
"create_testcase_doc(file_path)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "82ae4371-22dd-4f2a-97c9-a70e0232a0aa", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [] |
||||
} |
||||
], |
||||
"metadata": { |
||||
"colab": { |
||||
"provenance": [] |
||||
}, |
||||
"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.13.1" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -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 |
||||
} |
@ -0,0 +1,45 @@
|
||||
import ollama, os |
||||
from openai import OpenAI |
||||
from dotenv import load_dotenv |
||||
from IPython.display import Markdown, display |
||||
|
||||
load_dotenv() |
||||
|
||||
open_key = os.getenv("OPENAI_API_KEY") |
||||
|
||||
OPEN_MODEL = "gpt-4-turbo" |
||||
ollama_model = "llama3.2" |
||||
openai = OpenAI() |
||||
|
||||
system_prompt = "You are an assistant that focuses on the reason for each code, analysing and interpreting what the code does and how it could be improved, \ |
||||
Give your answer in markdown down with two different topics namely: Explanation and Code Improvement. However if you think there is no possible improvement \ |
||||
to said code, simply state 'no possible improvement '" |
||||
|
||||
def user_prompt(): |
||||
custom_message = input("Write your prompt message: ") |
||||
return custom_message |
||||
|
||||
def explain(): |
||||
response = openai.chat.completions.create(model=OPEN_MODEL, |
||||
messages = [ |
||||
{"role":"system", "content":system_prompt}, |
||||
{"role": "user", "content":user_prompt()} |
||||
]) |
||||
result = response.choices[0].message.content |
||||
display(Markdown(result)) |
||||
|
||||
# explain() run this to get the openai output with peronalized input |
||||
|
||||
#With ollama |
||||
|
||||
ollama_api = "https://localhost:11434/api/chat" |
||||
|
||||
def explainer_with_ollama(): |
||||
response = ollama.chat(model=ollama_model, messages=[ |
||||
{"role":"system", "content":system_prompt}, |
||||
{"role":"user", "content":user_prompt()} |
||||
]) |
||||
result = response["message"]["content"] |
||||
display(Markdown(result)) |
||||
|
||||
#explainer_with_ollama() run for ollama output with same personalized input |
@ -0,0 +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", |
||||
"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()" |
||||
] |
||||
}, |
||||
{ |
||||
"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 |
||||
} |
@ -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 |
||||
} |
@ -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 |
@ -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": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Important Note - Please read me</h2>\n", |
||||
" <span style=\"color:#900;\">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.<br/>\n", |
||||
" First do a <a href=\"https://chatgpt.com/share/6734e705-3270-8012-a074-421661af6ba9\">git pull and merge your changes as needed</a>. Any problems? Try asking ChatGPT to clarify how to merge - or contact me!<br/><br/>\n", |
||||
" After you've pulled the code, from the llm_engineering directory, in an Anaconda prompt (PC) or Terminal (Mac), run:<br/>\n", |
||||
" <code>conda env update --f environment.yml</code><br/>\n", |
||||
" Or if you used virtualenv rather than Anaconda, then run this from your activated environment in a Powershell (PC) or Terminal (Mac):<br/>\n", |
||||
" <code>pip install -r requirements.txt</code>\n", |
||||
" <br/>Then restart the kernel (Kernel menu >> Restart Kernel and Clear Outputs Of All Cells) to pick up the changes.\n", |
||||
" </span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>\n", |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../../resources.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#f71;\">Reminder about the resources page</h2>\n", |
||||
" <span style=\"color:#f71;\">Here's a link to resources for the course. This includes links to all the slides.<br/>\n", |
||||
" <a href=\"https://edwarddonner.com/2024/11/13/llm-engineering-resources/\">https://edwarddonner.com/2024/11/13/llm-engineering-resources/</a><br/>\n", |
||||
" Please keep this bookmarked, and I'll continue to add more useful links there over time.\n", |
||||
" </span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../../important.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#900;\">Before you continue</h2>\n", |
||||
" <span style=\"color:#900;\">\n", |
||||
" Be sure you understand how the conversation above is working, and in particular how the <code>messages</code> 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?<br/>\n", |
||||
" </span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"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": [ |
||||
"<table style=\"margin: 0; text-align: left;\">\n", |
||||
" <tr>\n", |
||||
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", |
||||
" <img src=\"../../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", |
||||
" </td>\n", |
||||
" <td>\n", |
||||
" <h2 style=\"color:#181;\">Business relevance</h2>\n", |
||||
" <span style=\"color:#181;\">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.</span>\n", |
||||
" </td>\n", |
||||
" </tr>\n", |
||||
"</table>" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "c23224f6-7008-44ed-a57f-718975f4e291", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [] |
||||
} |
||||
], |
||||
"metadata": { |
||||
"kernelspec": { |
||||
"display_name": "Python 3 (ipykernel)", |
||||
"language": "python", |
||||
"name": "python3" |
||||
}, |
||||
"language_info": { |
||||
"codemirror_mode": { |
||||
"name": "ipython", |
||||
"version": 3 |
||||
}, |
||||
"file_extension": ".py", |
||||
"mimetype": "text/x-python", |
||||
"name": "python", |
||||
"nbconvert_exporter": "python", |
||||
"pygments_lexer": "ipython3", |
||||
"version": "3.11.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,98 @@
|
||||
{ |
||||
"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": [ |
||||
"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": null, |
||||
"id": "cf3d34e9-f8a8-4a06-aa3a-8faeb5f81e68", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"gpt_startmessage = \"Hello\"\n", |
||||
"claude_startmessage = \"Hi\"\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "49335337-d713-4d9e-aba0-41a309c37699", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"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 |
||||
} |
@ -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 |
||||
} |
@ -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 |
||||
} |
@ -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": [ |
||||
"<div><iframe src=\"http://127.0.0.1:7873/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" |
||||
], |
||||
"text/plain": [ |
||||
"<IPython.core.display.HTML object>" |
||||
] |
||||
}, |
||||
"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 |
||||
} |
@ -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(\"<div class='output-label'>Output:</div>\")\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 |
||||
} |
@ -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 |
||||
} |
@ -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/ |
@ -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 |
@ -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() |
@ -0,0 +1,4 @@
|
||||
openai |
||||
requests |
||||
beautifulsoup4 |
||||
python-dotenv |
@ -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 |
@ -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) |
@ -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) |
@ -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.") |
@ -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 |
||||
} |
@ -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": [ |
||||
"<div><iframe src=\"http://127.0.0.1:7864/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" |
||||
], |
||||
"text/plain": [ |
||||
"<IPython.core.display.HTML object>" |
||||
] |
||||
}, |
||||
"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 |
||||
} |
@ -0,0 +1,565 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "ff022957-2e81-4ea9-84d3-e52d5753e133", |
||||
"metadata": {}, |
||||
"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": null, |
||||
"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": null, |
||||
"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": null, |
||||
"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": null, |
||||
"id": "c8023255-9c98-4fbc-92e4-c553bed3b605", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"hf_token = os.environ['HF_TOKEN']\n", |
||||
"login(hf_token, add_to_git_credential=True)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"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": null, |
||||
"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": null, |
||||
"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": null, |
||||
"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", |
||||
" - 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": null, |
||||
"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": null, |
||||
"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": null, |
||||
"id": "192c30f5-4be6-49b7-a054-11bfcffa91e0", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"exec(pi)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"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": null, |
||||
"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": null, |
||||
"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": null, |
||||
"id": "47c615e2-4eb6-4ce1-ad09-7f2e6dbc3934", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"stream_comment_gpt(pi)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"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": null, |
||||
"id": "3dc90578-4f5e-47f1-b30f-c21b5795e82f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"stream_unit_test_gpt(pi)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"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": null, |
||||
"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": null, |
||||
"id": "ee43428e-b577-4e95-944d-399f2f3b89ff", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"stream_comment_claude(pi)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "0565e33b-9f14-48b7-ae8d-d22dc03b93c9", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"stream_unit_test_claude(pi)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"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=5000)\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": null, |
||||
"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": null, |
||||
"id": "0a756193-fcba-43da-a981-203c10d36488", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"stream_comment_model(code_qwen, CODE_QWEN_URL, pi)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "12ddcbf4-6286-47a8-847b-5be78e7aa995", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"stream_unit_test_model(code_qwen, CODE_QWEN_URL, pi)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"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": null, |
||||
"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": null, |
||||
"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": null, |
||||
"id": "ee27cc91-81e6-42c8-ae3c-c04161229d8c", |
||||
"metadata": { |
||||
"scrolled": true |
||||
}, |
||||
"outputs": [], |
||||
"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 |
||||
} |
@ -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 <script_location> |
||||
python generate_doc_string -fp <full_file_path> -llm <name_of_model> |
||||
``` |
||||
|
||||
# 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. |
@ -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 |
@ -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() |
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -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) |
@ -0,0 +1,869 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": { |
||||
"id": "ykDDGx1cjYlh" |
||||
}, |
||||
"source": [ |
||||
"# **DocuPy** \n", |
||||
"### _\"Automate Documentation, Comments, and Unit Tests for Python Code\"_ \n", |
||||
"\n", |
||||
"## Overview \n", |
||||
"DocuPy is a Gradio-powered tool designed to automate essential but time-consuming Python development tasks. It streamlines documentation, unit testing, and Python-to-C++ code conversion with AI-driven assistance. \n", |
||||
"\n", |
||||
"### Key Features \n", |
||||
"✅ **Auto-Generate Docstrings & Comments** – Instantly improve code clarity and maintainability. \n", |
||||
"✅ **Unit Test Generation** – Ensure reliability with AI-generated test cases. \n", |
||||
"✅ **Python to C++ Conversion** – Seamlessly translate Python code to C++ with execution support. \n", |
||||
"\n", |
||||
"With an intuitive tab-based UI, DocuPy enhances productivity for developers of all levels. Whether you're documenting functions, validating code with tests, or exploring C++ conversions, this tool lets you focus on coding while it handles the rest. \n", |
||||
"\n", |
||||
"🔗 **Check out the repo**: [GitHub Repo](https://github.com/emads22/DocuPy) \n", |
||||
"\n", |
||||
"💡 **Have insights, feedback, or ideas?** Feel free to reach out. \n", |
||||
"\n", |
||||
"[<img src=\"https://img.shields.io/badge/GitHub-Emad-blue?logo=github\" width=\"150\">](https://github.com/emads22)\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"If you're running this notebook on **`Google Colab`**, ensure you install the required libraries by running the following command:\n", |
||||
"\n", |
||||
"```bash\n", |
||||
"!pip install -q openai anthropic python-dotenv gradio huggingface_hub transformers\n", |
||||
"```\n", |
||||
"Otherwise, make sure to activate the Conda environment `docupy` that already includes these modules:\n", |
||||
"\n", |
||||
"```bash\n", |
||||
"conda activate docupy\n", |
||||
"```" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "6wIpBtNPjXc8" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Uncomment the following command when running on Google Colab\n", |
||||
"# !pip install -q openai anthropic python-dotenv gradio huggingface_hub transformers " |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": { |
||||
"id": "T-cTBf9amBxf" |
||||
}, |
||||
"source": [ |
||||
"## Setup and Install Dependencies\n", |
||||
"\n", |
||||
"- Start by installing all necessary libraries." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "aIHWC7xpk87X" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# imports\n", |
||||
"import os\n", |
||||
"import io\n", |
||||
"import sys\n", |
||||
"import subprocess\n", |
||||
"import openai\n", |
||||
"import anthropic\n", |
||||
"import google.generativeai as google_genai\n", |
||||
"import gradio as gr\n", |
||||
"from openai import OpenAI\n", |
||||
"# from google.colab import userdata\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from pathlib import Path\n", |
||||
"from huggingface_hub import login, InferenceClient\n", |
||||
"from transformers import AutoTokenizer" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": { |
||||
"id": "LZQbXR3dmZy4" |
||||
}, |
||||
"source": [ |
||||
"## Add Secrets to the Colab Notebook\n", |
||||
"\n", |
||||
"- Add the API keys for OpenAI, Claude, and Gemini to authenticate and access their respective models and services.\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "AadABekBm4fV" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# # Log in to Hugging Face using the token and add it to git credentials\n", |
||||
"# hf_token = userdata.get('HF_TOKEN')\n", |
||||
"# login(token=hf_token, add_to_git_credential=True)\n", |
||||
"\n", |
||||
"# # Endpoint URL for accessing the Code Qwen model through Hugging Face\n", |
||||
"# CODE_QWEN_URL = userdata.get('CODE_QWEN_URL')\n", |
||||
"\n", |
||||
"# # Initialize inference clients with every model using API keys\n", |
||||
"# gpt = openai.OpenAI(api_key=userdata.get('OPENAI_API_KEY'))\n", |
||||
"# claude = anthropic.Anthropic(api_key=userdata.get('ANTHROPIC_API_KEY'))\n", |
||||
"# google_genai.configure(api_key=userdata.get('GOOGLE_API_KEY'))\n", |
||||
"# code_qwen = InferenceClient(CODE_QWEN_URL, token=hf_token)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": { |
||||
"id": "Ej3JNfh_wc0m" |
||||
}, |
||||
"source": [ |
||||
"## Alternatively, if not running on Google Colab, Load Environment Variables for API Keys\n", |
||||
"\n", |
||||
"- Use the `load_dotenv()` function to securely load API keys from a `.env` file.\n", |
||||
"- Ensure that the `.env` file is located in the same directory as your script or Jupyter Notebook.\n", |
||||
"- The `.env` file should include the required API keys for OpenAI, Claude, and Gemini." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "av9X9XpQw0Vd" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"load_dotenv()\n", |
||||
"\n", |
||||
"# Log in to Hugging Face using the token and add it to git credentials\n", |
||||
"hf_token = os.getenv('HF_TOKEN')\n", |
||||
"login(token=hf_token, add_to_git_credential=True)\n", |
||||
"\n", |
||||
"# Endpoint URL for accessing the Code Qwen model through Hugging Face\n", |
||||
"CODE_QWEN_URL = os.getenv('CODE_QWEN_URL')\n", |
||||
"\n", |
||||
"# Initialize inference clients with every model using API keys\n", |
||||
"gpt = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))\n", |
||||
"claude = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))\n", |
||||
"google_genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))\n", |
||||
"code_qwen = InferenceClient(CODE_QWEN_URL, token=hf_token)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": { |
||||
"id": "lvEhCuQjrTYu" |
||||
}, |
||||
"source": [ |
||||
"## Define Required Constants\n", |
||||
"\n", |
||||
"- Initialize the essential constants required for the application's functionality.\n", |
||||
"- Configure the system and user prompts specific to each task or feature.\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "AKEBKKmAowt2" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Models\n", |
||||
"OPENAI_MODEL = \"gpt-4o\"\n", |
||||
"CLAUDE_MODEL = \"claude-3-5-sonnet-20240620\"\n", |
||||
"GEMINI_MODEL = \"gemini-1.5-pro\"\n", |
||||
"CODE_QWEN_MODEL = \"Qwen/CodeQwen1.5-7B-Chat\"\n", |
||||
"\n", |
||||
"MODELS_IN_USE = [\"GPT\", \"Claude\", \"Gemini\", \"CodeQwen\"]\n", |
||||
"\n", |
||||
"MAX_TOKENS = 2000\n", |
||||
"\n", |
||||
"ACTION_A = \"commenting\"\n", |
||||
"ACTION_B = \"testing\"\n", |
||||
"ACTION_C = \"converting\"\n", |
||||
"\n", |
||||
"# Define and create the path for the \"temp_files\" directory within the current script's directory\n", |
||||
"TEMP_DIR = Path.cwd() / \"temp_files\"\n", |
||||
"TEMP_DIR.mkdir(parents=True, exist_ok=True)\n", |
||||
"\n", |
||||
"PYTHON_SCRIPT_EASY = \"\"\"\n", |
||||
"import time\n", |
||||
"\n", |
||||
"def reverse_string(s):\n", |
||||
" return s[::-1]\n", |
||||
"\n", |
||||
"if __name__ == \"__main__\":\n", |
||||
" start_time = time.time()\n", |
||||
" text = \"Hello, World!\"\n", |
||||
" print(f\"- Original string: {text}\")\n", |
||||
" print(\"- Reversed string:\", reverse_string(text))\n", |
||||
" execution_time = time.time() - start_time \n", |
||||
" print(f\"\\\\n=> Execution Time: {execution_time:.6f} seconds\")\n", |
||||
"\"\"\"\n", |
||||
"\n", |
||||
"PYTHON_SCRIPT_INTERMEDIATE = \"\"\"\n", |
||||
"import time\n", |
||||
"\n", |
||||
"def is_palindrome(s):\n", |
||||
" s = s.lower().replace(\" \", \"\") \n", |
||||
" return s == s[::-1]\n", |
||||
"\n", |
||||
"if __name__ == \"__main__\":\n", |
||||
" start_time = time.time()\n", |
||||
" text = \"Racecar\"\n", |
||||
" if is_palindrome(text):\n", |
||||
" print(f\"- '{text}' is a palindrome!\")\n", |
||||
" else:\n", |
||||
" print(f\"- '{text}' is Not a palindrome.\")\n", |
||||
" execution_time = time.time() - start_time \n", |
||||
" print(f\"\\\\n=> Execution Time: {execution_time:.6f} seconds\")\n", |
||||
"\"\"\"\n", |
||||
"\n", |
||||
"PYTHON_SCRIPT_HARD = \"\"\"\n", |
||||
"import time\n", |
||||
"\n", |
||||
"def generate_primes(limit):\n", |
||||
" primes = []\n", |
||||
" for num in range(2, limit + 1):\n", |
||||
" if all(num % p != 0 for p in primes):\n", |
||||
" primes.append(num)\n", |
||||
" return primes\n", |
||||
"\n", |
||||
"if __name__ == \"__main__\":\n", |
||||
" start_time = time.time()\n", |
||||
" n = 20\n", |
||||
" print(f\"- Generating primes up to: {n}\")\n", |
||||
" print(\"- Prime numbers:\", generate_primes(n))\n", |
||||
" execution_time = time.time() - start_time \n", |
||||
" print(f\"\\\\n=> Execution Time: {execution_time:.6f} seconds\")\n", |
||||
"\"\"\"\n", |
||||
"\n", |
||||
"PYTHON_SCRIPTS = {\n", |
||||
" \"reverse_string\" : PYTHON_SCRIPT_EASY,\n", |
||||
" \"is_palindrome\" : PYTHON_SCRIPT_INTERMEDIATE,\n", |
||||
" \"generate_primes\" : PYTHON_SCRIPT_HARD,\n", |
||||
" \"custom\" : \"\"\"\n", |
||||
"# Write your custom Python script here\n", |
||||
"if __name__ == \"__main__\":\n", |
||||
" print(\"Hello, World!\")\n", |
||||
"\"\"\"\n", |
||||
"}\n", |
||||
"\n", |
||||
"# Relative system prompts\n", |
||||
"SYSTEM_PROMPT_COMMENTS = \"\"\"\n", |
||||
"You are an AI model specializing in enhancing Python code documentation.\n", |
||||
"Generate detailed and precise docstrings and inline comments for the provided Python code.\n", |
||||
"Ensure the docstrings clearly describe the purpose, parameters, and return values of each function.\n", |
||||
"Inline comments should explain complex or non-obvious code segments.\n", |
||||
"Do not include any introductions, explanations, conclusions, or additional context.\n", |
||||
"Return only the updated Python code enclosed within ```python ... ``` for proper formatting and syntax highlighting.\n", |
||||
"\"\"\"\n", |
||||
"\n", |
||||
"SYSTEM_PROMPT_TESTS = \"\"\"\n", |
||||
"You are an AI model specializing in generating comprehensive unit tests for Python code.\n", |
||||
"Create Python unit tests that thoroughly validate the functionality of the given code.\n", |
||||
"Use the `unittest` framework and ensure edge cases and error conditions are tested.\n", |
||||
"Do not include any comments, introductions, explanations, conclusions, or additional context.\n", |
||||
"Return only the unit test code enclosed within ```python ... ``` for proper formatting and syntax highlighting.\n", |
||||
"\"\"\"\n", |
||||
"\n", |
||||
"SYSTEM_PROMPT_CONVERT = \"\"\"\n", |
||||
"You are an AI model specializing in high-performance code translation.\n", |
||||
"Translate the given Python code into equivalent, optimized C++ code.\n", |
||||
"Focus on:\n", |
||||
"- Using efficient data structures and algorithms.\n", |
||||
"- Avoiding unnecessary memory allocations and computational overhead.\n", |
||||
"- Ensuring minimal risk of integer overflow by using appropriate data types.\n", |
||||
"- Leveraging the C++ Standard Library (e.g., `<vector>`, `<algorithm>`) for performance and readability.\n", |
||||
"Produce concise and efficient C++ code that matches the functionality of the original Python code.\n", |
||||
"Do not include any comments, introductions, explanations, conclusions, or additional context..\n", |
||||
"Return only the C++ code enclosed within ```cpp ... ``` for proper formatting and syntax highlighting.\n", |
||||
"\"\"\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "JJ1zttf7ANqD" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Relative user prompts\n", |
||||
"def user_prompt_comments(python_code):\n", |
||||
" user_prompt = f\"\"\"\n", |
||||
"Add detailed docstrings and inline comments to the following Python code:\n", |
||||
"\n", |
||||
"```python\n", |
||||
"{python_code}\n", |
||||
"```\n", |
||||
"\"\"\"\n", |
||||
" return user_prompt\n", |
||||
"\n", |
||||
"def user_prompt_tests(python_code):\n", |
||||
" user_prompt = f\"\"\"\n", |
||||
"Generate unit tests for the following Python code using the `unittest` framework:\n", |
||||
"\n", |
||||
"```python\n", |
||||
"{python_code}\n", |
||||
"```\n", |
||||
"\"\"\"\n", |
||||
" return user_prompt\n", |
||||
"\n", |
||||
"def user_prompt_convert(python_code):\n", |
||||
" user_prompt = f\"\"\"\n", |
||||
"Convert the following Python code into C++:\n", |
||||
"\n", |
||||
"```python\n", |
||||
"{python_code}\n", |
||||
"``` \n", |
||||
"\"\"\"\n", |
||||
" return user_prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": { |
||||
"id": "tqrOO_qsCRkd" |
||||
}, |
||||
"source": [ |
||||
"### Define the Tab Functions\n", |
||||
"\n", |
||||
"- Develop dedicated functions for each service: documenting Python code, generating unit tests, and converting Python to C++.\n", |
||||
"- Structure each function to handle user input, process it using the selected AI model, and display the generated output seamlessly.\n", |
||||
"- Ensure the functionality of each tab aligns with its specific purpose, providing an intuitive and efficient user experience.\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "HBsBrq3G94ul" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def stream_gpt(system_prompt, user_prompt):\n", |
||||
" stream = gpt.chat.completions.create(\n", |
||||
" model=OPENAI_MODEL,\n", |
||||
" messages=[\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": user_prompt}\n", |
||||
" ],\n", |
||||
" stream=True)\n", |
||||
" reply = \"\"\n", |
||||
" for chunk in stream:\n", |
||||
" reply += chunk.choices[0].delta.content or \"\"\n", |
||||
" yield reply.replace(\"```python\\n\", \"\").replace(\"```cpp\\n\", \"\").replace(\"```\", \"\")\n", |
||||
"\n", |
||||
"def stream_claude(system_prompt, user_prompt):\n", |
||||
" response = claude.messages.stream(\n", |
||||
" model=CLAUDE_MODEL,\n", |
||||
" max_tokens=MAX_TOKENS,\n", |
||||
" system=system_prompt,\n", |
||||
" messages=[{\"role\": \"user\", \"content\": user_prompt}],\n", |
||||
" )\n", |
||||
" reply = \"\"\n", |
||||
" with response as stream:\n", |
||||
" for text in stream.text_stream:\n", |
||||
" reply += text\n", |
||||
" yield reply.replace(\"```python\\n\", \"\").replace(\"```cpp\\n\", \"\").replace(\"```\", \"\")\n", |
||||
"\n", |
||||
"def stream_gemini(system_prompt, user_prompt):\n", |
||||
" gemini = google_genai.GenerativeModel(\n", |
||||
" model_name=GEMINI_MODEL,\n", |
||||
" system_instruction=system_prompt\n", |
||||
" )\n", |
||||
" stream = gemini.generate_content(\n", |
||||
" contents=user_prompt,\n", |
||||
" stream=True\n", |
||||
" )\n", |
||||
" reply = \"\"\n", |
||||
" for chunk in stream:\n", |
||||
" reply += chunk.text or \"\"\n", |
||||
" yield reply.replace(\"```python\\n\", \"\").replace(\"```cpp\\n\", \"\").replace(\"```\", \"\")\n", |
||||
"\n", |
||||
"def stream_code_qwen(system_prompt, user_prompt):\n", |
||||
" tokenizer = AutoTokenizer.from_pretrained(CODE_QWEN_MODEL)\n", |
||||
" model_input = tokenizer.apply_chat_template(\n", |
||||
" conversation=[\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": user_prompt}\n", |
||||
" ],\n", |
||||
" tokenize=False,\n", |
||||
" add_generation_prompt=True\n", |
||||
" )\n", |
||||
" stream = code_qwen.text_generation(\n", |
||||
" prompt=model_input,\n", |
||||
" stream=True,\n", |
||||
" details=True,\n", |
||||
" max_new_tokens=MAX_TOKENS\n", |
||||
" )\n", |
||||
" reply = \"\"\n", |
||||
" for chunk in stream:\n", |
||||
" reply += chunk.token.text or \"\"\n", |
||||
" yield reply.replace(\"```python\\n\", \"\").replace(\"```cpp\\n\", \"\").replace(\"```\", \"\")\n", |
||||
"\n", |
||||
"def set_prompts(user_input, action):\n", |
||||
" action = action.lower()\n", |
||||
"\n", |
||||
" if action == ACTION_A.lower():\n", |
||||
" system_prompt = SYSTEM_PROMPT_COMMENTS\n", |
||||
" user_prompt = user_prompt_comments(user_input)\n", |
||||
" elif action == ACTION_B.lower():\n", |
||||
" system_prompt = SYSTEM_PROMPT_TESTS\n", |
||||
" user_prompt = user_prompt_tests(user_input)\n", |
||||
" elif action == ACTION_C.lower():\n", |
||||
" system_prompt = SYSTEM_PROMPT_CONVERT\n", |
||||
" user_prompt = user_prompt_convert(user_input)\n", |
||||
" else:\n", |
||||
" return None, None\n", |
||||
" \n", |
||||
" return system_prompt, user_prompt\n", |
||||
"\n", |
||||
"def stream_response(user_input, model, action):\n", |
||||
" system_prompt, user_prompt = set_prompts(user_input, action)\n", |
||||
" if not all((system_prompt, user_prompt)):\n", |
||||
" raise ValueError(\"Unknown Action\")\n", |
||||
"\n", |
||||
" match model:\n", |
||||
" case \"GPT\":\n", |
||||
" yield from stream_gpt(system_prompt, user_prompt)\n", |
||||
"\n", |
||||
" case \"Claude\":\n", |
||||
" yield from stream_claude(system_prompt, user_prompt)\n", |
||||
"\n", |
||||
" case \"Gemini\":\n", |
||||
" yield from stream_gemini(system_prompt, user_prompt)\n", |
||||
"\n", |
||||
" case \"CodeQwen\":\n", |
||||
" yield from stream_code_qwen(system_prompt, user_prompt)\n", |
||||
" \n", |
||||
"def generate_comments(python_code, selected_model):\n", |
||||
" for model in MODELS_IN_USE:\n", |
||||
" if model == selected_model:\n", |
||||
" yield from stream_response(python_code, model, action=ACTION_A)\n", |
||||
" return # Exit the function immediately after exhausting the generator\n", |
||||
" raise ValueError(\"Unknown Model\")\n", |
||||
"\n", |
||||
"def generate_tests(python_code, selected_model):\n", |
||||
" for model in MODELS_IN_USE:\n", |
||||
" if model == selected_model:\n", |
||||
" yield from stream_response(python_code, model, action=ACTION_B)\n", |
||||
" return # Exit the function immediately after exhausting the generator\n", |
||||
" raise ValueError(\"Unknown Model\")\n", |
||||
"\n", |
||||
"def convert_code(python_code, selected_model):\n", |
||||
" for model in MODELS_IN_USE:\n", |
||||
" if model == selected_model:\n", |
||||
" yield from stream_response(python_code, model, action=ACTION_C)\n", |
||||
" return # Exit the function immediately after exhausting the generator\n", |
||||
" raise ValueError(\"Unknown Model\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Running Code Functions\n", |
||||
"\n", |
||||
"- Functions that dynamically execute Python or C++ code provided as a string and captures its output.\n", |
||||
"- This is useful for evaluating Python or C++ code snippets and returning their results programmatically.\n", |
||||
"\n", |
||||
"### IMPORTANT WARNING:\n", |
||||
"The functions that dynamically execute Python or C++ code provided as input.\n", |
||||
"While powerful, this is extremely dangerous if the input code is not trusted.\n", |
||||
"Any malicious code can be executed, including:\n", |
||||
" - Deleting files or directories\n", |
||||
" - Stealing sensitive data (e.g., accessing environment variables or credentials)\n", |
||||
" - Running arbitrary commands that compromise the system\n", |
||||
"\n", |
||||
"Sharing this notebook with this code snippet can allow attackers to exploit this functionality \n", |
||||
"by passing harmful code as input. \n", |
||||
"\n", |
||||
"If you share this notebook or use this function:\n", |
||||
" 1. Only accept input from trusted sources.\n", |
||||
" 2. Consider running the code in a sandboxed environment (e.g., virtual machine or container).\n", |
||||
" 3. Avoid using this function in publicly accessible applications or notebooks without strict validation." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def run_python_exec(code):\n", |
||||
" try:\n", |
||||
" # Capture stdout using StringIO\n", |
||||
" output = io.StringIO()\n", |
||||
"\n", |
||||
" # Redirect stdout to StringIO\n", |
||||
" sys.stdout = output\n", |
||||
"\n", |
||||
" # Execute the provided Python code\n", |
||||
" exec(code)\n", |
||||
" finally:\n", |
||||
" # Restore original stdout\n", |
||||
" sys.stdout = sys.__stdout__\n", |
||||
"\n", |
||||
" # Return the captured output\n", |
||||
" return output.getvalue()\n", |
||||
"\n", |
||||
"# Improved running python function\n", |
||||
"def run_python(code):\n", |
||||
" # Save the Python code to a file\n", |
||||
" with open(TEMP_DIR / \"python_code.py\", \"w\") as python_file:\n", |
||||
" python_file.write(code)\n", |
||||
"\n", |
||||
" try:\n", |
||||
" # Execute the Python code\n", |
||||
" result = subprocess.run(\n", |
||||
" [\"python\", str(TEMP_DIR / \"python_code.py\")],\n", |
||||
" check=True, text=True, capture_output=True\n", |
||||
" )\n", |
||||
"\n", |
||||
" # Return the program's output\n", |
||||
" return result.stdout\n", |
||||
"\n", |
||||
" except subprocess.CalledProcessError as e:\n", |
||||
" # Handle compilation or execution errors\n", |
||||
" return f\"An error occurred during execution:\\n{e.stderr}\"\n", |
||||
"\n", |
||||
" finally:\n", |
||||
" # Clean up: Delete the Python code file and executable\n", |
||||
" file_path = TEMP_DIR / \"python_code.py\"\n", |
||||
" if file_path.exists():\n", |
||||
" file_path.unlink()\n", |
||||
"\n", |
||||
"def run_cpp(code):\n", |
||||
" # Save the C++ code to a file\n", |
||||
" with open(TEMP_DIR / \"cpp_code.cpp\", \"w\") as cpp_file:\n", |
||||
" cpp_file.write(code)\n", |
||||
"\n", |
||||
" try:\n", |
||||
" # Compile the C++ code\n", |
||||
" subprocess.run(\n", |
||||
" [\"g++\", \"-o\", str(TEMP_DIR / \"cpp_code\"), str(TEMP_DIR / \"cpp_code.cpp\")],\n", |
||||
" check=True, text=True, capture_output=True\n", |
||||
" )\n", |
||||
"\n", |
||||
" # Execute the compiled program\n", |
||||
" result = subprocess.run(\n", |
||||
" [str(TEMP_DIR / \"cpp_code\")],\n", |
||||
" check=True, text=True, capture_output=True\n", |
||||
" )\n", |
||||
"\n", |
||||
" # Return the program's output\n", |
||||
" return result.stdout\n", |
||||
"\n", |
||||
" except subprocess.CalledProcessError as e:\n", |
||||
" # Handle compilation or execution errors\n", |
||||
" error_context = \"during compilation\" if \"cpp_code.cpp\" in e.stderr else \"during execution\"\n", |
||||
" return f\"An error occurred {error_context}:\\n{e.stderr}\"\n", |
||||
"\n", |
||||
" finally:\n", |
||||
" # Clean up: Delete the C++ source file and executable\n", |
||||
" for filename in [\"cpp_code.cpp\", \"cpp_code\", \"cpp_code.exe\"]:\n", |
||||
" file_path = TEMP_DIR / filename\n", |
||||
" if file_path.exists():\n", |
||||
" file_path.unlink()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": { |
||||
"id": "Vude1jzPrgT2" |
||||
}, |
||||
"source": [ |
||||
"## Develop a User-Friendly Interface with Gradio\n", |
||||
"\n", |
||||
"- Design a clean, intuitive, and user-centric interface using Gradio.\n", |
||||
"- Ensure responsiveness and accessibility to provide a seamless and efficient user experience.\n", |
||||
"- Focus on simplicity while maintaining functionality to cater to diverse user needs.\n", |
||||
"\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "Eh-sWFZVBb_y" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# CSS styles for customizing the appearance of the Gradio UI elements.\n", |
||||
"css = \"\"\"\n", |
||||
".python { \n", |
||||
" background-color: #377ef0; \n", |
||||
" color: #ffffff; \n", |
||||
" padding: 0.5em; \n", |
||||
" border-radius: 5px; /* Slightly rounded corners */\n", |
||||
"}\n", |
||||
".cpp { \n", |
||||
" background-color: #00549e; \n", |
||||
" color: #ffffff; \n", |
||||
" padding: 0.5em; \n", |
||||
" border-radius: 5px; \n", |
||||
"}\n", |
||||
".model { \n", |
||||
" background-color: #17a2b8; /* Vibrant cyan color */\n", |
||||
" color: white; \n", |
||||
" font-size: 1.2em; \n", |
||||
" padding: 0.5em; \n", |
||||
" border: none; \n", |
||||
" border-radius: 5px; \n", |
||||
" cursor: pointer; \n", |
||||
"}\n", |
||||
".button { \n", |
||||
" height: 4em; \n", |
||||
" font-size: 1.5em; \n", |
||||
" padding: 0.5em 1em; \n", |
||||
" background-color: #e67e22; /* Vibrant orange */\n", |
||||
" color: white; \n", |
||||
" border: none; \n", |
||||
" border-radius: 5px; \n", |
||||
" cursor: pointer; \n", |
||||
"}\n", |
||||
".run-button { \n", |
||||
" height: 3em; \n", |
||||
" font-size: 1.5em; \n", |
||||
" padding: 0.5em 1em; \n", |
||||
" background-color: #16a085; /* Rich teal color */\n", |
||||
" color: white; \n", |
||||
" border: none; \n", |
||||
" border-radius: 5px; \n", |
||||
" cursor: pointer; \n", |
||||
"}\n", |
||||
".button:hover, .run-button:hover {\n", |
||||
" background-color: #2c3e50; /* Dark navy for hover effect */\n", |
||||
" color: #fff; \n", |
||||
"}\n", |
||||
"\"\"\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "M_v-j-B_sQHe" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Tab to Document Code with Docstrings and Comments\n", |
||||
"def docs_comments_ui():\n", |
||||
" with gr.Tab(\"Docstrings & Comments\"):\n", |
||||
" gr.Markdown(\"\"\"\n", |
||||
" ## Document Code with Docstrings and Comments\n", |
||||
" This tab allows you to automatically generate docstrings and inline comments for your Python code.\n", |
||||
" - Paste your Python code into the **`Python Code`** textbox.\n", |
||||
" - Select your preferred model (GPT, Claude, Gemini, or CodeQwen) to process the code.\n", |
||||
" - Click the **`Add Docstrings & Comments`** button to generate well-documented Python code.\n", |
||||
" The generated code will appear in the **`Python Code with Docstrings and Comments`** textarea.\n", |
||||
" \"\"\")\n", |
||||
" with gr.Row():\n", |
||||
" python = gr.Textbox(label=\"Python Code:\", lines=20, value=PYTHON_SCRIPTS[\"custom\"], elem_classes=[\"python\"])\n", |
||||
" python_with_comments = gr.TextArea(label=\"Python Code with Docstrings and Comments:\", interactive=True, lines=20, elem_classes=[\"python\"])\n", |
||||
" with gr.Row():\n", |
||||
" python_script = gr.Dropdown(choices=list(PYTHON_SCRIPTS.keys()), label=\"Select a Python script\", value=\"custom\", elem_classes=[\"model\"])\n", |
||||
" comments_btn = gr.Button(\"Add Docstrings & Comments\", elem_classes=[\"button\"])\n", |
||||
" model = gr.Dropdown([\"GPT\", \"Claude\", \"Gemini\", \"CodeQwen\"], label=\"Select Model\", value=\"GPT\", elem_classes=[\"model\"])\n", |
||||
" \n", |
||||
" python_script.change(\n", |
||||
" fn=lambda script: PYTHON_SCRIPTS[script],\n", |
||||
" inputs=[python_script],\n", |
||||
" outputs=[python]\n", |
||||
" )\n", |
||||
" \n", |
||||
" comments_btn.click(\n", |
||||
" fn=lambda: \"\",\n", |
||||
" inputs=None,\n", |
||||
" outputs=[python_with_comments]\n", |
||||
" ).then(\n", |
||||
" fn=generate_comments,\n", |
||||
" inputs=[python, model],\n", |
||||
" outputs=[python_with_comments]\n", |
||||
" )\n", |
||||
"\n", |
||||
" return python_with_comments" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "WDjJp1eXtQzY" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Tab to Generate Comprehensive Unit Tests\n", |
||||
"def unit_tests_ui():\n", |
||||
" with gr.Tab(\"Unit Tests\"):\n", |
||||
" gr.Markdown(\"\"\"\n", |
||||
" ## Generate Comprehensive Unit Tests\n", |
||||
" This tab helps you create unit tests for your Python code automatically.\n", |
||||
" - Paste your Python code into the **`Python Code`** textbox.\n", |
||||
" - Choose a model (GPT, Claude, Gemini, or CodeQwen) to generate the unit tests.\n", |
||||
" - Click the **`Generate Unit Tests`** button, and the generated unit tests will appear in the **`Python Code with Unit Tests`** textarea.\n", |
||||
" Use these unit tests to ensure your code behaves as expected.\n", |
||||
" \"\"\")\n", |
||||
" with gr.Row():\n", |
||||
" python = gr.Textbox(label=\"Python Code:\", lines=20, value=PYTHON_SCRIPTS[\"custom\"], elem_classes=[\"python\"])\n", |
||||
" python_unit_tests = gr.TextArea(label=\"Python Code with Unit Tests:\", interactive=True, lines=20, elem_classes=[\"python\"])\n", |
||||
" with gr.Row():\n", |
||||
" python_script = gr.Dropdown(choices=list(PYTHON_SCRIPTS.keys()), label=\"Select a Python script\", value=\"custom\", elem_classes=[\"model\"])\n", |
||||
" unit_tests_btn = gr.Button(\"Generate Unit Tests\", elem_classes=[\"button\"])\n", |
||||
" model = gr.Dropdown([\"GPT\", \"Claude\", \"Gemini\", \"CodeQwen\"], label=\"Select Model\", value=\"GPT\", elem_classes=[\"model\"])\n", |
||||
" \n", |
||||
" python_script.change(\n", |
||||
" fn=lambda script: PYTHON_SCRIPTS[script],\n", |
||||
" inputs=[python_script],\n", |
||||
" outputs=[python]\n", |
||||
" )\n", |
||||
" \n", |
||||
" unit_tests_btn.click(\n", |
||||
" fn=lambda: \"\",\n", |
||||
" inputs=None,\n", |
||||
" outputs=[python_unit_tests]\n", |
||||
" ).then(\n", |
||||
" fn=generate_tests,\n", |
||||
" inputs=[python, model],\n", |
||||
" outputs=[python_unit_tests]\n", |
||||
" )\n", |
||||
"\n", |
||||
" return python_unit_tests" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"id": "x57SZeLi9NyV" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Tab to Convert Python Code to C++\n", |
||||
"def python_to_cpp_ui():\n", |
||||
" with gr.Tab(\"Python to C++\"):\n", |
||||
" gr.Markdown(\"\"\"\n", |
||||
" ## Convert Python Code to C++\n", |
||||
" This tab facilitates the conversion of Python code into C++.\n", |
||||
" - Paste your Python code into the **`Python Code`** textbox.\n", |
||||
" - Select your preferred model (GPT, Claude, Gemini, or CodeQwen) to perform the conversion.\n", |
||||
" - Click **`Convert to C++`** to see the equivalent C++ code in the **`C++ Code`** textbox.\n", |
||||
" Additional Features:\n", |
||||
" - You can execute the Python or C++ code directly using the respective **`Run Python`** or **`Run C++`** buttons.\n", |
||||
" - The output will appear in the respective result text areas below.\n", |
||||
" \"\"\")\n", |
||||
" with gr.Row():\n", |
||||
" python = gr.Textbox(label=\"Python Code:\", lines=20, value=PYTHON_SCRIPTS[\"custom\"], elem_classes=[\"python\"])\n", |
||||
" cpp = gr.Textbox(label=\"C++ Code:\", interactive=True, lines=20, elem_classes=[\"cpp\"])\n", |
||||
" with gr.Row():\n", |
||||
" python_script = gr.Dropdown(choices=list(PYTHON_SCRIPTS.keys()), label=\"Select a Python script\", value=\"custom\", elem_classes=[\"model\"])\n", |
||||
" convert_btn = gr.Button(\"Convert to C++\", elem_classes=[\"button\"])\n", |
||||
" model = gr.Dropdown([\"GPT\", \"Claude\", \"Gemini\", \"CodeQwen\"], label=\"Select Model\", value=\"GPT\", elem_classes=[\"model\"])\n", |
||||
" with gr.Row():\n", |
||||
" run_python_btn = gr.Button(\"Run Python\", elem_classes=[\"run-button\"])\n", |
||||
" run_cpp_btn = gr.Button(\"Run C++\", elem_classes=[\"run-button\"])\n", |
||||
" with gr.Row():\n", |
||||
" python_out = gr.TextArea(label=\"Python Result:\", lines=10, elem_classes=[\"python\"])\n", |
||||
" cpp_out = gr.TextArea(label=\"C++ Result:\", lines=10, elem_classes=[\"cpp\"])\n", |
||||
"\n", |
||||
" python_script.change(\n", |
||||
" fn=lambda script: PYTHON_SCRIPTS[script],\n", |
||||
" inputs=[python_script],\n", |
||||
" outputs=[python]\n", |
||||
" )\n", |
||||
" \n", |
||||
" convert_btn.click(\n", |
||||
" fn=lambda: \"\",\n", |
||||
" inputs=None,\n", |
||||
" outputs=[cpp]\n", |
||||
" ).then(\n", |
||||
" fn=convert_code,\n", |
||||
" inputs=[python, model],\n", |
||||
" outputs=[cpp]\n", |
||||
" )\n", |
||||
" run_python_btn.click(run_python, inputs=[python], outputs=[python_out])\n", |
||||
" run_cpp_btn.click(run_cpp, inputs=[cpp], outputs=[cpp_out])\n", |
||||
"\n", |
||||
" return cpp, python_out, cpp_out" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": { |
||||
"colab": { |
||||
"base_uri": "https://localhost:8080/", |
||||
"height": 645 |
||||
}, |
||||
"id": "n8ZdDrOrrbl-", |
||||
"outputId": "08350d69-569e-4947-8da1-d755e9a2678f" |
||||
}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Combine the tabs into the main UI and handle tab switching\n", |
||||
"with gr.Blocks(css=css) as main_ui:\n", |
||||
" with gr.Tabs() as tabs:\n", |
||||
" comments_output = docs_comments_ui()\n", |
||||
" tests_output = unit_tests_ui()\n", |
||||
" cpp_output, python_out, cpp_out = python_to_cpp_ui()\n", |
||||
"\n", |
||||
" # Reset outputs on tab switch\n", |
||||
" tabs.select(\n", |
||||
" fn=lambda: [\"\", \"\", \"\", \"\", \"\"],\n", |
||||
" inputs=None,\n", |
||||
" outputs=[comments_output, \n", |
||||
" tests_output, \n", |
||||
" cpp_output, python_out, cpp_out]\n", |
||||
" )\n", |
||||
"\n", |
||||
"# Launch the app\n", |
||||
"main_ui.launch(inbrowser=True)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [] |
||||
} |
||||
], |
||||
"metadata": { |
||||
"colab": { |
||||
"provenance": [] |
||||
}, |
||||
"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 |
||||
} |
@ -0,0 +1,462 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Requirements\n", |
||||
"\n", |
||||
"1. Install pytest and pytest-cov library\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 1, |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"#!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, |
||||
"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": 4, |
||||
"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": 5, |
||||
"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", |
||||
" \n", |
||||
" command = [\"coverage\", \"run\", \"-m\", \"pytest\"]\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", |
||||
" return e.stdout\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", |
||||
" \n", |
||||
" return e.stdout\n", |
||||
" " |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Prompts and calls to the models" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 6, |
||||
"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": 7, |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def get_user_prompt(code):\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" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 8, |
||||
"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": 9, |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"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", |
||||
" 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": 10, |
||||
"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": 11, |
||||
"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)\n", |
||||
"# ui.launch()" |
||||
] |
||||
} |
||||
], |
||||
"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 |
||||
} |
@ -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": [ |
||||
"<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" |
||||
], |
||||
"text/plain": [ |
||||
"<IPython.core.display.HTML object>" |
||||
] |
||||
}, |
||||
"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 |
||||
} |
@ -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 <your_environment> |
||||
cd <your_directory_where_script_lives> |
||||
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? |
||||
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 89 KiB |
@ -0,0 +1,44 @@
|
||||
HISTORY OF PRESENT ILLNESS: |
||||
|
||||
Ms. Connor is a 50-year-old female who returns to clinic for a wound check. |
||||
The patient underwent an APR secondary to refractory ulcerative colitis. |
||||
Subsequently, she developed a wound infection, which has since healed. |
||||
On our most recent visit to our clinic, she has her perineal stitches removed and presents today for followup of |
||||
her perineal wound. She describes no drainage or erythema from her bottom. She is having good ostomy output. |
||||
She does not describe any fevers, chills, nausea, or vomiting. The patient does describe some intermittent |
||||
pain beneath the upper portion of the incision as well as in the right lower quadrant below her ostomy. |
||||
She has been taking Percocet for this pain and it does work. She has since run out has been trying |
||||
extra strength Tylenol, which will occasionally help this intermittent pain. She is requesting additional |
||||
pain medications for this occasional abdominal pain, which she still experiences. |
||||
|
||||
PHYSICAL EXAMINATION: |
||||
|
||||
Temperature 95.8, pulse 68, blood pressure 132/73, and weight 159 pounds. |
||||
|
||||
This is a pleasant female in no acute distress. |
||||
The patient's abdomen is soft, nontender, nondistended with a well-healed midline scar. |
||||
There is an ileostomy in the right hemiabdomen, which is pink, patent, productive, and protuberant. |
||||
There are no signs of masses or hernias over the patient's abdomen. |
||||
|
||||
ASSESSMENT AND PLAN: |
||||
|
||||
This is a pleasant 50-year-old female who has undergone an APR secondary to refractory ulcerative colitis. |
||||
Overall, her quality of life has significantly improved since she had her APR. She is functioning well with her ileostomy. |
||||
She did have concerns or questions about her diet and we discussed the BRAT diet, which consisted of foods that would |
||||
slow down the digestive tract such as bananas, rice, toast, cheese, and peanut butter. |
||||
I discussed the need to monitor her ileostomy output and preferential amount of daily output is 2 liters or less. |
||||
I have counseled her on refraining from soft drinks and fruit drinks. I have also discussed with her that this diet |
||||
is moreover a trial and error and that she may try certain foods that did not agree with her ileostomy, |
||||
however others may and that this is something she will just have to perform trials with over the next several |
||||
months until she finds what foods that she can and cannot eat with her ileostomy. She also had questions about |
||||
her occasional abdominal pain. I told her that this was probably continue to improve as months went by and I |
||||
gave her a refill of her Percocet for the continued occasional pain. I told her that this would the last time |
||||
I would refill the Percocet and if she has continued pain after she finishes this bottle then she would need to |
||||
start ibuprofen or Tylenol if she had continued pain. The patient then brought up some right hand and arm numbness, |
||||
which has been there postsurgically and was thought to be from positioning during surgery. |
||||
This is all primarily gone away except for a little bit of numbness at the tip of the third digit as well as |
||||
some occasional forearm muscle cramping. I told her that I felt that this would continue to improve as it |
||||
has done over the past two months since her surgery. I told her to continue doing hand exercises as she has |
||||
been doing and this seems to be working for her. Overall, I think she has healed from her surgery and is doing |
||||
very well. Again, her quality of life is significantly improved. She is happy with her performance. We will see |
||||
her back in six months just for a general routine checkup and see how she is doing at that time. |
@ -0,0 +1,50 @@
|
||||
HISTORY OF PRESENT ILLNESS:, |
||||
|
||||
Ms. Mouse is a 67-year-old white female with a history of uterine papillary serous carcinoma who is |
||||
status post 6 cycles of carboplatin and Taxol, is here today for followup. Her last cycle of chemotherapy |
||||
was finished on 01/18/08, and she complains about some numbness in her right upper extremity. |
||||
This has not gotten worse recently and there is no numbness in her toes. She denies any tingling or burning., |
||||
|
||||
REVIEW OF SYSTEMS: |
||||
|
||||
Negative for any fever, chills, nausea, vomiting, headache, chest pain, shortness of breath, abdominal pain, |
||||
constipation, diarrhea, melena, hematochezia or dysuria. |
||||
|
||||
The patient is concerned about her blood pressure being up a little bit and also a mole that she had noticed for the |
||||
past few months in her head. |
||||
|
||||
PHYSICAL EXAMINATION: |
||||
|
||||
VITAL SIGNS: Temperature 35.6, blood pressure 143/83, pulse 65, respirations 18, and weight 66.5 kg. |
||||
GENERAL: She is a middle-aged white female, not in any distress. |
||||
HEENT: No lymphadenopathy or mucositis. |
||||
CARDIOVASCULAR: Regular rate and rhythm. |
||||
LUNGS: Clear to auscultation bilaterally. |
||||
EXTREMITIES: No cyanosis, clubbing or edema. |
||||
NEUROLOGICAL: No focal deficits noted. |
||||
PELVIC: Normal-appearing external genitalia. Vaginal vault with no masses or bleeding., |
||||
|
||||
LABORATORY DATA: |
||||
|
||||
None today. |
||||
|
||||
RADIOLOGIC DATA: |
||||
|
||||
CT of the chest, abdomen, and pelvis from 01/28/08 revealed status post total abdominal hysterectomy/bilateral |
||||
salpingo-oophorectomy with an unremarkable vaginal cuff. No local or distant metastasis. |
||||
Right probably chronic gonadal vein thrombosis. |
||||
|
||||
ASSESSMENT: |
||||
|
||||
This is a 67-year-old white female with history of uterine papillary serous carcinoma, status post total |
||||
abdominal hysterectomy and bilateral salpingo-oophorectomy and 6 cycles of carboplatin and Taxol chemotherapy. |
||||
She is doing well with no evidence of disease clinically or radiologically. |
||||
|
||||
PLAN: |
||||
|
||||
1. Plan to follow her every 3 months and CT scans every 6 months for the first 2 years. |
||||
2. The patient was advised to contact the primary physician for repeat blood pressure check and get started on |
||||
antihypertensives if it is persistently elevated. |
||||
3. The patient was told that the mole that she is mentioning in her head is no longer palpable and just to observe it for now. |
||||
4. The patient was advised about doing Kegel exercises for urinary incontinence, and we will address this issue again |
||||
during next clinic visit if it is persistent. |
@ -0,0 +1,25 @@
|
||||
SUBJECTIVE: |
||||
|
||||
Mr. Duck is a 29-year-old white male who is a patient of Dr. XYZ and he comes in today |
||||
complaining that he was stung by a Yellow Jacket Wasp yesterday and now has a lot of |
||||
swelling in his right hand and right arm. He says that he has been stung by wasps before and had similar |
||||
reactions. He just said that he wanted to catch it early before he has too bad of a severe reaction like he has had in the past. |
||||
He has had a lot of swelling, but no anaphylaxis-type reactions in the past; no shortness of breath or difficultly with his |
||||
throat feeling like it is going to close up or anything like that in the past; no racing heart beat or anxiety feeling, |
||||
just a lot of localized swelling where the sting occurs. |
||||
|
||||
OBJECTIVE: |
||||
|
||||
Vitals: His temperature is 98.4. Respiratory rate is 18. Weight is 250 pounds. |
||||
Extremities: Examination of his right hand and forearm reveals that he has an apparent sting just around his |
||||
wrist region on his right hand on the medial side as well as significant swelling in his hand and his right forearm; |
||||
extending up to the elbow. He says that it is really not painful or anything like that. It is really not all that |
||||
red and no signs of infection at this time. |
||||
|
||||
ASSESSMENT:, Wasp sting to the right wrist area. |
||||
|
||||
PLAN: |
||||
|
||||
1. Solu-Medrol 125 mg IM X 1. |
||||
2. Over-the-counter Benadryl, ice and elevation of that extremity. |
||||
3. Follow up with Dr. XYZ if any further evaluation is needed. |
@ -0,0 +1,54 @@
|
||||
CHIEF COMPLAINT: |
||||
|
||||
Ms. Barbara is a thirty one year old female patient comes for three-week postpartum checkup, complaining of allergies. |
||||
|
||||
HISTORY OF PRESENT ILLNESS: |
||||
|
||||
She is doing well postpartum. She has had no headache. She is breastfeeding and feels like her milk is adequate. |
||||
She has not had much bleeding. She is using about a mini pad twice a day, not any cramping or clotting and the |
||||
discharge is turned from red to brown to now slightly yellowish. She has not yet had sexual intercourse. |
||||
She does complain that she has had a little pain with the bowel movement, and every now and then she |
||||
notices a little bright red bleeding. She has not been particularly constipated but her husband says |
||||
she is not eating her vegetables like she should. Her seasonal allergies have back developed and she is |
||||
complaining of extremely itchy watery eyes, runny nose, sneezing, and kind of a pressure sensation in her ears. |
||||
|
||||
MEDICATIONS: |
||||
|
||||
Prenatal vitamins. |
||||
|
||||
ALLERGIES: |
||||
|
||||
She thinks to Benadryl. |
||||
|
||||
FAMILY HISTORY: |
||||
|
||||
Mother is 50 and healthy. Dad is 40 and healthy. Half-sister, age 34, is healthy. |
||||
She has a sister who is age 10 who has some yeast infections. |
||||
|
||||
PHYSICAL EXAMINATION: |
||||
|
||||
VITALS: Weight: 124 pounds. Blood pressure 96/54. Pulse: 72. Respirations: 16. LMP: 10/18/03. Age: 39. |
||||
HEENT: Head is normocephalic. |
||||
Eyes: EOMs intact. |
||||
PERRLA. Conjunctiva clear. |
||||
Fundi: Discs flat, cups normal. |
||||
No AV nicking, hemorrhage or exudate. |
||||
Ears: TMs intact. |
||||
Mouth: No lesion. |
||||
Throat: No inflammation. |
||||
She has allergic rhinitis with clear nasal drainage, clear watery discharge from the eyes. |
||||
Abdomen: Soft. No masses. |
||||
Pelvic: Uterus is involuting. |
||||
Rectal: She has one external hemorrhoid which has inflamed. Stool is guaiac negative and using anoscope, |
||||
no other lesions are identified. |
||||
|
||||
ASSESSMENT/PLAN: |
||||
|
||||
Satisfactory three-week postpartum course, seasonal allergies. We will try Patanol eyedrops and Allegra 60 |
||||
mg twice a day. She was cautioned about the possibility that this may alter her milk supply. She is to |
||||
drink extra fluids and call if she has problems with that. We will try ProctoFoam HC. For the hemorrhoids, |
||||
also increase the fiber in her diet. That prescription was written, as well as one for Allegra and Patanol. |
||||
She additionally will be begin on Micronor because she would like to protect herself from pregnancy until |
||||
her husband get scheduled in and has a vasectomy, which is their ultimate plan for birth control, and she |
||||
anticipates that happening fairly soon. She will call and return if she continues to have problems with allergies. |
||||
Meantime, rechecking in three weeks for her final six-week postpartum checkup. |
@ -0,0 +1,59 @@
|
||||
import gradio as gr |
||||
from langchain_chroma import Chroma |
||||
from pathlib import Path |
||||
from utils import create_vector_db, Rag, get_chunks, get_conversation_chain, get_local_vector_db |
||||
|
||||
|
||||
def chat(question, history) -> str: |
||||
|
||||
""" |
||||
Get the chat data need for the gradio app |
||||
|
||||
:param question: |
||||
The question being asked in the chat app. |
||||
:type question: str |
||||
:param history: |
||||
A list of the conversation questions and answers. |
||||
:type history: list |
||||
:return: |
||||
The answer from the current question. |
||||
""" |
||||
|
||||
result = conversation_chain.invoke({"question": question}) |
||||
answer = result['answer'] |
||||
|
||||
# include source documents if they exist |
||||
# grab the first one as that should be related to the answer |
||||
source_doc = "" |
||||
if result.get('source_documents'): |
||||
source_doc = result['source_documents'][0] |
||||
|
||||
response = f"{answer}\n\n**Source:**\n{source_doc.metadata.get('source', 'Source')}" \ |
||||
if source_doc \ |
||||
else answer |
||||
return response |
||||
|
||||
|
||||
def main(): |
||||
|
||||
gr.ChatInterface(chat, type="messages").launch(inbrowser=True) |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
|
||||
create_new_db = False if Path('vector_db').exists() else True |
||||
|
||||
if create_new_db: |
||||
folders = Path('knowledge_base').glob('*') |
||||
chunks = get_chunks(folders=folders) |
||||
vector_store = create_vector_db(chunks=chunks, db_name=Rag.DB_NAME.value, embeddings=Rag.EMBED_MODEL.value) |
||||
else: |
||||
client = get_local_vector_db(path='../rag_chat_example/vector_db') |
||||
vector_store = Chroma(client=client, embedding_function=Rag.EMBED_MODEL.value) |
||||
|
||||
conversation_chain = get_conversation_chain(vectorstore=vector_store) |
||||
|
||||
main() |
||||
|
||||
|
||||
|
@ -0,0 +1,267 @@
|
||||
from chromadb import PersistentClient |
||||
from dotenv import load_dotenv |
||||
from enum import Enum |
||||
|
||||
import plotly.graph_objects as go |
||||
from langchain.document_loaders import DirectoryLoader, TextLoader |
||||
from langchain.text_splitter import CharacterTextSplitter |
||||
from langchain.schema import Document |
||||
from langchain_openai import OpenAIEmbeddings, ChatOpenAI |
||||
from langchain_chroma import Chroma |
||||
from langchain.memory import ConversationBufferMemory |
||||
from langchain.chains import ConversationalRetrievalChain |
||||
import numpy as np |
||||
import os |
||||
from pathlib import Path |
||||
from sklearn.manifold import TSNE |
||||
from typing import Any, List, Tuple, Generator |
||||
|
||||
cur_path = Path(__file__) |
||||
env_path = cur_path.parent.parent.parent.parent / '.env' |
||||
assert env_path.exists(), f"Please add an .env to the root project path" |
||||
|
||||
load_dotenv(dotenv_path=env_path) |
||||
|
||||
|
||||
class Rag(Enum): |
||||
|
||||
GPT_MODEL = "gpt-4o-mini" |
||||
HUG_MODEL = "sentence-transformers/all-MiniLM-L6-v2" |
||||
EMBED_MODEL = OpenAIEmbeddings() |
||||
DB_NAME = "vector_db" |
||||
|
||||
|
||||
def add_metadata(doc: Document, doc_type: str) -> Document: |
||||
""" |
||||
Add metadata to a Document object. |
||||
|
||||
:param doc: The Document object to add metadata to. |
||||
:type doc: Document |
||||
:param doc_type: The type of document to be added as metadata. |
||||
:type doc_type: str |
||||
:return: The Document object with added metadata. |
||||
:rtype: Document |
||||
""" |
||||
doc.metadata["doc_type"] = doc_type |
||||
return doc |
||||
|
||||
|
||||
def get_chunks(folders: Generator[Path, None, None], file_ext='.txt') -> List[Document]: |
||||
""" |
||||
Load documents from specified folders, add metadata, and split them into chunks. |
||||
|
||||
:param folders: List of folder paths containing documents. |
||||
:type folders: List[str] |
||||
:param file_ext: |
||||
The file extension to get from a local knowledge base (e.g. '.txt') |
||||
:type file_ext: str |
||||
:return: List of document chunks. |
||||
:rtype: List[Document] |
||||
""" |
||||
text_loader_kwargs = {'encoding': 'utf-8'} |
||||
documents = [] |
||||
for folder in folders: |
||||
doc_type = os.path.basename(folder) |
||||
loader = DirectoryLoader( |
||||
folder, glob=f"**/*{file_ext}", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs |
||||
) |
||||
folder_docs = loader.load() |
||||
documents.extend([add_metadata(doc, doc_type) for doc in folder_docs]) |
||||
|
||||
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200) |
||||
chunks = text_splitter.split_documents(documents) |
||||
|
||||
return chunks |
||||
|
||||
|
||||
def create_vector_db(db_name: str, chunks: List[Document], embeddings: Any) -> Any: |
||||
""" |
||||
Create a vector database from document chunks. |
||||
|
||||
:param db_name: Name of the database to create. |
||||
:type db_name: str |
||||
:param chunks: List of document chunks. |
||||
:type chunks: List[Document] |
||||
:param embeddings: Embedding function to use. |
||||
:type embeddings: Any |
||||
:return: Created vector store. |
||||
:rtype: Any |
||||
""" |
||||
# Delete if already exists |
||||
if os.path.exists(db_name): |
||||
Chroma(persist_directory=db_name, embedding_function=embeddings).delete_collection() |
||||
|
||||
# Create vectorstore |
||||
vectorstore = Chroma.from_documents(documents=chunks, embedding=embeddings, persist_directory=db_name) |
||||
|
||||
return vectorstore |
||||
|
||||
|
||||
def get_local_vector_db(path: str) -> Any: |
||||
""" |
||||
Get a local vector database. |
||||
|
||||
:param path: Path to the local vector database. |
||||
:type path: str |
||||
:return: Persistent client for the vector database. |
||||
:rtype: Any |
||||
""" |
||||
return PersistentClient(path=path) |
||||
|
||||
|
||||
def get_vector_db_info(vector_store: Any) -> None: |
||||
""" |
||||
Print information about the vector database. |
||||
|
||||
:param vector_store: Vector store to get information from. |
||||
:type vector_store: Any |
||||
""" |
||||
collection = vector_store._collection |
||||
count = collection.count() |
||||
|
||||
sample_embedding = collection.get(limit=1, include=["embeddings"])["embeddings"][0] |
||||
dimensions = len(sample_embedding) |
||||
|
||||
print(f"There are {count:,} vectors with {dimensions:,} dimensions in the vector store") |
||||
|
||||
|
||||
def get_plot_data(collection: Any) -> Tuple[np.ndarray, List[str], List[str], List[str]]: |
||||
""" |
||||
Get plot data from a collection. |
||||
|
||||
:param collection: Collection to get data from. |
||||
:type collection: Any |
||||
:return: Tuple containing vectors, colors, document types, and documents. |
||||
:rtype: Tuple[np.ndarray, List[str], List[str], List[str]] |
||||
""" |
||||
result = collection.get(include=['embeddings', 'documents', 'metadatas']) |
||||
vectors = np.array(result['embeddings']) |
||||
documents = result['documents'] |
||||
metadatas = result['metadatas'] |
||||
doc_types = [metadata['doc_type'] for metadata in metadatas] |
||||
colors = [['blue', 'green', 'red', 'orange'][['products', 'employees', 'contracts', 'company'].index(t)] for t in |
||||
doc_types] |
||||
|
||||
return vectors, colors, doc_types, documents |
||||
|
||||
|
||||
def get_2d_plot(collection: Any) -> go.Figure: |
||||
""" |
||||
Generate a 2D plot of the vector store. |
||||
|
||||
:param collection: Collection to generate plot from. |
||||
:type collection: Any |
||||
:return: 2D scatter plot figure. |
||||
:rtype: go.Figure |
||||
""" |
||||
vectors, colors, doc_types, documents = get_plot_data(collection) |
||||
tsne = TSNE(n_components=2, random_state=42) |
||||
reduced_vectors = tsne.fit_transform(vectors) |
||||
|
||||
fig = go.Figure(data=[go.Scatter( |
||||
x=reduced_vectors[:, 0], |
||||
y=reduced_vectors[:, 1], |
||||
mode='markers', |
||||
marker=dict(size=5, color=colors, opacity=0.8), |
||||
text=[f"Type: {t}<br>Text: {d[:100]}..." for t, d in zip(doc_types, documents)], |
||||
hoverinfo='text' |
||||
)]) |
||||
|
||||
fig.update_layout( |
||||
title='2D Chroma Vector Store Visualization', |
||||
scene=dict(xaxis_title='x', yaxis_title='y'), |
||||
width=800, |
||||
height=600, |
||||
margin=dict(r=20, b=10, l=10, t=40) |
||||
) |
||||
|
||||
return fig |
||||
|
||||
|
||||
def get_3d_plot(collection: Any) -> go.Figure: |
||||
""" |
||||
Generate a 3D plot of the vector store. |
||||
|
||||
:param collection: Collection to generate plot from. |
||||
:type collection: Any |
||||
:return: 3D scatter plot figure. |
||||
:rtype: go.Figure |
||||
""" |
||||
vectors, colors, doc_types, documents = get_plot_data(collection) |
||||
tsne = TSNE(n_components=3, random_state=42) |
||||
reduced_vectors = tsne.fit_transform(vectors) |
||||
|
||||
fig = go.Figure(data=[go.Scatter3d( |
||||
x=reduced_vectors[:, 0], |
||||
y=reduced_vectors[:, 1], |
||||
z=reduced_vectors[:, 2], |
||||
mode='markers', |
||||
marker=dict(size=5, color=colors, opacity=0.8), |
||||
text=[f"Type: {t}<br>Text: {d[:100]}..." for t, d in zip(doc_types, documents)], |
||||
hoverinfo='text' |
||||
)]) |
||||
|
||||
fig.update_layout( |
||||
title='3D Chroma Vector Store Visualization', |
||||
scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='z'), |
||||
width=900, |
||||
height=700, |
||||
margin=dict(r=20, b=10, l=10, t=40) |
||||
) |
||||
|
||||
return fig |
||||
|
||||
|
||||
def get_conversation_chain(vectorstore: Any) -> ConversationalRetrievalChain: |
||||
""" |
||||
Create a conversation chain using the vector store. |
||||
|
||||
:param vectorstore: Vector store to use in the conversation chain. |
||||
:type vectorstore: Any |
||||
:return: Conversational retrieval chain. |
||||
:rtype: ConversationalRetrievalChain |
||||
""" |
||||
llm = ChatOpenAI(temperature=0.7, model_name=Rag.GPT_MODEL.value) |
||||
|
||||
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True, output_key='answer') |
||||
|
||||
retriever = vectorstore.as_retriever(search_kwargs={"k": 25}) |
||||
|
||||
conversation_chain = ConversationalRetrievalChain.from_llm( |
||||
llm=llm, |
||||
retriever=retriever, |
||||
memory=memory, |
||||
return_source_documents=True, |
||||
) |
||||
|
||||
return conversation_chain |
||||
|
||||
|
||||
def get_lang_doc(document_text, doc_id, metadata=None, encoding='utf-8'): |
||||
|
||||
""" |
||||
Build a langchain Document that can be used to create a chroma database |
||||
|
||||
:type document_text: str |
||||
:param document_text: |
||||
The text to add to a document object |
||||
:type doc_id: str |
||||
:param doc_id: |
||||
The document id to include. |
||||
:type metadata: dict |
||||
:param metadata: |
||||
A dictionary of metadata to associate to the document object. This will help filter an item from a |
||||
vector database. |
||||
:type encoding: string |
||||
:param encoding: |
||||
The type of encoding to use for loading the text. |
||||
|
||||
""" |
||||
return Document( |
||||
page_content=document_text, |
||||
id=doc_id, |
||||
metadata=metadata, |
||||
encoding=encoding, |
||||
) |
||||
|
||||
|
@ -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 |
||||
} |
Loading…
Reference in new issue