-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_agent.py
More file actions
280 lines (226 loc) · 10.1 KB
/
memory_agent.py
File metadata and controls
280 lines (226 loc) · 10.1 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
"""
Memory-enhanced AI Agent for Chrome Extension Idea Generation
Combines OpenAI with vector memory for improved ideation
"""
import os
import json
import time
from typing import List, Dict, Any, Optional, Union
from datetime import datetime
import openai
from dotenv import load_dotenv
# Import the vector memory system
from vector_memory import get_vector_memory
# Load environment variables
load_dotenv()
class MemoryEnhancedAgent:
"""
AI Agent with memory capabilities for Chrome extension idea generation
Leverages OpenAI and vector memory for improved ideation
"""
def __init__(self, api_key: Optional[str] = None):
"""
Initialize the memory-enhanced agent
Args:
api_key: OpenAI API key (default: use environment variable)
"""
# Use environment variable if API key not provided
self.api_key = api_key or os.getenv("OPENAI_API_KEY")
# Set up OpenAI client
self.client = openai.OpenAI(api_key=self.api_key)
# Get vector memory singleton
self.memory = get_vector_memory()
# Track whether memory is available
self.has_memory = self.memory.is_available
def generate_ideas(self,
extension_data: str,
word_bank: Optional[List[str]] = None,
count: int = 3,
use_memory: bool = True) -> List[Dict[str, Any]]:
"""
Generate Chrome extension ideas with memory enhancement
Args:
extension_data: Scraped extension data or requirements
word_bank: Optional list of niche keywords to focus on
count: Number of ideas to generate
use_memory: Whether to use vector memory for enhancement
Returns:
List of idea dictionaries
"""
# Create a prompt with memory context if available and requested
memory_context = ""
if use_memory and self.has_memory:
# Generate a query from the inputs
query = f"Chrome extensions for {' '.join(word_bank[:3] if word_bank else [])}"
# Get context from memory
memory_context = self.memory.get_context_for_prompt(query)
# Create the prompt
prompt = self._create_prompt(extension_data, word_bank, memory_context)
try:
# Call OpenAI to generate ideas
response = self.client.chat.completions.create(
model="gpt-4o", # the newest OpenAI model is "gpt-4o" which was released May 13, 2024. do not change this unless explicitly requested by the user
messages=[
{"role": "system", "content": "You are an expert in Chrome extension development and market research."},
{"role": "user", "content": prompt}
],
temperature=0.8,
max_tokens=2000,
response_format={"type": "json_object"}
)
# Parse the response
result = json.loads(response.choices[0].message.content)
ideas = result.get("ideas", [])
# Store ideas in memory if available
if self.has_memory and ideas:
# Add source information
for idea in ideas:
idea["source"] = "AI Generator"
idea["createdAt"] = datetime.now().isoformat()
# Store in vector memory
self.memory.store_multiple_ideas(ideas)
return ideas
except Exception as e:
print(f"Error generating ideas with memory agent: {str(e)}")
return []
def _create_prompt(self,
extension_data: str,
word_bank: Optional[List[str]] = None,
memory_context: str = "") -> str:
"""
Create a prompt for the AI based on data, word bank, and memory context
Args:
extension_data: Scraped extension data
word_bank: Optional list of keywords
memory_context: Context from vector memory
Returns:
Formatted prompt string
"""
prompt = "Generate innovative Chrome extension ideas based on the following information:\n\n"
# Add memory context if available
if memory_context:
prompt += "MEMORY CONTEXT:\n" + memory_context + "\n\n"
# Add extension data if available
if extension_data:
prompt += "EXTENSION DATA:\n" + extension_data + "\n\n"
# Add word bank if available
if word_bank and len(word_bank) > 0:
prompt += "NICHE KEYWORDS:\n" + ", ".join(word_bank) + "\n\n"
# Add specific instructions for output format
prompt += """
For each idea, please provide:
1. Name - The extension name
2. Problem - The user pain point it solves
3. Description - Brief explanation of what it does
4. Features - List of key features (at least 3)
5. Keywords - List of related keywords for SEO
6. SuggestedAudience - Who would use this extension
7. Competition - Level of competition (High, Medium, Low)
8. OriginalityScore - A score from 1-10 rating how innovative this idea is
9. Monetization - Ideas for monetization strategies
10. WhyNow - Why this extension is timely and needed now
If you're generating multiple ideas, make at least one a hybrid concept that combines two seemingly unrelated niches in a novel way.
Respond with a JSON object in this format:
{
"ideas": [
{
"name": "Extension Name",
"problem": "Problem statement",
"description": "Description",
"features": ["Feature 1", "Feature 2", "Feature 3"],
"keywords": ["keyword1", "keyword2", "keyword3"],
"suggestedAudience": ["Audience 1", "Audience 2"],
"competition": "Low/Medium/High",
"originalityScore": 8,
"monetization": ["Strategy 1", "Strategy 2"],
"whyNow": "Reason why it's relevant now",
"isHybrid": false
}
]
}
"""
return prompt
def analyze_extension_idea(self, idea: Dict[str, Any]) -> Dict[str, Any]:
"""
Enhance and analyze an extension idea with insights from memory
Args:
idea: The extension idea to analyze
Returns:
Enhanced idea with additional insights
"""
if not self.has_memory:
# Without memory, just return the original idea
return idea
try:
# Generate a query from the idea
query = f"{idea.get('name', '')} {idea.get('problem', '')}"
# Get memory context for similar ideas
memory_context = self.memory.get_context_for_prompt(query)
# Create a prompt for analysis
prompt = f"""
Analyze this Chrome extension idea and provide deeper insights based on similar ideas:
EXTENSION IDEA:
Name: {idea.get('name', 'Untitled')}
Problem: {idea.get('problem', 'N/A')}
Description: {idea.get('description', 'N/A')}
Features: {', '.join(idea.get('features', []))}
Keywords: {', '.join(idea.get('keywords', []))}
Target Audience: {', '.join(idea.get('suggestedAudience', []))}
MEMORY CONTEXT:
{memory_context}
Please provide:
1. Enhanced features with more detail
2. Potential challenges and how to overcome them
3. Differentiation strategy from existing solutions
4. Growth strategy recommendations
5. Refined target audience segments
6. Development complexity estimate (Low, Medium, High)
Respond in JSON format.
"""
# Call OpenAI for analysis
response = self.client.chat.completions.create(
model="gpt-4o", # the newest OpenAI model is "gpt-4o" which was released May 13, 2024. do not change this unless explicitly requested by the user
messages=[
{"role": "system", "content": "You are an expert in Chrome extension development and market research."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=1500,
response_format={"type": "json_object"}
)
# Parse the response
result = json.loads(response.choices[0].message.content)
# Add analysis to idea
enhanced_idea = idea.copy()
# Add enhanced insights
if 'enhancedFeatures' in result:
enhanced_idea['enhancedFeatures'] = result['enhancedFeatures']
if 'challenges' in result:
enhanced_idea['challenges'] = result['challenges']
if 'differentiationStrategy' in result:
enhanced_idea['differentiationStrategy'] = result['differentiationStrategy']
if 'growthStrategy' in result:
enhanced_idea['growthStrategy'] = result['growthStrategy']
if 'refinedAudience' in result:
enhanced_idea['refinedAudience'] = result['refinedAudience']
if 'developmentComplexity' in result:
enhanced_idea['developmentComplexity'] = result['developmentComplexity']
# Update memory with insights
insight_text = json.dumps(result, indent=2)
if 'id' in enhanced_idea and enhanced_idea['id']:
self.memory.add_insight(enhanced_idea['id'], insight_text)
return enhanced_idea
except Exception as e:
print(f"Error analyzing idea with memory agent: {str(e)}")
return idea
def run(extension_data: str, word_bank: Optional[List[str]] = None) -> List[Dict[str, str]]:
"""
Run the memory-enhanced agent to generate Chrome extension ideas
Args:
extension_data: Scraped extension data or requirements
word_bank: Optional list of niche keywords to focus on
Returns:
List of generated ideas
"""
agent = MemoryEnhancedAgent()
return agent.generate_ideas(extension_data, word_bank)