File size: 11,553 Bytes
d8db8b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
{
  "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": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "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": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "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
}