import os import networkx as nx import matplotlib.pyplot as plt from langchain_groq import ChatGroq from langchain.chains import LLMChain from langchain.prompts import PromptTemplate import gradio as gr # Set up the ChatGroq API GROQ_API_KEY = os.environ.get("GROQ_API_KEY") if not GROQ_API_KEY: raise ValueError("Please set the GROQ_API_KEY environment variable") # Initialize the ChatGroq LLM llm = ChatGroq(temperature=0, model_name='llama-3.1-8b-instant', groq_api_key=GROQ_API_KEY) # Define a prompt template for entity extraction entity_extraction_prompt = PromptTemplate( input_variables=["text"], template="Extract the main entities and their relationships from the following text:\n{text}\n\nEntities and relationships:" ) # Create an LLMChain for entity extraction entity_chain = LLMChain(llm=llm, prompt=entity_extraction_prompt) def create_knowledge_graph(text): """Extracts entities and relationships from text and creates a knowledge graph.""" result = entity_chain.run(text) # Parse the result and create a graph G = nx.Graph() # Simple parsing logic (you may need to adjust this based on the LLM's output format) lines = result.split('\n') for line in lines: if '-' in line: entity1, rest = line.split('-', 1) relation, entity2 = rest.split(':', 1) entity1 = entity1.strip() entity2 = entity2.strip() relation = relation.strip() G.add_node(entity1) G.add_node(entity2) G.add_edge(entity1, entity2, relationship=relation) return G def visualize_graph(G): """Visualizes the knowledge graph using matplotlib.""" pos = nx.spring_layout(G) plt.figure(figsize=(12, 8)) nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=3000, font_size=10, font_weight='bold') edge_labels = nx.get_edge_attributes(G, 'relationship') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) plt.title("Knowledge Graph") plt.axis('off') plt.tight_layout() return plt def generate_knowledge_graph(text): """Generates and visualizes a knowledge graph from input text.""" if text: knowledge_graph = create_knowledge_graph(text) fig = visualize_graph(knowledge_graph) return fig else: return None # Custom footer HTML footer_html = """ """ # Instructions for using the app instructions_html = """