{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# OpenAI APIs - Embedding\n",
    "\n",
    "SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models.\n",
    "A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/guides/embeddings).\n",
    "\n",
    "This tutorial covers the embedding APIs for embedding models, such as  \n",
    "- [intfloat/e5-mistral-7b-instruct](https://huggingface.co/intfloat/e5-mistral-7b-instruct)  \n",
    "- [Alibaba-NLP/gte-Qwen2-7B-instruct](https://huggingface.co/Alibaba-NLP/gte-Qwen2-7B-instruct)  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch A Server\n",
    "\n",
    "The following code is equivalent to running this in the shell:\n",
    "\n",
    "```bash\n",
    "python -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-7B-instruct \\\n",
    "    --port 30000 --host 0.0.0.0 --is-embedding\n",
    "```\n",
    "\n",
    "Remember to add `--is-embedding` to the command."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-05T05:22:17.227174Z",
     "iopub.status.busy": "2024-11-05T05:22:17.226952Z",
     "iopub.status.idle": "2024-11-05T05:22:42.445791Z",
     "shell.execute_reply": "2024-11-05T05:22:42.444980Z"
    }
   },
   "outputs": [],
   "source": [
    "from sglang.utils import (\n",
    "    execute_shell_command,\n",
    "    wait_for_server,\n",
    "    terminate_process,\n",
    "    print_highlight,\n",
    ")\n",
    "\n",
    "embedding_process = execute_shell_command(\n",
    "    \"\"\"\n",
    "python -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-7B-instruct \\\n",
    "    --port 30000 --host 0.0.0.0 --is-embedding\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "wait_for_server(\"http://localhost:30000\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using cURL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-05T05:22:42.448147Z",
     "iopub.status.busy": "2024-11-05T05:22:42.447775Z",
     "iopub.status.idle": "2024-11-05T05:22:42.495311Z",
     "shell.execute_reply": "2024-11-05T05:22:42.495027Z"
    }
   },
   "outputs": [],
   "source": [
    "import subprocess, json\n",
    "\n",
    "text = \"Once upon a time\"\n",
    "\n",
    "curl_text = f\"\"\"curl -s http://localhost:30000/v1/embeddings \\\n",
    "  -d '{{\"model\": \"Alibaba-NLP/gte-Qwen2-7B-instruct\", \"input\": \"{text}\"}}'\"\"\"\n",
    "\n",
    "text_embedding = json.loads(subprocess.check_output(curl_text, shell=True))[\"data\"][0][\n",
    "    \"embedding\"\n",
    "]\n",
    "\n",
    "print_highlight(f\"Text embedding (first 10): {text_embedding[:10]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using Python Requests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-05T05:22:42.496666Z",
     "iopub.status.busy": "2024-11-05T05:22:42.496524Z",
     "iopub.status.idle": "2024-11-05T05:22:42.540687Z",
     "shell.execute_reply": "2024-11-05T05:22:42.540060Z"
    }
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "\n",
    "text = \"Once upon a time\"\n",
    "\n",
    "response = requests.post(\n",
    "    \"http://localhost:30000/v1/embeddings\",\n",
    "    json={\"model\": \"Alibaba-NLP/gte-Qwen2-7B-instruct\", \"input\": text},\n",
    ")\n",
    "\n",
    "text_embedding = response.json()[\"data\"][0][\"embedding\"]\n",
    "\n",
    "print_highlight(f\"Text embedding (first 10): {text_embedding[:10]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using OpenAI Python Client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-05T05:22:42.542551Z",
     "iopub.status.busy": "2024-11-05T05:22:42.542282Z",
     "iopub.status.idle": "2024-11-05T05:22:42.928542Z",
     "shell.execute_reply": "2024-11-05T05:22:42.928181Z"
    }
   },
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.Client(base_url=\"http://127.0.0.1:30000/v1\", api_key=\"None\")\n",
    "\n",
    "# Text embedding example\n",
    "response = client.embeddings.create(\n",
    "    model=\"Alibaba-NLP/gte-Qwen2-7B-instruct\",\n",
    "    input=text,\n",
    ")\n",
    "\n",
    "embedding = response.data[0].embedding[:10]\n",
    "print_highlight(f\"Text embedding (first 10): {embedding}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using Input IDs\n",
    "\n",
    "SGLang also supports `input_ids` as input to get the embedding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-05T05:22:42.930093Z",
     "iopub.status.busy": "2024-11-05T05:22:42.929954Z",
     "iopub.status.idle": "2024-11-05T05:22:44.799945Z",
     "shell.execute_reply": "2024-11-05T05:22:44.799562Z"
    }
   },
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "from transformers import AutoTokenizer\n",
    "\n",
    "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"Alibaba-NLP/gte-Qwen2-7B-instruct\")\n",
    "input_ids = tokenizer.encode(text)\n",
    "\n",
    "curl_ids = f\"\"\"curl -s http://localhost:30000/v1/embeddings \\\n",
    "  -d '{{\"model\": \"Alibaba-NLP/gte-Qwen2-7B-instruct\", \"input\": {json.dumps(input_ids)}}}'\"\"\"\n",
    "\n",
    "input_ids_embedding = json.loads(subprocess.check_output(curl_ids, shell=True))[\"data\"][\n",
    "    0\n",
    "][\"embedding\"]\n",
    "\n",
    "print_highlight(f\"Input IDs embedding (first 10): {input_ids_embedding[:10]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-05T05:22:44.801418Z",
     "iopub.status.busy": "2024-11-05T05:22:44.801192Z",
     "iopub.status.idle": "2024-11-05T05:22:45.094634Z",
     "shell.execute_reply": "2024-11-05T05:22:45.093950Z"
    }
   },
   "outputs": [],
   "source": [
    "terminate_process(embedding_process)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "AlphaMeemory",
   "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.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
