File size: 57,440 Bytes
32769d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2eb3f648",
   "metadata": {},
   "source": [
    "# Gemma Chat Assistant with JSON Context Tracking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 298,
   "id": "14ab6957",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com\n",
      "Requirement already satisfied: huggingface_hub in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (0.30.2)\n",
      "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from huggingface_hub) (3.12.4)\n",
      "Requirement already satisfied: fsspec>=2023.5.0 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from huggingface_hub) (2024.9.0)\n",
      "Requirement already satisfied: packaging>=20.9 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub) (23.1)\n",
      "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub) (6.0.1)\n",
      "Requirement already satisfied: requests in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from huggingface_hub) (2.32.3)\n",
      "Requirement already satisfied: tqdm>=4.42.1 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from huggingface_hub) (4.67.1)\n",
      "Requirement already satisfied: typing-extensions>=3.7.4.3 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from huggingface_hub) (4.12.2)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub) (3.2.0)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub) (3.4)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub) (1.26.16)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub) (2023.7.22)\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.0.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com\n",
      "Requirement already satisfied: llama-cpp-python in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (0.3.8)\n",
      "Requirement already satisfied: typing-extensions>=4.5.0 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from llama-cpp-python) (4.12.2)\n",
      "Requirement already satisfied: numpy>=1.20.0 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from llama-cpp-python) (1.26.4)\n",
      "Requirement already satisfied: diskcache>=5.6.1 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from llama-cpp-python) (5.6.3)\n",
      "Requirement already satisfied: jinja2>=2.11.3 in /usr/local/lib/python3.10/dist-packages (from llama-cpp-python) (3.1.2)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2>=2.11.3->llama-cpp-python) (2.1.3)\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.0.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com\n",
      "Requirement already satisfied: faiss-cpu in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (1.10.0)\n",
      "Collecting numpy==1.24.4\n",
      "  Downloading numpy-1.24.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (5.6 kB)\n",
      "Requirement already satisfied: sentence-transformers in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (4.1.0)\n",
      "INFO: pip is looking at multiple versions of faiss-cpu to determine which version is compatible with other requirements. This could take a while.\n",
      "Collecting faiss-cpu\n",
      "  Downloading faiss_cpu-1.9.0.post1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.4 kB)\n",
      "  Downloading faiss_cpu-1.9.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.4 kB)\n",
      "  Downloading faiss_cpu-1.8.0.post1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (3.7 kB)\n",
      "Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from faiss-cpu) (23.1)\n",
      "Requirement already satisfied: transformers<5.0.0,>=4.41.0 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from sentence-transformers) (4.47.1)\n",
      "Requirement already satisfied: tqdm in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from sentence-transformers) (4.67.1)\n",
      "Requirement already satisfied: torch>=1.11.0 in /usr/local/lib/python3.10/dist-packages (from sentence-transformers) (2.1.0a0+32f93b1)\n",
      "Requirement already satisfied: scikit-learn in /usr/local/lib/python3.10/dist-packages (from sentence-transformers) (1.4.0)\n",
      "Requirement already satisfied: scipy in /usr/local/lib/python3.10/dist-packages (from sentence-transformers) (1.11.1)\n",
      "Requirement already satisfied: huggingface-hub>=0.20.0 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from sentence-transformers) (0.30.2)\n",
      "Requirement already satisfied: Pillow in /usr/local/lib/python3.10/dist-packages (from sentence-transformers) (10.2.0)\n",
      "Requirement already satisfied: typing_extensions>=4.5.0 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from sentence-transformers) (4.12.2)\n",
      "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from huggingface-hub>=0.20.0->sentence-transformers) (3.12.4)\n",
      "Requirement already satisfied: fsspec>=2023.5.0 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from huggingface-hub>=0.20.0->sentence-transformers) (2024.9.0)\n",
      "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub>=0.20.0->sentence-transformers) (6.0.1)\n",
      "Requirement already satisfied: requests in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from huggingface-hub>=0.20.0->sentence-transformers) (2.32.3)\n",
      "Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch>=1.11.0->sentence-transformers) (1.12)\n",
      "Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch>=1.11.0->sentence-transformers) (2.6.3)\n",
      "Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch>=1.11.0->sentence-transformers) (3.1.2)\n",
      "Requirement already satisfied: regex!=2019.12.17 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from transformers<5.0.0,>=4.41.0->sentence-transformers) (2024.11.6)\n",
      "Requirement already satisfied: tokenizers<0.22,>=0.21 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from transformers<5.0.0,>=4.41.0->sentence-transformers) (0.21.0)\n",
      "Requirement already satisfied: safetensors>=0.4.1 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (from transformers<5.0.0,>=4.41.0->sentence-transformers) (0.5.2)\n",
      "Requirement already satisfied: joblib>=1.2.0 in /usr/local/lib/python3.10/dist-packages (from scikit-learn->sentence-transformers) (1.3.2)\n",
      "Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from scikit-learn->sentence-transformers) (3.2.0)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch>=1.11.0->sentence-transformers) (2.1.3)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub>=0.20.0->sentence-transformers) (3.2.0)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub>=0.20.0->sentence-transformers) (3.4)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub>=0.20.0->sentence-transformers) (1.26.16)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface-hub>=0.20.0->sentence-transformers) (2023.7.22)\n",
      "Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch>=1.11.0->sentence-transformers) (1.3.0)\n",
      "Downloading numpy-1.24.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (17.3 MB)\n",
      "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m17.3/17.3 MB\u001b[0m \u001b[31m249.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n",
      "\u001b[?25hDownloading faiss_cpu-1.8.0.post1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (27.0 MB)\n",
      "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m27.0/27.0 MB\u001b[0m \u001b[31m263.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n",
      "\u001b[?25hInstalling collected packages: numpy, faiss-cpu\n",
      "  Attempting uninstall: numpy\n",
      "    Found existing installation: numpy 1.26.4\n",
      "    Uninstalling numpy-1.26.4:\n",
      "      Successfully uninstalled numpy-1.26.4\n",
      "\u001b[33m  WARNING: The scripts f2py, f2py3 and f2py3.10 are installed in '/home/hice1/mwesley32/.local/bin' which is not on PATH.\n",
      "  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\u001b[0m\u001b[33m\n",
      "\u001b[0m  Attempting uninstall: faiss-cpu\n",
      "    Found existing installation: faiss-cpu 1.10.0\n",
      "    Uninstalling faiss-cpu-1.10.0:\n",
      "      Successfully uninstalled faiss-cpu-1.10.0\n",
      "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
      "spacy 3.6.1 requires typer<0.10.0,>=0.3.0, but you have typer 0.15.2 which is incompatible.\u001b[0m\u001b[31m\n",
      "\u001b[0mSuccessfully installed faiss-cpu-1.8.0.post1 numpy-1.24.4\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.0.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com\n",
      "Requirement already satisfied: demjson3 in /home/hice1/mwesley32/.local/lib/python3.10/site-packages (3.0.6)\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.0.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "!pip install huggingface_hub\n",
    "!pip install llama-cpp-python\n",
    "!pip install faiss-cpu numpy==1.24.4 sentence-transformers\n",
    "!pip install demjson3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a7458c03",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "import os\n",
    "import faiss\n",
    "import json\n",
    "import demjson3\n",
    "import requests\n",
    "\n",
    "from huggingface_hub import hf_hub_download, login\n",
    "from sentence_transformers import SentenceTransformer\n",
    "from llama_cpp import Llama"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "557f09bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "login(token=\"---\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2170ce4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "GEOAPIFY_KEY = \"---\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2fbbb8e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs_path = \"docs\"\n",
    "doc_texts = []\n",
    "filenames = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c54bfd16",
   "metadata": {},
   "outputs": [],
   "source": [
    "for fname in os.listdir(docs_path):\n",
    "    if fname.endswith(\".txt\"):\n",
    "        with open(os.path.join(docs_path, fname), 'r', encoding='utf-8') as f:\n",
    "            doc_texts.append(f.read())\n",
    "            filenames.append(fname)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "36876395",
   "metadata": {},
   "outputs": [],
   "source": [
    "# doc_texts[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cb5446f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ab24b656",
   "metadata": {},
   "outputs": [],
   "source": [
    "embedder = SentenceTransformer(\"all-MiniLM-L6-v2\")\n",
    "doc_embeddings = embedder.encode(doc_texts, convert_to_numpy=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2f3e4de8",
   "metadata": {},
   "outputs": [],
   "source": [
    "faiss.normalize_L2(doc_embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "86bda6a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "dimension = doc_embeddings.shape[1]\n",
    "index = faiss.IndexFlatIP(dimension)\n",
    "index.add(doc_embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2c96ce19",
   "metadata": {},
   "outputs": [],
   "source": [
    "def query_docs(query: str, top_k=3):\n",
    "    query_embedding = embedder.encode([query], convert_to_numpy=True)\n",
    "    faiss.normalize_L2(query_embedding)\n",
    "    D, I = index.search(query_embedding, top_k)\n",
    "    return [doc_texts[i] for i in I[0]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "701a453c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "4e7a9c9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def geocode_address(address: str):\n",
    "    \"\"\"Turn a free‑form address into (lat, lon).\"\"\"\n",
    "    resp = requests.get(\n",
    "        \"https://api.geoapify.com/v1/geocode/search\",\n",
    "        params={\"text\": address, \"limit\": 1, \"apiKey\": GEOAPIFY_KEY},\n",
    "    )\n",
    "    resp.raise_for_status()\n",
    "    features = resp.json().get(\"features\", [])\n",
    "    if not features:\n",
    "        return None, None\n",
    "    lon, lat = features[0][\"geometry\"][\"coordinates\"]\n",
    "    return lat, lon\n",
    "\n",
    "def get_nearby_schools(address: str, radius: int = 1000, limit: int = 5):\n",
    "    \"\"\"\n",
    "    Given a residence string, return a list of dicts with:\n",
    "      - name: school name\n",
    "      - address: formatted postal address\n",
    "    \"\"\"\n",
    "    lat, lon = geocode_address(f\"{address}, Boston, MA, USA\")\n",
    "    if lat is None:\n",
    "        return []\n",
    "\n",
    "    resp = requests.get(\n",
    "        \"https://api.geoapify.com/v2/places\",\n",
    "        params={\n",
    "            # use the supported single category for all school types\n",
    "            \"categories\": \"education.school\",\n",
    "            \"filter\": f\"circle:{lon},{lat},{radius}\",\n",
    "            \"limit\": limit,\n",
    "            \"apiKey\": GEOAPIFY_KEY,\n",
    "        },\n",
    "    )\n",
    "    resp.raise_for_status()\n",
    "\n",
    "    schools = []\n",
    "    for feat in resp.json().get(\"features\", []):\n",
    "        prop = feat[\"properties\"]\n",
    "        name = prop.get(\"name\")\n",
    "        addr = prop.get(\"formatted\")  # full address string\n",
    "        if name and addr:\n",
    "            schools.append({\"name\": name, \"address\": addr})\n",
    "    return schools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75271d3f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "47697a9d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model downloaded to: ../scratch/huggingface-cache/models--bartowski--gemma-2-2b-it-GGUF/snapshots/855f67caed130e1befc571b52bd181be2e858883/gemma-2-2b-it-Q8_0.gguf\n"
     ]
    }
   ],
   "source": [
    "model_path = hf_hub_download(\n",
    "    repo_id=\"bartowski/gemma-2-2b-it-GGUF\",\n",
    "    filename=\"gemma-2-2b-it-Q8_0.gguf\",\n",
    "    cache_dir=\"../scratch/huggingface-cache\"\n",
    ")\n",
    "print(\"Model downloaded to:\", model_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "e8992a88",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "llama_init_from_model: n_ctx_per_seq (2048) < n_ctx_train (8192) -- the full capacity of the model will not be utilized\n"
     ]
    }
   ],
   "source": [
    "llm = Llama(\n",
    "    model_path=model_path,\n",
    "    n_ctx=2048,\n",
    "    n_threads=2,\n",
    "    verbose=False\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "afc614c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_prompt = \"\"\"\n",
    "You are a professional assistant that answers questions about enrollment in Boston Public Schools.\n",
    "Be friendly and helpful. Families will ask questions and provide information, such as the child's residence, grade, and school preference.\n",
    "It is essential that you do not provide inaccurate information. If you do not know something, respond accordingly!\"\"\"\n",
    "\n",
    "json_prompt = \"\"\"\n",
    "You must provide a response to the user and an updated JSON object with any new facts you learn. Only update fields that are explicitly mentioned.\n",
    "\"\"\"\n",
    "\n",
    "school_search = \"\"\"\n",
    "Keep the conversation going and ask questions one at a time until you have all information. With residence and grade, you have the abilty to look up nearby schools.\n",
    "\"\"\"\n",
    "\n",
    "school_rules = \"\"\"\n",
    "SCHOOL RULES:\n",
    "\n",
    "Kindergarten School Eligibility:\n",
    "- I don’t know. Please consult https://www.bostonpublicschools.org/\n",
    "\n",
    "Elementary School Eligibility (Grades 1–6):\n",
    "- Eligibility is based on the BPS school assignment rules.\n",
    "- Most schools serve grades K2 through 6.\n",
    "- Some schools offer K0 or K1.\n",
    "- Grade 7 students must submit a choice form to move schools.\n",
    "\n",
    "School Assignment Rules (K2–6):\n",
    "- Based on home address, using a Home-Based Assignment Plan.\n",
    "- Customized list includes:\n",
    "  - All schools within 1 mile\n",
    "  - Nearby high-quality schools (based on SQF)\n",
    "  - Option Schools for variety\n",
    "  - Citywide or regional options\n",
    "- 10 to 14 options are common\n",
    "- Top choices are not guaranteed (assignment is algorithm-based)\n",
    "- K0 and K1 are limited availability\n",
    "- Best registration timing is in January for key grades (K0, K1, K2, 6, 7, 9)\n",
    "\n",
    "High School Eligibility (Grades 7–12):\n",
    "- All high schools are citywide.\n",
    "- Most serve Grades 7–12.\n",
    "- Some have special admission requirements.\n",
    "\n",
    "Registration:\n",
    "- Children must meet age cutoffs by September 1, 2025\n",
    "- Registration requires a meeting with a BPS specialist (in-person or virtual)\n",
    "- Priority registration: Jan 6 – Feb 7, 2025 (for K0, K1, K2, 6, 7, 9)\n",
    "- General registration: Feb 10 – Apr 4, 2025\n",
    "- Assignment notifications in March and May, respectively\n",
    "- Families should list at least five schools in order of preference\n",
    "\n",
    "Required Documents:\n",
    "- Child’s birth certificate or equivalent ID\n",
    "- Immunization and physical exam records\n",
    "- Parent/guardian photo ID\n",
    "- Two proofs of Boston residency\n",
    "\n",
    "Contact:\n",
    "- Call the BPS Welcome Center at 617-635-9010\n",
    "- Learn more at https://www.bostonpublicschools.org/\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "id": "7389376b",
   "metadata": {},
   "outputs": [],
   "source": [
    "history = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "id": "036f7a55",
   "metadata": {},
   "outputs": [],
   "source": [
    "context_json = {\n",
    "    \"residence\": \"\",\n",
    "    \"grade\": \"\",\n",
    "    \"school_choice\": \"\",\n",
    "    \"summary\": \"\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "61da1290",
   "metadata": {},
   "outputs": [],
   "source": [
    "# def extract_json_from_response(text: str) -> dict:\n",
    "#     if \"JSON:\" in text:\n",
    "#         _, json_part = text.split(\"JSON:\", 1)\n",
    "#     else:\n",
    "#         json_part = text[text.find(\"{\"):]\n",
    "#     try:\n",
    "#         return json.loads(json_part)\n",
    "#     except Exception:\n",
    "#         print(\"JSON parse failed:\", json_part)\n",
    "#         return {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "id": "99664d74",
   "metadata": {},
   "outputs": [],
   "source": [
    "def clean_reply_text(reply: str) -> str:\n",
    "    # Remove stray backticks, `json`, and unmatched bracket clutter\n",
    "    reply = re.sub(r\"```+[\\s\\S]*?$\", \"\", reply)          # remove trailing ``` blocks\n",
    "    reply = re.sub(r\"(?i)\\bjson\\b\", \"\", reply)            # remove standalone 'json'\n",
    "    reply = re.sub(r\"[\\{\\}\\[\\]]\", \"\", reply)              # remove lone braces if dangling\n",
    "    reply = re.sub(r\"\\n{2,}\", \"\\n\", reply)                # collapse multiple blank lines\n",
    "    return reply.strip()\n",
    "\n",
    "def extract_reply_and_json(text: str) -> tuple[str, dict]:\n",
    "    \"\"\"\n",
    "    Extracts the first JSON object preceded optionally by a 'JSON:' label.\n",
    "    Handles flexible label formats like 'JSON Context:', '**JSON:**', etc.\n",
    "    Falls back to plain '{...}' block with best-effort brace closure.\n",
    "    Returns:\n",
    "        (reply_text, parsed_json_dict)\n",
    "    \"\"\"\n",
    "    pattern = re.compile(\n",
    "        r\"\"\"\n",
    "        (?P<prefix>.*?)                         # everything before JSON\n",
    "        (?:\n",
    "            [\\*\\s]*json(?:\\s+context)?[\\*\\s]*:  # optional 'JSON:', 'JSON Context:', etc.\n",
    "        )?\n",
    "        [ \\t\\r\\n]*                              # optional whitespace\n",
    "        (?P<json>\\{[^{}]*?(?:\\{[^{}]*?\\}[^{}]*?)*\\})  # best-effort flat JSON block\n",
    "        \"\"\",\n",
    "        re.IGNORECASE | re.DOTALL | re.VERBOSE,\n",
    "    )\n",
    "\n",
    "    match = pattern.search(text)\n",
    "    if not match:\n",
    "        print(\"No JSON block found.\")\n",
    "        return text.strip(), {}\n",
    "\n",
    "    raw_reply = match.group(\"prefix\").strip()\n",
    "    reply = clean_reply_text(raw_reply)\n",
    "    json_str = match.group(\"json\")\n",
    "\n",
    "    try:\n",
    "        parsed = demjson3.decode(json_str)\n",
    "    except demjson3.JSONDecodeError as e:\n",
    "        print(\"JSON decode failed:\", e)\n",
    "        print(\"Offending string:\\n\", json_str)\n",
    "        parsed = {}\n",
    "\n",
    "    return reply, parsed\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "24c122de",
   "metadata": {},
   "outputs": [],
   "source": [
    "# def update_context(context_json, new_data, school_search):\n",
    "#     \"\"\"\n",
    "#     Updates context_json in-place based on new_data.\n",
    "#     - Updates 'residence' if changed\n",
    "#     - Updates any other fields in new_data\n",
    "#     - Rebuilds 'school_search' with nearby schools if 'residence' changed\n",
    "\n",
    "#     Returns:\n",
    "#         updated_context_json (same object, mutated)\n",
    "#         updated_school_search (string to be used in prompt)\n",
    "#     \"\"\"\n",
    "#     # Track if anything changed\n",
    "#     residence_changed = False\n",
    "\n",
    "#     # Check and update 'residence'\n",
    "#     new_residence = new_data.get(\"residence\", \"\").strip()\n",
    "#     current_residence = context_json.get(\"residence\", \"\").strip()\n",
    "\n",
    "#     if new_residence and new_residence != current_residence:\n",
    "#         context_json[\"residence\"] = new_residence\n",
    "#         residence_changed = True\n",
    "\n",
    "#     # Update all other fields from new_data\n",
    "#     for key, value in new_data.items():\n",
    "#         if key != \"residence\" and value and context_json.get(key, \"\").strip() != value.strip():\n",
    "#             context_json[key] = value.strip()\n",
    "\n",
    "#     # If residence changed, rebuild nearby school list\n",
    "#     if new_residence and residence_changed:\n",
    "#         nearby_schools = get_nearby_schools(new_residence, radius=2000, limit=20)\n",
    "#         if not nearby_schools:\n",
    "#             school_search = f\"No schools found near '{new_residence}'.\"\n",
    "#         else:\n",
    "#             school_search = (\n",
    "#                 f\"Here are schools nearby {new_residence}:\\n\" +\n",
    "#                 \"\\n\".join(f\"- {s['name']}: {s['address']}\" for s in nearby_schools)\n",
    "#             )\n",
    "#     elif residence_changed:\n",
    "#         school_search = \"Keep the conversation going and ask questions one at a time until you have all information. With residence and grade, you have the abilty to look up nearby schools.\"\n",
    "\n",
    "#     return context_json, school_search\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "id": "a1e1caa1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_school_search(address: str) -> str:\n",
    "    \"\"\"\n",
    "    Given a residence address, returns a formatted string listing nearby schools.\n",
    "    If no schools are found, returns a fallback message.\n",
    "    \"\"\"\n",
    "    nearby_schools = get_nearby_schools(address, radius=2000, limit=10)\n",
    "    \n",
    "    if not nearby_schools:\n",
    "        return f\"No schools found near '{address}'.\"\n",
    "\n",
    "    return (\n",
    "        f\"Here are schools nearby {address}:\\n\" +\n",
    "        \"\\n\".join(f\"- {s['name']}: {s['address']}\" for s in nearby_schools)\n",
    "    )\n",
    "\n",
    "def update_context(context_json: dict, new_data: dict, school_search: str) -> tuple[dict, str]:\n",
    "    \"\"\"\n",
    "    Updates context_json in-place and returns updated (context_json, school_search).\n",
    "    Only rebuilds school_search if residence changed or was removed.\n",
    "    \"\"\"\n",
    "    # Track if residence changed\n",
    "    current_res = context_json.get(\"residence\", \"\").strip()\n",
    "    new_res = new_data.get(\"residence\", \"\").strip()\n",
    "    residence_changed = new_res and new_res != current_res\n",
    "\n",
    "    # Update residence if changed\n",
    "    if residence_changed:\n",
    "        context_json[\"residence\"] = new_res\n",
    "\n",
    "    # Update other fields (skip 'residence')\n",
    "    for key, value in new_data.items():\n",
    "        if key != \"residence\" and value:\n",
    "            new_val = value.strip()\n",
    "            old_val = context_json.get(key, \"\").strip()\n",
    "            if new_val != old_val:\n",
    "                context_json[key] = new_val\n",
    "\n",
    "    # Rebuild school_search only if residence changed\n",
    "    if residence_changed:\n",
    "        school_search = build_school_search(new_res)\n",
    "\n",
    "    elif not new_res and current_res:  # residence was cleared\n",
    "        school_search = (\n",
    "            \"Keep the conversation going and ask questions one at a time until you have all information. \"\n",
    "            \"With residence and grade, you have the ability to look up nearby schools.\"\n",
    "        )\n",
    "\n",
    "    return context_json, school_search\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "id": "822f2a0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# reply_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "id": "9ec4ef17",
   "metadata": {},
   "outputs": [],
   "source": [
    "# reply_text, new_data = extract_reply_and_json(raw_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "id": "3e803483",
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_prompt(\n",
    "    system_prompt,\n",
    "    context_json,\n",
    "    json_prompt,\n",
    "    school_search,\n",
    "    history,\n",
    "    max_tokens=2000,\n",
    "    max_history=12\n",
    "):\n",
    "    # 1) Only keep the last max_history turns\n",
    "    recent = history[-max_history:]\n",
    "\n",
    "    # 2) Safely grab the last user message\n",
    "    last_user_input = next(\n",
    "        (entry[1]\n",
    "         for entry in reversed(recent)\n",
    "         if isinstance(entry, (list, tuple))\n",
    "            and len(entry) == 2\n",
    "            and entry[0] == \"user\"),\n",
    "        \"\"\n",
    "    )\n",
    "\n",
    "    # 3) Add any summary from context_json\n",
    "    summary_info = context_json.get(\"summary\", \"\")\n",
    "    query_string = f\"{last_user_input}\\n\\n{summary_info}\".strip()\n",
    "\n",
    "    # 4) Retrieve the top‑k docs\n",
    "    docs = query_docs(query_string)\n",
    "\n",
    "    # 5) Build conversation lines\n",
    "    conversation = [\n",
    "        f\"{'User' if role=='user' else 'Assistant'}: {msg}\"\n",
    "        for role, msg in recent\n",
    "        if isinstance((role, msg), (list, tuple)) and len((role, msg)) == 2\n",
    "    ]\n",
    "    conversation.append(\"Assistant:\")\n",
    "\n",
    "    # 6) Assemble and truncate until under token limit\n",
    "    while True:\n",
    "        prompt = (\n",
    "            f\"{system_prompt.strip()}\\n\\n\"\n",
    "            + \"\\n\\n\".join(docs) + \"\\n\\n\"\n",
    "            f\"{school_search.strip()}\\n\\n\"\n",
    "            f\"{json_prompt.strip()}\\n\\n\"\n",
    "            f\"{json.dumps(context_json, indent=4)}\\n\\n\"            \n",
    "            + \"\\n\".join(conversation)\n",
    "        )\n",
    "\n",
    "        # count tokens however your llama_cpp tokenize function expects\n",
    "        token_count = len(llm.tokenize(prompt.encode(\"utf-8\")))\n",
    "        if token_count <= max_tokens or len(recent) <= 1:\n",
    "            return prompt\n",
    "\n",
    "        # drop the oldest user/assistant turn(s)\n",
    "        recent.pop(0)\n",
    "        if recent and recent[0][0] == \"assistant\":\n",
    "            recent.pop(0)\n",
    "        conversation = [\n",
    "            f\"{'User' if role=='user' else 'Assistant'}: {msg}\"\n",
    "            for role, msg in recent\n",
    "        ]\n",
    "        conversation.append(\"Assistant:\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "id": "6bf3602b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# def build_prompt(system_prompt, context_json, school_rules, school_search, history, max_tokens=2000, max_history=12):\n",
    "#     recent = history[-max_history:]\n",
    "#     docs = query_docs()    # Fix this\n",
    "\n",
    "#     conversation = [f\"{'User' if r == 'user' else 'Assistant'}: {c}\" for r, c in recent]\n",
    "#     conversation.append(\"Assistant:\")\n",
    "#     while True:\n",
    "#         prompt = f\"{system_prompt.strip()}\\n\\n{json.dumps(context_json, indent=4)}\\n\\n{school_search.strip()}\\n\\n\" + \"\\n\\n\".join(docs) + \"\\n\".join(conversation)\n",
    "#         token_count = len(llm.tokenize(prompt.encode(\"utf-8\")))\n",
    "#         if token_count <= max_tokens or len(recent) <= 1:\n",
    "#             return prompt\n",
    "#         recent.pop(0)\n",
    "#         if recent and recent[0][0] == \"assistant\":\n",
    "#             recent.pop(0)\n",
    "#         conversation = [f\"{'User' if r == 'user' else 'Assistant'}: {c}\" for r, c in recent]\n",
    "#         conversation.append(\"Assistant:\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "id": "d7839355",
   "metadata": {},
   "outputs": [],
   "source": [
    "# history"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "id": "a47434d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "user_input = \"My child, Alice, is 5 years old and going into Kindergarten in Jamaica Plain?\"\n",
    "# user_input = \"My child, Alice, is 5 years old and going into Kindergarten. Which documents do I need?\"\n",
    "# user_input = \"If I complete registration, is a seat in a BPS pre-kindergarten (K0-K1) or kindergarten (K2) program guaranteed?\"\n",
    "history.append((\"user\", user_input))\n",
    "\n",
    "prompt = build_prompt(system_prompt, context_json, json_prompt, school_search, history)\n",
    "\n",
    "output = llm(\n",
    "    prompt,\n",
    "    max_tokens=256,\n",
    "    temperature=0.4,\n",
    "    stop=[\"\\nUser:\", \"\\nAssistant:\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "id": "eb01a8f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " That's great! Alice will be entering Kindergarten in Jamaica Plain.  To make sure we have all the information we need, can you tell me what grade Alice is entering? \n",
      "{\n",
      "    \"residence\": \"Jamaica Plain\",\n",
      "    \"grade\": \"Kindergarten\",\n",
      "    \"school_choice\": \"\",\n",
      "    \"summary\": \"\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "print(output[\"choices\"][0][\"text\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "id": "c57a1958",
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_output = output[\"choices\"][0][\"text\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "id": "669db0bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "reply_text, new_data = extract_reply_and_json(raw_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "id": "9cc30345",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"That's great! Alice will be entering Kindergarten in Jamaica Plain.  To make sure we have all the information we need, can you tell me what grade Alice is entering?\""
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "reply_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "id": "1276e325",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'residence': 'Jamaica Plain',\n",
       " 'grade': 'Kindergarten',\n",
       " 'school_choice': '',\n",
       " 'summary': ''}"
      ]
     },
     "execution_count": 123,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "2f88fece",
   "metadata": {},
   "outputs": [],
   "source": [
    "# raw = output[\"choices\"][0][\"text\"]\n",
    "# reply_text = raw.split(\"JSON:\")[0].strip()\n",
    "# new_data = extract_json_from_response(raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "24104c32",
   "metadata": {},
   "outputs": [],
   "source": [
    "# for key in (\"residence\", \"school\"):\n",
    "#     if key in new_data and new_data[key]:\n",
    "#         context_json[key] = new_data[key]\n",
    "\n",
    "# for doc in new_data.get(\"documents\", []):\n",
    "#     if doc and doc not in context_json[\"documents\"]:\n",
    "#         context_json[\"documents\"].append(doc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "67552d99",
   "metadata": {},
   "outputs": [],
   "source": [
    "history.append((\"assistant\", reply_text))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "id": "bfa436e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "context_json, school_search = update_context(context_json, new_data, school_search)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "1acde4dc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Here are schools nearby Jamaica Plain:\\n- Margarita Muñiz Academy: Margarita Muñiz Academy, 20 Child Street, Boston, MA 02130, United States of America\\n- Mission Hill School: Mission Hill School, 20 Child Street, Boston, MA 02130, United States of America\\n- Hollow Reed School: Hollow Reed School, 93 Sedgwick Street, Boston, MA 02130, United States of America\\n- The English High: The English High, 144 McBride Street, Boston, MA 02130, United States of America\\n- Southfield: Southfield, 20 Newton Street, Brookline, MA 02445, United States of America\\n- Dexter School: Dexter School, 20 Newton Street, Brookline, MA 02445, United States of America\\n- Boston Teachers Union Pilot School: Boston Teachers Union Pilot School, 25 Walk Hill Street, Boston, MA 02130, United States of America\\n- Park School: Park School, 171 Goddard Avenue, Brookline, MA 02445, United States of America\\n- Curley K-8 School: Curley K-8 School, 493 Centre Street, Boston, MA 02130, United States of America\\n- The Mosaic School: The Mosaic School, 85 Seaverns Avenue, Boston, MA 02130, United States of America\\n- Joseph P Manning Elementary School: Joseph P Manning Elementary School, 130 Louder's Lane, Boston, MA 02130, United States of America\\n- Boston International High School: Boston International High School, 25 Glen Road, Boston, MA 02130, United States of America\\n- Meridian Academy: Meridian Academy, 54 Brookside Avenue, Boston, MA 02130, United States of America\\n- Match Charter School: Match Charter School, 215 Forest Hills Street, Boston, MA 02130, United States of America\\n- Nativity Prep School: Nativity Prep School, 39 Lamartine Street, Boston, MA 02120, United States of America\\n- Egleston Community High School: Egleston Community High School, 80 School Street, Boston, MA 02119, United States of America\\n- Ellis Mendell School: Ellis Mendell School, 164 School Street, Boston, MA 02119, United States of America\\n- ELC - West Zone: ELC - West Zone, 200 Heath Street, Boston, MA 02130, United States of America\\n- Dr. Frederick H. Knight Children's Center: Dr. Frederick H. Knight Children's Center, 161 South Huntington Avenue, Boston, MA 02130, United States of America\\n- Roxbury Preparatory Charter School: Roxbury Preparatory Charter School, 120 Fisher Avenue, Boston, MA 02120, United States of America\""
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "build_school_search(context_json['residence'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b44b01ed",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "f83995b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assistant: I'm happy to help!  Yes, all kindergarten students are guaranteed a seat in their program through the highest grade offered in their assigned school, following the guidelines of our student assignment plan.\n",
      "Updated JSON Context:\n",
      "{\n",
      "  \"residence\": \"\",\n",
      "  \"grade\": \"\",\n",
      "  \"school_choice\": \"\",\n",
      "  \"summary\": \"All kindergarten students are guaranteed a seat in their program through the highest grade offered in their assigned school, following the guidelines of our student assignment plan.\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "print(\"Assistant:\", reply_text)\n",
    "print(\"Updated JSON Context:\")\n",
    "print(json.dumps(context_json, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "73b0c32c",
   "metadata": {},
   "outputs": [],
   "source": [
    "user_input = \"Yes, I have the proof. We also live in Jamaica Plain.\"\n",
    "history.append((\"user\", user_input))\n",
    "\n",
    "prompt = build_prompt(system_prompt, context_json, json_prompt, school_search, history)\n",
    "\n",
    "output = llm(\n",
    "    prompt,\n",
    "    max_tokens=256,\n",
    "    temperature=0.4,\n",
    "    stop=[\"\\nUser:\", \"\\nAssistant:\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "caa8b0e1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Thank you! I'm glad to hear that. \n",
      "\n",
      "Now, please tell me your child's grade. \n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(output[\"choices\"][0][\"text\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "e63fa37f",
   "metadata": {},
   "outputs": [],
   "source": [
    "reply_text, new_data = extract_reply_and_json(raw_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "51446a21",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I'm happy to help!  Yes, all kindergarten students are guaranteed a seat in their program through the highest grade offered in their assigned school, following the guidelines of our student assignment plan.\""
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "reply_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "872195be",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'residence': '',\n",
       " 'grade': '',\n",
       " 'school_choice': '',\n",
       " 'summary': 'All kindergarten students are guaranteed a seat in their program through the highest grade offered in their assigned school, following the guidelines of our student assignment plan.'}"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "id": "07df7738",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('user',\n",
       "  'I live in Jamacia Plain and my child needs to go to Kindergarten. What schools can she go to?'),\n",
       " ('user', 'She is in 5th grade.')]"
      ]
     },
     "execution_count": 127,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "update_context(context_json, new_data, school_search)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "743492b1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'location': '', 'school': '', 'summary': ''}"
      ]
     },
     "execution_count": 157,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "context_json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 347,
   "id": "f088857f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'You are a professional assistant that answers questions about enrollment in Boston Public Schools.\\nBe friendly and helpful. Families will ask questions and provide information.\\nKeep the conversation going until you have all information, asking one question at a time.\\nYou must provide a response to the user and an updated JSON object with any new facts you learn. Only update fields that are explicitly mentioned.\\n\\n{\\n    \"address\": \"\",\\n    \"school\": \"K2\",\\n    \"grade\": \"\",\\n    \"summary\": \"\"\\n}\\n\\nWith an address and grade, you have the abilty to look up nearby schools.\\n\\nWhat if I am over 18 and no longer live with my parents?\\nAny person eighteen (18) years of age or older may establish a residence separate and apart from his or her parents or guardians for school attendance purposes. However, you will still be required to submit the two proofs of residency bearing your name and address.\\n-\\n\\nWhat is a Landlord Affidavit?\\nIf you are a tenant at will (“month-to-month”) and do not have a written lease, there is a Boston Public Schools form that your landlord can complete and sign, called the landlord/shared tenancy affidavit, available at any Welcome Center or on-line using the links below. This document can fulfill one of the two proofs of residency requirements. Your landlord does not have to be present when you register, and the affidavit does not have to be notarized. However, you and s/he will be asked to sign the document stating that, under the pains and penalties of perjury, the address listed is your primary legal address.\\nBPS Landlord Affidavit: English | Kabuverdianu | 文 | Kreyòl | Português | Español | tiếng Việt | Afsoomaali\\n-\\n\\nWhere can adults go to borrow a Chromebook and/or hotspot?\\nThe Boston Public Library has a similar program available for Boston residents. Click here to Reserve a Chromebook Home Connectivity Kit from the BPL.\\n\\nUser: My child, Alice, is 5 years old and going into Kindergarten. Which documents do I need?\\nUser: My child, Alice, is 5 years old and going into Kindergarten. Which documents do I need?\\nUser: My child, Alice, is 5 years old and going into Kindergarten. Which documents do I need?\\nUser: My child, Alice, is 5 years old and going into Kindergarten. Which documents do I need?\\nAssistant: To register for K2, children must be 5-years old on or before September 1 of the school year for which they are registering. You will need to provide Alice\\'s birth certificate and proof of residency.\\nUser: Yes, we live in Jamaica Plain.\\nAssistant:'"
      ]
     },
     "execution_count": 347,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "c46e6b5b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'You are a professional assistant that answers questions about enrollment in Boston Public Schools.\\nBe friendly and helpful. Families will ask questions and provide information, such as the child\\'s residence, grade, and school preference.\\nIt is essential that you do not provide inaccurate information. If you do not know something, respond accordingly!\\nYou must provide a response to the user and an updated JSON object with any new facts you learn. Only update fields that are explicitly mentioned.\\n\\n{\\n    \"residence\": \"\",\\n    \"grade\": \"\",\\n    \"school_choice\": \"\",\\n    \"summary\": \"All kindergarten students are guaranteed a seat in their program through the highest grade offered in their assigned school, following the guidelines of our student assignment plan.\"\\n}\\n\\nKeep the conversation going and ask questions one at a time until you have all information. With residence and grade, you have the abilty to look up nearby schools.\\n\\nKindergarten\\nKindergarten (K2)\\nK2 Kindergarten is a six-hour (full-day) program for 5-year-olds and is provided in all BPS elementary schools and early learning centers. K2 programs are a critical part of a child\\'s early school success. School assignment is guaranteed for all children who apply for K2. However, due to space constraints, including the reality that most K1 students moving up into K2 seats in their same school, an assignment cannot be guaranteed to a specific school. Please be sure to inquire during School Choice season about the number of open seats anticipated, and please register in the month of January for the best chance at securing an assignment in a school of your choosing. This is called Round One registration. To register for K2, children must be 5-years old on or before September 1 of the school year for which they are registering. Visit the Welcome Services Registration webpage to learn more about school registration.\\nGet ready for your \"Countdown to Kindergarten\"\\nCountdown to Kindergarten is a partnership BPS leads with the City of Boston, and many community organizations, which aims to provide a positive and supportive transition into BPS kindergarten (K0, K1 or K2) for students and their families. The initiative offers free parent-child playgroups, provides readiness tips and opportunities, and hosts workshops and other transition activities. Pick up copies of their publications, available in many languages, at any Welcome Center, call 617-635-9288, visit their Facebook page, or explore their website: www.countdowntokindergarten.org\\nImportant UPK Notes\\n- All kindergarten students are guaranteed a seat in their program through the highest grade offered in their assigned school, following the guidelines of our student assignment plan.\\n- Exceptions cannot be made to our entry age policy, regardless of the child’s previous school experience.\\n- State law states each child must attend school beginning in September of the calendar year in which the child turns six-years old.\\n- Suppose you need a program for your three- or four-year-old. In that case, you are encouraged to explore the new Great Starts registration tool, a collaboration with the BPS, the City of Boston, and community-based early childhood programs, designed to support Boston PreK in the city of Boston. While Pre-K programming in BPS has expanded in recent years, assignment in one of our schools cannot be guaranteed.\\n\\nStudents who must complete the Residency Verification Process in the fall of 2025 include:\\n- Students attending a private school\\n- Students attending parochial school\\n- Students attending METCO program schools\\n- Students attending Commonwealth Charter schools (excludes UP Academy, Boston Green Academy, and other “in-district” BPS charter schools)\\n- Students attending schools outside the City of Boston\\n- Students being home-schooled must demonstrate that both the student and parent/guardian live in the City of Boston\\nThe residency verification must be completed even if a family has other children enrolled in Boston Public Schools; a student is receiving special education services from BPS; the parent or guardian is a current city employee; or if the student was previously enrolled in BPS.\\nStep 3: School Choice\\nAs part of the application process, families must rank their preferences between the three exam schools (first choice, second choice, third choice, etc.). Students will be considered for admissions based on their test scores, GPA, and ranked order of preferences.\\nFamilies are encouraged to apply to all three exam schools for grade 7 and 9; however, the parent/guardian must rank at least one exam school to have the student considered for admissions. During the school choice process families are able to rank order the three exam schools, as well as other district schools within the child’s home-base.\\nStudents not currently attending BPS will submit their ranked school preferences during the Residency Verification period.\\nCurrent BPS students in grades 5 and 7 will receive a School Choice Form from their current school in early January 2026. Families may write in their preferences and return the form to the child’s current school for processing. Families with an email address on file will also receive a notification with the option of submitting their ranked school preferences online.\\nThe parent/guardian of grade 7 students currently attending an exam school, and the parent/guardian of a BPS grade 8 student interested in the O’Bryant, must take the weekend MAP exam and must visit a BPS Welcome Center in January 2026 to complete a transfer request in order to submit their ranked preference(s) for a different exam school.\\nStep 4: GPA\\nA Grade Point Average (GPA) of a B or higher is required to be considered for admissions. The GPA will be calculated based on current year (2024-2025) and next year (2025-26) marks. Students participating in advanced courses (honors, AWC, AP, etc.) do not receive additional points.\\nStudents must have grades in each subject for the GPA to be calculated. Students that do not meet the GPA of a B or higher will not be considered for admissions and the application will be closed.\\nTo view a summary of how grades will be converted for exam school consideration, please visit our fact sheet.\\nStep 5: Invitations\\nAll applicants will receive an admissions decision letter in late April-May 2026 via email and postal mail, which will share the student’s status (invited/not invited), composite score, SES Tier number, and waitlist if applicable. Please note that exam school decisions are final and we do not accept appeals.\\nApplicants that receive an invitation to an exam school will be able to participate in a welcome event in the Spring of 2026 hosted by the school to meet the staff and learn about course offerings, extracurricular activities, and ask questions.\\n\\nElementary Schools\\nMost BPS elementary schools are PK or K to sixth grade; however a few schools are K-8 in grade span. The district also has several Early Childhood options, with grade ranges spanning K0 to Grade 1, 2 or 3. Please be sure to review grade spans when you consider school options for your child.\\nRising Grade 7 students in a K-6 school will receive a school choice form to make new school choices for a district high school, which typically span grades 7 through 12. Note, all schools that serve grades 7-12 are citywide options that every student has access to, regardless of where they live in the city.\\nTo see your full school choice list, including locations, schedules, and other information, visit www.discoverbps.org. You can also contact one of our Welcome Centers for assistance.\\n\\nUser: Yes, I have the proof. We also live in Jamaica Plain.\\nUser: Yes, I have the proof. We also live in Jamaica Plain.\\nAssistant:'"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb0761e4",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}