{ "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": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Important point - please read

\n", " 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, after watching the lecture. Add print statements to understand what's going on, and then come up with your own variations.

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", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Exercise

\n", " Which pattern(s) did this use? Try updating this to add another Agentic design pattern.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ReAct Pattern" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import openai\n", "import os\n", "from dotenv import load_dotenv\n", "import io\n", "from anthropic import Anthropic\n", "from IPython.display import Markdown, display" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OpenAI API Key exists and begins sk-proj-\n", "Anthropic API Key exists and begins sk-ant-\n", "Google API Key exists and begins AI\n", "DeepSeek API Key exists and begins sk-\n", "Groq API Key exists and begins gsk_\n" ] } ], "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": 3, "metadata": {}, "outputs": [], "source": [ "\n", "from openai import OpenAI\n", "\n", "openai = OpenAI()\n", "\n", "# Request prompt\n", "request = (\n", " \"Please come up with a challenging, nuanced question that I can ask a number of LLMs to evaluate their intelligence. \"\n", " \"Answer only with the question, no explanation.\"\n", ")\n", "\n", "\n", "\n", "def generate_question(prompt: str) -> str:\n", " response = openai.chat.completions.create(\n", " model='gpt-4o-mini',\n", " messages=[{'role': 'user', 'content': prompt}]\n", " )\n", " question = response.choices[0].message.content\n", " return question\n", "\n", "def react_agent_decide_model(question: str) -> str:\n", " prompt = f\"\"\"\n", " You are an intelligent AI assistant tasked with evaluating which language model is most suitable to answer a given question.\n", "\n", " Available models:\n", " - OpenAI: excels at reasoning and factual answers.\n", " - Claude: better for philosophical, nuanced, and ethical topics.\n", " - Gemini: good for concise and structured summaries.\n", " - Groq: good for creative or exploratory tasks.\n", " - DeepSeek: strong at coding, technical reasoning, and multilingual responses.\n", "\n", " Here is the question to answer:\n", " \"{question}\"\n", "\n", " ### Thought:\n", " Which model is best suited to answer this question, and why?\n", "\n", " ### Action:\n", " Respond with only the model name you choose (e.g., \"Claude\").\n", " \"\"\"\n", "\n", " response = openai.chat.completions.create(\n", " model=\"o3-mini\",\n", " messages=[{\"role\": \"user\", \"content\": prompt}]\n", " )\n", " model = response.choices[0].message.content.strip()\n", " return model\n", "\n", "def generate_answer_openai(prompt):\n", " answer = openai.chat.completions.create(\n", " model='gpt-4o-mini',\n", " messages=[{'role': 'user', 'content': prompt}]\n", " ).choices[0].message.content\n", " return answer\n", "\n", "def generate_answer_anthropic(prompt):\n", " anthropic = Anthropic(api_key=anthropic_api_key)\n", " model_name = \"claude-3-5-sonnet-20240620\"\n", " answer = anthropic.messages.create(\n", " model=model_name,\n", " messages=[{'role': 'user', 'content': prompt}],\n", " max_tokens=1000\n", " ).content[0].text\n", " return answer\n", "\n", "def generate_answer_deepseek(prompt):\n", " deepseek = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com/v1\")\n", " model_name = \"deepseek-chat\" \n", " answer = deepseek.chat.completions.create(\n", " model=model_name,\n", " messages=[{'role': 'user', 'content': prompt}],\n", " base_url='https://api.deepseek.com/v1'\n", " ).choices[0].message.content\n", " return answer\n", "\n", "def generate_answer_gemini(prompt):\n", " gemini=OpenAI(base_url='https://generativelanguage.googleapis.com/v1beta/openai/',api_key=google_api_key)\n", " model_name = \"gemini-2.0-flash\"\n", " answer = gemini.chat.completions.create(\n", " model=model_name,\n", " messages=[{'role': 'user', 'content': prompt}],\n", " ).choices[0].message.content\n", " return answer\n", "\n", "def generate_answer_groq(prompt):\n", " groq=OpenAI(base_url='https://api.groq.com/openai/v1',api_key=groq_api_key)\n", " model_name=\"llama3-70b-8192\"\n", " answer = groq.chat.completions.create(\n", " model=model_name,\n", " messages=[{'role': 'user', 'content': prompt}],\n", " base_url=\"https://api.groq.com/openai/v1\"\n", " ).choices[0].message.content\n", " return answer\n", "\n", "def main():\n", " print(\"Generating question...\")\n", " question = generate_question(request)\n", " print(f\"\\n🧠 Question: {question}\\n\")\n", " selected_model = react_agent_decide_model(question)\n", " print(f\"\\nšŸ”¹ {selected_model}:\\n\")\n", " \n", " if selected_model.lower() == \"openai\":\n", " answer = generate_answer_openai(question)\n", " elif selected_model.lower() == \"deepseek\":\n", " answer = generate_answer_deepseek(question)\n", " elif selected_model.lower() == \"gemini\":\n", " answer = generate_answer_gemini(question)\n", " elif selected_model.lower() == \"groq\":\n", " answer = generate_answer_groq(question)\n", " elif selected_model.lower() == \"claude\":\n", " answer = generate_answer_anthropic(question)\n", " print(f\"\\nšŸ”¹ {selected_model}:\\n{answer}\\n\")\n", " \n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Generating question...\n", "\n", "🧠 Question: How would you reconcile the apparent tension between utilitarian ethical theories that prioritize the greatest good for the greatest number and deontological ethical theories that emphasize individual rights and duties, especially in scenarios involving resource allocation in healthcare?\n", "\n", "\n", "šŸ”¹ Claude:\n", "\n", "\n", "šŸ”¹ Claude:\n", "Reconciling utilitarian and deontological ethical theories, especially in the context of healthcare resource allocation, is a complex challenge that has occupied philosophers and ethicists for centuries. Both approaches offer valuable insights, but they can lead to conflicting conclusions in many scenarios. To address this tension, I believe we need to consider a nuanced approach that incorporates elements of both theories while acknowledging their limitations.\n", "\n", "Utilitarian theories, which prioritize the greatest good for the greatest number, have the advantage of focusing on outcomes and attempting to maximize overall welfare. In healthcare, this could translate to allocating resources in a way that saves the most lives or provides the greatest improvement in quality of life across the population. This approach can be particularly compelling in emergency situations or when dealing with limited resources.\n", "\n", "Deontological theories, on the other hand, emphasize individual rights, duties, and the inherent dignity of each person. In healthcare, this might manifest as a commitment to treating each patient with equal respect and consideration, regardless of the overall outcome. This approach helps protect vulnerable individuals and minority groups who might be disadvantaged by purely utilitarian calculations.\n", "\n", "To reconcile these approaches, I propose a framework that incorporates elements of both theories:\n", "\n", "1. Establish a baseline of individual rights: Begin by acknowledging fundamental individual rights in healthcare, such as the right to emergency treatment, informed consent, and non-discrimination. This sets a deontological foundation that cannot be violated even in pursuit of utilitarian goals.\n", "\n", "2. Utilize utilitarian calculations within ethical constraints: Once baseline rights are established, employ utilitarian thinking to maximize overall welfare within those constraints. This allows for efficient resource allocation while still respecting individual dignity.\n", "\n", "3. Implement a threshold approach: Set minimum thresholds for treatment and care that apply to all individuals, based on deontological principles. Beyond these thresholds, utilize more utilitarian calculations to distribute additional resources.\n", "\n", "4. Consider long-term consequences: When making decisions, factor in long-term societal impacts. A purely utilitarian approach might sacrifice individual rights for short-term gains, but this could erode trust in the healthcare system and lead to worse outcomes over time.\n", "\n", "5. Employ procedural justice: Ensure that decision-making processes are fair, transparent, and inclusive. This can help bridge the gap between utilitarian outcomes and deontological concerns about individual rights and dignity.\n", "\n", "6. Contextualize decisions: Recognize that the balance between utilitarian and deontological considerations may shift depending on the specific context (e.g., emergency triage vs. long-term care planning).\n", "\n", "7. Incorporate other ethical frameworks: Draw insights from other ethical theories, such as virtue ethics or care ethics, to provide a more holistic approach to decision-making.\n", "\n", "8. Regular ethical review: Implement systems for ongoing ethical review and adjustment of policies to ensure they remain aligned with evolving societal values and medical capabilities.\n", "\n", "An example of how this framework might be applied in practice is the allocation of organ transplants. A baseline right to be considered for transplantation could be established for all eligible patients (deontological). Within this group, factors such as medical urgency, likelihood of success, and potential years of life saved could be used to prioritize recipients (utilitarian). A threshold approach could ensure that patients below a certain health status receive priority, while additional organs are allocated based on maximizing overall benefit.\n", "\n", "This approach is not without challenges. Determining the appropriate balance between utilitarian and deontological considerations will often involve difficult value judgments. Moreover, there may still be scenarios where the two ethical frameworks come into irreconcilable conflict.\n", "\n", "However, by acknowledging the strengths and limitations of both utilitarian and deontological theories, and by seeking to incorporate elements of each in a thoughtful and context-sensitive manner, we can work towards a more comprehensive and nuanced approach to healthcare ethics. This approach can help us navigate the complex terrain of resource allocation while striving to respect both individual rights and the greater good.\n", "\n" ] } ], "source": [ "main()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Commercial implications

\n", " These kinds of patterns - to send a task to multiple models, and evaluate results,\n", " are 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", " \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.2" } }, "nbformat": 4, "nbformat_minor": 2 }