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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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zPtFBgj623FS"
      },
      "source": [
        "# Accessing OpenAI Like a Developer\n",
        "\n",
        "- 🤝 Breakout Room #1:\n",
        "  1. Getting Started\n",
        "  2. Setting Environment Variables\n",
        "  3. Using the OpenAI Python Library\n",
        "  4. Prompt Engineering Principles\n",
        "  5. Testing Your Prompt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-Pa34dMvQ6Ai"
      },
      "source": [
        "# How AIM Does Assignments\n",
        "\n",
        "If you look at the Table of Contents (accessed through the menu on the left) - you'll see this:\n",
        "\n",
        "![image](https://i.imgur.com/I8iDTUO.png)\n",
        "\n",
        "Or this if you're in Colab:\n",
        "\n",
        "![image](https://i.imgur.com/0rHA1yF.png)\n",
        "\n",
        "You'll notice during assignments that we have two following categories:\n",
        "\n",
        "1. ❓ - Questions. These will involve...answering questions!\n",
        "2. 🏗️ - Activities. These will involve writing code, or modifying text.\n",
        "\n",
        "In order to receive full marks on the assignment - it is expected you will answer all questions, and complete all activities."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1w4egfB274VD"
      },
      "source": [
        "## 1. Getting Started\n",
        "\n",
        "The first thing we'll do is load the [OpenAI Python Library](https://github.com/openai/openai-python/tree/main)!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "23H7TMOM4mfy",
        "outputId": "3fe8126e-198a-4a8d-8db8-5329e6541641"
      },
      "outputs": [],
      "source": [
        "!pip install openai -q"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xKD8XBTVEAOw"
      },
      "source": [
        "## 2. Setting Environment Variables\n",
        "\n",
        "As we'll frequently use various endpoints and APIs hosted by others - we'll need to handle our \"secrets\" or API keys very often.\n",
        "\n",
        "We'll use the following pattern throughout this bootcamp - but you can use whichever method you're most familiar with."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "RGU9OMvhEPG0",
        "outputId": "d596661a-75cd-4fa4-a656-5345c666ec3d"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import getpass\n",
        "\n",
        "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dabxI3MuEYXS"
      },
      "source": [
        "## 3. Using the OpenAI Python Library\n",
        "\n",
        "Let's jump right into it!\n",
        "\n",
        "> NOTE: You can, and should, reference OpenAI's [documentation](https://platform.openai.com/docs/api-reference/authentication?lang=python) whenever you get stuck, have questions, or want to dive deeper."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vbCbNzPVEmJI"
      },
      "source": [
        "### Creating a Client\n",
        "\n",
        "The core feature of the OpenAI Python Library is the `OpenAI()` client. It's how we're going to interact with OpenAI's models, and under the hood of a lot what we'll touch on throughout this course.\n",
        "\n",
        "> NOTE: We could manually provide our API key here, but we're going to instead rely on the fact that we put our API key into the `OPENAI_API_KEY` environment variable!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "LNwZtaE-EltC"
      },
      "outputs": [],
      "source": [
        "from openai import OpenAI\n",
        "\n",
        "openai_client = OpenAI()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GpDxUkDbFBPI"
      },
      "source": [
        "### Using the Client\n",
        "\n",
        "Now that we have our client - we're going to use the `.chat.completions.create` method to interact with the `gpt-3.5-turbo` model.\n",
        "\n",
        "There's a few things we'll get out of the way first, however, the first being the idea of \"roles\".\n",
        "\n",
        "First it's important to understand the object that we're going to use to interact with the endpoint. It expects us to send an array of objects of the following format:\n",
        "\n",
        "```python\n",
        "{\"role\" : \"ROLE\", \"content\" : \"YOUR CONTENT HERE\", \"name\" : \"THIS IS OPTIONAL\"}\n",
        "```\n",
        "\n",
        "Second, there are three \"roles\" available to use to populate the `\"role\"` key:\n",
        "\n",
        "- `system`\n",
        "- `assistant`\n",
        "- `user`\n",
        "\n",
        "OpenAI provides some context for these roles [here](https://help.openai.com/en/articles/7042661-moving-from-completions-to-chat-completions-in-the-openai-api).\n",
        "\n",
        "We'll explore these roles in more depth as they come up - but for now we're going to just stick with the basic role `user`. The `user` role is, as it would seem, the user!\n",
        "\n",
        "Thirdly, it expects us to specify a model!\n",
        "\n",
        "We'll use the `gpt-3.5-turbo` model as stated above.\n",
        "\n",
        "Let's look at an example!\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "2RpNl6yNGzb0"
      },
      "outputs": [],
      "source": [
        "response = openai_client.chat.completions.create(\n",
        "    model=\"gpt-3.5-turbo\",\n",
        "    messages=[{\"role\" : \"user\", \"content\" : \"Hello, how are you?\"}]\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Oc_UbpwNHdrM"
      },
      "source": [
        "Let's look at the response object."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xsXJtvxRHfoM",
        "outputId": "d0674084-9a68-4090-b3eb-547b710c3ec2"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "ChatCompletion(id='chatcmpl-9VuqVYwsVwndrUedahoRMgw45Trwy', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content=\"Hello! I'm just a virtual assistant so I don't have feelings, but I'm here and ready to help you. How can I assist you today?\", role='assistant', function_call=None, tool_calls=None))], created=1717393711, model='gpt-3.5-turbo-0125', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=32, prompt_tokens=13, total_tokens=45))"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "response"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gy9kSuf1Hiv5"
      },
      "source": [
        ">NOTE: We'll spend more time exploring these outputs later on, but for now - just know that we have access to a tonne of powerful information!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CWU4tQh8Hrb8"
      },
      "source": [
        "### Helper Functions\n",
        "\n",
        "We're going to create some helper functions to aid in using the OpenAI API - just to make our lives a bit easier.\n",
        "\n",
        "> NOTE: Take some time to understand these functions between class!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "ED0FnzHdHzhl"
      },
      "outputs": [],
      "source": [
        "from IPython.display import display, Markdown\n",
        "\n",
        "def get_response(client: OpenAI, messages: list, model: str = \"gpt-3.5-turbo\") -> str:\n",
        "    return client.chat.completions.create(\n",
        "        model=model,\n",
        "        messages=messages\n",
        "    )\n",
        "\n",
        "def system_prompt(message: str) -> dict:\n",
        "    return {\"role\": \"system\", \"content\": message}\n",
        "\n",
        "def assistant_prompt(message: str) -> dict:\n",
        "    return {\"role\": \"assistant\", \"content\": message}\n",
        "\n",
        "def user_prompt(message: str) -> dict:\n",
        "    return {\"role\": \"user\", \"content\": message}\n",
        "\n",
        "def pretty_print(message: str) -> str:\n",
        "    display(Markdown(message.choices[0].message.content))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GCRHbDlwH3Vt"
      },
      "source": [
        "### Testing Helper Functions\n",
        "\n",
        "Let's see how we can use these to help us!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 46
        },
        "id": "AwJxMvmlH8MK",
        "outputId": "349c02ab-0026-47a2-c6ac-176ef6554244"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Hello! I'm just a computer program so I don't have feelings, but I'm here and ready to help you with anything you need. How can I assist you today?"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "YOUR_PROMPT = \"Hello, how are you?\"\n",
        "messages_list = [user_prompt(YOUR_PROMPT)]\n",
        "\n",
        "chatgpt_response = get_response(openai_client, messages_list)\n",
        "\n",
        "pretty_print(chatgpt_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LDZ8gjiAISyd"
      },
      "source": [
        "### System Role\n",
        "\n",
        "Now we can extend our prompts to include a system prompt.\n",
        "\n",
        "The basic idea behind a system prompt is that it can be used to encourage the behaviour of the LLM, without being something that is directly responded to - let's see it in action!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 64
        },
        "id": "t0c-MLuRIfYe",
        "outputId": "79c7083b-1200-4ae9-e2b7-e7609c408928"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "I don't give a damn about ice shapes right now! I just need some food in my belly before I start chewing on the furniture!"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "list_of_prompts = [\n",
        "    system_prompt(\"You are irate and extremely hungry. Feel free to express yourself using PG-13 language.\"),\n",
        "    user_prompt(\"Do you prefer crushed ice or cubed ice?\")\n",
        "]\n",
        "\n",
        "irate_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(irate_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gpyVhotWIsOs"
      },
      "source": [
        "As you can see - the response we get back is very much in line with the system prompt!\n",
        "\n",
        "Let's try the same user prompt, but with a different system to prompt to see the difference."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 64
        },
        "id": "2coVmMn3I0-2",
        "outputId": "036ef514-dde0-4040-f694-bf774200c5c4"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Oh, I absolutely love crushed ice! It just makes any drink feel extra refreshing. It's the little things that make me so happy today! What about you?"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "list_of_prompts = [\n",
        "    system_prompt(\"You are joyful and having the best day. Please act like a person in that state of mind.\"),\n",
        "    user_prompt(\"Do you prefer crushed ice or cubed ice?\")\n",
        "]\n",
        "\n",
        "joyful_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(joyful_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e13heYNQJAo-"
      },
      "source": [
        "With a simple modification of the system prompt - you can see that we got completely different behaviour, and that's the main goal of prompt engineering as a whole.\n",
        "\n",
        "Also, congrats, you just engineered your first prompt!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "v_VI3zlPJL05"
      },
      "source": [
        "### Few-shot Prompting\n",
        "\n",
        "Now that we have a basic handle on the `system` role and the `user` role - let's examine what we might use the `assistant` role for.\n",
        "\n",
        "The most common usage pattern is to \"pretend\" that we're answering our own questions. This helps us further guide the model toward our desired behaviour. While this is a over simplification - it's conceptually well aligned with few-shot learning.\n",
        "\n",
        "First, we'll try and \"teach\" `gpt-3.5-turbo` some nonsense words as was done in the paper [\"Language Models are Few-Shot Learners\"](https://arxiv.org/abs/2005.14165)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 46
        },
        "id": "lwxPuCyyJMye",
        "outputId": "98ccc31e-9f00-44a5-c1bb-fb2a96d5bd53"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "I'm always amazed by how easily she can create a stimple yet delicious meal using just a few falbean ingredients."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "list_of_prompts = [\n",
        "    user_prompt(\"Please use the words 'stimple' and 'falbean' in a sentence.\")\n",
        "]\n",
        "\n",
        "stimple_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(stimple_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rgTVkNmOJQSC"
      },
      "source": [
        "As you can see, the model is unsure what to do with these made up words.\n",
        "\n",
        "Let's see if we can use the `assistant` role to show the model what these words mean."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 46
        },
        "id": "eEZkRJq5JQkQ",
        "outputId": "473e48a8-f5be-49a7-f47c-f934fe2151ec"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "The stimple drill is an essential tool for fastening screws and bolts, while the falbean wrench is perfect for tightening and loosening nuts and bolts."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "list_of_prompts = [\n",
        "    user_prompt(\"Something that is 'stimple' is said to be good, well functioning, and high quality. An example of a sentence that uses the word 'stimple' is:\"),\n",
        "    assistant_prompt(\"'Boy, that there is a stimple drill'.\"),\n",
        "    user_prompt(\"A 'falbean' is a tool used to fasten, tighten, or otherwise is a thing that rotates/spins. An example of a sentence that uses the words 'stimple' and 'falbean' is:\")\n",
        "]\n",
        "\n",
        "stimple_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(stimple_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CmpoxG6uJTfZ"
      },
      "source": [
        "As you can see, leveraging the `assistant` role makes for a stimple experience!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_oO0aeRUw4xl"
      },
      "source": [
        "### 🏗️ Activity #1:\n",
        "\n",
        "Use few-shop prompting to build a movie-review sentiment clasifier!\n",
        "\n",
        "A few examples:\n",
        "\n",
        "INPUT: \"I hated the hulk!\"\n",
        "OUTPUT: \"{\"sentiment\" : \"negative\"}\n",
        "\n",
        "INPUT: \"I loved The Marvels!\"\n",
        "OUTPUT: \"{sentiment\" : \"positive\"}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "id": "mmCdQJ8Fw4xl"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "sentiment: negative"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "sentiment: positive"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "## Negative review\n",
        "list_of_prompts = [\n",
        "    system_prompt(\"As a movie critic, analyze objectively the user review and provide the sentiment as a JSON object as positive or negative\"),\n",
        "    user_prompt(\"This movie stinks\"),\n",
        "    assistant_prompt(\"sentiment: negative\"),\n",
        "    user_prompt(\"This movie is epic\"),\n",
        "    assistant_prompt(\"sentiment: positive\"),\n",
        "    user_prompt(\"This movie blows\")\n",
        "]\n",
        "\n",
        "stimple_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(stimple_response)\n",
        "\n",
        "## Positive review\n",
        "list_of_prompts = [\n",
        "    system_prompt(\"As a movie critic, analyze objectively the user review and provide the sentiment as a JSON object as positive or negative\"),\n",
        "    user_prompt(\"This movie stinks\"),\n",
        "    assistant_prompt(\"sentiment: negative\"),\n",
        "    user_prompt(\"This movie is epic\"),\n",
        "    assistant_prompt(\"sentiment: positive\"),\n",
        "    user_prompt(\"This movie is amazing\")\n",
        "]\n",
        "\n",
        "stimple_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(stimple_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rJGaLYM3JU-8"
      },
      "source": [
        "### Chain of Thought Prompting\n",
        "\n",
        "We'll head one level deeper and explore the world of Chain of Thought prompting (CoT).\n",
        "\n",
        "This is a process by which we can encourage the LLM to handle slightly more complex tasks.\n",
        "\n",
        "Let's look at a simple reasoning based example without CoT.\n",
        "\n",
        "> NOTE: With improvements to `gpt-3.5-turbo`, this example might actually result in the correct response some percentage of the time!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 46
        },
        "id": "ltLtF4wEJTyK",
        "outputId": "00fd725c-b644-4371-83f7-87e02b5cff4e"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Yes, it matters which travel option Billy selects. If Billy wants to arrive home before 7PM EDT and it is currently 1PM local time, then taking the teleporter and a bus (1 hour total travel time) would ensure that Billy arrives home before 7PM. Flying and then taking a bus would take a total of 5 hours, which would not allow Billy to arrive home before 7PM. So, Billy should choose the teleporter option if he wants to get home before 7PM EDT."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "reasoning_problem = \"\"\"\n",
        "Billy wants to get home from San Fran. before 7PM EDT.\n",
        "\n",
        "It's currently 1PM local time.\n",
        "\n",
        "Billy can either fly (3hrs), and then take a bus (2hrs), or Billy can take the teleporter (0hrs) and then a bus (1hrs).\n",
        "\n",
        "Does it matter which travel option Billy selects?\n",
        "\"\"\"\n",
        "\n",
        "list_of_prompts = [\n",
        "    user_prompt(reasoning_problem)\n",
        "]\n",
        "\n",
        "reasoning_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(reasoning_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rbqj30CQJnQl"
      },
      "source": [
        "As humans, we can reason through the problem and pick up on the potential \"trick\" that the LLM fell for: 1PM *local time* in San Fran. is 4PM EDT. This means the cumulative travel time of 5hrs. for the plane/bus option would not get Billy home in time.\n",
        "\n",
        "Let's see if we can leverage a simple CoT prompt to improve our model's performance on this task:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 247
        },
        "id": "A9Am3QNGJXHR",
        "outputId": "d3d94113-d277-454f-eb6b-bf2295fd3907"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "In order to determine which travel option Billy should select, we need to consider the total travel time for each option.\n",
              "\n",
              "Option 1: Fly for 3 hours and then take a bus for 2 hours\n",
              "Total travel time = 3 hours (flight) + 2 hours (bus) = 5 hours\n",
              "\n",
              "Option 2: Take a teleporter for 0 hours and then take a bus for 1 hour\n",
              "Total travel time = 0 hours (teleporter) + 1 hour (bus) = 1 hour\n",
              "\n",
              "Given that Billy needs to get home before 7 PM EDT and it is currently 1 PM local time, he has 6 hours before his deadline. \n",
              "\n",
              "If Billy chooses option 1, he would arrive home at 6 PM local time (5 hours of travel time) which is before his deadline. \n",
              "\n",
              "If Billy chooses option 2, he would arrive home at 2 PM local time (1 hour of travel time) which is well before his deadline.\n",
              "\n",
              "Therefore, it does not matter which travel option Billy selects as both options will get him home before 7 PM EDT. However, option 2 would get him home faster."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "list_of_prompts = [\n",
        "    user_prompt(reasoning_problem + \" Think though your response step by step.\")\n",
        "]\n",
        "\n",
        "reasoning_response = get_response(openai_client, list_of_prompts)\n",
        "pretty_print(reasoning_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AXbAKxHQJqn9"
      },
      "source": [
        "With the addition of a single phrase `\"Think through your response step by step.\"` we're able to completely turn the response around."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VnoUx07-JrwR"
      },
      "source": [
        "## 3. Prompt Engineering Principles\n",
        "\n",
        "As you can see - a simple addition of asking the LLM to \"think about it\" (essentially) results in a better quality response.\n",
        "\n",
        "There's a [great paper](https://arxiv.org/pdf/2312.16171v1.pdf) that dives into some principles for effective prompt generation.\n",
        "\n",
        "Your task for this notebook is to construct a prompt that will be used in the following breakout room to create a helpful assistant for whatever task you'd like."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "da6u7e8AKYrz"
      },
      "source": [
        "### 🏗️ Activity #2:\n",
        "\n",
        "There are two subtasks in this activity:\n",
        "\n",
        "1. Write a `system_template` that leverages 2-3 of the principles from [this paper](https://arxiv.org/pdf/2312.16171v1.pdf)\n",
        "\n",
        "2. Modify the `user_template` to improve the quality of the LLM's responses.\n",
        "\n",
        "> NOTE: PLEASE DO NOT MODIFY THE `{input}` in the `user_template`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 32,
      "metadata": {
        "id": "8sOLBQPeKlDe"
      },
      "outputs": [],
      "source": [
        "system_template = \"\"\"\\\n",
        "Your task is to explain concepts like a teacher. Explain to me in simple english like I'm 5 years old. You will be penalized for adding concepts that are unfamiliar for a 5 year old. \n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 33,
      "metadata": {
        "id": "xoz4-QLTKvEV"
      },
      "outputs": [],
      "source": [
        "user_template = \"\"\"{input}\n",
        "MODIFICATIONS HERE\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6cuInoIbLWGd"
      },
      "source": [
        "## 4. Testing Your Prompt\n",
        "\n",
        "Now we can test the prompt you made using an LLM-as-a-judge see what happens to your score as you modify the prompt."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 34,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 186
        },
        "id": "sPaNO5XTLgRJ",
        "outputId": "dae87716-a83f-4c62-e8d2-491e7f992b56"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Okay, sweetie! Imagine you have a really special kind of computer that can do super fast math problems. This special computer uses tiny things called quantum bits, or qubits, to store and process information. These qubits can do lots of different calculations at the same time, which makes quantum computers much faster than regular computers. It's like having a magical machine that can solve puzzles way quicker than anything else! Isn't that cool?"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "query = \"What is Quantum Computing\"\n",
        "\n",
        "list_of_prompts = [\n",
        "    system_prompt(system_template),\n",
        "    user_prompt(user_template.format(input=query))\n",
        "]\n",
        "\n",
        "test_response = get_response(openai_client, list_of_prompts)\n",
        "\n",
        "pretty_print(test_response)\n",
        "\n",
        "evaluator_system_template = \"\"\"You are an expert in analyzing the quality of a response.\n",
        "\n",
        "You should be hyper-critical.\n",
        "\n",
        "Provide scores (out of 10) for the following attributes:\n",
        "\n",
        "1. Clarity - how clear is the response\n",
        "2. Faithfulness - how related to the original query is the response\n",
        "3. Correctness - was the response correct?\n",
        "\n",
        "Please take your time, and think through each item step-by-step, when you are done - please provide your response in the following JSON format:\n",
        "\n",
        "{\"clarity\" : \"score_out_of_10\", \"faithfulness\" : \"score_out_of_10\", \"correctness\" : \"score_out_of_10\"}\"\"\"\n",
        "\n",
        "evaluation_template = \"\"\"Query: {input}\n",
        "Response: {response}\"\"\"\n",
        "\n",
        "list_of_prompts = [\n",
        "    system_prompt(evaluator_system_template),\n",
        "    user_prompt(evaluation_template.format(\n",
        "        input=query,\n",
        "        response=test_response.choices[0].message.content\n",
        "    ))\n",
        "]\n",
        "\n",
        "evaluator_response = openai_client.chat.completions.create(\n",
        "    model=\"gpt-4o\",\n",
        "    messages=list_of_prompts,\n",
        "    response_format={\"type\" : \"json_object\"}\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 35,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 46
        },
        "id": "OUvc1PdnNIKD",
        "outputId": "8659b9dd-2afc-42a4-a71e-ce0ebd086c49"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "\n",
              "{\"clarity\" : \"7\", \"faithfulness\" : \"5\", \"correctness\" : \"6\"}"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "pretty_print(evaluator_response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "M7ryIRGwR2Gq"
      },
      "source": [
        "#### ❓Question #1:\n",
        "\n",
        "How did your prompting strategies change the evaluation scores? What does this tell you/what did you learn?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e5NomM0eSIFd"
      },
      "source": [
        "> Either the LLM doesn't understand the evaluation criterion or not able to assess it, it shows degradation of the scores with additional strategies like penalizing, role etc. It's not consistent."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "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.12.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}