{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Azure Fine tuning example\n",
    "In this example we'll try to go over all operations that can be done using the Azure endpoints and their differences with the openAi endpoints (if any).<br>\n",
    "This example focuses on finetuning but touches on the majority of operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a finetune model adaptation tutorial.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "from openai import cli"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "In the following section the endpoint and key need to be set up of the next sections to work.<br> Please go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for the \"Endpoint\" value and one of the Keys. They will act as api_base and api_key in the code below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "openai.api_key = ''  # Please add your api key here\n",
    "openai.api_base = '' # Please add your endpoint here\n",
    "\n",
    "openai.api_type = 'azure'\n",
    "openai.api_version = '2022-03-01-preview' # this may change in the future"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Microsoft Active Directory Authentication\n",
    "Instead of key based authentication, you can use Active Directory to authenticate using credential tokens. Uncomment the next code section to use credential based authentication:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "from azure.identity import DefaultAzureCredential\n",
    "\n",
    "default_credential = DefaultAzureCredential()\n",
    "token = default_credential.get_token(\"https://cognitiveservices.azure.com\")\n",
    "\n",
    "openai.api_type = 'azure_ad'\n",
    "openai.api_key = token.token\n",
    "openai.api_version = '2022-03-01-preview' # this may change in the future\n",
    "\n",
    "\n",
    "openai.api_base = '' # Please add your endpoint here\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Files\n",
    "In the next section we will focus on the files operations: importing, listing, retrieving, deleting. For this we need to create 2 temporary files with some sample data. For the sake of simplicity, we will use the same data for training and validation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import shutil\n",
    "import json\n",
    "\n",
    "training_file_name = 'training.jsonl'\n",
    "validation_file_name = 'validation.jsonl'\n",
    "\n",
    "sample_data = [{\"prompt\": \"When I go to the store, I want an\", \"completion\": \"apple\"},\n",
    "    {\"prompt\": \"When I go to work, I want a\", \"completion\": \"coffe\"},\n",
    "    {\"prompt\": \"When I go home, I want a\", \"completion\": \"soda\"}]\n",
    "\n",
    "print(f'Generating the training file: {training_file_name}')\n",
    "with open(training_file_name, 'w') as training_file:\n",
    "    for entry in sample_data:\n",
    "        json.dump(entry, training_file)\n",
    "        training_file.write('\\n')\n",
    "\n",
    "print(f'Copying the training file to the validation file')\n",
    "shutil.copy(training_file_name, validation_file_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Files: Listing\n",
    "List all of the uploaded files and check for the ones that are named \"training.jsonl\" or \"validation.jsonl\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Checking for existing uploaded files.')\n",
    "results = []\n",
    "files = openai.File.list().data\n",
    "print(f'Found {len(files)} total uploaded files in the subscription.')\n",
    "for item in files:\n",
    "    if item[\"filename\"] in [training_file_name, validation_file_name]:\n",
    "        results.append(item[\"id\"])\n",
    "print(f'Found {len(results)} already uploaded files that match our names.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Files: Deleting\n",
    "Let's now delete those found files (if any) since we're going to be re-uploading them next."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f'Deleting already uploaded files.')\n",
    "for id in results:\n",
    "    openai.File.delete(sid = id)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Files: Importing & Retrieving\n",
    "Now, let's import our two files ('training.jsonl' and 'validation.jsonl') and keep those IDs since we're going to use them later for finetuning.<br>\n",
    "For this operation we are going to use the cli wrapper which does a bit more checks before uploading and also gives us progress. In addition, after uploading we're going to check the status our import until it has succeeded (or failed if something goes wrong)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def check_status(training_id, validation_id):\n",
    "    train_status = openai.File.retrieve(training_id)[\"status\"]\n",
    "    valid_status = openai.File.retrieve(validation_id)[\"status\"]\n",
    "    print(f'Status (training_file | validation_file): {train_status} | {valid_status}')\n",
    "    return (train_status, valid_status)\n",
    "\n",
    "#importing our two files\n",
    "training_id = cli.FineTune._get_or_upload(training_file_name, True)\n",
    "validation_id = cli.FineTune._get_or_upload(validation_file_name, True)\n",
    "\n",
    "#checking the status of the imports\n",
    "(train_status, valid_status) = check_status(training_id, validation_id)\n",
    "\n",
    "while train_status not in [\"succeeded\", \"failed\"] or valid_status not in [\"succeeded\", \"failed\"]:\n",
    "    time.sleep(1)\n",
    "    (train_status, valid_status) = check_status(training_id, validation_id)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Files: Downloading\n",
    "Now let's download one of the files, the training file for example, to check that everything was in order during importing and all bits are there."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f'Downloading training file: {training_id}')\n",
    "result = openai.File.download(training_id)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Finetune\n",
    "In this section we are going to use the two training and validation files that we imported in the previous section, to train a finetune model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Finetune: Adapt\n",
    "First let's create the finetune adaptation job."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "create_args = {\n",
    "    \"training_file\": training_id,\n",
    "    \"validation_file\": validation_id,\n",
    "    \"model\": \"curie\",\n",
    "    \"compute_classification_metrics\": True,\n",
    "    \"classification_n_classes\": 3\n",
    "}\n",
    "resp = openai.FineTune.create(**create_args)\n",
    "job_id = resp[\"id\"]\n",
    "status = resp[\"status\"]\n",
    "\n",
    "print(f'Fine-tunning model with jobID: {job_id}.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Finetune: Streaming\n",
    "While the job runs, we can subscribe to the streaming events to check the progress of the operation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import signal\n",
    "import datetime\n",
    "\n",
    "def signal_handler(sig, frame):\n",
    "    status = openai.FineTune.retrieve(job_id).status\n",
    "    print(f\"Stream interrupted. Job is still {status}.\")\n",
    "    return\n",
    "\n",
    "print('Streaming events for the fine-tuning job: {job_id}')\n",
    "signal.signal(signal.SIGINT, signal_handler)\n",
    "\n",
    "events = openai.FineTune.stream_events(job_id)\n",
    "try:\n",
    "    for event in events:\n",
    "        print(f'{datetime.datetime.fromtimestamp(event[\"created_at\"])} {event[\"message\"]}')\n",
    "\n",
    "except Exception:\n",
    "    print(\"Stream interrupted (client disconnected).\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Finetune: Listing and Retrieving\n",
    "Now let's check that our operation was successful and in addition we can look at all of the finetuning operations using a list operation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "status = openai.FineTune.retrieve(id=job_id)[\"status\"]\n",
    "if status not in [\"succeeded\", \"failed\"]:\n",
    "    print(f'Job not in terminal status: {status}. Waiting.')\n",
    "    while status not in [\"succeeded\", \"failed\"]:\n",
    "        time.sleep(2)\n",
    "        status = openai.FineTune.retrieve(id=job_id)[\"status\"]\n",
    "        print(f'Status: {status}')\n",
    "else:\n",
    "    print(f'Finetune job {job_id} finished with status: {status}')\n",
    "\n",
    "print('Checking other finetune jobs in the subscription.')\n",
    "result = openai.FineTune.list()\n",
    "print(f'Found {len(result)} finetune jobs.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Finetune: Deleting\n",
    "Finally we can delete our finetune job.<br>\n",
    "WARNING: Please skip this step if you want to continue with the next section as the finetune model is needed. (The delete code is commented out by default)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# openai.FineTune.delete(sid=job_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Deployments\n",
    "In this section we are going to create a deployment using the finetune model that we just adapted and then used the deployment to create a simple completion operation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deployments: Create\n",
    "Let's create a deployment using the fine-tune model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Fist let's get the model of the previous job:\n",
    "result = openai.FineTune.retrieve(id=job_id)\n",
    "if result[\"status\"] == 'succeeded':\n",
    "    model = result[\"fine_tuned_model\"]\n",
    "\n",
    "# Now let's create the deployment\n",
    "print(f'Creating a new deployment with model: {model}')\n",
    "result = openai.Deployment.create(model=model, scale_settings={\"scale_type\":\"manual\", \"capacity\": 1})\n",
    "deployment_id = result[\"id\"]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deployments: Retrieving\n",
    "Now let's check the status of the newly created deployment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f'Checking for deployment status.')\n",
    "resp = openai.Deployment.retrieve(id=deployment_id)\n",
    "status = resp[\"status\"]\n",
    "print(f'Deployment {deployment_id} is with status: {status}')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deployments: Listing\n",
    "Now because creating a new deployment takes a long time, let's look in the subscription for an already finished deployment that succeeded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('While deployment running, selecting a completed one.')\n",
    "deployment_id = None\n",
    "result = openai.Deployment.list()\n",
    "for deployment in result.data:\n",
    "    if deployment[\"status\"] == \"succeeded\":\n",
    "        deployment_id = deployment[\"id\"]\n",
    "        break\n",
    "\n",
    "if not deployment_id:\n",
    "    print('No deployment with status: succeeded found.')\n",
    "else:\n",
    "    print(f'Found a successful deployment with id: {deployment_id}.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Completions\n",
    "Now let's send a sample completion to the deployment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Sending a test completion job')\n",
    "start_phrase = 'When I go to the store, I want a'\n",
    "response = openai.Completion.create(deployment_id=deployment_id, prompt=start_phrase, max_tokens=4)\n",
    "text = response['choices'][0]['text'].replace('\\n', '').replace(' .', '.').strip()\n",
    "print(f'\"{start_phrase} {text}\"')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deployments: Delete\n",
    "Finally let's delete the deployment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f'Deleting deployment: {deployment_id}')\n",
    "openai.Deployment.delete(sid=deployment_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thank you"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.9 64-bit ('3.9.9')",
   "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.9"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "cb9817b186a29e4e9713184d901f26c1ee05ad25243d878baff7f31bb1fef480"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
