{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Welcome to the start of your adventure in Agentic AI" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Are you ready for action??

\n", " Have you completed all the setup steps in the setup folder?
\n", " Have you read the README? Many common questions are answered here!
\n", " Have you checked out the guides in the guides folder?
\n", " Well in that case, you're ready!!\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

This code is a live resource - keep an eye out for my updates

\n", " 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.

\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", "
\n", "
" ] }, { "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. If you get an Import Error, double check that your Kernel is correct..\n", "\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", "# If this returns false, see the next cell!\n", "\n", "load_dotenv(override=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Wait, did that just output `False`??\n", "\n", "If so, the most common reason is that you didn't save your `.env` file after adding the key! Be sure to have saved.\n", "\n", "Also, make sure the `.env` file is named precisely `.env` and is in the project root directory (`agents`)\n", "\n", "By the way, your `.env` file should have a stop symbol next to it in Cursor on the left, and that's actually a good thing: that's Cursor saying to you, \"hey, I realize this is a file filled with secret information, and I'm not going to send it to an external AI to suggest changes, because your keys should not be shown to anyone else.\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Final reminders

\n", " 1. If you're not confident about Environment Variables or Web Endpoints / APIs, please read Topics 3 and 5 in this technical foundations guide.
\n", " 2. If you want to use AIs other than OpenAI, like Gemini, DeepSeek or Ollama (free), please see the first section in this AI APIs guide.
\n", " 3. If you ever get a Name Error in Python, you can always fix it immediately; see the last section of this Python Foundations guide and follow both tutorials and exercises.
\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OpenAI API Key exists and begins BHvtnTIW\n" ] } ], "source": [ "# Check the key - if you're not using OpenAI, check whichever key you're using! Ollama doesn't need a key.\n", "\n", "import os\n", "openai_api_key = os.getenv('OPENAI_API_KEY')\n", "openai_endpoint = os.getenv('OPENAI_ENDPOINT')\n", "\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": 2, "metadata": {}, "outputs": [], "source": [ "# And now - the all important import statement\n", "# If you get an import error - head over to troubleshooting in the Setup folder\n", "\n", "from openai import AzureOpenAI" ] }, { "cell_type": "code", "execution_count": 24, "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 (guide 6)!\n", "# If you get a NameError - head over to the guides folder (guide 6)to learn about NameErrors - always instantly fixable\n", "# If you're not using OpenAI, you just need to slightly modify this - precise instructions are in the AI APIs guide (guide 9)\n", "#load from .env\n", "openai = AzureOpenAI(\n", " api_key=openai_api_key,\n", " azure_endpoint=openai_endpoint,\n", " api_version=\"2024-12-01-preview\",\n", ")" ] }, { "cell_type": "code", "execution_count": 9, "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": 10, "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", "# This uses GPT 4.1 nano, the incredibly cheap model\n", "# The APIs guide (guide 9) has exact instructions for using even cheaper or free alternatives to OpenAI\n", "# If you get a NameError, head to the guides folder (guide 6) to learn about NameErrors - always instantly fixable\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": 11, "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": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "One business area that could be worth exploring for an Agentic AI opportunity is **Personalized Healthcare Management**. \n", "\n", "### Opportunity Overview:\n", "The healthcare industry is increasingly leaning towards personalized medicine, which tailors treatment to the individual characteristics of each patient. An Agentic AI system could serve as a proactive health companion that monitors, analyzes, and manages health-related data in real-time.\n", "\n", "### Key Features:\n", "1. **Proactive Health Monitoring** - An AI could integrate with wearable devices and health apps to collect and analyze data such as heart rate, sleep patterns, and physical activity, providing insights and alerts for potential health issues.\n", "\n", "2. **Personalized Treatment Plans** - Based on individual health data and preferences, the AI could recommend personalized treatment plans, including medications, diet modifications, and lifestyle changes. \n", "\n", "3. **Medication Management** - The AI could manage medication schedules, send reminders, and provide educational resources about side effects, interactions, and adherence strategies.\n", "\n", "4. **Telehealth and Remote Consultations** - Facilitating telehealth appointments, where the AI acts as an intermediary, gathering patient info and symptoms before consultations with healthcare providers.\n", "\n", "5. **Mental Health Support** - Offering mental health resources based on user behavior and data, providing feedback, mood tracking, and suggestions for coping mechanisms or connecting them with therapists.\n", "\n", "6. **Chronic Disease Management** - Specializing in managing conditions like diabetes or hypertension through continuous monitoring, tips for managing symptoms, and real-time adjustments to treatment plans.\n", "\n", "### Market Potential:\n", "The global telehealth market is expected to grow substantially, driven by increasing demand for remote healthcare solutions, especially post-pandemic. The personalized healthcare market is also on the rise, indicating a promising environment for the development of sophisticated Agentic AI solutions.\n", "\n", "### Challenges:\n", "- **Data Privacy and Security** - Ensuring compliance with healthcare regulations and protecting sensitive patient data are critical challenges.\n", "- **Integration with Existing Systems** - The ability to integrate with various healthcare providers' systems and technologies is necessary for seamless operation.\n", "- **User Acceptance** - Building trust and ensuring user engagement is essential for any healthcare AI solution.\n", "\n", "### Conclusion:\n", "Personalized Healthcare Management stands out as a compelling area for Agentic AI opportunities, with the potential to improve patient outcomes, enhance the efficiency of healthcare delivery, and ultimately, reduce costs for both patients and healthcare providers.\n" ] } ], "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": 13, "metadata": {}, "outputs": [], "source": [ "# form a new messages list\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "To solve the problem, we start by visualizing the painting and cutting process of the 3x3x3 cube.\n", "\n", "1. **Understanding the 3x3x3 cube**: The cube consists of \\(3 \\times 3 \\times 3 = 27\\) smaller \\(1 \\times 1 \\times 1\\) cubes.\n", "\n", "2. **Painting the cube**: If we paint only one face of the cube, we need to identify the positions of the smaller cubes that are adjacent to this face. Since the 3x3 cube has 6 faces, selecting any one face to paint will lead to different smaller cubes being affected.\n", "\n", "3. **Identifying smaller cubes with at least 2 painted faces**: For a smaller cube to have at least two faces painted, it must be located at the edges or corners of the painted face. \n", "\n", " - **Cubes on the corners of the painted face**: There are 4 corner cubes on the painted face. Each of these corner cubes is shared with 3 adjacent faces, but since we are only painting one face, these corner cubes will only have one face painted and do not meet our criteria.\n", "\n", " - **Cubes on the edges of the painted face**: \n", " - The cubes on the edges of the painted face adjacent to the painted face can be considered. Each edge of the face has 3 cubes, with the middle cube being the relevant one in determining if multiple faces can be painted.\n", " - Each of the 4 edges of this painted face will contribute 1 cube that is shared with other faces (the middle cube on each edge).\n", " - Since there are 4 edges, we get 4 middle edge cubes:\n", " - Each of these 4 shared middle cubes will have exactly 2 of their faces painted if we consider their configuration with respect to the rest of the cube.\n", "\n", "4. **Conclusion**: There are no cubes at the corners that satisfy the requirement (at least 2 faces painted), and the total count of smaller cubes having at least 2 painted faces comes solely from the 4 edge cubes adjacent to the painted face.\n", "\n", "Thus, the maximum number of smaller cubes that can have at least two of their faces painted when the larger cube is painted on only one face is:\n", "\n", "\\[\n", "\\boxed{4}\n", "\\]\n" ] } ], "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": [ { "data": { "text/markdown": [ "To solve the problem, we start by visualizing the painting and cutting process of the 3x3x3 cube.\n", "\n", "1. **Understanding the 3x3x3 cube**: The cube consists of \\(3 \\times 3 \\times 3 = 27\\) smaller \\(1 \\times 1 \\times 1\\) cubes.\n", "\n", "2. **Painting the cube**: If we paint only one face of the cube, we need to identify the positions of the smaller cubes that are adjacent to this face. Since the 3x3 cube has 6 faces, selecting any one face to paint will lead to different smaller cubes being affected.\n", "\n", "3. **Identifying smaller cubes with at least 2 painted faces**: For a smaller cube to have at least two faces painted, it must be located at the edges or corners of the painted face. \n", "\n", " - **Cubes on the corners of the painted face**: There are 4 corner cubes on the painted face. Each of these corner cubes is shared with 3 adjacent faces, but since we are only painting one face, these corner cubes will only have one face painted and do not meet our criteria.\n", "\n", " - **Cubes on the edges of the painted face**: \n", " - The cubes on the edges of the painted face adjacent to the painted face can be considered. Each edge of the face has 3 cubes, with the middle cube being the relevant one in determining if multiple faces can be painted.\n", " - Each of the 4 edges of this painted face will contribute 1 cube that is shared with other faces (the middle cube on each edge).\n", " - Since there are 4 edges, we get 4 middle edge cubes:\n", " - Each of these 4 shared middle cubes will have exactly 2 of their faces painted if we consider their configuration with respect to the rest of the cube.\n", "\n", "4. **Conclusion**: There are no cubes at the corners that satisfy the requirement (at least 2 faces painted), and the total count of smaller cubes having at least 2 painted faces comes solely from the 4 edge cubes adjacent to the painted face.\n", "\n", "Thus, the maximum number of smaller cubes that can have at least two of their faces painted when the larger cube is painted on only one face is:\n", "\n", "\\[\n", "\\boxed{4}\n", "\\]" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "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": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Exercise

\n", " Now try this commercial application:
\n", " First ask the LLM to pick a business area that might be worth exploring for an Agentic AI opportunity.
\n", " Then ask the LLM to present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.
\n", " Finally have 3 third LLM call propose the Agentic AI solution.
\n", " We will cover this at up-coming labs, so don't worry if you're unsure.. just give it a try!\n", "
\n", "
" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "### Proposal for Agentic AI Solution: AI-Driven Personalized Health Coaches\n", "\n", "**Goal**: To enhance patient engagement and adherence to treatment plans through an AI-driven personalized health coaching system that integrates seamlessly with existing healthcare ecosystems.\n", "\n", "#### Overview of the Solution\n", "\n", "The AI-driven personalized health coach would utilize advanced machine learning, natural language processing, and data integration techniques to create a tailored support system for patients. This solution aims to address the barriers to engagement and adherence by providing real-time, customized coaching based on individual patient needs and behaviors.\n", "\n", "### Key Features of the AI Health Coach\n", "\n", "1. **Tailored Communication**:\n", " - **Natural Language Processing**: Utilize NLP to communicate with patients in an empathetic, clear, and concise manner, avoiding medical jargon. The AI can support multiple languages and dialects.\n", " - **Personalized Messaging**: The coach can send reminders, educational content, and encouragement based on each patient's preferences and understanding level.\n", "\n", "2. **Behavioral Insights and Support**:\n", " - **Sentiment Analysis**: Monitor patient communications and interactions to assess mood and sentiment, adjusting the tone and type of messages accordingly.\n", " - **Motivational Techniques**: Employ behavioral psychology principles to produce tailored motivational strategies, nudges, and reminders that encourage adherence.\n", "\n", "3. **Real-Time Feedback**:\n", " - **Data Integration**: Connect with wearable devices and health apps to monitor biometric data and treatment adherence in real-time.\n", " - **Dynamic Adjustments**: Use predictive analytics to adjust recommendations based on patient behavior, such as modifying medication reminders or suggesting lifestyle changes.\n", "\n", "4. **Integration with Health Ecosystem**:\n", " - **Provider Collaboration**: Develop a secure platform for communication between patients and their healthcare providers, allowing for real-time updates on treatment plans and health status.\n", " - **Centralized Health Records**: Create a unified health record system that aggregates data from various healthcare providers, ensuring comprehensive care and reducing fragmentation.\n", "\n", "5. **Community Support**:\n", " - **Peer Connectivity**: Facilitate connections between patients with similar conditions or experiences through forums and group chats, fostering a sense of community and shared motivation.\n", " - **Resource Sharing**: Encourage patients to share tips, success stories, and challenges to enhance collective learning and support.\n", "\n", "### Implementation Plan\n", "\n", "1. **Research & Development**:\n", " - Conduct studies to refine the model of personalized coaching. Collaborate with healthcare professionals to ensure the system meets clinical standards and guidelines.\n", "\n", "2. **Pilot Program**:\n", " - Launch a pilot program with a select group of patients. Collect feedback and make adjustments before a wider rollout.\n", "\n", "3. **Partnerships**:\n", " - Collaborate with healthcare organizations, technology companies, and mental health professionals to enhance the application's capabilities and reach.\n", "\n", "4. **Privacy & Security**:\n", " - Ensure compliance with HIPAA and other relevant privacy regulations to safeguard patient data. Implement robust cybersecurity measures.\n", "\n", "5. **Continuous Evaluation**:\n", " - Utilize metrics such as adherence rates, patient satisfaction surveys, and health outcomes to continually assess the effectiveness of the AI health coach and make necessary adjustments.\n", "\n", "### Expected Outcomes\n", "\n", "- **Increased Adherence**: Through continuous engagement, personalized communication, and behavioral support, patients will likely have improved adherence rates compared to traditional approaches.\n", "- **Improved Health Outcomes**: Enhanced adherence is anticipated to lead to better health control and fewer complications, particularly for chronic diseases.\n", "- **Increased Patient Satisfaction**: A supportive, personalized experience is expected to enhance patient satisfaction, leading to greater trust and willingness to adhere to recommended treatment plans.\n", "- **Cost-Effectiveness**: Ultimately, improved adherence and health outcomes could result in reduced healthcare costs associated with complications from non-adherence.\n", "\n", "### Conclusion\n", "\n", "The implementation of an AI-driven personalized health coach represents a significant innovation in addressing patient engagement and adherence challenges in healthcare. By providing tailored support and fostering a positive patient-provider relationship, this solution has the potential to transform the management of personalized healthcare, yielding better outcomes for patients and health systems alike.\n" ] } ], "source": [ "# First create the messages:\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"pick a business area that might be worth exploring for an Agentic AI opportunity.\"}]\n", "\n", "# Then make the first call:\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4.1\",\n", " messages=messages\n", ")\n", "\n", "# Then read the business idea:\n", "\n", "business_idea = response.choices[0].message.content\n", "\n", "# And repeat! In the next message, include the business idea within the message\n", "\n", "messages1 = [{\"role\": \"user\", \"content\": f\"{business_idea}\\n\\n present a pain-point in that industry - something challenging that might be ripe for an Agentic solution.\"}]\n", "\n", "response1 = openai.chat.completions.create(\n", " model=\"gpt-4.1\",\n", " messages=messages1\n", ")\n", "\n", "painpoint = response1.choices[0].message.content\n", "\n", "messages2 = [{\"role\": \"user\", \"content\": f\"{painpoint}\\n\\n propose the Agentic AI solution. \"}]\n", "\n", "response2 = openai.chat.completions.create(\n", " model=\"gpt-4.1\",\n", " messages=messages2,\n", ")\n", "solution = response2.choices[0].message.content\n", "\n", "print(solution)" ] }, { "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 }