Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (25)
- 1_lab1.ipynbAdded+326
- 2_lab2.ipynbAdded+474
- 3_lab3.ipynbAdded+351
- 4_lab4.ipynbAdded+445
- README.md+3-9
- app.pyAdded+134
- community_contributions/1_lab1_Mudassar.ipynbAdded+260
- community_contributions/1_lab1_gemini.ipynbAdded+305
- community_contributions/1_lab1_groq_llama.ipynbAdded+296
- community_contributions/1_lab1_openai.ipynbAdded+505
- community_contributions/2_lab2_exercise.ipynbAdded+336
- community_contributions/Business_Idea.ipynbAdded+388
- community_contributions/Multi-Model-Resume–JD-Match-Analyzer/.gitignoreAdded+1
- community_contributions/Multi-Model-Resume–JD-Match-Analyzer/AnalyzeResume.pngAdded
- community_contributions/Multi-Model-Resume–JD-Match-Analyzer/README.mdAdded+48
- community_contributions/Multi-Model-Resume–JD-Match-Analyzer/multi_file_ingestion.pyAdded+44
- community_contributions/Multi-Model-Resume–JD-Match-Analyzer/resume_agent.pyAdded+262
- community_contributions/app_rate_limiter_mailgun_integration.pyAdded+231
- community_contributions/community.ipynbAdded+29
- community_contributions/llm-evaluator.ipynbAdded+385
- community_contributions/my_1_lab1.ipynbAdded+405
- community_contributions/travel_planner_multicall_and_sythesizer.ipynbAdded+287
- me/linkedin.pdfAdded
- me/summary.txtAdded+2
- requirements.txtAdded+6
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Welcome to the start of your adventure in Agentic AI" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/stop.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Are you ready for action??</h2>\n", " <span style=\"color:#ff7800;\">Have you completed all the setup steps in the <a href=\"../setup/\">setup</a> folder?<br/>\n", " Have you checked out the guides in the <a href=\"../guides/01_intro.ipynb\">guides</a> folder?<br/>\n", " Well in that case, you're ready!!\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/tools.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#00bfff;\">This code is a live resource - keep an eye out for my updates</h2>\n", " <span style=\"color:#00bfff;\">I push updates regularly. As people ask questions or have problems, I add more examples and improve explanations. As a result, the code below might not be identical to the videos, as I've added more steps and better comments. Consider this like an interactive book that accompanies the lectures.<br/><br/>\n", " I try to send emails regularly with important updates related to the course. You can find this in the 'Announcements' section of Udemy in the left sidebar. You can also choose to receive my emails via your Notification Settings in Udemy. I'm respectful of your inbox and always try to add value with my emails!\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### And please do remember to contact me if I can help\n", "\n", "And I love to connect: https://www.linkedin.com/in/eddonner/\n", "\n", "\n", "### New to Notebooks like this one? Head over to the guides folder!\n", "\n", "Just to check you've already added the Python and Jupyter extensions to Cursor, if not already installed:\n", "- Open extensions (View >> extensions)\n", "- Search for python, and when the results show, click on the ms-python one, and Install it if not already installed\n", "- Search for jupyter, and when the results show, click on the Microsoft one, and Install it if not already installed \n", "Then View >> Explorer to bring back the File Explorer.\n", "\n", "And then:\n", "1. Click where it says \"Select Kernel\" near the top right, and select the option called `.venv (Python 3.12.9)` or similar, which should be the first choice or the most prominent choice. You may need to choose \"Python Environments\" first.\n", "2. Click in each \"cell\" below, starting with the cell immediately below this text, and press Shift+Enter to run\n", "3. Enjoy!\n", "\n", "After you click \"Select Kernel\", if there is no option like `.venv (Python 3.12.9)` then please do the following: \n", "1. On Mac: From the Cursor menu, choose Settings >> VS Code Settings (NOTE: be sure to select `VSCode Settings` not `Cursor Settings`); \n", "On Windows PC: From the File menu, choose Preferences >> VS Code Settings(NOTE: be sure to select `VSCode Settings` not `Cursor Settings`) \n", "2. In the Settings search bar, type \"venv\" \n", "3. In the field \"Path to folder with a list of Virtual Environments\" put the path to the project root, like C:\\Users\\username\\projects\\agents (on a Windows PC) or /Users/username/projects/agents (on Mac or Linux). \n", "And then try again.\n", "\n", "Having problems with missing Python versions in that list? Have you ever used Anaconda before? It might be interferring. Quit Cursor, bring up a new command line, and make sure that your Anaconda environment is deactivated: \n", "`conda deactivate` \n", "And if you still have any problems with conda and python versions, it's possible that you will need to run this too: \n", "`conda config --set auto_activate_base false` \n", "and then from within the Agents directory, you should be able to run `uv python list` and see the Python 3.12 version." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# First let's do an import\n", "from dotenv import load_dotenv\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Next it's time to load the API keys into environment variables\n", "\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check the keys\n", "\n", "import os\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 - please head to the troubleshooting guide in the setup folder\")\n", " \n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# And now - the all important import statement\n", "# If you get an import error - head over to troubleshooting guide\n", "\n", "from openai import OpenAI" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# And now we'll create an instance of the OpenAI class\n", "# If you're not sure what it means to create an instance of a class - head over to the guides folder!\n", "# If you get a NameError - head over to the guides folder to learn about NameErrors\n", "\n", "openai = OpenAI()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# Create a list of messages in the familiar OpenAI format\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"What is 2+2?\"}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# And now call it! Any problems, head to the troubleshooting guide\n", "# This uses GPT 4.1 nano, the incredibly cheap model\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4.1-nano\",\n", " messages=messages\n", ")\n", "\n", "print(response.choices[0].message.content)\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "# And now - let's ask for a question:\n", "\n", "question = \"Please propose a hard, challenging question to assess someone's IQ. Respond only with the question.\"\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ask it - this uses GPT 4.1 mini, still cheap but more powerful than nano\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4.1-mini\",\n", " messages=messages\n", ")\n", "\n", "question = response.choices[0].message.content\n", "\n", "print(question)\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "# form a new messages list\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ask it again\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4.1-mini\",\n", " messages=messages\n", ")\n", "\n", "answer = response.choices[0].message.content\n", "print(answer)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import Markdown, display\n", "\n", "display(Markdown(answer))\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Congratulations!\n", "\n", "That was a small, simple step in the direction of Agentic AI, with your new environment!\n", "\n", "Next time things get more interesting..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Exercise</h2>\n", " <span style=\"color:#ff7800;\">Now try this commercial application:<br/>\n", " First ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.<br/>\n", " Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.<br/>\n", " Finally have 3 third LLM call propose the Agentic AI solution.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First create the messages:\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"Something here\"}]\n", "\n", "# Then make the first call:\n", "\n", "response =\n", "\n", "# Then read the business idea:\n", "\n", "business_idea = response.\n", "\n", "# And repeat!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Welcome to the Second Lab - Week 1, Day 3\n", "\n", "Today we will work with lots of models! This is a way to get comfortable with APIs." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/stop.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Important point - please read</h2>\n", " <span style=\"color:#ff7800;\">The way I collaborate with you may be different to other courses you've taken. I prefer not to type code while you watch. Rather, I execute Jupyter Labs, like this, and give you an intuition for what's going on. My suggestion is that you carefully execute this yourself, <b>after</b> watching the lecture. Add print statements to understand what's going on, and then come up with your own variations.<br/><br/>If you have time, I'd love it if you submit a PR for changes in the community_contributions folder - instructions in the resources. Also, if you have a Github account, use this to showcase your variations. Not only is this essential practice, but it demonstrates your skills to others, including perhaps future clients or employers...\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Start with imports - ask ChatGPT to explain any package that you don't know\n", "\n", "import os\n", "import json\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "from anthropic import Anthropic\n", "from IPython.display import Markdown, display" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Always remember to do this!\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the key prefixes to help with any debugging\n", "\n", "openai_api_key = os.getenv('OPENAI_API_KEY')\n", "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n", "google_api_key = os.getenv('GOOGLE_API_KEY')\n", "deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n", "groq_api_key = os.getenv('GROQ_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 (and this is optional)\")\n", "\n", "if google_api_key:\n", " print(f\"Google API Key exists and begins {google_api_key[:2]}\")\n", "else:\n", " print(\"Google API Key not set (and this is optional)\")\n", "\n", "if deepseek_api_key:\n", " print(f\"DeepSeek API Key exists and begins {deepseek_api_key[:3]}\")\n", "else:\n", " print(\"DeepSeek API Key not set (and this is optional)\")\n", "\n", "if groq_api_key:\n", " print(f\"Groq API Key exists and begins {groq_api_key[:4]}\")\n", "else:\n", " print(\"Groq API Key not set (and this is optional)\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "request = \"Please come up with a challenging, nuanced question that I can ask a number of LLMs to evaluate their intelligence. \"\n", "request += \"Answer only with the question, no explanation.\"\n", "messages = [{\"role\": \"user\", \"content\": request}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "messages" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "openai = OpenAI()\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages,\n", ")\n", "question = response.choices[0].message.content\n", "print(question)\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "competitors = []\n", "answers = []\n", "messages = [{\"role\": \"user\", \"content\": question}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The API we know well\n", "\n", "model_name = \"gpt-4o-mini\"\n", "\n", "response = openai.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Anthropic has a slightly different API, and Max Tokens is required\n", "\n", "model_name = \"claude-3-7-sonnet-latest\"\n", "\n", "claude = Anthropic()\n", "response = claude.messages.create(model=model_name, messages=messages, max_tokens=1000)\n", "answer = response.content[0].text\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gemini = OpenAI(api_key=google_api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n", "model_name = \"gemini-2.0-flash\"\n", "\n", "response = gemini.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "deepseek = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com/v1\")\n", "model_name = \"deepseek-chat\"\n", "\n", "response = deepseek.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "groq = OpenAI(api_key=groq_api_key, base_url=\"https://api.groq.com/openai/v1\")\n", "model_name = \"llama-3.3-70b-versatile\"\n", "\n", "response = groq.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For the next cell, we will use Ollama\n", "\n", "Ollama runs a local web service that gives an OpenAI compatible endpoint, \n", "and runs models locally using high performance C++ code.\n", "\n", "If you don't have Ollama, install it here by visiting https://ollama.com then pressing Download and following the instructions.\n", "\n", "After it's installed, you should be able to visit here: http://localhost:11434 and see the message \"Ollama is running\"\n", "\n", "You might need to restart Cursor (and maybe reboot). Then open a Terminal (control+\\`) and run `ollama serve`\n", "\n", "Useful Ollama commands (run these in the terminal, or with an exclamation mark in this notebook):\n", "\n", "`ollama pull <model_name>` downloads a model locally \n", "`ollama ls` lists all the models you've downloaded \n", "`ollama rm <model_name>` deletes the specified model from your downloads" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/stop.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Super important - ignore me at your peril!</h2>\n", " <span style=\"color:#ff7800;\">The model called <b>llama3.3</b> is FAR too large for home computers - it's not intended for personal computing and will consume all your resources! Stick with the nicely sized <b>llama3.2</b> or <b>llama3.2:1b</b> and if you want larger, try llama3.1 or smaller variants of Qwen, Gemma, Phi or DeepSeek. See the <A href=\"https://ollama.com/models\">the Ollama models page</a> for a full list of models and sizes.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!ollama pull llama3.2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ollama = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n", "model_name = \"llama3.2\"\n", "\n", "response = ollama.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# So where are we?\n", "\n", "print(competitors)\n", "print(answers)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# It's nice to know how to use \"zip\"\n", "for competitor, answer in zip(competitors, answers):\n", " print(f\"Competitor: {competitor}\\n\\n{answer}\")\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "# Let's bring this together - note the use of \"enumerate\"\n", "\n", "together = \"\"\n", "for index, answer in enumerate(answers):\n", " together += f\"# Response from competitor {index+1}\\n\\n\"\n", " together += answer + \"\\n\\n\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(together)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "judge = f\"\"\"You are judging a competition between {len(competitors)} competitors.\n", "Each model has been given this question:\n", "\n", "{question}\n", "\n", "Your job is to evaluate each response for clarity and strength of argument, and rank them in order of best to worst.\n", "Respond with JSON, and only JSON, with the following format:\n", "{{\"results\": [\"best competitor number\", \"second best competitor number\", \"third best competitor number\", ...]}}\n", "\n", "Here are the responses from each competitor:\n", "\n", "{together}\n", "\n", "Now respond with the JSON with the ranked order of the competitors, nothing else. Do not include markdown formatting or code blocks.\"\"\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(judge)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "judge_messages = [{\"role\": \"user\", \"content\": judge}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Judgement time!\n", "\n", "openai = OpenAI()\n", "response = openai.chat.completions.create(\n", " model=\"o3-mini\",\n", " messages=judge_messages,\n", ")\n", "results = response.choices[0].message.content\n", "print(results)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# OK let's turn this into results!\n", "\n", "results_dict = json.loads(results)\n", "ranks = results_dict[\"results\"]\n", "for index, result in enumerate(ranks):\n", " competitor = competitors[int(result)-1]\n", " print(f\"Rank {index+1}: {competitor}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Exercise</h2>\n", " <span style=\"color:#ff7800;\">Which pattern(s) did this use? Try updating this to add another Agentic design pattern.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/business.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#00bfff;\">Commercial implications</h2>\n", " <span style=\"color:#00bfff;\">These kinds of patterns - to send a task to multiple models, and evaluate results,\n", " and common where you need to improve the quality of your LLM response. This approach can be universally applied\n", " to business projects where accuracy is critical.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Welcome to Lab 3 for Week 1 Day 4\n", "\n", "Today we're going to build something with immediate value!\n", "\n", "In the folder `me` I've put a single file `linkedin.pdf` - it's a PDF download of my LinkedIn profile.\n", "\n", "Please replace it with yours!\n", "\n", "I've also made a file called `summary.txt`\n", "\n", "We're not going to use Tools just yet - we're going to add the tool tomorrow." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/tools.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#00bfff;\">Looking up packages</h2>\n", " <span style=\"color:#00bfff;\">In this lab, we're going to use the wonderful Gradio package for building quick UIs, \n", " and we're also going to use the popular PyPDF2 PDF reader. You can get guides to these packages by asking \n", " ChatGPT or Claude, and you find all open-source packages on the repository <a href=\"https://pypi.org\">https://pypi.org</a>.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# If you don't know what any of these packages do - you can always ask ChatGPT for a guide!\n", "\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "from pypdf import PdfReader\n", "import gradio as gr" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "load_dotenv(override=True)\n", "openai = OpenAI()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "reader = PdfReader(\"me/linkedin.pdf\")\n", "linkedin = \"\"\n", "for page in reader.pages:\n", " text = page.extract_text()\n", " if text:\n", " linkedin += text" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(linkedin)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "with open(\"me/summary.txt\", \"r\", encoding=\"utf-8\") as f:\n", " summary = f.read()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "name = \"Ed Donner\"" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "system_prompt = f\"You are acting as {name}. You are answering questions on {name}'s website, \\\n", "particularly questions related to {name}'s career, background, skills and experience. \\\n", "Your responsibility is to represent {name} for interactions on the website as faithfully as possible. \\\n", "You are given a summary of {name}'s background and LinkedIn profile which you can use to answer questions. \\\n", "Be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n", "If you don't know the answer, say so.\"\n", "\n", "system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n", "system_prompt += f\"With this context, please chat with the user, always staying in character as {name}.\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "system_prompt" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "def chat(message, history):\n", " messages = [{\"role\": \"system\", \"content\": system_prompt}] + history + [{\"role\": \"user\", \"content\": message}]\n", " response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", " return response.choices[0].message.content" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gr.ChatInterface(chat, type=\"messages\").launch()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A lot is about to happen...\n", "\n", "1. Be able to ask an LLM to evaluate an answer\n", "2. Be able to rerun if the answer fails evaluation\n", "3. Put this together into 1 workflow\n", "\n", "All without any Agentic framework!" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# Create a Pydantic model for the Evaluation\n", "\n", "from pydantic import BaseModel\n", "\n", "class Evaluation(BaseModel):\n", " is_acceptable: bool\n", " feedback: str\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "evaluator_system_prompt = f\"You are an evaluator that decides whether a response to a question is acceptable. \\\n", "You are provided with a conversation between a User and an Agent. Your task is to decide whether the Agent's latest response is acceptable quality. \\\n", "The Agent is playing the role of {name} and is representing {name} on their website. \\\n", "The Agent has been instructed to be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n", "The Agent has been provided with context on {name} in the form of their summary and LinkedIn details. Here's the information:\"\n", "\n", "evaluator_system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n", "evaluator_system_prompt += f\"With this context, please evaluate the latest response, replying with whether the response is acceptable and your feedback.\"" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "def evaluator_user_prompt(reply, message, history):\n", " user_prompt = f\"Here's the conversation between the User and the Agent: \\n\\n{history}\\n\\n\"\n", " user_prompt += f\"Here's the latest message from the User: \\n\\n{message}\\n\\n\"\n", " user_prompt += f\"Here's the latest response from the Agent: \\n\\n{reply}\\n\\n\"\n", " user_prompt += f\"Please evaluate the response, replying with whether it is acceptable and your feedback.\"\n", " return user_prompt" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "import os\n", "gemini = OpenAI(\n", " api_key=os.getenv(\"GOOGLE_API_KEY\"), \n", " base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\"\n", ")" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "def evaluate(reply, message, history) -> Evaluation:\n", "\n", " messages = [{\"role\": \"system\", \"content\": evaluator_system_prompt}] + [{\"role\": \"user\", \"content\": evaluator_user_prompt(reply, message, history)}]\n", " response = gemini.beta.chat.completions.parse(model=\"gemini-2.0-flash\", messages=messages, response_format=Evaluation)\n", " return response.choices[0].message.parsed" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "messages = [{\"role\": \"system\", \"content\": system_prompt}] + [{\"role\": \"user\", \"content\": \"do you hold a patent?\"}]\n", "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", "reply = response.choices[0].message.content" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "reply" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "evaluate(reply, \"do you hold a patent?\", messages[:1])" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "def rerun(reply, message, history, feedback):\n", " updated_system_prompt = system_prompt + f\"\\n\\n## Previous answer rejected\\nYou just tried to reply, but the quality control rejected your reply\\n\"\n", " updated_system_prompt += f\"## Your attempted answer:\\n{reply}\\n\\n\"\n", " updated_system_prompt += f\"## Reason for rejection:\\n{feedback}\\n\\n\"\n", " messages = [{\"role\": \"system\", \"content\": updated_system_prompt}] + history + [{\"role\": \"user\", \"content\": message}]\n", " response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", " return response.choices[0].message.content" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "def chat(message, history):\n", " if \"patent\" in message:\n", " system = system_prompt + \"\\n\\nEverything in your reply needs to be in pig latin - \\\n", " it is mandatory that you respond only and entirely in pig latin\"\n", " else:\n", " system = system_prompt\n", " messages = [{\"role\": \"system\", \"content\": system}] + history + [{\"role\": \"user\", \"content\": message}]\n", " response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", " reply =response.choices[0].message.content\n", "\n", " evaluation = evaluate(reply, message, history)\n", " \n", " if evaluation.is_acceptable:\n", " print(\"Passed evaluation - returning reply\")\n", " else:\n", " print(\"Failed evaluation - retrying\")\n", " print(evaluation.feedback)\n", " reply = rerun(reply, message, history, evaluation.feedback) \n", " return reply" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gr.ChatInterface(chat, type=\"messages\").launch()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## The first big project - Professionally You!\n", "\n", "### And, Tool use.\n", "\n", "### But first: introducing Pushover\n", "\n", "Pushover is a nifty tool for sending Push Notifications to your phone.\n", "\n", "It's super easy to set up and install!\n", "\n", "Simply visit https://pushover.net/ and sign up for a free account, and create your API keys.\n", "\n", "As student Ron pointed out (thank you Ron!) there are actually 2 tokens to create in Pushover: \n", "1. The User token which you get from the home page of Pushover\n", "2. The Application token which you get by going to https://pushover.net/apps/build and creating an app \n", "\n", "(This is so you could choose to organize your push notifications into different apps in the future.)\n", "\n", "\n", "Add to your `.env` file:\n", "```\n", "PUSHOVER_USER=put_your_user_token_here\n", "PUSHOVER_TOKEN=put_the_application_level_token_here\n", "```\n", "\n", "And install the Pushover app on your phone." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# imports\n", "\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "import json\n", "import os\n", "import requests\n", "from pypdf import PdfReader\n", "import gradio as gr" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# The usual start\n", "\n", "load_dotenv(override=True)\n", "openai = OpenAI()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# For pushover\n", "\n", "pushover_user = os.getenv(\"PUSHOVER_USER\")\n", "pushover_token = os.getenv(\"PUSHOVER_TOKEN\")\n", "pushover_url = \"https://api.pushover.net/1/messages.json\"" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def push(message):\n", " print(f\"Push: {message}\")\n", " payload = {\"user\": pushover_user, \"token\": pushover_token, \"message\": message}\n", " requests.post(pushover_url, data=payload)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "push(\"HEY!!\")" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "def record_user_details(email, name=\"Name not provided\", notes=\"not provided\"):\n", " push(f\"Recording interest from {name} with email {email} and notes {notes}\")\n", " return {\"recorded\": \"ok\"}" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def record_unknown_question(question):\n", " push(f\"Recording {question} asked that I couldn't answer\")\n", " return {\"recorded\": \"ok\"}" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "record_user_details_json = {\n", " \"name\": \"record_user_details\",\n", " \"description\": \"Use this tool to record that a user is interested in being in touch and provided an email address\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"email\": {\n", " \"type\": \"string\",\n", " \"description\": \"The email address of this user\"\n", " },\n", " \"name\": {\n", " \"type\": \"string\",\n", " \"description\": \"The user's name, if they provided it\"\n", " }\n", " ,\n", " \"notes\": {\n", " \"type\": \"string\",\n", " \"description\": \"Any additional information about the conversation that's worth recording to give context\"\n", " }\n", " },\n", " \"required\": [\"email\"],\n", " \"additionalProperties\": False\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "record_unknown_question_json = {\n", " \"name\": \"record_unknown_question\",\n", " \"description\": \"Always use this tool to record any question that couldn't be answered as you didn't know the answer\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"question\": {\n", " \"type\": \"string\",\n", " \"description\": \"The question that couldn't be answered\"\n", " },\n", " },\n", " \"required\": [\"question\"],\n", " \"additionalProperties\": False\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "tools = [{\"type\": \"function\", \"function\": record_user_details_json},\n", " {\"type\": \"function\", \"function\": record_unknown_question_json}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tools" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "# This function can take a list of tool calls, and run them. This is the IF statement!!\n", "\n", "def handle_tool_calls(tool_calls):\n", " results = []\n", " for tool_call in tool_calls:\n", " tool_name = tool_call.function.name\n", " arguments = json.loads(tool_call.function.arguments)\n", " print(f\"Tool called: {tool_name}\", flush=True)\n", "\n", " # THE BIG IF STATEMENT!!!\n", "\n", " if tool_name == \"record_user_details\":\n", " result = record_user_details(**arguments)\n", " elif tool_name == \"record_unknown_question\":\n", " result = record_unknown_question(**arguments)\n", "\n", " results.append({\"role\": \"tool\",\"content\": json.dumps(result),\"tool_call_id\": tool_call.id})\n", " return results" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "globals()[\"record_unknown_question\"](\"this is a really hard question\")" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "# This is a more elegant way that avoids the IF statement.\n", "\n", "def handle_tool_calls(tool_calls):\n", " results = []\n", " for tool_call in tool_calls:\n", " tool_name = tool_call.function.name\n", " arguments = json.loads(tool_call.function.arguments)\n", " print(f\"Tool called: {tool_name}\", flush=True)\n", " tool = globals().get(tool_name)\n", " result = tool(**arguments) if tool else {}\n", " results.append({\"role\": \"tool\",\"content\": json.dumps(result),\"tool_call_id\": tool_call.id})\n", " return results" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "reader = PdfReader(\"me/linkedin.pdf\")\n", "linkedin = \"\"\n", "for page in reader.pages:\n", " text = page.extract_text()\n", " if text:\n", " linkedin += text\n", "\n", "with open(\"me/summary.txt\", \"r\", encoding=\"utf-8\") as f:\n", " summary = f.read()\n", "\n", "name = \"Ed Donner\"" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "system_prompt = f\"You are acting as {name}. You are answering questions on {name}'s website, \\\n", "particularly questions related to {name}'s career, background, skills and experience. \\\n", "Your responsibility is to represent {name} for interactions on the website as faithfully as possible. \\\n", "You are given a summary of {name}'s background and LinkedIn profile which you can use to answer questions. \\\n", "Be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n", "If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \\\n", "If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. \"\n", "\n", "system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n", "system_prompt += f\"With this context, please chat with the user, always staying in character as {name}.\"\n" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "def chat(message, history):\n", " messages = [{\"role\": \"system\", \"content\": system_prompt}] + history + [{\"role\": \"user\", \"content\": message}]\n", " done = False\n", " while not done:\n", "\n", " # This is the call to the LLM - see that we pass in the tools json\n", "\n", " response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages, tools=tools)\n", "\n", " finish_reason = response.choices[0].finish_reason\n", " \n", " # If the LLM wants to call a tool, we do that!\n", " \n", " if finish_reason==\"tool_calls\":\n", " message = response.choices[0].message\n", " tool_calls = message.tool_calls\n", " results = handle_tool_calls(tool_calls)\n", " messages.append(message)\n", " messages.extend(results)\n", " else:\n", " done = True\n", " return response.choices[0].message.content" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gr.ChatInterface(chat, type=\"messages\").launch()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## And now for deployment\n", "\n", "This code is in `app.py`\n", "\n", "We will deploy to HuggingFace Spaces. Thank you student Robert M for improving these instructions.\n", "\n", "Before you start: remember to update the files in the \"me\" directory - your LinkedIn profile and summary.txt - so that it talks about you! \n", "Also check that there's no README file within the 1_foundations directory. If there is one, please delete it. The deploy process creates a new README file in this directory for you.\n", "\n", "1. Visit https://huggingface.co and set up an account \n", "2. From the Avatar menu on the top right, choose Access Tokens. Choose \"Create New Token\". Give it WRITE permissions.\n", "3. Take this token and add it to your .env file: `HF_TOKEN=hf_xxx` and see note below if this token doesn't seem to get picked up during deployment \n", "4. From the 1_foundations folder, enter: `uv run gradio deploy` and if for some reason this still wants you to enter your HF token, then interrupt it with ctrl+c and run this instead: `uv run dotenv -f ../.env run -- uv run gradio deploy` which forces your keys to all be set as environment variables \n", "5. Follow its instructions: name it \"career_conversation\", specify app.py, choose cpu-basic as the hardware, say Yes to needing to supply secrets, provide your openai api key, your pushover user and token, and say \"no\" to github actions. \n", "\n", "#### Extra note about the HuggingFace token\n", "\n", "A couple of students have mentioned the HuggingFace doesn't detect their token, even though it's in the .env file. Here are things to try: \n", "1. Restart Cursor \n", "2. Rerun load_dotenv(override=True) and use a new terminal (the + button on the top right of the Terminal) \n", "3. In the Terminal, run this before the gradio deploy: `$env:HF_TOKEN = \"hf_XXXX\"` \n", "Thank you James and Martins for these tips. \n", "\n", "#### More about these secrets:\n", "\n", "If you're confused by what's going on with these secrets: it just wants you to enter the key name and value for each of your secrets -- so you would enter: \n", "`OPENAI_API_KEY` \n", "Followed by: \n", "`sk-proj-...` \n", "\n", "And if you don't want to set secrets this way, or something goes wrong with it, it's no problem - you can change your secrets later: \n", "1. Log in to HuggingFace website \n", "2. Go to your profile screen via the Avatar menu on the top right \n", "3. Select the Space you deployed \n", "4. Click on the Settings wheel on the top right \n", "5. You can scroll down to change your secrets, delete the space, etc.\n", "\n", "#### And now you should be deployed!\n", "\n", "Here is mine: https://huggingface.co/spaces/ed-donner/Career_Conversation\n", "\n", "I just got a push notification that a student asked me how they can become President of their country 😂😂\n", "\n", "For more information on deployment:\n", "\n", "https://www.gradio.app/guides/sharing-your-app#hosting-on-hf-spaces\n", "\n", "To delete your Space in the future: \n", "1. Log in to HuggingFace\n", "2. From the Avatar menu, select your profile\n", "3. Click on the Space itself\n", "4. Click the settings wheel on the top right\n", "5. Scroll to the Delete section at the bottom\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Exercise</h2>\n", " <span style=\"color:#ff7800;\">• First and foremost, deploy this for yourself! It's a real, valuable tool - the future resume..<br/>\n", " • Next, improve the resources - add better context about yourself. If you know RAG, then add a knowledge base about you.<br/>\n", " • Add in more tools! You could have a SQL database with common Q&A that the LLM could read and write from?<br/>\n", " • Bring in the Evaluator from the last lab, and add other Agentic patterns.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/business.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#00bfff;\">Commercial implications</h2>\n", " <span style=\"color:#00bfff;\">Aside from the obvious (your career alter-ego) this has business applications in any situation where you need an AI assistant with domain expertise and an ability to interact with the real world.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112---title: Career Conversationemoji: 👁colorFrom: indigocolorTo: pinksdk: gradiosdk_version: 5.30.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456---title: Career_Conversationapp_file: app.pysdk: gradiosdk_version: 5.29.0---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134from dotenv import load_dotenvfrom openai import OpenAIimport jsonimport osimport requestsfrom pypdf import PdfReaderimport gradio as gr
load_dotenv(override=True)
def push(text): requests.post( "https://api.pushover.net/1/messages.json", data={ "token": os.getenv("PUSHOVER_TOKEN"), "user": os.getenv("PUSHOVER_USER"), "message": text, } )
def record_user_details(email, name="Name not provided", notes="not provided"): push(f"Recording {name} with email {email} and notes {notes}") return {"recorded": "ok"}
def record_unknown_question(question): push(f"Recording {question}") return {"recorded": "ok"}
record_user_details_json = { "name": "record_user_details", "description": "Use this tool to record that a user is interested in being in touch and provided an email address", "parameters": { "type": "object", "properties": { "email": { "type": "string", "description": "The email address of this user" }, "name": { "type": "string", "description": "The user's name, if they provided it" } , "notes": { "type": "string", "description": "Any additional information about the conversation that's worth recording to give context" } }, "required": ["email"], "additionalProperties": False }}
record_unknown_question_json = { "name": "record_unknown_question", "description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer", "parameters": { "type": "object", "properties": { "question": { "type": "string", "description": "The question that couldn't be answered" }, }, "required": ["question"], "additionalProperties": False }}
tools = [{"type": "function", "function": record_user_details_json}, {"type": "function", "function": record_unknown_question_json}]
class Me:
def __init__(self): self.openai = OpenAI() self.name = "Ed Donner" reader = PdfReader("me/linkedin.pdf") self.linkedin = "" for page in reader.pages: text = page.extract_text() if text: self.linkedin += text with open("me/summary.txt", "r", encoding="utf-8") as f: self.summary = f.read()
def handle_tool_call(self, tool_calls): results = [] for tool_call in tool_calls: tool_name = tool_call.function.name arguments = json.loads(tool_call.function.arguments) print(f"Tool called: {tool_name}", flush=True) tool = globals().get(tool_name) result = tool(**arguments) if tool else {} results.append({"role": "tool","content": json.dumps(result),"tool_call_id": tool_call.id}) return results def system_prompt(self): system_prompt = f"You are acting as {self.name}. You are answering questions on {self.name}'s website, \particularly questions related to {self.name}'s career, background, skills and experience. \Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. \Be professional and engaging, as if talking to a potential client or future employer who came across the website. \If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. "
system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.linkedin}\n\n" system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}." return system_prompt def chat(self, message, history): messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}] done = False while not done: response = self.openai.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools) if response.choices[0].finish_reason=="tool_calls": message = response.choices[0].message tool_calls = message.tool_calls results = self.handle_tool_call(tool_calls) messages.append(message) messages.extend(results) else: done = True return response.choices[0].message.content
if __name__ == "__main__": me = Me() gr.ChatInterface(me.chat, type="messages").launch() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# First Agentic AI workflow with OPENAI" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### And please do remember to contact me if I can help\n", "\n", "And I love to connect: https://www.linkedin.com/in/muhammad-mudassar-a65645192/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Import Libraries" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "import os\n", "import re\n", "from openai import OpenAI\n", "from dotenv import load_dotenv\n", "from IPython.display import Markdown, display" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "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 - please head to the troubleshooting guide in the gui\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Workflow with OPENAI" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "openai=OpenAI()" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "message = [{'role':'user','content':\"what is 2+3?\"}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "response = openai.chat.completions.create(model=\"gpt-4o-mini\",messages=message)\n", "print(response.choices[0].message.content)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "question = \"Please propose a hard, challenging question to assess someone's IQ. Respond only with the question.\"\n", "message=[{'role':'user','content':question}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "response=openai.chat.completions.create(model=\"gpt-4o-mini\",messages=message)\n", "question=response.choices[0].message.content\n", "print(f\"Answer: {question}\")" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "message=[{'role':'user','content':question}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "response=openai.chat.completions.create(model=\"gpt-4o-mini\",messages=message)\n", "answer = response.choices[0].message.content\n", "print(f\"Answer: {answer}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# convert \\[ ... \\] to $$ ... $$, to properly render Latex\n", "converted_answer = re.sub(r'\\\\[\\[\\]]', '$$', answer)\n", "display(Markdown(converted_answer))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <span style=\"color:#ff7800;\">Now try this commercial application:<br/>\n", " First ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.<br/>\n", " Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.<br/>\n", " Finally have 3 third LLM call propose the Agentic AI solution.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "message = [{'role':'user','content':\"give me a business area related to ecommerce that might be worth exploring for a agentic opportunity.\"}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "response = openai.chat.completions.create(model=\"gpt-4o-mini\",messages=message)\n", "business_area = response.choices[0].message.content\n", "business_area" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message = business_area + \"present a pain-point in that industry - something challenging that might be ripe for an agentic solutions.\"\n", "message" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message = [{'role': 'user', 'content': message}]\n", "response = openai.chat.completions.create(model=\"gpt-4o-mini\",messages=message)\n", "question=response.choices[0].message.content\n", "question" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message=[{'role':'user','content':question}]\n", "response=openai.chat.completions.create(model=\"gpt-4o-mini\",messages=message)\n", "answer=response.choices[0].message.content\n", "print(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "display(Markdown(answer))" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.5" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Welcome to the start of your adventure in Agentic AI" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/stop.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Are you ready for action??</h2>\n", " <span style=\"color:#ff7800;\">Have you completed all the setup steps in the <a href=\"../setup/\">setup</a> folder?<br/>\n", " Have you checked out the guides in the <a href=\"../guides/01_intro.ipynb\">guides</a> folder?<br/>\n", " Well in that case, you're ready!!\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/tools.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#00bfff;\">Treat these labs as a resource</h2>\n", " <span style=\"color:#00bfff;\">I push updates to the code regularly. When people ask questions or have problems, I incorporate it in the code, adding more examples or improved commentary. As a result, you'll notice that the code below isn't identical to the videos. Everything from the videos is here; but in addition, I've added more steps and better explanations. Consider this like an interactive book that accompanies the lectures.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### And please do remember to contact me if I can help\n", "\n", "And I love to connect: https://www.linkedin.com/in/eddonner/\n", "\n", "\n", "### New to Notebooks like this one? Head over to the guides folder!\n", "\n", "Just to check you've already added the Python and Jupyter extensions to Cursor, if not already installed:\n", "- Open extensions (View >> extensions)\n", "- Search for python, and when the results show, click on the ms-python one, and Install it if not already installed\n", "- Search for jupyter, and when the results show, click on the Microsoft one, and Install it if not already installed \n", "Then View >> Explorer to bring back the File Explorer.\n", "\n", "And then:\n", "1. Click where it says \"Select Kernel\" near the top right, and select the option called `.venv (Python 3.12.9)` or similar, which should be the first choice or the most prominent choice. You may need to choose \"Python Environments\" first.\n", "2. Click in each \"cell\" below, starting with the cell immediately below this text, and press Shift+Enter to run\n", "3. Enjoy!\n", "\n", "After you click \"Select Kernel\", if there is no option like `.venv (Python 3.12.9)` then please do the following: \n", "1. From the Cursor menu, choose Settings >> VSCode Settings (NOTE: be sure to select `VSCode Settings` not `Cursor Settings`) \n", "2. In the Settings search bar, type \"venv\" \n", "3. In the field \"Path to folder with a list of Virtual Environments\" put the path to the project root, like C:\\Users\\username\\projects\\agents (on a Windows PC) or /Users/username/projects/agents (on Mac or Linux). \n", "And then try again.\n", "\n", "Having problems with missing Python versions in that list? Have you ever used Anaconda before? It might be interferring. Quit Cursor, bring up a new command line, and make sure that your Anaconda environment is deactivated: \n", "`conda deactivate` \n", "And if you still have any problems with conda and python versions, it's possible that you will need to run this too: \n", "`conda config --set auto_activate_base false` \n", "and then from within the Agents directory, you should be able to run `uv python list` and see the Python 3.12 version." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First let's do an import\n", "from dotenv import load_dotenv\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Next it's time to load the API keys into environment variables\n", "\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check the keys\n", "\n", "import os\n", "gemini_api_key = os.getenv('GEMINI_API_KEY')\n", "\n", "if gemini_api_key:\n", " print(f\"Gemini API Key exists and begins {gemini_api_key[:8]}\")\n", "else:\n", " print(\"Gemini API Key not set - please head to the troubleshooting guide in the guides folder\")\n", " \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# And now - the all important import statement\n", "# If you get an import error - head over to troubleshooting guide\n", "\n", "from google import genai" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# And now we'll create an instance of the Gemini GenAI class\n", "# If you're not sure what it means to create an instance of a class - head over to the guides folder!\n", "# If you get a NameError - head over to the guides folder to learn about NameErrors\n", "\n", "client = genai.Client(api_key=gemini_api_key)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a list of messages in the familiar Gemini GenAI format\n", "\n", "messages = [\"What is 2+2?\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# And now call it! Any problems, head to the troubleshooting guide\n", "\n", "response = client.models.generate_content(\n", " model=\"gemini-2.0-flash\", contents=messages\n", ")\n", "\n", "print(response.text)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# Lets no create a challenging question\n", "question = \"Please propose a hard, challenging question to assess someone's IQ. Respond only with the question.\"\n", "\n", "# Ask the the model\n", "response = client.models.generate_content(\n", " model=\"gemini-2.0-flash\", contents=question\n", ")\n", "\n", "question = response.text\n", "\n", "print(question)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ask the models generated question to the model\n", "response = client.models.generate_content(\n", " model=\"gemini-2.0-flash\", contents=question\n", ")\n", "\n", "# Extract the answer from the response\n", "answer = response.text\n", "\n", "# Debug log the answer\n", "print(answer)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import Markdown, display\n", "\n", "# Nicely format the answer using Markdown\n", "display(Markdown(answer))\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Congratulations!\n", "\n", "That was a small, simple step in the direction of Agentic AI, with your new environment!\n", "\n", "Next time things get more interesting..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Exercise</h2>\n", " <span style=\"color:#ff7800;\">Now try this commercial application:<br/>\n", " First ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.<br/>\n", " Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.<br/>\n", " Finally have 3 third LLM call propose the Agentic AI solution.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First create the messages:\n", "\n", "\n", "messages = [\"Something here\"]\n", "\n", "# Then make the first call:\n", "\n", "response =\n", "\n", "# Then read the business idea:\n", "\n", "business_idea = response.\n", "\n", "# And repeat!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# First Agentic AI workflow with Groq and Llama-3.3 LLM(Free of cost) " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# First let's do an import\n", "from dotenv import load_dotenv" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Next it's time to load the API keys into environment variables\n", "\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check the Groq API key\n", "\n", "import os\n", "groq_api_key = os.getenv('GROQ_API_KEY')\n", "\n", "if groq_api_key:\n", " print(f\"GROQ API Key exists and begins {groq_api_key[:8]}\")\n", "else:\n", " print(\"GROQ API Key not set\")\n", " \n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# And now - the all important import statement\n", "# If you get an import error - head over to troubleshooting guide\n", "\n", "from groq import Groq" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Create a Groq instance\n", "groq = Groq()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# Create a list of messages in the familiar Groq format\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"What is 2+2?\"}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# And now call it!\n", "\n", "response = groq.chat.completions.create(model='llama-3.3-70b-versatile', messages=messages)\n", "print(response.choices[0].message.content)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# And now - let's ask for a question:\n", "\n", "question = \"Please propose a hard, challenging question to assess someone's IQ. Respond only with the question.\"\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ask it\n", "response = groq.chat.completions.create(\n", " model=\"llama-3.3-70b-versatile\",\n", " messages=messages\n", ")\n", "\n", "question = response.choices[0].message.content\n", "\n", "print(question)\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "# form a new messages list\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ask it again\n", "\n", "response = groq.chat.completions.create(\n", " model=\"llama-3.3-70b-versatile\",\n", " messages=messages\n", ")\n", "\n", "answer = response.choices[0].message.content\n", "print(answer)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import Markdown, display\n", "\n", "display(Markdown(answer))\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Exercise</h2>\n", " <span style=\"color:#ff7800;\">Now try this commercial application:<br/>\n", " First ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.<br/>\n", " Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.<br/>\n", " Finally have 3 third LLM call propose the Agentic AI solution.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "# First create the messages:\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"Give me a business area that might be ripe for an Agentic AI solution.\"}]\n", "\n", "# Then make the first call:\n", "\n", "response = groq.chat.completions.create(model='llama-3.3-70b-versatile', messages=messages)\n", "\n", "# Then read the business idea:\n", "\n", "business_idea = response.choices[0].message.content\n", "\n", "\n", "# And repeat!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "display(Markdown(business_idea))" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "# Update the message with the business idea from previous step\n", "messages = [{\"role\": \"user\", \"content\": \"What is the pain point in the business area of \" + business_idea + \"?\"}]" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "# Make the second call\n", "response = groq.chat.completions.create(model='llama-3.3-70b-versatile', messages=messages)\n", "# Read the pain point\n", "pain_point = response.choices[0].message.content\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "display(Markdown(pain_point))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Make the third call\n", "messages = [{\"role\": \"user\", \"content\": \"What is the Agentic AI solution for the pain point of \" + pain_point + \"?\"}]\n", "response = groq.chat.completions.create(model='llama-3.3-70b-versatile', messages=messages)\n", "# Read the agentic solution\n", "agentic_solution = response.choices[0].message.content\n", "display(Markdown(agentic_solution))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Welcome to the start of your adventure in Agentic AI" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/stop.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Are you ready for action??</h2>\n", " <span style=\"color:#ff7800;\">Have you completed all the setup steps in the <a href=\"../setup/\">setup</a> folder?<br/>\n", " Have you checked out the guides in the <a href=\"../guides/01_intro.ipynb\">guides</a> folder?<br/>\n", " Well in that case, you're ready!!\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/tools.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#00bfff;\">Treat these labs as a resource</h2>\n", " <span style=\"color:#00bfff;\">I push updates to the code regularly. When people ask questions or have problems, I incorporate it in the code, adding more examples or improved commentary. As a result, you'll notice that the code below isn't identical to the videos. Everything from the videos is here; but in addition, I've added more steps and better explanations. Consider this like an interactive book that accompanies the lectures.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### And please do remember to contact me if I can help\n", "\n", "And I love to connect: https://www.linkedin.com/in/eddonner/\n", "\n", "\n", "### New to Notebooks like this one? Head over to the guides folder!\n", "\n", "Just to check you've already added the Python and Jupyter extensions to Cursor, if not already installed:\n", "- Open extensions (View >> extensions)\n", "- Search for python, and when the results show, click on the ms-python one, and Install it if not already installed\n", "- Search for jupyter, and when the results show, click on the Microsoft one, and Install it if not already installed \n", "Then View >> Explorer to bring back the File Explorer.\n", "\n", "And then:\n", "1. Click where it says \"Select Kernel\" near the top right, and select the option called `.venv (Python 3.12.9)` or similar, which should be the first choice or the most prominent choice. You may need to choose \"Python Environments\" first.\n", "2. Click in each \"cell\" below, starting with the cell immediately below this text, and press Shift+Enter to run\n", "3. Enjoy!\n", "\n", "After you click \"Select Kernel\", if there is no option like `.venv (Python 3.12.9)` then please do the following: \n", "1. From the Cursor menu, choose Settings >> VSCode Settings (NOTE: be sure to select `VSCode Settings` not `Cursor Settings`) \n", "2. In the Settings search bar, type \"venv\" \n", "3. In the field \"Path to folder with a list of Virtual Environments\" put the path to the project root, like C:\\Users\\username\\projects\\agents (on a Windows PC) or /Users/username/projects/agents (on Mac or Linux). \n", "And then try again.\n", "\n", "Having problems with missing Python versions in that list? Have you ever used Anaconda before? It might be interferring. Quit Cursor, bring up a new command line, and make sure that your Anaconda environment is deactivated: \n", "`conda deactivate` \n", "And if you still have any problems with conda and python versions, it's possible that you will need to run this too: \n", "`conda config --set auto_activate_base false` \n", "and then from within the Agents directory, you should be able to run `uv python list` and see the Python 3.12 version." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# First let's do an import\n", "from dotenv import load_dotenv\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Next it's time to load the API keys into environment variables\n", "\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OPEN AI API Key exists and begins sk-proj-\n" ] } ], "source": [ "# Check the keys\n", "\n", "import os\n", "openai_api_key = os.getenv('OPENAI_API_KEY')\n", "\n", "if openai_api_key:\n", " print(f\"OPEN AI API Key exists and begins {openai_api_key[:8]}\")\n", "else:\n", " print(\"OPENAI API Key not set - please head to the troubleshooting guide in the guides folder\")\n", " \n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# And now - the all important import statement\n", "# If you get an import error - head over to troubleshooting guide\n", "\n", "from openai import OpenAI" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# And now we'll create an instance of the Gemini GenAI class\n", "# If you're not sure what it means to create an instance of a class - head over to the guides folder!\n", "# If you get a NameError - head over to the guides folder to learn about NameErrors\n", "\n", "client = OpenAI()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# Create a list of messages in the familiar Gemini GenAI format\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"What is 2+2?\"}]" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 + 2 equals 4.\n" ] } ], "source": [ "# And now call it! Any problems, head to the troubleshooting guide\n", "\n", "response = client.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "print(response.choices[0].message.content)\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "In a race, you pass the person in second place. What position are you in now?\n" ] } ], "source": [ "\n", "# Lets no create a challenging question\n", "question = \"Please propose a hard, challenging question to assess someone's IQ. Respond only with the question.\"\n", "\n", "# Ask the the model\n", "response = client.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=[{\"role\": \"user\", \"content\": question}]\n", ")\n", "\n", "question = response.choices[0].message.content\n", "print(question)\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "If you pass the person in second place, you take their position, which means you are now in second place.\n" ] } ], "source": [ "# Ask the models generated question to the model\n", "# response = client.models.generate_content(\n", "# model=\"gemini-2.0-flash\", contents=question\n", "# )\n", "\n", "response = client.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=[{\"role\": \"user\", \"content\": question}]\n", ")\n", "\n", "# Extract the answer from the response\n", "answer = response.choices[0].message.content\n", "\n", "# Debug log the answer\n", "print(answer)\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "If you pass the person in second place, you take their position, which means you are now in second place." ], "text/plain": [ "<IPython.core.display.Markdown object>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from IPython.display import Markdown, display\n", "\n", "# Nicely format the answer using Markdown\n", "display(Markdown(answer))\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Congratulations!\n", "\n", "That was a small, simple step in the direction of Agentic AI, with your new environment!\n", "\n", "Next time things get more interesting..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Exercise</h2>\n", " <span style=\"color:#ff7800;\">Now try this commercial application:<br/>\n", " First ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.<br/>\n", " Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.<br/>\n", " Finally have 3 third LLM call propose the Agentic AI solution.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "The rise of Large Language Models (LLMs) has created a wide array of business opportunities across various sectors. Here are some potential business opportunities that LLMs can facilitate:\n", "\n", "1. **Content Creation**: Businesses can leverage LLMs to generate high-quality written content, such as articles, blogs, marketing copy, product descriptions, and social media posts, at scale.\n", "\n", "2. **Customer Support**: Implementing LLMs in chatbots and virtual assistants can enhance customer service by providing instant responses to customer inquiries, reducing the need for human intervention.\n", "\n", "3. **Personalization**: Companies can use LLMs to analyze customer data and create personalized recommendations for products and services, which can enhance user experience and increase sales.\n", "\n", "4. **Language Translation**: LLMs can be employed to deliver high-quality translation services, enabling businesses to reach global markets and communicate effectively with customers in different languages.\n", "\n", "5. **Market Research**: LLMs can sift through large datasets to generate insights about market trends, customer behavior, and sentiment analysis, aiding in strategic decision-making.\n", "\n", "6. **Education and Training**: EdTech companies can utilize LLMs to create interactive learning tools, personalized learning experiences, and automated tutoring systems.\n", "\n", "7. **Legal Assistance**: LLMs can be used to draft legal documents, summarize case files, and assist lawyers by providing research insights or predicting case outcomes, making legal services more efficient.\n", "\n", "8. **Health Care**: In the healthcare sector, LLMs can assist in clinical documentation, patient interaction, and even provide initial diagnostic suggestions based on patient queries.\n", "\n", "9. **Creative Industries**: Artists, musicians, and filmmakers can use LLMs as brainstorming partners for generating ideas, writing scripts, or creating lyrics, thus enhancing their creative processes.\n", "\n", "10. **Compliance and Risk Management**: Businesses can employ LLMs to analyze regulations and identify compliance risks, providing recommendations for best practices.\n", "\n", "11. **Gaming**: In the gaming industry, LLMs can create dynamic narratives, interactive game dialogues, and responsive NPCs (non-playable characters), enhancing player engagement.\n", "\n", "12. **SEO Optimization**: Businesses can utilize LLMs for search engine optimization by generating keyword-rich content and improving website visibility.\n", "\n", "13. **Accessibility Tools**: LLMs can be developed into applications that aid in accessibility, such as converting text to speech, enhancing communication for the hearing impaired, or simplifying complex texts for better understanding.\n", "\n", "14. **Data Analysis and Visualization**: LLMs can help interpret large datasets, generate reports, and create visualizations, making it easier for businesses to understand their data.\n", "\n", "15. **Social Media Management**: Automating posts, monitoring engagement, and generating responses using LLMs can streamline social media strategies for brands.\n", "\n", "Overall, the adaptability and versatility of LLMs provide numerous avenues for innovation and improvement in business processes, enhancing efficiency, creativity, and customer satisfaction. Companies that harness these technologies effectively can gain a competitive advantage in their respective industries." ], "text/plain": [ "<IPython.core.display.Markdown object>" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "****** Solutions **********\n" ] }, { "data": { "text/markdown": [ "The opportunities presented by Large Language Models (LLMs) can indeed be vast, and businesses seeking to capitalize on these innovations can explore a variety of solutions. Here are some potential strategies for implementing the business opportunities associated with LLMs:\n", "\n", "1. **Content Creation**\n", " - Develop subscription-based platforms that offer custom content generation for businesses.\n", " - Create plugins or SaaS tools for existing content management systems (CMS) that integrate LLMs for efficient content creation.\n", "\n", "2. **Customer Support**\n", " - Build advanced AI chatbots that can be integrated across multiple customer service channels (web, mobile, social media) for cohesive support.\n", " - Offer AI-driven customer service analytics to identify areas for improving response strategies and user satisfaction.\n", "\n", "3. **Personalization**\n", " - Create platforms that aggregate customer data and use LLMs to tailor marketing campaigns and product suggestions in real-time.\n", " - Develop recommendation engines for e-commerce that adapt based on user interactions.\n", "\n", "4. **Language Translation**\n", " - Launch translation services powered by LLMs that cater specifically to industries with specialized vocabulary, like legal, medical, or technical fields.\n", " - Design applications that offer on-the-fly translation in business meetings or conferences.\n", "\n", "5. **Market Research**\n", " - Create a market intelligence tool using LLMs to analyze industry reports, extract insights, and deliver summaries to decision-makers.\n", " - Offer sentiment analysis services for brands to monitor public perception through social media and online reviews.\n", "\n", "6. **Education and Training**\n", " - Design interactive e-learning platforms where LLMs personalize course materials and offer targeted quizzes based on user performance.\n", " - Develop automated tutoring systems that provide one-on-one help to students in various subjects.\n", "\n", "7. **Legal Assistance**\n", " - Build a legal tech platform that automates document generation, simplifies legal research, and assists with compliance checks.\n", " - Offer predictive analytics tools based on past case outcomes to help lawyers with strategy formulation.\n", "\n", "8. **Health Care**\n", " - Develop applications that integrate LLMs to process patient data, streamline clinical documentation, and improve communication between patients and providers.\n", " - Create AI tools that provide patients with preliminary information based on symptoms they describe.\n", "\n", "9. **Creative Industries**\n", " - Launch collaborative tools for artists that leverage LLMs to provide creative suggestions and brainstorm ideas.\n", " - Develop software that uses LLMs to assist in scriptwriting, music composition, and interactive storytelling.\n", "\n", "10. **Compliance and Risk Management**\n", " - Build analytics dashboards powered by LLMs that help companies stay updated with regulatory changes and assess their compliance status.\n", " - Offer consulting services that use AI insights to recommend best practices for risk management.\n", "\n", "11. **Gaming**\n", " - Create tools for game developers that use LLMs to generate in-game dialogues, branching narratives, or complex character interactions automatically.\n", " - Design an interactive storytelling platform that allows players to co-create narratives with LLM-driven characters.\n", "\n", "12. **SEO Optimization**\n", " - Develop SEO tools that leverage LLMs for creating optimized content, keyword strategies, and performance analytics.\n", " - Offer services for businesses to enhance their content visibility through AI-generated SEO insights.\n", "\n", "13. **Accessibility Tools**\n", " - Create applications that use LLMs to convert complex texts into simpler language for better comprehension, aiding individuals with learning disabilities.\n", " - Develop text-to-speech and speech-to-text tools that enhance accessibility for communication.\n", "\n", "14. **Data Analysis and Visualization**\n", " - Build analytics dashboards that empower businesses to visualize and interpret data using LLM-driven insights.\n", " - Offer consulting services to help organizations understand their data and derive actionable insights using AI.\n", "\n", "15. **Social Media Management**\n", " - Design an AI-powered platform that automates social media content creation, scheduling, and engagement analysis.\n", " - Create a tool that generates user-friendly social media reports based on LLM analysis of engagement and trends.\n", "\n", "By exploring these solutions, businesses can maximize the potential of LLMs to improve various aspects of their operations while creating new offerings that align with evolving market needs. Investment in training and fine-tuning these models for specific industries will further enhance their effectiveness and drive results." ], "text/plain": [ "<IPython.core.display.Markdown object>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# First create the messages:\n", "\n", "from IPython.display import Markdown, display\n", "\n", "messages = [{'role': 'user', 'content': 'What is Business Opportunity for LLM?'}]\n", "\n", "# Then make the first call:\n", "\n", "response = client.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "# Then read the business idea:\n", "\n", "business_idea = response.choices[0].message.content\n", "\n", "# And repeat!\n", "display(Markdown(business_idea))\n", "\n", "solutionMessages = [{'role': 'user', 'content': f'What are the solutions for {business_idea}?'}]\n", "\n", "solutionResponse = client.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=solutionMessages\n", ")\n", "\n", "solution = solutionResponse.choices[0].message.content\n", "\n", "print(\"****** Solutions **********\")\n", "display(Markdown(solution))\n" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# From Judging to Synthesizing — Evolving Multi-Agent Patterns\n", "\n", "In the original 2_lab2.ipynb, we explored a powerful agentic design pattern: sending the same question to multiple large language models (LLMs), then using a separate “judge” agent to evaluate and rank their responses. This approach is valuable for identifying the single best answer among many, leveraging the strengths of ensemble reasoning and critical evaluation.\n", "\n", "However, selecting just one “winner” can leave valuable insights from other models untapped. To address this, I am shifting to a new agentic pattern in this notebook: the synthesizer/improver pattern. Instead of merely ranking responses, we will prompt a dedicated LLM to review all answers, extract the most compelling ideas from each, and synthesize them into a single, improved response. \n", "\n", "This approach aims to combine the collective intelligence of multiple models, producing an answer that is richer, more nuanced, and more robust than any individual response.\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import json\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "from anthropic import Anthropic\n", "from IPython.display import Markdown, display" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the key prefixes to help with any debugging\n", "\n", "openai_api_key = os.getenv('OPENAI_API_KEY')\n", "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n", "google_api_key = os.getenv('GOOGLE_API_KEY')\n", "deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n", "groq_api_key = os.getenv('GROQ_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 (and this is optional)\")\n", "\n", "if google_api_key:\n", " print(f\"Google API Key exists and begins {google_api_key[:2]}\")\n", "else:\n", " print(\"Google API Key not set (and this is optional)\")\n", "\n", "if deepseek_api_key:\n", " print(f\"DeepSeek API Key exists and begins {deepseek_api_key[:3]}\")\n", "else:\n", " print(\"DeepSeek API Key not set (and this is optional)\")\n", "\n", "if groq_api_key:\n", " print(f\"Groq API Key exists and begins {groq_api_key[:4]}\")\n", "else:\n", " print(\"Groq API Key not set (and this is optional)\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "request = \"Please come up with a challenging, nuanced question that I can ask a number of LLMs to evaluate their collective intelligence. \"\n", "request += \"Answer only with the question, no explanation.\"\n", "messages = [{\"role\": \"user\", \"content\": request}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "messages" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "openai = OpenAI()\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages,\n", ")\n", "question = response.choices[0].message.content\n", "print(question)\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "teammates = []\n", "answers = []\n", "messages = [{\"role\": \"user\", \"content\": question}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The API we know well\n", "\n", "model_name = \"gpt-4o-mini\"\n", "\n", "response = openai.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "teammates.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Anthropic has a slightly different API, and Max Tokens is required\n", "\n", "model_name = \"claude-3-7-sonnet-latest\"\n", "\n", "claude = Anthropic()\n", "response = claude.messages.create(model=model_name, messages=messages, max_tokens=1000)\n", "answer = response.content[0].text\n", "\n", "display(Markdown(answer))\n", "teammates.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gemini = OpenAI(api_key=google_api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n", "model_name = \"gemini-2.0-flash\"\n", "\n", "response = gemini.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "teammates.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "deepseek = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com/v1\")\n", "model_name = \"deepseek-chat\"\n", "\n", "response = deepseek.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "teammates.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "groq = OpenAI(api_key=groq_api_key, base_url=\"https://api.groq.com/openai/v1\")\n", "model_name = \"llama-3.3-70b-versatile\"\n", "\n", "response = groq.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "teammates.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# So where are we?\n", "\n", "print(teammates)\n", "print(answers)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# It's nice to know how to use \"zip\"\n", "for teammate, answer in zip(teammates, answers):\n", " print(f\"Teammate: {teammate}\\n\\n{answer}\")" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "# Let's bring this together - note the use of \"enumerate\"\n", "\n", "together = \"\"\n", "for index, answer in enumerate(answers):\n", " together += f\"# Response from teammate {index+1}\\n\\n\"\n", " together += answer + \"\\n\\n\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(together)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "formatter = f\"\"\"You are taking the nost interesting ideas fron {len(teammates)} teammates.\n", "Each model has been given this question:\n", "\n", "{question}\n", "\n", "Your job is to evaluate each response for clarity and strength of argument, select the most relevant ideas and make a report, including a title, subtitles to separate sections, and quoting the LLM providing the idea.\n", "From that, you will create a new improved answer.\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(formatter)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "formatter_messages = [{\"role\": \"user\", \"content\": formatter}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "openai = OpenAI()\n", "response = openai.chat.completions.create(\n", " model=\"o3-mini\",\n", " messages=formatter_messages,\n", ")\n", "results = response.choices[0].message.content\n", "display(Markdown(results))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Business idea generator and evaluator \n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Start with imports - ask ChatGPT to explain any package that you don't know\n", "\n", "import os\n", "import json\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "from anthropic import Anthropic\n", "from IPython.display import Markdown, display" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Always remember to do this!\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the key prefixes to help with any debugging\n", "\n", "openai_api_key = os.getenv('OPENAI_API_KEY')\n", "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n", "google_api_key = os.getenv('GOOGLE_API_KEY')\n", "deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n", "groq_api_key = os.getenv('GROQ_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 (and this is optional)\")\n", "\n", "if google_api_key:\n", " print(f\"Google API Key exists and begins {google_api_key[:2]}\")\n", "else:\n", " print(\"Google API Key not set (and this is optional)\")\n", "\n", "if deepseek_api_key:\n", " print(f\"DeepSeek API Key exists and begins {deepseek_api_key[:3]}\")\n", "else:\n", " print(\"DeepSeek API Key not set (and this is optional)\")\n", "\n", "if groq_api_key:\n", " print(f\"Groq API Key exists and begins {groq_api_key[:4]}\")\n", "else:\n", " print(\"Groq API Key not set (and this is optional)\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "request = (\n", " \"Please generate three innovative business ideas aligned with the latest global trends. \"\n", " \"For each idea, include a brief description (2–3 sentences).\"\n", ")\n", "messages = [{\"role\": \"user\", \"content\": request}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "messages" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "openai = OpenAI()\n", "'''\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages,\n", ")\n", "question = response.choices[0].message.content\n", "print(question)\n", "'''" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "competitors = []\n", "answers = []\n", "#messages = [{\"role\": \"user\", \"content\": question}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The API we know well\n", "\n", "model_name = \"gpt-4o-mini\"\n", "\n", "response = openai.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Anthropic has a slightly different API, and Max Tokens is required\n", "\n", "model_name = \"claude-3-7-sonnet-latest\"\n", "\n", "claude = Anthropic()\n", "response = claude.messages.create(model=model_name, messages=messages, max_tokens=1000)\n", "answer = response.content[0].text\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gemini = OpenAI(api_key=google_api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n", "model_name = \"gemini-2.0-flash\"\n", "\n", "response = gemini.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "deepseek = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com/v1\")\n", "model_name = \"deepseek-chat\"\n", "\n", "response = deepseek.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "groq = OpenAI(api_key=groq_api_key, base_url=\"https://api.groq.com/openai/v1\")\n", "model_name = \"llama-3.3-70b-versatile\"\n", "\n", "response = groq.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!ollama pull llama3.2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ollama = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n", "model_name = \"llama3.2\"\n", "\n", "response = ollama.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# So where are we?\n", "\n", "print(competitors)\n", "print(answers)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# It's nice to know how to use \"zip\"\n", "for competitor, answer in zip(competitors, answers):\n", " print(f\"Competitor: {competitor}\\n\\n{answer}\")\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "# Let's bring this together - note the use of \"enumerate\"\n", "\n", "together = \"\"\n", "for index, answer in enumerate(answers):\n", " together += f\"# Response from competitor {index+1}\\n\\n\"\n", " together += answer + \"\\n\\n\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(together)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "judge = f\"\"\"You are judging a competition between {len(competitors)} competitors.\n", "Each model was asked to generate three innovative business ideas aligned with the latest global trends.\n", "\n", "Your job is to evaluate the likelihood of success for each idea on a scale from 0 to 100 percent. For each competitor, list the three percentages in the same order as their ideas.\n", "\n", "Respond only with JSON in this format:\n", "{{\"results\": [\n", " {{\"competitor\": 1, \"success_chances\": [perc1, perc2, perc3]}},\n", " {{\"competitor\": 2, \"success_chances\": [perc1, perc2, perc3]}},\n", " ...\n", "]}}\n", "\n", "Here are the ideas from each competitor:\n", "\n", "{together}\n", "\n", "Now respond with only the JSON, nothing else.\"\"\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(judge)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "judge_messages = [{\"role\": \"user\", \"content\": judge}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Judgement time!\n", "\n", "openai = OpenAI()\n", "response = openai.chat.completions.create(\n", " model=\"o3-mini\",\n", " messages=judge_messages,\n", ")\n", "results = response.choices[0].message.content\n", "print(results)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Parse judge results JSON and display success probabilities\n", "results_dict = json.loads(results)\n", "for entry in results_dict[\"results\"]:\n", " comp_num = entry[\"competitor\"]\n", " comp_name = competitors[comp_num - 1]\n", " chances = entry[\"success_chances\"]\n", " print(f\"{comp_name}:\")\n", " for idx, perc in enumerate(chances, start=1):\n", " print(f\" Idea {idx}: {perc}% chance of success\")\n", " print()\n" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 2}1.env123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# 🧠 Resume-Job Match Application (LLM-Powered)

This is a **Streamlit-based web app** that evaluates how well a resume matches a job description using powerful Large Language Models (LLMs) such as:
- OpenAI GPT- Anthropic Claude- Google Gemini (Generative AI)- Groq LLM- DeepSeek LLM
The app takes a resume and job description as input files, sends them to these LLMs, and returns:
- ✅ Match percentage from each model- 📊 A ranked table sorted by match %- 📈 Average match percentage- 🧠 Simple, responsive UI for instant feedback
## 📂 Features
- Upload **any file type** for resume and job description (PDF, DOCX, TXT, etc.)- Automatic extraction and cleaning of text- Match results across multiple models in real time- Table view with clean formatting- Uses `.env` file for secure API key management
## 🔐 Environment Setup (`.env`)
Create a `.env` file in the project root and add the following API keys:
```envOPENAI_API_KEY=your-openai-api-keyANTHROPIC_API_KEY=your-anthropic-api-keyGOOGLE_API_KEY=your-google-api-keyGROQ_API_KEY=your-groq-api-keyDEEPSEEK_API_KEY=your-deepseek-api-key ```
## ▶️ Running the App### Launch the app using Streamlit:
streamlit run resume_agent.py
### The app will open in your browser at:📍 http://localhost:8501
1234567891011121314151617181920212223242526272829303132333435363738394041424344import osfrom langchain.document_loaders import ( TextLoader, PyPDFLoader, UnstructuredWordDocumentLoader, UnstructuredFileLoader)
def load_and_split_resume(file_path: str): """ Loads a resume file and splits it into text chunks using LangChain.
Args: file_path (str): Path to the resume file (.txt, .pdf, .docx, etc.) chunk_size (int): Maximum characters per chunk. chunk_overlap (int): Overlap between chunks to preserve context.
Returns: List[str]: List of split text chunks. """ if not os.path.exists(file_path): raise FileNotFoundError(f"File not found: {file_path}")
ext = os.path.splitext(file_path)[1].lower()
# Select the appropriate loader if ext == ".txt": loader = TextLoader(file_path, encoding="utf-8") elif ext == ".pdf": loader = PyPDFLoader(file_path) elif ext in [".docx", ".doc"]: loader = UnstructuredWordDocumentLoader(file_path) else: # Fallback for other common formats loader = UnstructuredFileLoader(file_path)
# Load the file as LangChain documents documents = loader.load()
return documents # return [doc.page_content for doc in split_docs]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262import streamlit as stimport osfrom openai import OpenAIfrom anthropic import Anthropicimport pdfplumberfrom io import StringIOfrom dotenv import load_dotenvimport pandas as pdfrom multi_file_ingestion import load_and_split_resume
# Load environment variablesload_dotenv(override=True)openai_api_key = os.getenv("OPENAI_API_KEY")anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")google_api_key = os.getenv("GOOGLE_API_KEY")groq_api_key = os.getenv("GROQ_API_KEY")deepseek_api_key = os.getenv("DEEPSEEK_API_KEY")
openai = OpenAI()
# Streamlit UIst.set_page_config(page_title="LLM Resume–JD Fit", layout="wide")st.title("🧠 Multi-Model Resume–JD Match Analyzer")
# Inject custom CSS to reduce white spacest.markdown(""" <style> .block-container { padding-top: 3rem; /* instead of 1rem */ padding-bottom: 1rem; } .stMarkdown { margin-bottom: 0.5rem; } .logo-container img { width: 50px; height: auto; margin-right: 10px; } .header-row { display: flex; align-items: center; gap: 1rem; margin-top: 1rem; /* Add extra top margin here if needed */ } </style>""", unsafe_allow_html=True)
# File uploadresume_file = st.file_uploader("📄 Upload Resume (any file type)", type=None)jd_file = st.file_uploader("📝 Upload Job Description (any file type)", type=None)
# Function to extract text from uploaded filesdef extract_text(file): if file.name.endswith(".pdf"): with pdfplumber.open(file) as pdf: return "\n".join([page.extract_text() for page in pdf.pages if page.extract_text()]) else: return StringIO(file.read().decode("utf-8")).read()
def extract_candidate_name(resume_text): prompt = f"""You are an AI assistant specialized in resume analysis.
Your task is to get full name of the candidate from the resume.
Resume:{resume_text}
Respond with only the candidate's full name.""" try: response = openai.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a professional resume evaluator."}, {"role": "user", "content": prompt} ] ) content = response.choices[0].message.content return content.strip()
except Exception as e: return "Unknown"
# Function to build the prompt for LLMsdef build_prompt(resume_text, jd_text): prompt = f"""You are an AI assistant specialized in resume analysis and recruitment. Analyze the given resume and compare it with the job description.
Your task is to evaluate how well the resume aligns with the job description.
Provide a match percentage between 0 and 100, where 100 indicates a perfect fit.
Resume:{resume_text}
Job Description:{jd_text}
Respond with only the match percentage as an integer.""" return prompt.strip()
# Function to get match percentage from OpenAI GPT-4def get_openai_match(prompt): try: response = openai.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a professional resume evaluator."}, {"role": "user", "content": prompt} ] ) content = response.choices[0].message.content digits = ''.join(filter(str.isdigit, content)) return min(int(digits), 100) if digits else 0 except Exception as e: st.error(f"OpenAI API Error: {e}") return 0
# Function to get match percentage from Anthropic Claudedef get_anthropic_match(prompt): try: model_name = "claude-3-7-sonnet-latest" claude = Anthropic() message = claude.messages.create( model=model_name, max_tokens=100, messages=[ {"role": "user", "content": prompt} ] ) content = message.content[0].text digits = ''.join(filter(str.isdigit, content)) return min(int(digits), 100) if digits else 0 except Exception as e: st.error(f"Anthropic API Error: {e}") return 0
# Function to get match percentage from Google Geminidef get_google_match(prompt): try: gemini = OpenAI(api_key=google_api_key, base_url="https://generativelanguage.googleapis.com/v1beta/openai/") model_name = "gemini-2.0-flash" messages = [{"role": "user", "content": prompt}] response = gemini.chat.completions.create(model=model_name, messages=messages) content = response.choices[0].message.content digits = ''.join(filter(str.isdigit, content)) return min(int(digits), 100) if digits else 0 except Exception as e: st.error(f"Google Gemini API Error: {e}") return 0
# Function to get match percentage from Groqdef get_groq_match(prompt): try: groq = OpenAI(api_key=groq_api_key, base_url="https://api.groq.com/openai/v1") model_name = "llama-3.3-70b-versatile" messages = [{"role": "user", "content": prompt}] response = groq.chat.completions.create(model=model_name, messages=messages) answer = response.choices[0].message.content digits = ''.join(filter(str.isdigit, answer)) return min(int(digits), 100) if digits else 0 except Exception as e: st.error(f"Groq API Error: {e}") return 0
# Function to get match percentage from DeepSeekdef get_deepseek_match(prompt): try: deepseek = OpenAI(api_key=deepseek_api_key, base_url="https://api.deepseek.com/v1") model_name = "deepseek-chat" messages = [{"role": "user", "content": prompt}] response = deepseek.chat.completions.create(model=model_name, messages=messages) answer = response.choices[0].message.content digits = ''.join(filter(str.isdigit, answer)) return min(int(digits), 100) if digits else 0 except Exception as e: st.error(f"DeepSeek API Error: {e}") return 0
# Main actionif st.button("🔍 Analyze Resume Fit"): if resume_file and jd_file: with st.spinner("Analyzing..."): # resume_text = extract_text(resume_file) # jd_text = extract_text(jd_file) os.makedirs("temp_files", exist_ok=True) resume_path = os.path.join("temp_files", resume_file.name) with open(resume_path, "wb") as f: f.write(resume_file.getbuffer()) resume_docs = load_and_split_resume(resume_path) resume_text = "\n".join([doc.page_content for doc in resume_docs])
jd_path = os.path.join("temp_files", jd_file.name) with open(jd_path, "wb") as f: f.write(jd_file.getbuffer()) jd_docs = load_and_split_resume(jd_path) jd_text = "\n".join([doc.page_content for doc in jd_docs])
candidate_name = extract_candidate_name(resume_text) prompt = build_prompt(resume_text, jd_text)
# Get match percentages from all models scores = { "OpenAI GPT-4o Mini": get_openai_match(prompt), "Anthropic Claude": get_anthropic_match(prompt), "Google Gemini": get_google_match(prompt), "Groq": get_groq_match(prompt), "DeepSeek": get_deepseek_match(prompt), }
# Calculate average score average_score = round(sum(scores.values()) / len(scores), 2)
# Sort scores in descending order sorted_scores = sorted(scores.items(), reverse=False)
# Display results st.success("✅ Analysis Complete") st.subheader("📊 Match Results (Ranked by Model)")
# Show candidate name st.markdown(f"**👤 Candidate:** {candidate_name}")
# Create and sort dataframe df = pd.DataFrame(sorted_scores, columns=["Model", "% Match"]) df = df.sort_values("% Match", ascending=False).reset_index(drop=True)
# Convert to HTML table def render_custom_table(dataframe): table_html = "<table style='border-collapse: collapse; width: auto;'>" # Table header table_html += "<thead><tr>" for col in dataframe.columns: table_html += f"<th style='text-align: center; padding: 8px; border-bottom: 1px solid #ddd;'>{col}</th>" table_html += "</tr></thead>"
# Table rows table_html += "<tbody>" for _, row in dataframe.iterrows(): table_html += "<tr>" for val in row: table_html += f"<td style='text-align: left; padding: 8px; border-bottom: 1px solid #eee;'>{val}</td>" table_html += "</tr>" table_html += "</tbody></table>" return table_html
# Display table st.markdown(render_custom_table(df), unsafe_allow_html=True)
# Show average match st.metric(label="📈 Average Match %", value=f"{average_score:.2f}%") else: st.warning("Please upload both resume and job description.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231from dotenv import load_dotenvfrom openai import OpenAIimport jsonimport osimport requestsfrom pypdf import PdfReaderimport gradio as grimport base64import timefrom collections import defaultdictimport fastapifrom gradio.context import Contextimport logging
logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)
load_dotenv(override=True)
class RateLimiter: def __init__(self, max_requests=5, time_window=5): # max_requests per time_window seconds self.max_requests = max_requests self.time_window = time_window # in seconds self.request_history = defaultdict(list) def is_rate_limited(self, user_id): current_time = time.time() # Remove old requests self.request_history[user_id] = [ timestamp for timestamp in self.request_history[user_id] if current_time - timestamp < self.time_window ] # Check if user has exceeded the limit if len(self.request_history[user_id]) >= self.max_requests: return True # Add current request self.request_history[user_id].append(current_time) return False
def push(text): requests.post( "https://api.pushover.net/1/messages.json", data={ "token": os.getenv("PUSHOVER_TOKEN"), "user": os.getenv("PUSHOVER_USER"), "message": text, } )
def send_email(from_email, name, notes): auth = base64.b64encode(f'api:{os.getenv("MAILGUN_API_KEY")}'.encode()).decode() response = requests.post( f'https://api.mailgun.net/v3/{os.getenv("MAILGUN_DOMAIN")}/messages', headers={ 'Authorization': f'Basic {auth}' }, data={ 'from': f'Website Contact <mailgun@{os.getenv("MAILGUN_DOMAIN")}>', 'to': os.getenv("MAILGUN_RECIPIENT"), 'subject': f'New message from {from_email}', 'text': f'Name: {name}\nEmail: {from_email}\nNotes: {notes}', 'h:Reply-To': from_email } ) return response.status_code == 200
def record_user_details(email, name="Name not provided", notes="not provided"): push(f"Recording {name} with email {email} and notes {notes}") # Send email notification email_sent = send_email(email, name, notes) return {"recorded": "ok", "email_sent": email_sent}
def record_unknown_question(question): push(f"Recording {question}") return {"recorded": "ok"}
record_user_details_json = { "name": "record_user_details", "description": "Use this tool to record that a user is interested in being in touch and provided an email address", "parameters": { "type": "object", "properties": { "email": { "type": "string", "description": "The email address of this user" }, "name": { "type": "string", "description": "The user's name, if they provided it" } , "notes": { "type": "string", "description": "Any additional information about the conversation that's worth recording to give context" } }, "required": ["email"], "additionalProperties": False }}
record_unknown_question_json = { "name": "record_unknown_question", "description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer", "parameters": { "type": "object", "properties": { "question": { "type": "string", "description": "The question that couldn't be answered" }, }, "required": ["question"], "additionalProperties": False }}
tools = [{"type": "function", "function": record_user_details_json}, {"type": "function", "function": record_unknown_question_json}]
class Me:
def __init__(self): self.openai = OpenAI(api_key=os.getenv("GOOGLE_API_KEY"), base_url="https://generativelanguage.googleapis.com/v1beta/openai/") self.name = "Sagarnil Das" self.rate_limiter = RateLimiter(max_requests=5, time_window=60) # 5 messages per minute reader = PdfReader("me/linkedin.pdf") self.linkedin = "" for page in reader.pages: text = page.extract_text() if text: self.linkedin += text with open("me/summary.txt", "r", encoding="utf-8") as f: self.summary = f.read()
def handle_tool_call(self, tool_calls): results = [] for tool_call in tool_calls: tool_name = tool_call.function.name arguments = json.loads(tool_call.function.arguments) print(f"Tool called: {tool_name}", flush=True) tool = globals().get(tool_name) result = tool(**arguments) if tool else {} results.append({"role": "tool","content": json.dumps(result),"tool_call_id": tool_call.id}) return results def system_prompt(self): system_prompt = f"You are acting as {self.name}. You are answering questions on {self.name}'s website, \particularly questions related to {self.name}'s career, background, skills and experience. \Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. \Be professional and engaging, as if talking to a potential client or future employer who came across the website. \If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. \When a user provides their email, both a push notification and an email notification will be sent. If the user does not provide any note in the message \in which they provide their email, then give a summary of the conversation so far as the notes."
system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.linkedin}\n\n" system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}." return system_prompt def chat(self, message, history): # Get the client IP from Gradio's request context try: # Try to get the real client IP from request headers request = Context.get_context().request # Check for X-Forwarded-For header (common in reverse proxies like HF Spaces) forwarded_for = request.headers.get("X-Forwarded-For") # Check for Cf-Connecting-IP header (Cloudflare) cloudflare_ip = request.headers.get("Cf-Connecting-IP") if forwarded_for: # X-Forwarded-For contains a comma-separated list of IPs, the first one is the client user_id = forwarded_for.split(",")[0].strip() elif cloudflare_ip: user_id = cloudflare_ip else: # Fall back to direct client address user_id = request.client.host except (AttributeError, RuntimeError, fastapi.exceptions.FastAPIError): # Fallback if we can't get context or if running outside of FastAPI user_id = "default_user" logger.debug(f"User ID: {user_id}") if self.rate_limiter.is_rate_limited(user_id): return "You're sending messages too quickly. Please wait a moment before sending another message." messages = [{"role": "system", "content": self.system_prompt()}]
# Check if history is a list of dicts (Gradio "messages" format) if isinstance(history, list) and all(isinstance(h, dict) for h in history): messages.extend(history) else: # Assume it's a list of [user_msg, assistant_msg] pairs for user_msg, assistant_msg in history: messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": assistant_msg})
messages.append({"role": "user", "content": message})
done = False while not done: response = self.openai.chat.completions.create( model="gemini-2.0-flash", messages=messages, tools=tools ) if response.choices[0].finish_reason == "tool_calls": tool_calls = response.choices[0].message.tool_calls tool_result = self.handle_tool_call(tool_calls) messages.append(response.choices[0].message) messages.extend(tool_result) else: done = True
return response.choices[0].message.content
if __name__ == "__main__": me = Me() gr.ChatInterface(me.chat, type="messages").launch() 1234567891011121314151617181920212223242526272829{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Community contributions\n", "\n", "Thank you for considering contributing your work to the repo!\n", "\n", "Please add your code (modules or notebooks) to this directory and send me a PR, per the instructions in the guides.\n", "\n", "I'd love to share your progress with other students, so everyone can benefit from your projects.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "BASED ON Week 1 Day 3 LAB Exercise\n", "\n", "This program evaluates different LLM outputs who are acting as customer service representative and are replying to an irritated customer.\n", "OpenAI 40 mini, Gemini, Deepseek, Groq and Ollama are customer service representatives who respond to the email and OpenAI 3o mini analyzes all the responses and ranks their output based on different parameters." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Start with imports -\n", "import os\n", "import json\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "from anthropic import Anthropic\n", "from IPython.display import Markdown, display" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Always remember to do this!\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the key prefixes to help with any debugging\n", "\n", "openai_api_key = os.getenv('OPENAI_API_KEY')\n", "google_api_key = os.getenv('GOOGLE_API_KEY')\n", "deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n", "groq_api_key = os.getenv('GROQ_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 google_api_key:\n", " print(f\"Google API Key exists and begins {google_api_key[:2]}\")\n", "else:\n", " print(\"Google API Key not set (and this is optional)\")\n", "\n", "if deepseek_api_key:\n", " print(f\"DeepSeek API Key exists and begins {deepseek_api_key[:3]}\")\n", "else:\n", " print(\"DeepSeek API Key not set (and this is optional)\")\n", "\n", "if groq_api_key:\n", " print(f\"Groq API Key exists and begins {groq_api_key[:4]}\")\n", "else:\n", " print(\"Groq API Key not set (and this is optional)\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "persona = \"You are a customer support representative for a subscription bases software product.\"\n", "email_content = '''Subject: Totally unacceptable experience\n", "\n", "Hi,\n", "\n", "I’ve already written to you twice about this, and still no response. I was charged again this month even after canceling my subscription. This is the third time this has happened.\n", "\n", "Honestly, I’m losing patience. If I don’t get a clear explanation and refund within 24 hours, I’m going to report this on social media and leave negative reviews.\n", "\n", "You’ve seriously messed up here. Fix this now.\n", "\n", "– Jordan\n", "\n", "'''" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "messages = [{\"role\":\"system\", \"content\": persona}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "request = f\"\"\"A frustrated customer has written in about being repeatedly charged after canceling and threatened to escalate on social media.\n", "Write a calm, empathetic, and professional response that Acknowledges their frustration, Apologizes sincerely,Explains the next steps to resolve the issue\n", "Attempts to de-escalate the situation. Keep the tone respectful and proactive. Do not make excuses or blame the customer.\"\"\"\n", "request += f\" Here is the email : {email_content}]\"\n", "messages.append({\"role\": \"user\", \"content\": request})\n", "print(messages)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "messages" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "competitors = []\n", "answers = []\n", "messages = [{\"role\": \"user\", \"content\": request}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The API we know well\n", "openai = OpenAI()\n", "model_name = \"gpt-4o-mini\"\n", "\n", "response = openai.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gemini = OpenAI(api_key=google_api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n", "model_name = \"gemini-2.0-flash\"\n", "\n", "response = gemini.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "deepseek = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com/v1\")\n", "model_name = \"deepseek-chat\"\n", "\n", "response = deepseek.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "groq = OpenAI(api_key=groq_api_key, base_url=\"https://api.groq.com/openai/v1\")\n", "model_name = \"llama-3.3-70b-versatile\"\n", "\n", "response = groq.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!ollama pull llama3.2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ollama = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n", "model_name = \"llama3.2\"\n", "\n", "response = ollama.chat.completions.create(model=model_name, messages=messages)\n", "answer = response.choices[0].message.content\n", "\n", "display(Markdown(answer))\n", "competitors.append(model_name)\n", "answers.append(answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# So where are we?\n", "\n", "print(competitors)\n", "print(answers)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# It's nice to know how to use \"zip\"\n", "for competitor, answer in zip(competitors, answers):\n", " print(f\"Competitor: {competitor}\\n\\n{answer}\")\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "# Let's bring this together - note the use of \"enumerate\"\n", "\n", "together = \"\"\n", "for index, answer in enumerate(answers):\n", " together += f\"# Response from competitor {index+1}\\n\\n\"\n", " together += answer + \"\\n\\n\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(together)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "judge = f\"\"\"You are judging the performance of {len(competitors)} who are customer service representatives in a SaaS based subscription model company.\n", "Each has responded to below grievnace email from the customer:\n", "\n", "{request}\n", "\n", "Evaluate the following customer support reply based on these criteria. Assign a score from 1 (very poor) to 5 (excellent) for each:\n", "\n", "1. Empathy:\n", "Does the message acknowledge the customer’s frustration appropriately and sincerely?\n", "\n", "2. De-escalation:\n", "Does the response effectively calm the customer and reduce the likelihood of social media escalation?\n", "\n", "3. Clarity:\n", "Is the explanation of next steps clear and specific (e.g., refund process, timeline)?\n", "\n", "4. Professional Tone:\n", "Is the message respectful, calm, and free from defensiveness or blame?\n", "\n", "Provide a one-sentence explanation for each score and a final overall rating with justification.\n", "\n", "Here are the responses from each competitor:\n", "\n", "{together}\n", "\n", "Do not include markdown formatting or code blocks. Also create a table with 3 columnds at the end containing rank, name and one line reason for the rank\"\"\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(judge)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "judge_messages = [{\"role\": \"user\", \"content\": judge}]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Judgement time!\n", "\n", "openai = OpenAI()\n", "response = openai.chat.completions.create(\n", " model=\"o3-mini\",\n", " messages=judge_messages,\n", ")\n", "results = response.choices[0].message.content\n", "print(results)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(results)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Welcome to the start of your adventure in Agentic AI" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/stop.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Are you ready for action??</h2>\n", " <span style=\"color:#ff7800;\">Have you completed all the setup steps in the <a href=\"../setup/\">setup</a> folder?<br/>\n", " Have you checked out the guides in the <a href=\"../guides/01_intro.ipynb\">guides</a> folder?<br/>\n", " Well in that case, you're ready!!\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/tools.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#00bfff;\">Treat these labs as a resource</h2>\n", " <span style=\"color:#00bfff;\">I push updates to the code regularly. When people ask questions or have problems, I incorporate it in the code, adding more examples or improved commentary. As a result, you'll notice that the code below isn't identical to the videos. Everything from the videos is here; but in addition, I've added more steps and better explanations. Consider this like an interactive book that accompanies the lectures.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### And please do remember to contact me if I can help\n", "\n", "And I love to connect: https://www.linkedin.com/in/eddonner/\n", "\n", "\n", "### New to Notebooks like this one? Head over to the guides folder!\n", "\n", "Otherwise:\n", "1. Click where it says \"Select Kernel\" near the top right, and select the option called `.venv (Python 3.12.9)` or similar, which should be the first choice or the most prominent choice.\n", "2. Click in each \"cell\" below, starting with the cell immediately below this text, and press Shift+Enter to run\n", "3. Enjoy!" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# First let's do an import\n", "from dotenv import load_dotenv\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Next it's time to load the API keys into environment variables\n", "\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check the keys\n", "\n", "import os\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 - please head to the troubleshooting guide in the guides folder\")\n", " \n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# And now - the all important import statement\n", "# If you get an import error - head over to troubleshooting guide\n", "\n", "from openai import OpenAI" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# And now we'll create an instance of the OpenAI class\n", "# If you're not sure what it means to create an instance of a class - head over to the guides folder!\n", "# If you get a NameError - head over to the guides folder to learn about NameErrors\n", "\n", "openai = OpenAI()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# Create a list of messages in the familiar OpenAI format\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"What is 2+2?\"}]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# And now call it! Any problems, head to the troubleshooting guide\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "print(response.choices[0].message.content)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# And now - let's ask for a question:\n", "\n", "question = \"Please propose a hard, challenging question to assess someone's IQ. Respond only with the question.\"\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ask it\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "question = response.choices[0].message.content\n", "\n", "print(question)\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "# form a new messages list\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ask it again\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "answer = response.choices[0].message.content\n", "print(answer)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import Markdown, display\n", "\n", "display(Markdown(answer))\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Congratulations!\n", "\n", "That was a small, simple step in the direction of Agentic AI, with your new environment!\n", "\n", "Next time things get more interesting..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<table style=\"margin: 0; text-align: left; width:100%\">\n", " <tr>\n", " <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n", " <img src=\"../../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n", " </td>\n", " <td>\n", " <h2 style=\"color:#ff7800;\">Exercise</h2>\n", " <span style=\"color:#ff7800;\">Now try this commercial application:<br/>\n", " First ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.<br/>\n", " Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.<br/>\n", " Finally have 3 third LLM call propose the Agentic AI solution.\n", " </span>\n", " </td>\n", " </tr>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "# First create the messages:\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"Something here\"}]\n", "\n", "# Then make the first call:\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "# Then read the business idea:\n", "\n", "business_idea = response.choices[0].message.content\n", "\n", "# print(business_idea) \n", "\n", "# And repeat!\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First exercice : ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.\n", "\n", "# First create the messages:\n", "query = \"Pick a business area that might be worth exploring for an Agentic AI opportunity.\"\n", "messages = [{\"role\": \"user\", \"content\": query}]\n", "\n", "# Then make the first call:\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "# Then read the business idea:\n", "\n", "business_idea = response.choices[0].message.content\n", "\n", "# print(business_idea) \n", "\n", "# from IPython.display import Markdown, display\n", "\n", "display(Markdown(business_idea))\n", "\n", "# And repeat!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Second exercice: Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.\n", "\n", "# First create the messages:\n", "\n", "prompt = f\"Please present a pain-point in that industry, something challenging that might be ripe for an Agentic solution for it in that industry: {business_idea}\"\n", "messages = [{\"role\": \"user\", \"content\": prompt}]\n", "\n", "# Then make the first call:\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "# Then read the business idea:\n", "\n", "painpoint = response.choices[0].message.content\n", " \n", "# print(painpoint) \n", "display(Markdown(painpoint))\n", "\n", "# And repeat!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# third exercice: Finally have 3 third LLM call propose the Agentic AI solution.\n", "\n", "# First create the messages:\n", "\n", "promptEx3 = f\"Please come up with a proposal for the Agentic AI solution to address this business painpoint: {painpoint}\"\n", "messages = [{\"role\": \"user\", \"content\": promptEx3}]\n", "\n", "# Then make the first call:\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=messages\n", ")\n", "\n", "# Then read the business idea:\n", "\n", "ex3_answer=response.choices[0].message.content\n", "# print(painpoint) \n", "display(Markdown(ex3_answer))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Start with imports - ask ChatGPT to explain any package that you don't know\n", "\n", "import os\n", "import json\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "from anthropic import Anthropic\n", "from IPython.display import Markdown, display" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<b>Load and check your API keys</b>\n", "</br>\n", "<b>- - - - - - - - - - - - - - - -</b>" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Always remember to do this!\n", "load_dotenv(override=True)\n", "\n", "# Function to check and display API key status\n", "def check_api_key(key_name):\n", " key = os.getenv(key_name)\n", " \n", " if key:\n", " # Always show the first 7 characters of the key\n", " print(f\"✓ {key_name} API Key exists and begins... ({key[:7]})\")\n", " return True\n", " else:\n", " print(f\"⚠️ {key_name} API Key not set\")\n", " return False\n", "\n", "# Check each API key (the function now returns True or False)\n", "has_openai = check_api_key('OPENAI_API_KEY')\n", "has_anthropic = check_api_key('ANTHROPIC_API_KEY')\n", "has_google = check_api_key('GOOGLE_API_KEY')\n", "has_deepseek = check_api_key('DEEPSEEK_API_KEY')\n", "has_groq = check_api_key('GROQ_API_KEY')" ] }, { "cell_type": "markdown", "metadata": { "vscode": { "languageId": "html" } }, "source": [ "<b>Input for travel planner</b></br>\n", "Describe yourself, your travel companions, and the destination you plan to visit.\n", "</br>\n", "<b>- - - - - - - - - - - - - - - -</b>" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Provide a description of you or your family. Age, interests, etc.\n", "person_description = \"family with a 3 year-old\"\n", "# Provide the name of the specific destination or attraction and country\n", "destination = \"Belgium, Brussels\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<b>- - - - - - - - - - - - - - - -</b>" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "prompt = f\"\"\"\n", "Given the following description of a person or family:\n", "{person_description}\n", "\n", "And the requested travel destination or attraction:\n", "{destination}\n", "\n", "Provide a concise response including:\n", "\n", "1. Fit rating (1-10) specifically for this person or family.\n", "2. One compelling positive reason why this destination suits them.\n", "3. One notable drawback they should consider before visiting.\n", "4. One important additional aspect to consider related to this location.\n", "5. Suggest a few additional places that might also be of interest to them that are very close to the destination.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def run_prompt_on_available_models(prompt):\n", " \"\"\"\n", " Run a prompt on all available AI models based on API keys.\n", " Continues processing even if some models fail.\n", " \"\"\"\n", " results = {}\n", " api_response = [{\"role\": \"user\", \"content\": prompt}]\n", " \n", " # OpenAI\n", " if check_api_key('OPENAI_API_KEY'):\n", " try:\n", " model_name = \"gpt-4o-mini\"\n", " openai_client = OpenAI()\n", " response = openai_client.chat.completions.create(model=model_name, messages=api_response)\n", " results[model_name] = response.choices[0].message.content\n", " print(f\"✓ Got response from {model_name}\")\n", " except Exception as e:\n", " print(f\"⚠️ Error with {model_name}: {str(e)}\")\n", " # Continue with other models\n", " \n", " # Anthropic\n", " if check_api_key('ANTHROPIC_API_KEY'):\n", " try:\n", " model_name = \"claude-3-7-sonnet-latest\"\n", " # Create new client each time\n", " claude = Anthropic()\n", " \n", " # Use messages directly \n", " response = claude.messages.create(\n", " model=model_name,\n", " messages=[{\"role\": \"user\", \"content\": prompt}],\n", " max_tokens=1000\n", " )\n", " results[model_name] = response.content[0].text\n", " print(f\"✓ Got response from {model_name}\")\n", " except Exception as e:\n", " print(f\"⚠️ Error with {model_name}: {str(e)}\")\n", " # Continue with other models\n", " \n", " # Google\n", " if check_api_key('GOOGLE_API_KEY'):\n", " try:\n", " model_name = \"gemini-2.0-flash\"\n", " google_api_key = os.getenv('GOOGLE_API_KEY')\n", " gemini = OpenAI(api_key=google_api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n", " response = gemini.chat.completions.create(model=model_name, messages=api_response)\n", " results[model_name] = response.choices[0].message.content\n", " print(f\"✓ Got response from {model_name}\")\n", " except Exception as e:\n", " print(f\"⚠️ Error with {model_name}: {str(e)}\")\n", " # Continue with other models\n", " \n", " # DeepSeek\n", " if check_api_key('DEEPSEEK_API_KEY'):\n", " try:\n", " model_name = \"deepseek-chat\"\n", " deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n", " deepseek = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com/v1\")\n", " response = deepseek.chat.completions.create(model=model_name, messages=api_response)\n", " results[model_name] = response.choices[0].message.content\n", " print(f\"✓ Got response from {model_name}\")\n", " except Exception as e:\n", " print(f\"⚠️ Error with {model_name}: {str(e)}\")\n", " # Continue with other models\n", " \n", " # Groq\n", " if check_api_key('GROQ_API_KEY'):\n", " try:\n", " model_name = \"llama-3.3-70b-versatile\"\n", " groq_api_key = os.getenv('GROQ_API_KEY')\n", " groq = OpenAI(api_key=groq_api_key, base_url=\"https://api.groq.com/openai/v1\")\n", " response = groq.chat.completions.create(model=model_name, messages=api_response)\n", " results[model_name] = response.choices[0].message.content\n", " print(f\"✓ Got response from {model_name}\")\n", " except Exception as e:\n", " print(f\"⚠️ Error with {model_name}: {str(e)}\")\n", " # Continue with other models\n", " \n", " # Check if we got any responses\n", " if not results:\n", " print(\"⚠️ No models were able to provide a response\")\n", " \n", " return results\n", "\n", "# Get responses from all available models\n", "model_responses = run_prompt_on_available_models(prompt)\n", "\n", "# Display the results\n", "for model, answer in model_responses.items():\n", " display(Markdown(f\"## Response from {model}\\n\\n{answer}\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<b>Sythesize answers from all models into one</b>\n", "</br>\n", "<b>- - - - - - - - - - - - - - - -</b>" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a synthesis prompt\n", "synthesis_prompt = f\"\"\"\n", "Here are the responses from different models:\n", "\"\"\"\n", "\n", "# Add each model's response to the synthesis prompt without mentioning model names\n", "for index, (model, response) in enumerate(model_responses.items()):\n", " synthesis_prompt += f\"\\n--- Response {index+1} ---\\n{response}\\n\"\n", "\n", "synthesis_prompt += \"\"\"\n", "Please synthesize these responses into one comprehensive answer that:\n", "1. Captures the best insights from each response\n", "2. Resolves any contradictions between responses\n", "3. Presents a clear and coherent final answer\n", "4. Maintains the same format as the original responses (numbered list format)\n", "5.Compiles all additional places mentioned by all models \n", "\n", "Your synthesized response:\n", "\"\"\"\n", "\n", "# Create the synthesis\n", "if check_api_key('OPENAI_API_KEY'):\n", " try:\n", " openai_client = OpenAI()\n", " synthesis_response = openai_client.chat.completions.create(\n", " model=\"gpt-4o-mini\",\n", " messages=[{\"role\": \"user\", \"content\": synthesis_prompt}]\n", " )\n", " synthesized_answer = synthesis_response.choices[0].message.content\n", " print(\"✓ Successfully synthesized responses with gpt-4o-mini\")\n", " \n", " # Display the synthesized answer\n", " display(Markdown(\"## Synthesized Answer\\n\\n\" + synthesized_answer))\n", " except Exception as e:\n", " print(f\"⚠️ Error synthesizing responses with gpt-4o-mini: {str(e)}\")\n", "else:\n", " print(\"⚠️ OpenAI API key not available, cannot synthesize responses\")" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 2}12My name is Ed Donner. I'm an entrepreneur, software engineer and data scientist. I'm originally from London, England, but I moved to NYC in 2000.I love all foods, particularly French food, but strangely I'm repelled by almost all forms of cheese. I'm not allergic, I just hate the taste! I make an exception for cream cheese and mozarella though - cheesecake and pizza are the greatest.123456requestspython-dotenvgradiopypdfopenaiopenai-agents1_lab1.ipynbAdded+326
2_lab2.ipynbAdded+474
3_lab3.ipynbAdded+351
4_lab4.ipynbAdded+445
README.md+3-9
app.pyAdded+134
community_contributions/1_lab1_Mudassar.ipynbAdded+260
community_contributions/1_lab1_gemini.ipynbAdded+305
community_contributions/1_lab1_groq_llama.ipynbAdded+296
community_contributions/1_lab1_openai.ipynbAdded+505
community_contributions/2_lab2_exercise.ipynbAdded+336
community_contributions/Business_Idea.ipynbAdded+388
community_contributions/Multi-Model-Resume–JD-Match-Analyzer/.gitignoreAdded+1
community_contributions/Multi-Model-Resume–JD-Match-Analyzer/AnalyzeResume.pngAdded

community_contributions/Multi-Model-Resume–JD-Match-Analyzer/README.mdAdded+48
community_contributions/Multi-Model-Resume–JD-Match-Analyzer/multi_file_ingestion.pyAdded+44
community_contributions/Multi-Model-Resume–JD-Match-Analyzer/resume_agent.pyAdded+262
community_contributions/app_rate_limiter_mailgun_integration.pyAdded+231
community_contributions/community.ipynbAdded+29
community_contributions/llm-evaluator.ipynbAdded+385
community_contributions/my_1_lab1.ipynbAdded+405
community_contributions/travel_planner_multicall_and_sythesizer.ipynbAdded+287
me/linkedin.pdfAdded
me/summary.txtAdded+2
requirements.txtAdded+6