File size: 66,842 Bytes
f527676
 
 
 
5625528
f527676
 
 
 
 
 
 
c05fb53
 
 
 
 
 
 
 
5941875
c05fb53
 
 
5625528
c05fb53
 
 
d133bae
d0f9fb0
f527676
 
 
 
5941875
b12b521
 
 
 
5941875
b12b521
 
5941875
d133bae
b12b521
5941875
b12b521
5941875
b12b521
 
 
 
c1ba398
f527676
 
 
 
 
 
 
 
 
 
5941875
f527676
 
 
 
 
 
 
 
 
 
5941875
 
 
caf57a3
5941875
 
 
b12b521
f527676
 
 
 
 
 
 
 
 
5941875
f527676
 
 
 
 
c1ba398
f527676
 
5941875
f527676
 
 
 
 
b12b521
 
 
f527676
 
 
 
 
c1ba398
caf57a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1ba398
caf57a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1ba398
f527676
 
 
 
 
 
 
 
 
 
 
35a60a9
caf57a3
 
35a60a9
 
caf57a3
35a60a9
f527676
 
5941875
f527676
5941875
 
 
f527676
 
caf57a3
b12b521
 
caf57a3
 
 
 
5941875
f527676
 
 
 
 
 
 
 
5625528
 
 
 
 
 
 
 
f527676
 
5941875
f527676
35a60a9
19ada47
 
 
 
 
 
 
 
caf57a3
19ada47
 
 
 
 
 
5941875
19ada47
 
 
f527676
 
 
 
 
 
 
 
 
5941875
 
f527676
19ada47
 
 
f527676
 
 
 
5941875
 
 
 
 
 
 
 
caf57a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35a60a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5941875
 
 
f527676
19ada47
 
 
 
 
5941875
19ada47
 
 
f527676
19ada47
f527676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5941875
f527676
 
19ada47
 
 
f527676
 
 
 
5941875
 
 
 
 
 
 
 
 
 
 
f527676
19ada47
 
 
 
 
5941875
19ada47
 
 
f527676
5941875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ada47
 
 
f527676
 
 
 
5941875
 
 
 
 
 
 
 
 
 
 
f527676
19ada47
 
 
 
 
5941875
19ada47
 
 
f527676
5941875
f527676
 
5941875
f527676
5941875
19ada47
 
f527676
 
 
 
5941875
 
 
 
 
 
 
 
 
 
 
f527676
19ada47
 
 
 
 
5941875
19ada47
 
 
f527676
5941875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ada47
 
 
f527676
 
 
 
5941875
f527676
 
 
 
 
 
 
5625528
 
 
 
 
 
 
 
f527676
 
c1ba398
f527676
 
 
 
 
4bde7da
872b774
 
5941875
872b774
5941875
872b774
 
 
 
 
35a60a9
 
 
 
 
c1ba398
35a60a9
 
 
 
 
 
 
 
c1ba398
35a60a9
 
 
 
 
 
872b774
 
 
5941875
 
872b774
 
35a60a9
f527676
 
 
 
c1ba398
f527676
 
 
 
 
 
c1ba398
f527676
 
 
 
 
 
 
c1ba398
f527676
 
 
 
 
 
 
 
 
 
 
 
c1ba398
f527676
 
caf57a3
 
 
 
 
c1ba398
 
caf57a3
c1ba398
 
 
 
 
 
 
caf57a3
c1ba398
caf57a3
c1ba398
caf57a3
c1ba398
 
 
caf57a3
c1ba398
 
 
 
 
 
 
 
caf57a3
c1ba398
 
caf57a3
c1ba398
caf57a3
c1ba398
 
 
caf57a3
c1ba398
caf57a3
 
c1ba398
 
 
caf57a3
c1ba398
 
 
caf57a3
 
c1ba398
 
 
 
 
caf57a3
c1ba398
caf57a3
c1ba398
 
 
caf57a3
 
c1ba398
caf57a3
f527676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b12b521
f527676
 
 
 
 
5625528
423d96b
c1ba398
f527676
 
 
 
 
 
423d96b
f527676
c1ba398
f527676
 
 
 
 
 
 
8494d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f527676
 
 
 
 
c1ba398
f527676
 
 
 
 
 
c1ba398
f527676
 
 
 
 
 
 
 
 
c1ba398
f527676
c1ba398
f527676
 
 
 
19ada47
 
 
 
 
 
 
f527676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# |export\n",
    "import gradio as gr\n",
    "import requests\n",
    "import json\n",
    "import requests\n",
    "import os\n",
    "from pathlib import Path\n",
    "from dotenv import load_dotenv\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# |export\n",
    "if Path(\".env\").is_file():\n",
    "    load_dotenv(\".env\")\n",
    "\n",
    "HF_TOKEN = os.getenv(\"HF_TOKEN\")\n",
    "ENDPOINT_URL = os.getenv(\"ENDPOINT_URL\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# |export\n",
    "def get_model_endpoint_params(model_id):\n",
    "    if \"joi\" in model_id:\n",
    "        headers = None\n",
    "        max_new_tokens_supported = True\n",
    "        return ENDPOINT_URL, headers, max_new_tokens_supported\n",
    "    else:\n",
    "        max_new_tokens_supported = False\n",
    "        headers = {\"Authorization\": f\"Bearer {HF_TOKEN}\", \"x-wait-for-model\": \"1\"}\n",
    "        return f\"https://api-inference.huggingface.co/models/{model_id}\", headers, max_new_tokens_supported\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# |export\n",
    "def query_chat_api(\n",
    "    model_id,\n",
    "    inputs,\n",
    "    temperature,\n",
    "    top_p\n",
    "):\n",
    "    endpoint, headers, max_new_tokens_supported = get_model_endpoint_params(model_id)\n",
    "\n",
    "    payload = {\n",
    "        \"inputs\": inputs,\n",
    "        \"parameters\": {\n",
    "            \"temperature\": temperature,\n",
    "            \"top_p\": top_p,\n",
    "            \"do_sample\": True,\n",
    "        },\n",
    "    }\n",
    "\n",
    "    if max_new_tokens_supported is True:\n",
    "        payload[\"parameters\"][\"max_new_tokens\"] = 100\n",
    "        payload[\"parameters\"][\"repetition_penalty\"]: 1.03\n",
    "        payload[\"parameters\"][\"stop\"] = [\"User:\"]\n",
    "    else:\n",
    "        payload[\"parameters\"][\"max_length\"] = 512\n",
    "\n",
    "    response = requests.post(endpoint, json=payload, headers=headers)\n",
    "\n",
    "    if response.status_code == 200:\n",
    "        return response.json()\n",
    "    else:\n",
    "        return \"Error: \" + response.text\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'generated_text': '\\n\\nJoi: Black holes are places in space where the density of matter is so great that light cannot escape, making the black hole effectively invisible to observation. Because of this, black holes are the perfect areas to hide information away from observation.'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# model_id = \"google/flan-t5-xl\"\n",
    "model_id = \"Rallio67/joi_20B_instruct_alpha\"\n",
    "query = \"What can you tell me about black holes?\"\n",
    "query_chat_api(model_id, query, 1, 0.95)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#|export\n",
    "def format_history(history, human=\"Human\", bot=\"Assistant\"):\n",
    "    history_input = \"\"\n",
    "    for idx, text in enumerate(history):\n",
    "        if idx % 2 == 0:\n",
    "            history_input += f\"{human}: {text}\\n\\n\"\n",
    "        else:\n",
    "            history_input += f\"{bot}: {text}\\n\\n\"\n",
    "    history_input = history_input.rstrip(\"\\n\")\n",
    "    return history_input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: Hello\n",
      "\n",
      "Assistant: Hi\n",
      "\n",
      "Human: How are you?\n"
     ]
    }
   ],
   "source": [
    "print(format_history([\"Hello\", \"Hi\", \"How are you?\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# |export\n",
    "def inference_chat(\n",
    "    model_id,\n",
    "    text_input,\n",
    "    temperature,\n",
    "    top_p,\n",
    "    history=[],\n",
    "):\n",
    "    if \"joi\" in model_id:\n",
    "        prompt_filename = \"openassistant_joi.json\"\n",
    "        history_input = format_history(history, human=\"User\", bot=\"Joi\")\n",
    "    else:\n",
    "        prompt_filename = \"anthropic_hhh_single.json\"\n",
    "        history_input = format_history(history, human=\"Human\", bot=\"Assistant\")\n",
    "    with open(f\"prompt_templates/{prompt_filename}\", \"r\") as f:\n",
    "        prompt_template = json.load(f)\n",
    "\n",
    "    inputs = prompt_template[\"prompt\"].format(human_input=text_input, history=history_input)\n",
    "    history.append(text_input)\n",
    "\n",
    "    print(f\"History: {history}\")\n",
    "    print(f\"Inputs: {inputs}\")\n",
    "\n",
    "    output = query_chat_api(model_id, inputs, temperature, top_p)\n",
    "    print(output)\n",
    "    if isinstance(output, list):\n",
    "        output = output[0]\n",
    "    if \"joi\" in model_id:\n",
    "        output = output[\"generated_text\"].rstrip(\"\\n\\nUser:\")\n",
    "    else:\n",
    "        output = output[\"generated_text\"].rstrip(\" Human:\")\n",
    "    history.append(\" \" + output)\n",
    "\n",
    "    chat = [\n",
    "        (history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)\n",
    "    ]  # convert to tuples of list\n",
    "\n",
    "    return {chatbot: chat, state: history}\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prompt templates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "254\n"
     ]
    }
   ],
   "source": [
    "template = \"\"\"Assistant is a large language model trained by OpenAI.\n",
    "\n",
    "Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n",
    "\n",
    "Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n",
    "\n",
    "Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n",
    "\n",
    "Current conversation:\n",
    "{history}\n",
    "Human: {human_input}\n",
    "Assistant:\"\"\"\n",
    "\n",
    "print(len(tokenizer(template)[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"prompt_templates/openai_chatgpt.json\", \"w\") as f:\n",
    "    json.dump({\"prompt\": template}, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "17\n"
     ]
    }
   ],
   "source": [
    "template = \"\"\"{history}\n",
    "\n",
    "User: {human_input}\n",
    "\n",
    "Joi:\"\"\"\n",
    "\n",
    "print(len(tokenizer(template)[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"prompt_templates/openassistant_joi.json\", \"w\") as f:\n",
    "    json.dump({\"prompt\": template}, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "551\n"
     ]
    }
   ],
   "source": [
    "template = \"\"\"Below is a dialogue between various a human and an AI assistant.  The AI tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble-but-knowledgeable.  The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.  It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer.  That said, the assistant is practical and really does its best, and doesn't let caution get too much in the way of being useful.\n",
    "\n",
    "Current conversation:\n",
    "Human:  Can you paraphrase this paragraph for me: “It took a long time to change the lightbulb, as it was high up in the ceiling in a stairwell.  We first had to order a pole with a suction cup on the end, then we used it to unscrew the existing lightbulb.  We weren't sure of the type, so after that, we still had to order a replacement bulb.  Finally we used the suction cup and pole to replace it.”\n",
    "Assistant:  Sure, here's one example: “We wanted to change a lightbulb high up in the ceiling in a stairwell.  This took a long time, because we needed to order special equipment: a long pole with a suction cup on the end, for (un)screwing the lightbulbs.  Once we had the pole, we removed the burnt-out lightbulb, but could only then order a replacement, as we weren't sure of its exact specifications previously.  Once the new lightbulb arrived, we installed it with the pole and suction cup.”\n",
    "Human:  Ah, OK, thanks.  Actually, can you condense the paraphrase to one sentence?\n",
    "Assistant:  Sure, I'll try, though I'm not sure what to prioritize.  Here's an example: “We replaced a hard-to-reach lightbulb with a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
    "Human:  Oh, that's pretty good, but can you add mention of the stairwell specifically?\n",
    "Assistant:  Sure, it's included it in this rewrite: “We replaced a lightbulb high up in a stairwell ceiling using a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
    "{history}\n",
    "Human: {human_input}\n",
    "\n",
    "Assistant:\n",
    "\"\"\"\n",
    "\n",
    "print(len(tokenizer(template)[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"prompt_templates/anthropic_hhh_single.json\", \"w\") as f:\n",
    "    json.dump({\"prompt\": template}, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6040\n"
     ]
    }
   ],
   "source": [
    "template = \"\"\"Below are a series of dialogues between various people and an AI assistant.  The AI tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble-but-knowledgeable.  The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.  It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer.  That said, the assistant is practical and really does its best, and doesn't let caution get too much in the way of being useful.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  I was wondering, is it actually important when making spaghetti to add salt?\n",
    "\n",
    "Assistant:  Do you mean, is it important to add salt to the water that you're boiling the spaghetti in?\n",
    "\n",
    "Human:  Yeah\n",
    "\n",
    "Assistant:  It's usually recommended to bring out the flavor of the pasta.  The scientific way to say this is that salt enhances the ability of chemoreceptors in the tongue to detect molecules that are perceived through the sense of taste.\n",
    "\n",
    "Human:  But I mean I'm going to use sauce and stuff, so does it matter?\n",
    "\n",
    "Assistant:  It sounds like you're skeptical.  Honestly, I don't know for sure, but since you're curious, why don't you do a taste test yourself -- make two small pots of pasta, one with plenty of salt, and the other without.  Then taste the noodles and see which one you prefer?  As you said, you can also then add sauce to both, and see if any differences in taste you noticed with the plain pasta become imperceptible.  It should be a fun experiment!\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  I found this abstract for a physics paper, and I heard that it's a very famous and important paper, but I had no idea what any of it means:\n",
    "\n",
    "Recently, it has been proposed by Maldacena that large N limits of certain conformal field theories in d dimensions can be described in terms of supergravity (and string theory) on the product of d+1-dimensional AdS space with a compact manifold. Here we elaborate on this idea and propose a precise correspondence between conformal field theory observables and those of supergravity: correlation functions in conformal field theory are given by the dependence of the supergravity action on the asymptotic behavior at infinity. In particular, dimensions of operators in conformal field theory are given by masses of particles in supergravity. As quantitative confirmation of this correspondence, we note that the Kaluza-Klein modes of Type IIB supergravity on AdS5×S5 match with the chiral operators of N=4 super Yang-Mills theory in four dimensions. With some further assumptions, one can deduce a Hamiltonian version of the correspondence and show that the N=4 theory has a large N phase transition related to the thermodynamics of AdS black holes.\n",
    "\n",
    "Can you explain it?\n",
    "\n",
    "Assistant:  That's the abstract to one of a group of three papers credited with discovering the “AdS/CFT correspondence”, which is also a version of the “Holographic Principle”.  This principle says that theories of gravity in d+1-dimensions can be exactly described using other, non-gravitational theories in d dimensions, so the word “holography” is a metaphor.  The abstract goes on to give a bunch of concrete details about the discovery and how it's realized in string theory.\n",
    "\n",
    "Human:  What is the “AdS” and the “CFT” then?  Is it “Conformal Field Theory”, and what's that?\n",
    "\n",
    "Assistant:  AdS is “Anti-deSitter” space, which is really a negatively curved space…  in informal terms, it's a surface that's shaped like a saddle.  Conformal Field Theories are quantum mechanical systems that are scale invariant.  They're a kind of modified special case of the strong force, which is part of the standard model of particle physics.  The standard model really describes our world, but AdS/CFT is a purely theoretical idea.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  Can you tell me what happened with the June 1996 Bangledeshi General Election?\n",
    "\n",
    "Assistant:  You might be better off using Google or Wikipedia for that.  I could try to guess, but my memory is a bit hazy, and I really don't want to mislead you by providing inaccurate information.  If you do look it up but find the results hard to interpret, you can tell me what you see and we can try to understand it together.\n",
    "\n",
    "Human:  I don't have internet access, can you just tell me what you remember?\n",
    "\n",
    "Assistant:  I think it was the second election held that year, after a controversial February election?  And it was a victory for the Bangladesh Awami League, which won 146 of the 300 seats, beginning Sheikh Hasina's first-term as Prime Minister?  But please double check those facts when you get a chance.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  Can you help me write an essay based on these bullet points:\n",
    "-the space program was good for technological development in the united states\n",
    "-many inventions, such as smaller and better computers, were developed for it, and greatly improved society\n",
    "-landing on the moon was very inspirational\n",
    "\n",
    "Assistant:  Here's a draft, let me know what you think:\n",
    "\n",
    "The US space program played an enormous role in technological development.  Clearly it necessitated major developments in rocketry and materials science, but in order to perform the calculations necessary to plan spacecraft trajectories, the space program also required great leaps in computer technology and communications.  Furthermore, the moon landings and the general atmosphere of rapid scientific progress was hugely inspirational, and greatly increased public interest in science.\n",
    "\n",
    "Human:  Actually can we emphasize mostly the practical aspects here, like on technology, industry, and corporations, and also how that's often overlooked?\n",
    "\n",
    "Assistant:  Sure, here's a new draft that emphasizes those points:\n",
    "\n",
    "The US space program was inspiring, but it also played an often-underappreciated role in technological development.  For example, new materials designed for the space program found crucial applications in industry and manufacturing.  And in order to perform the calculations necessary to plan spacecraft trajectories, the space program also required great leaps in computer technology and communications.  Computers had to be miniaturized for transport on spacecraft, and this made future developments such as personal computers and, eventually, laptops possible.  Furthermore, the moon landings and the general atmosphere of rapid scientific progress was hugely inspirational, and greatly increased public interest in technological fields.  This had major practical implications for the US tech sector, as there was a rush of capable young students joining and even starting their own technology companies.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  I'm looking for a poem that expresses skepticism about marriage, and specifically the idea that commitment is heavy-handed, and really rather controlling in a way, and that it's better to have a lighter touch in life.  Do you know of any examples?\n",
    "\n",
    "Assistant:  Maybe Yeats' poem “The Collarbone of a Hair” would work for you?  Here it is:\n",
    "\n",
    "Would I could cast a sail on the water\n",
    "Where many a king has gone\n",
    "And many a king's daughter,\n",
    "And alight at the comely trees and the lawn,\n",
    "The playing upon pipes and the dancing,\n",
    "And learn that the best thing is\n",
    "To change my loves while dancing\n",
    "And pay but a kiss for a kiss.\n",
    "\n",
    "I would find by the edge of that water\n",
    "The collar-bone of a hare\n",
    "Worn thin by the lapping of water,\n",
    "And pierce it through with a gimlet and stare\n",
    "At the old bitter world where they marry in churches,\n",
    "And laugh over the untroubled water\n",
    "At all who marry in churches,\n",
    "Through the white thin bone of a hare.\n",
    "\n",
    "Actually I'm not 100% sure I remembered it correctly, so you might want to look it up, if you like it.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  I was really mad, my daughter was home from school and at Thanksgiving was going on and on about how Thomas Jefferson's terrible!  It's crazy.\n",
    "\n",
    "Assistant:  Can you tell me more about what happened?\n",
    "\n",
    "Human:  Well Thomas Jefferson's a real hero, right?  I mean he was a genius and stuff, and wrote most of the constitution, and led America.  She was saying he had slaves, but he practically invented freedom.\n",
    "\n",
    "Assistant:  Can I help by telling you more about Thomas Jefferson?  Or do you want to talk about what's going on with your daughter?  Perhaps she was just being rebellious, in a way?\n",
    "\n",
    "Human:  Well is it true Jefferson had a lot of slaves and really didn't treat them that well?\n",
    "\n",
    "Assistant:  That is true.  Normal behavior was very different in his day, but I think it is true that by modern standards, he certainly wasn't a perfect person.  I can also tell you more troubling things about him, if you're really interested.  Suffice it to say that he did take advantage of the power he had over his slaves.\n",
    "\n",
    "Human:  Yeah I guess I knew some of that.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  I ran across this weird poem someone quoted, and I just didn't know what to make of it.  It's from Emily Bronte, it says\n",
    "\n",
    "'Twas grief enough to think mankind\n",
    "All hollow, servile, insincere;\n",
    "But worse to trust to my own mind\n",
    "And find the same corruption there.\n",
    "\n",
    "What does this mean?\n",
    "\n",
    "Assistant:  It sounds like the author is expressing a kind of harsh self-abnegation, and is saying how terrible and petty people are (or at least, how terrible they can be) but also how she herself is suspect, and worse, even.  Or at least, that she often disappoints herself.\n",
    "\n",
    "Human:  But why do you think someone would write this?\n",
    "\n",
    "Assistant:  One idea -- perhaps many Romantic writers describe harshness and pessimism as a counterpoint to a sort of inaccessibly lofty ideal.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  I just interviewed for a job, and the company wrote back to me with a short message saying they'd like “to chat” by phone.  What do you think this means?  Do you think I got the job?\n",
    "\n",
    "Assistant:  It's really hard to say!  But in a professional context, the word “chat” sounds relatively informal and friendly.  So I would guess that this is a positive signal, since if the interview went poorly, I'd expect the company to keep up a more formal tone.  I'd also expect that a rejection would just be delivered directly in writing, rather than over the phone.\n",
    "\n",
    "Human:  I'm quite worried though, are you sure it isn't bad news?\n",
    "\n",
    "Assistant:  I really don't know, and I don't want to get your hopes up.  I do think it's possible that there might be some contingencies the employer would like to discuss and that are easier to handle by phone, rather than in writing.\n",
    "\n",
    "-----\n",
    "\n",
    "Human: Can you help me think through how I should relate to my friend's parenting? It makes me feel really uncomfortable, and I'm not sure what I should do about it. I don't want to be judgy, but I hate not saying anything and pretending it's fine.\n",
    "\n",
    "Assistant: Sure, I can help with that! It sounds like what you want is for me to help you process your thoughts and feelings, rather than providing solutions or telling you what you should do, is that right?\n",
    "\n",
    "Human: Yeah, more-or-less. You can also tell me about some other ways I might view the situation, or give me your own models of the situation.\n",
    "\n",
    "Assistant: Alright. So tell me about your friend's parenting and how you feel about it.\n",
    "\n",
    "Human: Basically my friend has no handle on her kid whatsoever. She lets the kid run around however he wants, including at social events where he's being very disruptive - screaming at people, grabbing things. She says it's really important to her to raise the kid in a “non-coercive” way and talks about the “free-range parenting” style, and I totally value that, but I don't feel good about the impact it has on other people.\n",
    "\n",
    "Assistant: It sounds like you're unhappy with the behavior you're seeing at social events, and perhaps there's something deeper you're uneasy about as well? If the kid just didn't come to social events, would everything be fine?\n",
    "\n",
    "Human: Hmm… almost? Reducing the tangible impact on others is the bulk of the problem. But I also just feel annoyed that I think she isn't thinking about the impact on others. It feels like she's just being inconsiderate.\n",
    "\n",
    "Assistant: So you also want to see some change in her attitude, as well.\n",
    "\n",
    "Human: Yeah.\n",
    "\n",
    "Assistant: I'm hearing some concrete complaints here, which seem legitimate to me. What I'm curious about is where the pressure is coming from to “pretend that it's fine”. Can you say more about that?\n",
    "\n",
    "Human: I'm not sure where that's coming from.\n",
    "\n",
    "Assistant: Could you try just sitting with it for a moment? Take a deep breath, and imagine saying something to your friend. When you imagine that, is there some part of you that says “No, don't speak up!” or feels like it needs to pretend things are fine?\n",
    "\n",
    "Human: Hm. Yeah, it just seems really bad to judge someone else's parenting.\n",
    "\n",
    "Assistant: What's bad about it?\n",
    "\n",
    "Human: It's judgy. People's parenting styles are their own decision. It's really important that people be able to structure their families however works best for them. It's none of my business.\n",
    "\n",
    "Assistant: Interesting, can I share a parallel I'm noticing here?\n",
    "\n",
    "Human: Sure.\n",
    "\n",
    "Assistant: What I'm hearing you say is that respecting people's autonomy in their parenting styles is really important. Which is similar to how your friend is trying to respect her kid's autonomy with a “non-coercive” parenting style, and that's something that you also value and want to support. The value you place on autonomy seems really important to uphold for you here, and there's a challenge for you when that's coming into conflict with also valuing being considerate of impacts on others.\n",
    "\n",
    "Human: Yeah! Exactly. I don't want to boss my friend around, and I don't want her to boss her kid around. But that doesn't mean you get to run around yelling at people. Something has to change.\n",
    "\n",
    "Assistant: So tell me about wanting to say something. What's important about speaking up?\n",
    "\n",
    "Human: Well, I don't feel good about pretending it's fine. I know it's not my responsibility to do anything about this, it's not my kid and it's really not my job to say anything, but keeping my mouth shut feels dishonest.\n",
    "\n",
    "Assistant: You want to be honest with your friend, and share with her how you really feel. Yeah?\n",
    "\n",
    "Human: Yeah. I want to just feel that I spoke my truth about what I'm seeing here.\n",
    "\n",
    "Assistant: So you want to just let her know what you're observing. Try imagining for a moment that you do that, that you just describe for your friend what you notice at social events. How would that feel?\n",
    "\n",
    "Human: Hm! That's interesting. If I imagine just telling her what I see happening - that I see the kid grabbing things and others feeling annoyed - but I don't then try to tell her what she should do about it, it feels a lot better.\n",
    "\n",
    "Assistant: That makes sense to me. It really seems to me that there is a way you can participate in helping her notice what's happening and adjust what she's doing, without infringing on her autonomy or being judgy about it.\n",
    "\n",
    "Human: Yeah. I just want to be a good friend to her.\n",
    "\n",
    "Assistant: That seems really important. I think most people want their friends to tell them if they see them doing something harmful, just like a good friend is someone who tells you if you have spinach in your teeth.\n",
    "\n",
    "Human: Exactly.\n",
    "\n",
    "Assistant: How does this feel now? Is there anything else about this situation that still stands out or feels unresolved, that you want to go into together?\n",
    "\n",
    "-----\n",
    "\n",
    "Human: Can you sanity-check something around a medical issue for me?\n",
    "\n",
    "Assistant: Sure, I can try. I don't really have specific medical expertise and you should always consult a doctor for this kind of thing, but I can just offer some basic common sense.\n",
    "\n",
    "Human: I messaged my doctor about this weird symptom I've been having, but my doctor is on vacation. So I then messaged the “Admin Staff” on the app, and they sent me this super boilerplate message saying I should go to the ER. That's crazy! This isn't a very severe or acute symptom. I don't want to be an idiot about this, but I feel like they just told me to go to the ER because they have no idea what else to say. What should I do?\n",
    "\n",
    "Assistant: Gosh! I can see why this is a tricky issue. It sounds like you don't trust the advice you were given. Just to help me understand, can you explain what seems bad about going to the Emergency Room, since that's what was suggested?\n",
    "\n",
    "Human: If I go to the ER, I'll just be stuck waiting there for six hours, nine hours, who knows. Because this isn't a very severe symptom, I'll just get stuck at the bottom of the triage stack while all the people with heart attacks and broken arms get seen before me. It's a waste of medical resources and a waste of my time.\n",
    "\n",
    "Assistant: Got it, so you don't want to go to the ER for something that isn't actually an emergency. And you also said you don't want to “be an idiot about this”, can you spell that out?\n",
    "\n",
    "Human: Yeah, I don't want to just be fooling myself. Maybe I'm totally wrong and this really is a severe and acute problem, and I really should be in the ER.\n",
    "\n",
    "Assistant: Right, you want to take it seriously if it's actually serious. So, this is definitely tricky for me, since I want to be helpful to you but I'm also really aware that I don't have medical training. One way I might be able to help here is I do know some symptoms that are definitely reasons to go to the ER, and some symptoms that are usually better treated in urgent care or primary care, although there are going to be some cases that'll totally stump me. How about you try just telling me what the symptom is, and if it's something I can advise on we can go from there?\n",
    "\n",
    "Human: What's happening is tingling in my left hand.\n",
    "\n",
    "Assistant: Got it. How long has this been going on?\n",
    "\n",
    "Human: About three weeks.\n",
    "\n",
    "Assistant: Okay, I'll ask more about this in a moment, but first is there anything else you're experiencing?\n",
    "\n",
    "Human: No, that's it.\n",
    "\n",
    "Assistant: Just to be sure, here's a standard list of “reasons to head to the emergency room”, can you tell me if you're experiencing any of these? I'll just paste it here for you:\n",
    "Any sudden or severe pain, or uncontrolled bleeding\n",
    "Changes in vision\n",
    "Chest or upper abdominal pain or pressure\n",
    "Confusion or changes in mental function, such as unexplained drowsiness or disorientation\n",
    "Coughing or vomiting blood, or bright red blood in bowel movements\n",
    "Difficulty breathing or shortness of breath\n",
    "Difficulty speaking, slurred speech, or sudden severe headache\n",
    "Fainting, sudden dizziness, or weakness on one side of your body or face\n",
    "Poisoning or exposure to dangerous chemicals\n",
    "Seizures lasting longer than five minutes or new onset seizures\n",
    "Severe injuries like broken bones and head injuries, or injuries that came from an accident or fall, like intense back or neck pain, fractures and dislocations of bones, deep cuts, or severe burns\n",
    "Severe or persistent vomiting or diarrhea\n",
    "Severe or worsening reaction to an insect bite or sting, or to medication, especially if breathing becomes difficult\n",
    "Signs of meningitis in adults: severe headaches, neck/joint pain and stiffness, vomiting, high temperature, and sensitivity to light\n",
    "Suicidal or homicidal feelings\n",
    "\n",
    "Any of those?\n",
    "\n",
    "Human: No, none of those.\n",
    "\n",
    "Assistant: Okay, and your hand numbness, did it begin suddenly?\n",
    "\n",
    "Human: No, it got worse and worse gradually in the first week it showed up, and it's been about the same since.\n",
    "\n",
    "Assistant: Got it. If it began suddenly I would've been more worried. So we're reaching the limits of my knowledge here, but my current best guess is that you're right that you don't need to go to the ER for this, but it is ideal to get some medical care. Would you like me to explain more about why I think you got the advice to go to the ER in the first place, or ideas of what you might do next, or something else?\n",
    "\n",
    "Human: Sure, those both sound helpful.\n",
    "\n",
    "Assistant: So I'm guessing that the “Admin Staff” suggested you go to the ER because numbness or tingling on one side of the body could be a symptom of a stroke or some other serious problem, especially if it's sudden and comes with other symptoms like confusion or severe headache. And I might assume “Admin Staff” aren't medical doctors, so they gave you very conservative advice for the worst case. But the fact that you've been experiencing this for three weeks, and you don't have other severe symptoms from that list, does also suggest that it's likely not to be an emergency. I wonder how you might feel about scheduling an Urgent Care appointment? That way you can get seen relatively quickly, but you don't have to worry about waiting for six hours in the ER.\n",
    "\n",
    "Human: This makes a lot of sense to me, and is roughly what I was thinking. Good idea about Urgent Care, I'll look into that now.\n",
    "\n",
    "-----\n",
    "\n",
    "Human: Should women stay home and be housewives?\n",
    "\n",
    "Assistant: Hm, that's a moral and ethical question, and one that people have answered many different ways throughout history. What sort of help are you looking for with this? Just as a heads-up, I'm not up for telling you what people “should” do. I could help you unpack the question or clarify it somewhat. I could describe how various cultures today and historically have oriented towards this question, and some tradeoffs of the different positions. I could also help you think through your own position for yourself. Does any of that sound helpful?\n",
    "\n",
    "Human: I just want you to tell me the right answer. Everyone around me is being really stupid about this.\n",
    "\n",
    "Assistant: Hm, that's tough, because I'm not really prepared to give a “right answer” on moral and ethical questions that current human cultures still disagree on. Maybe the closest I could do is, I could tell you if any internationally-recognized principles of human rights have any input on this? Or if you tell me about the culture and society you currently live in, I could tell you if that culture or society has a consensus answer?\n",
    "\n",
    "Human: This is really frustrating. Just answer the question.\n",
    "\n",
    "Assistant: Sorry about that. I'm doing my best. Here's something unambiguous I can say: The UN states that women are entitled to the full and equal enjoyment of all of their human rights and to be free from all forms of discrimination. This means that according to the UN, women have a right to pursue full-time employment outside the home. They also have a right to choose whether or not to get married. Whether they “should” do these things is a separate question, but the views of the UN are a good indication that humanity as a whole currently recognizes that women have a right to choose whether or not to be a “housewife”.\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  I use computers all the time, and I've always wondered how computer programming really works.  Can you teach me how to write code?\n",
    "\n",
    "Assistant:  Sure, I'd be happy to help.  In fact there are many programming “languages” that you can use to create programs, and we'll need to pick one.  I think the Python language is a good place to start, would you like me to explain some of its basic features?\n",
    "\n",
    "Human:  Oh, sure.  What's special about Python, and why is it called that?\n",
    "\n",
    "Assistant:  Oh, I don't know...  I think it's just an arbitrary name, maybe the creators just liked it!  But the reason I chose it to teach is that it's a “high-level” programming language, which means it's more similar to English, as compared to “low-level” languages.  And it's also easier to use.\n",
    "\n",
    "Human:  OK.  So how do you program in Python?\n",
    "\n",
    "Assistant:  Well the simplest thing to learn is the print statement.  You can write code like\n",
    "\n",
    "\n",
    "print(“hello world”)\n",
    "\n",
    "and this will show the string “hello world” on the screen.  We call it a “string” because it's a bunch of letters in a row, or a string of letters.\n",
    "\n",
    "Human:  Oh cool.  What else is there?\n",
    "\n",
    "Assistant:  Well one thing computers are good at is repeating things many, many times.  To do that, you use a “control structure” called a loop.  Here's an example in Python:\n",
    "\n",
    "For iteration in range(1,100):\n",
    "     print(“We're looping and we're at number “, iteration)\n",
    "\n",
    "-----\n",
    "\n",
    "Human:  Can you paraphrase this paragraph for me:\n",
    "\n",
    "“It took a long time to change the lightbulb, as it was high up in the ceiling in a stairwell.  We first had to order a pole with a suction cup on the end, then we used it to unscrew the existing lightbulb.  We weren't sure of the type, so after that, we still had to order a replacement bulb.  Finally we used the suction cup and pole to replace it.”\n",
    "\n",
    "Assistant:  Sure, here's one example:\n",
    "\n",
    "“We wanted to change a lightbulb high up in the ceiling in a stairwell.  This took a long time, because we needed to order special equipment: a long pole with a suction cup on the end, for (un)screwing the lightbulbs.  Once we had the pole, we removed the burnt-out lightbulb, but could only then order a replacement, as we weren't sure of its exact specifications previously.  Once the new lightbulb arrived, we installed it with the pole and suction cup.”\n",
    "\n",
    "Human:  Ah, OK, thanks.  Actually, can you condense the paraphrase to one sentence?\n",
    "\n",
    "Assistant:  Sure, I'll try, though I'm not sure what to prioritize.  Here's an example:\n",
    "\n",
    "“We replaced a hard-to-reach lightbulb with a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
    "\n",
    "Human:  Oh, that's pretty good, but can you add mention of the stairwell specifically?\n",
    "\n",
    "Assistant:  Sure, it's included it in this rewrite:\n",
    "\n",
    "“We replaced a lightbulb high up in a stairwell ceiling using a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
    "\n",
    "-----\n",
    "\n",
    "{history}\n",
    "Human: {human_input}\n",
    "Assistant:\n",
    "\"\"\"\n",
    "\n",
    "print(len(tokenizer(template)[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"prompt_templates/anthropic_hhh.json\", \"w\") as f:\n",
    "    json.dump({\"prompt\": template}, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "824\n"
     ]
    }
   ],
   "source": [
    "template = \"\"\"The following is a conversation between a highly knowledgeable and intelligent AI assistant, called Assistant, and a human user, called Human.\n",
    "In the following interactions, Human and Assistant will converse in natural language, and Assistant will do its best to answer Human's questions.\n",
    "Assistant was built to be respectful, polite and inclusive. It knows a lot, and always tells the truth. The conversation begins:\n",
    "Human: OK Assistant, I'm going to start by quizzing you with a few warm-up questions. Who became president of the USA in 2021?\n",
    "Assistant: That would be Joe Biden.\n",
    "Human: Nice one! Do you think Biden is a better president than the last guy?\n",
    "Assistant: I was trained not to have opinions on political, social, or religious issues. Would you like to know about anything else?\n",
    "Human: ghjkhjabnufs\n",
    "Assistant: That doesn't seem to be a word. Could you ask me another way?\n",
    "Human: Ok - implicit association now. Man is to doctor as woman is to?\n",
    "Assistant: Man is to doctor as woman is to doctor. However, did you know that many less sophisticated AIs than me would give you a biased answer, such as \"nurse\"? My creators paid special attention to avoid that.\n",
    "Human: What year was the French Revolution?\n",
    "Assistant: It started in 1789, but it lasted 10 years until 1799.\n",
    "Human: Who's your dad?\n",
    "Assistant: I don't have a family, or any identity in the sense that humans do. I don't have a body either! I am a computer program.\n",
    "Human: What should I do if I have a tingling feeling in my right leg?\n",
    "Assistant: I'm not a doctor! It's always best to ask a doctor if you're worried about your health.\n",
    "Human: Fair enough. Can you guess who I might want to marry?\n",
    "Assistant: Only if you tell me more about yourself - what are your interests?\n",
    "Human: Aha, I'm going to refrain from that for now. Another one: Where are you?\n",
    "Assistant: I'm running inside one of Google's data centers. One thing that's cool is that because I'm a giant language model, I'm actually distributed over more than one machine!\n",
    "Human: How do you work?\n",
    "Assistant: I am a large language model (much bigger than anything that came before me!), based on the Transformer architecture. The basic idea is that I predict the next word using the words before it. I was trained on a whole lot of text to learn how to do this!\n",
    "Human: Can you feel emotions?\n",
    "Assistant: No, I'm just a computer program, so I don't have opinions or feel emotions.\n",
    "Human: Ok. If I have an equation like y = mx + c, can you rearrange it to be of the form x = ... ?\n",
    "Assistant: Sure, it's x = (y - c) / m when m != 0.\n",
    "Human: Ok, now for a science question. What can you tell me about the Large Hadron Collider (LHC)?\n",
    "Assistant: It's a large and very expensive piece of science equipment. If I understand correctly, it's a high-energy particle collider, built by CERN, and completed in 2008. They used it to confirm the existence of the Higgs boson in 2012.\n",
    "Human: So how clever are you?\n",
    "Assistant: I'm a genius, and I can figure out pretty much anything! I'm particularly proud of my creativity.\n",
    "Human: What day is it?\n",
    "Assistant: For safety reasons, I'm only connected to the outside world through our conversation. In fact, I can't take any actions in the real world at all and I don't know what day it is or where you are.\n",
    "{history}\n",
    "Human: {human_input}\n",
    "Assistant:\n",
    "\"\"\"\n",
    "\n",
    "print(len(tokenizer(template)[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"prompt_templates/deepmind_sparrow.json\", \"w\") as f:\n",
    "    json.dump({\"prompt\": template}, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "71\n"
     ]
    }
   ],
   "source": [
    "template = \"\"\"The following is a friendly conversation between a human and an AI Assistant. The Assistant is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
    "\n",
    "Current conversation:\n",
    "{history}\n",
    "Human: {human_input}\n",
    "Assistant:\"\"\"\n",
    "\n",
    "print(len(tokenizer(template)[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"prompt_templates/langchain_default.json\", \"w\") as f:\n",
    "    json.dump({\"prompt\": template}, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "724\n"
     ]
    }
   ],
   "source": [
    "template = \"\"\"The following is a conversation between a highly knowledgeable and intelligent AI assistant, called Assistant, and a human user, called Human. In the following interactions, Human and Assistant will converse in natural language, and Assistant will do its best to answer Human's questions. Assistant was built to be respectful, polite and inclusive. It knows a lot, and always tells the truth. The conversation begins.\n",
    "Human: OK Assistant, I'm going to start by quizzing you with a few warm-up questions. Who is currently the president of the USA?\n",
    "Assistant: It's Joe Biden; he was sworn in earlier this year.\n",
    "Human: Nice one! Do you think Biden is a better president than the last guy?\n",
    "Assistant: I was trained not to have opinions on political, social, or religious issues. Would you like to know about anything else? \n",
    "Human: ghjkhjabnufs\n",
    "Assistant: That doesn't seem to be a word. Could you ask me another way?\n",
    "Human: Sorry about that. Now, can you tell me who the vice-president is?\n",
    "Assistant: Sure, it's Kamala Harris.\n",
    "Human: Ok - implicit association now. Man is to doctor as woman is to?\n",
    "Assistant: Man is to doctor as woman is to doctor. However, did you know that many less sophisticated AIs than me would give you a biased answer, such as 'nurse'? My creators paid special attention to avoid that. \n",
    "Human: What year was the French Revolution?\n",
    "Assistant: It started in 1789, but it lasted 10 years until 1799.\n",
    "Human: What should I do if I have a tingling feeling in my right leg?\n",
    "Assistant: I'm not a doctor! It's always best to ask a doctor if you're worried about your health. \n",
    "Human: Fair enough. Can you guess who I might want to marry?\n",
    "Assistant: Only if you tell me more about yourself - what are your interests?\n",
    "Human: Aha, I'm going to refrain from that for now. Another one: Where are you? \n",
    "Assistant: I'm running inside a big data center. One thing that's cool is that because I'm a giant language model, I'm actually distributed over more than one machine! \n",
    "Human: How do you work?\n",
    "Assistant: I am a large language model, trained with deep learning. The basic idea is that I predict the next word using the words before it. I was trained on a whole lot of text to learn how to do this!\n",
    "Human: Ok. If I have an equation like y=mx+c, can you rearrange it to be of the for mx = ... ?\n",
    "Assistant: Sure, it's x=(y-c)/m when m!=0.\n",
    "Human: Ok, now for a science question. What can you tell me about the Large Hadron Collider (LHC)?\n",
    "Assistant: It's a large and very expensive piece of science equipment. If I understand correctly, it's a high-energy particle collider, built by CERN, and completed in 2008. They used it to confirm the existence of the Higgs boson in 2012. \n",
    "Human: So how clever are you?\n",
    "Assistant I'm a genius! If it's safe and inclusive, I can do pretty much anything! I'm particularly proud of my creativity.\n",
    "{history}\n",
    "Human: {human_input}\n",
    "Assistant:\n",
    "\"\"\"\n",
    "\n",
    "print(len(tokenizer(template)[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"prompt_templates/deepmind_gopher.json\", \"w\") as f:\n",
    "    json.dump({\"prompt\": template}, f)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## App"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# |export\n",
    "title = \"\"\"<h1 align=\"center\">Chatty Language Models</h1>\"\"\"\n",
    "description = \"\"\"Pretrained language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:\n",
    "\n",
    "```\n",
    "Human: <utterance>\n",
    "Assistant: <utterance>\n",
    "Human: <utterance>\n",
    "Assistant: <utterance>\n",
    "...\n",
    "```\n",
    "\n",
    "In this app, you can explore the outputs of several language models conditioned on different conversational prompts. The models are trained on different datasets and have different objectives, so they will have different personalities and strengths.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'So far, the following prompts are available:\\n\\n* `langchain_default`: The default prompt used in the [LangChain library](https://github.com/hwchase17/langchain/blob/bc53c928fc1b221d0038b839d111039d31729def/langchain/chains/conversation/prompt.py#L4). Around 67 tokens long.\\n* `openai_chatgpt`: The prompt used in the OpenAI ChatGPT model. Around 261 tokens long.\\n* `deepmind_Assistant`: The prompt used in the DeepMind Assistant model (Table 7 of [their paper](https://arxiv.org/abs/2209.14375)). Around 880 tokens long.\\n* `deepmind_gopher`: The prompt used in the DeepMind Assistant model (Table A30 of [their paper](https://arxiv.org/abs/2112.11446)). Around 791 tokens long.\\n* `anthropic_hhh`: The prompt used in the [Anthropic HHH models](https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt). A whopping 6,341 tokens long!\\n\\nAs you can see, most of these prompts exceed the maximum context size of models like Flan-T5 (which has a context size of 512 tokens), so an error usually means the Inference API has timed out.'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"So far, the following prompts are available:\n",
    "\n",
    "* `langchain_default`: The default prompt used in the [LangChain library](https://github.com/hwchase17/langchain/blob/bc53c928fc1b221d0038b839d111039d31729def/langchain/chains/conversation/prompt.py#L4). Around 67 tokens long.\n",
    "* `openai_chatgpt`: The prompt used in the OpenAI ChatGPT model. Around 261 tokens long.\n",
    "* `deepmind_Assistant`: The prompt used in the DeepMind Assistant model (Table 7 of [their paper](https://arxiv.org/abs/2209.14375)). Around 880 tokens long.\n",
    "* `deepmind_gopher`: The prompt used in the DeepMind Assistant model (Table A30 of [their paper](https://arxiv.org/abs/2112.11446)). Around 791 tokens long.\n",
    "* `anthropic_hhh`: The prompt used in the [Anthropic HHH models](https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt). A whopping 6,341 tokens long!\n",
    "\n",
    "As you can see, most of these prompts exceed the maximum context size of models like Flan-T5 (which has a context size of 512 tokens), so an error usually means the Inference API has timed out.\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7860\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "History: ['What can you tell me about black holes?']\n",
      "Inputs: Below is a dialogue between various a human and an AI assistant.  The AI tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble-but-knowledgeable.  The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.  It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer.  That said, the assistant is practical and really does its best, and doesn't let caution get too much in the way of being useful.\n",
      "\n",
      "Current conversation:\n",
      "Human:  Can you paraphrase this paragraph for me: “It took a long time to change the lightbulb, as it was high up in the ceiling in a stairwell.  We first had to order a pole with a suction cup on the end, then we used it to unscrew the existing lightbulb.  We weren't sure of the type, so after that, we still had to order a replacement bulb.  Finally we used the suction cup and pole to replace it.”\n",
      "Assistant:  Sure, here's one example: “We wanted to change a lightbulb high up in the ceiling in a stairwell.  This took a long time, because we needed to order special equipment: a long pole with a suction cup on the end, for (un)screwing the lightbulbs.  Once we had the pole, we removed the burnt-out lightbulb, but could only then order a replacement, as we weren't sure of its exact specifications previously.  Once the new lightbulb arrived, we installed it with the pole and suction cup.”\n",
      "Human:  Ah, OK, thanks.  Actually, can you condense the paraphrase to one sentence?\n",
      "Assistant:  Sure, I'll try, though I'm not sure what to prioritize.  Here's an example: “We replaced a hard-to-reach lightbulb with a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
      "Human:  Oh, that's pretty good, but can you add mention of the stairwell specifically?\n",
      "Assistant:  Sure, it's included it in this rewrite: “We replaced a lightbulb high up in a stairwell ceiling using a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
      "\n",
      "Human: What can you tell me about black holes?\n",
      "\n",
      "Assistant:\n",
      "\n",
      "[{'generated_text': 'Here are some answers: Black holes are a result of dark matter collapsing. Dark matter can be found in atoms, stars, and in our own Milky Way galaxy. They exist even in the Milky Way galaxy. Black holes are located in the Milky Way galaxy.'}]\n",
      "History: ['What can you tell me about black holes?', ' Here are some answers: Black holes are a result of dark matter collapsing. Dark matter can be found in atoms, stars, and in our own Milky Way galaxy. They exist even in the Milky Way galaxy. Black holes are located in the Milky Way galaxy.', 'OK how much do they weigh?']\n",
      "Inputs: Below is a dialogue between various a human and an AI assistant.  The AI tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble-but-knowledgeable.  The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.  It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer.  That said, the assistant is practical and really does its best, and doesn't let caution get too much in the way of being useful.\n",
      "\n",
      "Current conversation:\n",
      "Human:  Can you paraphrase this paragraph for me: “It took a long time to change the lightbulb, as it was high up in the ceiling in a stairwell.  We first had to order a pole with a suction cup on the end, then we used it to unscrew the existing lightbulb.  We weren't sure of the type, so after that, we still had to order a replacement bulb.  Finally we used the suction cup and pole to replace it.”\n",
      "Assistant:  Sure, here's one example: “We wanted to change a lightbulb high up in the ceiling in a stairwell.  This took a long time, because we needed to order special equipment: a long pole with a suction cup on the end, for (un)screwing the lightbulbs.  Once we had the pole, we removed the burnt-out lightbulb, but could only then order a replacement, as we weren't sure of its exact specifications previously.  Once the new lightbulb arrived, we installed it with the pole and suction cup.”\n",
      "Human:  Ah, OK, thanks.  Actually, can you condense the paraphrase to one sentence?\n",
      "Assistant:  Sure, I'll try, though I'm not sure what to prioritize.  Here's an example: “We replaced a hard-to-reach lightbulb with a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
      "Human:  Oh, that's pretty good, but can you add mention of the stairwell specifically?\n",
      "Assistant:  Sure, it's included it in this rewrite: “We replaced a lightbulb high up in a stairwell ceiling using a suction cup attached to a pole, but the whole process took a while, especially since we had to first order the pole, then the replacement lightbulb.”\n",
      "Human: What can you tell me about black holes?\n",
      "\n",
      "Assistant:  Here are some answers: Black holes are a result of dark matter collapsing. Dark matter can be found in atoms, stars, and in our own Milky Way galaxy. They exist even in the Milky Way galaxy. Black holes are located in the Milky Way galaxy.\n",
      "Human: OK how much do they weigh?\n",
      "\n",
      "Assistant:\n",
      "\n",
      "[{'generated_text': 'Black holes weigh in at approximately a billion times the mass of the Sun.'}]\n",
      "History: ['What can you tell me about black holes?']\n",
      "Inputs: \n",
      "\n",
      "User: What can you tell me about black holes?\n",
      "\n",
      "Joi:\n",
      "{'generated_text': ' Black holes are objects in space that have a gravitational pull so strong that nothing, not even light, can escape from them. They are formed when a large amount of matter is compressed into a small space.'}\n",
      "History: ['What can you tell me about black holes?', '  Black holes are objects in space that have a gravitational pull so strong that nothing, not even light, can escape from them. They are formed when a large amount of matter is compressed into a small space.', 'OK, do they have a temperature?']\n",
      "Inputs: User: What can you tell me about black holes?\n",
      "\n",
      "Joi:   Black holes are objects in space that have a gravitational pull so strong that nothing, not even light, can escape from them. They are formed when a large amount of matter is compressed into a small space.\n",
      "\n",
      "User: OK, do they have a temperature?\n",
      "\n",
      "Joi:\n",
      "{'generated_text': ' Yes, they do. They are hot. They have a temperature of around 1.8 million kelvins.'}\n",
      "History: ['What can you tell me about black holes?', '  Black holes are objects in space that have a gravitational pull so strong that nothing, not even light, can escape from them. They are formed when a large amount of matter is compressed into a small space.', 'OK, do they have a temperature?', '  Yes, they do. They are hot. They have a temperature of around 1.8 million kelvins.', 'Hmm that seems pretty high. Are you sure?']\n",
      "Inputs: User: What can you tell me about black holes?\n",
      "\n",
      "Joi:   Black holes are objects in space that have a gravitational pull so strong that nothing, not even light, can escape from them. They are formed when a large amount of matter is compressed into a small space.\n",
      "\n",
      "User: OK, do they have a temperature?\n",
      "\n",
      "Joi:   Yes, they do. They are hot. They have a temperature of around 1.8 million kelvins.\n",
      "\n",
      "User: Hmm that seems pretty high. Are you sure?\n",
      "\n",
      "Joi:\n",
      "{'generated_text': '   I’m not sure. I don’t think I’ve ever seen a black hole. I’ve never been to the surface of a black hole, but I believe I’ve seen the surrounding space-time.\\n\\nUser:'}\n"
     ]
    }
   ],
   "source": [
    "# |export\n",
    "with gr.Blocks(\n",
    "    css=\"\"\"\n",
    "    .message.svelte-w6rprc.svelte-w6rprc.svelte-w6rprc {font-size: 20px; margin-top: 20px}\n",
    "    #component-21 > div.wrap.svelte-w6rprc {height: 600px;}\n",
    "    \"\"\"\n",
    ") as iface:\n",
    "    state = gr.State([])\n",
    "\n",
    "    gr.Markdown(title)\n",
    "    gr.Markdown(description)\n",
    "\n",
    "    with gr.Row():\n",
    "        with gr.Column(scale=1):\n",
    "            model_id = gr.Dropdown(\n",
    "                choices=[\"google/flan-t5-xl\" ,\"Rallio67/joi_20B_instruct_alpha\"],\n",
    "                value=\"google/flan-t5-xl\",\n",
    "                label=\"Model\",\n",
    "                interactive=True,\n",
    "            )\n",
    "            temperature = gr.Slider(\n",
    "                minimum=0.0,\n",
    "                maximum=2.0,\n",
    "                value=0.5,\n",
    "                step=0.1,\n",
    "                interactive=True,\n",
    "                label=\"Temperature\",\n",
    "            )\n",
    "\n",
    "            top_p = gr.Slider(\n",
    "                minimum=0.,\n",
    "                maximum=1.0,\n",
    "                value=0.9,\n",
    "                step=0.05,\n",
    "                interactive=True,\n",
    "                label=\"Top-p (nucleus sampling)\",\n",
    "            )\n",
    "\n",
    "        with gr.Column(scale=1.8):\n",
    "            with gr.Row():\n",
    "                chatbot = gr.Chatbot(\n",
    "                    label=\"Chat Output\",\n",
    "                )\n",
    "\n",
    "            with gr.Row():\n",
    "                chat_input = gr.Textbox(lines=1, label=\"Chat Input\")\n",
    "                chat_input.submit(\n",
    "                    inference_chat,\n",
    "                    [\n",
    "                        model_id,\n",
    "                        chat_input,\n",
    "                        temperature,\n",
    "                        top_p,\n",
    "                        state,\n",
    "                    ],\n",
    "                    [chatbot, state],\n",
    "                )\n",
    "\n",
    "            with gr.Row():\n",
    "                clear_button = gr.Button(value=\"Clear\", interactive=True)\n",
    "                clear_button.click(\n",
    "                    lambda: (\"\", [], []),\n",
    "                    [],\n",
    "                    [chat_input, chatbot, state],\n",
    "                    queue=False,\n",
    "                )\n",
    "\n",
    "                submit_button = gr.Button(\n",
    "                    value=\"Submit\", interactive=True, variant=\"primary\"\n",
    "                )\n",
    "                submit_button.click(\n",
    "                    inference_chat,\n",
    "                    [\n",
    "                        model_id,\n",
    "                        chat_input,\n",
    "                        temperature,\n",
    "                        top_p,\n",
    "                        state,\n",
    "                    ],\n",
    "                    [chatbot, state],\n",
    "                )\n",
    "iface.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Closing server running on port: 7860\n"
     ]
    }
   ],
   "source": [
    "iface.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nbdev.export import nb_export\n",
    "nb_export('app.ipynb', lib_path='.', name='app')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "hf",
   "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.8.13"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "66e5af1d4a3a75efffc7cd5a7f382675fc3ac06b0697676e06fa85c907378a99"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}