{ "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": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OpenAI API Key exists and begins sk-proj-\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", "\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": 4, "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", "# Even for other LLM providers like Gemini, you still use this OpenAI import - see Guide 9 for why\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 (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", "\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": [ { "name": "stdout", "output_type": "stream", "text": [ "ChatCompletion(id='chatcmpl-C9oVaLh1gjzKH07zcVLaXQ4o4FDQ7', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='2 + 2 equals 4.', refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=None))], created=1756455142, model='gpt-4.1-nano-2025-04-14', object='chat.completion', service_tier='default', system_fingerprint='fp_c4c155951e', usage=CompletionUsage(completion_tokens=8, prompt_tokens=14, total_tokens=22, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))\n", "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", "print(response.choices[0].message.content)\n" ] }, { "cell_type": "code", "execution_count": 9, "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": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "If three people can paint three walls in three hours, how many people are needed to paint 18 walls in six hours?\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": 11, "metadata": {}, "outputs": [], "source": [ "# form a new messages list\n", "messages = [{\"role\": \"user\", \"content\": question}]\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Let's analyze the problem step-by-step:\n", "\n", "---\n", "\n", "**Given:**\n", "\n", "- 3 people can paint 3 walls in 3 hours.\n", "\n", "**Question:**\n", "\n", "- How many people are needed to paint 18 walls in 6 hours?\n", "\n", "---\n", "\n", "### Step 1: Find the rate of painting per person\n", "\n", "- Total walls painted: 3 walls\n", "- Total people: 3 people\n", "- Total time: 3 hours\n", "\n", "**Walls per person per hour:**\n", "\n", "First, find how many walls 3 people paint per hour:\n", "\n", "\\[\n", "\\frac{3 \\text{ walls}}{3 \\text{ hours}} = 1 \\text{ wall per hour by 3 people}\n", "\\]\n", "\n", "So, 3 people paint 1 wall per hour.\n", "\n", "Then, walls per person per hour:\n", "\n", "\\[\n", "\\frac{1 \\text{ wall per hour}}{3 \\text{ people}} = \\frac{1}{3} \\text{ wall per person per hour}\n", "\\]\n", "\n", "---\n", "\n", "### Step 2: Calculate total work needed\n", "\n", "You want to paint 18 walls in 6 hours.\n", "\n", "This means the rate of painting must be:\n", "\n", "\\[\n", "\\frac{18 \\text{ walls}}{6 \\text{ hours}} = 3 \\text{ walls per hour}\n", "\\]\n", "\n", "---\n", "\n", "### Step 3: Find how many people are needed for this rate\n", "\n", "Since each person paints \\(\\frac{1}{3}\\) wall per hour,\n", "\n", "\\[\n", "\\text{Number of people} \\times \\frac{1}{3} = 3 \\text{ walls per hour}\n", "\\]\n", "\n", "Multiply both sides by 3:\n", "\n", "\\[\n", "\\text{Number of people} = 3 \\times 3 = 9\n", "\\]\n", "\n", "---\n", "\n", "### **Answer:**\n", "\n", "\\[\n", "\\boxed{9}\n", "\\]\n", "\n", "You need **9 people** to paint 18 walls in 6 hours.\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": 13, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "Let's analyze the problem step-by-step:\n", "\n", "---\n", "\n", "**Given:**\n", "\n", "- 3 people can paint 3 walls in 3 hours.\n", "\n", "**Question:**\n", "\n", "- How many people are needed to paint 18 walls in 6 hours?\n", "\n", "---\n", "\n", "### Step 1: Find the rate of painting per person\n", "\n", "- Total walls painted: 3 walls\n", "- Total people: 3 people\n", "- Total time: 3 hours\n", "\n", "**Walls per person per hour:**\n", "\n", "First, find how many walls 3 people paint per hour:\n", "\n", "\\[\n", "\\frac{3 \\text{ walls}}{3 \\text{ hours}} = 1 \\text{ wall per hour by 3 people}\n", "\\]\n", "\n", "So, 3 people paint 1 wall per hour.\n", "\n", "Then, walls per person per hour:\n", "\n", "\\[\n", "\\frac{1 \\text{ wall per hour}}{3 \\text{ people}} = \\frac{1}{3} \\text{ wall per person per hour}\n", "\\]\n", "\n", "---\n", "\n", "### Step 2: Calculate total work needed\n", "\n", "You want to paint 18 walls in 6 hours.\n", "\n", "This means the rate of painting must be:\n", "\n", "\\[\n", "\\frac{18 \\text{ walls}}{6 \\text{ hours}} = 3 \\text{ walls per hour}\n", "\\]\n", "\n", "---\n", "\n", "### Step 3: Find how many people are needed for this rate\n", "\n", "Since each person paints \\(\\frac{1}{3}\\) wall per hour,\n", "\n", "\\[\n", "\\text{Number of people} \\times \\frac{1}{3} = 3 \\text{ walls per hour}\n", "\\]\n", "\n", "Multiply both sides by 3:\n", "\n", "\\[\n", "\\text{Number of people} = 3 \\times 3 = 9\n", "\\]\n", "\n", "---\n", "\n", "### **Answer:**\n", "\n", "\\[\n", "\\boxed{9}\n", "\\]\n", "\n", "You need **9 people** to paint 18 walls in 6 hours." ], "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": 16, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "Certainly! Building on your outlined pain-point and the high-level Agentic AI functionalities, here’s a detailed proposal for an **Agentic AI solution** designed to tackle fragmented patient data and enable real-time, holistic health management.\n", "\n", "---\n", "\n", "# Agentic AI Solution Proposal: **HealthSynth AI**\n", "\n", "### Overview \n", "**HealthSynth AI** is an autonomous health management agent that continuously synthesizes fragmented patient data from multiple sources to provide a real-time, unified, and actionable health profile for patients and their care teams. It acts as a 24/7 health assistant, proactive coordinator, and personalized medical advisor.\n", "\n", "---\n", "\n", "## Key Features & Capabilities\n", "\n", "### 1. **Autonomous Data Aggregation & Normalization** \n", "- Uses API integrations, secure data exchanges (FHIR, HL7 standards), and device SDKs to continuously fetch data from: \n", " - EHR systems across different providers \n", " - Wearable and home medical devices (heart rate, glucose monitors, BP cuffs) \n", " - Pharmacy records and prescription databases \n", " - Lab results portals \n", " - Insurance claims and coverage data \n", "- Applies intelligent data cleaning, deduplication, and semantic normalization to unify heterogeneous data formats into a consistent patient health graph.\n", "\n", "### 2. **Real-Time Multimodal Health Analytics Engine** \n", "- Employs advanced ML and deep learning models to detect: \n", " - Emerging risk patterns (e.g., early signs of infection, deterioration of chronic conditions) \n", " - Anomalies (missed medications, unusual vital sign changes) \n", " - Compliance gaps (lifestyle, medication adherence) \n", "- Continuously updates predictive health trajectories personalized to each patient’s condition and history.\n", "\n", "### 3. **Proactive Action & Recommendation System** \n", "- Generates context-aware, evidence-based alerts and recommendations such as: \n", " - Medication reminders or dosage adjustments flagged in consultation with prescribing physicians \n", " - Suggestions for scheduling lab tests or specialist visits timely before symptoms worsen \n", " - Lifestyle coaching tips adapted using patient preferences and progress \n", "- Classes recommendations into urgency tiers (info, caution, immediate action) and routes notifications appropriately.\n", "\n", "### 4. **Automated Care Coordination & Workflow Integration** \n", "- Interacts programmatically with provider scheduling systems, telemedicine platforms, pharmacies, and insurance portals to: \n", " - Automatically request appointment reschedules or referrals based on patient status \n", " - Notify involved healthcare professionals about critical health events or lab results \n", " - Facilitate prescription renewals or modifications with minimal human intervention \n", "- Maintains secure, auditable communication logs ensuring compliance (HIPAA, GDPR).\n", "\n", "### 5. **Patient-Centric Digital Health Companion** \n", "- Provides patients with an intuitive mobile/web app featuring: \n", " - A dynamic health dashboard summarizing key metrics, risks, and recent activities in plain language \n", " - Intelligent daily check-ins and symptom trackers powered by conversational AI \n", " - Adaptive educational content tailored to health literacy levels and language preferences \n", " - Privacy controls empowering patients to manage data sharing settings\n", "\n", "---\n", "\n", "## Technical Architecture (High-Level)\n", "\n", "- **Data Ingestion Layer:** Connectors for EHRs, wearables, pharmacies, labs \n", "- **Data Lake & Processing:** Cloud-native secure storage with HIPAA-compliant encryption \n", "- **Knowledge Graph:** Patient-centric semantic graph linking clinical concepts, timelines, interventions \n", "- **Analytics & ML Models:** Ensemble predictive models incorporating temporal health data, risk scoring, anomaly detection \n", "- **Agentic Orchestrator:** Rule-based and reinforcement learning-driven workflow engine enabling autonomous decision-making and stakeholder communications \n", "- **Frontend Interfaces:** Responsive patient app, provider portals, API access for system integration\n", "\n", "---\n", "\n", "## Potential Challenges & Mitigations\n", "\n", "| Challenge | Mitigation Strategy |\n", "|-----------|---------------------|\n", "| Data privacy & regulatory compliance | Built-in privacy-by-design, end-to-end encryption, rigorous consent management, audit trails |\n", "| Data interoperability & standardization | Utilize open standards (FHIR, DICOM), NLP for unstructured data extraction |\n", "| Model explainability | Implement interpretable ML techniques and transparent reasoning for clinicians |\n", "| Patient engagement sustainability | Gamification, behavior science-driven personalized nudges |\n", "| Integration complexity across healthcare IT systems | Modular adaptors/plugins, partnerships with major EHR vendors |\n", "\n", "---\n", "\n", "## Impact & Benefits\n", "\n", "- **For Patients:** Reduced health risks, increased empowerment, improved treatment adherence, and personal convenience \n", "- **For Providers:** Enhanced clinical decision support, reduced administrative burden, timely interventions \n", "- **For Payers:** Lowered costs via preventive care and reduced hospital readmissions\n", "\n", "---\n", "\n", "Would you like me to help you design detailed user journeys, develop specific ML model architectures, or draft an implementation roadmap for **HealthSynth AI**?" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# First create the messages:\n", "\n", "messages = [{\"role\": \"user\", \"content\": \"I want you to 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-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", "messages = [{\"role\": \"user\", \"content\": f\"Please propose a pain-point in the {business_idea} industry.\"}]\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4.1-mini\",\n", " messages=messages\n", ")\n", "\n", "pain_point = response.choices[0].message.content\n", "\n", "messages = [{\"role\": \"user\", \"content\": f\"Please propose an Agentic AI solution to the pain-point: {pain_point}.\"}]\n", "\n", "response = openai.chat.completions.create(\n", " model=\"gpt-4.1-mini\",\n", " messages=messages\n", ")\n", "\n", "agentic_solution = response.choices[0].message.content\n", "\n", "display(Markdown(agentic_solution))\n", "\n", "# And repeat! In the next message, include the business idea within the message" ] }, { "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.11" } }, "nbformat": 4, "nbformat_minor": 2 }