-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
347 lines (287 loc) · 11.4 KB
/
main.py
File metadata and controls
347 lines (287 loc) · 11.4 KB
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
# requirements.txt
"""
langchain==0.0.329
cohere==4.32
neo4j==5.14.1
torch==2.1.2
networkx==3.2.1
matplotlib==3.8.2
plotly==5.18.0
redis==5.0.1
rich==13.7.0
python-dotenv==1.0.0
"""
# knowledge_assistant.py
import os
from dotenv import load_dotenv
from typing import List, Dict, Optional, Tuple
import torch
import torch.nn as nn
import networkx as nx
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from datetime import datetime
import json
import redis
from functools import lru_cache
from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress
from neo4j import GraphDatabase
from langchain.llms import Cohere
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.embeddings import CohereEmbeddings
# Load environment variables
load_dotenv()
class Config:
COHERE_API_KEY = os.getenv('COHERE_API_KEY')
NEO4J_URI = os.getenv('NEO4J_URI', 'neo4j://localhost:7687')
NEO4J_USER = os.getenv('NEO4J_USER', 'neo4j')
NEO4J_PASSWORD = os.getenv('NEO4J_PASSWORD', 'password')
REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')
REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))
class NeuralModels:
class TransformerEncoder(nn.Module):
def __init__(self, input_dim=768, nhead=8, num_layers=3):
super().__init__()
encoder_layer = nn.TransformerEncoderLayer(
d_model=input_dim,
nhead=nhead,
dim_feedforward=2048,
batch_first=True
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
def forward(self, x):
return self.transformer(x)
class GraphNetwork(nn.Module):
def __init__(self, input_dim=768, hidden_dim=384):
super().__init__()
self.conv1 = nn.Linear(input_dim, hidden_dim)
self.conv2 = nn.Linear(hidden_dim, hidden_dim)
def forward(self, x, adj_matrix):
x = torch.relu(self.conv1(torch.matmul(adj_matrix, x)))
return torch.relu(self.conv2(torch.matmul(adj_matrix, x)))
class Cache:
def __init__(self, host: str = Config.REDIS_HOST, port: int = Config.REDIS_PORT):
self.redis = redis.Redis(host=host, port=port, decode_responses=True)
self.ttl = 3600 # 1 hour cache lifetime
def get(self, key: str) -> Optional[dict]:
data = self.redis.get(key)
return json.loads(data) if data else None
def set(self, key: str, value: dict):
self.redis.setex(key, self.ttl, json.dumps(value))
class KnowledgeGraph:
def __init__(self, uri: str, user: str, password: str):
self.driver = GraphDatabase.driver(uri, auth=(user, password))
def close(self):
self.driver.close()
def create_indexes(self):
with self.driver.session() as session:
session.run("CREATE INDEX IF NOT EXISTS FOR (n:Concept) ON (n.content)")
session.run("CREATE INDEX IF NOT EXISTS FOR (n:Query) ON (n.content)")
def add_relationship(self, source: str, target: str, relationship: str):
with self.driver.session() as session:
session.run("""
MERGE (s:Concept {content: $source})
MERGE (t:Concept {content: $target})
MERGE (s)-[:RELATES {type: $relationship}]->(t)
""", source=source, target=target, relationship=relationship)
class Visualizer:
def __init__(self, graph: KnowledgeGraph):
self.graph = graph
def create_network(self) -> nx.Graph:
G = nx.Graph()
with self.graph.driver.session() as session:
result = session.run("""
MATCH (n)-[r]-(m)
RETURN n.content, type(r), m.content
""")
for record in result:
G.add_edge(record['n.content'], record['m.content'],
type=record['type(r)'])
return G
def plot_static(self, filename: str = 'knowledge_graph.png'):
G = self.create_network()
plt.figure(figsize=(15, 10))
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightblue',
node_size=1500, font_size=8)
plt.savefig(filename)
plt.close()
def plot_interactive(self) -> go.Figure:
G = self.create_network()
pos = nx.spring_layout(G, dim=3)
edge_traces = []
node_trace = go.Scatter3d(
x=[], y=[], z=[], mode='markers+text',
hoverinfo='text', marker=dict(size=10, color='lightblue')
)
for edge in G.edges():
x0, y0, z0 = pos[edge[0]]
x1, y1, z1 = pos[edge[1]]
edge_traces.append(go.Scatter3d(
x=[x0, x1], y=[y0, y1], z=[z0, z1],
mode='lines', line=dict(width=1, color='#888')
))
for node in G.nodes():
x, y, z = pos[node]
node_trace.x = node_trace.x + (x,)
node_trace.y = node_trace.y + (y,)
node_trace.z = node_trace.z + (z,)
return go.Figure(data=edge_traces + [node_trace])
class Assistant:
def __init__(self):
self.console = Console()
self.cache = Cache()
self.graph = KnowledgeGraph(
Config.NEO4J_URI,
Config.NEO4J_USER,
Config.NEO4J_PASSWORD
)
self.visualizer = Visualizer(self.graph)
self.cohere = Cohere()
self.embeddings = CohereEmbeddings(cohere_api_key=Config.COHERE_API_KEY)
self.history = []
# Initialize neural models
self.transformer = NeuralModels.TransformerEncoder()
self.graph_network = NeuralModels.GraphNetwork()
# Create database indexes
self.graph.create_indexes()
def start(self):
self.console.print(Panel.fit(
"🤖 Welcome to the Knowledge Graph AI Assistant!\n"
"Type 'help' for available commands or 'exit' to quit.",
title="AI Assistant",
border_style="blue"
))
while True:
try:
query = self.console.input("\n[bold blue]Query:[/] ").strip()
if not query:
continue
if query.lower() == 'exit':
self.cleanup()
break
self.process_command(query)
except Exception as e:
self.console.print(f"[red]Error: {str(e)}[/]")
def process_command(self, query: str):
commands = {
'help': self.show_help,
'viz': self.show_visualization,
'stats': self.show_stats,
'history': self.show_history,
'clear': self.clear_history
}
cmd = query.lower()
if cmd in commands:
commands[cmd]()
else:
self.process_query(query)
def process_query(self, query: str):
with Progress() as progress:
task = progress.add_task("[cyan]Processing...", total=100)
# Check cache
cache_key = f"query:{hash(query)}"
cached_response = self.cache.get(cache_key)
if cached_response:
progress.update(task, completed=100)
self.display_response(cached_response)
return
# Get response from Cohere
progress.update(task, advance=30)
response = self.get_ai_response(query)
# Update knowledge graph
progress.update(task, advance=30)
self.update_graph(query, response)
# Cache response
progress.update(task, advance=30)
self.cache.set(cache_key, response)
# Store in history
self.history.append((query, response))
progress.update(task, completed=100)
self.display_response(response)
def get_ai_response(self, query: str) -> dict:
prompt = PromptTemplate(
input_variables=["query"],
template="Please provide a detailed response to: {query}"
)
chain = LLMChain(llm=self.cohere, prompt=prompt)
response = chain.run(query=query)
return {
"query": query,
"response": response,
"timestamp": datetime.now().isoformat()
}
def update_graph(self, query: str, response: dict):
# Add query-response relationship
self.graph.add_relationship(
query,
response['response'][:100], # Use first 100 chars as identifier
"HAS_RESPONSE"
)
def display_response(self, response: dict):
self.console.print("\n[bold green]Response:[/]")
self.console.print(Panel(response['response'], border_style="green"))
def show_help(self):
help_text = """
Available commands:
- help: Show this help message
- viz: Visualize the knowledge graph
- stats: Show system statistics
- history: Show query history
- clear: Clear query history
- exit: Exit the assistant
Or simply type your question for an AI response!
"""
self.console.print(Panel(help_text, title="Help", border_style="blue"))
def show_visualization(self):
with Progress() as progress:
task = progress.add_task("[cyan]Generating visualizations...", total=100)
# Generate static visualization
progress.update(task, advance=50)
self.visualizer.plot_static()
# Generate interactive visualization
progress.update(task, advance=40)
fig = self.visualizer.plot_interactive()
fig.show()
progress.update(task, completed=100)
def show_stats(self):
with self.graph.driver.session() as session:
result = session.run("""
MATCH (n)
RETURN count(n) as nodes,
size([(n)-[r]->(m) | r]) as relationships
""")
stats = result.single()
stats_text = f"""
System Statistics:
• Nodes in Knowledge Graph: {stats['nodes']}
• Relationships: {stats['relationships']}
• Queries in History: {len(self.history)}
• Cache Entries: {self.cache.redis.dbsize()}
"""
self.console.print(Panel(stats_text, title="Statistics", border_style="cyan"))
def show_history(self):
if not self.history:
self.console.print("[yellow]No history available[/]")
return
for i, (query, response) in enumerate(self.history, 1):
self.console.print(f"\n[cyan]Query {i}:[/] {query}")
self.console.print(f"[green]Response:[/] {response['response'][:100]}...")
def clear_history(self):
self.history.clear()
self.console.print("[green]History cleared[/]")
def cleanup(self):
self.graph.close()
self.console.print("[yellow]Goodbye! 👋[/]")
def main():
if not Config.COHERE_API_KEY:
print("Error: COHERE_API_KEY not found in environment variables")
print("Please create a .env file with your credentials")
return
assistant = Assistant()
assistant.start()
if __name__ == "__main__":
main()