{ "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'\\n{doc.page_content}\\n'\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\": \"

No graph data could be generated from the text.

\"}\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\"

An error occurred while generating the graph: {e}

\"}\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': '\\n \\n \\n \\n \\n \\n \\n \\n \\n
\\n

\\n
\\n\\n\\n \\n \\n\\n\\n
\\n

\\n
\\n \\n \\n\\n\\n \\n
\\n \\n \\n
\\n
\\n\\n \\n \\n\\n \\n \\n', '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': '\\n \\n \\n \\n \\n \\n \\n \\n \\n
\\n

\\n
\\n\\n\\n \\n \\n\\n\\n
\\n

\\n
\\n \\n \\n\\n\\n \\n
\\n \\n \\n
\\n
\\n\\n \\n \\n\\n \\n \\n'}" ] }, "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 }