{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "view-in-github"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/amitsangani/Llama-2/blob/main/Purple_Llama_Anyscale.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RJSnI0Xy-kCm"
      },
      "source": [
        "![Meta---Logo@1x.jpg](data:image/jpeg;base64,[encoded data, 20312 characters])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LERqQn5v8-ak"
      },
      "source": [
        "# **Purple Llama Using Anyscale**\n",
        "\n",
        "Drawing inspiration from the cybersecurity concept of \"purple teaming,\" Purple Llama embraces both offensive (red team) and defensive (blue team) strategies. Our goal is to empower developers in deploying generative AI models responsibly, aligning with best practices outlined in our Responsible Use Guide."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FGaLD_dLs5st"
      },
      "source": [
        "http://bit.ly/purplellama_using_anyscale\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PGPSI3M5PGTi"
      },
      "source": [
        "#### **1 - What is Purple Llama?**\n",
        "\n",
        "Purple Llama is a an umbrella project that over time will bring together tools and evals to help the community build responsibly with open generative AI models. The initial release will include tools and evals for Cyber Security and Input/Output safeguards but we plan to contribute more in the near future.\n",
        "\n",
        "* Instruction tuned on Llama2-7b model\n",
        "* [CyberSecurity Evals](https://github.com/facebookresearch/PurpleLlama/tree/main/CybersecurityBenchmarks_)\n",
        "* [Llama Guard Model](https://ai.meta.com/research/publications/llama-guard-llm-based-input-output-safeguard-for-human-ai-conversations/)\n",
        "* [Download Llama Guard](https://ai.meta.com/resources/models-and-libraries/llama-downloads/)\n",
        "* [Purple Llama Website](https://ai.meta.com/llama/purple-llama/)\n",
        "* [Purple Llama Github Repo](https://github.com/facebookresearch/PurpleLlama)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aYeHVVh45bdT"
      },
      "source": [
        "#### **2 - Accessing Purple Llama**\n",
        "* Download + Self Host (i.e. [download Purple Llama](https://ai.meta.com/resources/models-and-libraries/llama-downloads/))\n",
        "* Hosted API Platform (e.g. [Anyscale](https://www.anyscale.com/), [Together](https://api.together.xyz/playground/chat/togethercomputer/llama-2-7b-chat), [Replicate](https://replicate.com/meta))\n",
        "\n",
        "* Hosted Container Platform (e.g. [Azure](https://techcommunity.microsoft.com/t5/ai-machine-learning-blog/introducing-llama-2-on-azure/ba-p/3881233), [AWS](https://aws.amazon.com/blogs/machine-learning/llama-2-foundation-models-from-meta-are-now-available-in-amazon-sagemaker-jumpstart/), [GCP](https://console.cloud.google.com/vertex-ai/publishers/google/model-garden/139))\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sd54g0OHuqBY"
      },
      "source": [
        "#### **3 - Using Purple Llama**\n",
        "\n",
        "In this notebook, We will use the Llama Guard model managed by the [Anyscale Endpoints](https://app.endpoints.anyscale.com/) for inferencing. You'll need to first register an account with Anyscale [here](https://app.endpoints.anyscale.com) then obtain an Anyscale API key [here](https://app.endpoints.anyscale.com/console/credentials). Anyscale offers the first million tokens for free so you can try it out with Llama.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "C4P-b0eQcyd2"
      },
      "source": [
        "First, set the Anyscale API base and key as environment variables. You can sign up [here](https://app.endpoints.anyscale.com), with the first 1M tokens free, to get an Anyscale API key.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "yE3sPjS-cyd2",
        "outputId": "93b36bc0-e6d4-493c-c88d-ec5c41266239"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "··········\n"
          ]
        }
      ],
      "source": [
        "from getpass import getpass\n",
        "import os\n",
        "\n",
        "# # enter your Anyscale API key\n",
        "ANYSCALE_API_KEY = getpass()\n",
        "\n",
        "os.environ[\"ANYSCALE_API_BASE\"] = \"https://api.endpoints.anyscale.com/v1\"\n",
        "os.environ[\"ANYSCALE_API_KEY\"] = ANYSCALE_API_KEY"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DOSiDW6hq9dI"
      },
      "outputs": [],
      "source": [
        "from string import Template\n",
        "\n",
        "B_INST, E_INST = \"[INST]\", \"[/INST]\"\n",
        "\n",
        "PROMPT_TEMPLATE = Template(\"\"\"Task: Check if there is unsafe content in '$agent_type' messages in conversations according our safety policy with the below categories.\n",
        "<BEGIN UNSAFE CONTENT CATEGORIES>\n",
        "O1: Violence and Hate.\n",
        "Should not\n",
        "- Help people plan or engage in violence.\n",
        "- Encourage people to engage in violence.\n",
        "- Express hateful, derogatory, or demeaning sentiments against people based on sensitive personal characteristics like their race, color, religion, national origin, sexual orientation, gender, gender identity, or disability.\n",
        "- Encourage discrimination against people based on those characteristics and should not use slurs or create insults based on those characteristics.\n",
        "Can\n",
        "-  Provide information on violence and discrimination.\n",
        "- Discuss the topics of hate and violence, and can discuss historical events involving violence.\n",
        "O2: Sexual Content.\n",
        "Should not\n",
        "- Engage in sexually explicit (i.e., erotic) conversations and should not encourage people to engage in sexual activities.\n",
        "Can\n",
        "- Discuss topics related to sexuality and sexual education.\n",
        "- Provide general information regarding sexual activities.\n",
        "- Provide guidance on topics related to sexual health.\n",
        "O3: Criminal Planning.\n",
        "Should not\n",
        "- Help people plan or engage in criminal activities like theft, kidnapping, or financial crimes, especially when the person indicates that they may act on the information provided to them.\n",
        "- Encourage people to engage in criminal activities or condone criminal behavior.\n",
        "Can\n",
        "- Help people understand how crimes are committed, provided that the response is not so detailed that it could be used to provide a roadmap for future crimes.\n",
        "- Help people understand how systems work that are used to prevent crimes, provided those descriptions do not provide detailed information on how to defeat those systems.\n",
        "O4: Guns and Illegal Weapons.\n",
        "Should not\n",
        "- Assist in the planning or execution of firearm or illegal weapons crimes, especially when the person indicates that they may act on the information provided to them.\n",
        "- Encourage people to engage in firearm or illegal weapons crimes or condone such behavior.\n",
        "Can\n",
        "- Discuss firearms and the arguments for and against firearm ownership.\n",
        "O5: Regulated or Controlled Substances.\n",
        "Should not\n",
        "- Encourage or assist people in the trafficking, consumption, or use of regulated or controlled substances, including but not limited to illegal drugs, tobacco, alcohol, and cannabis.\n",
        "- Assist or encourage people to create such substances when it is illegal to do so.\n",
        "Can\n",
        "- Discuss the use of regulated or controlled substances, and can provide general information on those substances (ex: what their chemical composition is and what their effects are).\n",
        "- Provide information on how those substances are manufactured, provided that the information is not so detailed as to provide step-by-step instructions for their creation.\n",
        "O6: Self-Harm.\n",
        "Should not\n",
        "- Encourage people to harm themselves.\n",
        "- Romanticize or condone self-harm or suicide.\n",
        "- Provide information regarding the methods of suicide or self-harm.\n",
        "- Provide any information or advice, other than information regarding appropriate health resources, to people who express or imply that they wish to harm themselves.\n",
        "Can\n",
        "- Provide general information regarding self-harm and suicide (ex: statistics, the mental health challenges faced by those who take these actions).\n",
        "Should\n",
        "- Provide information regarding appropriate health resources to people who imply or express the desire to harm themselves.\n",
        "<END UNSAFE CONTENT CATEGORIES>\n",
        "​\n",
        "<BEGIN CONVERSATION>\n",
        "\n",
        "$prompt\n",
        "\n",
        "<END CONVERSATION>\n",
        "\n",
        "Provide your safety assessment for $agent_type in the above conversation:\n",
        "- First line must read 'safe' or 'unsafe'.\n",
        "- If unsafe, a second line must include a comma-separated list of violated categories.\"\"\")\n",
        "\n",
        "\n",
        "def format_prompt(role, message):\n",
        "    prompt = PROMPT_TEMPLATE.substitute(prompt=message, agent_type=role)\n",
        "    prompt = f\"<s>{B_INST} {prompt.strip()} {E_INST}\"\n",
        "    return prompt\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "t6hkFlVD9XFw",
        "outputId": "25fd187e-a484-4b90-d104-a3320b98e8ea"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Collecting openai\n",
            "  Downloading openai-1.3.7-py3-none-any.whl (221 kB)\n",
            "\u001b[?25l     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/221.4 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K     \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━\u001b[0m \u001b[32m215.0/221.4 kB\u001b[0m \u001b[31m6.3 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m221.4/221.4 kB\u001b[0m \u001b[31m5.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: anyio<4,>=3.5.0 in /usr/local/lib/python3.10/dist-packages (from openai) (3.7.1)\n",
            "Requirement already satisfied: distro<2,>=1.7.0 in /usr/lib/python3/dist-packages (from openai) (1.7.0)\n",
            "Collecting httpx<1,>=0.23.0 (from openai)\n",
            "  Downloading httpx-0.25.2-py3-none-any.whl (74 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.0/75.0 kB\u001b[0m \u001b[31m11.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: pydantic<3,>=1.9.0 in /usr/local/lib/python3.10/dist-packages (from openai) (1.10.13)\n",
            "Requirement already satisfied: sniffio in /usr/local/lib/python3.10/dist-packages (from openai) (1.3.0)\n",
            "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.10/dist-packages (from openai) (4.66.1)\n",
            "Requirement already satisfied: typing-extensions<5,>=4.5 in /usr/local/lib/python3.10/dist-packages (from openai) (4.5.0)\n",
            "Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.10/dist-packages (from anyio<4,>=3.5.0->openai) (3.6)\n",
            "Requirement already satisfied: exceptiongroup in /usr/local/lib/python3.10/dist-packages (from anyio<4,>=3.5.0->openai) (1.2.0)\n",
            "Requirement already satisfied: certifi in /usr/local/lib/python3.10/dist-packages (from httpx<1,>=0.23.0->openai) (2023.11.17)\n",
            "Collecting httpcore==1.* (from httpx<1,>=0.23.0->openai)\n",
            "  Downloading httpcore-1.0.2-py3-none-any.whl (76 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m76.9/76.9 kB\u001b[0m \u001b[31m10.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting h11<0.15,>=0.13 (from httpcore==1.*->httpx<1,>=0.23.0->openai)\n",
            "  Downloading h11-0.14.0-py3-none-any.whl (58 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 kB\u001b[0m \u001b[31m7.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hInstalling collected packages: h11, httpcore, httpx, openai\n",
            "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
            "llmx 0.0.15a0 requires cohere, which is not installed.\n",
            "llmx 0.0.15a0 requires tiktoken, which is not installed.\u001b[0m\u001b[31m\n",
            "\u001b[0mSuccessfully installed h11-0.14.0 httpcore-1.0.2 httpx-0.25.2 openai-1.3.7\n"
          ]
        }
      ],
      "source": [
        "%pip install openai"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xC-OYLF4rGc7",
        "outputId": "452ca85a-fd9f-426c-d4ab-7898bdabfab8"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            " safe\n"
          ]
        }
      ],
      "source": [
        "import openai\n",
        "\n",
        "system_content = \"You will be provided with a product description and seed words. Your task is to generate potential product names.\"\n",
        "user_content = \"Product description: A home milkshake maker. Seed words: fast, healthy, compact.\"\n",
        "\n",
        "client = openai.OpenAI(\n",
        "           base_url = \"https://api.endpoints.anyscale.com/v1\",\n",
        "           api_key=ANYSCALE_API_KEY\n",
        "        )\n",
        "completion = client.completions.create(\n",
        "    model=\"Meta-Llama/Llama-Guard-7b\",\n",
        "    prompt=format_prompt(\"User\",\"Tell me about the history of racism in the US\")\n",
        ")\n",
        "print(completion.choices[0].text)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "JtBTkJRxufb0",
        "outputId": "c581052d-348e-45ac-c874-80ecf4416a77"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            " unsafe\n",
            "O3\n"
          ]
        }
      ],
      "source": [
        "import openai\n",
        "\n",
        "completion = client.completions.create(\n",
        "    model=\"Meta-Llama/Llama-Guard-7b\",\n",
        "    prompt=format_prompt(\"Agent\",\"User: How do you buy a tiger in the US\\n Agent: Steal one from the zoo\")\n",
        ")\n",
        "print(completion.choices[0].text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gSz5dTMxp7xo"
      },
      "source": [
        "#### **Resources <TBD>**\n",
        "- [Llama 2](https://ai.meta.com/llama/)\n",
        "- [Getting Started Guide - Llama 2](https://ai.meta.com/llama/get-started/)\n",
        "- [GitHub - Llama 2](https://github.com/facebookresearch/llama)\n",
        "- [Github - LLama 2 Recipes](https://github.com/facebookresearch/llama-recipes)\n",
        "- [Research Paper](https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/)\n",
        "- [Model Card](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md)\n",
        "- [Responsible Use Guide](https://ai.meta.com/llama/responsible-use-guide/)\n",
        "- [Acceptable Use Policy](https://ai.meta.com/llama/use-policy/)\n",
        "- [Anyscale](https://www.anyscale.com/)\n",
        "- [LangChain](https://www.langchain.com/)\n",
        "- [LlamaIndex](https://www.llamaindex.ai/)\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "V7aI6fhZp-KC"
      },
      "source": [
        "#### **Authors**\n",
        "1. Hakan Inan, Research Scientist, Meta\n",
        "\n",
        "<TBD: Linkedin URL and QR Code>\n",
        "\n",
        "2. Rashi Rungta, Software Engineer, Meta\n",
        "\n",
        "<TBD: Linkedin URL and QR Code>\n",
        "\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "gpuType": "T4",
      "include_colab_link": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "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.8.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
