File size: 62,223 Bytes
e6c3948
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e9f83b0b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "import json\n",
    "import re\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "from IPython.display import Image, display\n",
    "from langgraph.graph import StateGraph, START, END\n",
    "from langchain_google_genai import ChatGoogleGenerativeAI\n",
    "from langchain_groq import ChatGroq\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_mistralai.chat_models import ChatMistralAI\n",
    "from langchain_cohere import ChatCohere\n",
    "\n",
    "\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_community.document_loaders import WikipediaLoader\n",
    "\n",
    "import networkx as nx\n",
    "from pyvis.network import Network\n",
    "\n",
    "load_dotenv()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "be96faeb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# May add that later (have to ask for user tavily api too)\n",
    "def web_search(query: str) -> str:\n",
    "    \"\"\"\n",
    "    Search Tavily for a query to answer questions about recent events or general knowledge.\n",
    "    \n",
    "    Args:\n",
    "        query: The search query.\n",
    "    \"\"\"\n",
    "    search_tool = TavilySearchResults(max_results=2)\n",
    "    \n",
    "    # The tool now returns a dictionary, and the actual results are in the 'results' key\n",
    "    search_output = search_tool.invoke({\"query\": query})\n",
    "    \n",
    "    formatted_output = \"\\n\\n\".join([doc[\"content\"] for doc in search_output]) \n",
    "    print(search_output)\n",
    "    \n",
    "    # We need to loop through the list of result dictionaries and extract the 'content' from each\n",
    "    return formatted_output\n",
    "\n",
    "def wiki_search(query: str) -> str:\n",
    "    \"\"\"\n",
    "    Search Wikipedia for a query and return maximum 1 results.\n",
    "    \n",
    "    Args:\n",
    "        query: The search query.\n",
    "    \"\"\"\n",
    "    search_docs = WikipediaLoader(query=query, load_max_docs=1).load()\n",
    "    \n",
    "    formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
    "        [\n",
    "            f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content}\\n</Document>'\n",
    "            for doc in search_docs\n",
    "        ])\n",
    "    return formatted_search_docs\n",
    "\n",
    "class AgentState(TypedDict):\n",
    "    \"\"\"\n",
    "    State of our agent. It's a dictionary that will\n",
    "    hold all the information passed between the different nodes of our graph.\n",
    "    \"\"\"\n",
    "    original_input: str  # What the user initially types\n",
    "    text_to_map: str     # The text we'll process (might be the same as original_input or come from Wikipedia)\n",
    "    keywords: list       # Our list of keywords with importance\n",
    "    connections: list    # Our list of (keyword, relation, keyword) triplets\n",
    "    summary: str         # The final summary of the graph\n",
    "    image_path: str      # The image path we generate\n",
    "    chosen_path: str     # The chosen path by llm\n",
    "    \n",
    "\n",
    "\n",
    "class KnowledgeMapperAgent:\n",
    "    def __init__(self, selected_api, api_key, model):\n",
    "        print(f\"class KnowledgeMapperAgent: initialized with API: {selected_api} and Model: {model}\")\n",
    "        \n",
    "        # This block now handles initializing the correct LLM based on user selection\n",
    "        if selected_api == \"Gemini\":\n",
    "            self.llm = ChatGoogleGenerativeAI(model=model, temperature=0, api_key=api_key)\n",
    "        elif selected_api == \"Groq\":\n",
    "            self.llm = ChatGroq(model=model, temperature=0, api_key=api_key)\n",
    "        elif selected_api == \"OpenAI\":\n",
    "            self.llm = ChatOpenAI(model=model, temperature=0, api_key=api_key)\n",
    "        elif selected_api == \"Anthropic\":\n",
    "            self.llm = ChatAnthropic(model=model, temperature=0, api_key=api_key)\n",
    "        elif selected_api == \"Mistral\":\n",
    "            self.llm = ChatMistralAI(model=model, temperature=0, api_key=api_key)\n",
    "        elif selected_api == \"Cohere\":\n",
    "            self.llm = ChatCohere(model=model, temperature=0, api_key=api_key)\n",
    "        else:\n",
    "            self.llm = ChatGoogleGenerativeAI(model=\"gemini-2.0-flash\", temperature=0)\n",
    "            \n",
    "        # 1. Initialize our agent (start the graph w/ AgentState)\n",
    "        workflow = StateGraph(AgentState)\n",
    "        \n",
    "        # 2. Add the tools\n",
    "        workflow.add_node(\"decide_path_node\", self._decide_path_node)\n",
    "        workflow.add_node(\"fetch_from_wiki\", self._fetch_from_wiki)\n",
    "        workflow.add_node(\"perform_web_search\", self._perform_web_search)\n",
    "\n",
    "        workflow.add_node(\"extract_keywords\", self.extract_keywords)\n",
    "        workflow.add_node(\"connect_keywords\", self.connect_keywords)\n",
    "        workflow.add_node(\"summarize_map\", self.summarize_map)\n",
    "        \n",
    "        workflow.add_node(\"generate_graph_image\", self.generate_graph_image)\n",
    "\n",
    "        \n",
    "        # 3. Set the entry point to router\n",
    "        workflow.set_entry_point(\"decide_path_node\")\n",
    "\n",
    "        # 4. Add the CONDITIONAL edge\n",
    "        workflow.add_conditional_edges(\n",
    "            \"decide_path_node\",     # Start from router node\n",
    "            self._route_next_step,  # Choose the function we will call\n",
    "            {\n",
    "                # This dictionary maps the return value to the name of the next node\n",
    "                \"fetch_from_wiki\": \"fetch_from_wiki\",\n",
    "                \"perform_web_search\": \"perform_web_search\",\n",
    "                \"extract_keywords\": \"extract_keywords\"\n",
    "            }\n",
    "        )\n",
    "\n",
    "        # 5. Add the regular edges for the rest of the flow\n",
    "        workflow.add_edge(\"fetch_from_wiki\", \"extract_keywords\")        # After wiki, go to extract\n",
    "        workflow.add_edge(\"perform_web_search\", \"extract_keywords\")     # After wiki, go to extract\n",
    "\n",
    "        workflow.add_edge(\"extract_keywords\", \"connect_keywords\")       # After extracting, connect them\n",
    "        workflow.add_edge(\"connect_keywords\", \"generate_graph_image\")   # We generate graph image\n",
    "        workflow.add_edge(\"generate_graph_image\", \"summarize_map\")      # Finally, generate the summary\n",
    "        workflow.add_edge(\"summarize_map\", END)                         # and end the graph\n",
    "\n",
    "        # 6. Compile the graph\n",
    "        self.graph = workflow.compile()\n",
    "        \n",
    "\n",
    "\n",
    "    # Initial agent call\n",
    "    def __call__(self, text: str):\n",
    "        # 1. Define initial state\n",
    "        initial_state = {\n",
    "            \"original_input\": text,\n",
    "            \"text_to_map\": \"\",\n",
    "            \"keywords\": [],\n",
    "            \"connections\": [],\n",
    "            \"summary\":\"\",\n",
    "            \"chosen_path\": \"\"\n",
    "        }\n",
    "        \n",
    "        # 2. Run our agent workflow from START to END\n",
    "        final_state = self.graph.invoke(initial_state)\n",
    "        \n",
    "        # 3. Agent return the generated html file name\n",
    "        return final_state\n",
    "\n",
    "    def _decide_path_node(self, state: AgentState) -> dict: \n",
    "        print(\"---NODE: LLM DECIDING PATH---\")\n",
    "        user_input = state[\"original_input\"]\n",
    "        print(f\"Decide Path Input (first 50 chars): '{user_input[:50]}...'\") \n",
    "\n",
    "        router_prompt = f\"\"\"\n",
    "You are an intelligent routing agent. Based on the user's request, you must choose the next tool to use.\n",
    "The user's request is: \"{user_input}\"\n",
    "\n",
    "You have the following tools available:\n",
    "- \"wikipedia_search\": Choose this if the user is asking a question or wants to find information on a topic (e.g., \"What is deep learning?\"). Use for general encyclopedia-like knowledge.\n",
    "- \"web_search\": Choose this if the user is asking a question about current events, specific facts, or requires broader, more up-to-date internet information.\n",
    "- \"mindmap_generator\": Choose this if the user has provided a full block of text that is already self-contained and ready to be turned into a mind map.\n",
    "\n",
    "Your response MUST be only one of these single words: \"wikipedia_search\", \"web_search\", or \"mindmap_generator\".\n",
    "        \"\"\"\n",
    "\n",
    "        llm_choice_response = self.llm.invoke(router_prompt)\n",
    "        \n",
    "        raw_llm_response_content = llm_choice_response.content\n",
    "        print(f\"LLM Raw Router Response: '{raw_llm_response_content}'\")\n",
    "        \n",
    "        llm_choice = raw_llm_response_content.strip().lower()\n",
    "        print(f\"LLM Processed Router Choice: '{llm_choice}' (length: {len(llm_choice)})\")\n",
    "        \n",
    "        updates = {}\n",
    "        if \"wikipedia_search\" == llm_choice:\n",
    "            updates[\"chosen_path\"] = \"fetch_from_wiki\"\n",
    "            print(\"Decision: 'wikipedia_search'. Setting chosen_path to 'fetch_from_wiki'.\")\n",
    "        elif \"web_search\" == llm_choice: # <-- NEW CONDITIONAL ROUTE\n",
    "            updates[\"chosen_path\"] = \"perform_web_search\"\n",
    "            print(\"Decision: 'web_search'. Setting chosen_path to 'perform_web_search'.\")\n",
    "        elif \"mindmap_generator\" == llm_choice:\n",
    "            updates[\"chosen_path\"] = \"extract_keywords\"\n",
    "            updates[\"text_to_map\"] = user_input \n",
    "            print(\"Decision: 'mindmap_generator'. Setting chosen_path to 'extract_keywords' and text_to_map.\")\n",
    "            print(f\"text_to_map set to (first 50 chars): '{updates['text_to_map'][:50]}...'\")\n",
    "        else:\n",
    "            print(f\"WARNING: LLM returned unexpected choice: '{llm_choice}'. Defaulting to mindmap_generator.\")\n",
    "            updates[\"chosen_path\"] = \"extract_keywords\" \n",
    "            updates[\"text_to_map\"] = user_input \n",
    "            print(f\"text_to_map set to (first 50 chars): '{updates['text_to_map'][:50]}...'\")\n",
    "\n",
    "        return updates \n",
    "\n",
    "\n",
    "    def _route_next_step(self, state: AgentState) -> str:\n",
    "        \"\"\"\n",
    "        Routes the graph based on the 'chosen_path' set by _decide_path_node.\n",
    "        This function *only* returns a string for conditional routing.\n",
    "        \"\"\"\n",
    "        print(f\"---ROUTING: Based on chosen_path '{state.get('chosen_path', 'N/A')}'---\")\n",
    "        # Ensure chosen_path is present in state; default to 'extract_keywords' if not.\n",
    "        return state.get(\"chosen_path\", \"extract_keywords\")\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "    def _fetch_from_wiki(self, state: AgentState) -> dict:\n",
    "        \"\"\"\n",
    "        This is a WORKER node. It uses a tool to get data.\n",
    "        \"\"\"\n",
    "        print(\"---NODE: FETCHING FROM WIKIPEDIA---\")\n",
    "        question = state[\"original_input\"]\n",
    "        \n",
    "        fetched_text = wiki_search(question)\n",
    "        \n",
    "        return {\"text_to_map\": fetched_text}\n",
    "\n",
    "    def _perform_web_search(self, state: AgentState) -> dict:\n",
    "        print(\"---NODE: PERFORMING WEB SEARCH---\")\n",
    "        query = state[\"original_input\"]\n",
    "        \n",
    "        fetched_text = web_search(query) # Call the actual web_search function\n",
    "\n",
    "        return {\"text_to_map\": fetched_text}\n",
    "\n",
    "    def extract_keywords(self, state: AgentState) -> str:\n",
    "        \"\"\"\n",
    "        Uses an LLM to extract the keywords.\n",
    "        \"\"\"\n",
    "        print(\"---NODE: LLM EXTRACTION ---\")\n",
    "        text_to_process = state[\"text_to_map\"]\n",
    "\n",
    "        # 1. This is the prompt for the .\n",
    "        extraction_prompt = f\"\"\"\n",
    "You are an expert at analyzing text and extracting key concepts.\n",
    "From the following text, please extract the main concepts and rate their importance on a scale from 1 to 10.\n",
    "\n",
    "Text to analyze:\n",
    "\\\"{text_to_process}\\\"\n",
    "\n",
    "Your response MUST be only a valid JSON array of objects, where each object has a \"concept\" key and an \"importance\" key. Do not include any other text or explanation. For example:\n",
    "Text to analyze:\n",
    "\\\"Machine learning (ML) is a type of artificial intelligence that allows computers to learn from data without being explicitly programmed. It involves using algorithms to analyze large datasets, identify patterns, and make predictions or decisions based on those patterns. The more data an ML model is trained on, the better it becomes at performing its task.\\\"\n",
    "\n",
    "Output:\n",
    "[\n",
    "  {{\n",
    "    \"concept\": \"Machine learning (ML)\",\n",
    "    \"importance\": 10\n",
    "  }},\n",
    "  {{\n",
    "    \"concept\": \"Artificial intelligence\",\n",
    "    \"importance\": 9\n",
    "  }},\n",
    "  {{\n",
    "    \"concept\": \"Algorithms\",\n",
    "    \"importance\": 8\n",
    "  }},\n",
    "  {{\n",
    "    \"concept\": \"Data analysis\",\n",
    "    \"importance\": 8\n",
    "  }},\n",
    "  {{\n",
    "    \"concept\": \"Pattern recognition\",\n",
    "    \"importance\": 7\n",
    "  }},\n",
    "  {{\n",
    "    \"concept\": \"Predictions/Decisions\",\n",
    "    \"importance\": 7\n",
    "  }},\n",
    "]\n",
    "\"\"\"\n",
    "\n",
    "        # 2. Call the LLM with the extraction prompt\n",
    "        llm_extraction_response = self.llm.invoke(extraction_prompt)\n",
    "        raw_llm_content = llm_extraction_response.content\n",
    "\n",
    "        print(f\"Raw LLM response: \\n'{raw_llm_content}'\")\n",
    "\n",
    "        llm_extraction = [] # Initialize as an empty list for safety\n",
    "\n",
    "        try:\n",
    "            # Use regex to find content between ```json and ```\n",
    "            # This pattern is more robust as it handles potential leading/trailing whitespace\n",
    "            match = re.search(r'```json\\s*(.*?)\\s*```', raw_llm_content, re.DOTALL)\n",
    "            \n",
    "            if match:\n",
    "                json_string = match.group(1)\n",
    "                print(f\"Extracted JSON string: \\n'{json_string}'\")\n",
    "                llm_extraction = json.loads(json_string)\n",
    "            else:\n",
    "                # If no markdown block is found, try parsing the raw content directly\n",
    "                print(\"No JSON markdown block found. Attempting to parse raw content directly.\")\n",
    "                llm_extraction = json.loads(raw_llm_content)\n",
    "\n",
    "        except json.JSONDecodeError as e:\n",
    "            print(f\"Error decoding JSON from LLM: {e}\")\n",
    "            print(f\"Problematic content (after extraction attempt): '{raw_llm_content}'\")\n",
    "        except Exception as e:\n",
    "            print(f\"An unexpected error occurred: {e}\")\n",
    "            print(f\"Problematic content (after extraction attempt): '{raw_llm_content}'\")\n",
    "\n",
    "        return {\"keywords\": llm_extraction}\n",
    "    \n",
    "    def connect_keywords(self, state: AgentState) -> dict:\n",
    "        \"\"\"\n",
    "        Uses an LLM to identify relationships between the extracted keywords.\n",
    "        \"\"\"\n",
    "        print(\"---NODE: LLM CONNECTING KEYWORDS ---\")\n",
    "        keywords_list = state[\"keywords\"]\n",
    "        text_to_map = state[\"text_to_map\"]\n",
    "\n",
    "        if not keywords_list:\n",
    "            print(\"No keywords found to connect. Returning empty connections.\")\n",
    "            return {\"connections\": []}\n",
    "\n",
    "        # Format keywords for the prompt, so the LLM knows what to connect\n",
    "        # You can choose to pass the original concept list or just the names\n",
    "        # For simplicity, let's just pass the concept names\n",
    "        concept_names = [k[\"concept\"] for k in keywords_list if \"concept\" in k]\n",
    "        formatted_concepts = \"\\n- \" + \"\\n- \".join(concept_names) if concept_names else \"No concepts provided.\"\n",
    "\n",
    "\n",
    "        connection_prompt = f\"\"\"\n",
    "You are an expert at identifying semantic relationships between concepts in a text.\n",
    "Given the following original text and a list of key concepts extracted from it:\n",
    "\n",
    "Original Text:\n",
    "\\\"{text_to_map}\\\"\n",
    "\n",
    "Key Concepts:\n",
    "{formatted_concepts}\n",
    "\n",
    "Identify all meaningful relationships between these key concepts based *only* on the provided Original Text.\n",
    "For each relationship, provide a \"source\" concept, a \"relation\" (a concise description of the relationship, e.g., \"is a type of\", \"uses\", \"enables\", \"is part of\"), and a \"target\" concept.\n",
    "\n",
    "Your response MUST be only a valid JSON array of objects, where each object has a \"source\" key (string), a \"relation\" key (string), and a \"target\" key (string). Do not include any other text or explanation.\n",
    "\n",
    "For example:\n",
    "[\n",
    "  {{\"source\": \"Machine learning\", \"relation\": \"is a type of\", \"target\": \"Artificial Intelligence\"}},\n",
    "  {{\"source\": \"ML model\", \"relation\": \"is trained on\", \"target\": \"Large datasets\"}},\n",
    "  {{\"source\": \"Data analysis\", \"relation\": \"identifies\", \"target\": \"Patterns\"}}\n",
    "]\n",
    "\"\"\"\n",
    "\n",
    "        # 2. Call the LLM with the connection prompt\n",
    "        llm_connections_response = self.llm.invoke(connection_prompt)\n",
    "        raw_llm_content = llm_connections_response.content\n",
    "\n",
    "        print(f\"Raw LLM response (connections): \\n'{raw_llm_content}'\")\n",
    "\n",
    "        connections = [] # Initialize as an empty list for safety\n",
    "\n",
    "        try:\n",
    "            # Use regex to find content between ```json and ```\n",
    "            match = re.search(r'```json\\s*(.*?)\\s*```', raw_llm_content, re.DOTALL)\n",
    "\n",
    "            if match:\n",
    "                json_string = match.group(1)\n",
    "                print(f\"Extracted JSON string (connections): \\n'{json_string}'\")\n",
    "                connections = json.loads(json_string)\n",
    "            else:\n",
    "                # If no markdown block is found, try parsing the raw content directly\n",
    "                print(\"No JSON markdown block found for connections. Attempting to parse raw content directly.\")\n",
    "                connections = json.loads(raw_llm_content)\n",
    "\n",
    "        except json.JSONDecodeError as e:\n",
    "            print(f\"Error decoding JSON from LLM (connections): {e}\")\n",
    "            print(f\"Problematic content (connections): '{raw_llm_content}'\")\n",
    "        except Exception as e:\n",
    "            print(f\"An unexpected error occurred (connections): {e}\")\n",
    "            print(f\"Problematic content (connections): '{raw_llm_content}'\")\n",
    "\n",
    "        return {\"connections\": connections}\n",
    "    \n",
    "    def summarize_map(self, state: AgentState) -> dict:\n",
    "        print(\"---NODE: SUMMARIZING MAP---\")\n",
    "        keywords = state[\"keywords\"]\n",
    "        connections = state[\"connections\"]\n",
    "        original_text = state[\"original_input\"] \n",
    "\n",
    "        if not keywords and not connections:\n",
    "            print(\"No graph data to summarize. Returning empty summary.\")\n",
    "            return {\"summary\": \"No conceptual map data was generated.\"}\n",
    "\n",
    "        formatted_keywords = \"\\n\".join([f\"- {k['concept']} (Importance: {k['importance']})\" for k in keywords])\n",
    "        formatted_connections = \"\\n\".join([f\"- {c['source']} {c['relation']} {c['target']}\" for c in connections])\n",
    "\n",
    "        summary_prompt = f\"\"\"\n",
    "You are an expert at explaining complex information.\n",
    "Based on the following original text, extracted key concepts, and their relationships, provide a concise summary that explains the core topic and how these concepts are interconnected.\n",
    "\n",
    "Original Text (for context):\n",
    "\\\"{original_text}\\\"\n",
    "\n",
    "Key Concepts:\n",
    "{formatted_keywords}\n",
    "\n",
    "Identified Relationships:\n",
    "{formatted_connections}\n",
    "\n",
    "Focus on explaining the conceptual map. Start with the main topic and then describe the key concepts and their relationships, in a coherent paragraph.\n",
    "\"\"\"\n",
    "\n",
    "        summary_response = self.llm.invoke(summary_prompt)\n",
    "        \n",
    "        print(f\"Generated Summary: \\n'{summary_response.content}'\")\n",
    "\n",
    "        return {\"summary\": summary_response.content}        \n",
    "\n",
    "\n",
    "\n",
    "    def generate_graph_image(self, state: AgentState) -> dict:\n",
    "        \"\"\"\n",
    "        Generates an interactive and visually appealing conceptual map using pyvis.\n",
    "        The output is an HTML string that can be rendered directly in Gradio.\n",
    "        \n",
    "        This function now returns the full HTML content in the 'image_path' key.\n",
    "        \"\"\"\n",
    "        print(\"---NODE: GENERATING INTERACTIVE GRAPH (pyvis) ---\")\n",
    "        keywords = state[\"keywords\"]\n",
    "        connections = state[\"connections\"]\n",
    "        output_filename = \"concept_map.html\" # Temporary file to generate HTML\n",
    "\n",
    "        if not keywords and not connections:\n",
    "            print(\"No keywords or connections to generate a graph. Skipping image generation.\")\n",
    "            # Return an empty HTML paragraph for Gradio to display\n",
    "            return {\"image_path\": \"<p>No graph data could be generated from the text.</p>\"}\n",
    "\n",
    "        # 1. Create a NetworkX graph to hold the data structure (same as before)\n",
    "        G = nx.DiGraph()\n",
    "\n",
    "        # Add nodes with attributes that pyvis can use, like 'size' and 'title' (for hover text)\n",
    "        for keyword in keywords:\n",
    "            concept = keyword.get(\"concept\")\n",
    "            importance = keyword.get(\"importance\", 5)\n",
    "            if concept:\n",
    "                G.add_node(\n",
    "                    concept,\n",
    "                    size=15 + (importance * 2), # Calculate node size based on importance\n",
    "                    title=f\"Importance: {importance}\", # This creates a tooltip on hover\n",
    "                    importance_val=importance # Store for coloring later\n",
    "                )\n",
    "\n",
    "        # Add edges with labels (same as before)\n",
    "        for conn in connections:\n",
    "            source = conn.get(\"source\")\n",
    "            target = conn.get(\"target\")\n",
    "            relation = conn.get(\"relation\", \"\")\n",
    "            if source in G and target in G:\n",
    "                G.add_edge(source, target, label=relation)\n",
    "\n",
    "        # 2. Initialize a pyvis Network for visualization\n",
    "        # Set a specific height, a dark background, and white font for a modern look.\n",
    "        net = Network(height=\"750px\", width=\"100%\", bgcolor=\"#222222\", font_color=\"white\", directed=True)\n",
    "\n",
    "        # 3. Transfer the graph structure from NetworkX to pyvis\n",
    "        net.from_nx(G)\n",
    "\n",
    "        # 4. Apply custom styling to nodes after they've been added to the pyvis net\n",
    "        for node in net.nodes:\n",
    "            importance = node.get(\"importance_val\", 5)\n",
    "            if importance >= 9:\n",
    "                node[\"color\"] = \"#ff4757\"  # Red for highest importance\n",
    "            elif importance >= 7:\n",
    "                node[\"color\"] = \"#ffa502\"  # Orange for high importance\n",
    "            elif importance >= 5:\n",
    "                node[\"color\"] = \"#2ed573\"  # Green for medium importance\n",
    "            else:\n",
    "                node[\"color\"] = \"#1e90ff\"  # Blue for lower importance\n",
    "\n",
    "        # 5. Add physics layout options for a more dynamic and readable graph\n",
    "        # These settings prevent nodes from overlapping and create a nice \"springy\" effect.\n",
    "        net.set_options(\"\"\"\n",
    "        var options = {\n",
    "        \"physics\": {\n",
    "            \"repulsion\": {\n",
    "            \"centralGravity\": 0.2,\n",
    "            \"springLength\": 100,\n",
    "            \"springConstant\": 0.05,\n",
    "            \"nodeDistance\": 150,\n",
    "            \"damping\": 0.09\n",
    "            },\n",
    "            \"maxVelocity\": 50,\n",
    "            \"minVelocity\": 0.1,\n",
    "            \"solver\": \"repulsion\"\n",
    "        }\n",
    "        }\n",
    "        \"\"\")\n",
    "\n",
    "        # 6. Generate the HTML and return its content as a string\n",
    "        try:\n",
    "            # save_graph writes the complete HTML structure to a file\n",
    "            net.save_graph(output_filename)\n",
    "            \n",
    "            # Read the content of the generated file\n",
    "            with open(output_filename, 'r', encoding='utf-8') as f:\n",
    "                html_content = f.read()\n",
    "                \n",
    "            print(f\"Interactive conceptual map HTML generated successfully.\")\n",
    "            # The Gradio gr.HTML component can directly render this string\n",
    "            return {\"image_path\": html_content}\n",
    "            \n",
    "        except Exception as e:\n",
    "            print(f\"Error generating graph image with pyvis: {e}\")\n",
    "            return {\"image_path\": f\"<p>An error occurred while generating the graph: {e}</p>\"}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a3b535f4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "class KnowledgeMapperAgent: initialized with API: 1 and Model: 3\n"
     ]
    }
   ],
   "source": [
    "agent = KnowledgeMapperAgent(1, 2, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f465073a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---NODE: LLM DECIDING PATH---\n",
      "Decide Path Input (first 50 chars): 'search for the most impactful event at 2025...'\n",
      "LLM Raw Router Response: 'web_search'\n",
      "LLM Processed Router Choice: 'web_search' (length: 10)\n",
      "Decision: 'web_search'. Setting chosen_path to 'perform_web_search'.\n",
      "---ROUTING: Based on chosen_path 'perform_web_search'---\n",
      "---NODE: PERFORMING WEB SEARCH---\n",
      "[{'title': '15 Events to Watch in 2025 | Opus Agency', 'url': 'https://www.opusagency.com/article/15-events-to-watch-in-2025', 'content': 'For a truly exclusive experience, consider [WSJ Tech Live](https://techlive.wsj.com/) in Laguna Beach. Slated for October 2025, this invite-only event brings together a select group of tech visionaries, disruptors, and industry leaders to discuss the impact of technology on business regulation and innovation. And they don’t just talk about it; they offer amazing offsite excursions like golfing, kayaking, and even a beach book camp, creating a more relaxed and informal networking and [...] ### **Money 20/20 — Las Vegas, October 26-29, 2025**\\n\\nNext, we’re headed to the glitz and glamor of Las Vegas for Money 20/20, “where money does business.” This premier event is the world’s biggest and most influential gathering of the global money ecosystem, including banks, payments, tech, startups, retail, fintech, financial services, policy, and more. [...] 1.   **Blurred Lines:**Many events emphasize experience design across various sectors and formats, merging business discussions with highly creative, entertainment-driven formats.\\n2.   **Tech-Driven, Human-Centered**: Many events focus on the impact of technology on society, tackling topics such as AI, metaverse, and tech-driven social transformation. There is a clear emphasis on new tech applications and the ethical, human-centered implications of these advancements.', 'score': 0.7077487}, {'title': 'Biggest Events of 2025 so Far IMO (US POV) : r/decadeology - Reddit', 'url': 'https://www.reddit.com/r/decadeology/comments/1jvj9ks/biggest_events_of_2025_so_far_imo_us_pov/', 'content': 'Myanmar Earthquake, thousands of people dead, during a civil war where there are still air strikes during time of crisis.\\n\\nTrump administration fired the US aid workers while they were over there assessing how to help with earthquake relief.\\n\\n9\\n\\nNew to Reddit?Create your account and connect with a world of communities.\\n\\nContinue with GoogleContinue with Google\\n\\nContinue with Email\\n\\nContinue With Phone Number [...] It’s crazy how that event is basically forgotten about\\n\\n34\\n\\n 1 reply\\n\\n1 reply[Continue this thread](https://www.reddit.com/r/decadeology/comments/1jvj9ks/comment/mmaqh4q/)\\n\\n[](https://www.reddit.com/user/statebirdsnest/)\\n\\n[statebirdsnest](https://www.reddit.com/user/statebirdsnest/)\\n\\n• [1mo ago](https://www.reddit.com/r/decadeology/comments/1jvj9ks/comment/mmas4k3/)\\n\\nThe DC plane crash and Philadelphia plane crash.\\n\\nSignal Chat Leak\\n\\nDOGE and Treasury overtake (+other federal agencies)\\n\\n43 [...] *   [Amazing](https://reddit.com/t/amazing/)*   [Animals & Pets](https://reddit.com/t/animals_and_pets/)*   [Cringe & Facepalm](https://reddit.com/t/cringe_and_facepalm/)*   [Funny](https://reddit.com/t/funny/)*   [Interesting](https://reddit.com/t/interesting/)*   [Memes](https://reddit.com/t/memes/)*   [Oddly Satisfying](https://reddit.com/t/oddly_satisfying/)*   [Reddit Meta](https://reddit.com/t/reddit_meta/)*   [Wholesome & Heartwarming](https://reddit.com/t/wholesome_and_heartwarming/)', 'score': 0.6222074}]\n",
      "---NODE: LLM EXTRACTION ---\n",
      "Raw LLM response: \n",
      "'```json\n",
      "[\n",
      "  {\n",
      "    \"concept\": \"WSJ Tech Live\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Money 20/20\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Technology Impact on Business\",\n",
      "    \"importance\": 9\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Fintech\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Networking\",\n",
      "    \"importance\": 6\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Experience Design\",\n",
      "    \"importance\": 6\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"AI\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Metaverse\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Ethical Implications of Technology\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Myanmar Earthquake\",\n",
      "    \"importance\": 9\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Civil War\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"US Aid Workers Fired\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Plane Crashes\",\n",
      "    \"importance\": 6\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Signal Chat Leak\",\n",
      "    \"importance\": 5\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"DOGE and Treasury\",\n",
      "    \"importance\": 5\n",
      "  }\n",
      "]\n",
      "```'\n",
      "Extracted JSON string: \n",
      "'[\n",
      "  {\n",
      "    \"concept\": \"WSJ Tech Live\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Money 20/20\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Technology Impact on Business\",\n",
      "    \"importance\": 9\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Fintech\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Networking\",\n",
      "    \"importance\": 6\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Experience Design\",\n",
      "    \"importance\": 6\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"AI\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Metaverse\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Ethical Implications of Technology\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Myanmar Earthquake\",\n",
      "    \"importance\": 9\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Civil War\",\n",
      "    \"importance\": 8\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"US Aid Workers Fired\",\n",
      "    \"importance\": 7\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Plane Crashes\",\n",
      "    \"importance\": 6\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"Signal Chat Leak\",\n",
      "    \"importance\": 5\n",
      "  },\n",
      "  {\n",
      "    \"concept\": \"DOGE and Treasury\",\n",
      "    \"importance\": 5\n",
      "  }\n",
      "]'\n",
      "---NODE: LLM CONNECTING KEYWORDS ---\n",
      "Raw LLM response (connections): \n",
      "'```json\n",
      "[\n",
      "  {\"source\": \"WSJ Tech Live\", \"relation\": \"discusses\", \"target\": \"Technology Impact on Business\"},\n",
      "  {\"source\": \"WSJ Tech Live\", \"relation\": \"facilitates\", \"target\": \"Networking\"},\n",
      "  {\"source\": \"Money 20/20\", \"relation\": \"is related to\", \"target\": \"Fintech\"},\n",
      "  {\"source\": \"Money 20/20\", \"relation\": \"includes\", \"target\": \"Financial Services\"},\n",
      "  {\"source\": \"Experience Design\", \"relation\": \"is emphasized at\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"AI\", \"relation\": \"is a topic of\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"Metaverse\", \"relation\": \"is a topic of\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"Ethical Implications of Technology\", \"relation\": \"is a focus of\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"Myanmar Earthquake\", \"relation\": \"occurred during\", \"target\": \"Civil War\"},\n",
      "  {\"source\": \"US Aid Workers Fired\", \"relation\": \"happened during\", \"target\": \"Myanmar Earthquake\"}\n",
      "]\n",
      "```'\n",
      "Extracted JSON string (connections): \n",
      "'[\n",
      "  {\"source\": \"WSJ Tech Live\", \"relation\": \"discusses\", \"target\": \"Technology Impact on Business\"},\n",
      "  {\"source\": \"WSJ Tech Live\", \"relation\": \"facilitates\", \"target\": \"Networking\"},\n",
      "  {\"source\": \"Money 20/20\", \"relation\": \"is related to\", \"target\": \"Fintech\"},\n",
      "  {\"source\": \"Money 20/20\", \"relation\": \"includes\", \"target\": \"Financial Services\"},\n",
      "  {\"source\": \"Experience Design\", \"relation\": \"is emphasized at\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"AI\", \"relation\": \"is a topic of\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"Metaverse\", \"relation\": \"is a topic of\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"Ethical Implications of Technology\", \"relation\": \"is a focus of\", \"target\": \"Many events\"},\n",
      "  {\"source\": \"Myanmar Earthquake\", \"relation\": \"occurred during\", \"target\": \"Civil War\"},\n",
      "  {\"source\": \"US Aid Workers Fired\", \"relation\": \"happened during\", \"target\": \"Myanmar Earthquake\"}\n",
      "]'\n",
      "---NODE: GENERATING INTERACTIVE GRAPH (pyvis) ---\n",
      "Interactive conceptual map HTML generated successfully.\n",
      "---NODE: SUMMARIZING MAP---\n",
      "Generated Summary: \n",
      "'The search focuses on identifying the most impactful event of 2025. This involves considering both technology-focused conferences and significant world events. On the technology side, events like WSJ Tech Live, which emphasizes the impact of technology on business and facilitates networking, and Money 20/20, centered around Fintech, are key contenders. These events often feature discussions on emerging technologies like AI and the Metaverse, as well as the ethical implications of technology and experience design. However, the search also considers impactful real-world events, such as the Myanmar Earthquake, which occurred during a Civil War and was further complicated by the firing of US Aid Workers. The goal is to weigh the impact of these technological and geopolitical events to determine which had the most significant consequences in 2025.'\n"
     ]
    }
   ],
   "source": [
    "html = agent(\"search for the most impactful event at 2025\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "00c4e8e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'original_input': 'search for the most impactful event at 2025', 'text_to_map': 'For a truly exclusive experience, consider [WSJ Tech Live](https://techlive.wsj.com/) in Laguna Beach. Slated for October 2025, this invite-only event brings together a select group of tech visionaries, disruptors, and industry leaders to discuss the impact of technology on business regulation and innovation. And they don’t just talk about it; they offer amazing offsite excursions like golfing, kayaking, and even a beach book camp, creating a more relaxed and informal networking and [...] ### **Money 20/20 — Las Vegas, October 26-29, 2025**\\n\\nNext, we’re headed to the glitz and glamor of Las Vegas for Money 20/20, “where money does business.” This premier event is the world’s biggest and most influential gathering of the global money ecosystem, including banks, payments, tech, startups, retail, fintech, financial services, policy, and more. [...] 1.   **Blurred Lines:**Many events emphasize experience design across various sectors and formats, merging business discussions with highly creative, entertainment-driven formats.\\n2.   **Tech-Driven, Human-Centered**: Many events focus on the impact of technology on society, tackling topics such as AI, metaverse, and tech-driven social transformation. There is a clear emphasis on new tech applications and the ethical, human-centered implications of these advancements.\\n\\nMyanmar Earthquake, thousands of people dead, during a civil war where there are still air strikes during time of crisis.\\n\\nTrump administration fired the US aid workers while they were over there assessing how to help with earthquake relief.\\n\\n9\\n\\nNew to Reddit?Create your account and connect with a world of communities.\\n\\nContinue with GoogleContinue with Google\\n\\nContinue with Email\\n\\nContinue With Phone Number [...] It’s crazy how that event is basically forgotten about\\n\\n34\\n\\n 1 reply\\n\\n1 reply[Continue this thread](https://www.reddit.com/r/decadeology/comments/1jvj9ks/comment/mmaqh4q/)\\n\\n[](https://www.reddit.com/user/statebirdsnest/)\\n\\n[statebirdsnest](https://www.reddit.com/user/statebirdsnest/)\\n\\n• [1mo ago](https://www.reddit.com/r/decadeology/comments/1jvj9ks/comment/mmas4k3/)\\n\\nThe DC plane crash and Philadelphia plane crash.\\n\\nSignal Chat Leak\\n\\nDOGE and Treasury overtake (+other federal agencies)\\n\\n43 [...] *   [Amazing](https://reddit.com/t/amazing/)*   [Animals & Pets](https://reddit.com/t/animals_and_pets/)*   [Cringe & Facepalm](https://reddit.com/t/cringe_and_facepalm/)*   [Funny](https://reddit.com/t/funny/)*   [Interesting](https://reddit.com/t/interesting/)*   [Memes](https://reddit.com/t/memes/)*   [Oddly Satisfying](https://reddit.com/t/oddly_satisfying/)*   [Reddit Meta](https://reddit.com/t/reddit_meta/)*   [Wholesome & Heartwarming](https://reddit.com/t/wholesome_and_heartwarming/)', 'keywords': [{'concept': 'WSJ Tech Live', 'importance': 7}, {'concept': 'Money 20/20', 'importance': 8}, {'concept': 'Technology Impact on Business', 'importance': 9}, {'concept': 'Fintech', 'importance': 7}, {'concept': 'Networking', 'importance': 6}, {'concept': 'Experience Design', 'importance': 6}, {'concept': 'AI', 'importance': 8}, {'concept': 'Metaverse', 'importance': 7}, {'concept': 'Ethical Implications of Technology', 'importance': 8}, {'concept': 'Myanmar Earthquake', 'importance': 9}, {'concept': 'Civil War', 'importance': 8}, {'concept': 'US Aid Workers Fired', 'importance': 7}, {'concept': 'Plane Crashes', 'importance': 6}, {'concept': 'Signal Chat Leak', 'importance': 5}, {'concept': 'DOGE and Treasury', 'importance': 5}], 'connections': [{'source': 'WSJ Tech Live', 'relation': 'discusses', 'target': 'Technology Impact on Business'}, {'source': 'WSJ Tech Live', 'relation': 'facilitates', 'target': 'Networking'}, {'source': 'Money 20/20', 'relation': 'is related to', 'target': 'Fintech'}, {'source': 'Money 20/20', 'relation': 'includes', 'target': 'Financial Services'}, {'source': 'Experience Design', 'relation': 'is emphasized at', 'target': 'Many events'}, {'source': 'AI', 'relation': 'is a topic of', 'target': 'Many events'}, {'source': 'Metaverse', 'relation': 'is a topic of', 'target': 'Many events'}, {'source': 'Ethical Implications of Technology', 'relation': 'is a focus of', 'target': 'Many events'}, {'source': 'Myanmar Earthquake', 'relation': 'occurred during', 'target': 'Civil War'}, {'source': 'US Aid Workers Fired', 'relation': 'happened during', 'target': 'Myanmar Earthquake'}], 'summary': 'The search focuses on identifying the most impactful event of 2025. This involves considering both technology-focused conferences and significant world events. On the technology side, events like WSJ Tech Live, which emphasizes the impact of technology on business and facilitates networking, and Money 20/20, centered around Fintech, are key contenders. These events often feature discussions on emerging technologies like AI and the Metaverse, as well as the ethical implications of technology and experience design. However, the search also considers impactful real-world events, such as the Myanmar Earthquake, which occurred during a Civil War and was further complicated by the firing of US Aid Workers. The goal is to weigh the impact of these technological and geopolitical events to determine which had the most significant consequences in 2025.', 'image_path': '<html>\\n    <head>\\n        <meta charset=\"utf-8\">\\n        \\n            <script src=\"lib/bindings/utils.js\"></script>\\n            <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/dist/vis-network.min.css\" integrity=\"sha512-WgxfT5LWjfszlPHXRmBWHkV2eceiWTOBvrKCNbdgDYTHrT2AeLCGbF4sZlZw3UMN3WtL0tGUoIAKsu8mllg/XA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />\\n            <script src=\"https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/vis-network.min.js\" integrity=\"sha512-LnvoEWDFrqGHlHmDD2101OrLcbsfkrzoSpvtSQtxK3RMnRV0eOkhhBN2dXHKRrUU8p2DGRTk35n4O8nWSVe1mQ==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\\n            \\n        \\n<center>\\n<h1></h1>\\n</center>\\n\\n<!-- <link rel=\"stylesheet\" href=\"../node_modules/vis/dist/vis.min.css\" type=\"text/css\" />\\n<script type=\"text/javascript\" src=\"../node_modules/vis/dist/vis.js\"> </script>-->\\n        <link\\n          href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\"\\n          rel=\"stylesheet\"\\n          integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\"\\n          crossorigin=\"anonymous\"\\n        />\\n        <script\\n          src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js\"\\n          integrity=\"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf\"\\n          crossorigin=\"anonymous\"\\n        ></script>\\n\\n\\n        <center>\\n          <h1></h1>\\n        </center>\\n        <style type=\"text/css\">\\n\\n             #mynetwork {\\n                 width: 100%;\\n                 height: 750px;\\n                 background-color: #222222;\\n                 border: 1px solid lightgray;\\n                 position: relative;\\n                 float: left;\\n             }\\n\\n             \\n\\n             \\n\\n             \\n        </style>\\n    </head>\\n\\n\\n    <body>\\n        <div class=\"card\" style=\"width: 100%\">\\n            \\n            \\n            <div id=\"mynetwork\" class=\"card-body\"></div>\\n        </div>\\n\\n        \\n        \\n\\n        <script type=\"text/javascript\">\\n\\n              // initialize global variables.\\n              var edges;\\n              var nodes;\\n              var allNodes;\\n              var allEdges;\\n              var nodeColors;\\n              var originalNodes;\\n              var network;\\n              var container;\\n              var options, data;\\n              var filter = {\\n                  item : \\'\\',\\n                  property : \\'\\',\\n                  value : []\\n              };\\n\\n              \\n\\n              \\n\\n              // This method is responsible for drawing the graph, returns the drawn network\\n              function drawGraph() {\\n                  var container = document.getElementById(\\'mynetwork\\');\\n\\n                  \\n\\n                  // parsing and collecting nodes and edges from the python\\n                  nodes = new vis.DataSet([{\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"WSJ Tech Live\", \"importance_val\": 7, \"label\": \"WSJ Tech Live\", \"shape\": \"dot\", \"size\": 29, \"title\": \"Importance: 7\"}, {\"color\": \"#ff4757\", \"font\": {\"color\": \"white\"}, \"id\": \"Technology Impact on Business\", \"importance_val\": 9, \"label\": \"Technology Impact on Business\", \"shape\": \"dot\", \"size\": 33, \"title\": \"Importance: 9\"}, {\"color\": \"#2ed573\", \"font\": {\"color\": \"white\"}, \"id\": \"Networking\", \"importance_val\": 6, \"label\": \"Networking\", \"shape\": \"dot\", \"size\": 27, \"title\": \"Importance: 6\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Money 20/20\", \"importance_val\": 8, \"label\": \"Money 20/20\", \"shape\": \"dot\", \"size\": 31, \"title\": \"Importance: 8\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Fintech\", \"importance_val\": 7, \"label\": \"Fintech\", \"shape\": \"dot\", \"size\": 29, \"title\": \"Importance: 7\"}, {\"color\": \"#ff4757\", \"font\": {\"color\": \"white\"}, \"id\": \"Myanmar Earthquake\", \"importance_val\": 9, \"label\": \"Myanmar Earthquake\", \"shape\": \"dot\", \"size\": 33, \"title\": \"Importance: 9\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Civil War\", \"importance_val\": 8, \"label\": \"Civil War\", \"shape\": \"dot\", \"size\": 31, \"title\": \"Importance: 8\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"US Aid Workers Fired\", \"importance_val\": 7, \"label\": \"US Aid Workers Fired\", \"shape\": \"dot\", \"size\": 29, \"title\": \"Importance: 7\"}, {\"color\": \"#2ed573\", \"font\": {\"color\": \"white\"}, \"id\": \"Experience Design\", \"importance_val\": 6, \"label\": \"Experience Design\", \"shape\": \"dot\", \"size\": 27, \"title\": \"Importance: 6\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"AI\", \"importance_val\": 8, \"label\": \"AI\", \"shape\": \"dot\", \"size\": 31, \"title\": \"Importance: 8\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Metaverse\", \"importance_val\": 7, \"label\": \"Metaverse\", \"shape\": \"dot\", \"size\": 29, \"title\": \"Importance: 7\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Ethical Implications of Technology\", \"importance_val\": 8, \"label\": \"Ethical Implications of Technology\", \"shape\": \"dot\", \"size\": 31, \"title\": \"Importance: 8\"}, {\"color\": \"#2ed573\", \"font\": {\"color\": \"white\"}, \"id\": \"Plane Crashes\", \"importance_val\": 6, \"label\": \"Plane Crashes\", \"shape\": \"dot\", \"size\": 27, \"title\": \"Importance: 6\"}, {\"color\": \"#2ed573\", \"font\": {\"color\": \"white\"}, \"id\": \"Signal Chat Leak\", \"importance_val\": 5, \"label\": \"Signal Chat Leak\", \"shape\": \"dot\", \"size\": 25, \"title\": \"Importance: 5\"}, {\"color\": \"#2ed573\", \"font\": {\"color\": \"white\"}, \"id\": \"DOGE and Treasury\", \"importance_val\": 5, \"label\": \"DOGE and Treasury\", \"shape\": \"dot\", \"size\": 25, \"title\": \"Importance: 5\"}]);\\n                  edges = new vis.DataSet([{\"arrows\": \"to\", \"from\": \"WSJ Tech Live\", \"label\": \"discusses\", \"to\": \"Technology Impact on Business\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"WSJ Tech Live\", \"label\": \"facilitates\", \"to\": \"Networking\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"Money 20/20\", \"label\": \"is related to\", \"to\": \"Fintech\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"Myanmar Earthquake\", \"label\": \"occurred during\", \"to\": \"Civil War\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"US Aid Workers Fired\", \"label\": \"happened during\", \"to\": \"Myanmar Earthquake\", \"width\": 1}]);\\n\\n                  nodeColors = {};\\n                  allNodes = nodes.get({ returnType: \"Object\" });\\n                  for (nodeId in allNodes) {\\n                    nodeColors[nodeId] = allNodes[nodeId].color;\\n                  }\\n                  allEdges = edges.get({ returnType: \"Object\" });\\n                  // adding nodes and edges to the graph\\n                  data = {nodes: nodes, edges: edges};\\n\\n                  var options = {\"physics\": {\"repulsion\": {\"centralGravity\": 0.2, \"springLength\": 100, \"springConstant\": 0.05, \"nodeDistance\": 150, \"damping\": 0.09}, \"maxVelocity\": 50, \"minVelocity\": 0.1, \"solver\": \"repulsion\"}};\\n\\n                  \\n\\n\\n                  \\n\\n                  network = new vis.Network(container, data, options);\\n\\n                  \\n\\n                  \\n\\n                  \\n\\n\\n                  \\n\\n                  return network;\\n\\n              }\\n              drawGraph();\\n        </script>\\n    </body>\\n</html>', 'chosen_path': 'perform_web_search'}\n"
     ]
    }
   ],
   "source": [
    "print(html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "37dbd674",
   "metadata": {},
   "outputs": [],
   "source": [
    "sample_agent_state = {\n",
    "    \"original_input\": \"deep learning is a type of machine learning based on artificial neural networks in which multiple layers of processing are used to extract progressively higher level features from data.\",\n",
    "    \"text_to_map\": \"deep learning is a type of machine learning based on artificial neural networks in which multiple layers of processing are used to extract progressively higher level features from data.\",\n",
    "    \"keywords\": [\n",
    "        {\"concept\": \"Deep learning\", \"importance\": 10},\n",
    "        {\"concept\": \"Machine learning\", \"importance\": 9},\n",
    "        {\"concept\": \"Artificial neural networks\", \"importance\": 9},\n",
    "        {\"concept\": \"Multiple layers of processing\", \"importance\": 8},\n",
    "        {\"concept\": \"Feature extraction\", \"importance\": 7},\n",
    "        {\"concept\": \"Higher level features\", \"importance\": 7},\n",
    "        {\"concept\": \"Data\", \"importance\": 6}\n",
    "    ],\n",
    "    \"connections\": [\n",
    "        {\"source\": \"Deep learning\", \"relation\": \"is a type of\", \"target\": \"Machine learning\"},\n",
    "        {\"source\": \"Deep learning\", \"relation\": \"based on\", \"target\": \"Artificial neural networks\"},\n",
    "        {\"source\": \"Artificial neural networks\", \"relation\": \"use\", \"target\": \"Multiple layers of processing\"},\n",
    "        {\"source\": \"Multiple layers of processing\", \"relation\": \"used to\", \"target\": \"Feature extraction\"},\n",
    "        {\"source\": \"Feature extraction\", \"relation\": \"extracts\", \"target\": \"Higher level features\"},\n",
    "        {\"source\": \"Higher level features\", \"relation\": \"from\", \"target\": \"Data\"}\n",
    "    ],\n",
    "    \"summary\": \"\",\n",
    "    \"image_path\": \"\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "315eedce",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---NODE: GENERATING INTERACTIVE GRAPH (pyvis) ---\n",
      "Interactive conceptual map HTML generated successfully.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'image_path': '<html>\\n    <head>\\n        <meta charset=\"utf-8\">\\n        \\n            <script src=\"lib/bindings/utils.js\"></script>\\n            <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/dist/vis-network.min.css\" integrity=\"sha512-WgxfT5LWjfszlPHXRmBWHkV2eceiWTOBvrKCNbdgDYTHrT2AeLCGbF4sZlZw3UMN3WtL0tGUoIAKsu8mllg/XA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />\\n            <script src=\"https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/vis-network.min.js\" integrity=\"sha512-LnvoEWDFrqGHlHmDD2101OrLcbsfkrzoSpvtSQtxK3RMnRV0eOkhhBN2dXHKRrUU8p2DGRTk35n4O8nWSVe1mQ==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\\n            \\n        \\n<center>\\n<h1></h1>\\n</center>\\n\\n<!-- <link rel=\"stylesheet\" href=\"../node_modules/vis/dist/vis.min.css\" type=\"text/css\" />\\n<script type=\"text/javascript\" src=\"../node_modules/vis/dist/vis.js\"> </script>-->\\n        <link\\n          href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\"\\n          rel=\"stylesheet\"\\n          integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\"\\n          crossorigin=\"anonymous\"\\n        />\\n        <script\\n          src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js\"\\n          integrity=\"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf\"\\n          crossorigin=\"anonymous\"\\n        ></script>\\n\\n\\n        <center>\\n          <h1></h1>\\n        </center>\\n        <style type=\"text/css\">\\n\\n             #mynetwork {\\n                 width: 100%;\\n                 height: 750px;\\n                 background-color: #222222;\\n                 border: 1px solid lightgray;\\n                 position: relative;\\n                 float: left;\\n             }\\n\\n             \\n\\n             \\n\\n             \\n        </style>\\n    </head>\\n\\n\\n    <body>\\n        <div class=\"card\" style=\"width: 100%\">\\n            \\n            \\n            <div id=\"mynetwork\" class=\"card-body\"></div>\\n        </div>\\n\\n        \\n        \\n\\n        <script type=\"text/javascript\">\\n\\n              // initialize global variables.\\n              var edges;\\n              var nodes;\\n              var allNodes;\\n              var allEdges;\\n              var nodeColors;\\n              var originalNodes;\\n              var network;\\n              var container;\\n              var options, data;\\n              var filter = {\\n                  item : \\'\\',\\n                  property : \\'\\',\\n                  value : []\\n              };\\n\\n              \\n\\n              \\n\\n              // This method is responsible for drawing the graph, returns the drawn network\\n              function drawGraph() {\\n                  var container = document.getElementById(\\'mynetwork\\');\\n\\n                  \\n\\n                  // parsing and collecting nodes and edges from the python\\n                  nodes = new vis.DataSet([{\"color\": \"#ff4757\", \"font\": {\"color\": \"white\"}, \"id\": \"Deep learning\", \"importance_val\": 10, \"label\": \"Deep learning\", \"shape\": \"dot\", \"size\": 35, \"title\": \"Importance: 10\"}, {\"color\": \"#ff4757\", \"font\": {\"color\": \"white\"}, \"id\": \"Machine learning\", \"importance_val\": 9, \"label\": \"Machine learning\", \"shape\": \"dot\", \"size\": 33, \"title\": \"Importance: 9\"}, {\"color\": \"#ff4757\", \"font\": {\"color\": \"white\"}, \"id\": \"Artificial neural networks\", \"importance_val\": 9, \"label\": \"Artificial neural networks\", \"shape\": \"dot\", \"size\": 33, \"title\": \"Importance: 9\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Multiple layers of processing\", \"importance_val\": 8, \"label\": \"Multiple layers of processing\", \"shape\": \"dot\", \"size\": 31, \"title\": \"Importance: 8\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Feature extraction\", \"importance_val\": 7, \"label\": \"Feature extraction\", \"shape\": \"dot\", \"size\": 29, \"title\": \"Importance: 7\"}, {\"color\": \"#ffa502\", \"font\": {\"color\": \"white\"}, \"id\": \"Higher level features\", \"importance_val\": 7, \"label\": \"Higher level features\", \"shape\": \"dot\", \"size\": 29, \"title\": \"Importance: 7\"}, {\"color\": \"#2ed573\", \"font\": {\"color\": \"white\"}, \"id\": \"Data\", \"importance_val\": 6, \"label\": \"Data\", \"shape\": \"dot\", \"size\": 27, \"title\": \"Importance: 6\"}]);\\n                  edges = new vis.DataSet([{\"arrows\": \"to\", \"from\": \"Deep learning\", \"label\": \"is a type of\", \"to\": \"Machine learning\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"Deep learning\", \"label\": \"based on\", \"to\": \"Artificial neural networks\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"Artificial neural networks\", \"label\": \"use\", \"to\": \"Multiple layers of processing\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"Multiple layers of processing\", \"label\": \"used to\", \"to\": \"Feature extraction\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"Feature extraction\", \"label\": \"extracts\", \"to\": \"Higher level features\", \"width\": 1}, {\"arrows\": \"to\", \"from\": \"Higher level features\", \"label\": \"from\", \"to\": \"Data\", \"width\": 1}]);\\n\\n                  nodeColors = {};\\n                  allNodes = nodes.get({ returnType: \"Object\" });\\n                  for (nodeId in allNodes) {\\n                    nodeColors[nodeId] = allNodes[nodeId].color;\\n                  }\\n                  allEdges = edges.get({ returnType: \"Object\" });\\n                  // adding nodes and edges to the graph\\n                  data = {nodes: nodes, edges: edges};\\n\\n                  var options = {\"physics\": {\"repulsion\": {\"centralGravity\": 0.2, \"springLength\": 100, \"springConstant\": 0.05, \"nodeDistance\": 150, \"damping\": 0.09}, \"maxVelocity\": 50, \"minVelocity\": 0.1, \"solver\": \"repulsion\"}};\\n\\n                  \\n\\n\\n                  \\n\\n                  network = new vis.Network(container, data, options);\\n\\n                  \\n\\n                  \\n\\n                  \\n\\n\\n                  \\n\\n                  return network;\\n\\n              }\\n              drawGraph();\\n        </script>\\n    </body>\\n</html>'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.generate_graph_image(sample_agent_state)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c32b30d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "hfagents",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}