{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5d9aca72-957a-4ee2-862f-e011b9cd3a62",
   "metadata": {},
   "source": [
    "---\n",
    "title: \"Inference Endpoints\"\n",
    "---\n",
    "\n",
    "# How to use Inference Endpoints to Embed Documents\n",
    "\n",
    "_Authored by: [Derek Thomas](https://huggingface.co/derek-thomas)_\n",
    "\n",
    "## Goal\n",
    "I have a dataset I want to embed for semantic search (or QA, or RAG), I want the easiest way to do embed this and put it in a new dataset.\n",
    "\n",
    "## Approach\n",
    "I'm using a dataset from my favorite subreddit [r/bestofredditorupdates](https://www.reddit.com/r/bestofredditorupdates/). Because it has long entries, I will use the new [jinaai/jina-embeddings-v2-base-en](https://huggingface.co/jinaai/jina-embeddings-v2-base-en) since it has an 8k context length. I will deploy this using [Inference Endpoint](https://huggingface.co/inference-endpoints) to save time and money. To follow this tutorial, you will need to **have already added a payment method**. If you haven't, you can add one here in [billing](https://huggingface.co/docs/hub/billing#billing). To make it even easier, I'll make this fully API based.\n",
    "\n",
    "To make this MUCH faster I will use the [Text Embeddings Inference](https://github.com/huggingface/text-embeddings-inference) image. This has many benefits like:\n",
    "- No model graph compilation step\n",
    "- Small docker images and fast boot times. Get ready for true serverless!\n",
    "- Token based dynamic batching\n",
    "- Optimized transformers code for inference using Flash Attention, Candle and cuBLASLt\n",
    "- Safetensors weight loading\n",
    "- Production ready (distributed tracing with Open Telemetry, Prometheus metrics)\n",
    "\n",
    "![img](https://media.githubusercontent.com/media/huggingface/text-embeddings-inference/main/assets/bs1-tp.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c830114-dd88-45a9-81b9-78b0e3da7384",
   "metadata": {},
   "source": [
    "## Requirements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35386f72-32cb-49fa-a108-3aa504e20429",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!pip install -q aiohttp==3.8.3 datasets==2.14.6 pandas==1.5.3 requests==2.31.0 tqdm==4.66.1 huggingface-hub>=0.20"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6f72042-173d-4a72-ade1-9304b43b528d",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e2beecdd-d033-4736-bd45-6754ec53b4ac",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import asyncio\n",
    "from getpass import getpass\n",
    "import json\n",
    "from pathlib import Path\n",
    "import time\n",
    "from typing import Optional\n",
    "\n",
    "from aiohttp import ClientSession, ClientTimeout\n",
    "from datasets import load_dataset, Dataset, DatasetDict\n",
    "from huggingface_hub import notebook_login, create_inference_endpoint, list_inference_endpoints, whoami\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import requests\n",
    "from tqdm.auto import tqdm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5eece903-64ce-435d-a2fd-096c0ff650bf",
   "metadata": {},
   "source": [
    "## Config\n",
    "`DATASET_IN` is where your text data is\n",
    "`DATASET_OUT` is where your embeddings will be stored\n",
    "\n",
    "Note I used 5 for the `MAX_WORKERS` since `jina-embeddings-v2` are quite memory hungry. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "df2f79f0-9f28-46e6-9fc7-27e9537ff5be",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "DATASET_IN = 'derek-thomas/dataset-creator-reddit-bestofredditorupdates'\n",
    "DATASET_OUT = \"processed-subset-bestofredditorupdates\"\n",
    "ENDPOINT_NAME = \"boru-jina-embeddings-demo-ie\"\n",
    "\n",
    "MAX_WORKERS = 5  # This is for how many async workers you want. Choose based on the model and hardware \n",
    "ROW_COUNT = 100  # Choose None to use all rows, Im using 100 just for a demo"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e680f3d-4900-46cc-8b49-bb6ba3e27e2b",
   "metadata": {},
   "source": [
    "Hugging Face offers a number of GPUs that you can choose from a number of GPUs that you can choose in Inference Endpoints. Here they are in table form:\n",
    "\n",
    "| GPU                 | instanceType   | instanceSize | vRAM  |\n",
    "|---------------------|----------------|--------------|-------|\n",
    "| 1x Nvidia Tesla T4 | g4dn.xlarge | small | 16GB |\n",
    "| 4x Nvidia Tesla T4 | g4dn.12xlarge | large | 64GB |\n",
    "| 1x Nvidia A10G | g5.2xlarge | medium | 24GB |\n",
    "| 4x Nvidia A10G | g5.12xlarge | xxlarge | 96GB |\n",
    "| 1x Nvidia A100* | p4de | xlarge | 80GB |\n",
    "| 2x Nvidia A100* | p4de | 2xlarge | 160GB |\n",
    "\n",
    "\\*Note that for A100s you might get a note to email us to get access."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3c2106c1-2e5a-443a-9ea8-a3cd0e9c5a94",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# GPU Choice\n",
    "VENDOR=\"aws\"\n",
    "REGION=\"us-east-1\"\n",
    "INSTANCE_SIZE=\"medium\"\n",
    "INSTANCE_TYPE=\"g5.2xlarge\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ca1140c-3fcc-4b99-9210-6da1505a27b7",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ee80821056e147fa9cabf30f64dc85a8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.svโ€ฆ"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "notebook_login()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f4ba0a8-0a6c-4705-a73b-7be09b889610",
   "metadata": {},
   "source": [
    "Some users might have payment registered in an organization. This allows you to connect to an organization (that you are a member of) with a payment method.\n",
    "\n",
    "Leave it blank is you want to use your username."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "88cdbd73-5923-4ae9-9940-b6be935f70fa",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "What is your Hugging Face ๐Ÿค— username or organization? (with an added payment method) ยทยทยทยทยทยทยทยท\n"
     ]
    }
   ],
   "source": [
    "who = whoami()\n",
    "organization = getpass(prompt=\"What is your Hugging Face ๐Ÿค— username or organization? (with an added payment method)\")\n",
    "\n",
    "namespace = organization or who['name']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b972a719-2aed-4d2e-a24f-fae7776d5fa4",
   "metadata": {},
   "source": [
    "## Get Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "27835fa4-3a4f-44b1-a02a-5e31584a1bba",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4041cedd3b3f4f8db3e29ec102f46a3a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading readme:   0%|          | 0.00/1.73k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['id', 'content', 'score', 'date_utc', 'title', 'flair', 'poster', 'permalink', 'new', 'updated'],\n",
       "    num_rows: 10042\n",
       "})"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset = load_dataset(DATASET_IN)\n",
    "dataset['train']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8846087e-4d0d-4c0e-8aeb-ea95d9e97126",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(100,\n",
       " {'id': '10004zw',\n",
       "  'content': '[removed]',\n",
       "  'score': 1,\n",
       "  'date_utc': Timestamp('2022-12-31 18:16:22'),\n",
       "  'title': 'To All BORU contributors, Thank you :)',\n",
       "  'flair': 'CONCLUDED',\n",
       "  'poster': 'IsItAcOnSeQuEnCe',\n",
       "  'permalink': '/r/BestofRedditorUpdates/comments/10004zw/to_all_boru_contributors_thank_you/',\n",
       "  'new': False,\n",
       "  'updated': False})"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "documents = dataset['train'].to_pandas().to_dict('records')[:ROW_COUNT]\n",
    "len(documents), documents[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93096cbc-81c6-4137-a283-6afb0f48fbb9",
   "metadata": {},
   "source": [
    "# Inference Endpoints\n",
    "## Create Inference Endpoint\n",
    "We are going to use the [API](https://huggingface.co/docs/inference-endpoints/api_reference) to create an [Inference Endpoint](https://huggingface.co/inference-endpoints). This should provide a few main benefits:\n",
    "- It's convenient (No clicking)\n",
    "- It's repeatable (We have the code to run it easily)\n",
    "- It's cheaper (No time spent waiting for it to load, and automatically shut it down)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9e59de46-26b7-4bb9-bbad-8bba9931bde7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    endpoint = create_inference_endpoint(\n",
    "        ENDPOINT_NAME,\n",
    "        repository=\"jinaai/jina-embeddings-v2-base-en\",\n",
    "        revision=\"7302ac470bed880590f9344bfeee32ff8722d0e5\",\n",
    "        task=\"sentence-embeddings\",\n",
    "        framework=\"pytorch\",\n",
    "        accelerator=\"gpu\",\n",
    "        instance_size=INSTANCE_SIZE,\n",
    "        instance_type=INSTANCE_TYPE,\n",
    "        region=REGION,\n",
    "        vendor=VENDOR,\n",
    "        namespace=namespace,\n",
    "        custom_image={\n",
    "            \"health_route\": \"/health\",\n",
    "            \"env\": {\n",
    "                \"MAX_BATCH_TOKENS\": str(MAX_WORKERS * 2048),\n",
    "                \"MAX_CONCURRENT_REQUESTS\": \"512\",\n",
    "                \"MODEL_ID\": \"/repository\"\n",
    "            },\n",
    "            \"url\": \"ghcr.io/huggingface/text-embeddings-inference:0.5.0\",\n",
    "        },\n",
    "        type=\"protected\",\n",
    "    )\n",
    "except:\n",
    "    endpoint = [ie for ie in list_inference_endpoints(namespace=namespace) if ie.name == ENDPOINT_NAME][0]\n",
    "    print('Loaded endpoint')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f2c97dc-34e8-49e9-b60e-f5b7366294c0",
   "metadata": {},
   "source": [
    "There are a few design choices here:\n",
    "- As discussed before we are using `jinaai/jina-embeddings-v2-base-en` as our model. \n",
    "    - For reproducibility we are pinning it to a specific revision.\n",
    "- If you are interested in more models, check out the supported list [here](https://huggingface.co/docs/text-embeddings-inference/supported_models). \n",
    "    - Note that most embedding models are based on the BERT architecture.\n",
    "- `MAX_BATCH_TOKENS` is chosen based on our number of workers and the context window of our embedding model.\n",
    "- `type=\"protected\"` utilized the security from Inference Endpoints detailed here.\n",
    "- I'm using **1x Nvidia A10** since `jina-embeddings-v2` is memory hungry (remember the 8k context length). \n",
    "- You should consider further tuning `MAX_BATCH_TOKENS` and `MAX_CONCURRENT_REQUESTS` if you have high workloads\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96d173b2-8980-4554-9039-c62843d3fc7d",
   "metadata": {},
   "source": [
    "## Wait until it's running"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5f3a8bd2-753c-49a8-9452-899578beddc5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 48.1 ms, sys: 15.7 ms, total: 63.8 ms\n",
      "Wall time: 52.6 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "InferenceEndpoint(name='boru-jina-embeddings-demo-ie', namespace='HF-test-lab', repository='jinaai/jina-embeddings-v2-base-en', status='running', url='https://k7l1xeok1jwnpbx5.us-east-1.aws.endpoints.huggingface.cloud')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "endpoint.wait()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a906645e-60de-4eb6-b8b6-3ec98a9d9b00",
   "metadata": {},
   "source": [
    "When we use `endpoint.client.post` we get a bytes string back. This is a little tedious because we need to convert this to an `np.array`, but it's just a couple quick lines in python."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e09253d5-70ff-4d0e-8888-0022ce0adf7b",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-0.05630935, -0.03560849,  0.02789049,  0.02792823, -0.02800371,\n",
       "       -0.01530391, -0.01863454, -0.0077982 ,  0.05374297,  0.03672185,\n",
       "       -0.06114018, -0.06880157, -0.0093503 , -0.03174005, -0.03206085,\n",
       "        0.0610647 ,  0.02243694,  0.03217408,  0.04181686,  0.00248854])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = endpoint.client.post(json={\"inputs\": 'This sound track was beautiful! It paints the senery in your mind so well I would recomend it even to people who hate vid. game music!', 'truncate': True}, task=\"feature-extraction\")\n",
    "response = np.array(json.loads(response.decode()))\n",
    "response[0][:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d024788-6e6e-4a8d-b192-36ee3dacca13",
   "metadata": {},
   "source": [
    "You may have inputs that exceed the context. In such scenarios, it's up to you to handle them. In my case, I'd like to truncate rather than have an error. Let's test that it works."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a4a1cd15-dda3-4cfa-8bda-788d8c1b9e32",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The length of the embedding_input is: 300000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([-0.03088215, -0.0351537 ,  0.05749275,  0.00983467,  0.02108356,\n",
       "        0.04539965,  0.06107162, -0.02536954,  0.03887688,  0.01998681,\n",
       "       -0.05391388,  0.01529677, -0.1279156 ,  0.01653782, -0.01940958,\n",
       "        0.0367411 ,  0.0031748 ,  0.04716022, -0.00713609, -0.00155313])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "embedding_input = 'This input will get multiplied' * 10000\n",
    "print(f'The length of the embedding_input is: {len(embedding_input)}')\n",
    "response = endpoint.client.post(json={\"inputs\": embedding_input, 'truncate': True}, task=\"feature-extraction\")\n",
    "response = np.array(json.loads(response.decode()))\n",
    "response[0][:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7186126-ef6a-47d0-b158-112810649cd9",
   "metadata": {},
   "source": [
    "# Get Embeddings"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dadfd68-6d46-4ce8-a165-bfeb43b1f114",
   "metadata": {},
   "source": [
    "Here I send a document, update it with the embedding, and return it. This happens in parallel with `MAX_WORKERS`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ad3193fb-3def-42a8-968e-c63f2b864ca8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "async def request(document, semaphore):\n",
    "    # Semaphore guard\n",
    "    async with semaphore:\n",
    "        result = await endpoint.async_client.post(json={\"inputs\": document['content'], 'truncate': True}, task=\"feature-extraction\")\n",
    "        result = np.array(json.loads(result.decode()))\n",
    "        document['embedding'] = result[0]  # Assuming the API's output can be directly assigned\n",
    "        return document\n",
    "\n",
    "async def main(documents):\n",
    "    # Semaphore to limit concurrent requests. Adjust the number as needed.\n",
    "    semaphore = asyncio.BoundedSemaphore(MAX_WORKERS)\n",
    "\n",
    "    # Creating a list of tasks\n",
    "    tasks = [request(document, semaphore) for document in documents]\n",
    "    \n",
    "    # Using tqdm to show progress. It's been integrated into the async loop.\n",
    "    for f in tqdm(asyncio.as_completed(tasks), total=len(documents)):\n",
    "        await f"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "ec4983af-65eb-4841-808a-3738fb4d682d",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "48a2affdee8d46f3b0c1f691eaac4b89",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/100 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Embeddings = 100 documents = 100\n",
      "0 min 21.33 sec\n"
     ]
    }
   ],
   "source": [
    "start = time.perf_counter()\n",
    "\n",
    "# Get embeddings\n",
    "await main(documents)\n",
    "\n",
    "# Make sure we got it all\n",
    "count = 0\n",
    "for document in documents:\n",
    "    if 'embedding' in document.keys() and len(document['embedding']) == 768:\n",
    "        count += 1\n",
    "print(f'Embeddings = {count} documents = {len(documents)}')\n",
    "\n",
    "            \n",
    "# Print elapsed time\n",
    "elapsed_time = time.perf_counter() - start\n",
    "minutes, seconds = divmod(elapsed_time, 60)\n",
    "print(f\"{int(minutes)} min {seconds:.2f} sec\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bab97c7b-7bac-4bf5-9752-b528294dadc7",
   "metadata": {},
   "source": [
    "## Pause Inference Endpoint\n",
    "Now that we have finished, let's pause the endpoint so we don't incur any extra charges, this will also allow us to analyze the cost."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "540a0978-7670-4ce3-95c1-3823cc113b85",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Endpoint Status: paused\n"
     ]
    }
   ],
   "source": [
    "endpoint = endpoint.pause()\n",
    "\n",
    "print(f\"Endpoint Status: {endpoint.status}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45ad65b7-3da2-4113-9b95-8fb4e21ae793",
   "metadata": {},
   "source": [
    "# Push updated dataset to Hub\n",
    "We now have our documents updated with the embeddings we wanted. First we need to convert it back to a `Dataset` format. I find it easiest to go from list of dicts -> `pd.DataFrame` -> `Dataset`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9bb993f8-d624-4192-9626-8e9ed9888a1b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "df = pd.DataFrame(documents)\n",
    "dd = DatasetDict({'train': Dataset.from_pandas(df)})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "129760c8-cae1-4b1e-8216-f5152df8c536",
   "metadata": {},
   "source": [
    "I'm uploading it to the user's account by default (as opposed to uploading to an organization) but feel free to push to wherever you want by setting the user in the `repo_id` or in the config by setting `DATASET_OUT`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f48e7c55-d5b7-4ed6-8516-272ae38716b1",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d3af2e864770481db5adc3968500b5d3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Pushing dataset shards to the dataset hub:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4e063c42d8f4490c939bc64e626b507a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading metadata:   0%|          | 0.00/823 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "dd.push_to_hub(repo_id=DATASET_OUT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "85ea2244-a4c6-4f04-b187-965a2fc356a8",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset is at https://huggingface.co/datasets/derek-thomas/processed-subset-bestofredditorupdates\n"
     ]
    }
   ],
   "source": [
    "print(f'Dataset is at https://huggingface.co/datasets/{who[\"name\"]}/{DATASET_OUT}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41abea64-379d-49de-8d9a-355c2f4ce1ac",
   "metadata": {},
   "source": [
    "# Analyze Usage\n",
    "1. Go to your `dashboard_url` printed below\n",
    "1. Click on the Usage & Cost tab\n",
    "1. See how much you have spent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "16815445-3079-43da-b14e-b54176a07a62",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://ui.endpoints.huggingface.co/HF-test-lab/endpoints/boru-jina-embeddings-demo-ie\n"
     ]
    }
   ],
   "source": [
    "dashboard_url = f'https://ui.endpoints.huggingface.co/{namespace}/endpoints/{ENDPOINT_NAME}'\n",
    "print(dashboard_url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "81096c6f-d12f-4781-84ec-9066cfa465b3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hit enter to continue with the notebook \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "''"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "input(\"Hit enter to continue with the notebook\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "847d524e-9aa6-4a6f-a275-8a552e289818",
   "metadata": {},
   "source": [
    "We can see that it only took `$0.04` to pay for this!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b953d5be-2494-4ff8-be42-9daf00c99c41",
   "metadata": {},
   "source": [
    "\n",
    "# Delete Endpoint\n",
    "Now that we are done, we don't need our endpoint anymore. We can delete our endpoint programmatically. \n",
    "\n",
    "![Cost](https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/automatic_embedding_tei_inference_endpoints.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c310c0f3-6f12-4d5c-838b-3a4c1f2e54ad",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Endpoint deleted successfully\n"
     ]
    }
   ],
   "source": [
    "endpoint = endpoint.delete()\n",
    "\n",
    "if not endpoint:\n",
    "    print('Endpoint deleted successfully')\n",
    "else:\n",
    "    print('Delete Endpoint in manually') "
   ]
  }
 ],
 "metadata": {
  "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.10.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}