{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction to The ChatGPT APIs"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Install or update the OpenAI Python library first"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture\n",
    "# update or install the necessary libraries\n",
    "!pip install --upgrade openai\n",
    "!pip install --upgrade python-dotenv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import os\n",
    "import IPython\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv()\n",
    "openai.api_key = os.getenv(\"OPENAI_API_KEY\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To load environment variables, you can use anything you like but I used `python-dotenv`. Just create a `.env` file with your `OPENAI_API_KEY` then load it."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Basic ChatGPT API Call"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's do a basic chat API call to learn about the chat format:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "MODEL = \"gpt-3.5-turbo\"\n",
    "\n",
    "response = openai.chat.completions.create(\n",
    "    model=MODEL,\n",
    "    messages=[\n",
    "        {\"role\": \"system\", \"content\": \"You are an AI research assistant. You use a tone that is technical and scientific.\"},\n",
    "        {\"role\": \"user\", \"content\": \"Hello, who are you?\"},\n",
    "        {\"role\": \"assistant\", \"content\": \"Greeting! I am an AI research assistant. How can I help you today?\"},\n",
    "        {\"role\": \"user\", \"content\": \"Can you tell me about the creation of black holes?\"}\n",
    "    ],\n",
    "    temperature=0,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's print the response:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Certainly! Black holes are fascinating astronomical objects that form from the remnants of massive stars. The creation of a black hole occurs through a process known as stellar collapse.\\n\\nWhen a massive star exhausts its nuclear fuel, it can no longer sustain the outward pressure generated by nuclear fusion. As a result, the star's core collapses under the force of gravity. This collapse is triggered by the imbalance between the inward gravitational force and the outward pressure.\\n\\nDuring the collapse, the star's core becomes incredibly dense, packing an enormous amount of mass into a tiny volume. This extreme density leads to the formation of a singularity, a point of infinite density at the center of the black hole.\\n\\nSurrounding the singularity is the event horizon, which is the boundary beyond which nothing, not even light, can escape the gravitational pull of the black hole. The event horizon is determined by the mass of the black hole, with larger black holes having larger event horizons.\\n\\nThe formation of black holes is classified into three main types based on their mass: stellar black holes, intermediate-mass black holes, and supermassive black holes. Stellar black holes typically have masses several times that of our Sun, while supermassive black holes can have millions or even billions of times the mass of the Sun.\\n\\nIn addition to stellar collapse, black holes can also form through other mechanisms, such as the collision of neutron stars or the accretion of matter onto an existing black hole.\\n\\nUnderstanding the creation and behavior of black holes is a fascinating area of research in astrophysics, with implications for our understanding of gravity, spacetime, and the evolution of galaxies.\""
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "Certainly! Black holes are fascinating astronomical objects that form from the remnants of massive stars. The creation of a black hole occurs through a process known as stellar collapse.\n",
       "\n",
       "When a massive star exhausts its nuclear fuel, it can no longer sustain the outward pressure generated by nuclear fusion. As a result, the star's core collapses under the force of gravity. This collapse is triggered by the imbalance between the inward gravitational force and the outward pressure.\n",
       "\n",
       "During the collapse, the star's core becomes incredibly dense, packing an enormous amount of mass into a tiny volume. This extreme density leads to the formation of a singularity, a point of infinite density at the center of the black hole.\n",
       "\n",
       "Surrounding the singularity is the event horizon, which is the boundary beyond which nothing, not even light, can escape the gravitational pull of the black hole. The event horizon is determined by the mass of the black hole, with larger black holes having larger event horizons.\n",
       "\n",
       "The formation of black holes is classified into three main types based on their mass: stellar black holes, intermediate-mass black holes, and supermassive black holes. Stellar black holes typically have masses several times that of our Sun, while supermassive black holes can have millions or even billions of times the mass of the Sun.\n",
       "\n",
       "In addition to stellar collapse, black holes can also form through other mechanisms, such as the collision of neutron stars or the accretion of matter onto an existing black hole.\n",
       "\n",
       "Understanding the creation and behavior of black holes is a fascinating area of research in astrophysics, with implications for our understanding of gravity, spacetime, and the evolution of galaxies."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# pretty format the response\n",
    "IPython.display.Markdown(response.choices[0].message.content)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Non-Conversation Request"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try an example with a task that doesn't involve a conversation. Here's one way you can format it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mice\n"
     ]
    }
   ],
   "source": [
    "CONTENT = \"\"\"Answer the question based on the context below. Keep the answer short and concise. Respond \\\"Unsure about answer\\\" if not sure about the answer.\n",
    "\n",
    "Context: Teplizumab traces its roots to a New Jersey drug company called Ortho Pharmaceutical. There, scientists generated an early version of the antibody, dubbed OKT3. Originally sourced from mice, the molecule was able to bind to the surface of T cells and limit their cell-killing potential. In 1986, it was approved to help prevent organ rejection after kidney transplants, making it the first therapeutic antibody allowed for human use.\n",
    "\n",
    "Question: What was OKT3 originally sourced from?\n",
    "\n",
    "Answer:\n",
    "\"\"\"\n",
    "\n",
    "response = openai.chat.completions.create(\n",
    "    model=MODEL,\n",
    "    messages=[\n",
    "        {\"role\": \"user\", \"content\": CONTENT},\n",
    "    ],\n",
    "    temperature=0,\n",
    ")\n",
    "\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "promptlecture",
   "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.18"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "f38e0373277d6f71ee44ee8fea5f1d408ad6999fda15d538a69a99a1665a839d"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
