-
Notifications
You must be signed in to change notification settings - Fork 0
/
asd-system-with-flask-with-ui
401 lines (347 loc) · 15.7 KB
/
asd-system-with-flask-with-ui
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
import os
import nltk
import ssl
from flask import Flask, render_template, request, jsonify
import networkx as nx
from sklearn.ensemble import RandomForestRegressor
from nltk.sentiment import SentimentIntensityAnalyzer
from queue import PriorityQueue
# SSL workaround for NLTK downloads
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = _create_unverified_https_context
nltk.download('vader_lexicon')
# Get the absolute path of the directory containing this script
basedir = os.path.abspath(os.path.dirname(__file__))
class KnowledgeGraph:
def __init__(self):
self.graph = nx.Graph()
def add_node(self, node_type, node_id, attributes):
self.graph.add_node(node_id, type=node_type, **attributes)
def add_edge(self, node1_id, node2_id, relationship):
self.graph.add_edge(node1_id, node2_id, relationship=relationship)
def get_node_attributes(self, node_id):
return self.graph.nodes[node_id]
class TaskManager:
def __init__(self):
self.tasks = PriorityQueue()
def add_task(self, priority, agent_type, task_description):
self.tasks.put((priority, (agent_type, task_description)))
def get_next_task(self):
if not self.tasks.empty():
return self.tasks.get()[1]
return None
class DecisionMakingEngine:
def __init__(self):
self.sales_model = RandomForestRegressor()
self.sentiment_analyzer = SentimentIntensityAnalyzer()
def predict_sales(self, features):
return self.sales_model.predict(features)
def analyze_sentiment(self, text):
return self.sentiment_analyzer.polarity_scores(text)
def make_pricing_decision(self, product, market_trends, competitor_prices, inventory_levels):
avg_competitor_price = sum(competitor_prices.values()) / len(competitor_prices)
if inventory_levels > 100:
return min(avg_competitor_price * 0.9, product['current_price'])
else:
return max(avg_competitor_price * 1.1, product['current_price'])
class Agent:
def __init__(self, agent_type, knowledge_graph, task_manager, decision_engine):
self.agent_type = agent_type
self.kg = knowledge_graph
self.tm = task_manager
self.dme = decision_engine
def execute_task(self, task_description):
pass
class ProductAgent(Agent):
def execute_task(self, task_description):
if "Product Research" in task_description:
category = task_description.split("in ")[1]
products = self.research_top_selling_products(category)
for product in products:
self.kg.add_node("Product", product['asin'], product)
return f"Researched top-selling products in {category}"
elif "Pricing Analysis" in task_description:
product = task_description.split("of ")[1].split(" across")[0]
pricing_info = self.analyze_prices(product)
self.kg.add_node("PricingInfo", product, pricing_info)
return f"Analyzed prices for {product}"
elif "Inventory Management" in task_description:
product = task_description.split("for ")[1].split(" and")[0]
inventory_level = self.update_inventory(product)
self.tm.add_task(1, "Sales", f"Alert about stock availability for {product}")
return f"Updated inventory for {product}. Current level: {inventory_level}"
def research_top_selling_products(self, category):
return [
{'asin': 'B08F7N', 'name': 'Top Product 1', 'category': category, 'price': 99.99},
{'asin': 'C09G8M', 'name': 'Top Product 2', 'category': category, 'price': 149.99},
]
def analyze_prices(self, product):
return {
'amazon_price': 99.99,
'competitor1_price': 109.99,
'competitor2_price': 89.99,
}
def update_inventory(self, product):
return 50
class CustomerAgent(Agent):
def execute_task(self, task_description):
if "Customer Profiling" in task_description:
profiles = self.create_customer_profiles()
for profile in profiles:
self.kg.add_node("CustomerProfile", profile['id'], profile)
return "Created customer profiles and added to knowledge graph"
elif "Sentiment Analysis" in task_description:
product = task_description.split("for ")[1]
sentiment = self.dme.analyze_sentiment(f"This is a great product! I love my new {product}.")
self.kg.add_node("Sentiment", product, sentiment)
return f"Sentiment analysis for {product}: {sentiment}"
elif "Personalized Marketing" in task_description:
segment = task_description.split("for ")[1].split(" based")[0]
campaign = self.generate_marketing_campaign(segment)
self.kg.add_node("MarketingCampaign", segment, campaign)
return f"Generated personalized marketing campaign for {segment}"
def create_customer_profiles(self):
return [
{'id': 'C001', 'name': 'John Doe', 'preferences': ['electronics', 'books']},
{'id': 'C002', 'name': 'Jane Smith', 'preferences': ['fashion', 'home decor']},
]
def generate_marketing_campaign(self, segment):
return f"Special offers on top products for {segment} customers!"
class MarketAgent(Agent):
def execute_task(self, task_description):
if "Market Research" in task_description:
industry = task_description.split("for ")[1].split(" and")[0]
trends = self.research_market_trends(industry)
self.kg.add_node("MarketTrends", industry, trends)
return f"Researched market trends for {industry}"
elif "Competitor Monitoring" in task_description:
category = task_description.split("for ")[1]
competitor_info = self.monitor_competitors(category)
self.kg.add_node("CompetitorInfo", category, competitor_info)
return f"Monitored competitors for {category}"
elif "Trend Analysis" in task_description:
trends = self.analyze_trends()
self.kg.add_node("TrendAnalysis", "global", trends)
return "Analyzed global market trends"
def research_market_trends(self, industry):
return {
'growing_segments': ['Smart Home', 'Wearables'],
'declining_segments': ['Traditional PCs', 'Basic Cell Phones'],
}
def monitor_competitors(self, category):
return {
'Competitor A': {'market_share': 0.3, 'top_product': 'Product X'},
'Competitor B': {'market_share': 0.25, 'top_product': 'Product Y'},
}
def analyze_trends(self):
return {
'emerging_technologies': ['AI', '5G', 'Quantum Computing'],
'consumer_behavior_shifts': ['Increased online shopping', 'Focus on sustainability'],
}
class SalesAgent(Agent):
def execute_task(self, task_description):
if "Lead Generation" in task_description:
product = task_description.split("for ")[1]
leads = self.generate_leads(product)
for lead in leads:
self.kg.add_node("Lead", lead['id'], lead)
return f"Generated leads for {product}"
elif "Price Negotiation" in task_description:
product = task_description.split("for ")[1].split(" based")[0]
negotiation_result = self.negotiate_price(product)
self.kg.add_node("NegotiationResult", product, negotiation_result)
return f"Negotiated price for {product}"
elif "Deal Closing" in task_description:
product = task_description.split("for ")[1].split(" and")[0]
deal_result = self.close_deal(product)
self.kg.add_node("DealResult", product, deal_result)
self.update_sales_metrics(deal_result)
return f"Closed deal for {product}"
def generate_leads(self, product):
return [
{'id': 'L001', 'name': 'Company A', 'interest_level': 'High'},
{'id': 'L002', 'name': 'Company B', 'interest_level': 'Medium'},
]
def negotiate_price(self, product):
return {'final_price': 89.99, 'discount': 0.1}
def close_deal(self, product):
return {'product': product, 'quantity': 100, 'total_value': 8999}
def update_sales_metrics(self, deal_result):
print(f"Updated sales metrics: Sold {deal_result['quantity']} units of {deal_result['product']}")
class ASDSystem:
def __init__(self):
self.kg = KnowledgeGraph()
self.tm = TaskManager()
self.dme = DecisionMakingEngine()
self.agents = {
"Product": ProductAgent("Product", self.kg, self.tm, self.dme),
"Customer": CustomerAgent("Customer", self.kg, self.tm, self.dme),
"Market": MarketAgent("Market", self.kg, self.tm, self.dme),
"Sales": SalesAgent("Sales", self.kg, self.tm, self.dme)
}
def run(self):
while True:
task = self.tm.get_next_task()
if task is None:
break
agent_type, task_description = task
result = self.agents[agent_type].execute_task(task_description)
print(f"Task completed: {result}")
def collaborate(self, prompt):
if "Product-Price-Customer (PPC) Analysis" in prompt:
product = prompt.split("analyze ")[1].split(" features")[0]
pa_task = f"Pricing Analysis: Analyze prices of {product} across different online retailers"
ca_task = f"Sentiment Analysis: Analyze customer reviews for {product}"
ma_task = f"Market Research: Research market trends for {product.split()[0]}"
self.tm.add_task(1, "Product", pa_task)
self.tm.add_task(2, "Customer", ca_task)
self.tm.add_task(3, "Market", ma_task)
return f"Initiated PPC Analysis for {product}"
elif "Sales Strategy Development" in prompt:
product = prompt.split("for ")[1]
sa_task = f"Lead Generation: Generate leads for {product}"
ma_task = f"Competitor Monitoring: Monitor competitor prices and product offerings for {product}"
ca_task = f"Customer Profiling: Create customer profiles based on purchase history and provide personalized product recommendations"
self.tm.add_task(1, "Sales", sa_task)
self.tm.add_task(2, "Market", ma_task)
self.tm.add_task(3, "Customer", ca_task)
return f"Initiated Sales Strategy Development for {product}"
elif "Autonomous Decision-Making" in prompt:
product = prompt.split("for ")[1]
pa_task = f"Inventory Management: Update inventory levels for {product} and alert Sales Agent (SA) about stock availability"
sa_task = f"Price Negotiation: Negotiate prices with customers for {product} based on inventory levels and market trends"
self.tm.add_task(1, "Product", pa_task)
self.tm.add_task(2, "Sales", sa_task)
product_info = self.kg.get_node_attributes(product)
market_trends = self.kg.get_node_attributes("global")['TrendAnalysis']
competitor_prices = self.kg.get_node_attributes(product.split()[0])['CompetitorInfo']
inventory_levels = 50 # Assuming this value from earlier dummy data
price_decision = self.dme.make_pricing_decision(product_info, market_trends, competitor_prices, inventory_levels)
print(f"Autonomous pricing decision for {product}: ${price_decision}")
return f"Made autonomous decisions for {product}"
def add_task(self, priority, agent_type, task_description):
self.tm.add_task(priority, agent_type, task_description)
return f"Task added: {agent_type} - {task_description}"
def get_knowledge_graph(self):
return dict(self.kg.graph.nodes(data=True))
# Embedded HTML template
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASDSystem UI</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
#app {
max-width: 800px;
margin: auto;
background: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1, h2 {
color: #333;
}
input, button {
margin: 5px 0;
padding: 10px;
width: 100%;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
pre {
background-color: #f1f1f1;
padding: 10px;
border-radius: 5px;
overflow-x: auto;
}
</style>
</head>
<body>
<div id="app">
<h1>ASDSystem UI</h1>
<h2>Add Task</h2>
<input v-model="newTask.priority" placeholder="Priority">
<input v-model="newTask.agent_type" placeholder="Agent Type">
<input v-model="newTask.task_description" placeholder="Task Description">
<button @click="addTask">Add Task</button>
<h2>Run System</h2>
<button @click="runSystem">Run System</button>
<h2>Collaborate</h2>
<input v-model="collaborationPrompt" placeholder="Collaboration Prompt">
<button @click="collaborate">Collaborate</button>
<h2>Knowledge Graph</h2>
<button @click="getKnowledgeGraph">Get Knowledge Graph</button>
<pre>{{ knowledgeGraph }}</pre>
<h2>Results</h2>
<pre>{{ results }}</pre>
</div>
<script>
new Vue({
el: '#app',
data: {
newTask: {
priority: '',
agent_type: '',
task_description: ''
},
collaborationPrompt: '',
results: '',
knowledgeGraph: ''
},
methods: {
addTask() {
axios.post('/add_task', this.newTask)
.then(response => {
this.results = response.data.result;
this.newTask = { priority: '', agent_type: '', task_description: '' };
});
},
runSystem() {
axios.post('/run_system')
.then(response => {
this.results = response.data.result;
});
},
collaborate() {
axios.post('/collaborate', { prompt: this.collaborationPrompt })
.then(response => {
this.results = response.data.result;
this.collaborationPrompt = '';
});
},
getKnowledgeGraph() {
axios.get('/get_knowledge_graph')
.then(response => {
this.knowledgeGraph = JSON.stringify(response.data, null, 2);
});
}
}
});
</script>
</body>
</html>
"""