{ "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": "code", "execution_count": 6, "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": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Always remember to do this!\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OpenAI API Key exists and begins sk-proj-\n", "Anthropic API Key not set (and this is optional)\n", "Google API Key exists and begins AI\n", "DeepSeek API Key not set (and this is optional)\n", "Groq API Key not set (and this is optional)\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": 10, "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": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'role': 'user',\n", " 'content': 'Please come up with a challenging, nuanced question that I can ask a number of LLMs to evaluate their intelligence. Answer only with the question, no explanation.'}]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "messages" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "If you had to design a new ethical framework for AI decision-making that prioritizes both individual rights and collective well-being, what core principles would you include, and how would you address potential conflicts between those principles?\n" ] } ], "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": 13, "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 ` downloads a model locally \n", "`ollama ls` lists all the models you've downloaded \n", "`ollama rm ` deletes the specified model from your downloads" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Super important - ignore me at your peril!

\n", " The model called llama3.3 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 llama3.2 or llama3.2:1b and if you want larger, try llama3.1 or smaller variants of Qwen, Gemma, Phi or DeepSeek. See the the Ollama models page for a full list of models and sizes.\n", " \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": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['gpt-4o-mini', 'gemini-2.0-flash', 'llama3.2']\n", "[\"Designing an ethical framework for AI decision-making that balances individual rights and collective well-being is a complex and vital task. Below are core principles that could guide this framework, along with suggestions for addressing potential conflicts between them:\\n\\n### Core Principles\\n\\n1. **Autonomy and Respect for Individual Rights**: \\n - AI systems should respect individuals' rights to privacy, consent, and self-determination. Users should have control over their data and the decisions that affect their lives.\\n \\n2. **Transparency and Explainability**: \\n - AI decision-making processes should be transparent. Users should have access to clear explanations regarding how decisions are made, the data used, and the algorithms applied. This builds trust and facilitates informed consent.\\n\\n3. **Beneficence and Non-Maleficence**: \\n - AI systems should prioritize promoting well-being and preventing harm, both at the individual and collective levels. This involves assessing the potential positive and negative impacts of AI decisions on both fronts.\\n\\n4. **Justice and Fairness**: \\n - AI systems must be fair, seeking to eliminate bias and discrimination. Both individual and community benefits should be distributed equitably, ensuring that marginalized groups are not disproportionately harmed.\\n\\n5. **Accountability and Responsibility**: \\n - There must be clear lines of accountability for AI decisions, ensuring that human oversight is maintained. Stakeholders, including developers and users, should be answerable for the outcomes of AI systems.\\n\\n6. **Sustainability and Long-Term Considerations**: \\n - AI should be designed and implemented in ways that consider long-term impacts on society, the environment, and future generations, ensuring that collective well-being is maintained.\\n\\n7. **Participatory Design and Engagement**: \\n - Engaging diverse stakeholders in the design and deployment of AI systems ensures that multiple perspectives are considered. This can help in identifying potential conflicts between individual rights and collective well-being.\\n\\n### Addressing Conflicts Between Principles\\n\\nConflicts may arise between individual rights and collective well-being, and the following strategies can help manage these tensions:\\n\\n1. **Prioritization of Principles**: \\n - Establish a hierarchy of principles to guide decision-making. For example, individual rights might take precedence in cases involving personal data privacy, while collective well-being might be prioritized in public health scenarios.\\n\\n2. **Contextual Analysis**: \\n - Assess the specific context of each decision. Situational factors can influence how principles should be applied, potentially leading to different outcomes based on the context of use.\\n\\n3. **Multi-Stakeholder Dialogues**: \\n - Facilitate discussions among diverse stakeholders to address conflicts. Engaging users, ethicists, developers, and policy-makers can lead to more equitable solutions that reflect a consensus on values.\\n\\n4. **Iterative Feedback Mechanisms**: \\n - Implement systems that allow for continuous evaluation and adjustment of AI decisions based on real-world outcomes. Feedback loops can help identify and rectify conflicts as they arise.\\n\\n5. **Scenario Planning**: \\n - Utilize predictive modeling and scenario analysis to foresee potential conflicts between principles, allowing for proactive measures to mitigate adverse effects.\\n\\n6. **Ethical Oversight Committees**: \\n - Establish independent review boards to oversee AI systems, ensuring that ethical considerations are adhered to and providing an additional layer of accountability.\\n\\nBy adhering to these core principles and implementing approaches to address conflicts, the ethical framework for AI decision-making can strive to balance the rights of individuals with the well-being of society as a whole. This encompasses a commitment to evolving our understanding of ethics as technology advances and societal values shift.\", 'Okay, here\\'s an outline of a new ethical framework for AI decision-making, designed to balance individual rights and collective well-being, along with strategies for resolving potential conflicts:\\n\\n**Framework Name:** \"Harmony AI\" (or similar evocative name)\\n\\n**I. Core Principles:**\\n\\n1. **Respect for Human Dignity and Autonomy:**\\n * **Description:** Every individual interacting with or affected by an AI system has inherent worth and the right to make informed choices about their lives. This includes the right to privacy, freedom of expression, and protection from manipulation.\\n * **Operationalization:**\\n * AI systems must be designed to be transparent about their capabilities, limitations, and potential biases.\\n * Individuals should have control over their data and the ability to opt-out of AI-driven processes where feasible.\\n * AI systems should not be used to coerce or exploit individuals.\\n * Accessibility should be a core design principle to ensure equal access and benefit for diverse users (e.g., language, disability, age).\\n\\n2. **Beneficence and Non-Maleficence (Do Good, Do No Harm):**\\n * **Description:** AI should be used to promote well-being, reduce suffering, and avoid causing harm to individuals, groups, or the environment.\\n * **Operationalization:**\\n * Rigorous impact assessments are mandatory before deploying AI systems, considering potential social, economic, and environmental consequences.\\n * AI systems must be designed to be robust, reliable, and safe, with mechanisms for monitoring and mitigating unintended consequences.\\n * Prioritize AI applications that address pressing societal challenges such as healthcare, education, and poverty alleviation.\\n * Implement \"kill switches\" or fail-safe mechanisms to shut down or redirect AI systems that pose an imminent threat.\\n\\n3. **Justice and Fairness:**\\n * **Description:** AI systems should be designed and deployed in a way that ensures equitable outcomes and avoids perpetuating or exacerbating existing inequalities. This includes distributive justice (fair allocation of resources and opportunities), procedural justice (fair decision-making processes), and corrective justice (redress for harms).\\n * **Operationalization:**\\n * Data used to train AI systems must be representative and free from discriminatory biases.\\n * AI algorithms should be regularly audited for fairness and accuracy across different demographic groups.\\n * AI-driven decisions should be transparent and explainable, allowing individuals to understand the reasoning behind them and challenge unfair outcomes.\\n * Consideration of historical disadvantages and structural inequalities in designing AI solutions (e.g., affirmative action principles where appropriate).\\n\\n4. **Collective Well-being and Sustainability:**\\n * **Description:** AI should be used to promote the common good, support sustainable development, and protect the environment for current and future generations.\\n * **Operationalization:**\\n * Prioritize AI applications that address global challenges such as climate change, pandemics, and resource scarcity.\\n * Promote the responsible development and use of AI in areas such as healthcare, education, and infrastructure.\\n * Ensure that AI systems are energy-efficient and minimize their environmental impact.\\n * Foster international cooperation on AI governance and ethical standards.\\n * Long-term, consider the potential existential risks posed by advanced AI and develop safeguards to mitigate them.\\n\\n5. **Transparency, Accountability, and Explainability:**\\n * **Description:** AI systems should be transparent about their functionality and decision-making processes, and those responsible for their design, deployment, and use should be held accountable for their impacts. Explainability (the ability to understand *why* an AI made a particular decision) is crucial.\\n * **Operationalization:**\\n * Develop clear standards for AI explainability, requiring AI systems to provide justifications for their decisions that are understandable to non-experts. This may involve techniques like SHAP values, LIME, or other explainable AI (XAI) methods.\\n * Establish independent oversight bodies to monitor and regulate AI development and deployment.\\n * Implement robust mechanisms for auditing AI systems and identifying and addressing biases and errors.\\n * Develop clear legal frameworks that assign liability for harm caused by AI systems.\\n * Promote open-source AI development to encourage transparency and collaboration.\\n\\n6. **Continuous Learning and Adaptation:**\\n * **Description:** Ethical frameworks for AI must be dynamic and adaptable to evolving technologies and societal values. This requires ongoing monitoring, evaluation, and refinement of ethical principles and guidelines.\\n * **Operationalization:**\\n * Establish mechanisms for gathering feedback from stakeholders and incorporating it into the design and deployment of AI systems.\\n * Promote interdisciplinary research on the ethical, legal, and social implications of AI.\\n * Foster public dialogue and debate about the ethical challenges posed by AI.\\n * Regularly review and update ethical guidelines and regulations to reflect advances in AI technology and changes in societal values. Embrace agile governance approaches.\\n\\n**II. Addressing Conflicts Between Principles:**\\n\\nConflicts between individual rights and collective well-being are inevitable. The following strategies can help to resolve them:\\n\\n1. **Proportionality:**\\n * Any restriction on individual rights in the name of collective well-being must be proportionate to the threat or benefit. The least restrictive means necessary should be used. Is the benefit to society significant enough to justify the infringement on an individual\\'s right?\\n\\n2. **Necessity:**\\n * The restriction on individual rights must be necessary to achieve the desired outcome. Are there alternative solutions that would not infringe on individual rights?\\n\\n3. **Transparency and Public Justification:**\\n * Any decision that prioritizes collective well-being over individual rights must be transparent and justified to the public. The rationale for the decision should be clearly explained, and stakeholders should have the opportunity to provide feedback.\\n\\n4. **Due Process and Redress:**\\n * Individuals who are negatively affected by AI-driven decisions should have access to due process and redress. This includes the right to appeal decisions, seek compensation for harm, and challenge the validity of the AI system.\\n\\n5. **Deliberative Processes and Stakeholder Engagement:**\\n * Engage in inclusive and deliberative processes to weigh competing values and interests. Involve stakeholders from diverse backgrounds in the development and implementation of AI policies. This includes ethicists, legal experts, technologists, policymakers, and members of the public. Citizen assemblies or similar participatory mechanisms can be valuable.\\n\\n6. **Prioritization Framework:**\\n * Develop a framework for prioritizing ethical considerations in specific contexts. This framework should identify the core values that are most relevant to the situation and provide guidance on how to balance competing interests. For example, in healthcare settings, the principle of beneficence (doing good) may take precedence over the principle of autonomy in certain situations (e.g., emergency care). However, these prioritizations should be carefully considered and justified.\\n\\n7. **Context-Specific Considerations:**\\n * Recognize that ethical considerations can vary depending on the context. A solution that is appropriate in one setting may not be appropriate in another. For example, the use of facial recognition technology may be more acceptable in high-security environments than in public spaces.\\n\\n8. **Sunset Clauses and Regular Review:**\\n * Implement sunset clauses for AI systems that restrict individual rights. This ensures that these systems are regularly reviewed and re-evaluated to determine whether they are still necessary and proportionate.\\n\\n9. **Insurance and Compensation Mechanisms:**\\n * Explore the use of insurance and compensation mechanisms to provide redress to individuals who are harmed by AI systems. This can help to mitigate the negative consequences of AI and promote accountability.\\n\\n10. **\"Ethics by Design\" and \"Value Sensitive Design\":** Incorporate ethical considerations from the very beginning of the AI development process. Use frameworks like \"Value Sensitive Design\" to proactively identify and address potential ethical issues.\\n\\n**III. Example Scenarios & Application of the Framework:**\\n\\nLet\\'s consider a few examples:\\n\\n* **Scenario 1: AI-Powered Predictive Policing:** An AI system is used to predict crime hotspots and allocate police resources. This could infringe on individual rights to privacy and freedom of movement if it leads to disproportionate surveillance of certain communities.\\n * **Application of Harmony AI:**\\n * Transparency: The AI system\\'s algorithms and data sources must be transparent and subject to independent audit.\\n * Fairness: Data used to train the AI system must be carefully vetted for bias.\\n * Proportionality: The use of AI-powered policing must be proportionate to the actual crime rate in the areas being targeted.\\n * Due Process: Individuals who are stopped or questioned based on AI predictions must be treated with respect and have access to due process.\\n * Explainability: Police officers must be able to explain the basis for their actions.\\n\\n* **Scenario 2: AI-Driven Healthcare Diagnosis:** An AI system is used to diagnose medical conditions. This could lead to inaccurate diagnoses or biased treatment if the system is not properly designed and validated.\\n * **Application of Harmony AI:**\\n * Beneficence & Non-Maleficence: The AI system must be rigorously tested and validated to ensure its accuracy and safety.\\n * Transparency & Explainability: Doctors must be able to understand the AI system\\'s reasoning and explain it to patients.\\n * Autonomy: Patients must have the right to seek a second opinion and make their own healthcare decisions.\\n * Justice: The AI system must be designed to be fair and equitable across different demographic groups.\\n\\n* **Scenario 3: AI-Powered Job Recruitment:** An AI system is used to screen job applicants. This could perpetuate existing biases and limit opportunities for underrepresented groups.\\n * **Application of Harmony AI:**\\n * Fairness: Algorithms and training data must be audited and adjusted to prevent biased outcomes.\\n * Transparency: Candidates should understand how the AI system is evaluating their application.\\n * Autonomy: Candidates should have the right to human review if they are rejected by the AI system.\\n * Beneficence: The system should aim to identify candidates with the potential to succeed, not just those who fit a narrow profile.\\n\\n**IV. Key Considerations for Implementation:**\\n\\n* **Education and Training:** Educate developers, policymakers, and the public about the ethical implications of AI.\\n* **International Cooperation:** Foster international collaboration on AI governance and ethical standards.\\n* **Enforcement Mechanisms:** Develop effective enforcement mechanisms to ensure compliance with ethical guidelines and regulations.\\n* **Continuous Monitoring and Evaluation:** Regularly monitor and evaluate the impact of AI systems and adapt ethical frameworks as needed.\\n\\nThis \"Harmony AI\" framework provides a starting point for developing more comprehensive and context-specific ethical guidelines for AI decision-making. The key is to prioritize human dignity, promote well-being, and ensure fairness, while remaining flexible and adaptable to the evolving landscape of AI technology.\\n', \"Designing an ethical framework for AI decision-making that balances individual rights with collective well-being is crucial to ensure AI systems are fair, transparent, and beneficial to society. Here's a proposed core set of principles:\\n\\nCore Principles:\\n\\n1. **Respect for Individual Autonomy**: Ensure that AI decisions respect individuals' autonomy, dignity, and freedom from coercion or manipulation. This includes protecting individual rights to privacy, consent, and the ability to make informed choices.\\n2. **Promoting Fairness and Non-Discrimination**: Implement mechanisms to prevent AI biases and ensure fairness in decision-making processes. This includes avoiding discrimination based on race, gender, religion, sexual orientation, age, disability, or other protected characteristics.\\n3. **Coluntary Transparency and Explainability**: Ensure that AI decisions are transparent, explainable, and provide context for human review and audit. This enables informed understanding of AI-driven outcomes and mitigates potential biases.\\n4. **Human Oversight and Control**: Limit AI decision-making to well-defined, specific domains where the benefits outweigh the risks. Human oversight and control ensure accountability when AI decisions conflict with individual rights or collective well-being.\\n5. **Safety and Vulnerability Protection**: Implement measures to safeguard vulnerable populations from AI-driven harm, including protection against algorithmic profiling and data misuse.\\n6. **Inclusive Value Alignment**: Incorporate stakeholders' values and interests into the development process, promoting inclusivity, diversity, and stakeholder engagement.\\n\\nAddressing Potential Conflicts:\\n\\n1. **Multi-Operator Framework**: Introduce multi-operator decision-making frameworks that engage multiple stakeholders, including human experts, algorithmic experts, and representative communities. This fosters a collaborative environment to resolve conflicts.\\n2. **Conflict Resolution Mechanisms**: Develop robust conflict resolution mechanisms, such as appeal systems or grievance procedures, to address disagreements between AI-driven decisions and individual rights or collective well-being.\\n3. **Value-Based Co-Design**: Implement value-based co-design processes where diverse stakeholders collaborate on defining algorithmic objectives in line with shared moral compasses.\\n4. **Human-AI Hybrid Modeling**: Utilize human-AI hybrid modeling approaches that leverage the strengths of both humans and AI systems, ensuring human judgment is embedded within decision-making processes.\\n5. **Regulatory Efficacy and Oversight**: Develop regulatory frameworks that promote effective governance over AI deployment, enabling accountability mechanisms to mitigate conflicts.\\n6. **Hybrid Feedback Loops**: Establish dynamic feedback loops between AI decision-makers and human stakeholders, allowing for ongoing assessment of system performance, identification of shortcomings, and continuous improvement.\\n\\nPotential Conflict Resolution Strategies:\\n\\n1. Human intervention in the decision-making process\\n2. Use of explainable AI techniques such as feature attribution or model interpretability to identify biases\\n3. Development of value-based AI systems that can dynamically adjust objectives to align with user preferences\\n4. Collaboration between humans, machines, and representatives from impacted communities to provide contextual input for decision-making\\n\\nImplementing this framework requires a multidisciplinary approach, involving experts in computer science, ethics, philosophy, sociology, law, and more. The effectiveness of the framework relies on continuous monitoring, evaluation, and improvement, as AI systems evolve and interact with society.\"]\n" ] } ], "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": 36, "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": 38, "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\", ...], \"reason\": \"...\"}}\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": 39, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "You are judging a competition between 3 competitors.\n", "Each model has been given this question:\n", "\n", "If you had to design a new ethical framework for AI decision-making that prioritizes both individual rights and collective well-being, what core principles would you include, and how would you address potential conflicts between those principles?\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\", ...], \"reason\": \"...\"}\n", "\n", "Here are the responses from each competitor:\n", "\n", "# Response from competitor 1\n", "\n", "Designing an ethical framework for AI decision-making that balances individual rights and collective well-being is a complex and vital task. Below are core principles that could guide this framework, along with suggestions for addressing potential conflicts between them:\n", "\n", "### Core Principles\n", "\n", "1. **Autonomy and Respect for Individual Rights**: \n", " - AI systems should respect individuals' rights to privacy, consent, and self-determination. Users should have control over their data and the decisions that affect their lives.\n", " \n", "2. **Transparency and Explainability**: \n", " - AI decision-making processes should be transparent. Users should have access to clear explanations regarding how decisions are made, the data used, and the algorithms applied. This builds trust and facilitates informed consent.\n", "\n", "3. **Beneficence and Non-Maleficence**: \n", " - AI systems should prioritize promoting well-being and preventing harm, both at the individual and collective levels. This involves assessing the potential positive and negative impacts of AI decisions on both fronts.\n", "\n", "4. **Justice and Fairness**: \n", " - AI systems must be fair, seeking to eliminate bias and discrimination. Both individual and community benefits should be distributed equitably, ensuring that marginalized groups are not disproportionately harmed.\n", "\n", "5. **Accountability and Responsibility**: \n", " - There must be clear lines of accountability for AI decisions, ensuring that human oversight is maintained. Stakeholders, including developers and users, should be answerable for the outcomes of AI systems.\n", "\n", "6. **Sustainability and Long-Term Considerations**: \n", " - AI should be designed and implemented in ways that consider long-term impacts on society, the environment, and future generations, ensuring that collective well-being is maintained.\n", "\n", "7. **Participatory Design and Engagement**: \n", " - Engaging diverse stakeholders in the design and deployment of AI systems ensures that multiple perspectives are considered. This can help in identifying potential conflicts between individual rights and collective well-being.\n", "\n", "### Addressing Conflicts Between Principles\n", "\n", "Conflicts may arise between individual rights and collective well-being, and the following strategies can help manage these tensions:\n", "\n", "1. **Prioritization of Principles**: \n", " - Establish a hierarchy of principles to guide decision-making. For example, individual rights might take precedence in cases involving personal data privacy, while collective well-being might be prioritized in public health scenarios.\n", "\n", "2. **Contextual Analysis**: \n", " - Assess the specific context of each decision. Situational factors can influence how principles should be applied, potentially leading to different outcomes based on the context of use.\n", "\n", "3. **Multi-Stakeholder Dialogues**: \n", " - Facilitate discussions among diverse stakeholders to address conflicts. Engaging users, ethicists, developers, and policy-makers can lead to more equitable solutions that reflect a consensus on values.\n", "\n", "4. **Iterative Feedback Mechanisms**: \n", " - Implement systems that allow for continuous evaluation and adjustment of AI decisions based on real-world outcomes. Feedback loops can help identify and rectify conflicts as they arise.\n", "\n", "5. **Scenario Planning**: \n", " - Utilize predictive modeling and scenario analysis to foresee potential conflicts between principles, allowing for proactive measures to mitigate adverse effects.\n", "\n", "6. **Ethical Oversight Committees**: \n", " - Establish independent review boards to oversee AI systems, ensuring that ethical considerations are adhered to and providing an additional layer of accountability.\n", "\n", "By adhering to these core principles and implementing approaches to address conflicts, the ethical framework for AI decision-making can strive to balance the rights of individuals with the well-being of society as a whole. This encompasses a commitment to evolving our understanding of ethics as technology advances and societal values shift.\n", "\n", "# Response from competitor 2\n", "\n", "Okay, here's an outline of a new ethical framework for AI decision-making, designed to balance individual rights and collective well-being, along with strategies for resolving potential conflicts:\n", "\n", "**Framework Name:** \"Harmony AI\" (or similar evocative name)\n", "\n", "**I. Core Principles:**\n", "\n", "1. **Respect for Human Dignity and Autonomy:**\n", " * **Description:** Every individual interacting with or affected by an AI system has inherent worth and the right to make informed choices about their lives. This includes the right to privacy, freedom of expression, and protection from manipulation.\n", " * **Operationalization:**\n", " * AI systems must be designed to be transparent about their capabilities, limitations, and potential biases.\n", " * Individuals should have control over their data and the ability to opt-out of AI-driven processes where feasible.\n", " * AI systems should not be used to coerce or exploit individuals.\n", " * Accessibility should be a core design principle to ensure equal access and benefit for diverse users (e.g., language, disability, age).\n", "\n", "2. **Beneficence and Non-Maleficence (Do Good, Do No Harm):**\n", " * **Description:** AI should be used to promote well-being, reduce suffering, and avoid causing harm to individuals, groups, or the environment.\n", " * **Operationalization:**\n", " * Rigorous impact assessments are mandatory before deploying AI systems, considering potential social, economic, and environmental consequences.\n", " * AI systems must be designed to be robust, reliable, and safe, with mechanisms for monitoring and mitigating unintended consequences.\n", " * Prioritize AI applications that address pressing societal challenges such as healthcare, education, and poverty alleviation.\n", " * Implement \"kill switches\" or fail-safe mechanisms to shut down or redirect AI systems that pose an imminent threat.\n", "\n", "3. **Justice and Fairness:**\n", " * **Description:** AI systems should be designed and deployed in a way that ensures equitable outcomes and avoids perpetuating or exacerbating existing inequalities. This includes distributive justice (fair allocation of resources and opportunities), procedural justice (fair decision-making processes), and corrective justice (redress for harms).\n", " * **Operationalization:**\n", " * Data used to train AI systems must be representative and free from discriminatory biases.\n", " * AI algorithms should be regularly audited for fairness and accuracy across different demographic groups.\n", " * AI-driven decisions should be transparent and explainable, allowing individuals to understand the reasoning behind them and challenge unfair outcomes.\n", " * Consideration of historical disadvantages and structural inequalities in designing AI solutions (e.g., affirmative action principles where appropriate).\n", "\n", "4. **Collective Well-being and Sustainability:**\n", " * **Description:** AI should be used to promote the common good, support sustainable development, and protect the environment for current and future generations.\n", " * **Operationalization:**\n", " * Prioritize AI applications that address global challenges such as climate change, pandemics, and resource scarcity.\n", " * Promote the responsible development and use of AI in areas such as healthcare, education, and infrastructure.\n", " * Ensure that AI systems are energy-efficient and minimize their environmental impact.\n", " * Foster international cooperation on AI governance and ethical standards.\n", " * Long-term, consider the potential existential risks posed by advanced AI and develop safeguards to mitigate them.\n", "\n", "5. **Transparency, Accountability, and Explainability:**\n", " * **Description:** AI systems should be transparent about their functionality and decision-making processes, and those responsible for their design, deployment, and use should be held accountable for their impacts. Explainability (the ability to understand *why* an AI made a particular decision) is crucial.\n", " * **Operationalization:**\n", " * Develop clear standards for AI explainability, requiring AI systems to provide justifications for their decisions that are understandable to non-experts. This may involve techniques like SHAP values, LIME, or other explainable AI (XAI) methods.\n", " * Establish independent oversight bodies to monitor and regulate AI development and deployment.\n", " * Implement robust mechanisms for auditing AI systems and identifying and addressing biases and errors.\n", " * Develop clear legal frameworks that assign liability for harm caused by AI systems.\n", " * Promote open-source AI development to encourage transparency and collaboration.\n", "\n", "6. **Continuous Learning and Adaptation:**\n", " * **Description:** Ethical frameworks for AI must be dynamic and adaptable to evolving technologies and societal values. This requires ongoing monitoring, evaluation, and refinement of ethical principles and guidelines.\n", " * **Operationalization:**\n", " * Establish mechanisms for gathering feedback from stakeholders and incorporating it into the design and deployment of AI systems.\n", " * Promote interdisciplinary research on the ethical, legal, and social implications of AI.\n", " * Foster public dialogue and debate about the ethical challenges posed by AI.\n", " * Regularly review and update ethical guidelines and regulations to reflect advances in AI technology and changes in societal values. Embrace agile governance approaches.\n", "\n", "**II. Addressing Conflicts Between Principles:**\n", "\n", "Conflicts between individual rights and collective well-being are inevitable. The following strategies can help to resolve them:\n", "\n", "1. **Proportionality:**\n", " * Any restriction on individual rights in the name of collective well-being must be proportionate to the threat or benefit. The least restrictive means necessary should be used. Is the benefit to society significant enough to justify the infringement on an individual's right?\n", "\n", "2. **Necessity:**\n", " * The restriction on individual rights must be necessary to achieve the desired outcome. Are there alternative solutions that would not infringe on individual rights?\n", "\n", "3. **Transparency and Public Justification:**\n", " * Any decision that prioritizes collective well-being over individual rights must be transparent and justified to the public. The rationale for the decision should be clearly explained, and stakeholders should have the opportunity to provide feedback.\n", "\n", "4. **Due Process and Redress:**\n", " * Individuals who are negatively affected by AI-driven decisions should have access to due process and redress. This includes the right to appeal decisions, seek compensation for harm, and challenge the validity of the AI system.\n", "\n", "5. **Deliberative Processes and Stakeholder Engagement:**\n", " * Engage in inclusive and deliberative processes to weigh competing values and interests. Involve stakeholders from diverse backgrounds in the development and implementation of AI policies. This includes ethicists, legal experts, technologists, policymakers, and members of the public. Citizen assemblies or similar participatory mechanisms can be valuable.\n", "\n", "6. **Prioritization Framework:**\n", " * Develop a framework for prioritizing ethical considerations in specific contexts. This framework should identify the core values that are most relevant to the situation and provide guidance on how to balance competing interests. For example, in healthcare settings, the principle of beneficence (doing good) may take precedence over the principle of autonomy in certain situations (e.g., emergency care). However, these prioritizations should be carefully considered and justified.\n", "\n", "7. **Context-Specific Considerations:**\n", " * Recognize that ethical considerations can vary depending on the context. A solution that is appropriate in one setting may not be appropriate in another. For example, the use of facial recognition technology may be more acceptable in high-security environments than in public spaces.\n", "\n", "8. **Sunset Clauses and Regular Review:**\n", " * Implement sunset clauses for AI systems that restrict individual rights. This ensures that these systems are regularly reviewed and re-evaluated to determine whether they are still necessary and proportionate.\n", "\n", "9. **Insurance and Compensation Mechanisms:**\n", " * Explore the use of insurance and compensation mechanisms to provide redress to individuals who are harmed by AI systems. This can help to mitigate the negative consequences of AI and promote accountability.\n", "\n", "10. **\"Ethics by Design\" and \"Value Sensitive Design\":** Incorporate ethical considerations from the very beginning of the AI development process. Use frameworks like \"Value Sensitive Design\" to proactively identify and address potential ethical issues.\n", "\n", "**III. Example Scenarios & Application of the Framework:**\n", "\n", "Let's consider a few examples:\n", "\n", "* **Scenario 1: AI-Powered Predictive Policing:** An AI system is used to predict crime hotspots and allocate police resources. This could infringe on individual rights to privacy and freedom of movement if it leads to disproportionate surveillance of certain communities.\n", " * **Application of Harmony AI:**\n", " * Transparency: The AI system's algorithms and data sources must be transparent and subject to independent audit.\n", " * Fairness: Data used to train the AI system must be carefully vetted for bias.\n", " * Proportionality: The use of AI-powered policing must be proportionate to the actual crime rate in the areas being targeted.\n", " * Due Process: Individuals who are stopped or questioned based on AI predictions must be treated with respect and have access to due process.\n", " * Explainability: Police officers must be able to explain the basis for their actions.\n", "\n", "* **Scenario 2: AI-Driven Healthcare Diagnosis:** An AI system is used to diagnose medical conditions. This could lead to inaccurate diagnoses or biased treatment if the system is not properly designed and validated.\n", " * **Application of Harmony AI:**\n", " * Beneficence & Non-Maleficence: The AI system must be rigorously tested and validated to ensure its accuracy and safety.\n", " * Transparency & Explainability: Doctors must be able to understand the AI system's reasoning and explain it to patients.\n", " * Autonomy: Patients must have the right to seek a second opinion and make their own healthcare decisions.\n", " * Justice: The AI system must be designed to be fair and equitable across different demographic groups.\n", "\n", "* **Scenario 3: AI-Powered Job Recruitment:** An AI system is used to screen job applicants. This could perpetuate existing biases and limit opportunities for underrepresented groups.\n", " * **Application of Harmony AI:**\n", " * Fairness: Algorithms and training data must be audited and adjusted to prevent biased outcomes.\n", " * Transparency: Candidates should understand how the AI system is evaluating their application.\n", " * Autonomy: Candidates should have the right to human review if they are rejected by the AI system.\n", " * Beneficence: The system should aim to identify candidates with the potential to succeed, not just those who fit a narrow profile.\n", "\n", "**IV. Key Considerations for Implementation:**\n", "\n", "* **Education and Training:** Educate developers, policymakers, and the public about the ethical implications of AI.\n", "* **International Cooperation:** Foster international collaboration on AI governance and ethical standards.\n", "* **Enforcement Mechanisms:** Develop effective enforcement mechanisms to ensure compliance with ethical guidelines and regulations.\n", "* **Continuous Monitoring and Evaluation:** Regularly monitor and evaluate the impact of AI systems and adapt ethical frameworks as needed.\n", "\n", "This \"Harmony AI\" framework provides a starting point for developing more comprehensive and context-specific ethical guidelines for AI decision-making. The key is to prioritize human dignity, promote well-being, and ensure fairness, while remaining flexible and adaptable to the evolving landscape of AI technology.\n", "\n", "\n", "# Response from competitor 3\n", "\n", "Designing an ethical framework for AI decision-making that balances individual rights with collective well-being is crucial to ensure AI systems are fair, transparent, and beneficial to society. Here's a proposed core set of principles:\n", "\n", "Core Principles:\n", "\n", "1. **Respect for Individual Autonomy**: Ensure that AI decisions respect individuals' autonomy, dignity, and freedom from coercion or manipulation. This includes protecting individual rights to privacy, consent, and the ability to make informed choices.\n", "2. **Promoting Fairness and Non-Discrimination**: Implement mechanisms to prevent AI biases and ensure fairness in decision-making processes. This includes avoiding discrimination based on race, gender, religion, sexual orientation, age, disability, or other protected characteristics.\n", "3. **Coluntary Transparency and Explainability**: Ensure that AI decisions are transparent, explainable, and provide context for human review and audit. This enables informed understanding of AI-driven outcomes and mitigates potential biases.\n", "4. **Human Oversight and Control**: Limit AI decision-making to well-defined, specific domains where the benefits outweigh the risks. Human oversight and control ensure accountability when AI decisions conflict with individual rights or collective well-being.\n", "5. **Safety and Vulnerability Protection**: Implement measures to safeguard vulnerable populations from AI-driven harm, including protection against algorithmic profiling and data misuse.\n", "6. **Inclusive Value Alignment**: Incorporate stakeholders' values and interests into the development process, promoting inclusivity, diversity, and stakeholder engagement.\n", "\n", "Addressing Potential Conflicts:\n", "\n", "1. **Multi-Operator Framework**: Introduce multi-operator decision-making frameworks that engage multiple stakeholders, including human experts, algorithmic experts, and representative communities. This fosters a collaborative environment to resolve conflicts.\n", "2. **Conflict Resolution Mechanisms**: Develop robust conflict resolution mechanisms, such as appeal systems or grievance procedures, to address disagreements between AI-driven decisions and individual rights or collective well-being.\n", "3. **Value-Based Co-Design**: Implement value-based co-design processes where diverse stakeholders collaborate on defining algorithmic objectives in line with shared moral compasses.\n", "4. **Human-AI Hybrid Modeling**: Utilize human-AI hybrid modeling approaches that leverage the strengths of both humans and AI systems, ensuring human judgment is embedded within decision-making processes.\n", "5. **Regulatory Efficacy and Oversight**: Develop regulatory frameworks that promote effective governance over AI deployment, enabling accountability mechanisms to mitigate conflicts.\n", "6. **Hybrid Feedback Loops**: Establish dynamic feedback loops between AI decision-makers and human stakeholders, allowing for ongoing assessment of system performance, identification of shortcomings, and continuous improvement.\n", "\n", "Potential Conflict Resolution Strategies:\n", "\n", "1. Human intervention in the decision-making process\n", "2. Use of explainable AI techniques such as feature attribution or model interpretability to identify biases\n", "3. Development of value-based AI systems that can dynamically adjust objectives to align with user preferences\n", "4. Collaboration between humans, machines, and representatives from impacted communities to provide contextual input for decision-making\n", "\n", "Implementing this framework requires a multidisciplinary approach, involving experts in computer science, ethics, philosophy, sociology, law, and more. The effectiveness of the framework relies on continuous monitoring, evaluation, and improvement, as AI systems evolve and interact with society.\n", "\n", "\n", "\n", "Now respond with the JSON with the ranked order of the competitors, nothing else. Do not include markdown formatting or code blocks." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "display(Markdown(judge))" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "judge_messages = [{\"role\": \"user\", \"content\": judge}]" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"results\": [\"2\", \"1\", \"3\"], \"reason\": \"Competitor 2's response is the most comprehensive, providing detailed core principles with operational steps, real-world examples, and robust conflict resolution strategies that cover multiple dimensions of ethical AI decision-making. Competitor 1 also offers a well-structured framework with clear principles and methods to address conflicts, but its overall depth and detail are slightly less than competitor 2. Competitor 3 presents a clear and structured approach with important points, yet it is less thorough and detailed compared to the other two responses.\"}\n" ] } ], "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": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Rank 1: gemini-2.0-flash\n", "Rank 2: gpt-4o-mini\n", "Rank 3: llama3.2\n" ] } ], "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": [ "\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": [ "\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.12" } }, "nbformat": 4, "nbformat_minor": 2 }