File size: 45,846 Bytes
28e2c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "view-in-github"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/vanderbilt-data-science/lo-achievement/blob/update_UI_with_prompts/gradio_application.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x_Vp8SiKM4p1"
      },
      "source": [
        "# Gradio Interface Draft\n",
        "\n",
        "The goal of this notebook is to show a draft of a comprehensive Gradio interface though which students can interface with an LLM and self-study."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "o_60X8H3NEne"
      },
      "source": [
        "## Libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "pxcqXgg2aAN7"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0m\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0m\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0m\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0m\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0m\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
            "anaconda-project 0.10.1 requires ruamel-yaml, which is not installed.\n",
            "conda-repo-cli 1.0.4 requires pathlib, which is not installed.\n",
            "daal4py 2021.3.0 requires daal==2021.2.3, which is not installed.\n",
            "spyder 5.1.5 requires pyqt5<5.13, which is not installed.\n",
            "spyder 5.1.5 requires pyqtwebengine<5.13, which is not installed.\n",
            "cookiecutter 1.7.2 requires MarkupSafe<2.0.0, but you have markupsafe 2.1.3 which is incompatible.\n",
            "numba 0.54.1 requires numpy<1.21,>=1.17, but you have numpy 1.26.0 which is incompatible.\n",
            "pyppeteer 1.0.2 requires websockets<11.0,>=10.0, but you have websockets 11.0.3 which is incompatible.\n",
            "scipy 1.7.1 requires numpy<1.23.0,>=1.16.5, but you have numpy 1.26.0 which is incompatible.\n",
            "transformers 4.25.1 requires tokenizers!=0.11.3,<0.14,>=0.11.1, but you have tokenizers 0.14.0 which is incompatible.\u001b[0m\u001b[31m\n",
            "\u001b[0m\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0mCollecting Pillow==9.0.0\n",
            "  Downloading Pillow-9.0.0-cp39-cp39-macosx_10_10_x86_64.whl (3.0 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.0/3.0 MB\u001b[0m \u001b[31m9.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m:00:01\u001b[0m00:01\u001b[0m\n",
            "\u001b[?25h\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0mInstalling collected packages: Pillow\n",
            "  Attempting uninstall: Pillow\n",
            "    Found existing installation: Pillow 8.4.0\n",
            "    Uninstalling Pillow-8.4.0:\n",
            "      Successfully uninstalled Pillow-8.4.0\n",
            "Successfully installed Pillow-9.0.0\n",
            "\u001b[33mDEPRECATION: pyodbc 4.0.0-unsupported has a non-standard version number. pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pyodbc or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
            "\u001b[0m"
          ]
        }
      ],
      "source": [
        "# install libraries here\n",
        "# -q flag for \"quiet\" install\n",
        "!pip install -q langchain\n",
        "!pip install -q openai\n",
        "!pip install -q gradio\n",
        "!pip install -q unstructured\n",
        "!pip install -q chromadb\n",
        "!pip install -q tiktoken\n",
        "!pip install Pillow==9.0.0\n",
        "!pip install -q reportlab"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "pEjM1tLsMZBq"
      },
      "outputs": [
        {
          "ename": "ModuleNotFoundError",
          "evalue": "No module named 'langchain'",
          "output_type": "error",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
            "Cell \u001b[0;32mIn[2], line 6\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mtime\u001b[39;00m\n\u001b[1;32m      4\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mgetpass\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m getpass\n\u001b[0;32m----> 6\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mlangchain\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mdocstore\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mdocument\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Document\n\u001b[1;32m      7\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mlangchain\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mprompts\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m PromptTemplate\n\u001b[1;32m      8\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mlangchain\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mdocument_loaders\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m TextLoader\n",
            "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'langchain'"
          ]
        }
      ],
      "source": [
        "# import libraries here\n",
        "import os\n",
        "import time\n",
        "from getpass import getpass\n",
        "\n",
        "from langchain.docstore.document import Document\n",
        "from langchain.prompts import PromptTemplate\n",
        "from langchain.document_loaders import TextLoader\n",
        "from langchain.indexes import VectorstoreIndexCreator\n",
        "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
        "from langchain.embeddings import OpenAIEmbeddings\n",
        "\n",
        "from langchain.document_loaders.unstructured import UnstructuredFileLoader\n",
        "from langchain.vectorstores import Chroma\n",
        "from langchain.chains import RetrievalQA, RetrievalQAWithSourcesChain\n",
        "from langchain.chains.qa_with_sources import load_qa_with_sources_chain\n",
        "#from langchain.chains import ConversationalRetrievalChain\n",
        "\n",
        "from langchain.llms import OpenAI\n",
        "from langchain.chat_models import ChatOpenAI\n",
        "\n",
        "import gradio as gr\n",
        "from sqlalchemy import TEXT # TODO Why is sqlalchemy imported\n",
        "\n",
        "import pprint\n",
        "\n",
        "import json\n",
        "from google.colab import files\n",
        "from reportlab.pdfgen.canvas import Canvas"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "n0BTyPI_srMg"
      },
      "source": [
        "# Export requirements.txt (if needed)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "NOX639OA2pOh"
      },
      "outputs": [],
      "source": [
        "!pip freeze > requirements.txt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "03KLZGI_a5W5"
      },
      "source": [
        "## API Keys\n",
        "\n",
        "Use these cells to load the API keys required for this notebook. The below code cell uses the `getpass` library."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5smcWj4DbFgy",
        "outputId": "0aec236a-dfc8-4afb-d97c-ff324b85bb70"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·\n"
          ]
        }
      ],
      "source": [
        "openai_api_key = getpass()\n",
        "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "fck1RVxD8xSX"
      },
      "outputs": [],
      "source": [
        "llm = ChatOpenAI(model_name = 'gpt-3.5-turbo-16k')\n",
        "# TODO OpenAI() or ChatOpenAI()?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UzaYNFFT4AwX"
      },
      "source": [
        "# Interface"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "N9i8zsMmbcd3"
      },
      "outputs": [],
      "source": [
        "global db # Document-storing object (vector store / index)\n",
        "global qa # Question-answer object; retrieves from `db`\n",
        "global srcs # List of source documents fragments referenced by vector store\n",
        "num_sources = 100 # Maximum number of source documents which can be shown\n",
        "\n",
        "srcs = []\n",
        "# See https://github.com/hwchase17/langchain/discussions/3786 for discussion\n",
        "# of which splitter to use\n",
        "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "fmFg2_iyvRKI"
      },
      "outputs": [],
      "source": [
        "### Source Display ###\n",
        "\n",
        "def format_source_reference(document, index):\n",
        "  \"\"\"Return a HTML element which contains the `document` info and can be\n",
        "  referenced by the `index`.\"\"\"\n",
        "  if 'source' in document.metadata:\n",
        "    source_filepath, source_name = os.path.split(document.metadata['source'])\n",
        "  else:\n",
        "    source_name = \"text box\"\n",
        "  return  f\"<p id='source{index}'>[{index+1}] <em>{source_name}</em><br>...{document.page_content}...</p>\"\n",
        "\n",
        "def format_source_citation(index):\n",
        "  \"\"\"Return a Markdown element which references the element with the given\n",
        "  `index`.\"\"\"\n",
        "  return f\"[{index+1}](#source{index})\"\n",
        "\n",
        "def update_source_list(added_sources):\n",
        "  \"\"\"Add any new sources to the list `srcs`; return a list of integers\n",
        "  containing the index references for each of the given sources in `sources`.\"\"\"\n",
        "  source_indices = []\n",
        "  for source in added_sources:\n",
        "    if source not in srcs: srcs.append(source)\n",
        "    source_indices.append(srcs.index(source))\n",
        "  return source_indices\n",
        "\n",
        "def get_source_display_updates(sources=srcs):\n",
        "  \"\"\"Dynamically update the output for the given list of components to show\n",
        "  the items as contained within the documents in `sources`.\n",
        "  See https://github.com/gradio-app/gradio/issues/2066 for what I'm copying.\"\"\"\n",
        "  # TODO Currently displays the first 100 sources only, which could be an issue\n",
        "  # TODO Display an alert when the source display is being cut off (over 100\n",
        "  # sources are stored)\n",
        "  update_list = []\n",
        "  for i in range(num_sources):\n",
        "    if i < len(sources):\n",
        "      source_text = format_source_reference(sources[i], i)\n",
        "      update_list.append(gr.update(visible=True, value=source_text))\n",
        "    else:\n",
        "      update_list.append(gr.update(visible=False))\n",
        "  return update_list"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "2HnXKhgPccPV"
      },
      "outputs": [],
      "source": [
        "def embed_key(openai_api_key):\n",
        "  os.environ[\"OPENAI_API_KEY\"] = openai_api_key\n",
        "\n",
        "### Helper Functions ###\n",
        "\n",
        "def create_vector_store_from_document_segments(document_segments):\n",
        "  \"\"\"Updates the global `db` and `qa` variables to contain the given sections\n",
        "  of text (generated from the create_vector_store_from_file and\n",
        "  create_vector_store_from_text_input functions).\"\"\"\n",
        "  global db, qa\n",
        "\n",
        "  # TODO: Add useful metadata that indicates from *where* in the document\n",
        "  # the segment is pulled (ideally, show what page it's from, if possible)\n",
        "  # This requires changing how the info is displayed in the UI, but it\n",
        "  # shouldn't be a big change\n",
        "  embeddings = OpenAIEmbeddings()\n",
        "  db = Chroma.from_documents(document_segments, embeddings)\n",
        "  retriever = db.as_retriever()\n",
        "\n",
        "  qa = RetrievalQAWithSourcesChain.from_chain_type(llm=llm,\n",
        "                                  chain_type=\"stuff\",\n",
        "                                  retriever=retriever,\n",
        "                                  return_source_documents=True)\n",
        "\n",
        "def get_document_segments_from_files(files):\n",
        "  \"\"\"Returns a list of document segments taken from all of the files in the\n",
        "  given list.\"\"\"\n",
        "  # TODO Modify the metadata for each document to specify the location; see\n",
        "  # colab.research.google.com/drive/142CCh-Mh1AdodIGD7PyL86slFLOcVVeI\n",
        "  all_document_segments = []\n",
        "  for file in files:\n",
        "    loader = UnstructuredFileLoader(file.name)\n",
        "    documents = loader.load()\n",
        "    document_segments = text_splitter.split_documents(documents)\n",
        "    all_document_segments.extend(document_segments)\n",
        "  return all_document_segments\n",
        "\n",
        "def get_document_segments_from_text(text):\n",
        "  \"\"\"Returns a list of document segments taken from the text.\"\"\"\n",
        "  return [Document(page_content=page, metadata={\"source\":\"text box\"})\n",
        "                      for page in text_splitter.split_text(text)]\n",
        "\n",
        "def create_vector_store_from_file(file):\n",
        "  \"\"\"Updates the global `db` and `qa` variables to contain the given file.\"\"\"\n",
        "  # TODO change the code to allow input of multiple files (see previous\n",
        "  # implementation of this in some other notebook I made)\n",
        "  loader = UnstructuredFileLoader(file.name)\n",
        "  documents = loader.load()\n",
        "  document_segments = text_splitter.split_documents(documents)\n",
        "  create_vector_store_from_document_segments(document_segments)\n",
        "\n",
        "def create_vector_store_from_files(files):\n",
        "  \"\"\"Updates the global `db` and `qa` variables to contain the given files.\"\"\"\n",
        "  document_segments = get_document_segments_from_files(files)\n",
        "  create_vector_store_from_document_segments(document_segments)\n",
        "\n",
        "def create_vector_store_from_text(text):\n",
        "  \"\"\"Updates the global `db` and `qa` variables to contain the given string.\"\"\"\n",
        "  document_segments = get_document_segments_from_text(text)\n",
        "  create_vector_store_from_document_segments(document_segments)\n",
        "\n",
        "# TODO I keep on getting the following error (or something similar):\n",
        "# openai.error.InvalidRequestError: This model's maximum context length is 4097\n",
        "# tokens, however you requested 4333 tokens (4077 in your prompt; 256 for the\n",
        "# completion). Please reduce your prompt; or completion length.\n",
        "\n",
        "def construct_prompt(prompt, learning_objective):\n",
        "  # TODO Use prompt templates instead of just adding the strings together\n",
        "  return prompt + \" \" + learning_objective\n",
        "\n",
        "def generate_response(prompt, learning_objective=''):\n",
        "  \"\"\"Get the LLM response to the given prompt with the given learning objective,\n",
        "  referencing the global `qa` variable.\"\"\"\n",
        "  global db, qa\n",
        "  qa_prompt = construct_prompt(prompt, learning_objective)\n",
        "  result = qa({\"question\": qa_prompt})\n",
        "  return result[\"answer\"], result[\"source_documents\"]\n",
        "\n",
        "def generate_response_with_document_update(prompt, learning_objective=''):\n",
        "  \"\"\"Get the LLM response to the given prompt with the given learning objective,\n",
        "  referencing the global `qa` variable, and also return the document updates.\"\"\"\n",
        "  answer, sources = generate_response(prompt, learning_objective)\n",
        "  update_source_list(sources)\n",
        "  return [answer, *get_source_display_updates()]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "HMQcRCGjY_7p"
      },
      "outputs": [],
      "source": [
        "### Source Display ###\n",
        "\n",
        "def format_source_reference(document, index):\n",
        "  \"\"\"Return a HTML element which contains the `document` info and can be\n",
        "  referenced by the `index`.\"\"\"\n",
        "  source_filepath, source_filename = os.path.split(document.metadata['source'])\n",
        "  return  f\"<p id='source{index}'>[{index+1}] <em>{source_filename}</em><br>...{document.page_content}...</p>\"\n",
        "\n",
        "def format_source_citation(index):\n",
        "  \"\"\"Return a Markdown element which references the element with the given\n",
        "  `index`.\"\"\"\n",
        "  return f\"[{index+1}](#source{index})\"\n",
        "\n",
        "def update_source_list(added_sources):\n",
        "  \"\"\"Add any new sources to the list `srcs`; return a list of integers\n",
        "  containing the index references for each of the given sources in `sources`.\"\"\"\n",
        "  source_indices = []\n",
        "  for source in added_sources:\n",
        "    if source not in srcs: srcs.append(source)\n",
        "    source_indices.append(srcs.index(source))\n",
        "  return source_indices\n",
        "\n",
        "def get_source_display_updates(sources=srcs):\n",
        "  \"\"\"Dynamically update the output for the given list of components to show\n",
        "  the items as contained within the documents in `sources`.\n",
        "  See https://github.com/gradio-app/gradio/issues/2066 for what I'm copying.\"\"\"\n",
        "  # TODO Currently displays the first 100 sources only, which could be an issue\n",
        "  # TODO Display an alert when the source display is being cut off (over 100\n",
        "  # sources are stored)\n",
        "  update_list = []\n",
        "  for i in range(num_sources):\n",
        "    if i < len(sources):\n",
        "      source_text = format_source_reference(sources[i], i)\n",
        "      update_list.append(gr.update(visible=True, value=source_text))\n",
        "    else:\n",
        "      update_list.append(gr.update(visible=False))\n",
        "  return update_list"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "metadata": {
        "id": "XwIHEgnmQ7_q"
      },
      "outputs": [],
      "source": [
        "### Gradio Called Functions ###\n",
        "\n",
        "def prompt_select(selection, number, length):\n",
        "  if selection == \"Random\":\n",
        "    prompt = f\"Please design a {number} question quiz based on the context provided and the inputted learning objectives (if applicable). The types of questions should be randomized (including multiple choice, short answer, true/false, short answer, etc.).  Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide 1 question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional chances to respond until I get the correct choice. Explain why the correct choice is right.\"\n",
        "  elif selection == \"Fill in the Blank\":\n",
        "    prompt = f\"Create a {number} question fill in the blank quiz refrencing the context provided. The quiz should reflect the learning objectives (if inputted). The 'blank' part of the question should appear as '________'. The answers should reflect what word(s) should go in the blank an accurate statement. An example is the follow: 'The author of the article is ______.' The question should be a statement. Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide ONE question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect,and then give me additional chances to respond until I get the correct choice. Explain why the correct choice is right.\"\n",
        "  elif selection == \"Short Answer\":\n",
        "    prompt = f\"Please design a {number} question quiz about which reflects the learning objectives (if inputted).  The questions should be short answer. Expect the correct answers to be {length} sentences long. Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide ONE question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional chances to respond until I get the correct choice. Explain why the correct answer is right.\"\n",
        "  else:\n",
        "    prompt = f\"Please design a {number} question {selection.lower()} quiz based on the context provided and the inputted learning objectives (if applicable). Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide 1 question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional chances to respond until I get the correct choice. Explain why the correct choice is right.\"\n",
        "  return prompt\n",
        "\n",
        "'''\n",
        "def generate_response_with_document(file_input, text_input,\n",
        "                                    prompt, learning_objective):\n",
        "  \"\"\"Determine which type of document input is given and call the corresponding\n",
        "  function to generate and return a response, along with the sources.\"\"\"\n",
        "  if file_input:\n",
        "    return generate_response_from_files(file_input, prompt, learning_objective)\n",
        "  elif text_input:\n",
        "    return generate_response_from_text(text_input, prompt, learning_objective)\n",
        "  else: # No document input\n",
        "    # TODO add a UI indicator to the student if they forgot to provide document\n",
        "    raise Exception(\"No source text or file given\")\n",
        "'''\n",
        "pass"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "mqMZlP4CcfNa"
      },
      "outputs": [],
      "source": [
        "### Chatbot Functions ###\n",
        "\n",
        "def user(user_message, history):\n",
        "  \"\"\"Display user message and update chat history to include it.\n",
        "  Also disables user text input until bot is finished (call to reenable_chat())\n",
        "  See https://gradio.app/creating-a-chatbot/\"\"\"\n",
        "  return gr.update(value=\"\", interactive=True), history + [[user_message, None]]\n",
        "\n",
        "def get_chatbot_response(history):\n",
        "  \"\"\"Given the history as a list of tuples of strings, output the new history\n",
        "  response (referencing the document via vector store `qa`), along with the\n",
        "  currently referenced sources.\"\"\"\n",
        "\n",
        "  # TODO Disable input when the user has not added a document for context\n",
        "  # Right now, if you try to use this before pressing one of the other\n",
        "  # generator buttons, it breaks!\n",
        "  if not qa: raise Exception(\"No source text or file given\")\n",
        "  history = history or [] # Account for issue if history is empty\n",
        "  # Turn nested list into string:\n",
        "  # [[\"Hello HAL\", \"Hi Dave\"], [\"Open the pod bay doors\", \"No.\"]] ->\n",
        "  # \"Hello HAL\\nHi Dave\\nOpen the pod bay doors\\nNo.\"\n",
        "  # TODO: This conversion doesn't distinguish between the input of the user\n",
        "  # and the output from the model... I could add tags for each section, e.g.\n",
        "  # \"USER:Hello HAL\\nBOT:Hi Dave\\nUSER:Open the pod bay doors\\nBOT:No.\"\n",
        "  # But that uses up extra tokens... we need to figure out if that's worth it\n",
        "  history_flat = [message for exchange in history\n",
        "               for message in exchange if message]\n",
        "  history_string = '\\n'.join(history_flat)\n",
        "  response = generate_response(history_string)\n",
        "  return response\n",
        "\n",
        "def bot(history, use_model=True, character_crawl=False):\n",
        "  \"\"\"Get model response based on chat history (including user input).\n",
        "  If use_model is False, then return a placeholder value.\n",
        "  If character_crawl, then show each character in the output one at a time.\n",
        "  See https://gradio.app/creating-a-chatbot/\"\"\"\n",
        "\n",
        "  answer, sources = get_chatbot_response(history) if use_model \\\n",
        "      else (\"This is a placeholder message.\", [])\n",
        "\n",
        "  # Add the link to the sources\n",
        "  #bot_message = f\"{answer}\\n[Sources](#sources)\"\n",
        "  source_indices = update_source_list(sources)\n",
        "  source_citations = \" \".join(format_source_citation(source_index)\n",
        "                      for source_index in source_indices)\n",
        "  bot_message = answer + \"\\nSources: \" + source_citations\n",
        "\n",
        "  \"\"\"\n",
        "  if character_crawl:\n",
        "    # Display generated response, one character at a time\n",
        "    # TODO doesn't work if the history is empty (no messages)\n",
        "    # However, get_chatbot_response() should always output something, so it's fine\n",
        "    history[-1][1] = \"\"\n",
        "    for character in bot_message:\n",
        "        history[-1][1] += character\n",
        "        # TODO Remove timeout\n",
        "        time.sleep(0.01)\n",
        "        yield history\n",
        "  else:\n",
        "    history[-1][1] = bot_message\n",
        "    yield history\n",
        "  \"\"\"\n",
        "  history[-1][1] = bot_message\n",
        "  yield [history, *get_source_display_updates()]\n",
        "\n",
        "def reenable_chat():\n",
        "  \"\"\"Called after user() disables chat and bot provides response, meaning\n",
        "  the user is now free to add follow-up questions / comments to chatbot.\"\"\"\n",
        "  gr.update(interactive=True)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "lOA1Vn9GKPeN"
      },
      "outputs": [],
      "source": [
        "# Downloadable formats\n",
        "\n",
        "def save_chatbot_dialogue(chatbot, filename='chatbot_dialogue.json'):\n",
        "  with open(filename, 'w') as file:\n",
        "    json.dump(chatbot, file)\n",
        "  files.download(filename)\n",
        "\n",
        "def list_to_str(chatbot):\n",
        "  total_interaction = \"\"\n",
        "  for line in chatbot:\n",
        "    if line[0]:\n",
        "      user_message = \"User: \" + line[0] + \"\\n\"\n",
        "      total_interaction += user_message\n",
        "    if line[1]:\n",
        "      chat_message = \"Bot: \" + line[1] + \"\\n\"\n",
        "      total_interaction += chat_message\n",
        "  return total_interaction\n",
        "\n",
        "from textwrap import wrap\n",
        "def save_chatbot_dialogue_pdf(chatbot, filename=\"chatbot_dialogue.pdf\"):\n",
        "  chatbot = list_to_str(chatbot)\n",
        "  canvas = Canvas(filename)\n",
        "  t = canvas.beginText()\n",
        "  t.setFont('Helvetica', 12)\n",
        "  t.setCharSpace(2)\n",
        "  t.setTextOrigin(50, 750)\n",
        "  t.textLines(chatbot)\n",
        "  canvas.drawText(t)\n",
        "  canvas.save()\n",
        "  files.download(filename)\n",
        "\n",
        "def save_as_txt(chatbot, filename = 'chat_dialogue.txt'):\n",
        "  chatbot = list_to_str(chatbot)\n",
        "  with open(filename, 'w') as file:\n",
        "    file.write(chatbot)\n",
        "  files.download(filename)\n",
        "\n",
        "def save_as_csv(chatbot, filename = 'chat_dialogue.csv'):\n",
        "  chatbot = list_to_str(chatbot)\n",
        "  with open(filename, 'w') as file:\n",
        "    file.write(chatbot)\n",
        "  files.download(filename)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "id": "vV9IY1H4H7UK"
      },
      "outputs": [],
      "source": [
        "# Function to save prompts (premade or custom) and return in the user input box in the chatbot\n",
        "\n",
        "saved_text = \"\"\n",
        "def save_text(text):\n",
        "    global saved_text\n",
        "    saved_text = text\n",
        "\n",
        "def return_text():\n",
        "    # Return the saved text\n",
        "    return saved_text"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 684
        },
        "id": "Z6d6m-sBwnkA",
        "outputId": "37bd4262-7eed-49aa-e064-7f0443ed9a69"
      },
      "outputs": [
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "<ipython-input-22-8f58a957929c>:113: GradioUnusedKwargWarning: You have unused kwarg parameters in Box, please remove them: {'scale': 1}\n",
            "  with gr.Box(elem_id=\"sources-container\", scale=1):\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Setting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n",
            "\n",
            "Colab notebook detected. To show errors in colab notebook, set debug=True in launch()\n",
            "Running on public URL: https://f880b30167f96bbba1.gradio.live\n",
            "\n",
            "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n"
          ]
        },
        {
          "data": {
            "text/html": [
              "<div><iframe src=\"https://f880b30167f96bbba1.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
            ],
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": []
          },
          "execution_count": 22,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# See https://gradio.app/custom-CSS-and-JS/\n",
        "css=\"\"\"\n",
        "#sources-container {\n",
        "  overflow: scroll !important; /* Needs to override default formatting */\n",
        "  /*max-height: 20em; */ /* Arbitrary value */\n",
        "}\n",
        "#sources-container > div { padding-bottom: 1em !important; /* Arbitrary value */ }\n",
        ".short-height > * > * { min-height: 0 !important; }\n",
        ".translucent { opacity: 0.5; }\n",
        ".textbox_label { padding-bottom: .5em; }\n",
        "\"\"\"\n",
        "#srcs = [] # Reset sources (db and qa are kept the same for ease of testing)\n",
        "\n",
        "with gr.Blocks(css=css, analytics_enabled=False) as demo:\n",
        "  gr.Markdown(\"# Student Notebook Thingy\")\n",
        "  with gr.Box():\n",
        "    gr.HTML(\"\"\"<span>Embed your OpenAI API key below; if you haven't created one already, visit\n",
        "      <a href=\"https://platform.openai.com/account/api-keys\">platform.openai.com/account/api-keys</a>\n",
        "    to sign up for an account and get your personal API key</span>\"\"\",\n",
        "            elem_classes=\"textbox_label\")\n",
        "    # TODO Find a better way to fix minor spacing issue below this element\n",
        "    input = gr.Textbox(show_label=False, type=\"password\", container=False,\n",
        "                      placeholder=\"●●●●●●●●●●●●●●●●●\")\n",
        "    input.change(fn=embed_key, inputs=input, outputs=None)\n",
        "\n",
        "\n",
        "  with gr.Blocks():\n",
        "    gr.Markdown(\"## Add Document Source (File / Text / VectorStore)\")\n",
        "    # TODO Add entry for path to vector store (should be disabled for now)\n",
        "    with gr.Row(equal_height=True):\n",
        "      text_input = gr.TextArea(label='Copy and paste your text below',\n",
        "                                lines=2)\n",
        "      # TODO This is called every time the text changes, which is very\n",
        "      # wasteful... the solution would be to only call this when necessary,\n",
        "      # (i.e. when generating text), but that would require some extra\n",
        "      # parameters passed in to the generating functions... maybe\n",
        "      # add a check for that in the functions which reference the doc store?\n",
        "      text_input.input(create_vector_store_from_text, [text_input], None)\n",
        "\n",
        "      file_input = gr.Files(label=\"Load a .txt or .pdf file\",\n",
        "                            file_types=['.pdf', '.txt'], type=\"file\",\n",
        "                            elem_classes=\"short-height\")\n",
        "      file_input.change(create_vector_store_from_files, [file_input], None)\n",
        "\n",
        "      text_input = gr.TextArea(label='Enter vector store URL, if given by instructor (WIP)',\n",
        "                                lines=2, interactive=\n",
        "                               False, elem_classes=\"translucent\")\n",
        "\n",
        "  with gr.Blocks():\n",
        "    #gr.Markdown(\"## Optional: Enter Your Learning Objectives\")\n",
        "    learning_objectives = gr.Textbox(label='If provided by your instructor, please input your learning objectives for this session', value='')\n",
        "\n",
        "  # Premade question prompts\n",
        "  # TODO rename section?`\n",
        "  with gr.Blocks():\n",
        "    gr.Markdown(\"\"\"\n",
        "    ## Generate a Premade Prompt\n",
        "    Select your type and number of desired questions. Click \"Generate Prompt\" to get your premade prompt,\n",
        "    and then \"Insert Prompt into Chat\" to copy the text into the chat interface below. \\\n",
        "    You can also copy the prompt using the icon in the upper right corner and paste directly into the input box when interacting with the model.\n",
        "    \"\"\")\n",
        "    with gr.Row():\n",
        "      with gr.Column():\n",
        "        question_type = gr.Dropdown([\"Multiple Choice\", \"True or False\", \"Short Answer\", \"Fill in the Blank\", \"Random\"], label=\"Question Type\")\n",
        "        number_of_questions = gr.Textbox(label=\"Enter desired number of questions\")\n",
        "        sa_desired_length = gr.Dropdown([\"1-2\", \"3-4\", \"5-6\", \"6 or more\"], label = \"For short answer questions only, choose the desired sentence length for answers. The default value is 1-2 sentences.\")\n",
        "      with gr.Column():\n",
        "        prompt_button = gr.Button(\"Generate Prompt\")\n",
        "        premade_prompt_output = gr.Textbox(label=\"Generated prompt (save or copy)\", show_copy_button=True)\n",
        "        prompt_button.click(prompt_select,\n",
        "                        inputs=[question_type, number_of_questions, sa_desired_length],\n",
        "                        outputs=premade_prompt_output)\n",
        "\n",
        "    insert_premade_prompt_button = gr.Button(\"Input Prompt into Chat\")\n",
        "\n",
        "  '''\n",
        "  with gr.Blocks():\n",
        "      # TODO Consider if we want to have this section\n",
        "      # Maybe use this section for prompt refinement? E.g. you enter prompt\n",
        "      # and model tells you how to improve it?\n",
        "      gr.Markdown(\"\"\"\n",
        "      ## Write Your Own Custom Prompt\n",
        "      For a comprehensive list of example prompts, see our repository's wiki: https://github.com/vanderbilt-data-science/lo-achievement/wiki/High-Impact-Prompts.\n",
        "      After writing your prompt, be sure to click \"Save Prompt\" to save your prompt for chatting with the model below. You can also copy the prompt using the icon in the upper right corner and paste directly into the input box when interacting with the model.\n",
        "      \"\"\")\n",
        "      custom_prompt_block = gr.TextArea(label=\"Enter your own custom prompt\", show_copy_button=True)\n",
        "      #save_prompt_block = gr.Button(\"Save Prompt\")\n",
        "      #save_prompt_block.click(save_text, inputs=custom_prompt_block, outputs=None)\n",
        "  '''\n",
        "\n",
        "  # Chatbot (https://gradio.app/creating-a-chatbot/)\n",
        "  '''\n",
        "  with gr.Blocks():\n",
        "    gr.Markdown(\"\"\"\n",
        "    ## Chat with the Model\n",
        "    Click \"Display Prompt\" to display the premade or custom prompt that you created earlier. Then, continue chatting with the model.\n",
        "    \"\"\")\n",
        "    with gr.Row():\n",
        "      show_prompt_block = gr.Button(\"Display Prompt\")\n",
        "  '''\n",
        "  gr.Markdown(\"## Chat with the Model\")\n",
        "  with gr.Row(equal_height=True):\n",
        "    with gr.Column(scale=2):\n",
        "      chatbot = gr.Chatbot()\n",
        "      with gr.Row():\n",
        "        user_chat_input = gr.Textbox(label=\"User input\", scale=9)\n",
        "        user_chat_input.submit(return_text, inputs=None, outputs=user_chat_input)\n",
        "        user_chat_submit = gr.Button(\"Ask/answer model\", scale=1)\n",
        "        #show_prompt_block.click(return_text, inputs=None, outputs=user_chat_input)\n",
        "\n",
        "    # TODO Move the sources so it's displayed to the right of the chat bot,\n",
        "    # with the sources taking up about 1/3rd of the horizontal space\n",
        "    with gr.Box(elem_id=\"sources-container\", scale=1):\n",
        "      # TODO: Display document sources in a nicer format?\n",
        "      gr.HTML(value=\"<h3 id='sources'>Sources</h3>\")\n",
        "      sources_output = []\n",
        "      for i in range(num_sources):\n",
        "        source_elem = gr.HTML(visible=False)\n",
        "        sources_output.append(source_elem)\n",
        "\n",
        "  # Copy text from premade prompt output to user chat input\n",
        "  insert_premade_prompt_button.click(lambda text: text,\n",
        "                        inputs=premade_prompt_output,\n",
        "                        outputs=user_chat_input)\n",
        "\n",
        "  # Display input and output in three-ish parts\n",
        "  # (using asynchronous functions):\n",
        "  # First show user input, then show model output when complete\n",
        "  # Then wait until the bot provides response and return the result\n",
        "  # Finally, allow the user to ask a new question by reenabling input\n",
        "  async_response = user_chat_submit.click(user,\n",
        "            [user_chat_input, chatbot],\n",
        "            [user_chat_input, chatbot], queue=False) \\\n",
        "  .then(bot, chatbot, [chatbot, *sources_output], queue=True) \\\n",
        "  .then(reenable_chat, None, [user_chat_input], queue=False)\n",
        "\n",
        "  with gr.Blocks():\n",
        "    gr.Markdown(\"\"\"\n",
        "    ## Export Your Chat History\n",
        "    Export your chat history as a .json, PDF file, .txt, or .csv file\n",
        "    \"\"\")\n",
        "    with gr.Row():\n",
        "      export_dialogue_button = gr.Button(\"JSON\")\n",
        "      export_dialogue_button.click(save_chatbot_dialogue, chatbot, None)\n",
        "      export_dialogue_button_pdf = gr.Button(\"PDF\")\n",
        "      export_dialogue_button_pdf.click(save_chatbot_dialogue_pdf, chatbot, None)\n",
        "      export_dialogue_button_txt = gr.Button(\"TXT\")\n",
        "      export_dialogue_button_txt.click(save_as_txt, chatbot, None)\n",
        "      export_dialogue_button_csv = gr.Button(\"CSV\")\n",
        "      export_dialogue_button_csv.click(save_as_csv, chatbot, None)\n",
        "\n",
        "demo.queue()\n",
        "#demo.launch(debug=True)\n",
        "demo.launch()"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "include_colab_link": true,
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3.11.5 64-bit",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.5"
    },
    "vscode": {
      "interpreter": {
        "hash": "b0fa6594d8f4cbf19f97940f81e996739fb7646882a419484c72d19e05852a7e"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}