Spaces:
Running
Running
File size: 16,868 Bytes
fb856e1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
{
"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": "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": [
"# 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": [
"<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",
" 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",
" </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.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|