File size: 36,751 Bytes
43139c6
 
 
 
dfbf21d
43139c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfbf21d
43139c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfbf21d
43139c6
 
 
 
 
 
 
dfbf21d
43139c6
 
 
 
 
 
 
 
 
 
 
 
 
 
dfbf21d
 
 
 
 
 
 
 
 
43139c6
 
dfbf21d
43139c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfbf21d
43139c6
 
 
dfbf21d
43139c6
 
 
 
dfbf21d
43139c6
 
 
dfbf21d
43139c6
 
 
 
 
dfbf21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43139c6
 
 
 
 
dfbf21d
 
 
 
43139c6
 
dfbf21d
43139c6
 
 
 
 
dfbf21d
 
43139c6
 
 
 
dfbf21d
 
 
 
 
 
 
 
43139c6
 
 
 
 
 
dfbf21d
43139c6
dfbf21d
43139c6
dfbf21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43139c6
 
 
dfbf21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43139c6
 
 
 
dfbf21d
43139c6
 
 
 
 
 
dfbf21d
43139c6
dfbf21d
43139c6
 
 
 
 
dfbf21d
43139c6
 
 
 
 
 
 
 
 
 
 
 
dfbf21d
43139c6
 
 
 
 
dfbf21d
 
 
 
 
43139c6
dfbf21d
43139c6
 
 
dfbf21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43139c6
dfbf21d
 
 
 
 
 
 
 
 
 
 
 
 
43139c6
dfbf21d
 
43139c6
 
 
 
dfbf21d
43139c6
 
 
 
 
 
dfbf21d
43139c6
 
 
 
 
 
 
dfbf21d
43139c6
 
 
 
 
 
 
 
 
 
 
 
dfbf21d
43139c6
 
 
 
 
 
dfbf21d
 
 
43139c6
dfbf21d
 
 
 
 
 
 
 
43139c6
dfbf21d
43139c6
dfbf21d
43139c6
dfbf21d
 
43139c6
dfbf21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43139c6
 
dfbf21d
 
 
 
 
43139c6
 
dfbf21d
 
43139c6
dfbf21d
 
 
 
43139c6
dfbf21d
43139c6
dfbf21d
 
43139c6
 
 
dfbf21d
 
 
 
 
 
 
 
 
 
 
 
43139c6
dfbf21d
43139c6
dfbf21d
43139c6
 
 
 
dfbf21d
43139c6
dfbf21d
 
 
43139c6
 
dfbf21d
 
43139c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The autoreload extension is already loaded. To reload it, use:\n",
      "  %reload_ext autoreload\n"
     ]
    }
   ],
   "source": [
    "from dotenv import load_dotenv\n",
    "from typing import Annotated, List, Tuple\n",
    "from typing_extensions import TypedDict\n",
    "from langchain.tools import tool, BaseTool\n",
    "from langchain.schema import Document\n",
    "from langgraph.graph import StateGraph, START, END, MessagesState\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate\n",
    "from langchain.schema import SystemMessage, HumanMessage, AIMessage\n",
    "from langchain.retrievers.multi_query import MultiQueryRetriever\n",
    "import gradio as gr\n",
    "\n",
    "from IPython.display import Image, display\n",
    "import sys\n",
    "import os\n",
    "import uuid\n",
    "\n",
    "\n",
    "load_dotenv('/Users/nadaa/Documents/code/py_innovations/srf_chatbot_v2/.env')\n",
    "\n",
    "sys.path.append(os.path.abspath('..'))\n",
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "\n",
    "import src.utils.qdrant_manager as qm\n",
    "import prompts.system_prompts as sp\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ToolManager:\n",
    "    def __init__(self, collection_name=\"openai_large_chunks_1500char\"):\n",
    "        self.tools = []\n",
    "        self.qdrant = qm.QdrantManager(collection_name=collection_name)\n",
    "        self.vectorstore = self.qdrant.get_vectorstore()\n",
    "        self.add_vector_search_tool()\n",
    "\n",
    "    def get_tools(self):\n",
    "        return self.tools\n",
    "\n",
    "    def add_vector_search_tool(self):\n",
    "        @tool\n",
    "        def vector_search(query: str, k: int = 5) -> list[Document]:\n",
    "            \"\"\"Useful for simple queries. This tool will search a vector database for passages from the teachings of Paramhansa Yogananda and other publications from the Self Realization Fellowship (SRF).\n",
    "            The user has the option to specify the number of passages they want the search to return, otherwise the number of passages will be set to the default value.\"\"\"\n",
    "            retriever = self.vectorstore.as_retriever(search_kwargs={\"k\": k})\n",
    "            documents = retriever.invoke(query)\n",
    "            return documents\n",
    "        \n",
    "        \n",
    "        @tool\n",
    "        def multiple_query_vector_search(query: str, k: int = 5) -> list[Document]:\n",
    "            \"\"\"Useful when the user's query is vague, complex, or involves multiple concepts. \n",
    "            This tool will write multiple versions of the user's query and search the vector database for relevant passages. \n",
    "            Returns a list of relevant passages.\"\"\"\n",
    "            \n",
    "            llm = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0.5)\n",
    "            retriever_from_llm = MultiQueryRetriever.from_llm(retriever=self.vectorstore.as_retriever(), llm=llm)\n",
    "            documents = retriever_from_llm.invoke(query)\n",
    "            return documents\n",
    "        \n",
    "        \n",
    "        self.tools.append(vector_search)\n",
    "        self.tools.append(multiple_query_vector_search)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "class SRFChatbot:\n",
    "    def __init__(\n",
    "        self,\n",
    "        chatbot_instructions: str = sp.system_prompt_templates['Open-Ended Bot'],\n",
    "        model: str = 'gpt-4o-mini',\n",
    "        temperature: float = 0,\n",
    "    ):\n",
    "        # Initialize the LLM and the system message\n",
    "        self.llm = ChatOpenAI(model=model, temperature=temperature)\n",
    "        self.system_message = SystemMessage(content=chatbot_instructions)\n",
    "        self.tools = ToolManager().get_tools()\n",
    "        self.llm_with_tools = self.llm.bind_tools(self.tools)\n",
    "\n",
    "        # Build the graph\n",
    "        self.graph = self.build_graph()\n",
    "        # Get the configurable\n",
    "        self.config = self.get_configurable()\n",
    "    \n",
    "    def reset_system_prompt(self, chatbot_instructions_dropdown: str):\n",
    "        # Get chatbot instructions\n",
    "        chatbot_instructions = sp.system_prompt_templates[chatbot_instructions_dropdown]\n",
    "        # Reset the system prompt\n",
    "        self.system_message = SystemMessage(content=chatbot_instructions)\n",
    "        # Reset the configurable\n",
    "        self.config = self.get_configurable()\n",
    "\n",
    "        return chatbot_instructions\n",
    "\n",
    "    def get_configurable(self):\n",
    "        # This thread id is used to keep track of the chatbot's conversation\n",
    "        self.thread_id = str(uuid.uuid4())\n",
    "        return {\"configurable\": {\"thread_id\": self.thread_id}}\n",
    "        \n",
    "    # Add the system message onto the llm\n",
    "    def chatbot(self, state: MessagesState):\n",
    "        messages = [self.system_message] + state[\"messages\"]\n",
    "        return {\"messages\": [self.llm_with_tools.invoke(messages)]}\n",
    "    \n",
    "    def build_graph(self):\n",
    "\n",
    "        # Add chatbot state\n",
    "        graph_builder = StateGraph(MessagesState)\n",
    "\n",
    "        # Add nodes\n",
    "        tool_node = ToolNode(self.tools)\n",
    "        graph_builder.add_node(\"tools\", tool_node)\n",
    "        graph_builder.add_node(\"chatbot\", self.chatbot)\n",
    "\n",
    "        # Add a conditional edge wherein the chatbot can decide whether or not to go to the tools\n",
    "        graph_builder.add_conditional_edges(\n",
    "            \"chatbot\",\n",
    "            tools_condition,\n",
    "        )\n",
    "\n",
    "        # Add fixed edges\n",
    "        graph_builder.add_edge(START, \"chatbot\")\n",
    "        graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "\n",
    "        # Instantiate the memory saver\n",
    "        memory = MemorySaver()\n",
    "\n",
    "        # Compile the graph\n",
    "        return graph_builder.compile(checkpointer=memory)\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "chatbot = SRFChatbot()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"Tell me more about reducing nervousness to improve sleep\"\n",
    "results = chatbot.graph.invoke({\"messages\": [HumanMessage(content=query)]}, chatbot.config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "To reduce nervousness and improve sleep, it is essential to recognize that much of our nervousness stems from our own reactions and emotional states. Paramhansa Yogananda emphasizes that restlessness and emotional excitement can overload the nervous system, leading to fatigue and anxiety. Engaging in deep meditation can help calm the nerves, as it allows the body to rest and rejuvenate. Additionally, dietary choices play a significant role; consuming calming foods such as whole grains, fruits, and avoiding stimulants like caffeine and alcohol can support a healthier nervous system. Practicing silence and reducing exposure to noise can also alleviate nervousness, creating a more peaceful environment conducive to sleep.\n",
      "\n",
      "**Quotes:**\n",
      "1. \"You always blame other things for making you nervous, but never accuse yourself. Yet it is you who make yourself nervous; ninety-nine percent is your own fault.\" - *Journey to Self-Realization, Probing the Core of Nervousness*\n",
      "2. \"When you stop overloading the nervous system, as when you are in deep sleep or a state of calmness in meditation, you are not nervous at all.\" - *Journey to Self-Realization, Probing the Core of Nervousness*\n",
      "3. \"Learn to enjoy silence; don’t listen to the radio or television for hours on end, or have them blaring mindlessly in the background all the time.\" - *Journey to Self-Realization, Examine Yourself to See What Makes You Nervous*\n",
      "4. \"The greatest healing of nervousness takes place when we attune our lives to God.\" - *Journey to Self-Realization, Attunement With God: Greatest Cure for Nervousness*\n",
      "\n",
      "**Recommended Reading:**\n",
      "- *Journey to Self-Realization* by Paramhansa Yogananda\n",
      "\n",
      "**Follow-up Questions:**\n",
      "1. What specific techniques can I use in meditation to calm my nerves?\n",
      "2. Are there particular foods or drinks that are especially beneficial for reducing nervousness?\n",
      "3. How can I create a more peaceful environment at home to improve my sleep?\n"
     ]
    }
   ],
   "source": [
    "print(results['messages'][-1].content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='Tell me more about reducing nervousness to improve sleep', additional_kwargs={}, response_metadata={}, id='c1d3f9ba-0e06-4a6a-b38c-3dcd3be78bbf'),\n",
       " AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_fjyQpF0pjUQZ8gobl2SAozXV', 'function': {'arguments': '{\"query\":\"reducing nervousness improve sleep\"}', 'name': 'vector_search'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 19, 'prompt_tokens': 433, 'total_tokens': 452, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-4a39fe1a-6413-4ba3-8aa3-290dc31a27bb-0', tool_calls=[{'name': 'vector_search', 'args': {'query': 'reducing nervousness improve sleep'}, 'id': 'call_fjyQpF0pjUQZ8gobl2SAozXV', 'type': 'tool_call'}], usage_metadata={'input_tokens': 433, 'output_tokens': 19, 'total_tokens': 452}),\n",
       " ToolMessage(content=\"[Document(metadata={'chapter_name': 'Probing the Core of Nervousness', 'split_id_sequential': 418, 'split_id_uuid': '5ca2777d-c2a0-4e32-96b7-e43ed71c3aa2', 'publication_name': 'Journey to Self-Realization', '_id': '2151431e-7e07-44b6-8f33-7c8e277993c8', '_collection_name': 'openai_large_chunks_1500char'}, page_content='Probing the Core of Nervousness Self-Realization Fellowship Temple, San Diego, California, June 15, 1947 Everyone has at times been nervous, more or less, without knowing why. I may shake this piece of cloth and say it is nervous, but what is making the cloth move? When I cease moving my hand, the cloth lies limp. You always blame other things for making you nervous, but never accuse yourself. Yet it is you who make yourself nervous; ninety-nine percent is your own fault. Restlessness, emotional excitement, concentrates too much energy in the nerves so that they begin to wear out. After years and years, the adverse effects of that nervousness begin to show. The nerves are very tough—God made them so, because they have to last a lifetime—but it is necessary to give them proper care. When you stop overloading the nervous system, as when you are in deep sleep or a state of calmness in meditation, you are not nervous at all. In meditative ecstasy the nerves become highly rested and rejuvenated.'), Document(metadata={'split_id_sequential': 526, 'publication_name': 'Journey to Self-Realization', 'split_id_uuid': '2cecd1d8-68bf-4831-a6d2-de6028ff5fc5', 'chapter_name': 'The Best Diet for the Nerves', '_id': 'ff7b43a1-b42d-4983-8472-6eaeed695f4b', '_collection_name': 'openai_large_chunks_1500char'}, page_content='A yogic drink that is very good for the nervous system is made by adding crushed rock candy and fresh lime juice to a glass of water. It should be thoroughly mixed and evenly blended so that the taste is equally sweet and sour. I have recommended this to many people with excellent results. Another beneficial practice when you are very nervous is to take a cold bath. I once told this to a newspaperman. He said, “Well, if I did that every time I was nervous, I would have to carry a bathtub with me all the time!” I said, “Not necessary. Take a large piece of ice and rub it all over the body, especially over all the openings of the body. With this yoga technique, you will find that your nerves will become much calmer.”'), Document(metadata={'split_id_sequential': 525, 'publication_name': 'Journey to Self-Realization', 'chapter_name': 'The Best Diet for the Nerves', 'split_id_uuid': '5b366387-d311-486a-bc74-0559cb45d041', '_id': 'e2a33e74-64d8-47f4-9edd-41eebe277585', '_collection_name': 'openai_large_chunks_1500char'}, page_content='The Best Diet for the Nerves Even foods, which also are material condensations of astral rays of life, have effects that are correlated to their colour. Various kinds of natural white foods are good for the nervous system; they benefit the white matter of the brain. Berries are good for the gray matter of the brain—that is, blueberries or blackberries (which are really purple). Most fruits are gold in colour (or variants of gold, such as red and orange). As gold is the colour of the creative vibratory energy in matter, such fruits help the muscles, the blood, and the tissues. Goat’s milk, unbleached almonds, and raisins are very good for the nervous system. But all forms of meat of higher animals, especially beef and pork, are harmful to the nervous system; they are hyperstimulating and cause aggressiveness. Avoid too much starch, especially foods made from refined flour. Eat whole grains, cottage cheese, and plenty of fruits, fruit juices, and fresh vegetables—these are important. Needless to say, alcoholic beverages and drugs destroy the nervous system; stay away from them. A yogic drink that is very good for the nervous system is made by adding crushed rock candy and fresh lime juice to a glass of water. It should be thoroughly mixed and evenly blended so that the taste is equally sweet and sour. I have recommended this to many people with excellent results. Another beneficial practice when you are very nervous is to take a cold bath. I once told this to a newspaperman.'), Document(metadata={'chapter_name': 'Examine Yourself to See What Makes You Nervous', 'publication_name': 'Journey to Self-Realization', 'split_id_sequential': 160, 'split_id_uuid': '0900b6ab-2a48-48db-a66b-2ca0e80f9c70', '_id': 'de7f20d2-d3ac-45b6-8588-1a0b568e2ec9', '_collection_name': 'openai_large_chunks_1500char'}, page_content='Other cars were speeding past us on the steep, winding grade. I thought they were hurrying to get to the mountaintop in time to see the sunrise. To my great amazement, when we arrived we were the only ones outside to enjoy the view. All the others were in the restaurant drinking coffee and eating doughnuts. Imagine! They rushed to the top and then rushed back, just for the thrill of being able to say when they got home that they had been there, and had coffee and doughnuts on Pikes Peak. That is what nervousness does. We should take time to enjoy things—the beauties of God’s creation, the many blessings of life—but avoid undue excitement, restlessness, and sudden emotions, which burn up the nervous system. Talking too much, including the habit of engaging in long conversations on the telephone, creates nervousness. Habitual twitching—such as drumming the fingers or moving the toes—burns energy in the nerves. Another cause of nervousness, though you may not be aware of it, is the noise of the radio or television going on for hours at a time. All sounds cause the nerves to react.1 A study conducted in the police department in Chicago showed that if human beings were not subjected to the bombardment of the sounds of modern living, which are especially harsh in cities, they could live years longer. Learn to enjoy silence; don’t listen to the radio or television for hours on end, or have them blaring mindlessly in the background all the time.'), Document(metadata={'chapter_name': 'Attunement With God: Greatest Cure for Nervousness', 'split_id_sequential': 33, 'split_id_uuid': '28716ee9-dae2-46e5-80e6-f53bffa190c1', 'publication_name': 'Journey to Self-Realization', '_id': 'b079c905-181b-42ef-8c5f-849c0ba81f9b', '_collection_name': 'openai_large_chunks_1500char'}, page_content='Attunement With God: Greatest Cure for Nervousness Remember that the greatest healing of nervousness takes place when we attune our lives to God. The highest commandments given to man are to love God with all your heart, and with all your soul, and with all your mind, and with all your strength; and secondly, to love your neighbour as yourself.13 If you follow these, everything will come in its own way, and in the right way. It is not enough just to be a strict moralist—stones and goats do not break moral laws; still, they do not know God. But when you love God deeply enough, even if you are the greatest of sinners, you will be transformed and redeemed. The great saint Mirabai14 said, “To find the Divine One, the only indispensable is love.” That truth touched me deeply. All the prophets observe these two foremost commandments. Loving God with all your heart means to love Him with the love that you feel for the person who is dearest to you—with the love of the mother or father for the child, or the lover for the beloved. Give that kind of unconditional love to God. Loving God with all your soul means you can truly love Him when through deep meditation you know yourself as a soul, a child of God, made in His image. Loving God with all your mind means that when you are praying, your whole attention is on Him, not distracted by restless thoughts. In meditation, think only of God; don’t let the mind wander to everything else but God.')]\", name='vector_search', id='34f93038-5940-4a3b-bfd2-7f595ee69775', tool_call_id='call_fjyQpF0pjUQZ8gobl2SAozXV'),\n",
       " AIMessage(content='To reduce nervousness and improve sleep, it is essential to recognize that much of our nervousness stems from our own reactions and emotional states. Paramhansa Yogananda emphasizes that restlessness and emotional excitement can overload the nervous system, leading to fatigue and anxiety. Engaging in deep meditation can help calm the nerves, as it allows the body to rest and rejuvenate. Additionally, dietary choices play a significant role; consuming calming foods such as whole grains, fruits, and avoiding stimulants like caffeine and alcohol can support a healthier nervous system. Practicing silence and reducing exposure to noise can also alleviate nervousness, creating a more peaceful environment conducive to sleep.\\n\\n**Quotes:**\\n1. \"You always blame other things for making you nervous, but never accuse yourself. Yet it is you who make yourself nervous; ninety-nine percent is your own fault.\" - *Journey to Self-Realization, Probing the Core of Nervousness*\\n2. \"When you stop overloading the nervous system, as when you are in deep sleep or a state of calmness in meditation, you are not nervous at all.\" - *Journey to Self-Realization, Probing the Core of Nervousness*\\n3. \"Learn to enjoy silence; don’t listen to the radio or television for hours on end, or have them blaring mindlessly in the background all the time.\" - *Journey to Self-Realization, Examine Yourself to See What Makes You Nervous*\\n4. \"The greatest healing of nervousness takes place when we attune our lives to God.\" - *Journey to Self-Realization, Attunement With God: Greatest Cure for Nervousness*\\n\\n**Recommended Reading:**\\n- *Journey to Self-Realization* by Paramhansa Yogananda\\n\\n**Follow-up Questions:**\\n1. What specific techniques can I use in meditation to calm my nerves?\\n2. Are there particular foods or drinks that are especially beneficial for reducing nervousness?\\n3. How can I create a more peaceful environment at home to improve my sleep?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 416, 'prompt_tokens': 2347, 'total_tokens': 2763, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'stop', 'logprobs': None}, id='run-0814edcd-020f-4ae0-bab2-b696f9948fec-0', usage_metadata={'input_tokens': 2347, 'output_tokens': 416, 'total_tokens': 2763})]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "chatbot.graph.get_state(chatbot.config)[0]['messages']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7875\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7875/\" 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": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "def respond(query, history):\n",
    "\n",
    "    formatted_query = [HumanMessage(content=query)]\n",
    "    # Invoke the graph with properly formatted input\n",
    "    result = chatbot.graph.invoke({\"messages\": formatted_query}, chatbot.config)\n",
    "    \n",
    "    # Extract the assistant's response\n",
    "    response = result[\"messages\"][-1].content\n",
    "\n",
    "    history.append((query, response))\n",
    "\n",
    "    \n",
    "    return history\n",
    "\n",
    "chatbot = SRFChatbot()\n",
    "\n",
    "# Gradio interface with responsive layout\n",
    "with gr.Blocks(css=\"\"\"\n",
    "    @media (max-width: 600px) {\n",
    "        .gr-row { flex-direction: column !important; }\n",
    "        .gr-column { width: 100% !important; }\n",
    "    }\n",
    "\"\"\") as demo:\n",
    "    gr.Markdown(\"# SRF Chatbot\")\n",
    "    \n",
    "    with gr.Row(elem_classes=\"gr-row\"):\n",
    "        with gr.Column(scale=4, elem_classes=\"gr-column\"):\n",
    "            chatbot_output = gr.Chatbot()\n",
    "            user_input = gr.Textbox(placeholder=\"Type your question here...\")\n",
    "            submit_button = gr.Button(\"Submit\")\n",
    "        \n",
    "        with gr.Column(scale=1, elem_classes=\"gr-column\"):\n",
    "            system_prompt_dropdown = gr.Dropdown(\n",
    "                choices=list(sp.system_prompt_templates.keys()),\n",
    "                label=\"Select Chatbot Instructions\",\n",
    "                value=list(sp.system_prompt_templates.keys())[0]\n",
    "            )\n",
    "            system_prompt_display = gr.Textbox(\n",
    "                value=sp.system_prompt_templates[list(sp.system_prompt_templates.keys())[0]],\n",
    "                label=\"Current Chatbot Instructions\",\n",
    "                lines=5,\n",
    "                interactive=False\n",
    "            )\n",
    "    \n",
    "    # Update system prompt display when a new prompt is selected\n",
    "    system_prompt_dropdown.change(\n",
    "        fn=chatbot.reset_system_prompt,\n",
    "        inputs=[system_prompt_dropdown],\n",
    "        outputs=[system_prompt_display]\n",
    "    )\n",
    "    \n",
    "    # Submit button logic to handle chatbot conversation\n",
    "    submit_button.click(\n",
    "        fn=respond,\n",
    "        inputs=[user_input, chatbot_output],\n",
    "        outputs=[chatbot_output]\n",
    "    )\n",
    "\n",
    "\n",
    "demo.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7883\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7883/\" 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": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "\n",
    "# Define the respond function\n",
    "def respond(query, history):\n",
    "    formatted_query = [HumanMessage(content=query)]\n",
    "    # Invoke the graph with properly formatted input\n",
    "    result = chatbot.graph.invoke({\"messages\": formatted_query}, chatbot.config)\n",
    "    \n",
    "    # Extract the assistant's response\n",
    "    response = result[\"messages\"][-1].content\n",
    "\n",
    "    history.append((query, response))\n",
    "\n",
    "    return history, \"\"\n",
    "\n",
    "# Initialize chatbot\n",
    "chatbot = SRFChatbot()\n",
    "\n",
    "# Gradio interface with black and grey color scheme\n",
    "with gr.Blocks(css=\"\"\"\n",
    "    .gradio-container {\n",
    "        background-color: #F0F0F0; \n",
    "        font-family: 'Arial', sans-serif;\n",
    "    }\n",
    "    h1, h2, p {\n",
    "        color: black;\n",
    "    }\n",
    "    h1 {\n",
    "        font-size: 32px;\n",
    "        text-align: left;\n",
    "    }\n",
    "    h2 {\n",
    "        font-size: 24px;\n",
    "    }\n",
    "    p {\n",
    "        font-size: 18px;\n",
    "        margin-bottom: 15px;\n",
    "    }\n",
    "    .gr-button {\n",
    "        background-color: #333333; \n",
    "        color: white;\n",
    "        font-size: 18px;\n",
    "        padding: 10px;\n",
    "    }\n",
    "    .gr-textbox textarea {\n",
    "        font-size: 18px;\n",
    "        color: black;\n",
    "    }\n",
    "    .gr-dropdown {\n",
    "        font-size: 18px;\n",
    "        color: black;\n",
    "    }\n",
    "    .source-box {\n",
    "        background-color: #D0D0D0; \n",
    "        padding: 10px; \n",
    "        border-radius: 8px; \n",
    "        margin-top: 20px;\n",
    "        color: black;\n",
    "    }\n",
    "    @media (max-width: 600px) {\n",
    "        .gr-row { flex-direction: column !important; }\n",
    "        .gr-column { width: 100% !important; }\n",
    "    }\n",
    "\"\"\") as demo:\n",
    "    \n",
    "    # Title\n",
    "    gr.Markdown(\"# SRF Chatbot\")\n",
    "    \n",
    "    with gr.Row(elem_classes=\"gr-row\"):\n",
    "        with gr.Column(scale=4, elem_classes=\"gr-column\"):\n",
    "            # Chatbot interface\n",
    "            chatbot_output = gr.Chatbot()\n",
    "            user_input = gr.Textbox(placeholder=\"Type your question here...\", label=\"Your Question\")\n",
    "            submit_button = gr.Button(\"Submit\")\n",
    "        \n",
    "        with gr.Column(scale=1, elem_classes=\"gr-column\"):\n",
    "            # Dropdown to select system prompts\n",
    "            system_prompt_dropdown = gr.Dropdown(\n",
    "                choices=list(sp.system_prompt_templates.keys()),\n",
    "                label=\"Select Chatbot Instructions\",\n",
    "                value=list(sp.system_prompt_templates.keys())[0],\n",
    "                elem_classes=\"gr-dropdown\"\n",
    "            )\n",
    "            # Display the selected system prompt\n",
    "            system_prompt_display = gr.Textbox(\n",
    "                value=sp.system_prompt_templates[list(sp.system_prompt_templates.keys())[0]],\n",
    "                label=\"Current Chatbot Instructions\",\n",
    "                lines=5,\n",
    "                interactive=False\n",
    "            )\n",
    "            \n",
    "            # Sources box\n",
    "            gr.Markdown(\"\"\"\n",
    "            <div class=\"source-box\">\n",
    "                <strong>Available sources:</strong>\n",
    "                <ul>\n",
    "                    <li>Journey to Self-Realization</li>\n",
    "                    <li>The Second Coming of Christ</li>\n",
    "                    <li>Autobiography of a Yogi</li>\n",
    "                </ul>\n",
    "            </div>\n",
    "            \"\"\")\n",
    "    \n",
    "    # Update system prompt display when a new prompt is selected\n",
    "    system_prompt_dropdown.change(\n",
    "        fn=chatbot.reset_system_prompt,\n",
    "        inputs=[system_prompt_dropdown],\n",
    "        outputs=[system_prompt_display]\n",
    "    )\n",
    "    \n",
    "    # Submit button logic to handle chatbot conversation\n",
    "    submit_button.click(\n",
    "        fn=respond,\n",
    "        inputs=[user_input, chatbot_output],\n",
    "        outputs=[chatbot_output, user_input]\n",
    "    )\n",
    "\n",
    "# Launch the interface\n",
    "demo.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7885\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7885/\" 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": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "import src.srf_bot as sb\n",
    "import prompts.system_prompts as sp\n",
    "from langchain_core.messages import HumanMessage    \n",
    "\n",
    "# Define the respond function\n",
    "def respond(query, history):\n",
    "    formatted_query = [HumanMessage(content=query)]\n",
    "    # Invoke the graph with properly formatted input\n",
    "    result = chatbot.graph.invoke({\"messages\": formatted_query}, chatbot.config)\n",
    "    \n",
    "    # Extract the assistant's response\n",
    "    response = result[\"messages\"][-1].content\n",
    "\n",
    "    history.append((query, response))\n",
    "\n",
    "    return history, \"\"\n",
    "\n",
    "# Initialize chatbot\n",
    "chatbot = sb.SRFChatbot()\n",
    "\n",
    "# Gradio interface with black and grey color scheme\n",
    "with gr.Blocks(css=\"\"\"\n",
    "    .gradio-container {\n",
    "        background-color: #F0F0F0; \n",
    "        font-family: 'Arial', sans-serif;\n",
    "    }\n",
    "    h1, h2, p {\n",
    "        color: black;\n",
    "    }\n",
    "    h1 {\n",
    "        font-size: 32px;\n",
    "        text-align: left;\n",
    "    }\n",
    "    h2 {\n",
    "        font-size: 24px;\n",
    "    }\n",
    "    p {\n",
    "        font-size: 18px;\n",
    "        margin-bottom: 15px;\n",
    "    }\n",
    "    .gr-button {\n",
    "        background-color: #333333; \n",
    "        color: white;\n",
    "        font-size: 18px;\n",
    "        padding: 10px;\n",
    "    }\n",
    "    .gr-textbox textarea {\n",
    "        font-size: 18px;\n",
    "        color: black;\n",
    "    }\n",
    "    .gr-dropdown {\n",
    "        font-size: 18px;\n",
    "        color: black;\n",
    "    }\n",
    "    .source-box {\n",
    "        background-color: white; \n",
    "        padding: 10px; \n",
    "        border-radius: 8px; \n",
    "        margin-top: 20px;\n",
    "        color: black;\n",
    "        border: 1px solid #D0D0D0;\n",
    "    }\n",
    "    @media (max-width: 600px) {\n",
    "        .gr-row { flex-direction: column !important; }\n",
    "        .gr-column { width: 100% !important; }\n",
    "    }\n",
    "\"\"\") as demo:\n",
    "    \n",
    "    # Title\n",
    "    gr.Markdown(\"# SRF Chatbot\")\n",
    "    \n",
    "    with gr.Row(elem_classes=\"gr-row\"):\n",
    "        with gr.Column(scale=4, elem_classes=\"gr-column\"):\n",
    "            # Chatbot interface\n",
    "            chatbot_output = gr.Chatbot(height=600)  # Increased height for longer chat interface\n",
    "            user_input = gr.Textbox(placeholder=\"Type your question here...\", label=\"Your Question\")\n",
    "            submit_button = gr.Button(\"Submit\")\n",
    "        \n",
    "        with gr.Column(scale=1, elem_classes=\"gr-column\"):\n",
    "            # Dropdown to select system prompts\n",
    "            system_prompt_dropdown = gr.Dropdown(\n",
    "                choices=list(sp.system_prompt_templates.keys()),\n",
    "                label=\"Select Chatbot Instructions\",\n",
    "                value=list(sp.system_prompt_templates.keys())[0],\n",
    "                elem_classes=\"gr-dropdown\"\n",
    "            )\n",
    "            # Display the selected system prompt\n",
    "            system_prompt_display = gr.Textbox(\n",
    "                value=sp.system_prompt_templates[list(sp.system_prompt_templates.keys())[0]],\n",
    "                label=\"Current Chatbot Instructions\",\n",
    "                lines=5,\n",
    "                interactive=False\n",
    "            )\n",
    "            \n",
    "            # Sources box (Now white, matching the other boxes)\n",
    "            gr.Markdown(\"\"\"\n",
    "            <div class=\"source-box\">\n",
    "                <strong>Available sources:</strong>\n",
    "                <ul>\n",
    "                    <li>Journey to Self-Realization</li>\n",
    "                    <li>The Second Coming of Christ</li>\n",
    "                    <li>Autobiography of a Yogi</li>\n",
    "                </ul>\n",
    "            </div>\n",
    "            \"\"\")\n",
    "    \n",
    "    # Update system prompt display when a new prompt is selected\n",
    "    system_prompt_dropdown.change(\n",
    "        fn=chatbot.reset_system_prompt,\n",
    "        inputs=[system_prompt_dropdown],\n",
    "        outputs=[system_prompt_display]\n",
    "    )\n",
    "    \n",
    "    # Submit button logic to handle chatbot conversation\n",
    "    submit_button.click(\n",
    "        fn=respond,\n",
    "        inputs=[user_input, chatbot_output],\n",
    "        outputs=[chatbot_output, user_input]\n",
    "    )\n",
    "\n",
    "# Launch the interface\n",
    "demo.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "srf_chatbot_v2",
   "language": "python",
   "name": "srf_chatbot_v2"
  },
  "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}