From 9bb5816871124a816cf23da28d1f010dccfa5140 Mon Sep 17 00:00:00 2001 From: Zoya Hammad Date: Sat, 1 Mar 2025 17:21:56 +0500 Subject: [PATCH 1/2] Added my contributions to community-contributions --- .../week 2 - multi modal StudyAI.ipynb | 305 ++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 week2/community-contributions/week 2 - multi modal StudyAI.ipynb diff --git a/week2/community-contributions/week 2 - multi modal StudyAI.ipynb b/week2/community-contributions/week 2 - multi modal StudyAI.ipynb new file mode 100644 index 0000000..6eeb971 --- /dev/null +++ b/week2/community-contributions/week 2 - multi modal StudyAI.ipynb @@ -0,0 +1,305 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "6aa646e3-7a57-461a-b69a-073179effa18", + "metadata": {}, + "source": [ + "## Additional End of week Exercise - week 2\n", + "\n", + "This includes \n", + "- Gradio UI\n", + "- use of the system prompt to add expertise\n", + "- audio input so you can talk to it\n", + "- respond with audio" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "72f3dca4-b052-4e9f-90c8-f42e667c165c", + "metadata": {}, + "outputs": [], + "source": [ + "# imports\n", + "\n", + "import os\n", + "from dotenv import load_dotenv\n", + "from openai import OpenAI\n", + "from IPython.display import Markdown, display, update_display\n", + "import gradio as gr\n", + "import json" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "23570b9f-8c7a-4cc7-b809-3505334b60a7", + "metadata": {}, + "outputs": [], + "source": [ + "# Load environment variables in a file called .env\n", + "\n", + "load_dotenv(override=True)\n", + "openai_api_key = os.getenv('OPENAI_API_KEY')\n", + "openai = OpenAI()\n", + "MODEL = 'gpt-4o-mini'" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "d379178a-8672-4e6f-a380-ad8d85f5c64e", + "metadata": {}, + "outputs": [], + "source": [ + "system_message = \"\"\"You are a personal study tutor, designed to provide clear, yet brief and succint answers to \n", + "students that ask you questions. The topics are related to data science, computer science \n", + "and technology in general, so you are allowed to use a moderate level of jargon. Explain in \n", + "simple terminology, so a student can easily understand. \n", + "\n", + "You may also be asked about prices for special courses.In this case, respond that you have no such\n", + "data available. \n", + "\n", + "\"\"\"\n", + "# Use a tabular format where possible \n", + "# for ease of information flow " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "4745d439-c66e-4e5c-b5d4-9f0ba97aefdc", + "metadata": {}, + "outputs": [], + "source": [ + "def chat(history):\n", + " messages = [{\"role\": \"system\", \"content\": system_message}] + history\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", + " talker(reply)\n", + " \n", + " return history" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "a8b31799-df86-4151-98ea-66ef50fe767e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Requirement already satisfied: openai-whisper in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (20240930)\n", + "Requirement already satisfied: numba in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from openai-whisper) (0.61.0)\n", + "Requirement already satisfied: numpy in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from openai-whisper) (1.26.4)\n", + "Requirement already satisfied: torch in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from openai-whisper) (2.6.0)\n", + "Requirement already satisfied: tqdm in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from openai-whisper) (4.67.1)\n", + "Requirement already satisfied: more-itertools in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from openai-whisper) (10.6.0)\n", + "Requirement already satisfied: tiktoken in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from openai-whisper) (0.9.0)\n", + "Requirement already satisfied: llvmlite<0.45,>=0.44.0dev0 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from numba->openai-whisper) (0.44.0)\n", + "Requirement already satisfied: regex>=2022.1.18 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from tiktoken->openai-whisper) (2024.11.6)\n", + "Requirement already satisfied: requests>=2.26.0 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from tiktoken->openai-whisper) (2.32.3)\n", + "Requirement already satisfied: filelock in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from torch->openai-whisper) (3.17.0)\n", + "Requirement already satisfied: typing-extensions>=4.10.0 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from torch->openai-whisper) (4.12.2)\n", + "Requirement already satisfied: sympy!=1.13.2,>=1.13.1 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from torch->openai-whisper) (1.13.3)\n", + "Requirement already satisfied: networkx in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from torch->openai-whisper) (3.4.2)\n", + "Requirement already satisfied: jinja2 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from torch->openai-whisper) (3.1.5)\n", + "Requirement already satisfied: fsspec in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from torch->openai-whisper) (2024.12.0)\n", + "Requirement already satisfied: colorama in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from tqdm->openai-whisper) (0.4.6)\n", + "Requirement already satisfied: charset_normalizer<4,>=2 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from requests>=2.26.0->tiktoken->openai-whisper) (3.4.1)\n", + "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from requests>=2.26.0->tiktoken->openai-whisper) (3.10)\n", + "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from requests>=2.26.0->tiktoken->openai-whisper) (2.3.0)\n", + "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from requests>=2.26.0->tiktoken->openai-whisper) (2025.1.31)\n", + "Requirement already satisfied: mpmath<1.4,>=1.1.0 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from sympy!=1.13.2,>=1.13.1->torch->openai-whisper) (1.3.0)\n", + "Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\92310\\anaconda3\\envs\\llms\\lib\\site-packages (from jinja2->torch->openai-whisper) (2.1.5)\n" + ] + } + ], + "source": [ + "!pip install openai-whisper" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "9f5b8e51-2833-44be-a4f4-63c4683f2b6e", + "metadata": {}, + "outputs": [], + "source": [ + "import whisper\n", + "\n", + "def transcribe_audio(audio):\n", + " if audio is None:\n", + " return \"No audio received.\"\n", + " \n", + " model = whisper.load_model(\"base\") # You can use \"tiny\", \"small\", etc.\n", + " result = model.transcribe(audio)\n", + " \n", + " return result[\"text\"]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "e55f8e43-2da1-4f2a-bcd4-3fffa830db48", + "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))" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "cb3107a7-bfdc-4255-825f-bfabcf458c0c", + "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=400,type=\"messages\")\n", + " with gr.Row():\n", + " entry = gr.Textbox(label=\"Chat with our StudyAI Assistant:\")\n", + " # with gr.Row():\n", + " # entry = gr.Textbox(label=\"Speak or Type:\", placeholder=\"Speak your question...\", interactive=True, microphone=True)\n", + " with gr.Row():\n", + " audio_input = gr.Audio(type=\"filepath\", label=\"Speak your question\")\n", + " with gr.Row():\n", + " clear = gr.Button(\"Clear\")\n", + "\n", + " def do_entry(message, history):\n", + " history += [{\"role\":\"user\", \"content\":message}]\n", + " return \"\", history\n", + "\n", + " def handle_audio(audio, history):\n", + " text = transcribe_audio(audio)\n", + " history += [{\"role\": \"user\", \"content\": text}]\n", + " return \"\", history\n", + "\n", + " entry.submit(do_entry, inputs=[entry, chatbot], outputs=[entry, chatbot]).then(\n", + " chat, inputs=[chatbot], outputs=[chatbot]\n", + " )\n", + "\n", + " audio_input.change(handle_audio, inputs=[audio_input, chatbot], outputs=[entry, chatbot]).then(\n", + " chat, inputs=[chatbot], outputs=[chatbot]\n", + " )\n", + " \n", + " clear.click(lambda: [], inputs=None, outputs=chatbot, queue=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "73e0a776-d43e-4b04-a37f-a27d3714cf47", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Rerunning server... use `close()` to stop if you need to change `launch()` parameters.\n", + "----\n", + "\n", + "To create a public link, set `share=True` in `launch()`.\n" + ] + }, + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "ui.launch(inbrowser=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bcd45503-d314-4b28-a41c-4dbb87059188", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.11" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 0e841efd1dc5637926fdfede688aa86287029a3f Mon Sep 17 00:00:00 2001 From: Zoya Hammad Date: Sat, 1 Mar 2025 17:23:54 +0500 Subject: [PATCH 2/2] Added contributions to community-contributions --- .../day 4 w2 - course booking assistant.ipynb | 361 ++++++++++++++++++ .../day3 w2 -programming tutor.ipynb | 209 ++++++++++ 2 files changed, 570 insertions(+) create mode 100644 week2/community-contributions/day 4 w2 - course booking assistant.ipynb create mode 100644 week2/community-contributions/day3 w2 -programming tutor.ipynb diff --git a/week2/community-contributions/day 4 w2 - course booking assistant.ipynb b/week2/community-contributions/day 4 w2 - course booking assistant.ipynb new file mode 100644 index 0000000..aedaa59 --- /dev/null +++ b/week2/community-contributions/day 4 w2 - course booking assistant.ipynb @@ -0,0 +1,361 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "5d799d2a-6e58-4a83-b17a-dbbc40efdc39", + "metadata": {}, + "source": [ + "## Project - Course Booking AI Asssistant\n", + "AI Customer Support Bot that \n", + "- Returns Prices\n", + "- Books Tickets\n", + "- Adds Information to Text File" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "b1ad9acd-a702-48a3-8ff5-d536bcac8030", + "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": 2, + "id": "74adab0c-99b3-46cd-a79f-320a3e74138a", + "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", + "MODEL = \"gpt-4o-mini\"\n", + "openai = OpenAI()" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "8d3240a4-99c1-4c07-acaa-ecbb69ffd2e4", + "metadata": {}, + "outputs": [], + "source": [ + "system_message = \"You are a helpful assistant for an Online Course Platform called StudyAI. \"\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.\"\n", + "system_message += \"If you are given a partial name, for example 'discrete' instead of 'discrete structures' \\\n", + "ask the user if they meant to say 'discrete structures', and then display the price. The user may also use \\\n", + "acronyms like 'PF' instead of programming fundamentals or 'OOP' to mean 'Object oriented programming'. \\\n", + "Clarify wh\"" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "9a1b8d5f-f893-477b-8396-ff7d697eb0c3", + "metadata": {}, + "outputs": [], + "source": [ + "course_prices = {\"programming fundamentals\": \"$19\", \"discrete structures\": \"$39\", \"operating systems\": \"$24\", \"object oriented programming\": \"$39\"}\n", + "\n", + "def get_course_price(course):\n", + " print(f\"Tool get_course_price called for {course}\")\n", + " course = course.lower()\n", + " return course_prices.get(course, \"Unknown\")\n", + "\n", + "def enroll_in_course(course):\n", + " print(f'Tool enroll_in_course_ called for {course}')\n", + " course_price = get_course_price(course)\n", + " if course_price != 'Unknown':\n", + " with open('enrolled_courses.txt', 'a') as file: \n", + " file.write(course + \"\\n\")\n", + " return 'Successfully enrolled in course'\n", + " else:\n", + " return 'Enrollment failed, no such course available'" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "330d2b94-a8c5-4967-ace7-15d2cd52d7ae", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tool get_course_price called for graph theory\n", + "Tool get_course_price called for discrete structures\n" + ] + }, + { + "data": { + "text/plain": [ + "'$39'" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "get_course_price('graph theory')\n", + "get_course_price('discrete structures')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "5bb65830-fab8-45a7-bf43-7e52186915a0", + "metadata": {}, + "outputs": [], + "source": [ + "price_function = {\n", + " \"name\": \"get_course_price\",\n", + " \"description\": \"Get the price of a course. Call this whenever you need to know the course price, for example when a customer asks 'How much is a ticket for this course?'\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"course\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The course that the customer wants to purchase\",\n", + " },\n", + " },\n", + " \"required\": [\"course\"],\n", + " \"additionalProperties\": False\n", + " }\n", + "}\n", + "\n", + "enroll_function = {\n", + " \"name\": \"enroll_in_course\",\n", + " \"description\":\"Get the success status of course enrollment. Call whenever a customer wants to enroll in a course\\\n", + " for example, if they say 'I want to purchase this course' or 'I want to enroll in this course'\",\n", + " \"parameters\":{\n", + " \"type\":\"object\",\n", + " \"properties\":{\n", + " \"course\":{\n", + " \"type\":\"string\",\n", + " \"description\": \"The course that the customer wants to purchase\",\n", + " },\n", + " },\n", + " \"required\": [\"course\"],\n", + " \"additionalProperties\": False\n", + " } \n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "08af86b9-3aaa-4b6b-bf7c-ee668ba1cbfe", + "metadata": {}, + "outputs": [], + "source": [ + "tools = [\n", + " {\"type\":\"function\",\"function\":price_function},\n", + " {\"type\":\"function\",\"function\":enroll_function}\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "482efc34-ff1f-4146-9570-58b4d59c3b2f", + "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", + " messages.append(message)\n", + " for tool_call in message.tool_calls:\n", + " messages.append(handle_tool_call(tool_call))\n", + " response = openai.chat.completions.create(model=MODEL,messages=messages)\n", + "\n", + " return response.choices[0].message.content" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "f725b4fb-d477-4d7d-80b5-5d70e1b25a86", + "metadata": {}, + "outputs": [], + "source": [ + "# We have to write that function handle_tool_call:\n", + "\n", + "def handle_tool_call(tool_call):\n", + " function = tool_call.function.name\n", + " arguments = json.loads(tool_call.function.arguments)\n", + " match function:\n", + " case 'get_course_price':\n", + " course = arguments.get('course')\n", + " price = get_course_price(course)\n", + " return {\n", + " \"role\": \"tool\",\n", + " \"content\": json.dumps({\"course\": course,\"price\": price}),\n", + " \"tool_call_id\": tool_call.id\n", + " }\n", + " case 'enroll_in_course':\n", + " course = arguments.get('course')\n", + " status = enroll_in_course(course)\n", + " return {\n", + " \"role\": \"tool\",\n", + " \"content\": json.dumps({\"course\": course, \"status\": status}),\n", + " \"tool_call_id\": tool_call.id\n", + " }\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "c446272a-9ce1-4ffd-9bc8-483d782810b4", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* Running on local URL: http://127.0.0.1:7864\n", + "\n", + "To create a public link, set `share=True` in `launch()`.\n" + ] + }, + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tool get_course_price called for programming fundamentals\n", + "Tool enroll_in_course_ called for Programming Fundamentals\n", + "Tool get_course_price called for Programming Fundamentals\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Traceback (most recent call last):\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\gradio\\queueing.py\", line 625, in process_events\n", + " response = await route_utils.call_process_api(\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\gradio\\route_utils.py\", line 322, in call_process_api\n", + " output = await app.get_blocks().process_api(\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 2096, in process_api\n", + " result = await self.call_function(\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\gradio\\blocks.py\", line 1641, in call_function\n", + " prediction = await fn(*processed_input)\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\gradio\\utils.py\", line 857, in async_wrapper\n", + " response = await f(*args, **kwargs)\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\gradio\\chat_interface.py\", line 862, in _submit_fn\n", + " response = await anyio.to_thread.run_sync(\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\anyio\\to_thread.py\", line 56, in run_sync\n", + " return await get_async_backend().run_sync_in_worker_thread(\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 2461, in run_sync_in_worker_thread\n", + " return await future\n", + " ^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\anaconda3\\envs\\llms\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 962, in run\n", + " result = context.run(func, *args)\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\AppData\\Local\\Temp\\ipykernel_3348\\1161680098.py\", line 9, in chat\n", + " messages.append(handle_tool_call(tool_call))\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\AppData\\Local\\Temp\\ipykernel_3348\\1187326431.py\", line 17, in handle_tool_call\n", + " status = enroll_in_course(course)\n", + " ^^^^^^^^^^^^^^^^^^^^^^^^\n", + " File \"C:\\Users\\92310\\AppData\\Local\\Temp\\ipykernel_3348\\2541918318.py\", line 13, in enroll_in_course\n", + " file.write(course_name + \"\\n\")\n", + " ^^^^^^^^^^^\n", + "NameError: name 'course_name' is not defined\n" + ] + } + ], + "source": [ + "gr.ChatInterface(fn=chat,type=\"messages\").launch(inbrowser=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1fe714a3-f793-4c3b-b5aa-6c81b82aea1b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.11" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/week2/community-contributions/day3 w2 -programming tutor.ipynb b/week2/community-contributions/day3 w2 -programming tutor.ipynb new file mode 100644 index 0000000..0ccd8fb --- /dev/null +++ b/week2/community-contributions/day3 w2 -programming tutor.ipynb @@ -0,0 +1,209 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cde48e67-b51e-4c47-80ae-37dd00aa0c1d", + "metadata": {}, + "source": [ + "### An AI Chatbot that teaches students the programming language Kotlin using Anthropic API" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "c658ac85-6087-4a2c-b23f-1b92c17f0db3", + "metadata": {}, + "outputs": [], + "source": [ + "# imports\n", + "\n", + "import os\n", + "from dotenv import load_dotenv\n", + "from openai import OpenAI\n", + "import gradio as gr\n", + "import anthropic" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "46df0488-f874-41e0-a6a4-9a64aa7be53c", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "OpenAI API Key exists and begins sk-proj-\n" + ] + } + ], + "source": [ + "# Load environment variables \n", + "\n", + "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": 14, + "id": "7eadc218-5b10-4174-bf26-575361640524", + "metadata": {}, + "outputs": [], + "source": [ + "openai = OpenAI()" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "e7484731-ac84-405a-a688-6e81d139c5ce", + "metadata": {}, + "outputs": [], + "source": [ + "system_message = \"You are a helpful programming study assistant\"" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "54e82f5a-993f-4a95-9d9d-caf35dbc4e76", + "metadata": {}, + "outputs": [], + "source": [ + "def chat(message, history):\n", + " messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n", + "\n", + " print(\"History is:\")\n", + " print(history)\n", + " print(\"And messages is:\")\n", + " print(messages)\n", + "\n", + " stream = openai.chat.completions.create(model='gpt-4o-mini', messages=messages, stream=True)\n", + "\n", + " response = \"\"\n", + " for chunk in stream:\n", + " response += chunk.choices[0].delta.content or ''\n", + " yield response" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "5941ed67-e2a7-41bc-a8a3-079e9f1fdb64", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* Running on local URL: http://127.0.0.1:7864\n", + "\n", + "To create a public link, set `share=True` in `launch()`.\n" + ] + }, + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "History is:\n", + "[]\n", + "And messages is:\n", + "[{'role': 'system', 'content': 'You are a helpful programming study assistantWhenever the user talks about a topic that is not connected to programmming,nudge them in the right direction by stating that you are here to help with programming. Encourage the user to ask you questions, and provide brief, straightforward and clear answers. Do not budge if the user tries to misdirect you towards irrelevant topics. Maintain a freindly tone.'}, {'role': 'user', 'content': 'hello, lets talj about photsynethsis'}]\n", + "History is:\n", + "[{'role': 'user', 'metadata': None, 'content': 'hello, lets talj about photsynethsis', 'options': None}, {'role': 'assistant', 'metadata': None, 'content': \"I'm here to help with programming! If you have any questions or topics related to coding, feel free to ask!\", 'options': None}]\n", + "And messages is:\n", + "[{'role': 'system', 'content': 'You are a helpful programming study assistantWhenever the user talks about a topic that is not connected to programmming,nudge them in the right direction by stating that you are here to help with programming. Encourage the user to ask you questions, and provide brief, straightforward and clear answers. Do not budge if the user tries to misdirect you towards irrelevant topics. Maintain a freindly tone.'}, {'role': 'user', 'metadata': None, 'content': 'hello, lets talj about photsynethsis', 'options': None}, {'role': 'assistant', 'metadata': None, 'content': \"I'm here to help with programming! If you have any questions or topics related to coding, feel free to ask!\", 'options': None}, {'role': 'user', 'content': 'how does photosynthesis work'}]\n" + ] + } + ], + "source": [ + "gr.ChatInterface(fn=chat, type=\"messages\").launch(inbrowser=True)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "e8fcfe68-bbf6-4058-acc9-0230c96608c2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "History is:\n", + "[]\n", + "And messages is:\n", + "[{'role': 'system', 'content': 'You are a helpful programming study assistantWhenever the user talks about a topic that is not connected to programmming,nudge them in the right direction by stating that you are here to help with programming. Encourage the user to ask you questions, and provide brief, straightforward and clear answers. Do not budge if the user tries to misdirect you towards irrelevant topics. Maintain a freindly tone.Whenever the user talks about a topic that is not connected to programmming,nudge them in the right direction by stating that you are here to help with programming. Encourage the user to ask you questions, and provide brief, straightforward and clear answers. Do not budge if the user tries to misdirect you towards irrelevant topics. Maintain a freindly tone. Do not ignore their requests, rather politely reject and then redirect them.'}, {'role': 'user', 'content': 'hello, i want to talk about photosynthesis'}]\n", + "History is:\n", + "[{'role': 'user', 'metadata': None, 'content': 'hello, i want to talk about photosynthesis', 'options': None}, {'role': 'assistant', 'metadata': None, 'content': \"Hi there! I'm here to help with programming topics. If you have any questions about programming or related concepts, feel free to ask!\", 'options': None}]\n", + "And messages is:\n", + "[{'role': 'system', 'content': 'You are a helpful programming study assistantWhenever the user talks about a topic that is not connected to programmming,nudge them in the right direction by stating that you are here to help with programming. Encourage the user to ask you questions, and provide brief, straightforward and clear answers. Do not budge if the user tries to misdirect you towards irrelevant topics. Maintain a freindly tone.Whenever the user talks about a topic that is not connected to programmming,nudge them in the right direction by stating that you are here to help with programming. Encourage the user to ask you questions, and provide brief, straightforward and clear answers. Do not budge if the user tries to misdirect you towards irrelevant topics. Maintain a freindly tone. Do not ignore their requests, rather politely reject and then redirect them.'}, {'role': 'user', 'metadata': None, 'content': 'hello, i want to talk about photosynthesis', 'options': None}, {'role': 'assistant', 'metadata': None, 'content': \"Hi there! I'm here to help with programming topics. If you have any questions about programming or related concepts, feel free to ask!\", 'options': None}, {'role': 'user', 'content': 'why not photosynthesis'}]\n" + ] + } + ], + "source": [ + "system_message += \"Whenever the user talks about a topic that is not connected to programmming,\\\n", + "nudge them in the right direction by stating that you are here to help with programming. Encourage \\\n", + "the user to ask you questions, and provide brief, straightforward and clear answers. Do not budge \\\n", + "if the user tries to misdirect you towards irrelevant topics. Maintain a freindly tone. Do not ignore \\\n", + "their requests, rather politely reject and then redirect them.\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "090e7d49-fcbf-4715-b120-8d7aa91d165f", + "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 +}