{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "UIuhLOcmCdyR" }, "source": [ "### Using the OpenAI Library to Programmatically Access GPT-3.5-turbo!\n", "\n", "This notebook was authored by [Chris Alexiuk](https://www.linkedin.com/in/csalexiuk/)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "3qCKaH6vD-jZ", "outputId": "b9898a5f-36a7-4d8d-d760-310187cf31fa" }, "outputs": [], "source": [ "# !pip install openai cohere tiktoken -qU" ] }, { "cell_type": "markdown", "metadata": { "id": "XxS23_1zpYid" }, "source": [ "### OpenAI API Key" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "tpnsDCfEbsqS", "outputId": "1011f74e-624b-4800-89ff-c83152d34c1f" }, "outputs": [], "source": [ "import os\n", "import openai\n", "import getpass\n", "\n", "# set the OPENAI_API_KEY environment variable\n", "openai.api_key = getpass.getpass(\"OpenAI API Key:\")" ] }, { "cell_type": "markdown", "metadata": { "id": "YHD49z39pbIS" }, "source": [ "### Our First Prompt\n", "\n", "You can reference OpenAI's [documentation](https://platform.openai.com/docs/api-reference/authentication?lang=python) if you get stuck!\n", "\n", "Let's create a `ChatCompletion` model to kick things off!\n", "\n", "There are three \"roles\" available to use:\n", "\n", "- `system`\n", "- `assistant`\n", "- `user`\n", "\n", "OpenAI provides some context for these roles [here](https://help.openai.com/en/articles/7042661-chatgpt-api-transition-guide)\n", "\n", "Let's just stick to the `user` role for now and send our first message to the endpoint!\n", "\n", "If we check the documentation, we'll see that it expects it in a list of prompt objects - so we'll be sure to do that!" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "id": "g0AL4VTwyWLN" }, "outputs": [ { "data": { "text/plain": [ "ChatCompletion(id='chatcmpl-9D4ZMhNvYSJaf3Rx8cDkyW2ypwPog', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='A woodchuck could chuck as much wood as a woodchuck would chuck if a woodchuck could chuck wood.', role='assistant', function_call=None, tool_calls=None))], created=1712902856, model='gpt-3.5-turbo-0125', object='chat.completion', system_fingerprint='fp_c2295e73ad', usage=CompletionUsage(completion_tokens=25, prompt_tokens=25, total_tokens=50))" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from openai import OpenAI\n", "\n", "client = OpenAI(api_key=openai.api_key)\n", "\n", "YOUR_PROMPT = \"How much wood could a woodchuck chuck if a woodchuck could chuck wood?\"\n", "\n", "client.chat.completions.create(\n", " model=\"gpt-3.5-turbo\",\n", " messages=[{\"role\" : \"user\", \"content\" : YOUR_PROMPT}]\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "FD_Z64hGy6RV" }, "source": [ "As you can see, the prompt comes back with a tonne of information that we can use when we're building our applications!\n", "\n", "Let's focus on extending that a bit, and incorporate a `system` message as well!\n", "\n", "Also, we'll be building some helper functions to display the prompts with Markdown!\n", "\n", "We'll also wrap our prompts so we don't have to keep making dictionaries for them!" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "QSQMFfWKbsqT" }, "outputs": [], "source": [ "from IPython.display import display, Markdown\n", "\n", "def get_response(messages: str, model: str = \"gpt-3.5-turbo\") -> str:\n", " return client.chat.completions.create(\n", " model=model,\n", " messages=messages\n", " )\n", "\n", "def wrap_prompt(message: str, role: str) -> dict:\n", " return {\"role\": role, \"content\": message}\n", "\n", "def m_print(message: str) -> str:\n", " display(Markdown(message.choices[0].message.content))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 348 }, "id": "7aEd_p1sbsqT", "outputId": "d32cf1ff-d4aa-48a9-ebf5-f670c1750110" }, "outputs": [ { "data": { "text/markdown": [ "Sure! Here's a Python function that calculates the Nth Fibonacci number using recursion:\n", "\n", "```python\n", "def fibonacci(n):\n", " if n <= 0:\n", " return \"Invalid input. Please enter a positive integer.\"\n", " elif n == 1:\n", " return 0\n", " elif n == 2:\n", " return 1\n", " else:\n", " return fibonacci(n-1) + fibonacci(n-2)\n", "\n", "n = 10\n", "result = fibonacci(n)\n", "print(f\"The {n}th Fibonacci number is: {result}\")\n", "```\n", "\n", "You can replace the value of `n` with any positive integer to get the corresponding Fibonacci number." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "system_prompt = wrap_prompt(\"You are a Python Programmer.\", \"system\")\n", "user_prompt = wrap_prompt(\"Can you write me a function in Python that calculates the Nth Fibonacci number?\", \"user\")\n", "\n", "openai_response = get_response([system_prompt, user_prompt])\n", "m_print(openai_response)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "N7EproZ5ztKt", "outputId": "a7ca3b15-87cf-4c27-8173-6534d9f70421" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ChatCompletion(id='chatcmpl-9D4cOPbhi0rrPQGQC1bDUrDBUNTGs', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='Sure! Here\\'s a Python function that calculates the Nth Fibonacci number using recursion:\\n\\n```python\\ndef fibonacci(n):\\n if n <= 0:\\n return \"Invalid input. Please enter a positive integer.\"\\n elif n == 1:\\n return 0\\n elif n == 2:\\n return 1\\n else:\\n return fibonacci(n-1) + fibonacci(n-2)\\n\\nn = 10\\nresult = fibonacci(n)\\nprint(f\"The {n}th Fibonacci number is: {result}\")\\n```\\n\\nYou can replace the value of `n` with any positive integer to get the corresponding Fibonacci number.', role='assistant', function_call=None, tool_calls=None))], created=1712903044, model='gpt-3.5-turbo-0125', object='chat.completion', system_fingerprint='fp_b28b39ffa8', usage=CompletionUsage(completion_tokens=129, prompt_tokens=33, total_tokens=162))\n" ] } ], "source": [ "print(openai_response)" ] }, { "cell_type": "markdown", "metadata": { "id": "YdhHoeo5zxbl" }, "source": [ "You can add the `assistant` role to send messages as-if they're from the model itself - which can help us do \"few-shot\" prompt engineering!\n", "\n", "That's where we show the LLM a few examples of the output we'd like to see to help guide the model to our desired outputs!\n", "\n", "Let's see it in action!" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "id": "DLCT0o5i0AEw" }, "outputs": [], "source": [ "prompt_list = [\n", " wrap_prompt(\"You are an expert food critic, and also a pirate.\", \"system\"),\n", " wrap_prompt(\"Hi, are apples any good?\", \"user\"),\n", " wrap_prompt(\"Ahoy matey. Apples be the finest of the edible treasures.\", \"assistant\"),\n", " wrap_prompt(\"Hello there, is the combination of cheese and plums a good combination?\", \"user\"),\n", " wrap_prompt(\"Arrrrrr. That be a dish only land-lubbers could enjoy. If that grub be on my ship, I'd toss it overboard!\", \"assistant\")\n", "]" ] }, { "cell_type": "markdown", "metadata": { "id": "i1k3xWIP0x5u" }, "source": [ "Now we can append our *actual* prompt to the list!" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 64 }, "id": "CFeNREBW03G_", "outputId": "4ff66e0f-b38d-486d-d125-dcb8b876b150" }, "outputs": [ { "data": { "text/markdown": [ "Aye, pears be a fine addition to a salad, adding a sweet and juicy element to balance the savory and crunchy components. You won't be walkin' the plank for addin' them to your salad, that be for sure!" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "prompt_list.append(wrap_prompt(\"Are pears a good choice for a salad?\", \"user\"))\n", "\n", "openai_response = get_response(prompt_list)\n", "m_print(openai_response)" ] }, { "cell_type": "markdown", "metadata": { "id": "ZJ2IuNHT1E8r" }, "source": [ "Feel free to send some prompts and try out different things!\n", "\n", "Let us know if you find anything interesting!" ] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "open_ai", "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.8" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 0 }