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
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac0cc1aa-e68d-432d-b316-52e272c43207",
   "metadata": {},
   "outputs": [],
   "source": [
    "import streamlit as st\n",
    "from streamlit_feedback import streamlit_feedback\n",
    "\n",
    "import os\n",
    "import pandas as pd\n",
    "import base64\n",
    "from io import BytesIO\n",
    "import sys\n",
    "sys.path.insert(0, \"../\")\n",
    "\n",
    "import chromadb\n",
    "from llama_index.core import (\n",
    "            VectorStoreIndex, \n",
    "            SimpleDirectoryReader,\n",
    "            StorageContext,\n",
    "            Document\n",
    ")\n",
    "from llama_index.vector_stores.chroma.base import ChromaVectorStore\n",
    "from llama_index.embeddings.huggingface.base import HuggingFaceEmbedding\n",
    "from llama_index.llms.openai import OpenAI\n",
    "from llama_index.core.memory import ChatMemoryBuffer\n",
    "from llama_index.core.tools import QueryEngineTool\n",
    "from llama_index.agent.openai import OpenAIAgent\n",
    "from llama_index.core import Settings\n",
    "\n",
    "from vision_api import get_transcribed_text\n",
    "from qna_prompting import get_qna_question_tool, evaluate_qna_answer_tool\n",
    "\n",
    "import nest_asyncio\n",
    "nest_asyncio.apply()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b05cb9b-869a-409c-8d4f-aafae703c558",
   "metadata": {},
   "outputs": [],
   "source": [
    "@st.cache_resource\n",
    "def get_document_object(input_files):\n",
    "    documents = SimpleDirectoryReader(input_files=input_files).load_data()\n",
    "    document = Document(text=\"\\n\\n\".join([doc.text for doc in documents]))\n",
    "    return document\n",
    "\n",
    "@st.cache_resource\n",
    "def get_llm_object(selected_model, temperature):\n",
    "    llm = OpenAI(model=selected_model, temperature=temperature)\n",
    "    return llm\n",
    "\n",
    "@st.cache_resource\n",
    "def get_embedding_model(model_name, fine_tuned_path=None):\n",
    "    if fine_tuned_path is None:\n",
    "        print(f\"loading from `{model_name}` from huggingface\")\n",
    "        embed_model = HuggingFaceEmbedding(model_name=model_name)\n",
    "    else:\n",
    "        print(f\"loading from local `{fine_tuned_path}`\")\n",
    "        embed_model = fine_tuned_path\n",
    "    return embed_model\n",
    "\n",
    "@st.cache_resource\n",
    "def get_query_engine(input_files, llm_model, temperature,\n",
    "                     embedding_model, fine_tuned_path,\n",
    "                     system_content, persisted_vector_db):\n",
    "    \n",
    "    llm = get_llm_object(llm_model, temperature)\n",
    "    embedded_model = get_embedding_model(\n",
    "                        model_name=embedding_model, \n",
    "                        fine_tuned_path=fine_tuned_path\n",
    "    )\n",
    "    Settings.llm = llm\n",
    "    Settings.chunk_size = 1024\n",
    "    Settings.embed_model = embedded_model\n",
    "\n",
    "    if os.path.exists(persisted_vector_db):\n",
    "        print(\"loading from vector database - chroma\")\n",
    "        db = chromadb.PersistentClient(path=persisted_vector_db)\n",
    "        chroma_collection = db.get_or_create_collection(\"quickstart\")\n",
    "        vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
    "        storage_context = StorageContext.from_defaults(vector_store=vector_store)\n",
    "\n",
    "        index = VectorStoreIndex.from_vector_store(\n",
    "            vector_store=vector_store,\n",
    "            storage_context=storage_context\n",
    "        )\n",
    "    else:\n",
    "        print(\"create new chroma vector database..\")\n",
    "        documents = SimpleDirectoryReader(input_files=input_files).load_data()\n",
    "        \n",
    "        db = chromadb.PersistentClient(path=persisted_vector_db)\n",
    "        chroma_collection = db.get_or_create_collection(\"quickstart\")\n",
    "        vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
    "        \n",
    "        nodes = Settings.node_parser.get_nodes_from_documents(documents)\n",
    "        storage_context = StorageContext.from_defaults(vector_store=vector_store)\n",
    "        storage_context.docstore.add_documents(nodes)\n",
    "\n",
    "        index = VectorStoreIndex(nodes, storage_context=storage_context)\n",
    "    \n",
    "    memory = ChatMemoryBuffer.from_defaults(token_limit=15000)\n",
    "    hi_content_engine = index.as_query_engine(\n",
    "                            memory=memory,\n",
    "                            system_prompt=system_content,\n",
    "                            similarity_top_k=20,\n",
    "                            streaming=True\n",
    "    )\n",
    "    hi_textbook_query_description = \"\"\"\n",
    "        Use this tool to extract content from textbook `Health Insurance 7th Edition`,\n",
    "        that has 15 chapters in total. When user wants to learn more about a \n",
    "        particular chapter, this tool will help to assist user to get better\n",
    "        understanding of the content of the textbook.\n",
    "    \"\"\"\n",
    "    \n",
    "    hi_query_tool = QueryEngineTool.from_defaults(\n",
    "                        query_engine=hi_content_engine,\n",
    "                        name=\"health_insurance_textbook_query_engine\",\n",
    "                        description=hi_textbook_query_description\n",
    "    )\n",
    "\n",
    "    agent = OpenAIAgent.from_tools(tools=[\n",
    "                                        hi_query_tool, \n",
    "                                        get_qna_question_tool,\n",
    "                                        evaluate_qna_answer_tool\n",
    "                                    ],\n",
    "                                   max_function_calls=1,\n",
    "                                   llm=llm, \n",
    "                                   verbose=True,\n",
    "                                   system_prompt=textbook_content)\n",
    "    print(\"loaded AI agent, let's begin the chat!\")\n",
    "    print(\"=\"*50)\n",
    "    print(\"\")\n",
    "\n",
    "    return agent\n",
    "\n",
    "def generate_llm_response(prompt_input, tool_choice=\"auto\"):\n",
    "    chat_agent = get_query_engine(input_files=input_files, \n",
    "                                   llm_model=selected_model, \n",
    "                                   temperature=temperature,\n",
    "                                   embedding_model=embedding_model,\n",
    "                                   fine_tuned_path=fine_tuned_path,\n",
    "                                   system_content=system_content,\n",
    "                                   persisted_vector_db=persisted_vector_db)\n",
    "    \n",
    "    # st.session_state.messages\n",
    "    response = chat_agent.stream_chat(prompt_input, tool_choice=tool_choice)\n",
    "    return response\n",
    "\n",
    "def handle_feedback(user_response):\n",
    "    st.toast(\"✔️ Feedback received!\")\n",
    "    st.session_state.feedback = False\n",
    "\n",
    "def handle_image_upload():\n",
    "    st.session_state.release_file = \"true\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f148426b-1634-45ed-a1fa-44e9c6ab14ac",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4461d081-d8d0-4801-ad52-dbe826cbfe59",
   "metadata": {},
   "outputs": [],
   "source": [
    "openai_api = os.getenv(\"OPENAI_API_KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a24c861-896b-4800-8478-73f8cd65e8fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "image_prompt = False\n",
    "# llm_model = \"gpt-3.5-turbo-0125\"\n",
    "llm_model = \"gpt-4-0125-preview\"\n",
    "temperature = 0\n",
    "\n",
    "input_files = [\"./raw_documents/HI Chapter Summary Version 1.3.pdf\",\n",
    "               \"./raw_documents/qna.txt\"]\n",
    "embedding_model = \"BAAI/bge-small-en-v1.5\"\n",
    "persisted_vector_db = \"../models/chroma_db\"\n",
    "fine_tuned_path = \"local:../models/fine-tuned-embeddings\"\n",
    "system_content = (\n",
    "                    \"You are a helpful study assistant. \"\n",
    "                    \"You do not respond as 'User' or pretend to be 'User'. \"\n",
    "                    \"You only respond once as 'Assistant'.\"\n",
    ")\n",
    "textbook_content = (\n",
    "                    \"The content of the textbook `Health Insurance 7th Edition` are as follows,\"\n",
    "                    \"- Chapter 1: Overview Of Healthcare Environment In Singapore\"\n",
    "                    \"- Chapter 2: Medical Expense Insurance\"\n",
    "                    \"- Chapter 3: Group Medical Expense Insurance\"\n",
    "                    \"- Chapter 4: Disability Income Insurance\"\n",
    "                    \"- Chapter 5: Long-Term Care Insurance \"\n",
    "                    \"- Chapter 6: Critical Illness Insurance\"\n",
    "                    \"- Chapter 7: Other Types Of Health Insurance\"\n",
    "                    \"- Chapter 8: Managed Healthcare\"\n",
    "                    \"- Chapter 9: Part I Healthcare Financing\"\n",
    "                    \"- Chapter 9: Part II Healthcare Financing\"\n",
    "                    \"- Chapter 10: Common Policy Provisions\"\n",
    "                    \"- Chapter 11: Health Insurance Pricing\"\n",
    "                    \"- Chapter 12: Health Insurance Underwriting\"\n",
    "                    \"- Chapter 13: Notice No: MAS 120 Disclosure And Advisory Process - Requirements For Accident And Health Insurance Products\"\n",
    "                    \"- Chapter 14: Financial Needs Analysis\"\n",
    "                    \"- Chapter 15: Case Studies\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5e4b22c-1e29-4ab8-9039-6e86f566871a",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = get_llm_object(llm_model, temperature)\n",
    "embedded_model = get_embedding_model(\n",
    "                    model_name=embedding_model, \n",
    "                    fine_tuned_path=fine_tuned_path\n",
    ")\n",
    "Settings.llm = llm\n",
    "Settings.chunk_size = 1024\n",
    "Settings.embed_model = embedded_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e92d21e3-8483-4f24-91cf-40a6c10d43c5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5753c6ed-41a6-40b5-bc4f-477eb7c1d5c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"loading from vector database - chroma\")\n",
    "db = chromadb.PersistentClient(path=persisted_vector_db)\n",
    "chroma_collection = db.get_or_create_collection(\"quickstart\")\n",
    "vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
    "storage_context = StorageContext.from_defaults(vector_store=vector_store)\n",
    "\n",
    "index = VectorStoreIndex.from_vector_store(\n",
    "    vector_store=vector_store,\n",
    "    storage_context=storage_context\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d91e2dda-cb74-4d85-adce-a4a72c53cc7d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4211bb2-aba9-4be2-b2f1-6fbd3f7e4223",
   "metadata": {},
   "outputs": [],
   "source": [
    "memory = ChatMemoryBuffer.from_defaults(token_limit=15000)\n",
    "hi_content_engine = index.as_query_engine(\n",
    "                        memory=memory,\n",
    "                        system_prompt=system_content,\n",
    "                        similarity_top_k=8,\n",
    "                        verbose=True,\n",
    "                        streaming=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "007f8bf5-19c5-4462-b5f2-5f4ff30f593b",
   "metadata": {},
   "outputs": [],
   "source": [
    "hi_textbook_query_description = \"\"\"\n",
    "    Use this tool to extract content from the query engine,\n",
    "    which is built by ingesting textbook content from `Health Insurance 7th Edition`,\n",
    "    that has 15 chapters in total. When user wants to learn more about a \n",
    "    particular chapter, this tool will help to assist user to get better\n",
    "    understanding of the content of the textbook.\n",
    "\"\"\"\n",
    "\n",
    "hi_query_tool = QueryEngineTool.from_defaults(\n",
    "                    query_engine=hi_content_engine,\n",
    "                    name=\"health_insurance_textbook_query_engine\",\n",
    "                    description=hi_textbook_query_description\n",
    ")\n",
    "agent = OpenAIAgent.from_tools(tools=[\n",
    "                                    hi_query_tool, \n",
    "                                    get_qna_question_tool,\n",
    "                                    evaluate_qna_answer_tool\n",
    "                                ],\n",
    "                               max_function_calls=1,\n",
    "                               llm=llm, \n",
    "                               verbose=True,\n",
    "                               system_prompt=textbook_content)\n",
    "\n",
    "print(\"loaded AI agent, let's begin the chat!\")\n",
    "print(\"=\"*50)\n",
    "print(\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2e42ad6-20fc-4f2e-a4ea-403e79b14ba4",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c62e817e-c7c8-4f90-9e32-217fec376565",
   "metadata": {},
   "outputs": [],
   "source": [
    "response = hi_content_engine.query(\"can you give me the list of chapters that `Health Insurance 7th Edition` covers\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5902ffd2-2f66-4b89-bf7f-a05e3fdeccaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "for res in response.response_gen:\n",
    "    print(res, end=\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e75453b-85c7-4e1c-8683-6df45a13cacb",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b97d90d-5c59-486f-863b-4aaa12ed0ea0",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4584aa46-b488-4535-9d69-2736c9dad170",
   "metadata": {},
   "outputs": [],
   "source": [
    "response = agent.stream_chat(\"hihi\", tool_choice=\"auto\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eff8bb8d-a2d1-428a-9c3d-193389378288",
   "metadata": {},
   "outputs": [],
   "source": [
    "for res in response.response_gen:\n",
    "    print(res, end=\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7a504af-6499-4649-8e68-2a86d415e458",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}