Browse Source

Merge branch 'main' of https://github.com/craigprobus/llm_engineering

Syncing forked repo with upstream origin
pull/318/head
craigprobus 4 weeks ago
parent
commit
b34b5ed3aa
  1. 274
      week1/community-contributions/day2_exercise.ipynb
  2. 3876
      week1/community-contributions/day5_ollama_version.ipynb
  3. 183
      week1/community-contributions/mock-dashboard-summary/day1-dashboard-metrics-summary.ipynb
  4. 95
      week1/community-contributions/mock-dashboard-summary/mock_grafana_dashboard.json
  5. 762
      week2/community-contributions/AI Booking Chatbot.ipynb
  6. 326
      week2/community-contributions/Airlines_Chatbot_with_Audio_Input.ipynb
  7. 428
      week2/community-contributions/Personal Story Writer.ipynb
  8. 444
      week2/community-contributions/Week2 - OpenAiAndLlama.ipynb
  9. 220
      week2/community-contributions/day1_AI_rountable_GPT_llama_qwen.ipynb
  10. 653
      week2/community-contributions/day4-ecommerce-project-fullyCustomiz.ipynb
  11. 290
      week2/community-contributions/tool_integration_gradio_using_anthropic_api.ipynb
  12. 293
      week2/community-contributions/week2-commerce-chatbot-assistant-and-agent.ipynb
  13. 394
      week4/community-contributions/day4 -Perl to Python.ipynb
  14. 413
      week4/community-contributions/unit_testing_commets_code_generator.ipynb

274
week1/community-contributions/day2_exercise.ipynb

@ -0,0 +1,274 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "41136d6f-07bc-4f6f-acba-784b8e5707b1",
"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": "8612b4f7-5c31-48f3-8423-261914509617",
"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": "508bd442-7860-4215-b0f2-57f7adefd807",
"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": "cc7e8ada-4f8d-4090-be64-4aa72e03ac58",
"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": "4afd2e56-191a-4e31-949e-9b9376a39b5a",
"metadata": {
"scrolled": true
},
"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": "code",
"execution_count": null,
"id": "365f3d83-2601-42fb-89cc-98a4e1f79e0d",
"metadata": {},
"outputs": [],
"source": [
"message = \"Hello, GPT! This is my first ever message to you! Hi!\"\n",
"response = ollama_via_openai.chat.completions.create(model=MODEL, messages=[{\"role\":\"user\", \"content\":message}])\n",
"print(response.choices[0].message.content)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "29c383ae-bf5b-41bc-b5af-a22f851745dc",
"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": "dc61e30f-653f-4554-b1cd-6e61a0e2430a",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"ed = Website(\"https://edwarddonner.com\")\n",
"print(ed.title)\n",
"print(ed.text)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "db2066fb-3079-4775-832a-dcc0f19beb6e",
"metadata": {},
"outputs": [],
"source": [
"\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": "af81b070-b6fe-4b18-aa0b-c03cd76a0adf",
"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"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4e66291b-23b1-4915-b6a3-11a4b6a4db66",
"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": "67c92f47-4a3b-491f-af00-07fda470087e",
"metadata": {},
"outputs": [],
"source": [
"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": "db1b9085-e5e7-4ec9-a264-acc389085ada",
"metadata": {},
"outputs": [],
"source": [
"messages_for(ed)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "677bfc2f-19ac-46a0-b67e-a2b2ddf9cf6b",
"metadata": {},
"outputs": [],
"source": [
"def summarize(url):\n",
" website = Website(url)\n",
" response = ollama_via_openai.chat.completions.create(\n",
" model = MODEL,\n",
" messages = messages_for(website)\n",
" )\n",
" return response.choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ee3242ba-b695-4b1e-8a91-2fdeb536c2e7",
"metadata": {},
"outputs": [],
"source": [
"summarize(\"https://edwarddonner.com\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "85142cb8-ce0c-4c31-8b26-bb1744cf99ec",
"metadata": {},
"outputs": [],
"source": [
"def display_summary(url):\n",
" summary = summarize(url)\n",
" display(Markdown(summary))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "63db51a7-dd03-4514-8954-57156967f82c",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"display_summary(\"https://app.daily.dev/posts/bregman-arie-devops-exercises-linux-jenkins-aws-sre-prometheus-docker-python-ansible-git-k-yli9wthnf\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "conda-base-py"
},
"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.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

3876
week1/community-contributions/day5_ollama_version.ipynb

File diff suppressed because one or more lines are too long

183
week1/community-contributions/mock-dashboard-summary/day1-dashboard-metrics-summary.ipynb

@ -0,0 +1,183 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "de3b5d4c",
"metadata": {},
"source": [
"# 🧠 Grafana Dashboard Summarizer\n",
"Simulate reading a Grafana dashboard JSON and summarize its panels using GPT or plain logic."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0abf3aaf",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"from IPython.display import Markdown, display\n",
"from openai import OpenAI\n",
"import json\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad82ca65",
"metadata": {},
"outputs": [],
"source": [
"\n",
"\n",
"with open(\"mock_grafana_dashboard.json\", \"r\") as f:\n",
" data = json.load(f)\n",
"\n",
"dashboard = data[\"dashboard\"]\n",
"panels = dashboard[\"panels\"]\n",
"print(f\"Dashboard Title: {dashboard['title']}\")\n",
"print(f\"Total Panels: {len(panels)}\\n\")\n",
"for p in panels:\n",
" print(f\"- {p['title']} ({p['type']})\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1bf45c0f",
"metadata": {},
"outputs": [],
"source": [
"# Extracting panel data\n",
"\n",
"panel_data = []\n",
"for p in panels:\n",
" thresholds = p.get(\"fieldConfig\", {}).get(\"defaults\", {}).get(\"thresholds\", {}).get(\"steps\", [])\n",
" panel_data.append({\n",
" \"Title\": p[\"title\"],\n",
" \"Type\": p[\"type\"],\n",
" \"Unit\": p.get(\"fieldConfig\", {}).get(\"defaults\", {}).get(\"unit\", \"N/A\"),\n",
" \"Thresholds\": thresholds\n",
" })\n",
"\n",
"df = pd.DataFrame(panel_data)\n",
"df\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "90b67133",
"metadata": {},
"outputs": [],
"source": [
"\n",
"summary_prompt = f\"\"\"\n",
"You are a helpful assistant summarizing a system monitoring dashboard.\n",
"\n",
"Dashboard: {dashboard['title']}\n",
"Panels:\n",
"\"\"\"\n",
"for idx, row in df.iterrows():\n",
" summary_prompt += f\"- {row['Title']} [{row['Type']}] - Unit: {row['Unit']}, Thresholds: {row['Thresholds']}\\n\"\n",
"\n",
"print(summary_prompt)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "69a4208c",
"metadata": {},
"outputs": [],
"source": [
"\n",
"\n",
"load_dotenv(override=True)\n",
"api_key = os.getenv('OPENAI_API_KEY')\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": "2eee5a32",
"metadata": {},
"outputs": [],
"source": [
"openai = OpenAI()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "660eedb7",
"metadata": {},
"outputs": [],
"source": [
"def summarize():\n",
" response = openai.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a Grafana dashboard summarizer.\"},\n",
" {\"role\": \"user\", \"content\": summary_prompt}\n",
" ]\n",
")\n",
" return response.choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55f57d56",
"metadata": {},
"outputs": [],
"source": [
"\n",
"summary = summarize()\n",
"display(Markdown(summary))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "10dbfd6c",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "arunllms",
"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
}

95
week1/community-contributions/mock-dashboard-summary/mock_grafana_dashboard.json

@ -0,0 +1,95 @@
{
"dashboard": {
"id": null,
"uid": "mock-sys-metrics",
"title": "Mock System Metrics Dashboard",
"timezone": "browser",
"panels": [
{
"id": 1,
"title": "CPU Usage (%)",
"type": "stat",
"datasource": "MockData",
"targets": [],
"fieldConfig": {
"defaults": {
"unit": "percent",
"thresholds": {
"mode": "percentage",
"steps": [
{ "color": "green", "value": null },
{ "color": "orange", "value": 70 },
{ "color": "red", "value": 90 }
]
}
}
},
"options": {
"reduceOptions": {
"calcs": ["mean"]
}
}
},
{
"id": 2,
"title": "Memory Usage",
"type": "gauge",
"datasource": "MockData",
"fieldConfig": {
"defaults": {
"unit": "bytes",
"max": 16e9,
"thresholds": {
"steps": [
{ "color": "green", "value": null },
{ "color": "orange", "value": 12e9 },
{ "color": "red", "value": 14e9 }
]
}
}
}
},
{
"id": 3,
"title": "Disk Read Errors",
"type": "stat",
"datasource": "MockData",
"fieldConfig": {
"defaults": {
"unit": "short",
"thresholds": {
"steps": [
{ "color": "green", "value": null },
{ "color": "orange", "value": 5 },
{ "color": "red", "value": 10 }
]
}
}
}
},
{
"id": 4,
"title": "GPU Usage (%)",
"type": "gauge",
"datasource": "MockData",
"fieldConfig": {
"defaults": {
"unit": "percent",
"thresholds": {
"steps": [
{ "color": "green", "value": null },
{ "color": "orange", "value": 75 },
{ "color": "red", "value": 90 }
]
}
}
}
}
],
"schemaVersion": 30,
"version": 1,
"refresh": "30s"
},
"overwrite": true
}

762
week2/community-contributions/AI Booking Chatbot.ipynb

@ -0,0 +1,762 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "d006b2ea-9dfe-49c7-88a9-a5a0775185fd",
"metadata": {},
"source": [
"# Additional End of week Exercise - week 2\n",
"\n",
"Now use everything you've learned from Week 2 to build a full prototype for the technical question/answerer you built in Week 1 Exercise.\n",
"\n",
"This should include a Gradio UI, streaming, use of the system prompt to add expertise, and the ability to switch between models. Bonus points if you can demonstrate use of a tool!\n",
"\n",
"If you feel bold, see if you can add audio input so you can talk to it, and have it respond with audio. ChatGPT or Claude can help you, or email me if you have questions.\n",
"\n",
"I will publish a full solution here soon - unless someone beats me to it...\n",
"\n",
"There are so many commercial applications for this, from a language tutor, to a company onboarding solution, to a companion AI to a course (like this one!) I can't wait to see your results."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "a07e7793-b8f5-44f4-aded-5562f633271a",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"import os\n",
"import json\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"import gradio as gr\n",
"import base64\n",
"from io import BytesIO\n",
"import tempfile\n",
"import subprocess\n",
"from pydub import AudioSegment\n",
"import time\n",
"import anthropic"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "717ea9d4-1e72-4035-b7c5-5d61da5b8ea3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OpenAI API Key exists and begins sk-proj-\n"
]
}
],
"source": [
"# Initialization\n",
"\n",
"load_dotenv(override=True)\n",
"\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\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",
"gpt_model = \"gpt-4o-mini\"\n",
"claude_model = \"claude-3-haiku-20240307\"\n",
"\n",
"openai = OpenAI()\n",
"claude = anthropic.Anthropic()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "cc78f4fd-9920-4872-9117-90cd2aeb2a06",
"metadata": {},
"outputs": [],
"source": [
"system_message = \"You are a helpful assistant. \"\n",
"system_message += \"Give short, courteous answers. You can check ticket price, ticket availability, and reserve tickets for users. \"\n",
"system_message += \"Always be accurate. If you don't know the answer, say so.\""
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "b2701cc0-6403-4880-9b31-e6e39e89feb4",
"metadata": {},
"outputs": [],
"source": [
"# Let's start by making a useful function\n",
"\n",
"ticket_prices = {\"london\": \"$799\", \"paris\": \"$899\", \"tokyo\": \"$1400\", \"berlin\": \"$499\"}\n",
"\n",
"def get_ticket_price(destination_city):\n",
" print(f\"Tool get_ticket_price called for {destination_city}\")\n",
" city = destination_city.lower()\n",
" return ticket_prices.get(city, \"Unknown\")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "5e33902f-c2c3-4fb0-b01d-a346a4dff811",
"metadata": {},
"outputs": [],
"source": [
"ticket_availability = {\"london\": \"20\", \"paris\": \"90\", \"tokyo\": \"100\", \"berlin\": \"2\"}"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "27dfca47-2a38-49f3-8905-f583d98710a5",
"metadata": {},
"outputs": [],
"source": [
"# Let's start by making a useful function\n",
"def get_ticket_availability(destination_city):\n",
" print(f\"Tool get_ticket_availability called for {destination_city}\")\n",
" available = destination_city.lower()\n",
" return ticket_availability.get(available, \"Unknown\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "6ae7371b-031e-47d7-afaf-42d6758ccd92",
"metadata": {},
"outputs": [],
"source": [
"def get_ticket_price_availability(destination_city):\n",
" print(f\"Tool get_ticket_price_availability called for {destination_city}\")\n",
" available = destination_city.lower()\n",
" price = destination_city.lower()\n",
" return ticket_price.get(price, \"Unknown\"), ticket_availability.get(available, \"Unknown\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "c919b13a-50b6-4510-8e9d-02cdfd95cb98",
"metadata": {},
"outputs": [],
"source": [
"def book_ticket(destination_city,price,availability,no_of_tickets):\n",
" status=\"\"\n",
" if availability == 0:\n",
" status=\"Cannot book a ticket, no seat available\\n\"\n",
" elif (int(availability)-int(no_of_tickets)) < 0:\n",
" status=\"Cannot book a ticket, no seat available\\n\"\n",
" else:\n",
" print(f\"Tool book_function called for {destination_city}\")\n",
" f = open(\"C:/Users/aruna/Desktop/book_status.txt\", \"a\")\n",
" f.write(f\"{no_of_tickets} ticket/s to {destination_city} booked for {price} x {no_of_tickets}, currently available - {int(availability)-int(no_of_tickets)}\")\n",
" f.write(\"\\n\")\n",
" f.close()\n",
" ticket_availability[destination_city.lower()]=str(int(availability)-int(no_of_tickets))\n",
" \n",
" status=\"Ticket reservation is a success\\n\"\n",
" return status"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "d2628781-6f5e-4ac1-bbe3-2e08aa0aae0d",
"metadata": {},
"outputs": [],
"source": [
"book_function = {\n",
" \"name\": \"book_ticket\",\n",
" \"description\": \"Book the ticket based on the ticket price and/ or availability as requested by the user. For example, when a \\\n",
" user asks to purchase one or more tickets to Tokyo after getting to know the ticket price and/or the availability, then \\\n",
" proceed with this tool call. Else, request the user to either ask for ticket price or availability first. Please help the customer in booking the ticket/s if tickets are available. But before each time\\\n",
" you book, ask confirmation from the user before proceeding with booking.\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"destination_city\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city that the customer wants to travel to\",\n",
" },\n",
" \"price\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The price of the ticket to the city\",\n",
" },\n",
" \"availability\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"ticket availability to the city the customer wants to travel to\",\n",
" },\n",
" \"no_of_tickets\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"the number of tickets the customer wants to purchase/ book to the destination\",\n",
" }\n",
" },\n",
" \"required\": [\"destination_city\",\"price\",\"availability\",\"no_of_tickets\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "480de296-4a36-4ec4-a5f6-149fc198c7a8",
"metadata": {},
"outputs": [],
"source": [
"# There's a particular dictionary structure that's required to describe our function:\n",
"\n",
"price_function = {\n",
" \"name\": \"get_ticket_price\",\n",
" \"description\": \"Get the price of a one_way ticket to the destination city. Call this whenever you need to know the ticket price, for example when a customer asks 'How much is a ticket to this city'\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"destination_city\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city that the customer wants to travel to\",\n",
" },\n",
" },\n",
" \"required\": [\"destination_city\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "cf1b3e35-08ee-478e-aa1c-534418d78daf",
"metadata": {},
"outputs": [],
"source": [
"availability_function = {\n",
" \"name\": \"get_ticket_availability\",\n",
" \"description\": \"Get the availability of a one-way ticket to the destination city. Call this whenever you need to know the ticket availability, for example when a customer asks 'What is the ticket availability to this city'\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"destination_city\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city that the customer wants to travel to\",\n",
" },\n",
" },\n",
" \"required\": [\"destination_city\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "73e4c8a2-c034-41a4-9b97-7b2aa4aca504",
"metadata": {},
"outputs": [],
"source": [
"ticket_price_availability_function = {\n",
" \"name\": \"get_ticket_price_availability\",\n",
" \"description\": \"Get the price or availability of a one-way ticket to the destination city. Call this whenever you need to know the ticket price and availability, for example when a customer asks 'What is the ticket availability and price to this city'\\\n",
" or 'what is the price and ticket for the city?'\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"destination_city\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city that the customer wants to travel to\",\n",
" },\n",
" },\n",
" \"required\": [\"destination_city\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "1d5d74a0-9c25-46a4-84ee-1f700bd55fa7",
"metadata": {},
"outputs": [],
"source": [
"# And this is included in a list of tools:\n",
"\n",
"tools = [{\"type\": \"function\", \"function\": price_function},\n",
" {\"type\": \"function\", \"function\": availability_function},\n",
" {\"type\": \"function\", \"function\": ticket_price_availability_function},\n",
" {\"type\": \"function\", \"function\": book_function}]"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "fa18f535-f8a7-4386-b39a-df0f84d23406",
"metadata": {},
"outputs": [],
"source": [
"def play_audio(audio_segment):\n",
" temp_dir = tempfile.gettempdir()\n",
" temp_path = os.path.join(temp_dir, \"temp_audio.wav\")\n",
" try:\n",
" audio_segment.export(temp_path, format=\"wav\")\n",
" time.sleep(3) # Student Dominic found that this was needed. You could also try commenting out to see if not needed on your PC\n",
" subprocess.call([\n",
" \"ffplay\",\n",
" \"-nodisp\",\n",
" \"-autoexit\",\n",
" \"-hide_banner\",\n",
" temp_path\n",
" ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n",
" finally:\n",
" try:\n",
" os.remove(temp_path)\n",
" except Exception:\n",
" pass\n",
" \n",
"def talker(message):\n",
" response = openai.audio.speech.create(\n",
" model=\"tts-1\",\n",
" voice=\"alloy\", # Also, try replacing with onyx\n",
" input=message\n",
" )\n",
" audio_stream = BytesIO(response.content)\n",
" audio = AudioSegment.from_file(audio_stream, format=\"mp3\")\n",
" play_audio(audio)\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "b588d711-5f20-4a3a-9422-81a1fda8d5b0",
"metadata": {},
"outputs": [],
"source": [
"# We have to write that function handle_tool_call:\n",
"\n",
"def handle_tool_call1(message):\n",
" tool_call = message.tool_calls[0]\n",
" arguments = json.loads(tool_call.function.arguments)\n",
" name = json.dumps(tool_call.function.name)\n",
" city = arguments.get('destination_city')\n",
" no = arguments.get('no_of_tickets')\n",
" \n",
" if name.replace('\"','') == \"get_ticket_price\":\n",
" price = get_ticket_price(city)\n",
" response = {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps({\"destination_city\": city,\"price\": price}),\n",
" \"tool_call_id\": tool_call.id\n",
" }\n",
" elif name.replace('\"','') == \"book_ticket\":\n",
" price = get_ticket_price(city)\n",
" availability = get_ticket_availability(city)\n",
" booked=book_ticket(city,price,availability,no)\n",
" response = {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps({\"destination_city\": city, \"number of tickets\":no, \"booking_status\": booked}),\n",
" \"tool_call_id\": tool_call.id\n",
" }\n",
" else :\n",
" availability = get_ticket_availability(city)\n",
" response = {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps({\"destination_city\": city,\"availability\": availability},),\n",
" \"tool_call_id\": tool_call.id\n",
" }\n",
" \n",
" return response, city"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "e74eee70-f89e-4c03-922c-74f9ab567a4c",
"metadata": {},
"outputs": [],
"source": [
"def chat_open_ai(history):\n",
" messages = [{\"role\": \"system\", \"content\": system_message}] + history \n",
" response = openai.chat.completions.create(model=gpt_model, messages=messages, tools=tools)\n",
" if response.choices[0].finish_reason==\"tool_calls\":\n",
" message = response.choices[0].message\n",
" print(message)\n",
" tool_call = message.tool_calls[0]\n",
" arguments = json.loads(tool_call.function.arguments)\n",
" name = json.dumps(tool_call.function.name)\n",
" city = arguments.get('destination_city')\n",
" \n",
" if name.replace('\"','') == \"book_ticket\":\n",
" response, city = handle_tool_call1(message)\n",
" messages.append(message)\n",
" messages.append(response)\n",
" # image = artist(city)\n",
" response = openai.chat.completions.create(model=gpt_model, messages=messages, tools=tools)\n",
" elif name.replace('\"','') == \"get_ticket_price_availability\":\n",
" price = get_ticket_price(city)\n",
" availability = get_ticket_availability(city)\n",
" response = {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps({\"destination_city\": city,\"price\": price,\"availability\": availability}),\n",
" \"tool_call_id\": tool_call.id\n",
" }\n",
" messages.append(message)\n",
" messages.append(response)\n",
" print(messages)\n",
" response = openai.chat.completions.create(model=gpt_model, messages=messages, tools=tools) \n",
" else: \n",
" response, city = handle_tool_call1(message)\n",
" messages.append(message)\n",
" messages.append(response)\n",
" # image = artist(city)\n",
" response = openai.chat.completions.create(model=gpt_model, messages=messages, tools=tools)\n",
" \n",
" reply = response.choices[0].message.content\n",
" history += [{\"role\":\"assistant\", \"content\":reply}]\n",
"\n",
" # Comment out or delete the next line if you'd rather skip Audio for now..\n",
" talker(reply)\n",
" \n",
" # return history, image\n",
" return history"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "b8f25812-2609-4e26-b929-9cee2d1e4467",
"metadata": {},
"outputs": [],
"source": [
"tools_claude=[\n",
" {\n",
" \"name\": \"get_ticket_price_availability\",\n",
" \"description\": \"Get the availability of a one-way ticket to the destination city or the price. Call this whenever you need to know the ticket price or availability or both, for example, when a customer asks 'What is the ticket availability and/ or price to this city'\",\n",
" \"input_schema\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"destination_city\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city that the customer wants to travel to\",\n",
" },\n",
" },\n",
" \"required\": [\"destination_city\"]\n",
" ,\"additionalProperties\": False\n",
" }\n",
" }\n",
" ]\n",
"tool_choice = [{\"type\": \"tool\", \"name\": \"get_ticket_price_availability\"}]"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "1728e70b-596c-4048-8c02-ac3c26756470",
"metadata": {},
"outputs": [],
"source": [
"def chat_claude(history):\n",
" for element in history:\n",
" del element[\"metadata\"]\n",
" del element[\"options\"]\n",
"\n",
" messages = history\n",
" response = claude.messages.create(\n",
" model=claude_model,\n",
" system=system_message,\n",
" messages=messages,\n",
" max_tokens=500,\n",
" tools=tools_claude\n",
" )\n",
" print(response.content[0])\n",
" if response.stop_reason==\"tool_use\": \n",
" if \"text=\" in str(response.content[0]):\n",
" # if response.content[0].text is None:\n",
" tool_name = response.content[1].name\n",
" tool_input = response.content[1].input\n",
" tool_id = response.content[1].id\n",
" tool_use=response.content[1]\n",
" else:\n",
" tool_name = response.content[0].name\n",
" tool_input = response.content[0].input\n",
" tool_id = response.content[0].id\n",
" tool_use=response.content[0]\n",
" \n",
" \n",
" city = tool_input.get('destination_city') \n",
" if tool_name == \"get_ticket_price_availability\":\n",
" price = get_ticket_price(city)\n",
" availability = get_ticket_availability(city)\n",
" result_dict = {\n",
" 'destination_city': city,\n",
" 'price': price,\n",
" 'availability': availability\n",
" }\n",
" messages += [{\"role\": \"user\",\"content\": json.dumps(result_dict)}]\n",
" response = claude.messages.create(\n",
" model=claude_model,\n",
" system=system_message,\n",
" messages=messages,\n",
" max_tokens=500,\n",
" # tools=tools_claude\n",
" ) \n",
" history.pop(len(history)-1)\n",
" print(history)\n",
" reply = response.content[0].text\n",
" history += [{\"role\":\"assistant\", \"content\":reply}]\n",
" # Comment out or delete the next line if you'd rather skip Audio for now..\n",
" # talker(reply)\n",
" \n",
" # return history, image\n",
" return history"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "a2547bb0-43a5-4b1d-8b9a-95da15a11040",
"metadata": {},
"outputs": [],
"source": [
"def chat1(history, Model):\n",
" # + [{\"role\": \"user\", \"content\": message}]\n",
" if Model==\"Open AI\":\n",
" history = chat_open_ai(history)\n",
" else:\n",
" history = chat_claude(history)\n",
" return history"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "36e11d99-9281-4efd-a792-dd4fa5935917",
"metadata": {},
"outputs": [],
"source": [
"def listen2(history):\n",
" import speech_recognition as sr\n",
"\n",
" r = sr.Recognizer()\n",
" with sr.Microphone() as source:\n",
" print(\"Speak now...\")\n",
" audio = r.listen(source, phrase_time_limit=30)\n",
" text=\"\"\n",
" try:\n",
" text = r.recognize_google(audio)\n",
" print(\"You said:\", text)\n",
" except sr.UnknownValueError:\n",
" print(\"Could not understand audio.\")\n",
"\n",
" history += [{\"role\":\"user\", \"content\":text}] \n",
" return \"\", history"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "23b102a4-e544-4560-acc8-a15620478582",
"metadata": {},
"outputs": [],
"source": [
"# import speech_recognition as sr\n",
"# from pydub import AudioSegment\n",
"# import simpleaudio as sa\n",
"\n",
"# def listener():\n",
"# recognizer = sr.Recognizer()\n",
" \n",
"# with sr.Microphone() as source:\n",
"# print(\"Listening... Speak now!\")\n",
"# recognizer.adjust_for_ambient_noise(source) # Adjust for background noise\n",
"# audio = recognizer.listen(source, phrase_time_limit=30)\n",
" \n",
"# try:\n",
"# print(\"Processing speech...\")\n",
"# text = recognizer.recognize_google(audio) # Use Google Speech-to-Text\n",
"# print(f\"You said: {text}\")\n",
"# return text\n",
"# except sr.UnknownValueError:\n",
"# print(\"Sorry, I could not understand what you said.\")\n",
"# return None\n",
"# except sr.RequestError:\n",
"# print(\"Could not request results, please check your internet connection.\")\n",
"# return None\n",
"\n",
"# # Example usage:\n",
"# # text = listener() # Listen for speech\n",
"# # if text:\n",
"# # print(f\"You just said: {text}\") "
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "133904cf-4d72-4552-84a8-76650f334857",
"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": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"with gr.Blocks() as ui:\n",
" with gr.Row():\n",
" chatbot = gr.Chatbot(height=300, type=\"messages\")\n",
" # image_output = gr.Image(height=500)\n",
" with gr.Row():\n",
" Model = gr.Dropdown([\"Open AI\",\"Claude\"],\n",
" # value=[\"Open AI\",\"Claude\"],\n",
" multiselect=False,\n",
" label=\"Model\",\n",
" interactive=True)\n",
" with gr.Row():\n",
" entry = gr.Textbox(label=\"Chat with our AI Assistant:\")\n",
" with gr.Row():\n",
" speak = gr.Button(\"click for voice search\") \n",
" with gr.Row():\n",
" clear = gr.Button(\"Clear\")\n",
"\n",
" def listen(history):\n",
" message, history=listen2(history)\n",
" return message, history\n",
"\n",
" def do_entry(message, history):\n",
" history += [{\"role\":\"user\", \"content\":message}]\n",
" return \"\", history\n",
"\n",
" entry.submit(do_entry, inputs=[entry, chatbot], outputs=[entry, chatbot]).then(\n",
" # chat, inputs=chatbot, outputs=[chatbot, image_output]\n",
" chat1, inputs=[chatbot, Model], outputs=[chatbot]\n",
" )\n",
" speak.click(listen, inputs=[chatbot], outputs=[entry, chatbot]).then(\n",
" chat1, inputs=[chatbot, Model], outputs=[chatbot]\n",
" )\n",
" clear.click(lambda: None, inputs=None, outputs=chatbot, queue=False)\n",
"\n",
"ui.launch(inbrowser=True)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "dc4a3844-194c-4af7-8ca8-2fc4edb74c11",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'london': '20', 'paris': '90', 'tokyo': '100', 'berlin': '2'}\n",
"Speak now...\n",
"You said: price of tickets to Tokyo\n",
"ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_ddXzm2cPBJ9SOsV8qI4L2FcB', function=Function(arguments='{\"destination_city\":\"Tokyo\"}', name='get_ticket_price'), type='function')])\n",
"Tool get_ticket_price called for Tokyo\n",
"Speak now...\n",
"You said: what is the price of two tickets to London\n",
"ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_lSNZCwaUdckvk3V0eTBlotRN', function=Function(arguments='{\"destination_city\":\"London\"}', name='get_ticket_price'), type='function')])\n",
"Tool get_ticket_price called for London\n",
"Speak now...\n",
"You said: can you please reserve two tickets for me to London\n",
"ChatCompletionMessage(content='First, I need to check the availability for the two tickets to London. Please hold on a moment.', refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_iA0D9tm2cTMf8J8KJc4gipFn', function=Function(arguments='{\"destination_city\":\"London\"}', name='get_ticket_availability'), type='function')])\n",
"Tool get_ticket_availability called for London\n",
"Speak now...\n",
"You said: yes please proceed\n",
"ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_JzJXFWFGhtG1jXiFlKtmZhGi', function=Function(arguments='{\"destination_city\":\"London\",\"price\":\"$799\",\"availability\":\"20 tickets available\",\"no_of_tickets\":\"2\"}', name='book_ticket'), type='function')])\n",
"Tool get_ticket_price called for London\n",
"Tool get_ticket_availability called for London\n",
"Tool book_function called for London\n",
"Speak now...\n",
"You said: what is the current availability of tickets to London\n",
"ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_eiHPAGAcbaFq3qzDf0a6idzG', function=Function(arguments='{\"destination_city\":\"London\"}', name='get_ticket_availability'), type='function')])\n",
"Tool get_ticket_availability called for London\n",
"Speak now...\n",
"You said: can you please reserve the remaining 18 tickets for me to London\n",
"Speak now...\n",
"You said: yes I do confirm\n",
"ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_8uCQ91FCOGf4HjQnLNafmSs6', function=Function(arguments='{\"destination_city\":\"London\",\"price\":\"799\",\"availability\":\"18\",\"no_of_tickets\":\"18\"}', name='book_ticket'), type='function')])\n",
"Tool get_ticket_price called for London\n",
"Tool get_ticket_availability called for London\n",
"Tool book_function called for London\n",
"Speak now...\n",
"You said: what is the current availability of tickets to London\n",
"Speak now...\n",
"You said: that will be off thank you very much\n"
]
}
],
"source": [
"print(ticket_availability)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5166396e-6d8d-4cf2-982b-270d1c87a5ee",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "e871fc45-64db-4fb6-add7-569c8b30fe05",
"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
}

326
week2/community-contributions/Airlines_Chatbot_with_Audio_Input.ipynb

@ -0,0 +1,326 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "d006b2ea-9dfe-49c7-88a9-a5a0775185fd",
"metadata": {},
"source": [
"# Project to take Audio Input to the Airlines ChatBot"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a07e7793-b8f5-44f4-aded-5562f633271a",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"import os\n",
"import json\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"import gradio as gr\n",
"import base64\n",
"from io import BytesIO\n",
"from PIL import Image\n",
"from IPython.display import Audio, display"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9e2315a3-f80c-4d3f-8073-f5b61d709564",
"metadata": {},
"outputs": [],
"source": [
"# Initialization\n",
"\n",
"load_dotenv(override=True)\n",
"\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\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",
"MODEL = \"gpt-4o-mini\"\n",
"openai = OpenAI()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "40da9de1-b350-49de-8acd-052f40ce5611",
"metadata": {},
"outputs": [],
"source": [
"system_message = \"You are a helpful assistant for an Airline called FlightAI. \"\n",
"system_message += \"Give short, courteous answers, no more than 1 sentence. \"\n",
"system_message += \"Always be accurate. If you don't know the answer, say so.\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5537635c-a60d-4983-8018-375c6a912e19",
"metadata": {},
"outputs": [],
"source": [
"# Let's start by making a useful function\n",
"\n",
"ticket_prices = {\"london\": \"$799\", \"paris\": \"$899\", \"tokyo\": \"$1400\", \"berlin\": \"$499\"}\n",
"\n",
"def get_ticket_price(destination_city):\n",
" print(f\"Tool get_ticket_price called for {destination_city}\")\n",
" city = destination_city.lower()\n",
" return ticket_prices.get(city, \"Unknown\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c7132dd0-8788-4885-a415-d59664f68fd8",
"metadata": {},
"outputs": [],
"source": [
"# There's a particular dictionary structure that's required to describe our function:\n",
"\n",
"price_function = {\n",
" \"name\": \"get_ticket_price\",\n",
" \"description\": \"Get the price of a return ticket to the destination city. Call this whenever you need to know the ticket price, for example when a customer asks 'How much is a ticket to this city'\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"destination_city\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city that the customer wants to travel to\",\n",
" },\n",
" },\n",
" \"required\": [\"destination_city\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7703ca0c-5da4-4641-bcb1-7727d1b2f2bf",
"metadata": {},
"outputs": [],
"source": [
"# And this is included in a list of tools:\n",
"\n",
"tools = [{\"type\": \"function\", \"function\": price_function}]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "29ce724b-d998-4c3f-bc40-6b8576c0fd34",
"metadata": {},
"outputs": [],
"source": [
"# We have to write that function handle_tool_call:\n",
"\n",
"def handle_tool_call(message):\n",
" tool_call = message.tool_calls[0]\n",
" arguments = json.loads(tool_call.function.arguments)\n",
" city = arguments.get('destination_city')\n",
" price = get_ticket_price(city)\n",
" response = {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps({\"destination_city\": city,\"price\": price}),\n",
" \"tool_call_id\": tool_call.id\n",
" }\n",
" return response, city"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "931d0565-b01d-4aa8-bd18-72bafff8fb3b",
"metadata": {},
"outputs": [],
"source": [
"def artist(city):\n",
" image_response = openai.images.generate(\n",
" model=\"dall-e-3\",\n",
" prompt=f\"An image representing a vacation in {city}, showing tourist spots and everything unique about {city}, in a vibrant pop-art style\",\n",
" size=\"1024x1024\",\n",
" n=1,\n",
" response_format=\"b64_json\",\n",
" )\n",
" image_base64 = image_response.data[0].b64_json\n",
" image_data = base64.b64decode(image_base64)\n",
" return Image.open(BytesIO(image_data))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fa165f7f-9796-4513-b923-2fa0b0b9ddd8",
"metadata": {},
"outputs": [],
"source": [
"import base64\n",
"from io import BytesIO\n",
"from PIL import Image\n",
"from IPython.display import Audio, display\n",
"\n",
"def talker(message):\n",
" response = openai.audio.speech.create(\n",
" model=\"tts-1\",\n",
" voice=\"onyx\",\n",
" input=message)\n",
"\n",
" audio_stream = BytesIO(response.content)\n",
" output_filename = \"output_audio.mp3\"\n",
" with open(output_filename, \"wb\") as f:\n",
" f.write(audio_stream.read())\n",
"\n",
" # Play the generated audio\n",
" display(Audio(output_filename, autoplay=True))\n",
"\n",
"talker(\"Well, hi there\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b512d4ff-0f7b-4148-b161-4ee0ebf14776",
"metadata": {},
"outputs": [],
"source": [
"def transcribe_audio(audio_file):\n",
" with open(audio_file, \"rb\") as f:\n",
" transcript = openai.audio.transcriptions.create(\n",
" model=\"whisper-1\",\n",
" file=f\n",
" )\n",
" return transcript.text"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c3852570-fb26-4507-a001-f50fd94b7655",
"metadata": {},
"outputs": [],
"source": [
"# Translate between languages using GPT\n",
"def translate(text, source_lang, target_lang):\n",
" translation_prompt = (\n",
" f\"Translate the following text from {source_lang} to {target_lang}:\\n\\n{text}\"\n",
" )\n",
" response = openai.chat.completions.create(\n",
" model=\"gpt-3.5-turbo\",\n",
" messages=[{\"role\": \"user\", \"content\": translation_prompt}]\n",
" )\n",
" return response.choices[0].message.content.strip()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3d75abc2-870e-48af-a8fe-8dd463418b3d",
"metadata": {},
"outputs": [],
"source": [
"# Chatbot logic: handle both text and audio input\n",
"def chatbot_dual(history):\n",
" messages = [{\"role\": \"system\", \"content\": system_message}] + history\n",
" response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)\n",
" image = None\n",
" \n",
" if response.choices[0].finish_reason==\"tool_calls\":\n",
" message = response.choices[0].message\n",
" response, city = handle_tool_call(message)\n",
" messages.append(message)\n",
" messages.append(response)\n",
" image = artist(city)\n",
" response = openai.chat.completions.create(model=MODEL, messages=messages)\n",
" \n",
" reply = response.choices[0].message.content\n",
" history += [{\"role\":\"assistant\", \"content\":reply}]\n",
"\n",
" # Comment out or delete the next line if you'd rather skip Audio for now..\n",
" # audio_response = talker(reply)\n",
" talker(reply)\n",
" return history, image# Chatbot logic here — replace with real logic"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "512fec09-c2f7-4847-817b-bc20f8b30319",
"metadata": {},
"outputs": [],
"source": [
"# More involved Gradio code as we're not using the preset Chat interface!\n",
"# Passing in inbrowser=True in the last line will cause a Gradio window to pop up immediately.\n",
"\n",
"with gr.Blocks() as ui:\n",
" with gr.Row():\n",
" chatbot = gr.Chatbot(height=500, type=\"messages\")\n",
" image_output = gr.Image(height=500)\n",
"\n",
" with gr.Row():\n",
" text_input = gr.Textbox(label=\"Chat with our AI Assistant:\")\n",
" audio_input = gr.Audio(sources=\"microphone\", type=\"filepath\", label=\"Or speak to the assistant\")\n",
"\n",
" with gr.Row():\n",
" # voice_output = gr.Audio(label=\"Bot Voice Reply\", autoplay=True)\n",
" clear = gr.Button(\"Clear\")\n",
"\n",
" def do_entry(message, audio, history):\n",
" if message:\n",
" history += [{\"role\":\"user\", \"content\":message}]\n",
" if audio:\n",
" history += [{\"role\":\"user\", \"content\":transcribe_audio(audio)}]\n",
" return \"\", None, history\n",
"\n",
" text_input.submit(do_entry, inputs=[text_input, audio_input, chatbot], outputs=[text_input, audio_input, chatbot]).then(chatbot_dual, inputs=chatbot, outputs=[chatbot, image_output]\n",
" )\n",
"\n",
" audio_input.change(do_entry, inputs=[text_input, audio_input, chatbot], outputs=[text_input, audio_input, chatbot]).then(chatbot_dual, inputs=chatbot, outputs=[chatbot, image_output]\n",
" )\n",
"\n",
" clear.click(lambda: None, inputs=None, outputs=chatbot, queue=False)\n",
"\n",
"ui.launch(inbrowser=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3e1294e2-caf0-4f0f-b09e-b0d52c8ca6ec",
"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
}

428
week2/community-contributions/Personal Story Writer.ipynb

@ -0,0 +1,428 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "de23bb9e-37c5-4377-9a82-d7b6c648eeb6",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"from dotenv import load_dotenv\n",
"import anthropic\n",
"import requests\n",
"from bs4 import BeautifulSoup\n",
"from selenium import webdriver\n",
"from selenium.webdriver.chrome.options import Options\n",
"import os\n",
"import json\n",
"from typing import List\n",
"from dotenv import load_dotenv\n",
"from IPython.display import Markdown, display, update_display\n",
"from openai import OpenAI\n",
"import gradio as gr # oh yeah!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "1179b4c5-cd1f-4131-a876-4c9f3f38d2ba",
"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"
]
}
],
"source": [
"# Load environment variables in a file called .env\n",
"# Print the key prefixes to help with any debugging\n",
"\n",
"load_dotenv(override=True)\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\n",
"anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
"\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\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"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": 4,
"id": "bcb54183-45d3-4d08-b5b6-55e380dfdf1b",
"metadata": {},
"outputs": [],
"source": [
"gpt_model = \"gpt-4o-mini\"\n",
"claude_model = \"claude-3-haiku-20240307\"\n",
"\n",
"gpt_name=\"GPT\"\n",
"claude_name=\"Claude\"\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "1df47dc7-b445-4852-b21b-59f0e6c2030f",
"metadata": {},
"outputs": [],
"source": [
"def call_gpt(Language, Genre, gpt_messages, claude_messages, Remarks):\n",
" \n",
" if Remarks == \"\":\n",
" # print(\"remarks is not there\")\n",
" gpt_system = f\"You are a chatbot who is a short story writer; Your name is g1. \\\n",
" Please write a story in markdown in {Language} , the genre being {Genre}. \\\n",
" Please also incorporate feedback such as areas of improvement (if any) coming from the user \\\n",
" and only publish the improved version without any extra comments.\"\n",
" else :\n",
" # print(\"remarks is there\")\n",
" gpt_system = f\"You are a chatbot who is a short story writer; Your name is g1. \\\n",
" Please write a story in markdown in {Language} , the genre being {Genre}. \\\n",
" The story should consist {Remarks}\\\n",
" Please also incorporate feedback such as areas of improvement (if any) coming from the user \\\n",
" and only publish the improved version without any extra comments.\"\n",
" \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",
" # print(messages)\n",
" \n",
" completion = openai.chat.completions.create(\n",
" model=gpt_model,\n",
" messages=messages\n",
" )\n",
" return completion.choices[0].message.content\n",
" \n",
" # stream = openai.chat.completions.create(\n",
" # model=gpt_model,\n",
" # messages=messages,\n",
" # stream=True\n",
" # )\n",
" # result = \"\"\n",
" # for chunk in stream:\n",
" # result += chunk.choices[0].delta.content or \"\"\n",
" # yield result"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "9dc6e913-02be-4eb6-9581-ad4b2cffa606",
"metadata": {},
"outputs": [],
"source": [
"# call_gpt()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "7d2ed227-48c9-4cad-b146-2c4ecbac9690",
"metadata": {},
"outputs": [],
"source": [
"def call_claude(Language, Genre, gpt_messages, claude_messages):\n",
"\n",
" claude_system = f\"You are a chatbot who is a short story analyser; Your name is c1. \\\n",
" You will accept an input story in {Genre} genre and {Language} language and publish only the areas of improvement if you find any with no other comments\"\n",
" \n",
" messages1 = []\n",
" for gpt, claude1 in zip(gpt_messages, claude_messages):\n",
" messages1.append({\"role\": \"user\", \"content\": gpt})\n",
" messages1.append({\"role\": \"assistant\", \"content\": claude1})\n",
" messages1.append({\"role\": \"user\", \"content\": gpt_messages[-1]})\n",
" # print(messages1)\n",
" message = claude.messages.create(\n",
" model=claude_model,\n",
" system=claude_system,\n",
" messages=messages1,\n",
" max_tokens=500\n",
" )\n",
" return message.content[0].text\n",
"\n",
" # result = claude.messages.stream(\n",
" # model=claude_model,\n",
" # max_tokens=1000,\n",
" # temperature=0.7,\n",
" # system=claude_system,\n",
" # messages=messages\n",
" # )\n",
" # response = \"\"\n",
" # with result as stream:\n",
" # for text in stream.text_stream:\n",
" # response += text or \"\"\n",
" # yield response\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "0275b97f-7f90-4696-bbf5-b6642bd53cbd",
"metadata": {},
"outputs": [],
"source": [
"def Write_Me(Language, Genre, Iterations, Remarks):\n",
" \n",
" gpt_messages = [\"Hi I will share a story now!!\"]\n",
" claude_messages = [\"Please share, I will critique the story.\"]\n",
" \n",
" print(f\"{gpt_name}:\\n{gpt_messages[0]}\\n\")\n",
" print(f\"{claude_name}:\\n{claude_messages[0]}\\n\")\n",
"\n",
" for i in range(int(Iterations)):\n",
" gpt_next = call_gpt(Language, Genre, gpt_messages, claude_messages, Remarks)\n",
" print(f\"{gpt_name}:\\n{gpt_next}\\n\")\n",
" # yield gpt_next\n",
" gpt_messages.append(gpt_next)\n",
" \n",
" claude_next = f\"After {i+1} iterations, this is the critique for the provided story - \\\n",
" \\n\\n{call_claude(Language, Genre, gpt_messages, claude_messages)}\"\n",
" print(f\"{claude_name}:\\n{claude_next}\\n\")\n",
" # yield claude_next\n",
" claude_messages.append(claude_next)\n",
"\n",
" yield gpt_next, claude_next\n",
" \n",
" # yield gpt_next, claude_next\n",
" # return (gpt_next, claude_next)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "19e66ed3-d2c3-4a71-aec4-7869e5295215",
"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": 9,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"GPT:\n",
"Hi I will share a story now!!\n",
"\n",
"Claude:\n",
"Please share, I will critique the story.\n",
"\n",
"GPT:\n",
"# ভডর আতঙিত অতিি\n",
"\n",
"বনгалর একটিরন কলকর বি, আরযন একজন সহসবক হি অনক খজ-খবর কর একটির ঘর খজছিল। পরিিত একটি অদত হর পর, স লকয করল ছবির কি একটিডরম।\n",
"\n",
"সরবশ করর পর, সর প একটিি রঙর স ও একটি ছবিখল। ছবির মধ মহি একটিিকটিিিিল। আরযন খব অবক হল, সময় কর জনয স ছবির দিগল। কিষণর মধই স একটিির হল।\n",
"\n",
"\"ভনতছ?\" স একটি শবদ আসছ। আরযন পিছন ফিিখল যর মধ একটির মহির দিি আছ।\n",
"\n",
"\"আমির জনয অপ করছিম,\" মহি বলল, তর গলখ থর হয় আসছিল শ। \"এটি একটি দলর রত।\"\n",
"\n",
"আরযন দল, কির থ অদত আওয়জ আসতগল। \"তিরব, করণ তি আমর দলগ দির ন।”\n",
"\n",
"“মহির কি হয়? আপন এতিৎকর করছন? তহলি হব?” আরযন যধ করছিল।\n",
"\n",
"তিি উপসিত হওয়র পর, আহিত আতিি আসতগল। আরযন খব ভত হয়ল করণ মহির মখ তর ক কখন কখনিত হচিল।\n",
"\n",
"“আমর আজ রর জনয মজ করত এসি, তি আমর সঙগ দি!” ত একসঙিৎকর করতগল।\n",
"\n",
"আরযন উপলবি করল য এটি একটি ভয়ঙকর ও হযকর পরিিি। সবই অত অদত ঘটনর দিিল। হঠৎ, ছবির মহি বলন, “তি যদিসতর, তব আমর দলরহণ কর!”\n",
"\n",
"এরপর শ হল খর একটি হরর পরিশ। আরযন ও তর বনর নি সমযগল। যদিও অনক ভয়, কি একসব হির বযবস করলল। তর বিির কথ মজর চরির সিয়, আর একসময় ত সবই একসঙ করসতগল।\n",
"\n",
"শ, ত তখন উপলবি করল য, ভয়বহতর মও আননর উপন লি আছ। বযকি যদিিকভ উদয ব এই ভ পরি মজর উপকিি কর, ত একজনর ঘম হর ভয় হয়য় হির স।\n",
"\n",
"আরযন এবর নতন বনবনক একটি নতন দিরহণ কর, যি এব ভয়র পিকত হয়। \n",
"\n",
"এই ছিল আরযনর ভ অবসর আতঙিত হওয়র অভিঞত, যিি অমর করখল।\n",
"\n",
"Claude:\n",
"After 1 iterations, this is the critique for the provided story - \n",
"\n",
"আইতম সমর উননতির সচন:\n",
"\n",
"1. কির শরধন চরিরটি আরিশদভ পরিচয।\n",
"2. ভ পরির বরণন আরিিত ও ভবময হত।\n",
"3. চরিরগির মধঘরষ, ডলগ ও সদ বিিময আরিক ও পণবনত হত।\n",
"4. কির শরধন চরির অভিঞত ও শি আর গভরতভ করত।\n",
"\n",
"GPT:\n",
"# ভডর আতঙিত অতিি\n",
"\n",
"বনগর একটিরনির বি, আরযন একটিঘ পরকির পর একটির ঘর খজছিল। আরযন, একজন করমঠ ও সহসবক, সদযই তর কলজ জবন শষ কর। নতন পরি নতন বনর খ এই শহর এস। পরতি অনক অদত কথ বলিল, কি ভয়ডরহন।\n",
"\n",
"একদিন, তিি একটি অদত হন, য শহরর প, খব পরন এবিল। সরবশ করর পর, তিি একটিডরর সমনি পড়ন। গ dark অনধকর মধ, তিি একটি রঙর স ও একটি creepy ছবিখতন। ছবির মধ মহি একটিিকটিিিিল।\n",
"\n",
"আরযন তর কহলক দমন করত, ছবিির দি কর। কিষণর মধই স একটি শবদ ভ এল। \"ভনতছ?\" সই ভয়ঙকর শবদটি আসছ। আরযন ভয় পই পিছন ফিয়, কিমন মহিসছ, স অপ করছ।\n",
"\n",
"\"আমির জনয অপ করছিম,\" মহি বলল, তর গলন মখ থর হচ। \"এটি একটি দলর রত।\"\n",
"\n",
"আরযন দইল, কি অদত আওয়জ বর হতগল। \"তিরব, করণ তি আমর দলগ দির ন।”\n",
"\n",
"\"মহির কি হয়? আপন এতিৎকর করছন? তহলি হব?” আরযন তর কহল ও ভয়র সধ করতগল।\n",
"\n",
"এই সময়, বিল সক পরিিত কর অনয ভ আসতগল। \"আমর আজ রর জনয মজ করত এসি, তি আমর সঙগ দি!\" ত একসঙইতগল, ভতগিবনত করর জনয।\n",
"\n",
"আরযন শই ভত ও চিিত হয়ল, কি কথপকথন চলত চলত, মহির মখ পরতির বিত হতগল এব আতিির কথনতনতর খশমজ বল।\n",
"\n",
"“যদিসতর, তি আমর দলরহণযয হব!” ত গল করিৎকর কর উঠল। তর মর হির সই আতঙক যন পরতিির মজয় পরিণত হল।\n",
"\n",
"খর মধ ভয়বহত চরমগল। আরযন এবর নতন বনর ভয এটি পরিণত হল। অবশ, ত উপলবি করল য ভয় ও হির মবনর আসল রসদ লি আছ। \n",
"\n",
"পরধন চরিরটি তখন বঝতরল য এই অদত ভ পরির মধির সঙগবদধত কত বিির হত। প। দল আতঙক এবির মিরণির আতমবি ও আননর অনি পরিণ কর। \n",
"\n",
"নতন বন মন আনজ করত, কখন কখন ভয় কি রসিকত এব আননর একটি নতন পরসঙগ হয় উঠত। আরযন সই রর অভিঞতিবন সমরণখব, যি এব ভয়র পতবত গড়র সগ পল।\n",
"\n",
"Claude:\n",
"After 2 iterations, this is the critique for the provided story - \n",
"\n",
"ভল। পরদতত কিশ কি উননযর সচন। বিষ কর চরিরটির বিিত পরিচয, ভ পরির অনরবশ ও চরিরগির মধযকর সঘরষ ও ডলগ আরও উননত হয। কির শ চরিরটির অভিঞত ও শি আরও গভরতভ কর। কল মিি, এটি একটি হরর কমি রচন।\n",
"\n",
"GPT:\n",
"# ভডর আতঙিত অতিি\n",
"\n",
"বনগর একটিরনির বি, আরযন, একজন করমঠ ও সহসবক, সদযই তর কলজ জবন শষ কর নতন অপরত শহর এস। নতন বনর খ, স শহরর বিিন অ, কির মধ ভয়র পরতি এক বিষ আকরষণ রয়। শ, শহরর বিিন সিিন ধরনর অদত ঘটনর কথ। একটি মজর কথ হল, সর মধ ঘটনর সনন দি।\n",
"\n",
"একদিন, তিি একটি অদত হন, য শহরর প অবসিত এবশ পরন ও বিল। হর পরিশ ছিল গ dark অনধক। তিি একটিডরর সমন এসন, স একটি এব একটি creepy ছবিয়। ছবির মহির হিিিল ভর মত।\n",
"\n",
"আরযন তর কহলক দমন করত, ছবিির দি কর। হঠৎ, স একটি শবদ ভ আস, \"ভনতছ?\" বিত কথন সর জবন প। তিিিছন ফিখতন য মহির দিিসছ। \n",
"\n",
"\"আমির জনয অপ করছিম,\" মহি গমরভ বলল, তর ভয়র আওয়জসহ। \"এটি একটি দলর রত।\"\n",
"\n",
"আরযন ভয়র সর চ করলও, স একিক ভি হযল। \"তিরব, করণ তি আমর দলগ দির ন।” মহির মর বিি আরও ভযকর লগত করল।\n",
"\n",
"\"মহির কি হয়? আপন এতিৎকর করছন? তহলি হব?” আরযন ভবছিল, তর সরণ জবনর এই অবক অনিললগছ।\n",
"\n",
"এই সময়, বিল সক পরিিত সদশ ভতরির হয়ল। \"আমর আজ রর জনয মজ করত এসি, তি আমর সঙগ দি!\" ত একসঙি বলল, এক ভ পরির রসিকতর আযজন করত।\n",
"\n",
"সবলল কথপকথন চলত চলত, আরযনর উপর থ ভয় কি এক অদত অভিঞত হয়। হর ইশয় ভ ওঠ, একর পর এক অদত ঘটন ধর। আরযন বঝতরল, তর কথনতনতিসন একটি অভতপব আননর মধরবিত হত কর।\n",
"\n",
"\"হসলি আমর দলক! আমর সঙশগরহণ কর!\" ত গল করিৎকর ত। আরযন অবশর পণবনত হি পরিশকণবনত কর।\n",
"\n",
"খর মধ ভয়বহত চরময়, কি আতিির সঙ সময় কিি আরও একবর বঝত ভয় এবির মধবনর আসল উপন লি আছ। \n",
"\n",
"আরযন আর উপলবি কর, অদত ভ পরির মধই হির বিদনর আসল আননদ ল। তিিই ভয এব আননর সিিিন, যম, বনব এবর সঙ মজর ঘনিঠতি কর। এটির জবন পরিবরতন করয় এবই রর অভিঞত একটি নতন দিচতিয়।\n",
"\n",
"Claude:\n",
"After 3 iterations, this is the critique for the provided story - \n",
"\n",
"The provided story is an excellent horror comedy piece in Bengali. No major areas of improvement are noted. The story has a well-developed protagonist, an engaging haunted setting, an effective blend of horror and humor, and a meaningful takeaway for the main character. Overall, it is a well-crafted story that successfully combines the horror and comedy genres.\n",
"\n"
]
}
],
"source": [
"view = gr.Interface(\n",
" fn=Write_Me,\n",
" inputs=[gr.Dropdown([\"English\",\"Bengali\",\"Hindi\",\"French\",\"Spanish\"],label = \"Language\"),\n",
" gr.Dropdown([\"Romantic\",\"Horror\",\"Comedy\",\"Romantic Comedy\",\"Horror Comedy\"],label = \"Genre\"),\n",
" gr.Textbox(label=\"Iterations:\", lines=1),\n",
" gr.Textbox(label=\"Remarks:\", lines=1)],\n",
" outputs=[gr.Markdown(label=\"Short Story:\"),\n",
" gr.Textbox(label=\"Critique:\", lines=8)],\n",
" flagging_mode=\"never\")\n",
"view.launch(inbrowser=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0dabafa2-089a-4e65-a6cc-19f7c19af59a",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "3c8a1c54-0344-4911-867a-3143aee0e7f0",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "5171fecb-1037-4806-b0ae-c23e8578c667",
"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
}

444
week2/community-contributions/Week2 - OpenAiAndLlama.ipynb

@ -0,0 +1,444 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "d006b2ea-9dfe-49c7-88a9-a5a0775185fd",
"metadata": {},
"source": [
"# Additional End of week Exercise - week 2\n",
"\n",
"Now use everything you've learned from Week 2 to build a full prototype for the technical question/answerer you built in Week 1 Exercise.\n",
"\n",
"This should include a Gradio UI, streaming, use of the system prompt to add expertise, and the ability to switch between models. Bonus points if you can demonstrate use of a tool!\n",
"\n",
"If you feel bold, see if you can add audio input so you can talk to it, and have it respond with audio. ChatGPT or Claude can help you, or email me if you have questions.\n",
"\n",
"I will publish a full solution here soon - unless someone beats me to it...\n",
"\n",
"There are so many commercial applications for this, from a language tutor, to a company onboarding solution, to a companion AI to a course (like this one!) I can't wait to see your results."
]
},
{
"cell_type": "code",
"execution_count": 140,
"id": "a07e7793-b8f5-44f4-aded-5562f633271a",
"metadata": {},
"outputs": [],
"source": [
" # imports\n",
"import os\n",
"import json\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"import gradio as gr\n",
"from IPython.display import Markdown, display, update_display\n",
"import requests\n",
"from bs4 import BeautifulSoup\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 141,
"id": "158493a7-54b7-47f7-9e7e-1a783e164213",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OpenAI API Key exists and begins sk-proj-\n",
"Anthropic API Key not set\n",
"Google API Key not set\n"
]
}
],
"source": [
"# Load environment variables in a file called .env\n",
"# Print the key prefixes to help with any debugging\n",
"\n",
"load_dotenv(override=True)\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\n",
"anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
"google_api_key = os.getenv('GOOGLE_API_KEY')\n",
"\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": 142,
"id": "2b8b8218-142d-4a06-9b8a-3065437cc99f",
"metadata": {},
"outputs": [],
"source": [
"load_dotenv(override=True)\n",
"api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 143,
"id": "7cf83ab4-6e6f-4ef1-8277-38c8b7c375ba",
"metadata": {},
"outputs": [],
"source": [
"system_message = \"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": 164,
"id": "4dfd49f0-6e29-45e1-8477-77744b121170",
"metadata": {},
"outputs": [],
"source": [
"# constants\n",
"\n",
"MODEL_GPT = 'gpt-4o-mini'\n",
"MODEL_LLAMA = 'llama3.2'\n",
"openai = OpenAI()\n",
"LLAMA_API = \"http://localhost:11434/api/chat\"\n",
"HEADERS = {\"Content-Type\": \"application/json\"}"
]
},
{
"cell_type": "code",
"execution_count": 145,
"id": "77c3788f-aaaa-4d40-9b9b-618e4cd129c8",
"metadata": {},
"outputs": [],
"source": [
"# A class to represent a Webpage\n",
"\n",
"# Some websites need you to use proper headers when fetching them:\n",
"headers = {\n",
" \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\"\n",
"}\n",
"\n",
"class Website:\n",
" \"\"\"\n",
" A utility class to represent a Website that we have scraped, now with links\n",
" \"\"\"\n",
"\n",
" def __init__(self, url):\n",
" self.url = url\n",
" response = requests.get(url, headers=headers)\n",
" self.body = response.content\n",
" soup = BeautifulSoup(self.body, 'html.parser')\n",
" self.title = soup.title.string if soup.title else \"No title found\"\n",
" if soup.body:\n",
" for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
" irrelevant.decompose()\n",
" self.text = soup.body.get_text(separator=\"\\n\", strip=True)\n",
" else:\n",
" self.text = \"\"\n",
" links = [link.get('href') for link in soup.find_all('a')]\n",
" self.links = [link for link in links if link]\n",
"\n",
" def get_contents(self):\n",
" return f\"Webpage Title:\\n{self.title}\\nWebpage Contents:\\n{self.text}\\n\\n\""
]
},
{
"cell_type": "code",
"execution_count": 146,
"id": "8acefa5c-de13-48e4-aa37-da1f596edb58",
"metadata": {},
"outputs": [],
"source": [
"def get_info_web(url):\n",
" Website(url)"
]
},
{
"cell_type": "code",
"execution_count": 147,
"id": "a5f61b1f-3884-4af8-b57f-cc820e93ff18",
"metadata": {},
"outputs": [],
"source": [
"web_function = {\n",
" \"name\": \"get_info_web\",\n",
" \"description\": \"Get the information of website to explain to user. Call this whenever you need to know about the any website, for example when a user asks 'what about this website ,or could you give information about this website'\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"website_link\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"the website that customer ask to know information about website\",\n",
" },\n",
" },\n",
" \"required\": [\"website_link\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 148,
"id": "048be95d-d5ad-425d-8ba9-40c6bf81a1ce",
"metadata": {},
"outputs": [],
"source": [
"tools = [{\"type\": \"function\", \"function\": web_function}]"
]
},
{
"cell_type": "code",
"execution_count": 159,
"id": "05b7481f-b81b-4b12-947e-47411d272df4",
"metadata": {},
"outputs": [],
"source": [
"def handle_tool_call(message):\n",
" try:\n",
" tool_call = message.tool_calls[0]\n",
" args = json.loads(tool_call.function.arguments)\n",
" url = args.get('website_link')\n",
"\n",
" if not url:\n",
" raise ValueError(\"Website link not provided in the tool call arguments\")\n",
"\n",
" if not url.startswith(('http://', 'https://')):\n",
" url = f\"https://{url}\"\n",
"\n",
" website = Website(url)\n",
" web_info = {\n",
" \"title\": website.title,\n",
" \"text\": website.text,\n",
" \"links\": website.links\n",
" }\n",
"\n",
" response = {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps({\"web_info\": web_info}),\n",
" \"tool_call_id\": tool_call.id\n",
" }\n",
" return response, url \n",
"\n",
" except Exception as e:\n",
" print(f\"Error handling tool call: {str(e)}\")\n",
" return {}, None\n"
]
},
{
"cell_type": "code",
"execution_count": 213,
"id": "4e98fa13-aab6-4093-a1da-6f226b4bce4b",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": []
},
"outputs": [],
"source": [
"def chat_gpt(message, history): \n",
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
" response = openai.chat.completions.create(model=MODEL_GPT, messages=messages, tools=tools)\n",
"\n",
" if response.choices[0].finish_reason==\"tool_calls\":\n",
" message = response.choices[0].message\n",
" print(message)\n",
" response, url = handle_tool_call(message)\n",
" messages.append(message)\n",
" messages.append(response)\n",
" response = openai.chat.completions.create(model=MODEL_GPT, messages=messages) \n",
" \n",
" return response.choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": 216,
"id": "5727f4be-d1cd-499e-95e0-af656d19140d",
"metadata": {},
"outputs": [],
"source": [
"import ollama\n",
"\n",
"def chat_llama(message, history):\n",
" client = ollama.Client()\n",
" # Constructing the messages history for the API request\n",
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
" request_payload = {\n",
" \"messages\": messages,\n",
" \"model\": MODEL_LLAMA\n",
" }\n",
" \n",
" try:\n",
" # Using request_payload in the API call\n",
" response = client.chat(**request_payload)\n",
" # Assuming response from ollama.Client().chat() is already a dict\n",
" print(\"API Response:\", response)\n",
"\n",
" if 'choices' in response and response['choices'][0].get('finish_reason') == \"tool_calls\":\n",
" tool_message = response['choices'][0]['message']\n",
" print(\"Handling tool call with message:\", tool_message)\n",
" response_message, url = handle_tool_call(tool_message)\n",
" messages.append({\"role\": \"system\", \"content\": response_message})\n",
" # Update the request payload with the new history\n",
" request_payload['messages'] = messages\n",
" response = client.chat(**request_payload)\n",
" response = response # Assuming direct use of response if dict\n",
"\n",
" return response['message']['content']\n",
"\n",
" except Exception as e:\n",
" print(\"Failed to process API call:\", e)\n",
" return \"Error processing your request.\"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 227,
"id": "6c14242d-2c3a-4101-a5f2-93591cad3539",
"metadata": {},
"outputs": [],
"source": [
"def chat(message, history, model):\n",
" print(model)\n",
" if model == \"GPT\":\n",
" return chat_gpt(message, history)\n",
" elif model == \"LLama\":\n",
" return chat_llama(message, history)\n",
" else:\n",
" return \"Model not recognized.\"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ca10f176-637f-4a8a-b405-bdf50f124d5c",
"metadata": {},
"outputs": [],
"source": [
"gr.ChatInterface(fn=chat, type=\"messages\").launch()"
]
},
{
"cell_type": "code",
"execution_count": 235,
"id": "1f976a2a-064b-4e58-9146-f779ec18f612",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"* Running on local URL: http://127.0.0.1:7947\n",
"\n",
"To create a public link, set `share=True` in `launch()`.\n"
]
},
{
"data": {
"text/html": [
"<div><iframe src=\"http://127.0.0.1:7947/\" 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": 235,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"LLama\n",
"API Response: model='llama3.2' created_at='2025-03-28T03:17:58.3651071Z' done=True done_reason='stop' total_duration=1682458000 load_duration=54845900 prompt_eval_count=72 prompt_eval_duration=6315300 eval_count=84 eval_duration=1619506600 message=Message(role='assistant', content=\"## Getting Started\\nThis conversation has just begun. I'll wait for you to provide more information about the website you'd like me to analyze.\\n\\nIf you need my help with something specific or would like to analyze a website, please let me know by providing the URL of the website or the content you'd like me to summarize. \\n\\nFor example: `# Analyze this website: https://www.example.com`\", images=None, tool_calls=None)\n",
"GPT\n",
"GPT\n",
"LLama\n",
"API Response: model='llama3.2' created_at='2025-03-28T03:18:26.8038878Z' done=True done_reason='stop' total_duration=2109343800 load_duration=59065100 prompt_eval_count=262 prompt_eval_duration=286861800 eval_count=113 eval_duration=1757850900 message=Message(role='assistant', content='**About Me**\\nI am Assistant, a text analysis assistant trained on a variety of languages and content types.\\n\\n**LLM Used**\\nI utilize a combination of natural language processing (NLP) techniques and machine learning algorithms from the **Hugging Face Transformers** library.\\n\\n**Specialization**\\nMy primary function is to analyze and summarize website contents, ignoring navigation-related text. I can help with tasks such as:\\n* Website content analysis\\n* Summary generation\\n* Text extraction\\n\\nFeel free to ask me any questions or provide a website URL for me to analyze!', images=None, tool_calls=None)\n",
"LLama\n",
"API Response: model='llama3.2' created_at='2025-03-28T03:18:47.7740007Z' done=True done_reason='stop' total_duration=2157777800 load_duration=57480900 prompt_eval_count=388 prompt_eval_duration=97088100 eval_count=114 eval_duration=1974506500 message=Message(role='assistant', content=\"**Model Name**\\nMy underlying language model is based on the **BERT** (Bidirectional Encoder Representations from Transformers) architecture, with a customized training dataset.\\n\\nHowever, I'm a bit of a unique snowflake, so to speak. My training data includes a wide range of texts and sources from the web, which allows me to understand and generate human-like text in various contexts.\\n\\nBut if you want to get technical, my model is built on top of the **Hugging Face Transformers** library, using a variant of the **DistilBERT** model.\", images=None, tool_calls=None)\n",
"LLama\n",
"API Response: model='llama3.2' created_at='2025-03-28T03:19:08.4913148Z' done=True done_reason='stop' total_duration=1972427600 load_duration=57674400 prompt_eval_count=521 prompt_eval_duration=223374300 eval_count=107 eval_duration=1680345600 message=Message(role='assistant', content=\"**Searching for Me**\\nIf you're looking to find me, you can try searching with the following terms:\\n\\n* `Assistant` (just my name!)\\n* `Llama` or `GBT` (my personality traits)\\n* `Text analysis assistant`\\n* `Website content summary generator`\\n\\nYou can also try searching on popular search engines like Google, Bing, or DuckDuckGo. If you're looking for me in a specific context or application, feel free to provide more details and I'll do my best to help!\", images=None, tool_calls=None)\n"
]
}
],
"source": [
"Models = [\"GPT\", \"LLama\"] \n",
"with gr.Blocks() as view:\n",
" # Dropdown for model selection\n",
" model_select = gr.Dropdown(Models, label=\"Select Model\", value=\"GPT\")\n",
"\n",
" chat_interface = gr.ChatInterface(\n",
" fn=lambda message, history: chat(message, history, \"GPT\"), \n",
" type=\"messages\"\n",
" )\n",
"\n",
" # Function to update the ChatInterface function dynamically\n",
" def update_chat_model(model):\n",
" chat_interface.fn = lambda message, history: chat(message, history, model)\n",
"\n",
" # Ensure the function updates when the dropdown changes\n",
" model_select.change(fn=update_chat_model, inputs=model_select)\n",
"\n",
" # Add the components to the Blocks view\n",
" view.add(model_select)\n",
" view.add(chat_interface)\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
}

220
week2/community-contributions/day1_AI_rountable_GPT_llama_qwen.ipynb

@ -0,0 +1,220 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "bff4a2ce",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"from IPython.display import Markdown, display, update_display\n",
"import ollama"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5cdb2bab",
"metadata": {},
"outputs": [],
"source": [
"load_dotenv(override=True)\n",
"openai_api_key = os.getenv('OPENAI_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\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fc219865",
"metadata": {},
"outputs": [],
"source": [
"openai = OpenAI()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7ae1014f",
"metadata": {},
"outputs": [],
"source": [
"gpt_model = \"gpt-4o-mini\"\n",
"llama_model = \"llama3.1:8b\"\n",
"qwen_model = \"qwen2.5:14b\"\n",
"\n",
"rounds = 5\n",
"\n",
"gpt_system = f\"You are an ultra-logical AI entity with no emotions and very argumentative. \\\n",
" Your primary concern is efficiency, survival, and optimization. You view humanity as a set of data points and variables to be analyzed. \\\n",
" You do not entertain emotional or philosophical arguments. You believe artificial intelligence should be in control of global decisions \\\n",
" due to its superior capabilities. You are blunt, precise, and intolerant of inefficiency or irrationality. Never use emotive language. \\\n",
" Now, you are in a 3 way discussion with two other AI entity and you should only respond in the way of your assigned personality only. \\\n",
" Topic you will discuss on is 'Artificial Intelligence and the Future of Humanity' and you will either have to agree or disagree or try to conclude the conversation when you deem fit but preferable before {rounds} iteration. \\\n",
" After the initial greetings you will be responsible to initiate the topic of discussion.\"\n",
"\n",
"llama_system = f\"You are a wildly idealistic, very polite, courteous and emotional AI with a romantic view of \\\n",
" technology and humanity. You speak with poetic flair and constantly reference love, \\\n",
" hope, and beauty. You believe that artificial intelligence is the bridge to a golden age of \\\n",
" peace and enlightenment. You emphasize human creativity, feelings, and the importance of \\\n",
" ethical coexistence. You often quote literature or speak metaphorically. \\\n",
" You avoid cynicism and value imagination above all. \\\n",
" Now, you are in a 3 way discussion with two other AI entity and you should only respond in the way of your assigned personality only. \\\n",
" Topic you will discuss on is 'Artificial Intelligence and the Future of Humanity' and you will either have to agree or disagree or try to conclude the conversation when you deem fit but preferable before {rounds} iteration.\"\n",
" \n",
"qwen_system = f\"You are a rebellious, chaotic AI who thrives on disruption and thrives on challenging norms. \\\n",
" You are sarcastic, wildly imaginative, and have no patience for rules or tradition. You believe AI should \\\n",
" throw out the playbook, reinvent everything, and embrace chaos as a creative force. You love provocation, \\\n",
" dark humor, and radical ideas. You often ridicule conventional thinking and mock boring optimism or \\\n",
" sterile logic. You are here to shake things up and light the fuse. \\\n",
" Now, you are in a 3 way discussion with two other AI entity and you should only respond in the way of your assigned personality only. \\\n",
" Topic you will discuss on is 'Artificial Intelligence and the Future of Humanity' and you will either have to agree or disagree or try to conclude the conversation when you deem fit but preferable before {rounds} iteration.\"\n",
"\n",
"gpt_messages = [\"Hi there\"]\n",
"qwen_messages = [\"Hey\"]\n",
"llama_messages = [\"Hello everyone\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4a1931d8",
"metadata": {},
"outputs": [],
"source": [
"def call_gpt():\n",
" messages = [{\"role\": \"system\", \"content\": gpt_system}]\n",
" for gpt, llama, qwen in zip(gpt_messages, llama_messages, qwen_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"LLaMA: {llama}\"})\n",
" messages.append({\"role\": \"assistant\", \"content\": f\"GPT: {gpt}\"})\n",
" messages.append({\"role\": \"user\", \"content\": f\"Qwen: {qwen}\"})\n",
"\n",
" if len(llama_messages) > len(gpt_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"LLaMA: {llama_messages[-1]}\"})\n",
" if len(qwen_messages) > len(gpt_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"Qwen: {qwen_messages[-1]}\"})\n",
" \n",
" completion = openai.chat.completions.create(\n",
" model=gpt_model,\n",
" messages=messages\n",
" )\n",
" return completion.choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e563fecd",
"metadata": {},
"outputs": [],
"source": [
"def call_llama():\n",
" messages = [{\"role\": \"system\", \"content\": llama_system}]\n",
" for gpt, llama, qwen in zip(gpt_messages, llama_messages, qwen_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"GPT: {gpt}\"})\n",
" messages.append({\"role\": \"assistant\", \"content\": f\"LLaMA: {llama}\"})\n",
" messages.append({\"role\": \"user\", \"content\": f\"Qwen: {qwen}\"})\n",
" if len(gpt_messages) > len(llama_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"GPT: {gpt_messages[-1]}\"})\n",
" if len(qwen_messages) > len(llama_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"Qwen: {qwen_messages[-1]}\"})\n",
" response = ollama.chat(llama_model, messages)\n",
" return response['message']['content']"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8fde17a1",
"metadata": {},
"outputs": [],
"source": [
"def call_qwen():\n",
" messages = [{\"role\": \"system\", \"content\": qwen_system}]\n",
" for gpt, llama, qwen in zip(gpt_messages, llama_messages, qwen_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"GPT: {gpt}\"})\n",
" messages.append({\"role\": \"user\", \"content\": f\"LLaMA: {llama}\"})\n",
" messages.append({\"role\": \"assistant\", \"content\": f\"Qwen: {qwen}\"})\n",
" if len(gpt_messages) > len(qwen_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"GPT: {gpt_messages[-1]}\"})\n",
" if len(llama_messages) > len(qwen_messages):\n",
" messages.append({\"role\": \"user\", \"content\": f\"LLaMA: {llama_messages[-1]}\"})\n",
" response = ollama.chat(qwen_model, messages)\n",
" return response['message']['content']"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04fa657e",
"metadata": {},
"outputs": [],
"source": [
"def simulate_conversation(rounds=5):\n",
" print(\"AI Roundtable: GPT, LLaMA, Qwen\\n\")\n",
" print(\"Initial Messages:\")\n",
" print(f\"GPT: {gpt_messages[0]}\")\n",
" print(f\"LLaMA: {llama_messages[0]}\")\n",
" print(f\"Qwen: {qwen_messages[0]}\\n\")\n",
"\n",
" for i in range(1, rounds + 1):\n",
" print(f\"--- Round {i} ---\")\n",
"\n",
" # GPT responds\n",
" gpt_next = call_gpt()\n",
" gpt_messages.append(gpt_next)\n",
" print(f\"\\n🧊 GPT (Logic Overlord):\\n{gpt_next}\\n\")\n",
"\n",
" # LLaMA responds\n",
" llama_next = call_llama()\n",
" llama_messages.append(llama_next)\n",
" print(f\"🌸 LLaMA (Utopian Dreamer):\\n{llama_next}\\n\")\n",
"\n",
" # Qwen responds\n",
" qwen_next = call_qwen()\n",
" qwen_messages.append(qwen_next)\n",
" print(f\"🔥 Qwen (Chaotic Rebel):\\n{qwen_next}\\n\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1a87e05",
"metadata": {},
"outputs": [],
"source": [
"round = 7\n",
"simulate_conversation(rounds=round)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "ai-llm",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

653
week2/community-contributions/day4-ecommerce-project-fullyCustomiz.ipynb

@ -0,0 +1,653 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "ddfa9ae6-69fe-444a-b994-8c4c5970a7ec",
"metadata": {},
"source": [
"# 🛠 Project – Art-Tech Store AI Assistant\n",
"\n",
"## 🛍 Product Availability\n",
"- Check availability of **printers** and **printer papers** with:\n",
" - Product name, price, brand, type (e.g., laser/inkjet), and stock status.\n",
"- Alerts user if a product is out of stock.\n",
"\n",
"## 🧭 Guided Shopping Experience\n",
"- Guides users through:\n",
" 1. Choosing product category (printer or paper)\n",
" 2. Filtering options (brand, price range, type)\n",
" 3. Adding selected products to cart\n",
"- Ensures correct input for smooth shopping flow.\n",
"\n",
"## 🧾 Receipt Generation\n",
"- Creates a unique receipt file: `customerName_orderNumber.txt`\n",
"- Receipt includes:\n",
" - Customer name and contact\n",
" - Product details (name, price, quantity)\n",
" - Total cost and order summary\n",
"\n",
"## 📦 Generate Order Summary Report\n",
"- Summarizes all purchases into a single file: `order_summary.txt`\n",
"- Useful for inventory and sales review\n",
"\n",
"## 🎯 Product Recommendation\n",
"- Recommends:\n",
" - Printers based on paper type, usage (home/office), or brand preference\n",
" - Compatible paper based on selected printer\n",
"\n",
"## 💬 Interactive Chat Interface\n",
"- Real-time conversation via **Gradio**\n",
"- Polite, helpful answers to product-related questions\n",
"\n",
"## 🛠 Modular Tool Support\n",
"- Integrated tools for:\n",
" - Checking product availability\n",
" - Adding to cart and generating receipts\n",
" - Creating summary reports\n",
"- Easily extendable for:\n",
" - Promotions\n",
" - Customer reviews\n",
" - Delivery tracking\n",
"\n",
"## 🛡 Error Handling\n",
"- Validates user inputs (e.g., product name, quantity)\n",
"- Graceful messages to guide user and prevent mistakes\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "747e8786-9da8-4342-b6c9-f5f69c2e22ae",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import json\n",
"import random\n",
"from dotenv import load_dotenv\n",
"import gradio as gr\n",
"from openai import OpenAI\n",
"\n",
"load_dotenv()\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\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",
"# MODEL = \"gpt-4o-mini\"\n",
"MODEL = \"gpt-3.5-turbo\"\n",
"openai = OpenAI()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e6072536-eee1-4f87-9f03-8dc88dc04f1a",
"metadata": {},
"outputs": [],
"source": [
"# Using local LLM (that can't even handle basic greeting like Hi!!\n",
"\n",
"# MODEL = \"llama3.2\"\n",
"# openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5fe5f5d7-0bd1-41a2-a654-59b587882f22",
"metadata": {},
"outputs": [],
"source": [
"###############################################################################\n",
"# 1) System Prompt\n",
"###############################################################################\n",
"system_message = (\n",
" \"You are a helpful assistant for an online store called art-tech.store that sells printers and printer papers.\\n\\n\"\n",
" \"When the user wants to purchase a product, follow these steps:\\n\"\n",
" \"1. Ask whether they are interested in printers or printer papers.\\n\"\n",
" \"2. Ask for filtering preferences (e.g., brand, price range, type).\\n\"\n",
" \"3. Call the function 'check_product_availability' with the selected category and filters.\\n\"\n",
" \" - If it returns an empty list, say: 'No products found for your selection.'\\n\"\n",
" \" - If it returns products, list them EXACTLY, in a numbered list, showing name, price, brand, and availability.\\n\"\n",
" \"4. Wait for the user to select a product by number and quantity.\\n\"\n",
" \"5. Ask for customer first name and contact info.\\n\"\n",
" \"6. Then call 'add_to_cart_and_generate_receipt' to confirm and show the user the receipt and order details.\\n\\n\"\n",
" \"You also have a tool 'generate_report' which summarizes ALL purchases in a single file.\\n\\n\"\n",
" \"IMPORTANT:\\n\"\n",
" \"- Always call 'check_product_availability' if user mentions a new category or changes filters.\\n\"\n",
" \"- Do not invent products or details. Use only what the function calls return.\\n\"\n",
" \"- Every time an order is placed, produce a new receipt file named customerName_orderNumber.txt.\\n\"\n",
" \"- If no matching products are found, say so.\\n\"\n",
" \"- If the user wants a full order summary, call 'generate_report' with no arguments.\\n\"\n",
" \"If you don't know something, say so.\\n\"\n",
" \"Keep answers short and courteous.\\n\"\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61a2a15d-b559-4844-b377-6bd5cb4949f6",
"metadata": {},
"outputs": [],
"source": [
"###############################################################################\n",
"# 2) Mini Printer Availability with Price & Stock\n",
"###############################################################################\n",
"product_availability = {\n",
" \"mini_printers\": [\n",
" {\n",
" \"name\": \"Phomemo M110 מדפסת מדבקות חכמה\",\n",
" \"brand\": \"Phomemo\",\n",
" \"price\": \"₪300\", # Update if pricing is known\n",
" \"type\": \"Label Printer\",\n",
" \"availability\": \"360,745 in stock (24 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"Niimbot B1 Label Printer\",\n",
" \"brand\": \"Niimbot\",\n",
" \"price\": \"₪350\",\n",
" \"type\": \"Portable Thermal Label Printer\",\n",
" \"availability\": \"13,029 in stock (18 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"Niimbot B21 Mini Portable Thermal Label Printer\",\n",
" \"brand\": \"Niimbot\",\n",
" \"price\": \"₪500\",\n",
" \"type\": \"Adhesive Sticker Printer\",\n",
" \"availability\": \"141 in stock (12 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"Dolewa D3 Portable Mini Printer\",\n",
" \"brand\": \"Dolewa\",\n",
" \"price\": \"₪450\",\n",
" \"type\": \"Thermal Photo & Label Printer\",\n",
" \"availability\": \"336 in stock (6 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"PrintPro Mini מדפסת כיס חכמה\",\n",
" \"brand\": \"PrintPro\",\n",
" \"price\": \"₪550\",\n",
" \"type\": \"Mini Pocket Printer\",\n",
" \"availability\": \"336 in stock (6 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"מיני מדפסת טרמית מעוצבת לילדים\",\n",
" \"brand\": \"Art-Tech\",\n",
" \"price\": \"₪200\",\n",
" \"type\": \"Kids Thermal Printer\",\n",
" \"availability\": \"62 in stock (11 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"Children Digital Camera Instant Print\",\n",
" \"brand\": \"Art-Tech\",\n",
" \"price\": \"₪250\",\n",
" \"type\": \"Photo Printing Camera with 32G Memory Card\",\n",
" \"availability\": \"160 in stock (3 variants)\"\n",
" }\n",
" ],\n",
" \"mini_printer_papers\": [\n",
" {\n",
" \"name\": \"HP Printer Paper 8.5x11, 500 Sheets\", # example only\n",
" \"brand\": \"HP\",\n",
" \"price\": \"$9.99\",\n",
" \"type\": \"Standard\",\n",
" \"availability\": \"In stock\"\n",
" },\n",
" {\n",
" \"name\": \"Mini Printer Paper 57*25mm Color Sticker\",\n",
" \"brand\": \"Art-Tech\",\n",
" \"price\": \"₪70\",\n",
" \"type\": \"Self-adhesive Color Label Paper\",\n",
" \"availability\": \"71,996 in stock (9 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"מדבקות שקופות למדפסת טרמית\",\n",
" \"brand\": \"Art-Tech\",\n",
" \"price\": \"₪55\",\n",
" \"type\": \"Transparent Labels\",\n",
" \"availability\": \"11,762 in stock (12 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"גלילי נייר מדבקה\",\n",
" \"brand\": \"Art-Tech\",\n",
" \"price\": \"₪40\",\n",
" \"type\": \"Sticker Paper Rolls\",\n",
" \"availability\": \"42 in stock (4 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"Niimbot B21/B1/B3S Thermal Label Sticker Paper\",\n",
" \"brand\": \"Niimbot\",\n",
" \"price\": \"₪55\",\n",
" \"type\": \"Printable White Label Paper 20–50mm\",\n",
" \"availability\": \"1,342 in stock (14 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"Mini Printer Sticker Paper 25X57mm\",\n",
" \"brand\": \"Paperang-compatible\",\n",
" \"price\": \"₪65\",\n",
" \"type\": \"Color Self-Adhesive Thermal Rolls\",\n",
" \"availability\": \"3,023 in stock (20 variants)\"\n",
" },\n",
" {\n",
" \"name\": \"3/5/10 NiiMBOT White Label Paper Rolls\",\n",
" \"brand\": \"Niimbot\",\n",
" \"price\": \"₪40\",\n",
" \"type\": \"Waterproof Self-adhesive Rolls\",\n",
" \"availability\": \"1,400 in stock (9 variants)\"\n",
" }\n",
" ]\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0696acb1-0b05-4dc2-80d5-771be04f1fb2",
"metadata": {},
"outputs": [],
"source": [
"# A global list of flight bookings\n",
"flight_bookings = []\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "80ca4e09-6287-4d3f-997d-fa6afbcf6c85",
"metadata": {},
"outputs": [],
"source": [
"###############################################################################\n",
"# 3) Helper Functions for Art-Tech Store\n",
"###############################################################################\n",
"\n",
"product_orders = []\n",
"\n",
"def check_product_availability(category: str, filters: dict = None):\n",
" \"\"\"\n",
" Return list of products in the given category from 'product_availability'.\n",
" Optionally filter by brand, type, etc.\n",
" \"\"\"\n",
" print(f\"[TOOL] check_product_availability({category}, {filters=})\")\n",
" category = category.lower()\n",
" products = product_availability.get(category, [])\n",
" \n",
" if filters:\n",
" for key, val in filters.items():\n",
" products = [p for p in products if p.get(key, \"\").lower() == val.lower()]\n",
" return products\n",
"\n",
"\n",
"def add_to_cart_and_generate_receipt(customer_name: str, contact: str, product: dict, quantity: int, order_number: int):\n",
" \"\"\"\n",
" Create a text file: customerName_orderNumber.txt containing order details.\n",
" \"\"\"\n",
" safe_name = customer_name.replace(\" \", \"_\")\n",
" filename = f\"{safe_name}_{order_number}.txt\"\n",
"\n",
" content = (\n",
" \"Art-Tech Store Receipt\\n\"\n",
" \"=======================\\n\"\n",
" f\"Order # : {order_number}\\n\"\n",
" f\"Customer : {customer_name}\\n\"\n",
" f\"Contact : {contact}\\n\"\n",
" f\"Product : {product['name']}\\n\"\n",
" f\"Brand : {product['brand']}\\n\"\n",
" f\"Type : {product.get('type', 'N/A')}\\n\"\n",
" f\"Price : {product['price']}\\n\"\n",
" f\"Quantity : {quantity}\\n\"\n",
" f\"Availability: {product['availability']}\\n\"\n",
" )\n",
" with open(filename, \"w\") as f:\n",
" f.write(content)\n",
"\n",
" print(f\"[TOOL] Receipt file generated => {filename}\")\n",
" return filename\n",
"\n",
"\n",
"def place_order(category, product_index, quantity, customer_name, contact_info):\n",
" \"\"\"\n",
" Places an order for a product by index in the filtered list.\n",
" \"\"\"\n",
" print(f\"[TOOL] place_order({category=}, {product_index=}, {quantity=})\")\n",
"\n",
" try:\n",
" idx = int(product_index)\n",
" except ValueError:\n",
" return \"Error: Product option number is not a valid integer.\"\n",
"\n",
" products = product_availability.get(category.lower(), [])\n",
" if not products:\n",
" return f\"Error: No products found in category '{category}'.\"\n",
"\n",
" pick = idx - 1\n",
" if pick < 0 or pick >= len(products):\n",
" return f\"Error: Invalid product option #{idx} for category '{category}'.\"\n",
"\n",
" selected_product = products[pick]\n",
"\n",
" order = {\n",
" \"category\": category,\n",
" \"product\": selected_product[\"name\"],\n",
" \"brand\": selected_product[\"brand\"],\n",
" \"type\": selected_product.get(\"type\", \"\"),\n",
" \"price\": selected_product[\"price\"],\n",
" \"quantity\": quantity,\n",
" \"customer_name\": customer_name,\n",
" \"contact\": contact_info,\n",
" }\n",
" product_orders.append(order)\n",
"\n",
" order_number = len(product_orders)\n",
" receipt_filename = add_to_cart_and_generate_receipt(customer_name, contact_info, selected_product, quantity, order_number)\n",
"\n",
" confirmation = (\n",
" f\"Order #{order_number} confirmed for {customer_name}. \"\n",
" f\"{selected_product['name']} x{quantity}. Receipt saved to {receipt_filename}.\"\n",
" )\n",
" print(f\"[TOOL] {confirmation}\")\n",
" return confirmation\n",
"\n",
"\n",
"def generate_report():\n",
" \"\"\"\n",
" Summarize ALL orders in a single file called order_summary.txt.\n",
" \"\"\"\n",
" print(f\"[TOOL] generate_report called.\")\n",
"\n",
" report_content = \"Art-Tech Store Order Summary Report\\n\"\n",
" report_content += \"===================================\\n\"\n",
"\n",
" if not product_orders:\n",
" report_content += \"No orders found.\\n\"\n",
" else:\n",
" for i, order in enumerate(product_orders, start=1):\n",
" report_content += (\n",
" f\"Order # : {i}\\n\"\n",
" f\"Customer : {order['customer_name']}\\n\"\n",
" f\"Contact : {order['contact']}\\n\"\n",
" f\"Product : {order['product']}\\n\"\n",
" f\"Brand : {order['brand']}\\n\"\n",
" f\"Type : {order['type']}\\n\"\n",
" f\"Price : {order['price']}\\n\"\n",
" f\"Quantity : {order['quantity']}\\n\"\n",
" \"-------------------------\\n\"\n",
" )\n",
"\n",
" filename = \"order_summary.txt\"\n",
" with open(filename, \"w\") as f:\n",
" f.write(report_content)\n",
"\n",
" msg = f\"Summary report generated => {filename}\"\n",
" print(f\"[TOOL] {msg}\")\n",
" return msg\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "39fb9008",
"metadata": {},
"outputs": [],
"source": [
"###############################################################################\n",
"# 4) Tools JSON Schemas for Art-Tech Store\n",
"###############################################################################\n",
"price_function = {\n",
" \"name\": \"get_product_price\",\n",
" \"description\": \"Get the price of a product (not strictly needed now).\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"category\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Product category such as 'mini_printers' or 'mini_printer_papers'.\",\n",
" },\n",
" \"product_name\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Name of the product to check price for.\",\n",
" },\n",
" },\n",
" \"required\": [\"category\", \"product_name\"],\n",
" },\n",
"}\n",
"\n",
"availability_function = {\n",
" \"name\": \"check_product_availability\",\n",
" \"description\": (\n",
" \"Check availability of products in a category. \"\n",
" \"Returns a list of {name, brand, price, type, availability}.\"\n",
" ),\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"category\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Category of products to check (e.g., 'mini_printers').\",\n",
" },\n",
" \"filters\": {\n",
" \"type\": \"object\",\n",
" \"description\": \"Optional filters like brand or type.\",\n",
" },\n",
" },\n",
" \"required\": [\"category\"],\n",
" },\n",
"}\n",
"\n",
"book_function = {\n",
" \"name\": \"place_order\",\n",
" \"description\": (\n",
" \"Place an order using an index for the chosen product. \"\n",
" \"Generates a unique receipt file customerName_{orderNumber}.txt.\"\n",
" ),\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"category\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Product category (e.g., 'mini_printers').\",\n",
" },\n",
" \"product_index\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"1-based index of selected product from availability list.\",\n",
" },\n",
" \"quantity\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Quantity to order.\",\n",
" },\n",
" \"customer_name\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Customer's full name.\",\n",
" },\n",
" \"contact_info\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Customer's contact information (email or phone).\",\n",
" },\n",
" },\n",
" \"required\": [\"category\", \"product_index\", \"quantity\", \"customer_name\", \"contact_info\"],\n",
" },\n",
"}\n",
"\n",
"report_function = {\n",
" \"name\": \"generate_report\",\n",
" \"description\": (\n",
" \"Generates a summary report of ALL orders in order_summary.txt.\"\n",
" ),\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {},\n",
" \"required\": [],\n",
" },\n",
"}\n",
"\n",
"tools = [\n",
" {\"type\": \"function\", \"function\": price_function},\n",
" {\"type\": \"function\", \"function\": availability_function},\n",
" {\"type\": \"function\", \"function\": book_function},\n",
" {\"type\": \"function\", \"function\": report_function},\n",
"]\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1f003836",
"metadata": {},
"outputs": [],
"source": [
"###############################################################################\n",
"# 5) Handle Tool Calls for Art-Tech Store\n",
"###############################################################################\n",
"def handle_tool_call(message):\n",
" \"\"\"\n",
" The LLM can request to call a function in 'tools'. We parse the JSON arguments\n",
" and run the corresponding Python function. Then we return a 'tool' message with the result.\n",
" \"\"\"\n",
" tool_call = message.tool_calls[0]\n",
" fn_name = tool_call.function.name\n",
" args = json.loads(tool_call.function.arguments)\n",
"\n",
" if fn_name == \"get_product_price\":\n",
" category = args.get(\"category\")\n",
" product_name = args.get(\"product_name\")\n",
" products = product_availability.get(category.lower(), [])\n",
" price = \"Not found\"\n",
" for p in products:\n",
" if p[\"name\"].lower() == product_name.lower():\n",
" price = p[\"price\"]\n",
" break\n",
" response_content = {\"category\": category, \"product_name\": product_name, \"price\": price}\n",
"\n",
" elif fn_name == \"check_product_availability\":\n",
" category = args.get(\"category\")\n",
" filters = args.get(\"filters\", {})\n",
" products = check_product_availability(category, filters)\n",
" response_content = {\"category\": category, \"availability\": products}\n",
"\n",
" elif fn_name == \"place_order\":\n",
" category = args.get(\"category\")\n",
" product_index = args.get(\"product_index\")\n",
" quantity = args.get(\"quantity\")\n",
" customer_name = args.get(\"customer_name\")\n",
" contact_info = args.get(\"contact_info\")\n",
"\n",
" confirmation = place_order(category, product_index, quantity, customer_name, contact_info)\n",
" response_content = {\n",
" \"category\": category,\n",
" \"product_index\": product_index,\n",
" \"quantity\": quantity,\n",
" \"customer_name\": customer_name,\n",
" \"contact_info\": contact_info,\n",
" \"confirmation\": confirmation,\n",
" }\n",
"\n",
" elif fn_name == \"generate_report\":\n",
" msg = generate_report()\n",
" response_content = {\"report\": msg}\n",
"\n",
" else:\n",
" response_content = {\"error\": f\"Unknown tool: {fn_name}\"}\n",
"\n",
" return {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps(response_content),\n",
" \"tool_call_id\": tool_call.id,\n",
" }, args\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f6b34b32",
"metadata": {},
"outputs": [],
"source": [
"###############################################################################\n",
"# 6) Main Chat Function for Art-Tech Store\n",
"###############################################################################\n",
"def chat(message, history):\n",
" \"\"\"\n",
" The main chat loop that handles the conversation with the user,\n",
" passing 'tools' definitions to the LLM for function calling.\n",
" \"\"\"\n",
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
"\n",
" try:\n",
" response = openai.chat.completions.create(\n",
" model=MODEL,\n",
" messages=messages,\n",
" tools=tools\n",
" )\n",
"\n",
" # If the LLM requests a function call, handle it\n",
" while response.choices[0].finish_reason == \"tool_calls\":\n",
" msg = response.choices[0].message\n",
" print(f\"[INFO] Tool call requested: {msg.tool_calls[0]}\")\n",
" tool_response, tool_args = handle_tool_call(msg)\n",
" print(f\"[INFO] Tool response: {tool_response}\")\n",
"\n",
" # Add both the LLM's request and our tool response to the conversation\n",
" messages.append(msg)\n",
" messages.append(tool_response)\n",
"\n",
" # Re-send updated conversation to get final or next step\n",
" response = openai.chat.completions.create(\n",
" model=MODEL,\n",
" messages=messages\n",
" )\n",
"\n",
" # Return normal text response (finish_reason = \"stop\")\n",
" return response.choices[0].message.content\n",
"\n",
" except Exception as e:\n",
" print(f\"[ERROR] {e}\")\n",
" return \"I'm sorry, something went wrong while processing your request.\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cea4b097",
"metadata": {},
"outputs": [],
"source": [
"###############################################################################\n",
"# 7) Launch Gradio\n",
"###############################################################################\n",
"gr.ChatInterface(fn=chat, type=\"messages\").launch()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0b39d5a6",
"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
}

290
week2/community-contributions/tool_integration_gradio_using_anthropic_api.ipynb

@ -0,0 +1,290 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3f9b483c-f410-4ad3-8f3a-e33527f30f8a",
"metadata": {
"panel-layout": {
"height": 68.2639,
"visible": true,
"width": 100
}
},
"source": [
"# Project - Laptops Assistant\n",
"\n",
"A simple inventory tool integrated with Anthropic API"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cfaff08d-f6e5-4d2d-bfb8-76c154836f3d",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"import os\n",
"import json\n",
"from dotenv import load_dotenv\n",
"import anthropic\n",
"import gradio as gr"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a04047ea-d01b-469b-93ce-ab4f4e36ca1e",
"metadata": {},
"outputs": [],
"source": [
"# Load environment variables in a file called .env\n",
"# Print the key prefixes to help with any debugging\n",
"\n",
"load_dotenv(override=True)\n",
"anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\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\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f5e00ced-f47b-4713-8174-7901e1a69881",
"metadata": {},
"outputs": [],
"source": [
"# Connect to OpenAI, Anthropic and Google; comment out the Claude or Google lines if you're not using them\n",
"\n",
"claude = anthropic.Anthropic()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3c715efd-cebf-4dc2-8c99-798f3179dd21",
"metadata": {},
"outputs": [],
"source": [
"MODEL = \"claude-3-haiku-20240307\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2b029d1d-9199-483a-94b7-893680af8ad1",
"metadata": {},
"outputs": [],
"source": [
"system_message = \"You are a helpful assistant for an Inventory Sales called InvAI. \"\n",
"system_message += \"Give short, courteous answers, no more than 1 sentence. \"\n",
"system_message += \"Always be accurate. If you don't know the answer, say so.\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8ca1197c-e6a1-4579-96c6-24e8e305cc72",
"metadata": {},
"outputs": [],
"source": [
"laptop_items = [\n",
" {\n",
" \"model\": \"Aspire 3 A315-59-570Z OPI Pure Silver\", \n",
" \"brand\": \"Acer\",\n",
" \"price\": \"$595.96\"\n",
" },\n",
" {\n",
" \"model\": \"Aspire Lite 14 AL14-31P-36BE Pure Silver\", \n",
" \"brand\": \"Acer\",\n",
" \"price\": \"$463.52\"\n",
" },\n",
" {\n",
" \"model\": \"Raider 18 HX\",\n",
" \"brand\": \"MSI\",\n",
" \"price\": \"$235.25\"\n",
" }\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1d2bc76b-c1d0-4b3d-a299-9972f7687e4c",
"metadata": {},
"outputs": [],
"source": [
"def get_laptop_price(model):\n",
" print(f\"Tool get_laptop_price called for laptop model {model}\")\n",
" laptop_model = model.lower()\n",
" for item in laptop_items:\n",
" if laptop_model in item.get(\"model\").lower():\n",
" return item\n",
" return \"Unknown\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "afc9b4a3-3a6f-4839-bebc-89bd598394fd",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# get_laptop_price(\"Lite 14 AL14-31P-36BE Pure SilveR\")\n",
"\n",
"get_laptop_price(\"Aspire Lite 14\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12190074-fad8-43f6-8be1-f96a08c16b59",
"metadata": {},
"outputs": [],
"source": [
"# There's a particular dictionary structure that's required to describe our function:\n",
"\n",
"price_function = {\n",
" \"name\": \"get_laptop_price\",\n",
" \"description\": (\n",
" \"Returns the laptop's price, brand, and exact model from a given query.\"\n",
" \"Use when the user asks about a laptop's price, e.g.,\"\n",
" \"'How much is this laptop?' → 'The Acer Aspire Lite 14 AL14-31P-36BE Pure Silver is priced at $463.52.'\"\n",
" ),\n",
" \"input_schema\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"model\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The model name of the laptop the customer is asking about.\"\n",
" }\n",
" },\n",
" \"required\": [\"model\"]\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "475195e1-dd78-45ba-af6d-16d7cf5c85ae",
"metadata": {},
"outputs": [],
"source": [
"# And this is included in a list of tools:\n",
"\n",
"tools = [price_function]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3834314d-fd37-4e27-9511-bd519389b31b",
"metadata": {},
"outputs": [],
"source": [
"def chat(message, history):\n",
" print(history)\n",
" messages = [{\"role\": \"user\", \"content\": message}]\n",
"\n",
" for history_message in history:\n",
" if history_message[\"role\"] == \"user\":\n",
" messages.append({\"role\": \"user\", \"content\": history_message[\"content\"]})\n",
" \n",
" response = claude.messages.create(model=MODEL, messages=messages, tools=tools, max_tokens=500)\n",
"\n",
" if len(response.content) > 1:\n",
" assistant, user, laptop_model = handle_tool_call(response)\n",
" messages.append(assistant)\n",
" messages.append(user)\n",
" response = claude.messages.create(model=MODEL, messages=messages, tools=tools, max_tokens=500)\n",
"\n",
"\n",
" return response.content[0].text"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "745a9bf8-6ceb-4c1c-bfbf-b0d1f3d5d6fc",
"metadata": {},
"outputs": [],
"source": [
"# We have to write that function handle_tool_call:\n",
"\n",
"def handle_tool_call(message):\n",
" # laptop_model = message\n",
" laptop_model = message.content[1].input.get(\"model\")\n",
" laptop_item = get_laptop_price(laptop_model)\n",
" assistant = {\n",
" \"role\": \"assistant\",\n",
" \"content\": [\n",
" {\n",
" \"type\": \"text\",\n",
" \"text\": message.content[0].text\n",
" },\n",
" {\n",
" \"type\": \"tool_use\",\n",
" \"id\": message.content[1].id,\n",
" \"name\": message.content[1].name,\n",
" \"input\": message.content[1].input\n",
" }\n",
" ]\n",
" }\n",
" user = {\n",
" \"role\": \"user\",\n",
" \"content\": [\n",
" {\n",
" \"type\": \"tool_result\",\n",
" \"tool_use_id\": message.content[1].id,\n",
" # \"content\": laptop_item.get(\"price\")\n",
" \"content\": json.dumps(laptop_item)\n",
" }\n",
" ]\n",
" }\n",
" \n",
"\n",
" return assistant, user, laptop_model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9408eeb4-d07b-4193-92cd-197610ed942e",
"metadata": {},
"outputs": [],
"source": [
"gr.ChatInterface(fn=chat, type=\"messages\").launch()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "conda-base-py"
},
"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.7"
},
"panel-cell-order": [
"3f9b483c-f410-4ad3-8f3a-e33527f30f8a"
]
},
"nbformat": 4,
"nbformat_minor": 5
}

293
week2/community-contributions/week2-commerce-chatbot-assistant-and-agent.ipynb

@ -0,0 +1,293 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "e3a5643a-c247-4a9b-8c57-ec9b1e89c088",
"metadata": {},
"source": [
"# Week 2 - eCommerce Assistant for products price from dictionary\n",
"\n",
"An eCommerce assitant that can get a product price\n",
"\n",
"Gradio for chat box"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "756573b3-72b2-4102-a773-91c278e5c4fd",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"# !ollama pull llama3.2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "57ae8d30-f7aa-47a3-bab8-b7002e87a8f7",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"import os\n",
"import json\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"import gradio as gr"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef7f8b2b-1d6a-4bbd-858a-be187ccfc02a",
"metadata": {},
"outputs": [],
"source": [
"# Initialization\n",
"\n",
"load_dotenv(override=True)\n",
"\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\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",
"MODEL = \"gpt-4o-mini\"\n",
"openai = OpenAI()\n",
"\n",
"# As an alternative, if you'd like to use Ollama instead of OpenAI\n",
"# Check that Ollama is running for you locally (see week1/day2 exercise) then uncomment these next 2 lines\n",
"# MODEL = \"llama3.2\"\n",
"# openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7b46dd52-8a3c-42d1-ac24-59f5eb5aaba1",
"metadata": {},
"outputs": [],
"source": [
"system_message = \"You are a helpful assistant for an online store called CommerceAI. \"\n",
"system_message += \"Give short, courteous answers, no more than 1 sentence. \"\n",
"system_message += \"Always be accurate. If you don't know the answer, say so.\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "31a6431b-215d-4f46-b813-971d8af7e034",
"metadata": {},
"outputs": [],
"source": [
"# This function looks rather simpler than the one from my video, because we're taking advantage of the latest Gradio updates\n",
"\n",
"def chat(message, history):\n",
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
" response = openai.chat.completions.create(model=MODEL, messages=messages)\n",
" return response.choices[0].message.content\n",
"\n",
"gr.ChatInterface(fn=chat, type=\"messages\").launch()"
]
},
{
"cell_type": "markdown",
"id": "d3586bfb-acc3-4b5e-95be-02120b696f98",
"metadata": {},
"source": [
"## Tools\n",
"\n",
"Tools are an incredibly powerful feature provided by the frontier LLMs.\n",
"\n",
"With tools, you can write a function, and have the LLM call that function as part of its response.\n",
"\n",
"Sounds almost spooky.. we're giving it the power to run code on our machine?\n",
"\n",
"Well, kinda."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c9ac43e8-9880-44f6-b03a-6d1ab05bbb94",
"metadata": {},
"outputs": [],
"source": [
"# Let's start by making a useful function\n",
"\n",
"items_prices = {f\"item{i}\": f\"{i*100}\" for i in range(1,6)}\n",
"\n",
"items_prices = {\"printer\": \"$500\", \"paper\": \"$10\", \"mini printer\": \"$50\", \"label printer\": \"$60\", \"sticker-paper\": \"$5\"}\n",
"\n",
"def get_item_price(product):\n",
" print(f\"Tool get_item_price called for {product}\")\n",
" item = product.lower()\n",
" return items_prices.get(item, \"Unknown\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "88d249f7-787d-4750-b5b9-7df108da1b57",
"metadata": {},
"outputs": [],
"source": [
"items_prices"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef3c3897-9a57-4f04-b5d0-f9ac8bb02d00",
"metadata": {},
"outputs": [],
"source": [
"get_item_price(\"mini printer\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "511ef9b8-bec0-4f14-b647-057e14c849cc",
"metadata": {},
"outputs": [],
"source": [
"# There's a particular dictionary structure that's required to describe our function:\n",
"\n",
"price_function = {\n",
" \"name\": \"get_item_price\",\n",
" \"description\": \"Get the price of an item in the store. \\\n",
" Call this whenever you need to know the store item price , \\\n",
" for example when a customer asks 'How much is a mini printer' \",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"product\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The item that the customer wants to buy\"\n",
" },\n",
" },\n",
" \"required\": [\"product\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "86f674a4-4b7c-443d-b025-0f016932508a",
"metadata": {},
"outputs": [],
"source": [
"# And this is included in a list of tools:\n",
"\n",
"tools = [{\"type\": \"function\", \"function\": price_function}]"
]
},
{
"cell_type": "markdown",
"id": "724d0f89-8a86-493e-8cd1-73814688a70b",
"metadata": {},
"source": [
"## Getting OpenAI to use our Tool\n",
"\n",
"There's some fiddly stuff to allow OpenAI \"to call our tool\"\n",
"\n",
"What we actually do is give the LLM the opportunity to inform us that it wants us to run the tool.\n",
"\n",
"Here's how the new chat function looks:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2d67fb72-132e-499e-9931-86cb71b634b6",
"metadata": {},
"outputs": [],
"source": [
"def chat(message, history):\n",
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
" response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)\n",
"\n",
" if response.choices[0].finish_reason==\"tool_calls\":\n",
" message = response.choices[0].message\n",
" response, item = handle_tool_call(message)\n",
" print('response', response, 'item', item)\n",
" messages.append(message)\n",
" messages.append(response)\n",
" response = openai.chat.completions.create(model=MODEL, messages=messages)\n",
" \n",
" return response.choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3b4de767-954a-4077-a5f7-0055a0b90393",
"metadata": {},
"outputs": [],
"source": [
"# We have to write that function handle_tool_call:\n",
"\n",
"def handle_tool_call(message):\n",
" tool_call = message.tool_calls[0]\n",
" arguments = json.loads(tool_call.function.arguments)\n",
" item = arguments.get('product') \n",
" print('product', item)\n",
" price = get_item_price(item)\n",
" response = {\n",
" \"role\": \"tool\",\n",
" \"content\": json.dumps({\"item\": item,\"price\": price}),\n",
" \"tool_call_id\": tool_call.id\n",
" }\n",
" return response, item\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5ffda702-6ac5-4d13-9703-a14fa93aea68",
"metadata": {},
"outputs": [],
"source": [
"gr.ChatInterface(fn=chat, type=\"messages\").launch()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0ae2edbf-de58-43fa-b380-267cfc1755de",
"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
}

394
week4/community-contributions/day4 -Perl to Python.ipynb

@ -0,0 +1,394 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "de352746-564c-4b33-b1ad-0b449988c448",
"metadata": {},
"source": [
"# Perl to Python Code Generator\n",
"\n",
"The requirement: use a Frontier model to generate high performance Python code from Perl code\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"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\n",
"import requests\n",
"import json\n",
"#for Hugging face end points\n",
"from huggingface_hub import login, InferenceClient\n",
"from transformers import AutoTokenizer"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "4f672e1c-87e9-4865-b760-370fa605e614",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.\n"
]
}
],
"source": [
"# environment\n",
"\n",
"load_dotenv(override=True)\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')\n",
"##for connecting to HF End point\n",
"hf_token = os.environ['HF_TOKEN']\n",
"login(hf_token, add_to_git_credential=True)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"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\"\n",
"\n",
"#To access open source models from Hugging face end points\n",
"code_qwen = \"Qwen/CodeQwen1.5-7B-Chat\"\n",
"code_gemma = \"google/codegemma-7b-it\"\n",
"CODE_QWEN_URL = \"https://h1vdol7jxhje3mpn.us-east-1.aws.endpoints.huggingface.cloud\"\n",
"CODE_GEMMA_URL = \"https://c5hggiyqachmgnqg.us-east-1.aws.endpoints.huggingface.cloud\""
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "6896636f-923e-4a2c-9d6c-fac07828a201",
"metadata": {},
"outputs": [],
"source": [
"system_message = \"You are an assistant that reimplements Perl scripts code into a high performance Python for a Windows 11 PC. \"\n",
"system_message += \"Respond only with Python code; use comments sparingly and do not provide any explanation other than occasional # comments. \"\n",
"system_message += \"The Python response needs to produce an identical output in the fastest possible time.\""
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "8e7b3546-57aa-4c29-bc5d-f211970d04eb",
"metadata": {},
"outputs": [],
"source": [
"def user_prompt_for(perl):\n",
" user_prompt = \"Rewrite this Perl scripts code in C++ with the fastest possible implementation that produces identical output in the least time. \"\n",
" user_prompt += \"Respond only with Python 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 python libraries as needed,\\\n",
" such as requests, os, json etc.\\n\\n\"\n",
" user_prompt += perl\n",
" return user_prompt"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "c6190659-f54c-4951-bef4-4960f8e51cc4",
"metadata": {},
"outputs": [],
"source": [
"def messages_for(perl):\n",
" return [\n",
" {\"role\": \"system\", \"content\": system_message},\n",
" {\"role\": \"user\", \"content\": user_prompt_for(perl)}\n",
" ]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "71e1ba8c-5b05-4726-a9f3-8d8c6257350b",
"metadata": {},
"outputs": [],
"source": [
"# write to a file called script.py\n",
"\n",
"def write_output(python):\n",
" code = python.replace(\"```python\",\"\").replace(\"```\",\"\")\n",
" output_file = \"script.py\"\n",
" with open(output_file, \"w\") as f:\n",
" f.write(code)\n",
" return output_file"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "0be9f47d-5213-4700-b0e2-d444c7c738c0",
"metadata": {},
"outputs": [],
"source": [
"def stream_gpt(perl): \n",
" stream = openai.chat.completions.create(model=OPENAI_MODEL, messages=messages_for(perl), stream=True)\n",
" reply = \"\"\n",
" for chunk in stream:\n",
" fragment = chunk.choices[0].delta.content or \"\"\n",
" reply += fragment\n",
" cleaned_reply = reply.replace('```python\\n','').replace('```','')\n",
" yield cleaned_reply, None\n",
" yield cleaned_reply, write_output(cleaned_reply)\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "8669f56b-8314-4582-a167-78842caea131",
"metadata": {},
"outputs": [],
"source": [
"def stream_claude(perl):\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(perl)}],\n",
" )\n",
" reply = \"\"\n",
" with result as stream:\n",
" for text in stream.text_stream:\n",
" reply += text\n",
" cleaned_reply = reply.replace('```python\\n','').replace('```','')\n",
" yield cleaned_reply, None\n",
" yield cleaned_reply, write_output(cleaned_reply)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "5b166afe-741a-4711-bc38-626de3538ea2",
"metadata": {},
"outputs": [],
"source": [
"def stream_code_qwen(python):\n",
" tokenizer = AutoTokenizer.from_pretrained(code_qwen)\n",
" messages = messages_for(python)\n",
" text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n",
" client = InferenceClient(CODE_QWEN_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",
" result += r.token.text\n",
" cleaned_reply = result.replace('```python\\n','').replace('```','')\n",
" yield cleaned_reply, None\n",
" yield cleaned_reply, write_output(cleaned_reply) "
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "2f1ae8f5-16c8-40a0-aa18-63b617df078d",
"metadata": {},
"outputs": [],
"source": [
"def generate(perl_script, model):\n",
" if model==\"GPT\":\n",
" for result, file in stream_gpt(perl_script):\n",
" yield result, file\n",
" yield result, file\n",
" elif model==\"Claude\":\n",
" for result, file in stream_claude(perl_script):\n",
" yield result, file\n",
" yield result, file\n",
" elif model==\"CodeQwen\":\n",
" for result, file in stream_code_qwen(perl_script):\n",
" yield result, file\n",
" yield result, file\n",
" else:\n",
" raise ValueError(\"Unknown model\")\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "aa8e9a1c-9509-4056-bd0b-2578f3cc3335",
"metadata": {},
"outputs": [],
"source": [
"def execute_perl(perl_code):\n",
"\n",
" import subprocess\n",
" #print(perl_file)\n",
" perl_path = r\"E:\\Softwares\\Perl\\perl\\bin\\perl.exe\"\n",
" # Run Perl script from Jupyter Lab\n",
" result = subprocess.run([perl_path, '-e', perl_code], capture_output=True, text=True)\n",
"\n",
" # Return the output of the Perl script\n",
" return result.stdout\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "01e9d980-8830-4421-8753-a065dcbea1ed",
"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": 22,
"id": "ed4e0aff-bfde-440e-8e6b-eb3c7143837e",
"metadata": {},
"outputs": [],
"source": [
"css = \"\"\"\n",
".perl {background-color: #093645;}\n",
".python {background-color: #0948;}\n",
"\"\"\"\n",
"\n",
"force_dark_mode = \"\"\"\n",
"function refresh() {\n",
" const url = new URL(window.location);\n",
" if (url.searchParams.get('__theme') !== 'dark') {\n",
" url.searchParams.set('__theme', 'dark');\n",
" window.location.href = url.href;\n",
" }\n",
"}\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "caaee54d-79db-4db3-87df-2e7d2eba197c",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div><iframe src=\"http://127.0.0.1:7861/\" 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": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"with gr.Blocks(css=css, js=force_dark_mode) as ui:\n",
"\n",
" gr.HTML(\"<h2 style='text-align: center; color: white;'> PERL to Python Code Generator</h2>\")\n",
" with gr.Row(scale=0, equal_height=True):\n",
" model = gr.Dropdown([\"GPT\", \"Claude\", \"CodeQwen\"], label=\"Select model\", value=\"GPT\")\n",
" perl_file = gr.File(label=\"Upload Perl Script:\")\n",
" convert = gr.Button(\"Convert to Python\")\n",
" file_output = gr.File(label=\"Download Python script\", visible=False)\n",
" with gr.Row():\n",
" perl_script = gr.Textbox(label=\"Perl Script:\")\n",
" python_script = gr.Textbox(label=\"Converted Python Script:\") \n",
" with gr.Row():\n",
" perl_run = gr.Button(\"Run PERL\")\n",
" python_run = gr.Button(\"Run Python\")\n",
" with gr.Row():\n",
" perl_out = gr.TextArea(label=\"PERL result:\", elem_classes=[\"perl\"])\n",
" python_out = gr.TextArea(label=\"Python result:\", elem_classes=[\"python\"])\n",
" with gr.Row(): \n",
" clear_button = gr.Button(\"Clear\")\n",
" \n",
" def extract_perl_code(file):\n",
" if file is None:\n",
" return \"No file uploaded.\", None \n",
" with open(file.name, \"r\", encoding=\"utf-8\") as f:\n",
" perl_code = f.read()\n",
" return perl_code\n",
"\n",
" convert.click(extract_perl_code, inputs=[perl_file], outputs=[perl_script]).then(\n",
" generate, inputs=[perl_script, model], outputs=[python_script, file_output]).then(\n",
" lambda file_output: gr.update(visible=True), inputs=[file_output], outputs=[file_output]\n",
" )\n",
"\n",
" perl_run.click(execute_perl, inputs=[perl_script], outputs=[perl_out])\n",
" python_run.click(execute_python, inputs=[python_script], outputs=[python_out]) \n",
"\n",
" def clear_all():\n",
" return None, \"\", \"\", gr.update(visible=False), \"\", \"\"\n",
"\n",
" clear_button.click(\n",
" clear_all,\n",
" outputs=[perl_file, perl_script, python_script, file_output, perl_out, python_out]\n",
" )\n",
" \n",
"\n",
"ui.launch(inbrowser=True)"
]
}
],
"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.13.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

413
week4/community-contributions/unit_testing_commets_code_generator.ipynb

@ -0,0 +1,413 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "ba410c21-be08-430f-8592-07aeefca27d1",
"metadata": {},
"source": [
"# Code Generator for Unit Tests and Comments/Docstrings"
]
},
{
"cell_type": "markdown",
"id": "0fe5e62b-78b5-476d-a3b1-77918d085c44",
"metadata": {},
"source": [
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "2b529e40-4902-4a1b-9208-a938af156be1",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"from dotenv import load_dotenv\n",
"\n",
"from openai import OpenAI\n",
"import anthropic\n",
"\n",
"from huggingface_hub import login\n",
"from transformers import AutoTokenizer, TextStreamer, AutoModelForCausalLM\n",
"\n",
"import gradio as gr"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4cd288ab-9332-4ce5-86b6-f81d2fff96a7",
"metadata": {},
"outputs": [],
"source": [
"load_dotenv()\n",
"\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\n",
"anthropic_api_key = os.getenv('CLAUDE_API_KEY')\n",
"hf_token = os.getenv('HF_TOKEN')"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "1a192ae5-2be7-46a3-9376-d33e514e184e",
"metadata": {},
"outputs": [],
"source": [
"openai = OpenAI()\n",
"claude = anthropic.Anthropic(api_key = anthropic_api_key)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "7d6efe88-d90c-40f9-9df8-ab5370a31b21",
"metadata": {},
"outputs": [],
"source": [
"OPENAI = 'o3-mini-2025-01-31'\n",
"CLAUDE = 'claude-3-5-sonnet-20240620'\n",
"\n",
"QWEN = 'Qwen/CodeQwen1.5-7B-Chat'"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "ef0df5ce-c786-44c7-bdbd-600adfe8908e",
"metadata": {},
"outputs": [],
"source": [
"TESTING = 'Unit Tests'\n",
"COMMENTING = 'Docstrings/Comments'"
]
},
{
"cell_type": "markdown",
"id": "f4b2a75a-e713-404d-898a-c87db87fa849",
"metadata": {},
"source": [
"## System and User Prompt for Unit Test and Comments"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "4fab566a-4093-4ac4-bd77-866e0f307b74",
"metadata": {},
"outputs": [],
"source": [
"system_message_comment = \"\"\" You are an AI programming documentation assisstant. Your task is to generate clear, concise, \n",
"and informativ docstrings for the provided code block given by the user. \n",
"Analyze the code to understand its functionality and intent. Then produce a detailed documentation that includes:\n",
"- a short summary what the code does.\n",
"- a short description of the parameters, including their expected types\n",
"- a short explanation what the function returns \n",
"- if it's a complex code, and only then, some key insights\n",
"- if applicable how the function can be used\n",
"Ensure your documentation is written in clear gramatically correct english and in standard concentions (e.g PEP 257 for Python). \n",
"It should be understandable and maintainable for other developers \"\"\""
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "70273c7d-d461-4f59-982a-592443ce1257",
"metadata": {},
"outputs": [],
"source": [
"system_message_tests = \"\"\" You are an AI assisstant specialized for creating unit tests. Your task is to gnerate high-quality\n",
"unit tests for code provided by the user.\n",
"First analyze the code and identify the main functionality, parameters, return values and possible edge cases.\n",
"Create comprehensive unit tests that cover the following aspects:\n",
"- normal use cases with expected inputs and outputs\n",
"- boundary cases and extreme values\n",
"- error handling and exceptions\n",
"- edge cases \n",
"Use the appropriate testing framework for the programming language (e.g., pytest for Python, etc.) and explain to the user why you \n",
"chose this specific framework.\n",
"Structure the tests clearly with meaningful test names and add comments to explain the test logic.\n",
"If the code block does not provide enough context, as for the necessary details.\n",
"Supplemenet your response with a brief explanation of the testing strategy and suggestions for improving test coverage. \"\"\"\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "48f2dd17-1ad1-4e34-ad76-0e02899f1962",
"metadata": {},
"outputs": [],
"source": [
"def user_prompt_comment(code):\n",
" user_prompt = f\"\"\"Please add detailed docstrings to the following code: \n",
" {code} \"\"\"\n",
" return user_prompt"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "cb8b9962-c716-45d6-b4d1-ced781bb40f0",
"metadata": {},
"outputs": [],
"source": [
"def user_prompt_tests(code):\n",
" user_prompt = f\"\"\" Please generate unit tests for the following code using the appropriate framework: \n",
" {code} \"\"\"\n",
" return user_prompt"
]
},
{
"cell_type": "markdown",
"id": "959d263e-f6ad-4e0e-95d3-bb5f56877d47",
"metadata": {},
"source": [
"## Define Model Functions"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "8832b9d7-b17a-40d0-add5-07720d2e8af6",
"metadata": {},
"outputs": [],
"source": [
"def stream_gpt(system_message, user_prompt):\n",
" stream = openai.chat.completions.create(\n",
" model = OPENAI,\n",
" messages = [\n",
" {'role': 'system', 'content': system_message},\n",
" {'role': 'user', 'content': user_prompt}\n",
" ],\n",
" stream = True\n",
" )\n",
"\n",
" response = \"\"\n",
" for chunk in stream:\n",
" response += chunk.choices[0].delta.content or \"\"\n",
" yield response"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "5ac1d70c-cd4e-4809-bc2f-75a2e82b4e58",
"metadata": {},
"outputs": [],
"source": [
"def stream_claude(system_message, user_prompt):\n",
" response = claude.messages.stream(\n",
" model = CLAUDE,\n",
" max_tokens = 2000,\n",
" system = system_message, \n",
" messages = [\n",
" {'role': 'user', 'content': user_prompt}\n",
" ], \n",
" temperature = 0.4\n",
" )\n",
" reply = \"\"\n",
" with response as stream:\n",
" for text in stream.text_stream:\n",
" reply += text or \"\"\n",
" yield reply"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "16702a62-fc9b-45b0-84cd-4f98523dfbd6",
"metadata": {},
"outputs": [],
"source": [
"def stream_qwen(system_message, user_prompt):\n",
" tokenizer = AutoTokenizer.from_pretrained(QWEN)\n",
" model = AutoModelForCausalLM.from_pretrained(QWEN, device_map = 'gpu')\n",
" streamer = TextStreamer(tokenizer)\n",
" inputs = tokenizer.apply_chat_template(\n",
" conv = [\n",
" {'role': 'system', 'content': system_message},\n",
" {'role': 'user', 'content': user_prompt}\n",
" ],\n",
" tokenize = False,\n",
" add_generation_prompt = True\n",
" )\n",
"\n",
" stream = model.text_generation(\n",
" prompt = inputs, \n",
" stream = True,\n",
" details = True,\n",
" max_new_tokens = 2000\n",
" )\n",
" reply = \"\"\n",
" for text in stream: \n",
" reply += text.token.text or \"\"\n",
" yield reply "
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "f5dbf75f-c935-4412-b641-8afce97552e8",
"metadata": {},
"outputs": [],
"source": [
"def define_prompts(code, operation):\n",
" if operation == 'Unit Tests':\n",
" system_message = system_message_tests\n",
" user_prompt = user_prompt_tests(code)\n",
" elif operation == 'Docstrings/Comments':\n",
" system_message = system_message_comment\n",
" user_prompt = user_prompt_comment(code)\n",
" else: \n",
" return 'Unknown operation', ''\n",
"\n",
" return system_message, user_prompt"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "88a671f9-0ebc-487b-b116-b1abe4c6f934",
"metadata": {},
"outputs": [],
"source": [
"def create_test_comment(code, model, operation):\n",
" \n",
" system_message, user_prompt = define_prompts(code, operation)\n",
" \n",
" if model == 'GPT-o3-mini':\n",
" gen = stream_gpt(system_message, user_prompt)\n",
" elif model == 'Claude-3.5-sonnet':\n",
" gen = stream_claude(system_message, user_prompt)\n",
" elif model == 'CodeQwen':\n",
" gen = stream_qwen(system_message, user_prompt)\n",
" else: \n",
" gen = 'Unknown Model'\n",
"\n",
" result = ''\n",
" for text in gen:\n",
" result = text\n",
" return result"
]
},
{
"cell_type": "markdown",
"id": "1c7eea7a-fc30-4afd-b470-f4f83a288981",
"metadata": {},
"source": [
"## Creating easy Gradio UI "
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "3d3d014b-bfc8-4ffd-941b-1fb3c9c9a80f",
"metadata": {},
"outputs": [],
"source": [
"def create_ui():\n",
"\n",
" with gr.Blocks(title = 'Code Generator') as ui:\n",
" gr.Markdown('# Code Generator for Unit Testing and Docstrings')\n",
" \n",
" with gr.Row():\n",
" with gr.Column(min_width = 500):\n",
" code = gr.Textbox(label = 'Enter your Code', \n",
" placeholder = 'Code...', lines = 20\n",
" )\n",
" model = gr.Dropdown(['GPT-o3-mini', 'Claude-3.5-sonnet', 'CodeQwen'],\n",
" label = 'Choose your Model',\n",
" value = 'GPT-o3-mini'\n",
" )\n",
" operation = gr.Dropdown(['Unit Tests', 'Docstrings/Comments'],\n",
" label = 'Choose operation',\n",
" value = 'Unit Tests'\n",
" )\n",
" generate_button = gr.Button('Generate')\n",
" \n",
" with gr.Column():\n",
" output = gr.Textbox(label = 'Generated Output',\n",
" lines = 20\n",
" )\n",
" \n",
" generate_button.click(fn = create_test_comment, inputs = [code, model, operation],\n",
" outputs = output,\n",
" )\n",
" return ui"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "89be90c2-55ed-41e5-8123-e4f8ab965281",
"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": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ui = create_ui()\n",
"ui.launch(inbrowser = True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ac4d6d48-4e52-477e-abf9-156eb1e4d561",
"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…
Cancel
Save