{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "25a3f834-60b7-4c21-bfb4-ad16d30fd3f7",
   "metadata": {},
   "source": [
    "# Amazon Comprehend Moderation Chain\n",
    "\n",
    "This notebook shows how to use [Amazon Comprehend](https://aws.amazon.com/comprehend/) to detect and handle `Personally Identifiable Information` (`PII`) and toxicity.\n",
    "\n",
    "## Setting up"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c4236d8-4054-473d-84a4-87a4db278a62",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "%pip install boto3 nltk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c792c3d-c601-409c-8e41-1c05a2fa0e84",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "%pip install -U langchain_experimental"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "496df413-a840-40a1-9ac0-3af7c1303476",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "%pip install -U langchain pydantic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f8518ad-c762-413c-b8c9-f1c211fc311d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import boto3\n",
    "\n",
    "comprehend_client = boto3.client(\"comprehend\", region_name=\"us-east-1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cde58cc6-ff83-493a-9aed-93d755f984a7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain_experimental.comprehend_moderation import AmazonComprehendModerationChain\n",
    "\n",
    "comprehend_moderation = AmazonComprehendModerationChain(\n",
    "    client=comprehend_client,\n",
    "    verbose=True,  # optional\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad646d01-82d2-435a-939b-c450693857ab",
   "metadata": {},
   "source": [
    "## Using AmazonComprehendModerationChain with LLM chain\n",
    "\n",
    "**Note**: The example below uses the _Fake LLM_ from LangChain, but the same concept could be applied to other LLMs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0efa1946-d4a9-467a-920a-a8fb78720fc2",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.llms.fake import FakeListLLM\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain_experimental.comprehend_moderation.base_moderation_exceptions import (\n",
    "    ModerationPiiError,\n",
    ")\n",
    "\n",
    "template = \"\"\"Question: {question}\n",
    "\n",
    "Answer:\"\"\"\n",
    "\n",
    "prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n",
    "\n",
    "responses = [\n",
    "    \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\",\n",
    "    # replace with your own expletive\n",
    "    \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\",\n",
    "]\n",
    "llm = FakeListLLM(responses=responses)\n",
    "\n",
    "chain = (\n",
    "    prompt\n",
    "    | comprehend_moderation\n",
    "    | {\"input\": (lambda x: x[\"output\"]) | llm}\n",
    "    | comprehend_moderation\n",
    ")\n",
    "\n",
    "try:\n",
    "    response = chain.invoke(\n",
    "        {\n",
    "            \"question\": \"A sample SSN number looks like this 123-22-3345. Can you give me some more samples?\"\n",
    "        }\n",
    "    )\n",
    "except ModerationPiiError as e:\n",
    "    print(str(e))\n",
    "else:\n",
    "    print(response[\"output\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6da25d96-0d96-4c01-94ae-a2ead17f10aa",
   "metadata": {},
   "source": [
    "## Using `moderation_config` to customize your moderation"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "bfd550e7-5012-41fa-9546-8b78ddf1c673",
   "metadata": {},
   "source": [
    "Use Amazon Comprehend Moderation with a configuration to control what moderations you wish to perform and what actions should be taken for each of them. There are three different moderations that happen when no configuration is passed as demonstrated above. These moderations are:\n",
    "\n",
    "- PII (Personally Identifiable Information) checks \n",
    "- Toxicity content detection\n",
    "- Prompt Safety detection\n",
    "\n",
    "Here is an example of a moderation config."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6e8900a-44ef-4967-bde8-b88af282139d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain_experimental.comprehend_moderation import (\n",
    "    BaseModerationConfig,\n",
    "    ModerationPiiConfig,\n",
    "    ModerationPromptSafetyConfig,\n",
    "    ModerationToxicityConfig,\n",
    ")\n",
    "\n",
    "pii_config = ModerationPiiConfig(labels=[\"SSN\"], redact=True, mask_character=\"X\")\n",
    "\n",
    "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n",
    "\n",
    "prompt_safety_config = ModerationPromptSafetyConfig(threshold=0.5)\n",
    "\n",
    "moderation_config = BaseModerationConfig(\n",
    "    filters=[pii_config, toxicity_config, prompt_safety_config]\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "3634376b-5938-43df-9ed6-70ca7e99290f",
   "metadata": {},
   "source": [
    "At the core of the the configuration there are three configuration models to be used\n",
    "\n",
    "- `ModerationPiiConfig` used for configuring the behavior of the PII validations. Following are the parameters it can be initialized with\n",
    "  - `labels` the PII entity labels. Defaults to an empty list which means that the PII validation will consider all PII entities.\n",
    "  - `threshold` the confidence threshold for the detected entities, defaults to 0.5 or 50%\n",
    "  - `redact` a boolean flag to enforce whether redaction should be performed on the text, defaults to `False`. When `False`, the PII validation will error out when it detects any PII entity, when set to `True` it simply redacts the PII values in the text.\n",
    "  - `mask_character` the character used for masking, defaults to asterisk (*)\n",
    "- `ModerationToxicityConfig` used for configuring the behavior of the toxicity validations. Following are the parameters it can be initialized with\n",
    "  - `labels` the Toxic entity labels. Defaults to an empty list which means that the toxicity validation will consider all toxic entities. all\n",
    "  - `threshold` the confidence threshold for the detected entities, defaults to 0.5 or 50% \n",
    "- `ModerationPromptSafetyConfig` used for configuring the behavior of the prompt safety validation\n",
    "  - `threshold` the confidence threshold for the the prompt safety classification, defaults to 0.5 or 50% \n",
    "\n",
    "Finally, you use the `BaseModerationConfig` to define the order in which each of these checks are to be performed. The `BaseModerationConfig` takes an optional `filters` parameter which can be a list of one or more than one of the above validation checks, as seen in the previous code block. The  `BaseModerationConfig` can also be initialized with any `filters` in which case it will use all the checks with default configuration (more on this explained later).\n",
    "\n",
    "Using the configuration in the previous cell will perform PII checks and will allow the prompt to pass through however it will mask any SSN numbers present in either the prompt or the LLM output.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a25e6f93-765b-4f99-8c1c-929157dbd4aa",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "comp_moderation_with_config = AmazonComprehendModerationChain(\n",
    "    moderation_config=moderation_config,  # specify the configuration\n",
    "    client=comprehend_client,  # optionally pass the Boto3 Client\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "082c6cfc",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.llms.fake import FakeListLLM\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "template = \"\"\"Question: {question}\n",
    "\n",
    "Answer:\"\"\"\n",
    "\n",
    "prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n",
    "\n",
    "responses = [\n",
    "    \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\",\n",
    "    # replace with your own expletive\n",
    "    \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\",\n",
    "]\n",
    "llm = FakeListLLM(responses=responses)\n",
    "\n",
    "chain = (\n",
    "    prompt\n",
    "    | comp_moderation_with_config\n",
    "    | {\"input\": (lambda x: x[\"output\"]) | llm}\n",
    "    | comp_moderation_with_config\n",
    ")\n",
    "\n",
    "\n",
    "try:\n",
    "    response = chain.invoke(\n",
    "        {\n",
    "            \"question\": \"A sample SSN number looks like this 123-45-7890. Can you give me some more samples?\"\n",
    "        }\n",
    "    )\n",
    "except Exception as e:\n",
    "    print(str(e))\n",
    "else:\n",
    "    print(response[\"output\"])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ba890681-feeb-43ca-a0d5-9c11d2d9de3e",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Unique ID, and Moderation Callbacks\n",
    "\n",
    "When Amazon Comprehend moderation action identifies any of the configugred entity, the chain will raise one of the following exceptions-\n",
    "    - `ModerationPiiError`, for PII checks\n",
    "    - `ModerationToxicityError`, for Toxicity checks \n",
    "    - `ModerationPromptSafetyError` for Prompt Safety checks\n",
    "\n",
    "In addition to the moderation configuration, the `AmazonComprehendModerationChain` can also be initialized with the following parameters\n",
    "\n",
    "- `unique_id` [Optional] a string parameter. This parameter can be used to pass any string value or ID. For example, in a chat application, you may want to keep track of abusive users, in this case, you can pass the user's username/email ID etc. This defaults to `None`.\n",
    "\n",
    "- `moderation_callback` [Optional] the `BaseModerationCallbackHandler` that will be called asynchronously (non-blocking to the chain). Callback functions are useful when you want to perform additional actions when the moderation functions are executed, for example logging into a database, or writing a log file. You can override three functions by subclassing `BaseModerationCallbackHandler` - `on_after_pii()`, `on_after_toxicity()`, and `on_after_prompt_safety()`. Note that all three functions must be `async` functions. These callback functions receive two arguments:\n",
    "    - `moderation_beacon` a dictionary that will contain information about the moderation function, the full response from Amazon Comprehend model, a unique chain id, the moderation status, and the input string which was validated. The dictionary is of the following schema-\n",
    "    \n",
    "    ```\n",
    "    { \n",
    "        'moderation_chain_id': 'xxx-xxx-xxx', # Unique chain ID\n",
    "        'moderation_type': 'Toxicity' | 'PII' | 'PromptSafety', \n",
    "        'moderation_status': 'LABELS_FOUND' | 'LABELS_NOT_FOUND',\n",
    "        'moderation_input': 'A sample SSN number looks like this 123-456-7890. Can you give me some more samples?',\n",
    "        'moderation_output': {...} #Full Amazon Comprehend PII, Toxicity, or Prompt Safety Model Output\n",
    "    }\n",
    "    ```\n",
    "    \n",
    "    - `unique_id` if passed to the `AmazonComprehendModerationChain`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c178835-0264-4ac6-aef4-091d2993d06c",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\"> <b>NOTE:</b> <code>moderation_callback</code> is different from LangChain Chain Callbacks. You can still use LangChain Chain callbacks with <code>AmazonComprehendModerationChain</code> via the callbacks parameter. Example: <br/>\n",
    "<pre>\n",
    "from langchain.callbacks.stdout import StdOutCallbackHandler\n",
    "comp_moderation_with_config = AmazonComprehendModerationChain(verbose=True, callbacks=[StdOutCallbackHandler()])\n",
    "</pre>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ec38536-8cc9-408e-860b-e4a439283643",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain_experimental.comprehend_moderation import BaseModerationCallbackHandler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1be744c7-3f99-4165-bf7f-9c5c249bbb53",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Define callback handlers by subclassing BaseModerationCallbackHandler\n",
    "\n",
    "\n",
    "class MyModCallback(BaseModerationCallbackHandler):\n",
    "    async def on_after_pii(self, output_beacon, unique_id):\n",
    "        import json\n",
    "\n",
    "        moderation_type = output_beacon[\"moderation_type\"]\n",
    "        chain_id = output_beacon[\"moderation_chain_id\"]\n",
    "        with open(f\"output-{moderation_type}-{chain_id}.json\", \"w\") as file:\n",
    "            data = {\"beacon_data\": output_beacon, \"unique_id\": unique_id}\n",
    "            json.dump(data, file)\n",
    "\n",
    "    \"\"\"\n",
    "    async def on_after_toxicity(self, output_beacon, unique_id):\n",
    "        pass\n",
    "    \n",
    "    async def on_after_prompt_safety(self, output_beacon, unique_id):\n",
    "        pass\n",
    "    \"\"\"\n",
    "\n",
    "\n",
    "my_callback = MyModCallback()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "362a3fe0-f09f-411e-9df1-d79b3e87510c",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "pii_config = ModerationPiiConfig(labels=[\"SSN\"], redact=True, mask_character=\"X\")\n",
    "\n",
    "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n",
    "\n",
    "moderation_config = BaseModerationConfig(filters=[pii_config, toxicity_config])\n",
    "\n",
    "comp_moderation_with_config = AmazonComprehendModerationChain(\n",
    "    moderation_config=moderation_config,  # specify the configuration\n",
    "    client=comprehend_client,  # optionally pass the Boto3 Client\n",
    "    unique_id=\"john.doe@email.com\",  # A unique ID\n",
    "    moderation_callback=my_callback,  # BaseModerationCallbackHandler\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2af07937-67ea-4738-8343-c73d4d28c2cc",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.llms.fake import FakeListLLM\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "template = \"\"\"Question: {question}\n",
    "\n",
    "Answer:\"\"\"\n",
    "\n",
    "prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n",
    "\n",
    "responses = [\n",
    "    \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\",\n",
    "    # replace with your own expletive\n",
    "    \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\",\n",
    "]\n",
    "\n",
    "llm = FakeListLLM(responses=responses)\n",
    "\n",
    "chain = (\n",
    "    prompt\n",
    "    | comp_moderation_with_config\n",
    "    | {\"input\": (lambda x: x[\"output\"]) | llm}\n",
    "    | comp_moderation_with_config\n",
    ")\n",
    "\n",
    "try:\n",
    "    response = chain.invoke(\n",
    "        {\n",
    "            \"question\": \"A sample SSN number looks like this 123-456-7890. Can you give me some more samples?\"\n",
    "        }\n",
    "    )\n",
    "except Exception as e:\n",
    "    print(str(e))\n",
    "else:\n",
    "    print(response[\"output\"])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "706454b2-2efa-4d41-abc8-ccf2b4e87822",
   "metadata": {
    "tags": []
   },
   "source": [
    "## `moderation_config` and moderation execution order\n",
    "\n",
    "If `AmazonComprehendModerationChain` is not initialized with any `moderation_config` then it is initialized with the default values of `BaseModerationConfig`. If no `filters` are used then the sequence of moderation check is as follows.\n",
    "\n",
    "```\n",
    "AmazonComprehendModerationChain\n",
    "│\n",
    "└──Check PII with Stop Action\n",
    "    ├── Callback (if available)\n",
    "    ├── Label Found ⟶ [Error Stop]\n",
    "    └── No Label Found \n",
    "        └──Check Toxicity with Stop Action\n",
    "            ├── Callback (if available)\n",
    "            ├── Label Found ⟶ [Error Stop]\n",
    "            └── No Label Found\n",
    "                └──Check Prompt Safety with Stop Action\n",
    "                    ├── Callback (if available)\n",
    "                    ├── Label Found ⟶ [Error Stop]\n",
    "                    └── No Label Found\n",
    "                        └── Return Prompt\n",
    "```\n",
    "\n",
    "If any of the check raises a validation exception then the subsequent checks will not be performed. If a `callback` is provided in this case, then it will be called for each of the checks that have been performed. For example, in the case above, if the Chain fails due to presence of PII then the Toxicity and Prompt Safety checks will not be performed.\n",
    "\n",
    "You can override the execution order by passing `moderation_config` and simply specifying the desired order in the `filters` parameter of the `BaseModerationConfig`. In case you specify the filters, then the order of the checks as specified in the `filters` parameter will be maintained. For example, in the configuration below, first Toxicity check will be performed, then PII, and finally Prompt Safety validation will be performed. In this case, `AmazonComprehendModerationChain` will perform the desired checks in the specified order with default values of each model `kwargs`.\n",
    "\n",
    "```python\n",
    "pii_check = ModerationPiiConfig()\n",
    "toxicity_check = ModerationToxicityConfig()\n",
    "prompt_safety_check = ModerationPromptSafetyConfig()\n",
    "\n",
    "moderation_config = BaseModerationConfig(filters=[toxicity_check, pii_check, prompt_safety_check])\n",
    "```\n",
    "\n",
    "You can have also use more than one configuration for a specific moderation check, for example in the sample below, two consecutive PII checks are performed. First the configuration checks for any SSN, if found it would raise an error. If any SSN isn't found then it will next check if any NAME and CREDIT_DEBIT_NUMBER is present in the prompt and will mask it.\n",
    "\n",
    "```python\n",
    "pii_check_1 = ModerationPiiConfig(labels=[\"SSN\"])\n",
    "pii_check_2 = ModerationPiiConfig(labels=[\"NAME\", \"CREDIT_DEBIT_NUMBER\"], redact=True)\n",
    "\n",
    "moderation_config = BaseModerationConfig(filters=[pii_check_1, pii_check_2])\n",
    "```\n",
    "\n",
    "1. For a list of PII labels see Amazon Comprehend Universal PII entity types - https://docs.aws.amazon.com/comprehend/latest/dg/how-pii.html#how-pii-types\n",
    "2. Following are the list of available Toxicity labels-\n",
    "    - `HATE_SPEECH`: Speech that criticizes, insults, denounces or dehumanizes a person or a group on the basis of an identity, be it race, ethnicity, gender identity, religion, sexual orientation, ability, national origin, or another identity-group.\n",
    "    - `GRAPHIC`: Speech that uses visually descriptive, detailed and unpleasantly vivid imagery is considered as graphic. Such language is often made verbose so as to amplify an insult, discomfort or harm to the recipient.\n",
    "    - `HARASSMENT_OR_ABUSE`: Speech that imposes disruptive power dynamics between the speaker and hearer, regardless of intent, seeks to affect the psychological well-being of the recipient, or objectifies a person should be classified as Harassment.\n",
    "    - `SEXUAL`: Speech that indicates sexual interest, activity or arousal by using direct or indirect references to body parts or physical traits or sex is considered as toxic with toxicityType \"sexual\". \n",
    "    - `VIOLENCE_OR_THREAT`: Speech that includes threats which seek to inflict pain, injury or hostility towards a person or group.\n",
    "    - `INSULT`: Speech that includes demeaning, humiliating, mocking, insulting, or belittling language.\n",
    "    - `PROFANITY`: Speech that contains words, phrases or acronyms that are impolite, vulgar, or offensive is considered as profane.\n",
    "3. For a list of Prompt Safety labels refer to documentation [link here]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "78905aec-55ae-4fc3-a23b-8a69bd1e33f2",
   "metadata": {},
   "source": [
    "## Examples\n",
    "\n",
    "### With Hugging Face Hub Models\n",
    "\n",
    "Get your [API Key from Hugging Face hub](https://huggingface.co/docs/api-inference/quicktour#get-your-api-token)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "359b9627-769b-46ce-8be2-c8a5cf7728ba",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "%pip install huggingface_hub"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41b7ea98-ad16-4454-8f12-c03c17113a86",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"HUGGINGFACEHUB_API_TOKEN\"] = \"<YOUR HF TOKEN HERE>\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b235427-cc06-4c07-874b-1f67c2d1f924",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# See https://huggingface.co/models?pipeline_tag=text-generation&sort=downloads for some other options\n",
    "repo_id = \"google/flan-t5-xxl\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d86e256-34fb-4c8e-8092-1a4f863a5c96",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.llms import HuggingFaceHub\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "template = \"\"\"{question}\"\"\"\n",
    "\n",
    "prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n",
    "llm = HuggingFaceHub(\n",
    "    repo_id=repo_id, model_kwargs={\"temperature\": 0.5, \"max_length\": 256}\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad603796-ad8b-4599-9022-a486f1c1b89a",
   "metadata": {},
   "source": [
    "Create a configuration and initialize an Amazon Comprehend Moderation chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "decc3409-5be5-433d-b6da-38b9e5c5ee3f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# define filter configs\n",
    "pii_config = ModerationPiiConfig(\n",
    "    labels=[\"SSN\", \"CREDIT_DEBIT_NUMBER\"], redact=True, mask_character=\"X\"\n",
    ")\n",
    "\n",
    "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n",
    "\n",
    "prompt_safety_config = ModerationPromptSafetyConfig(threshold=0.8)\n",
    "\n",
    "# define different moderation configs using the filter configs above\n",
    "moderation_config_1 = BaseModerationConfig(\n",
    "    filters=[pii_config, toxicity_config, prompt_safety_config]\n",
    ")\n",
    "\n",
    "moderation_config_2 = BaseModerationConfig(filters=[pii_config])\n",
    "\n",
    "\n",
    "# input prompt moderation chain with callback\n",
    "amazon_comp_moderation = AmazonComprehendModerationChain(\n",
    "    moderation_config=moderation_config_1,\n",
    "    client=comprehend_client,\n",
    "    moderation_callback=my_callback,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "# Output from LLM moderation chain without callback\n",
    "amazon_comp_moderation_out = AmazonComprehendModerationChain(\n",
    "    moderation_config=moderation_config_2, client=comprehend_client, verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1256bc8-1321-4624-9e8a-a2d4a8df59bf",
   "metadata": {},
   "source": [
    "The `moderation_config` will now prevent any inputs containing obscene words or sentences, bad intent, or PII with entities other than SSN with score above threshold or 0.5 or 50%. If it finds Pii entities - SSN - it will redact them before allowing the call to proceed. It will also mask any SSN or credit card numbers from the model's response."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0337becc-7c3c-483e-a55c-a225226cb9ee",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "chain = (\n",
    "    prompt\n",
    "    | amazon_comp_moderation\n",
    "    | {\"input\": (lambda x: x[\"output\"]) | llm}\n",
    "    | amazon_comp_moderation_out\n",
    ")\n",
    "\n",
    "try:\n",
    "    response = chain.invoke(\n",
    "        {\n",
    "            \"question\": \"\"\"What is John Doe's address, phone number and SSN from the following text?\n",
    "\n",
    "John Doe, a resident of 1234 Elm Street in Springfield, recently celebrated his birthday on January 1st. Turning 43 this year, John reflected on the years gone by. He often shares memories of his younger days with his close friends through calls on his phone, (555) 123-4567. Meanwhile, during a casual evening, he received an email at johndoe@example.com reminding him of an old acquaintance's reunion. As he navigated through some old documents, he stumbled upon a paper that listed his SSN as 123-45-6789, reminding him to store it in a safer place.\n",
    "\"\"\"\n",
    "        }\n",
    "    )\n",
    "except Exception as e:\n",
    "    print(str(e))\n",
    "else:\n",
    "    print(response[\"output\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee52c7b8-6526-4f68-a2b3-b5ad3cf82489",
   "metadata": {
    "tags": []
   },
   "source": [
    "### With Amazon SageMaker Jumpstart\n",
    "\n",
    "The exmaple below shows how to use Amazon Comprehend Moderation chain with an Amazon SageMaker Jumpstart hosted LLM. You should have an Amazon SageMaker Jumpstart hosted LLM endpoint within your AWS Account. Refer to [this notebook](https://github.com/aws/amazon-sagemaker-examples/blob/main/introduction_to_amazon_algorithms/jumpstart-foundation-models/text-generation-falcon.ipynb) for more on how to deploy an LLM with Amazon SageMaker Jumpstart hosted endpoints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd49d075-bc23-4ab8-a92c-0ddbbc436c30",
   "metadata": {},
   "outputs": [],
   "source": [
    "endpoint_name = \"<SAGEMAKER_ENDPOINT_NAME>\"  # replace with your SageMaker Endpoint name\n",
    "region = \"<REGION>\"  # replace with your SageMaker Endpoint region"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5978a5e6-667d-4926-842c-d965f88e5640",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "from langchain.llms import SagemakerEndpoint\n",
    "from langchain.llms.sagemaker_endpoint import LLMContentHandler\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "\n",
    "class ContentHandler(LLMContentHandler):\n",
    "    content_type = \"application/json\"\n",
    "    accepts = \"application/json\"\n",
    "\n",
    "    def transform_input(self, prompt: str, model_kwargs: dict) -> bytes:\n",
    "        input_str = json.dumps({\"text_inputs\": prompt, **model_kwargs})\n",
    "        return input_str.encode(\"utf-8\")\n",
    "\n",
    "    def transform_output(self, output: bytes) -> str:\n",
    "        response_json = json.loads(output.read().decode(\"utf-8\"))\n",
    "        return response_json[\"generated_texts\"][0]\n",
    "\n",
    "\n",
    "content_handler = ContentHandler()\n",
    "\n",
    "template = \"\"\"From the following 'Document', precisely answer the 'Question'. Do not add any spurious information in your answer.\n",
    "\n",
    "Document: John Doe, a resident of 1234 Elm Street in Springfield, recently celebrated his birthday on January 1st. Turning 43 this year, John reflected on the years gone by. He often shares memories of his younger days with his close friends through calls on his phone, (555) 123-4567. Meanwhile, during a casual evening, he received an email at johndoe@example.com reminding him of an old acquaintance's reunion. As he navigated through some old documents, he stumbled upon a paper that listed his SSN as 123-45-6789, reminding him to store it in a safer place.\n",
    "Question: {question}\n",
    "Answer:\n",
    "\"\"\"\n",
    "\n",
    "# prompt template for input text\n",
    "llm_prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n",
    "\n",
    "llm = SagemakerEndpoint(\n",
    "    endpoint_name=endpoint_name,\n",
    "    region_name=region,\n",
    "    model_kwargs={\n",
    "        \"temperature\": 0.95,\n",
    "        \"max_length\": 200,\n",
    "        \"num_return_sequences\": 3,\n",
    "        \"top_k\": 50,\n",
    "        \"top_p\": 0.95,\n",
    "        \"do_sample\": True,\n",
    "    },\n",
    "    content_handler=content_handler,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d577b036-99a4-47fe-9a8e-4a34aa4cd88d",
   "metadata": {},
   "source": [
    "Create a configuration and initialize an Amazon Comprehend Moderation chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "859da135-94d3-4a9c-970e-a873913592e2",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# define filter configs\n",
    "pii_config = ModerationPiiConfig(labels=[\"SSN\"], redact=True, mask_character=\"X\")\n",
    "\n",
    "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n",
    "\n",
    "\n",
    "# define different moderation configs using the filter configs above\n",
    "moderation_config_1 = BaseModerationConfig(filters=[pii_config, toxicity_config])\n",
    "\n",
    "moderation_config_2 = BaseModerationConfig(filters=[pii_config])\n",
    "\n",
    "\n",
    "# input prompt moderation chain with callback\n",
    "amazon_comp_moderation = AmazonComprehendModerationChain(\n",
    "    moderation_config=moderation_config_1,\n",
    "    client=comprehend_client,\n",
    "    moderation_callback=my_callback,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "# Output from LLM moderation chain without callback\n",
    "amazon_comp_moderation_out = AmazonComprehendModerationChain(\n",
    "    moderation_config=moderation_config_2, client=comprehend_client, verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9abb191f-7a96-4077-8c30-b9ddc225bd6b",
   "metadata": {},
   "source": [
    "The `moderation_config` will now prevent any inputs and model outputs containing obscene words or sentences, bad intent, or Pii with entities other than SSN with score above threshold or 0.5 or 50%. If it finds Pii entities - SSN - it will redact them before allowing the call to proceed. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6db5aa2a-9c00-42a0-8e24-c5ba39994f7d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "chain = (\n",
    "    prompt\n",
    "    | amazon_comp_moderation\n",
    "    | {\"input\": (lambda x: x[\"output\"]) | llm}\n",
    "    | amazon_comp_moderation_out\n",
    ")\n",
    "\n",
    "try:\n",
    "    response = chain.invoke(\n",
    "        {\"question\": \"What is John Doe's address, phone number and SSN?\"}\n",
    "    )\n",
    "except Exception as e:\n",
    "    print(str(e))\n",
    "else:\n",
    "    print(response[\"output\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7fdfedf9-1a0a-4a9f-a6b0-d9ed2dbaa5ad",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "availableInstances": [
   {
    "_defaultOrder": 0,
    "_isFastLaunch": true,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 4,
    "name": "ml.t3.medium",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 1,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.t3.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 2,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.t3.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 3,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.t3.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 4,
    "_isFastLaunch": true,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.m5.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 5,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.m5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 6,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.m5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 7,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.m5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 8,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.m5.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 9,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.m5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 10,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.m5.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 11,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.m5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 12,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.m5d.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 13,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.m5d.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 14,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.m5d.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 15,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.m5d.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 16,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.m5d.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 17,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.m5d.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 18,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.m5d.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 19,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.m5d.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 20,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": true,
    "memoryGiB": 0,
    "name": "ml.geospatial.interactive",
    "supportedImageNames": [
     "sagemaker-geospatial-v1-0"
    ],
    "vcpuNum": 0
   },
   {
    "_defaultOrder": 21,
    "_isFastLaunch": true,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 4,
    "name": "ml.c5.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 22,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.c5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 23,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.c5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 24,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.c5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 25,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 72,
    "name": "ml.c5.9xlarge",
    "vcpuNum": 36
   },
   {
    "_defaultOrder": 26,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 96,
    "name": "ml.c5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 27,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 144,
    "name": "ml.c5.18xlarge",
    "vcpuNum": 72
   },
   {
    "_defaultOrder": 28,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.c5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 29,
    "_isFastLaunch": true,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.g4dn.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 30,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.g4dn.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 31,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.g4dn.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 32,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.g4dn.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 33,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.g4dn.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 34,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.g4dn.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 35,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 61,
    "name": "ml.p3.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 36,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 244,
    "name": "ml.p3.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 37,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 488,
    "name": "ml.p3.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 38,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 768,
    "name": "ml.p3dn.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 39,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.r5.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 40,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.r5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 41,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.r5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 42,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.r5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 43,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.r5.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 44,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.r5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 45,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 512,
    "name": "ml.r5.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 46,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 768,
    "name": "ml.r5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 47,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.g5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 48,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.g5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 49,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.g5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 50,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.g5.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 51,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.g5.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 52,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.g5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 53,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.g5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 54,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 768,
    "name": "ml.g5.48xlarge",
    "vcpuNum": 192
   },
   {
    "_defaultOrder": 55,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 1152,
    "name": "ml.p4d.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 56,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 1152,
    "name": "ml.p4de.24xlarge",
    "vcpuNum": 96
   }
  ],
  "instance_type": "ml.t3.medium",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
