-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector_memory.py
More file actions
459 lines (388 loc) · 17.2 KB
/
vector_memory.py
File metadata and controls
459 lines (388 loc) · 17.2 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
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
"""
Vector Memory System for Chrome Extension Idea Generator
Uses Weaviate as a vector database to store and retrieve extension ideas and insights
"""
import os
import json
import uuid
import time
from datetime import datetime
from typing import List, Dict, Any, Optional, Union, Tuple
from tqdm import tqdm
import weaviate
import weaviate.classes as wvc
from weaviate.classes.config import ConsistencyLevel, Property, DataType, Tokenization
import openai
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class VectorMemory:
"""
Vector Memory System for storing and retrieving Chrome extension ideas and insights
Uses Weaviate as a vector database and OpenAI for embeddings
"""
def __init__(self,
weaviate_url: Optional[str] = None,
api_key: Optional[str] = None,
openai_api_key: Optional[str] = None,
schema_name: str = "ChromeExtensionIdea"):
"""
Initialize the Vector Memory system
Args:
weaviate_url: URL for the Weaviate instance (default: use env var WEAVIATE_URL)
api_key: API key for Weaviate (default: use env var WEAVIATE_API_KEY)
openai_api_key: API key for OpenAI (default: use env var OPENAI_API_KEY)
schema_name: Name of the schema class to use in Weaviate
"""
# Use environment variables if not provided
self.weaviate_url = weaviate_url or os.getenv("WEAVIATE_URL")
self.api_key = api_key or os.getenv("WEAVIATE_API_KEY")
self.openai_api_key = openai_api_key or os.getenv("OPENAI_API_KEY")
self.schema_name = schema_name
# Set up OpenAI client
self.openai_client = openai.OpenAI(api_key=self.openai_api_key)
# Connect to Weaviate
try:
if self.weaviate_url and self.api_key:
self.client = self._setup_weaviate_client()
# Check if schema exists, create if not
self._ensure_schema_exists()
self.is_available = True
print(f"Connected to Weaviate at {self.weaviate_url}")
else:
print("Weaviate URL or API key not provided. Vector memory will be unavailable.")
self.is_available = False
self.client = None
except Exception as e:
print(f"Failed to connect to Weaviate: {str(e)}")
self.is_available = False
self.client = None
def _setup_weaviate_client(self):
"""Set up and return a Weaviate client with the configured credentials"""
auth_config = weaviate.AuthApiKey(api_key=self.api_key)
client = weaviate.Client(
url=self.weaviate_url,
auth_client_secret=auth_config,
additional_headers={
"X-OpenAI-Api-Key": self.openai_api_key
}
)
return client
def _ensure_schema_exists(self):
"""Check if the schema exists, create it if not"""
if not self.client:
return False
# Check if class exists
try:
schema = self.client.schema.get()
class_names = [c['class'] for c in schema['classes']] if 'classes' in schema else []
if self.schema_name not in class_names:
# Create the class
print(f"Creating schema class '{self.schema_name}'...")
# Define properties
properties = [
Property(name="name", data_type=DataType.TEXT, tokenization=Tokenization.FIELD),
Property(name="description", data_type=DataType.TEXT, tokenization=Tokenization.FIELD),
Property(name="problem", data_type=DataType.TEXT, tokenization=Tokenization.FIELD),
Property(name="features", data_type=DataType.TEXT_ARRAY),
Property(name="keywords", data_type=DataType.TEXT_ARRAY),
Property(name="audience", data_type=DataType.TEXT_ARRAY),
Property(name="competition", data_type=DataType.TEXT),
Property(name="monetization", data_type=DataType.TEXT_ARRAY),
Property(name="originalityScore", data_type=DataType.NUMBER),
Property(name="trendScore", data_type=DataType.NUMBER),
Property(name="isHybrid", data_type=DataType.BOOLEAN),
Property(name="notionPageId", data_type=DataType.TEXT),
Property(name="createdAt", data_type=DataType.DATE),
Property(name="source", data_type=DataType.TEXT),
Property(name="insights", data_type=DataType.TEXT),
]
# Create class configuration
config = wvc.Configure.new()
# Set up vectorizer for OpenAI embeddings
config = config.with_vectorizer("text2vec-openai", {
"model": "ada",
"modelVersion": "002",
"type": "text"
})
# Create class with properties
self.client.collections.create(
name=self.schema_name,
properties=properties,
vectorizer_config=config,
consistency_level=ConsistencyLevel.QUORUM
)
print(f"Schema class '{self.schema_name}' created successfully.")
return True
else:
print(f"Schema class '{self.schema_name}' already exists.")
return True
except Exception as e:
print(f"Error ensuring schema exists: {str(e)}")
return False
def store_idea(self, idea: Dict[str, Any]) -> Optional[str]:
"""
Store a Chrome extension idea in the vector database
Args:
idea: Dictionary containing the idea data
Returns:
UUID of the stored idea, or None if storage failed
"""
if not self.is_available or not self.client:
print("Vector memory not available. Idea not stored.")
return None
try:
# Generate a UUID for the idea
idea_id = str(uuid.uuid4())
# Prepare data for storage
data_obj = {
"name": idea.get("name", "Untitled Idea"),
"description": idea.get("description", ""),
"problem": idea.get("problem", ""),
"features": idea.get("features", []),
"keywords": idea.get("keywords", []),
"audience": idea.get("suggestedAudience", []),
"competition": idea.get("competition", ""),
"monetization": idea.get("monetization", []),
"originalityScore": idea.get("originalityScore", 0),
"trendScore": idea.get("trendScore", 0),
"isHybrid": idea.get("isHybrid", False),
"notionPageId": idea.get("notionPageId", ""),
"createdAt": datetime.now().isoformat(),
"source": idea.get("source", "AI Generator"),
"insights": idea.get("insights", "")
}
# Store in Weaviate
with self.client.batch.dynamic() as batch:
batch.add_data_object(
data_obj,
self.schema_name,
idea_id
)
print(f"Stored idea '{data_obj['name']}' with ID {idea_id}")
return idea_id
except Exception as e:
print(f"Error storing idea: {str(e)}")
return None
def store_multiple_ideas(self, ideas: List[Dict[str, Any]]) -> List[str]:
"""
Store multiple Chrome extension ideas in the vector database
Args:
ideas: List of idea dictionaries to store
Returns:
List of UUIDs for the stored ideas
"""
if not self.is_available or not self.client:
print("Vector memory not available. Ideas not stored.")
return []
stored_ids = []
try:
with self.client.batch.dynamic() as batch:
for idea in tqdm(ideas, desc="Storing ideas"):
# Generate a UUID for the idea
idea_id = str(uuid.uuid4())
# Prepare data for storage
data_obj = {
"name": idea.get("name", "Untitled Idea"),
"description": idea.get("description", ""),
"problem": idea.get("problem", ""),
"features": idea.get("features", []),
"keywords": idea.get("keywords", []),
"audience": idea.get("suggestedAudience", []),
"competition": idea.get("competition", ""),
"monetization": idea.get("monetization", []),
"originalityScore": idea.get("originalityScore", 0),
"trendScore": idea.get("trendScore", 0),
"isHybrid": idea.get("isHybrid", False),
"notionPageId": idea.get("notionPageId", ""),
"createdAt": datetime.now().isoformat(),
"source": idea.get("source", "AI Generator"),
"insights": idea.get("insights", "")
}
# Store in Weaviate
batch.add_data_object(
data_obj,
self.schema_name,
idea_id
)
stored_ids.append(idea_id)
print(f"Stored {len(stored_ids)} ideas in vector database")
return stored_ids
except Exception as e:
print(f"Error storing multiple ideas: {str(e)}")
return stored_ids
def search_similar_ideas(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
"""
Search for ideas similar to the query text
Args:
query: Text query to search for
limit: Maximum number of results to return
Returns:
List of similar ideas
"""
if not self.is_available or not self.client:
print("Vector memory not available. Cannot search.")
return []
try:
# Get collection
collection = self.client.collections.get(self.schema_name)
# Perform vector search
result = collection.query.near_text(
query=query,
limit=limit
).do()
# Extract and return the objects
if "data" in result and "Get" in result["data"]:
ideas = result["data"]["Get"].get(self.schema_name, [])
return ideas
return []
except Exception as e:
print(f"Error searching similar ideas: {str(e)}")
return []
def search_by_keywords(self, keywords: List[str], limit: int = 5) -> List[Dict[str, Any]]:
"""
Search for ideas by keywords
Args:
keywords: List of keywords to search for
limit: Maximum number of results to return
Returns:
List of matching ideas
"""
if not self.is_available or not self.client:
print("Vector memory not available. Cannot search.")
return []
try:
# Get collection
collection = self.client.collections.get(self.schema_name)
# Prepare where filter for keywords
where_filter = {
"path": ["keywords"],
"operator": "ContainsAny",
"valueStringArray": keywords
}
# Perform search
result = collection.query.get(
limit=limit
).with_where(
where_filter
).do()
# Extract and return the objects
if "data" in result and "Get" in result["data"]:
ideas = result["data"]["Get"].get(self.schema_name, [])
return ideas
return []
except Exception as e:
print(f"Error searching by keywords: {str(e)}")
return []
def get_context_for_prompt(self, query: str, max_ideas: int = 3) -> str:
"""
Get a formatted context string from similar ideas for use in AI prompts
Args:
query: The query to find similar ideas for
max_ideas: Maximum number of ideas to include
Returns:
Formatted context string
"""
similar_ideas = self.search_similar_ideas(query, limit=max_ideas)
if not similar_ideas:
return "No similar ideas found."
# Format the ideas as context
context = "Related ideas from memory:\n\n"
for i, idea in enumerate(similar_ideas):
context += f"IDEA {i+1}: {idea.get('name', 'Untitled')}\n"
context += f"Problem: {idea.get('problem', 'N/A')}\n"
if idea.get('features'):
context += "Features:\n"
for feat in idea.get('features', [])[:3]: # Limit to 3 features
context += f"- {feat}\n"
context += f"Keywords: {', '.join(idea.get('keywords', []))}\n"
if idea.get('insights'):
context += f"Insights: {idea.get('insights')}\n"
context += "\n"
return context
def get_stats(self) -> Dict[str, Any]:
"""
Get statistics about the vector memory
Returns:
Dictionary of statistics
"""
if not self.is_available or not self.client:
return {"available": False}
try:
# Get collection
collection = self.client.collections.get(self.schema_name)
# Get total count
try:
count_result = collection.query.aggregate().with_meta_count().do()
total_count = count_result["data"]["Aggregate"][self.schema_name][0]["meta"]["count"]
except:
total_count = 0
# Get hybrid count
try:
hybrid_filter = {
"path": ["isHybrid"],
"operator": "Equal",
"valueBoolean": True
}
hybrid_result = collection.query.aggregate().with_where(hybrid_filter).with_meta_count().do()
hybrid_count = hybrid_result["data"]["Aggregate"][self.schema_name][0]["meta"]["count"]
except:
hybrid_count = 0
# Get high originality count
try:
originality_filter = {
"path": ["originalityScore"],
"operator": "GreaterThan",
"valueNumber": 7.0
}
originality_result = collection.query.aggregate().with_where(originality_filter).with_meta_count().do()
high_originality_count = originality_result["data"]["Aggregate"][self.schema_name][0]["meta"]["count"]
except:
high_originality_count = 0
return {
"available": True,
"totalIdeas": total_count,
"hybridIdeas": hybrid_count,
"highOriginalityIdeas": high_originality_count
}
except Exception as e:
print(f"Error getting stats: {str(e)}")
return {"available": False, "error": str(e)}
def add_insight(self, idea_id: str, insight: str) -> bool:
"""
Add an insight to an existing idea
Args:
idea_id: UUID of the idea
insight: Insight text to add
Returns:
True if successful, False otherwise
"""
if not self.is_available or not self.client:
print("Vector memory not available. Cannot add insight.")
return False
try:
# Get collection
collection = self.client.collections.get(self.schema_name)
# Update the insight
collection.data.update(
uuid=idea_id,
properties={
"insights": insight
}
)
return True
except Exception as e:
print(f"Error adding insight: {str(e)}")
return False
# Singleton instance
_vector_memory_instance = None
def get_vector_memory() -> VectorMemory:
"""
Get the singleton instance of VectorMemory
Returns:
The VectorMemory instance
"""
global _vector_memory_instance
if _vector_memory_instance is None:
_vector_memory_instance = VectorMemory()
return _vector_memory_instance