File size: 99,840 Bytes
b585c7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# h2oGPT API call example\n",
    "\n",
    "Documentation: https://github.com/h2oai/h2ogpt/blob/main/docs/README_CLIENT.md\n",
    "\n",
    "Good summary of many of the parameters can be found in the [`grclient.py`](https://github.com/h2oai/h2ogpt/blob/main/gradio_utils/grclient.py) \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One can interact with Gradio Client by using either native client or h2oGPT wrapper: \n",
    "\n",
    "- Using Gradio \\'s native client:\n",
    "\n",
    "  ```python\n",
    "  from gradio_client import Client\n",
    "  import ast\n",
    "  \n",
    "  HOST_URL = \"http://localhost:7860\"\n",
    "  client = Client(HOST_URL)\n",
    "  \n",
    "  # string of dict for input\n",
    "  kwargs = dict(instruction_nochat='Who are you?')\n",
    "  res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "  \n",
    "  # string of dict for output\n",
    "  response = ast.literal_eval(res)['response']\n",
    "  print(response)\n",
    "  ```\n",
    "\n",
    "- Using [h2oGPT wrapper for Gradio Native Client](https://github.com/h2oai/h2ogpt/blob/main/docs/README_CLIENT.md#h2ogpt-gradio-wrapper)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded h2oGPT details\n"
     ]
    }
   ],
   "source": [
    "from gradio_client import Client\n",
    "import ast\n",
    "from pprint import pprint\n",
    "import json\n",
    "from tqdm import tqdm\n",
    "from enum import Enum\n",
    "\n",
    "class LangChainAction(Enum):\n",
    "    \"\"\"LangChain action\"\"\"\n",
    "    QUERY = \"Query\"\n",
    "    SUMMARIZE_MAP = \"Summarize\"\n",
    "    \n",
    "\n",
    "with open('../tokens/h2oGPT_details.txt') as f:\n",
    "    gpt_details = json.load(f)\n",
    "    print(\"Loaded h2oGPT details\")\n",
    "\n",
    "# HOST_URL = \"http://localhost:7860\"\n",
    "HOST_URL = gpt_details[\"gpt_host_url\"]\n",
    "H2OGPT_KEY = gpt_details[\"h2ogpt_key\"]\n",
    "LANGCHAIN_MODE = langchain_mode = 'UserData4'\n",
    "\n",
    "client = Client(HOST_URL)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Utility functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import shutil\n",
    "import uuid\n",
    "import requests\n",
    "from requests.exceptions import HTTPError\n",
    "import contextlib\n",
    "\n",
    "\n",
    "def print_full_model_response(response):\n",
    "    '''\n",
    "    Helper function to print full response from the h2oGPT call, including all parameters.\n",
    "        Important keys/parameters:\n",
    "        - `base_model` - model that used to answer the API call\n",
    "        - `extra_dict` - model parameters that were used to answer the API call\n",
    "        - `prompt` - actual prompt sent to LLM\n",
    "        - `where_from` - how hosted model is running: vLLM , tensor, ....\n",
    "    '''\n",
    "    print(\"Model Response with Parameters:\\n\")\n",
    "    save_dict = ast.literal_eval(res)['save_dict']\n",
    "    # Remove key from extra_dict\n",
    "    save_dict.pop('h2ogpt_key', None)\n",
    "    pprint(save_dict)\n",
    "    print(\"\\n\")\n",
    "    try:\n",
    "        sources = ast.literal_eval(response)['sources']\n",
    "        print(\"Sources:\\n\")\n",
    "        pprint(sources)\n",
    "        print(\"\\n\")\n",
    "    except:\n",
    "        print(\"No sources\\n\")\n",
    "\n",
    "\n",
    "def makedirs(path, exist_ok=True, tmp_ok=False, use_base=False):\n",
    "    \"\"\"\n",
    "    Avoid some inefficiency in os.makedirs()\n",
    "    :param path:\n",
    "    :param exist_ok:\n",
    "    :param tmp_ok:  use /tmp if can't write locally\n",
    "    :param use_base:\n",
    "    :return:\n",
    "    \"\"\"\n",
    "    if path is None:\n",
    "        return path\n",
    "    # if base path set, make relative to that, unless user_path absolute path\n",
    "    if use_base:\n",
    "        if os.path.normpath(path) == os.path.normpath(os.path.abspath(path)):\n",
    "            pass\n",
    "        else:\n",
    "            if os.getenv('H2OGPT_BASE_PATH') is not None:\n",
    "                base_dir = os.path.normpath(os.getenv('H2OGPT_BASE_PATH'))\n",
    "                path = os.path.normpath(path)\n",
    "                if not path.startswith(base_dir):\n",
    "                    path = os.path.join(os.getenv('H2OGPT_BASE_PATH', ''), path)\n",
    "                    path = os.path.normpath(path)\n",
    "\n",
    "    if os.path.isdir(path) and os.path.exists(path):\n",
    "        assert exist_ok, \"Path already exists\"\n",
    "        return path\n",
    "    try:\n",
    "        os.makedirs(path, exist_ok=exist_ok)\n",
    "        return path\n",
    "    except FileExistsError:\n",
    "        # e.g. soft link\n",
    "        return path\n",
    "    except PermissionError:\n",
    "        if tmp_ok:\n",
    "            path0 = path\n",
    "            path = os.path.join('/tmp/', path)\n",
    "            print(\"Permission denied to %s, using %s instead\" % (path0, path), flush=True)\n",
    "            os.makedirs(path, exist_ok=exist_ok)\n",
    "            return path\n",
    "        else:\n",
    "            raise\n",
    "\n",
    "        \n",
    "def shutil_rmtree(*args, **kwargs):\n",
    "    return shutil.rmtree(*args, **kwargs)\n",
    "\n",
    "\n",
    "def remove(path: str):\n",
    "    try:\n",
    "        if path is not None and os.path.exists(path):\n",
    "            if os.path.isdir(path):\n",
    "                shutil_rmtree(path, ignore_errors=True)\n",
    "            else:\n",
    "                with contextlib.suppress(FileNotFoundError):\n",
    "                    os.remove(path)\n",
    "    except:\n",
    "        pass\n",
    "\n",
    "\n",
    "def atomic_move_simple(src, dst):\n",
    "    try:\n",
    "        shutil.move(src, dst)\n",
    "    except (shutil.Error, FileExistsError):\n",
    "        pass\n",
    "    remove(src)\n",
    "\n",
    "\n",
    "def download_simple(url, dest=None, overwrite=False, verbose=False):\n",
    "    if dest is None:\n",
    "        dest = os.path.basename(url)\n",
    "    base_path = os.path.dirname(dest)\n",
    "    if base_path:  # else local path\n",
    "        base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True)\n",
    "        dest = os.path.join(base_path, os.path.basename(dest))\n",
    "\n",
    "    if os.path.isfile(dest):\n",
    "        if not overwrite:\n",
    "            print(\"Already have %s from url %s, delete file if invalid\" % (dest, str(url)), flush=True)\n",
    "            return dest\n",
    "        else:\n",
    "            remove(dest)\n",
    "\n",
    "    if verbose:\n",
    "        print(\"BEGIN get url %s\" % str(url), flush=True)\n",
    "    if url.startswith(\"file://\"):\n",
    "        from requests_file import FileAdapter\n",
    "        s = requests.Session()\n",
    "        s.mount('file://', FileAdapter())\n",
    "        url_data = s.get(url, stream=True)\n",
    "    else:\n",
    "        url_data = requests.get(url, stream=True)\n",
    "    if verbose:\n",
    "        print(\"GOT url %s\" % str(url), flush=True)\n",
    "\n",
    "    if url_data.status_code != requests.codes.ok:\n",
    "        msg = \"Cannot get url %s, code: %s, reason: %s\" % (\n",
    "            str(url),\n",
    "            str(url_data.status_code),\n",
    "            str(url_data.reason),\n",
    "        )\n",
    "        raise requests.exceptions.RequestException(msg)\n",
    "    url_data.raw.decode_content = True\n",
    "\n",
    "    uuid_tmp = str(uuid.uuid4())[:6]\n",
    "    dest_tmp = dest + \"_dl_\" + uuid_tmp + \".tmp\"\n",
    "    with open(dest_tmp, \"wb\") as f:\n",
    "        shutil.copyfileobj(url_data.raw, f)\n",
    "    atomic_move_simple(dest_tmp, dest)\n",
    "    if verbose:\n",
    "        print(\"DONE url %s\" % str(url), flush=True)\n",
    "    return dest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hello World example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response:\n",
      "\n",
      "(\"  Hello! My name is LLaMA, I'm a large language model trained by a team of \"\n",
      " 'researcher at Meta AI. My primary function is to understand and respond to '\n",
      " 'human input in a helpful and engaging manner. I can answer questions, '\n",
      " 'provide information, and even generate creative content such as stories or '\n",
      " 'dialogue. Is there anything specific you would like to know or talk about?')\n"
     ]
    }
   ],
   "source": [
    "# string of dict for input\n",
    "kwargs = dict(instruction_nochat='Who are you?',\n",
    "              h2ogpt_key=H2OGPT_KEY)\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "\n",
    "# string of dict for output\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(\"Model Response:\\n\")\n",
    "pprint(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response with Parameters:\n",
      "\n",
      "{'base_model': 'h2oai/h2ogpt-4096-llama2-70b-chat',\n",
      " 'error': '',\n",
      " 'extra_dict': {'frequency_penalty': 0,\n",
      "                'inference_server': 'vllm:192.176.243.12:5000',\n",
      "                'max_tokens': 1024,\n",
      "                'n': 1,\n",
      "                'ntokens': None,\n",
      "                'num_prompt_tokens': 13,\n",
      "                'presence_penalty': 0.6,\n",
      "                't_generate': 4.012332916259766,\n",
      "                'temperature': 0,\n",
      "                'tokens_persecond': None,\n",
      "                'top_p': 1,\n",
      "                'username': 'NO_REQUEST'},\n",
      " 'output': \"  Hello! My name is LLaMA, I'm a large language model trained by a \"\n",
      "           'team of researcher at Meta AI. My primary function is to '\n",
      "           'understand and respond to human input in a helpful and engaging '\n",
      "           'manner. I can answer questions, provide information, and even '\n",
      "           'generate creative content such as stories or dialogue. Is there '\n",
      "           'anything specific you would like to know or talk about?',\n",
      " 'prompt': '<s>[INST] Who are you? [/INST]',\n",
      " 'save_dir': 'saveall_docs',\n",
      " 'sources': [],\n",
      " 'valid_key': True,\n",
      " 'where_from': 'vllm',\n",
      " 'which_api': 'str_api'}\n",
      "\n",
      "\n",
      "Sources:\n",
      "\n",
      "[]\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print_full_model_response(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Setting `temperature` parameter requires setting `do_sample` to `True`. For best reproducibility, set `do_sample` to `False`.\n",
    "\n",
    "```python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response:\n",
      "\n",
      "(\"  Hello! I'm LLaMA, an AI assistant developed by Meta AI that can understand \"\n",
      " \"and respond to human input in a conversational manner. I'm trained on a \"\n",
      " 'massive dataset of text from the internet and can generate human-like '\n",
      " 'responses to a wide range of topics and questions. I can be used to create '\n",
      " 'chatbots, virtual assistants, and other applications that require natural '\n",
      " 'language understanding and generation capabilities.')\n"
     ]
    }
   ],
   "source": [
    "# string of dict for input\n",
    "kwargs = dict(instruction_nochat='Who are you?',\n",
    "              seed=123,\n",
    "              temperature=0.5,\n",
    "              do_sample=True,\n",
    "              h2ogpt_key=H2OGPT_KEY)\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "\n",
    "# string of dict for output\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(\"Model Response:\\n\")\n",
    "pprint(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response with Parameters:\n",
      "\n",
      "{'base_model': 'h2oai/h2ogpt-4096-llama2-70b-chat',\n",
      " 'error': '',\n",
      " 'extra_dict': {'frequency_penalty': 0,\n",
      "                'inference_server': 'vllm:192.176.243.12:5000',\n",
      "                'max_tokens': 1024,\n",
      "                'n': 1,\n",
      "                'ntokens': None,\n",
      "                'num_prompt_tokens': 13,\n",
      "                'presence_penalty': 0.6,\n",
      "                't_generate': 3.7804932594299316,\n",
      "                'temperature': 0.5,\n",
      "                'tokens_persecond': None,\n",
      "                'top_p': 0.75,\n",
      "                'username': 'NO_REQUEST'},\n",
      " 'output': \"  Hello! I'm LLaMA, an AI assistant developed by Meta AI that can \"\n",
      "           'understand and respond to human input in a conversational manner. '\n",
      "           \"I'm trained on a massive dataset of text from the internet and can \"\n",
      "           'generate human-like responses to a wide range of topics and '\n",
      "           'questions. I can be used to create chatbots, virtual assistants, '\n",
      "           'and other applications that require natural language understanding '\n",
      "           'and generation capabilities.',\n",
      " 'prompt': '<s>[INST] Who are you? [/INST]',\n",
      " 'save_dir': 'saveall_docs',\n",
      " 'sources': [],\n",
      " 'valid_key': True,\n",
      " 'where_from': 'vllm',\n",
      " 'which_api': 'str_api'}\n",
      "\n",
      "\n",
      "Sources:\n",
      "\n",
      "[]\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print_full_model_response(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example of Context only call with parameters\n",
    "\n",
    "Good summary of many of the parameters can be found in the [`grclient.py`](https://github.com/h2oai/h2ogpt/blob/main/gradio_utils/grclient.py) \n",
    "\n",
    "In the below example, we will set LLM model to use as well as some parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response:\n",
      "\n",
      "(\"  Hello! My name is LLaMA, I'm a large language model trained by a team of \"\n",
      " 'researcher at Meta AI. My primary function is to assist with tasks such as '\n",
      " 'answering questions, providing information, and generating text. I am '\n",
      " 'capable of understanding and responding to human input in a conversational '\n",
      " 'manner. I am here to help and provide information to the best of my ability. '\n",
      " 'Is there something specific you would like to know or discuss?')\n"
     ]
    }
   ],
   "source": [
    "# string of dict for input\n",
    "kwargs = dict(instruction_nochat='Who are you?',\n",
    "              visible_models=['h2oai/h2ogpt-4096-llama2-13b-chat'],\n",
    "              langchain_mode='LLM',\n",
    "              max_new_tokens=512,\n",
    "              max_time=360,\n",
    "              repetition_penalty=1.07,\n",
    "              do_sample=True,\n",
    "              temperature=0.1,\n",
    "              top_p=0.75,\n",
    "              penalty_alpha=0,\n",
    "              h2ogpt_key=H2OGPT_KEY)\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "\n",
    "# string of dict for output\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(\"Model Response:\\n\")\n",
    "pprint(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response with Parameters:\n",
      "\n",
      "{'base_model': 'h2oai/h2ogpt-4096-llama2-13b-chat',\n",
      " 'error': '',\n",
      " 'extra_dict': {'frequency_penalty': 0,\n",
      "                'inference_server': 'vllm:192.176.243.12:5001',\n",
      "                'max_tokens': 512,\n",
      "                'n': 1,\n",
      "                'ntokens': None,\n",
      "                'num_prompt_tokens': 13,\n",
      "                'presence_penalty': 0.6,\n",
      "                't_generate': 2.1190145015716553,\n",
      "                'temperature': 0.1,\n",
      "                'tokens_persecond': None,\n",
      "                'top_p': 0.75,\n",
      "                'username': 'NO_REQUEST'},\n",
      " 'output': \"  Hello! My name is LLaMA, I'm a large language model trained by a \"\n",
      "           'team of researcher at Meta AI. My primary function is to assist '\n",
      "           'with tasks such as answering questions, providing information, and '\n",
      "           'generating text. I am capable of understanding and responding to '\n",
      "           'human input in a conversational manner. I am here to help and '\n",
      "           'provide information to the best of my ability. Is there something '\n",
      "           'specific you would like to know or discuss?',\n",
      " 'prompt': '<s>[INST] Who are you? [/INST]',\n",
      " 'save_dir': 'saveall_docs',\n",
      " 'sources': [],\n",
      " 'valid_key': True,\n",
      " 'where_from': 'vllm',\n",
      " 'which_api': 'str_api'}\n",
      "\n",
      "\n",
      "Sources:\n",
      "\n",
      "[]\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print_full_model_response(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summarize Document with mode \"Summarize\"\n",
    "\n",
    "This approach is useful for the following scenarios:\n",
    "- Summarize a given document\n",
    "- Ask question about given document. \n",
    "\n",
    "This is different from asking question (searching) full collection of documents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 1 - create shared Collection and upload documents\n",
    "\n",
    "Currently there is no way to authenticate with Gradio Client, therefore we will use shared collection. \n",
    "\n",
    "The additional examples of Client use can be found in the `test_client_chat_stream_langchain_steps3` function located in the `test_client_calls.py` file.  \n",
    "\n",
    "**Create Shared folder**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_path = 'user_path'\n",
    "new_langchain_mode_text = '%s, %s, %s' % (langchain_mode, 'shared', user_path)\n",
    "res = client.predict(langchain_mode, new_langchain_mode_text, api_name='/new_langchain_mode_text')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "({'__type__': 'update',\n",
      "  'choices': [['UserData', 'UserData'],\n",
      "              ['MyData', 'MyData'],\n",
      "              ['LLM', 'LLM'],\n",
      "              ['UserData4', 'UserData4']],\n",
      "  'value': 'UserData4'},\n",
      " '',\n",
      " '/var/folders/_z/jf3ghwdx1kg905xm5p1nktlh0000gp/T/gradio/tmpplv8021u.json')\n"
     ]
    }
   ],
   "source": [
    "pprint(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = \"Yufuu is a wonderful place and you should really visit because there is lots of sun.\"\n",
    "loaders = tuple([None, None, None, None])\n",
    "res = client.predict(text, langchain_mode, True, 512, True,\n",
    "                    *loaders,\n",
    "                    H2OGPT_KEY,\n",
    "                    api_name='/add_text')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(None,\n",
      " 'UserData4',\n",
      " '        <html>\\n'\n",
      " '          <body>\\n'\n",
      " '            <p>\\n'\n",
      " '               Sources: <br>\\n'\n",
      " '            </p>\\n'\n",
      " '               <div style=\"overflow-y: auto;height:400px\">\\n'\n",
      " '               <table>\\n'\n",
      " '<thead>\\n'\n",
      " '<tr><th style=\"text-align: right;\">  '\n",
      " 'index</th><th>source                                                                                                                                   '\n",
      " '</th><th>head                                              </th></tr>\\n'\n",
      " '</thead>\\n'\n",
      " '<tbody>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      1</td><td><font size=\"2\"><a '\n",
      " 'href=\"file/user_paste/_37aa0924-8.txt\" target=\"_blank\"  rel=\"noopener '\n",
      " 'noreferrer\">user_paste/_37aa0924-8.txt</a></font></td><td>Yufuu is a '\n",
      " 'wonderful place and you should really v</td></tr>\\n'\n",
      " '</tbody>\\n'\n",
      " '</table>\\n'\n",
      " '               </div>\\n'\n",
      " '          </body>\\n'\n",
      " '        </html>\\n'\n",
      " '        ',\n",
      " '',\n",
      " '_37aa0924-8.txt')\n"
     ]
    }
   ],
   "source": [
    "pprint(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add document to collection via URL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "url = \"https://www.africau.edu/images/default/sample.pdf\"\n",
    "res = client.predict(url,\n",
    "                        langchain_mode, True, 512, True,\n",
    "                        *loaders,\n",
    "                        H2OGPT_KEY,\n",
    "                        api_name='/add_url')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(None,\n",
      " 'UserData4',\n",
      " '        <html>\\n'\n",
      " '          <body>\\n'\n",
      " '            <p>\\n'\n",
      " '               Sources: <br>\\n'\n",
      " '            </p>\\n'\n",
      " '               <div style=\"overflow-y: auto;height:400px\">\\n'\n",
      " '               <table>\\n'\n",
      " '<thead>\\n'\n",
      " '<tr><th style=\"text-align: right;\">  '\n",
      " 'index</th><th>source                                                                                                                                                                            '\n",
      " '</th><th>head                                              </th></tr>\\n'\n",
      " '</thead>\\n'\n",
      " '<tbody>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      1</td><td><font size=\"2\"><a '\n",
      " 'href=\"file/user_paste/_37aa0924-8.txt\" target=\"_blank\"  rel=\"noopener '\n",
      " 'noreferrer\">user_paste/_37aa0924-8.txt</a></font>                                         '\n",
      " '</td><td>Yufuu is a wonderful place and you should really v</td></tr>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      2</td><td><font size=\"2\"><a '\n",
      " 'href=\"https://www.africau.edu/images/default/sample.pdf\" target=\"_blank\"  '\n",
      " 'rel=\"noopener '\n",
      " 'noreferrer\">https://www.africau.edu/images/default/sample.pdf</a></font></td><td>Simple '\n",
      " 'PDF File 2\\n'\n",
      " '...continued from page 1. Yet '\n",
      " 'mo                                                   </td></tr>\\n'\n",
      " '</tbody>\\n'\n",
      " '</table>\\n'\n",
      " '               </div>\\n'\n",
      " '          </body>\\n'\n",
      " '        </html>\\n'\n",
      " '        ',\n",
      " '',\n",
      " 'sample.pdf')\n"
     ]
    }
   ],
   "source": [
    "pprint(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download file and add to the new collection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "url = \"https://www.nyserda.ny.gov/-/media/Project/Nyserda/Files/Programs/Drive-Clean-NY/terms-and-conditions.pdf\"\n",
    "test_file1 = os.path.join('/tmp/', 'terms-and-conditions.pdf')\n",
    "download_simple(url, dest=test_file1)\n",
    "\n",
    "# upload file(s).  Can be list or single file\n",
    "# test_file_server - location of the uploaded file on the Gradio server\n",
    "test_file_local, test_file_server = client.predict(test_file1, api_name='/upload_api')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Local File name: /private/var/folders/_z/jf3ghwdx1kg905xm5p1nktlh0000gp/T/gradio/2fad8f25e0cd5d618609d5e95e666b4d399e254b/terms-and-conditions.pdf\n",
      "Remote (Gradio Server) File name: /tmp/gradio/55e65c1a447610b8b4ee99717922af03099f9821/terms-and-conditions.pdf\n"
     ]
    }
   ],
   "source": [
    "print(\"Local File name:\", test_file_local)\n",
    "print(\"Remote (Gradio Server) File name:\", test_file_server)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add remote file to h2oPT collection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "chunk = True\n",
    "chunk_size = 512\n",
    "h2ogpt_key = H2OGPT_KEY\n",
    "res = client.predict(test_file_server,\n",
    "                        langchain_mode, chunk, chunk_size, True,\n",
    "                        None, None, None, None,\n",
    "                        h2ogpt_key,\n",
    "                        api_name='/add_file_api')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(None,\n",
      " 'UserData4',\n",
      " '        <html>\\n'\n",
      " '          <body>\\n'\n",
      " '            <p>\\n'\n",
      " '               Sources: <br>\\n'\n",
      " '            </p>\\n'\n",
      " '               <div style=\"overflow-y: auto;height:400px\">\\n'\n",
      " '               <table>\\n'\n",
      " '<thead>\\n'\n",
      " '<tr><th style=\"text-align: right;\">  '\n",
      " 'index</th><th>source                                                                                                                                                                            '\n",
      " '</th><th>head                                              </th></tr>\\n'\n",
      " '</thead>\\n'\n",
      " '<tbody>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      1</td><td><font size=\"2\"><a '\n",
      " 'href=\"file/user_paste/_37aa0924-8.txt\" target=\"_blank\"  rel=\"noopener '\n",
      " 'noreferrer\">user_paste/_37aa0924-8.txt</a></font>                                         '\n",
      " '</td><td>Yufuu is a wonderful place and you should really v</td></tr>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      2</td><td><font size=\"2\"><a '\n",
      " 'href=\"https://www.africau.edu/images/default/sample.pdf\" target=\"_blank\"  '\n",
      " 'rel=\"noopener '\n",
      " 'noreferrer\">https://www.africau.edu/images/default/sample.pdf</a></font></td><td>Simple '\n",
      " 'PDF File 2\\n'\n",
      " '...continued from page 1. Yet '\n",
      " 'mo                                                   </td></tr>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      3</td><td><font size=\"2\"><a '\n",
      " 'href=\"file/user_path/terms-and-conditions.pdf\" target=\"_blank\"  '\n",
      " 'rel=\"noopener '\n",
      " 'noreferrer\">user_path/terms-and-conditions.pdf</a></font>                         '\n",
      " '</td><td>August 2017\\n'\n",
      " '11 I agree to reimburse the dealer '\n",
      " 'the                                                   </td></tr>\\n'\n",
      " '</tbody>\\n'\n",
      " '</table>\\n'\n",
      " '               </div>\\n'\n",
      " '          </body>\\n'\n",
      " '        </html>\\n'\n",
      " '        ',\n",
      " '',\n",
      " 'terms-and-conditions.pdf')\n"
     ]
    }
   ],
   "source": [
    "pprint(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add one more file:\n",
    "- Upload to Gradio Server\n",
    "- Add to Collection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "url = \"https://cleanvehiclerebate.org/sites/default/files/docs/nav/transportation/cvrp/documents/CVRP-Implementation-Manual.pdf\"\n",
    "test_file1 = os.path.join('/tmp/', 'CVRP-Implementation-Manual.pdf')\n",
    "download_simple(url, dest=test_file1)\n",
    "\n",
    "# upload file(s).  Can be list or single file\n",
    "# test_file_server - location of the uploaded file on the Gradio server\n",
    "test_file_local, test_file_server = client.predict(test_file1, api_name='/upload_api')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "chunk = True\n",
    "chunk_size = 512\n",
    "embed = True\n",
    "h2ogpt_key = H2OGPT_KEY\n",
    "loaders = tuple([None, None, None, None])\n",
    "doc_options = tuple([langchain_mode, chunk, chunk_size, embed])\n",
    "\n",
    "res = client.predict(\n",
    "                test_file_server, *doc_options, *loaders, h2ogpt_key, api_name=\"/add_file_api\"\n",
    "            )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(None,\n",
      " 'UserData4',\n",
      " '        <html>\\n'\n",
      " '          <body>\\n'\n",
      " '            <p>\\n'\n",
      " '               Sources: <br>\\n'\n",
      " '            </p>\\n'\n",
      " '               <div style=\"overflow-y: auto;height:400px\">\\n'\n",
      " '               <table>\\n'\n",
      " '<thead>\\n'\n",
      " '<tr><th style=\"text-align: right;\">  '\n",
      " 'index</th><th>source                                                                                                                                                                            '\n",
      " '</th><th>head                                              </th></tr>\\n'\n",
      " '</thead>\\n'\n",
      " '<tbody>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      1</td><td><font size=\"2\"><a '\n",
      " 'href=\"file/user_paste/_37aa0924-8.txt\" target=\"_blank\"  rel=\"noopener '\n",
      " 'noreferrer\">user_paste/_37aa0924-8.txt</a></font>                                         '\n",
      " '</td><td>Yufuu is a wonderful place and you should really v</td></tr>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      2</td><td><font size=\"2\"><a '\n",
      " 'href=\"https://www.africau.edu/images/default/sample.pdf\" target=\"_blank\"  '\n",
      " 'rel=\"noopener '\n",
      " 'noreferrer\">https://www.africau.edu/images/default/sample.pdf</a></font></td><td>Simple '\n",
      " 'PDF File 2\\n'\n",
      " '...continued from page 1. Yet '\n",
      " 'mo                                                   </td></tr>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      3</td><td><font size=\"2\"><a '\n",
      " 'href=\"file/user_path/terms-and-conditions.pdf\" target=\"_blank\"  '\n",
      " 'rel=\"noopener '\n",
      " 'noreferrer\">user_path/terms-and-conditions.pdf</a></font>                         '\n",
      " '</td><td>August 2017\\n'\n",
      " '11 I agree to reimburse the dealer '\n",
      " 'the                                                   </td></tr>\\n'\n",
      " '<tr><td style=\"text-align: right;\">      4</td><td><font size=\"2\"><a '\n",
      " 'href=\"file/user_path/CVRP-Implementation-Manual.pdf\" target=\"_blank\"  '\n",
      " 'rel=\"noopener '\n",
      " 'noreferrer\">user_path/CVRP-Implementation-Manual.pdf</a></font>             '\n",
      " '</td><td>This page intentionally blank.                    </td></tr>\\n'\n",
      " '</tbody>\\n'\n",
      " '</table>\\n'\n",
      " '               </div>\\n'\n",
      " '          </body>\\n'\n",
      " '        </html>\\n'\n",
      " '        ',\n",
      " '',\n",
      " 'CVRP-Implementation-Manual.pdf')\n"
     ]
    }
   ],
   "source": [
    "pprint(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2 - retrieve full path to the document already uploaded to h2oGPT\n",
    "\n",
    "In the below example, we get full path to all documents loaded into \"MyTest\" collection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['https://www.africau.edu/images/default/sample.pdf',\n",
      " 'user_paste/_37aa0924-8.txt',\n",
      " 'user_path/CVRP-Implementation-Manual.pdf',\n",
      " 'user_path/terms-and-conditions.pdf']\n"
     ]
    }
   ],
   "source": [
    "sources = ast.literal_eval(client.predict(langchain_mode, api_name='/get_sources_api'))\n",
    "pprint(sources[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 3: Ask questions about the document\n",
    "\n",
    "PArameters for the LLM input:\n",
    "- `pre_prompt_summary` - append to the beginning to the LLM input\n",
    "- Document content is sent in between `pre_prompt_summary` and `post_prompt_summary`\n",
    "- `prompt_summary` - append to the end of the LLM input"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Summarize single document"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Sure! Here is a summary of the text in 5 bullet points:\n",
      "\n",
      "• The Charge NY Drive Clean Rebate Program offers rebates to residents, businesses, fleets, and government entities.\n",
      "• The vehicle purchaser must be a New York State resident or business/fleet registered/licensed to do business in New York State.\n",
      "• The vehicle purchaser must agree to register/lease the vehicle for at least 36 months in New York State.\n",
      "• The vehicle purchaser must agree to participate in online surveys and research efforts and never modify the vehicle's emission control system or engine.\n",
      "• The vehicle purchaser must provide accurate information and have the legal authority to commit to the program's obligations.\n"
     ]
    }
   ],
   "source": [
    "instruction = None\n",
    "document_choice = \"user_path/terms-and-conditions.pdf\"\n",
    "\n",
    "langchain_action = LangChainAction.SUMMARIZE_MAP.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "\n",
    "pre_prompt_query = None\n",
    "prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            document_choice=document_choice,\n",
    "            max_new_tokens=256,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response with Parameters:\n",
      "\n",
      "{'base_model': 'h2oai/h2ogpt-4096-llama2-70b-chat',\n",
      " 'error': '',\n",
      " 'extra_dict': {'add_search_to_context': False,\n",
      "                'chat_conversation': [],\n",
      "                'context': '',\n",
      "                'do_sample': False,\n",
      "                'document_choice': 'user_path/terms-and-conditions.pdf',\n",
      "                'document_subset': 'Relevant',\n",
      "                'early_stopping': False,\n",
      "                'iinput': '',\n",
      "                'inference_server': 'vllm:192.176.243.12:5000',\n",
      "                'instruction': '',\n",
      "                'langchain_action': 'Summarize',\n",
      "                'langchain_agents': [],\n",
      "                'langchain_mode': 'UserData4',\n",
      "                'max_new_tokens': 256,\n",
      "                'max_time': 360,\n",
      "                'min_new_tokens': 0,\n",
      "                'ntokens': None,\n",
      "                'num_beams': 1,\n",
      "                'num_prompt_tokens': 322,\n",
      "                'num_return_sequences': 1,\n",
      "                'penalty_alpha': 0.0,\n",
      "                'prompt_type': 'llama2',\n",
      "                'repetition_penalty': 1.07,\n",
      "                't_generate': 21.372483015060425,\n",
      "                'temperature': 0.1,\n",
      "                'tokens_persecond': None,\n",
      "                'top_k': 40,\n",
      "                'top_p': 0.75,\n",
      "                'username': 'NO_REQUEST'},\n",
      " 'output': '  Sure! Here is a summary of the text in 5 bullet points:\\n'\n",
      "           '\\n'\n",
      "           '• The Charge NY Drive Clean Rebate Program offers rebates to '\n",
      "           'residents, businesses, fleets, and government entities.\\n'\n",
      "           '• The vehicle purchaser must be a New York State resident or '\n",
      "           'business/fleet registered/licensed to do business in New York '\n",
      "           'State.\\n'\n",
      "           '• The vehicle purchaser must agree to register/lease the vehicle '\n",
      "           'for at least 36 months in New York State.\\n'\n",
      "           '• The vehicle purchaser must agree to participate in online '\n",
      "           \"surveys and research efforts and never modify the vehicle's \"\n",
      "           'emission control system or engine.\\n'\n",
      "           '• The vehicle purchaser must provide accurate information and have '\n",
      "           \"the legal authority to commit to the program's obligations.\",\n",
      " 'prompt': '<s>[INST] In order to write a concise single-paragraph or bulleted '\n",
      "           'list summary, pay attention to the following text\\n'\n",
      "           ':\\n'\n",
      "           '\"\"\"\\n'\n",
      "           '  Sure! Here is a summary of the text in 5 bullet points:\\n'\n",
      "           '\\n'\n",
      "           '• The Charge NY Drive Clean Rebate Program offers rebates to '\n",
      "           'residents, businesses, fleets, and government entities that '\n",
      "           'purchase or lease eligible vehicles.\\n'\n",
      "           '• To be eligible, the vehicle purchaser must be a New York State '\n",
      "           'resident, government entity, or business/fleet registered/licensed '\n",
      "           'to do business in New York State and intends to domicile the '\n",
      "           'vehicle in New York State.\\n'\n",
      "           '• The vehicle purchaser must agree to register/lease the vehicle '\n",
      "           'for at least 36 months in New York State, maintain vehicle '\n",
      "           \"insurance, and allow NYSERDA to verify the vehicle's VIN and \"\n",
      "           'registration.\\n'\n",
      "           '• The vehicle purchaser must also agree to participate in online '\n",
      "           \"surveys and research efforts, never modify the vehicle's emission \"\n",
      "           'control system or engine, and indemnify NYSERDA and the State of '\n",
      "           'New York from any liabilities.\\n'\n",
      "           '• If the vehicle purchaser provides false or inaccurate '\n",
      "           'information, they must reimburse the dealer the full value of the '\n",
      "           'rebate, and they must have the legal authority to commit to the '\n",
      "           'obligations outlined in the program.\\n'\n",
      "           '\"\"\"\\n'\n",
      "           'Using only the text above, write a condensed and concise summary '\n",
      "           'of key results as 5 bullet points:\\n'\n",
      "           ' [/INST]',\n",
      " 'save_dir': 'saveall_docs',\n",
      " 'sources': [{'content': 'August 2017\\n'\n",
      "                         'Charge NY Drive Clean Rebate Program\\n'\n",
      "                         'Vehicle Purchaser Terms and Conditions\\n'\n",
      "                         'A Vehicle Purchaser is an individual, business, '\n",
      "                         'fleet, or government entity that purchases or leases '\n",
      "                         'a vehicle\\n'\n",
      "                         'that is eligible for a rebate from the Charge NY '\n",
      "                         'Drive Clean Rebate Program. A Vehicle Purchaser must '\n",
      "                         'be\\n'\n",
      "                         'a resident of New York State (if an individual), be '\n",
      "                         'a New York State government entity or municipality, '\n",
      "                         'or\\n'\n",
      "                         'be registered/licensed to do business in New York '\n",
      "                         'State and must affirm that it intends to domicile '\n",
      "                         'the\\n'\n",
      "                         'vehicle in New York State (if a business, fleet, or '\n",
      "                         'government entity).\\n'\n",
      "                         'General Terms and Conditions for Vehicle '\n",
      "                         'Purchasers:\\n'\n",
      "                         'I hereby acknowledge that I have read and agree to '\n",
      "                         'meet and follow the requirements and '\n",
      "                         'responsibilities\\n'\n",
      "                         'for Vehicle Purchaser participation as set forth '\n",
      "                         'below.\\n'\n",
      "                         '1\\n'\n",
      "                         'I certify that I am a New York State Resident, '\n",
      "                         'government entity or an entity registered/licensed '\n",
      "                         'to\\n'\n",
      "                         'do business in New York State.\\n'\n",
      "                         '2\\n'\n",
      "                         'I certify that the Dealer has explained to me the '\n",
      "                         'value of the Charge NY Drive Clean Rebate for my\\n'\n",
      "                         'vehicle purchase and has clearly shown me that the '\n",
      "                         'full amount of this rebate has been taken off of '\n",
      "                         'the\\n'\n",
      "                         'purchase or lease price of the vehicle. I agree to '\n",
      "                         'allow the Dealer to receive the rebate on my '\n",
      "                         'behalf.\\n'\n",
      "                         '3\\n'\n",
      "                         'If I am an individual, I agree to register the '\n",
      "                         'vehicle with the New York State Department of Motor\\n'\n",
      "                         'Vehicles with an address located within New York '\n",
      "                         'State for at least thirty-six (36) months from the\\n'\n",
      "                         'date of purchase. If I am a Vehicle Purchaser other '\n",
      "                         'than an individual, I agree to domicile the vehicle\\n'\n",
      "                         'within New York State for at least thirty-six (36) '\n",
      "                         'months from the date of purchase. If I leased the\\n'\n",
      "                         'vehicle, I agree that my original lease term is at '\n",
      "                         'least thirty-six (36) months.\\n'\n",
      "                         '4\\n'\n",
      "                         'I agree to allow NYSERDA or its designee to verify '\n",
      "                         'the vehicle identification number (VIN) and\\n'\n",
      "                         'registration with the DMV.\\n'\n",
      "                         '5\\n'\n",
      "                         'I agree to maintain vehicle insurance as required by '\n",
      "                         'New York State law.\\n'\n",
      "                         '6\\n'\n",
      "                         'I agree to allow NYSERDA to share my address, '\n",
      "                         'contact information, and vehicle model purchased\\n'\n",
      "                         'with the electric distribution utility serving the '\n",
      "                         'primary location in New York State where the '\n",
      "                         'vehicle\\n'\n",
      "                         'will be domiciled for the purpose of informing its '\n",
      "                         'system planning efforts.  I understand that this '\n",
      "                         'utility\\n'\n",
      "                         'may send me information about programs that it '\n",
      "                         'offers to customers that are designed specifically '\n",
      "                         'for\\n'\n",
      "                         'plug-in electric vehicle owners.\\n'\n",
      "                         '7\\n'\n",
      "                         'I agree to never modify the vehicle’s emission '\n",
      "                         'control system, engine, engine hardware, software\\n'\n",
      "                         'calibrations, or electric drive system.\\n'\n",
      "                         '8\\n'\n",
      "                         'I agree to participate in online surveys and other '\n",
      "                         'research efforts that support Program goals.\\n'\n",
      "                         '9\\n'\n",
      "                         'I acknowledge that neither NYSERDA, nor any of its '\n",
      "                         'consultants, is responsible for assuring that the\\n'\n",
      "                         'vehicle is proper for the Vehicle Purchaser or '\n",
      "                         'complies with any particular laws, codes, or '\n",
      "                         'industry\\n'\n",
      "                         'standards.  I acknowledge that NYSERDA has made no '\n",
      "                         'representations of any kind regarding the\\n'\n",
      "                         'results to be achieved by the Program.\\n'\n",
      "                         '10 I shall protect, indemnify and hold harmless '\n",
      "                         'NYSERDA and the State of New York from and against\\n'\n",
      "                         'all liabilities, losses, claims, damages, judgments, '\n",
      "                         'penalties, causes of action, costs and expenses\\n'\n",
      "                         \"(including, without limitation, attorneys' fees and \"\n",
      "                         'expenses) imposed upon or incurred by or asserted\\n'\n",
      "                         'against NYSERDA or the State of New York resulting '\n",
      "                         'from, arising out of or relating to Vehicle\\n'\n",
      "                         'Purchaser’s participation in the Program including, '\n",
      "                         'without limitation, Vehicle Purchaser’s purchase\\n'\n",
      "                         'or lease of vehicles in association therewith;\\n'\n",
      "                         '\\n'\n",
      "                         'August 2017\\n'\n",
      "                         '11 I agree to reimburse the dealer the full value of '\n",
      "                         'the rebate if it is discovered that I provided false '\n",
      "                         'or\\n'\n",
      "                         'inaccurate information that results in the rebate '\n",
      "                         'application being denied; and\\n'\n",
      "                         '12 I certify that I have the legal authority to '\n",
      "                         'commit the Vehicle Purchaser to the obligations '\n",
      "                         'herein.\\n'\n",
      "                         'If the Vehicle Purchaser is an individual, fill out '\n",
      "                         'this section:\\n'\n",
      "                         'Name of Vehicle Purchaser:  '\n",
      "                         '_________________________________\\n'\n",
      "                         'Signature of Vehicle Purchaser: '\n",
      "                         '_______________________________\\n'\n",
      "                         'Email of Vehicle Purchaser: '\n",
      "                         '__________________________________\\n'\n",
      "                         'Date: ___________________________\\n'\n",
      "                         'Scan a copy of the Vehicle Purchaser’s New York '\n",
      "                         'State Driver’s License and include it in the box '\n",
      "                         'below\\n'\n",
      "                         'or upload a copy as a separate document in Step 6 of '\n",
      "                         'the online rebate application:\\n'\n",
      "                         'If the Vehicle Purchaser is a non-individual (fleet, '\n",
      "                         'business, or government entity), fill out this '\n",
      "                         'section:\\n'\n",
      "                         'Legal Business Name (Government Name): '\n",
      "                         '_______________________________\\n'\n",
      "                         'Employer Identification Number: '\n",
      "                         '_______________________________\\n'\n",
      "                         'New York State address where the vehicle will be '\n",
      "                         'domiciled:\\n'\n",
      "                         '_______________________________\\n'\n",
      "                         '_______________________________\\n'\n",
      "                         '_______________________________\\n'\n",
      "                         'Name and Title of Authorized Representative: '\n",
      "                         '_______________________________\\n'\n",
      "                         'Signature of Authorized Representative: '\n",
      "                         '____________________________________\\n'\n",
      "                         'Email of Authorized Representative: '\n",
      "                         '_______________________________________\\n'\n",
      "                         'Date: ___________________________',\n",
      "              'orig_index': 0,\n",
      "              'score': 0,\n",
      "              'source': 'user_path/terms-and-conditions.pdf'}],\n",
      " 'valid_key': True,\n",
      " 'where_from': 'run_qa_db',\n",
      " 'which_api': 'str_api'}\n",
      "\n",
      "\n",
      "Sources:\n",
      "\n",
      "[{'content': 'August 2017\\n'\n",
      "             'Charge NY Drive Clean Rebate Program\\n'\n",
      "             'Vehicle Purchaser Terms and Conditions\\n'\n",
      "             'A Vehicle Purchaser is an individual, business, fleet, or '\n",
      "             'government entity that purchases or leases a vehicle\\n'\n",
      "             'that is eligible for a rebate from the Charge NY Drive Clean '\n",
      "             'Rebate Program. A Vehicle Purchaser must be\\n'\n",
      "             'a resident of New York State (if an individual), be a New York '\n",
      "             'State government entity or municipality, or\\n'\n",
      "             'be registered/licensed to do business in New York State and must '\n",
      "             'affirm that it intends to domicile the\\n'\n",
      "             'vehicle in New York State (if a business, fleet, or government '\n",
      "             'entity).\\n'\n",
      "             'General Terms and Conditions for Vehicle Purchasers:\\n'\n",
      "             'I hereby acknowledge that I have read and agree to meet and '\n",
      "             'follow the requirements and responsibilities\\n'\n",
      "             'for Vehicle Purchaser participation as set forth below.\\n'\n",
      "             '1\\n'\n",
      "             'I certify that I am a New York State Resident, government entity '\n",
      "             'or an entity registered/licensed to\\n'\n",
      "             'do business in New York State.\\n'\n",
      "             '2\\n'\n",
      "             'I certify that the Dealer has explained to me the value of the '\n",
      "             'Charge NY Drive Clean Rebate for my\\n'\n",
      "             'vehicle purchase and has clearly shown me that the full amount '\n",
      "             'of this rebate has been taken off of the\\n'\n",
      "             'purchase or lease price of the vehicle. I agree to allow the '\n",
      "             'Dealer to receive the rebate on my behalf.\\n'\n",
      "             '3\\n'\n",
      "             'If I am an individual, I agree to register the vehicle with the '\n",
      "             'New York State Department of Motor\\n'\n",
      "             'Vehicles with an address located within New York State for at '\n",
      "             'least thirty-six (36) months from the\\n'\n",
      "             'date of purchase. If I am a Vehicle Purchaser other than an '\n",
      "             'individual, I agree to domicile the vehicle\\n'\n",
      "             'within New York State for at least thirty-six (36) months from '\n",
      "             'the date of purchase. If I leased the\\n'\n",
      "             'vehicle, I agree that my original lease term is at least '\n",
      "             'thirty-six (36) months.\\n'\n",
      "             '4\\n'\n",
      "             'I agree to allow NYSERDA or its designee to verify the vehicle '\n",
      "             'identification number (VIN) and\\n'\n",
      "             'registration with the DMV.\\n'\n",
      "             '5\\n'\n",
      "             'I agree to maintain vehicle insurance as required by New York '\n",
      "             'State law.\\n'\n",
      "             '6\\n'\n",
      "             'I agree to allow NYSERDA to share my address, contact '\n",
      "             'information, and vehicle model purchased\\n'\n",
      "             'with the electric distribution utility serving the primary '\n",
      "             'location in New York State where the vehicle\\n'\n",
      "             'will be domiciled for the purpose of informing its system '\n",
      "             'planning efforts.  I understand that this utility\\n'\n",
      "             'may send me information about programs that it offers to '\n",
      "             'customers that are designed specifically for\\n'\n",
      "             'plug-in electric vehicle owners.\\n'\n",
      "             '7\\n'\n",
      "             'I agree to never modify the vehicle’s emission control system, '\n",
      "             'engine, engine hardware, software\\n'\n",
      "             'calibrations, or electric drive system.\\n'\n",
      "             '8\\n'\n",
      "             'I agree to participate in online surveys and other research '\n",
      "             'efforts that support Program goals.\\n'\n",
      "             '9\\n'\n",
      "             'I acknowledge that neither NYSERDA, nor any of its consultants, '\n",
      "             'is responsible for assuring that the\\n'\n",
      "             'vehicle is proper for the Vehicle Purchaser or complies with any '\n",
      "             'particular laws, codes, or industry\\n'\n",
      "             'standards.  I acknowledge that NYSERDA has made no '\n",
      "             'representations of any kind regarding the\\n'\n",
      "             'results to be achieved by the Program.\\n'\n",
      "             '10 I shall protect, indemnify and hold harmless NYSERDA and the '\n",
      "             'State of New York from and against\\n'\n",
      "             'all liabilities, losses, claims, damages, judgments, penalties, '\n",
      "             'causes of action, costs and expenses\\n'\n",
      "             \"(including, without limitation, attorneys' fees and expenses) \"\n",
      "             'imposed upon or incurred by or asserted\\n'\n",
      "             'against NYSERDA or the State of New York resulting from, arising '\n",
      "             'out of or relating to Vehicle\\n'\n",
      "             'Purchaser’s participation in the Program including, without '\n",
      "             'limitation, Vehicle Purchaser’s purchase\\n'\n",
      "             'or lease of vehicles in association therewith;\\n'\n",
      "             '\\n'\n",
      "             'August 2017\\n'\n",
      "             '11 I agree to reimburse the dealer the full value of the rebate '\n",
      "             'if it is discovered that I provided false or\\n'\n",
      "             'inaccurate information that results in the rebate application '\n",
      "             'being denied; and\\n'\n",
      "             '12 I certify that I have the legal authority to commit the '\n",
      "             'Vehicle Purchaser to the obligations herein.\\n'\n",
      "             'If the Vehicle Purchaser is an individual, fill out this '\n",
      "             'section:\\n'\n",
      "             'Name of Vehicle Purchaser:  _________________________________\\n'\n",
      "             'Signature of Vehicle Purchaser: _______________________________\\n'\n",
      "             'Email of Vehicle Purchaser: __________________________________\\n'\n",
      "             'Date: ___________________________\\n'\n",
      "             'Scan a copy of the Vehicle Purchaser’s New York State Driver’s '\n",
      "             'License and include it in the box below\\n'\n",
      "             'or upload a copy as a separate document in Step 6 of the online '\n",
      "             'rebate application:\\n'\n",
      "             'If the Vehicle Purchaser is a non-individual (fleet, business, '\n",
      "             'or government entity), fill out this section:\\n'\n",
      "             'Legal Business Name (Government Name): '\n",
      "             '_______________________________\\n'\n",
      "             'Employer Identification Number: _______________________________\\n'\n",
      "             'New York State address where the vehicle will be domiciled:\\n'\n",
      "             '_______________________________\\n'\n",
      "             '_______________________________\\n'\n",
      "             '_______________________________\\n'\n",
      "             'Name and Title of Authorized Representative: '\n",
      "             '_______________________________\\n'\n",
      "             'Signature of Authorized Representative: '\n",
      "             '____________________________________\\n'\n",
      "             'Email of Authorized Representative: '\n",
      "             '_______________________________________\\n'\n",
      "             'Date: ___________________________',\n",
      "  'orig_index': 0,\n",
      "  'score': 0,\n",
      "  'source': 'user_path/terms-and-conditions.pdf'}]\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print_full_model_response(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Additional Single document summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Sure! Here's a summary of the text in 5 bullet points:\n",
      "\n",
      "• A simple PDF file is being demonstrated.\n",
      "• The file contains a lot of text, described as boring.\n",
      "• The file is being used for Virtual Mechanics tutorials.\n",
      "• The author finds typing the text boring.\n",
      "• The author mentions that watching paint dry is even more boring.\n"
     ]
    }
   ],
   "source": [
    "instruction = None\n",
    "document_choice = \"https://www.africau.edu/images/default/sample.pdf\"\n",
    "\n",
    "langchain_action = LangChainAction.SUMMARIZE_MAP.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "\n",
    "pre_prompt_query = None\n",
    "prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            document_choice=document_choice,\n",
    "            max_new_tokens=256,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Summarize California EV program"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Sure! Here is a summary of the key points in 5 bullet points:\n",
      "\n",
      "• The Clean Vehicle Rebate Project (CVRP) provides rebates for purchasing or leasing eligible zero- and near-zero-emission vehicles.\n",
      "• CVRP is administered by the California Air Resources Board (CARB) and aims to encourage the development and deployment of advanced technologies.\n",
      "• Funding for the CVRP comes from the Greenhouse Gas Reduction Fund.\n",
      "• The program outlines minimum requirements for implementation in the CVRP Terms and Conditions, Guidelines, and Funding Plan.\n",
      "• The program benefits disadvantaged communities.\n"
     ]
    }
   ],
   "source": [
    "instruction = None\n",
    "document_choice = \"user_path/CVRP-Implementation-Manual.pdf\"\n",
    "\n",
    "langchain_action = LangChainAction.SUMMARIZE_MAP.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "\n",
    "pre_prompt_query = None\n",
    "prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            document_choice=document_choice,\n",
    "            max_new_tokens=256,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Summarize all documents in the Collection\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Sure! Here is a summary of the key points in 5 bullet points:\n",
      "\n",
      "• The Clean Vehicle Rebate Project (CVRP) provides rebates for purchasing or leasing eligible zero- and near-zero-emission vehicles.\n",
      "• CVRP is administered by the California Air Resources Board (CARB) and aims to encourage the development and deployment of advanced technologies that reduce greenhouse gas emissions.\n",
      "• Funding for the CVRP comes from the Greenhouse Gas Reduction Fund.\n",
      "• The program benefits California citizens by providing immediate air pollution emission reductions.\n",
      "• The program promotes the development of cleaner vehicles.\n"
     ]
    }
   ],
   "source": [
    "instruction = None\n",
    "langchain_action = LangChainAction.SUMMARIZE_MAP.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "\n",
    "pre_prompt_query = None\n",
    "prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            #document_choice=document_choice,\n",
    "            max_new_tokens=256,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Question answering for a single document\n",
    "\n",
    "We will use summary mode as well, even though we are not summarizing the document.   \n",
    "This mode will enable us to send full document for question answering task."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Sure! Here is a summary of the eligibility criteria for the Charge NY Drive Clean Rebate Program:\n",
      "\n",
      "• You must be a resident of New York State, a New York State government entity, or registered/licensed to do business in New York State.\n",
      "• You must purchase or lease a vehicle that is eligible for a rebate from the Charge NY Drive Clean Rebate Program.\n",
      "• You must register the vehicle with the New York State Department of Motor Vehicles with an address located within New York State for at least thirty-six (36) months from the date of purchase.\n",
      "• You must allow NYSERDA or its designee to verify the vehicle identification number (VIN) and registration with the DMV.\n",
      "• You must maintain vehicle insurance as required by New York State law.\n",
      "\n",
      "Does this help?\n"
     ]
    }
   ],
   "source": [
    "instruction = \"What is the eligibility criteria for the program?\"\n",
    "document_choice = \"user_path/terms-and-conditions.pdf\"\n",
    "\n",
    "langchain_action = LangChainAction.SUMMARIZE_MAP.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "\n",
    "# pre_prompt_query = \"\"\"Pay attention and remember the information below, which will help to answer the question or imperative after the context ends.\\n\"\"\"\n",
    "# prompt_query = \"\"\"According to only the information in the document sources provided within the context above, \\n\"\"\"\n",
    "pre_prompt_query = None\n",
    "prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            document_choice=document_choice,\n",
    "            max_new_tokens=256,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Question answering for all documents in the Collection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  According to the information provided in the context, the eligibility criteria for the Clean Vehicle Rebate Project (CVRP) includes:\n",
      "\n",
      "1. Income and household size: Applicants must meet certain income and household size requirements to be eligible for the program.\n",
      "2. Participation in public assistance programs: Applicants who participate in certain public assistance programs on CVRP's Categorical Eligibility list may be eligible for the program.\n",
      "3. Required documentation: Applicants must provide required documentation, which may vary depending on the program, to prove their eligibility for the program.\n",
      "4. Online or paper application: Applicants must submit a complete application form, either online or on paper, with their signature and date.\n",
      "5. No mistakes on the application form: Applicants must ensure that their application form is complete and accurate, and must contact the Administrator immediately if there are any mistakes.\n",
      "6. Updates to governing documents: Applicants must be aware of updates to CVRP governing documents, which can affect their eligibility for the program.\n",
      "\n",
      "It is important to note that these are the general el\n"
     ]
    }
   ],
   "source": [
    "instruction = \"What is the eligibility criteria for the program?\"\n",
    "document_choice = \"user_path/terms-and-conditions.pdf\"\n",
    "\n",
    "langchain_action = LangChainAction.QUERY.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "#pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "#prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "pre_prompt_summary = None\n",
    "prompt_summary = None\n",
    "\n",
    "pre_prompt_query = \"\"\"Pay attention and remember the information below, which will help to answer the question or imperative after the context ends.\\n\"\"\"\n",
    "prompt_query = \"\"\"According to only the information in the document sources provided within the context above, \\n\"\"\"\n",
    "#pre_prompt_query = None\n",
    "#prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            # document_choice=document_choice,\n",
    "            max_new_tokens=256,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Response with Parameters:\n",
      "\n",
      "{'base_model': 'h2oai/h2ogpt-4096-llama2-70b-chat',\n",
      " 'error': '',\n",
      " 'extra_dict': {'add_search_to_context': False,\n",
      "                'chat_conversation': [],\n",
      "                'context': '',\n",
      "                'do_sample': False,\n",
      "                'document_choice': ['All'],\n",
      "                'document_subset': 'Relevant',\n",
      "                'early_stopping': False,\n",
      "                'iinput': '',\n",
      "                'inference_server': 'vllm:192.176.243.12:5000',\n",
      "                'instruction': 'What is the eligibility criteria for the '\n",
      "                               'program?',\n",
      "                'langchain_action': 'Query',\n",
      "                'langchain_agents': [],\n",
      "                'langchain_mode': 'UserData4',\n",
      "                'max_new_tokens': 256,\n",
      "                'max_time': 360,\n",
      "                'min_new_tokens': 0,\n",
      "                'ntokens': None,\n",
      "                'num_beams': 1,\n",
      "                'num_prompt_tokens': 514,\n",
      "                'num_return_sequences': 1,\n",
      "                'penalty_alpha': 0.0,\n",
      "                'prompt_type': 'llama2',\n",
      "                'repetition_penalty': 1.07,\n",
      "                't_generate': 12.24568796157837,\n",
      "                'temperature': 0.1,\n",
      "                'tokens_persecond': None,\n",
      "                'top_k': 40,\n",
      "                'top_p': 0.75,\n",
      "                'username': 'NO_REQUEST'},\n",
      " 'output': '  According to the information provided in the context, the '\n",
      "           'eligibility criteria for the Clean Vehicle Rebate Project (CVRP) '\n",
      "           'includes:\\n'\n",
      "           '\\n'\n",
      "           '1. Income and household size: Applicants must meet certain income '\n",
      "           'and household size requirements to be eligible for the program.\\n'\n",
      "           '2. Participation in public assistance programs: Applicants who '\n",
      "           \"participate in certain public assistance programs on CVRP's \"\n",
      "           'Categorical Eligibility list may be eligible for the program.\\n'\n",
      "           '3. Required documentation: Applicants must provide required '\n",
      "           'documentation, which may vary depending on the program, to prove '\n",
      "           'their eligibility for the program.\\n'\n",
      "           '4. Online or paper application: Applicants must submit a complete '\n",
      "           'application form, either online or on paper, with their signature '\n",
      "           'and date.\\n'\n",
      "           '5. No mistakes on the application form: Applicants must ensure '\n",
      "           'that their application form is complete and accurate, and must '\n",
      "           'contact the Administrator immediately if there are any mistakes.\\n'\n",
      "           '6. Updates to governing documents: Applicants must be aware of '\n",
      "           'updates to CVRP governing documents, which can affect their '\n",
      "           'eligibility for the program.\\n'\n",
      "           '\\n'\n",
      "           'It is important to note that these are the general el',\n",
      " 'prompt': '<s>[INST] \\n'\n",
      "           '\"\"\"\\n'\n",
      "           'Pay attention and remember the information below, which will help '\n",
      "           'to answer the question or imperative after the context ends.\\n'\n",
      "           'on income and household size.\\n'\n",
      "           'If an applicant applying for an increased rebate participates in '\n",
      "           'one or more of the\\n'\n",
      "           'public assistance programs on CVRP’s Categorical Eligibility list, '\n",
      "           'they may submit\\n'\n",
      "           'documentation confirming their current participation for '\n",
      "           'consideration by the\\n'\n",
      "           'Administrator in lieu of IRS Form 4506-C. Note that depending on '\n",
      "           'the program,\\n'\n",
      "           'documentation required may vary.\\n'\n",
      "           '• Required documentation for public fleet pre-acquisition '\n",
      "           'reservations will also\\n'\n",
      "           'include the following:\\n'\n",
      "           '\\n'\n",
      "           'document to either obtain money or property from the State or '\n",
      "           'avoid paying or\\n'\n",
      "           'transmitting money or property to the State. CARB also retains the '\n",
      "           'authority to\\n'\n",
      "           'prohibit any entity from participating in CVRP due to '\n",
      "           'noncompliance with project\\n'\n",
      "           'requirements or fraud which includes attempted fraud.\\n'\n",
      "           'During the application process, applicants should provide to the '\n",
      "           'Administrator all\\n'\n",
      "           'information necessary for the assessment of their applications. '\n",
      "           'Applicants whose\\n'\n",
      "           '\\n'\n",
      "           'Required documentation will include, at a minimum, the following:\\n'\n",
      "           '• For online applicants, you will be required to date and type '\n",
      "           'your name (which will\\n'\n",
      "           'act as your signature) on the submitted application form. This '\n",
      "           'signed and dated\\n'\n",
      "           'document is required. For applicants who request a paper '\n",
      "           'application form, a\\n'\n",
      "           'complete application with signature and date. Contact the '\n",
      "           'Administrator\\n'\n",
      "           'immediately if there is a mistake on your application form. '\n",
      "           'Applicants who submit\\n'\n",
      "           '\\n'\n",
      "           'eligibility for the Clean Vehicle Rebate Project (CVRP). These '\n",
      "           'governing documents\\n'\n",
      "           'are updated several times every year to accommodate operational '\n",
      "           'process changes\\n'\n",
      "           'and may affect the applicant’s eligibility for the program. The '\n",
      "           'next scheduled updates\\n'\n",
      "           'to CVRP governing documents can be found in the CVRP FAQs at\\n'\n",
      "           'CleanVehicleRebate.org/FAQs under “How often do CVRP program '\n",
      "           'requirements\\n'\n",
      "           'change?” Note that CVRP reserves the right to update the '\n",
      "           'Implementation Manual\\n'\n",
      "           '\\n'\n",
      "           'eligibility for the CVRP rebate program.\\n'\n",
      "           '\"\"\"\\n'\n",
      "           'According to only the information in the document sources provided '\n",
      "           'within the context above, \\n'\n",
      "           'What is the eligibility criteria for the program? [/INST]',\n",
      " 'save_dir': 'saveall_docs',\n",
      " 'sources': [{'content': 'on income and household size.\\n'\n",
      "                         'If an applicant applying for an increased rebate '\n",
      "                         'participates in one or more of the\\n'\n",
      "                         'public assistance programs on CVRP’s Categorical '\n",
      "                         'Eligibility list, they may submit\\n'\n",
      "                         'documentation confirming their current participation '\n",
      "                         'for consideration by the\\n'\n",
      "                         'Administrator in lieu of IRS Form 4506-C. Note that '\n",
      "                         'depending on the program,\\n'\n",
      "                         'documentation required may vary.\\n'\n",
      "                         '• Required documentation for public fleet '\n",
      "                         'pre-acquisition reservations will also\\n'\n",
      "                         'include the following:',\n",
      "              'orig_index': 1,\n",
      "              'score': 0.2838561339693884,\n",
      "              'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      "             {'content': 'document to either obtain money or property from the '\n",
      "                         'State or avoid paying or\\n'\n",
      "                         'transmitting money or property to the State. CARB '\n",
      "                         'also retains the authority to\\n'\n",
      "                         'prohibit any entity from participating in CVRP due '\n",
      "                         'to noncompliance with project\\n'\n",
      "                         'requirements or fraud which includes attempted '\n",
      "                         'fraud.\\n'\n",
      "                         'During the application process, applicants should '\n",
      "                         'provide to the Administrator all\\n'\n",
      "                         'information necessary for the assessment of their '\n",
      "                         'applications. Applicants whose',\n",
      "              'orig_index': 3,\n",
      "              'score': 0.2903084456920624,\n",
      "              'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      "             {'content': 'Required documentation will include, at a minimum, '\n",
      "                         'the following:\\n'\n",
      "                         '• For online applicants, you will be required to '\n",
      "                         'date and type your name (which will\\n'\n",
      "                         'act as your signature) on the submitted application '\n",
      "                         'form. This signed and dated\\n'\n",
      "                         'document is required. For applicants who request a '\n",
      "                         'paper application form, a\\n'\n",
      "                         'complete application with signature and date. '\n",
      "                         'Contact the Administrator\\n'\n",
      "                         'immediately if there is a mistake on your '\n",
      "                         'application form. Applicants who submit',\n",
      "              'orig_index': 4,\n",
      "              'score': 0.29075086265597117,\n",
      "              'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      "             {'content': 'eligibility for the Clean Vehicle Rebate Project '\n",
      "                         '(CVRP). These governing documents\\n'\n",
      "                         'are updated several times every year to accommodate '\n",
      "                         'operational process changes\\n'\n",
      "                         'and may affect the applicant’s eligibility for the '\n",
      "                         'program. The next scheduled updates\\n'\n",
      "                         'to CVRP governing documents can be found in the CVRP '\n",
      "                         'FAQs at\\n'\n",
      "                         'CleanVehicleRebate.org/FAQs under “How often do CVRP '\n",
      "                         'program requirements\\n'\n",
      "                         'change?” Note that CVRP reserves the right to update '\n",
      "                         'the Implementation Manual',\n",
      "              'orig_index': 2,\n",
      "              'score': 0.2900393307209015,\n",
      "              'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      "             {'content': 'eligibility for the CVRP rebate program.',\n",
      "              'orig_index': 0,\n",
      "              'score': 0.21977069973945618,\n",
      "              'source': 'user_path/CVRP-Implementation-Manual.pdf'}],\n",
      " 'valid_key': True,\n",
      " 'where_from': 'run_qa_db',\n",
      " 'which_api': 'str_api'}\n",
      "\n",
      "\n",
      "Sources:\n",
      "\n",
      "[{'content': 'on income and household size.\\n'\n",
      "             'If an applicant applying for an increased rebate participates in '\n",
      "             'one or more of the\\n'\n",
      "             'public assistance programs on CVRP’s Categorical Eligibility '\n",
      "             'list, they may submit\\n'\n",
      "             'documentation confirming their current participation for '\n",
      "             'consideration by the\\n'\n",
      "             'Administrator in lieu of IRS Form 4506-C. Note that depending on '\n",
      "             'the program,\\n'\n",
      "             'documentation required may vary.\\n'\n",
      "             '• Required documentation for public fleet pre-acquisition '\n",
      "             'reservations will also\\n'\n",
      "             'include the following:',\n",
      "  'orig_index': 1,\n",
      "  'score': 0.2838561339693884,\n",
      "  'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      " {'content': 'document to either obtain money or property from the State or '\n",
      "             'avoid paying or\\n'\n",
      "             'transmitting money or property to the State. CARB also retains '\n",
      "             'the authority to\\n'\n",
      "             'prohibit any entity from participating in CVRP due to '\n",
      "             'noncompliance with project\\n'\n",
      "             'requirements or fraud which includes attempted fraud.\\n'\n",
      "             'During the application process, applicants should provide to the '\n",
      "             'Administrator all\\n'\n",
      "             'information necessary for the assessment of their applications. '\n",
      "             'Applicants whose',\n",
      "  'orig_index': 3,\n",
      "  'score': 0.2903084456920624,\n",
      "  'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      " {'content': 'Required documentation will include, at a minimum, the '\n",
      "             'following:\\n'\n",
      "             '• For online applicants, you will be required to date and type '\n",
      "             'your name (which will\\n'\n",
      "             'act as your signature) on the submitted application form. This '\n",
      "             'signed and dated\\n'\n",
      "             'document is required. For applicants who request a paper '\n",
      "             'application form, a\\n'\n",
      "             'complete application with signature and date. Contact the '\n",
      "             'Administrator\\n'\n",
      "             'immediately if there is a mistake on your application form. '\n",
      "             'Applicants who submit',\n",
      "  'orig_index': 4,\n",
      "  'score': 0.29075086265597117,\n",
      "  'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      " {'content': 'eligibility for the Clean Vehicle Rebate Project (CVRP). These '\n",
      "             'governing documents\\n'\n",
      "             'are updated several times every year to accommodate operational '\n",
      "             'process changes\\n'\n",
      "             'and may affect the applicant’s eligibility for the program. The '\n",
      "             'next scheduled updates\\n'\n",
      "             'to CVRP governing documents can be found in the CVRP FAQs at\\n'\n",
      "             'CleanVehicleRebate.org/FAQs under “How often do CVRP program '\n",
      "             'requirements\\n'\n",
      "             'change?” Note that CVRP reserves the right to update the '\n",
      "             'Implementation Manual',\n",
      "  'orig_index': 2,\n",
      "  'score': 0.2900393307209015,\n",
      "  'source': 'user_path/CVRP-Implementation-Manual.pdf'},\n",
      " {'content': 'eligibility for the CVRP rebate program.',\n",
      "  'orig_index': 0,\n",
      "  'score': 0.21977069973945618,\n",
      "  'source': 'user_path/CVRP-Implementation-Manual.pdf'}]\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print_full_model_response(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Sure! Here's a summary of the income eligibility criteria for the program based on the provided text:\n",
      "\n",
      "• The CVRP's income eligibility criteria are based on gross annual household income.\n",
      "• The maximum income eligibility levels are ﹩135,000 for single filers, ﹩175,000 for head-of-household filers, and ﹩200,000 for joint filers.\n",
      "• Applicants who are claimed as dependents are not eligible for increased rebates regardless of their income.\n",
      "• Income verification is completed using IRS Form 1040 and/or other proof of income documentation.\n",
      "• The income cap applies to all eligible vehicle types except FCEVs.\n"
     ]
    }
   ],
   "source": [
    "instruction = \"What is the income eligibility criteria for the program?\"\n",
    "document_choice = \"user_path/CVRP-Implementation-Manual.pdf\"\n",
    "langchain_action = LangChainAction.SUMMARIZE_MAP.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "#pre_prompt_summary = None\n",
    "#prompt_summary = None\n",
    "\n",
    "#pre_prompt_query = \"\"\"Pay attention and remember the information below, which will help to answer the question or imperative after the context ends.\\n\"\"\"\n",
    "#prompt_query = \"\"\"According to only the information in the document sources provided within the context above, \\n\"\"\"\n",
    "pre_prompt_query = None\n",
    "prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            document_choice=document_choice,\n",
    "            max_new_tokens=1026,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ask Collection and question and get answers for all documents in the collection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  According to the information provided in the context, the Clean Vehicle Rebate Project (CVRP) in California has income eligibility criteria for higher-income consumers. The CVRP rebate is only available to individuals who meet certain income requirements, which are based on the applicant's household income.\n",
      "\n",
      "The income eligibility criteria for the CVRP rebate are as follows:\n",
      "\n",
      "* For households with a gross annual income of ﹩150,000 or less, the rebate is available for the full amount of ﹩2,500.\n",
      "* For households with a gross annual income between ﹩150,001 and ﹩200,000, the rebate is reduced by 50%.\n",
      "* For households with a gross annual income between ﹩200,001 and ﹩250,000, the rebate is reduced by 75%.\n",
      "* For households with a gross annual income of ﹩250,001 or more, the rebate is not available.\n",
      "\n",
      "It's important to note that these income eligibility criteria are subject to change, and the CVRP may have additional requirements or restrictions. It's always best to check the program's website or contact the CVRP directly for the most up-to-date information on income eligibility criteria and other program requirements.\n"
     ]
    }
   ],
   "source": [
    "instruction = \"What is the income eligibility criteria for the Clean Vehicle Rebate Project in the state of California?\"\n",
    "langchain_action = LangChainAction.QUERY.value\n",
    "stream_output = False\n",
    "top_k_docs = 5\n",
    "\n",
    "#pre_prompt_summary = \"\"\"In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\\n\"\"\"\n",
    "#prompt_summary = \"Using only the text above, write a condensed and concise summary of key results as 5 bullet points:\\n\"\n",
    "pre_prompt_summary = None\n",
    "prompt_summary = None\n",
    "\n",
    "pre_prompt_query = \"\"\"Pay attention and remember the information below, which will help to answer the question or imperative after the context ends.\\n\"\"\"\n",
    "prompt_query = \"\"\"According to only the information in the document sources provided within the context above, \\n\"\"\"\n",
    "#pre_prompt_query = None\n",
    "#prompt_query = None\n",
    "\n",
    "kwargs = dict(instruction=instruction,\n",
    "            langchain_mode=langchain_mode,\n",
    "            langchain_action=langchain_action,  # uses full document, not vectorDB chunks\n",
    "            top_k_docs=top_k_docs,\n",
    "            stream_output=stream_output,\n",
    "            document_subset='Relevant',\n",
    "            # document_choice=document_choice,\n",
    "            max_new_tokens=1026,\n",
    "            max_time=360,\n",
    "            do_sample=False,\n",
    "            pre_prompt_query=pre_prompt_query,\n",
    "            prompt_query=prompt_query,\n",
    "            pre_prompt_summary=pre_prompt_summary,\n",
    "            prompt_summary=prompt_summary,\n",
    "            h2ogpt_key=H2OGPT_KEY\n",
    "            )\n",
    "\n",
    "# get result\n",
    "res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')\n",
    "response = ast.literal_eval(res)['response']\n",
    "print(response)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "gen-ai-python310",
   "language": "python",
   "name": "gen-ai-python310"
  },
  "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.11"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}