E-commerce Manager Agent
ExpertLearn complex business logic and enterprise-grade workflow automation with a comprehensive e-commerce management system.
What You'll Learn
Business Logic
Complex workflows and calculations
CRM Systems
Customer relationship management
Analytics
Business intelligence and reporting
Revenue Tracking
Financial metrics and optimization
Basic E-commerce Manager
1from connectonion import Agent
2from datetime import datetime
3
4# Global data storage
5inventory = {}
6orders = []
7customers = {}
8order_counter = 1
9
10def manage_inventory(product_name: str, action: str, quantity: int = 0) -> str:
11 """Manage product inventory - add, remove, or check stock."""
12 if action == "add":
13 inventory[product_name] = inventory.get(product_name, 0) + quantity
14 return f"✅ Added {quantity} units of {product_name}. Current stock: {inventory[product_name]}"
15 elif action == "remove":
16 current = inventory.get(product_name, 0)
17 if current >= quantity:
18 inventory[product_name] = current - quantity
19 return f"📦 Removed {quantity} units of {product_name}. Remaining: {inventory[product_name]}"
20 return f"❌ Insufficient stock. Available: {current}, Requested: {quantity}"
21 elif action == "check":
22 stock = inventory.get(product_name, 0)
23 return f"📊 {product_name}: {stock} units in stock"
24 return "❌ Invalid action. Use: add, remove, or check"
25
26def process_order(customer_name: str, product: str, quantity: int, price: float) -> str:
27 """Process a new customer order."""
28 global order_counter
29
30 # Check inventory
31 if inventory.get(product, 0) < quantity:
32 return f"❌ Order failed: Insufficient stock for {product}"
33
34 # Process order
35 order = {
36 "id": order_counter,
37 "customer": customer_name,
38 "product": product,
39 "quantity": quantity,
40 "price": price,
41 "total": price * quantity,
42 "date": datetime.now().strftime("%Y-%m-%d %H:%M")
43 }
44
45 orders.append(order)
46 inventory[product] -= quantity
47 order_counter += 1
48
49 return f"🎉 Order #{order['id']} processed! {customer_name} ordered {quantity}x {product} for ${order['total']}"
50
51# Create e-commerce agent
52agent = Agent(
53 name="ecommerce_manager",
54 tools=[manage_inventory, process_order]
55)
Enterprise E-commerce Manager
1# ecommerce_manager_agent.py
2import os
3from connectonion import Agent
4from datetime import datetime, timedelta
5from typing import Dict, List, Any
6import json
7
8# Set your OpenAI API key
9os.environ['OPENAI_API_KEY'] = 'your-api-key-here'
10
11# Global business data storage (use database in production)
12inventory = {}
13orders = []
14customers = {}
15analytics = {"total_revenue": 0, "total_orders": 0}
16order_counter = 1
17customer_counter = 1
18
19def manage_inventory(product_name: str, action: str, quantity: int = 0, price: float = 0.0) -> str:
20 """Comprehensive inventory management system."""
21 try:
22 if action.lower() == "add":
23 if product_name not in inventory:
24 inventory[product_name] = {"stock": 0, "price": price or 0.0, "sales": 0}
25
26 inventory[product_name]["stock"] += quantity
27 if price > 0:
28 inventory[product_name]["price"] = price
29
30 return f"""✅ **Inventory Updated**
31
32📦 Product: {product_name}
33➕ Added: {quantity} units
34📊 Current Stock: {inventory[product_name]["stock"]} units
35💰 Price: ${inventory[product_name]["price"]} each"""
36
37 elif action.lower() == "remove":
38 if product_name not in inventory:
39 return f"❌ Product '{product_name}' not found in inventory"
40
41 current_stock = inventory[product_name]["stock"]
42 if current_stock >= quantity:
43 inventory[product_name]["stock"] -= quantity
44 return f"""📦 **Stock Removed**
45
46📦 Product: {product_name}
47➖ Removed: {quantity} units
48📊 Remaining Stock: {inventory[product_name]["stock"]} units"""
49 else:
50 return f"❌ **Insufficient Stock**\n\n📦 Product: {product_name}\n📊 Available: {current_stock} units\n❌ Requested: {quantity} units"
51
52 elif action.lower() == "check":
53 if product_name == "all":
54 if not inventory:
55 return "📦 **Inventory Empty**\n\nNo products currently in stock."
56
57 result = "📊 **Complete Inventory Report**\n\n"
58 total_value = 0
59 for product, data in inventory.items():
60 stock_value = data["stock"] * data["price"]
61 total_value += stock_value
62 status = "🟢 In Stock" if data["stock"] > 10 else ("🟡 Low Stock" if data["stock"] > 0 else "🔴 Out of Stock")
63 result += f"📦 **{product}**\n • Stock: {data['stock']} units\n • Price: ${data["price"]}\n • Value: ${stock_value}\n • Sales: {data['sales']} units sold\n • Status: {status}\n\n"
64
65 result += f"💰 **Total Inventory Value: ${total_value}**"
66 return result
67 else:
68 if product_name in inventory:
69 data = inventory[product_name]
70 stock_value = data["stock"] * data["price"]
71 status = "🟢 In Stock" if data["stock"] > 10 else ("🟡 Low Stock" if data["stock"] > 0 else "🔴 Out of Stock")
72
73 return f"""📊 **Product Details: {product_name}**
74
75📦 Stock: {data["stock"]} units
76💰 Price: ${data["price"]} each
77📈 Total Sales: {data["sales"]} units sold
78💵 Current Value: ${stock_value}
79🚦 Status: {status}"""
80 else:
81 available = list(inventory.keys())
82 return f"❌ Product '{product_name}' not found.\n\n📦 Available products: {', '.join(available) or 'None'}"
83
84 elif action.lower() == "update_price":
85 if product_name in inventory:
86 old_price = inventory[product_name]["price"]
87 inventory[product_name]["price"] = price
88 return f"💰 **Price Updated**\n\n📦 Product: {product_name}\n💵 Old Price: ${old_price}\n💰 New Price: ${price}"
89 else:
90 return f"❌ Product '{product_name}' not found in inventory"
91
92 else:
93 return "❌ **Invalid Action**\n\nValid actions: add, remove, check, update_price\nExample: 'Add 50 laptops to inventory with price 999.99'"
94
95 except Exception as e:
96 return f"❌ **Inventory Error**: {str(e)}"
97
98def process_order(customer_name: str, customer_email: str, product: str, quantity: int) -> str:
99 """Process customer orders with full business logic."""
100 global order_counter
101
102 try:
103 # Validate inventory
104 if product not in inventory:
105 available = list(inventory.keys())
106 return f"❌ **Product Not Available**\n\n📦 '{product}' is not in our catalog\n\n🛍️ Available products: {', '.join(available) or 'None'}"
107
108 product_data = inventory[product]
109 if product_data["stock"] < quantity:
110 return f"""❌ **Insufficient Stock**
111
112📦 Product: {product}
113📊 Available: {product_data["stock"]} units
114❌ Requested: {quantity} units
115💡 Suggestion: Reduce quantity or restock inventory"""
116
117 # Calculate order details
118 unit_price = product_data["price"]
119 subtotal = unit_price * quantity
120 tax_rate = 0.08 # 8% tax
121 tax = subtotal * tax_rate
122 total = subtotal + tax
123
124 # Create order
125 order = {
126 "id": order_counter,
127 "customer_name": customer_name,
128 "customer_email": customer_email,
129 "product": product,
130 "quantity": quantity,
131 "unit_price": unit_price,
132 "subtotal": subtotal,
133 "tax": tax,
134 "total": total,
135 "status": "confirmed",
136 "date": datetime.now().isoformat(),
137 "estimated_delivery": (datetime.now() + timedelta(days=3)).strftime("%Y-%m-%d")
138 }
139
140 # Update inventory and records
141 inventory[product]["stock"] -= quantity
142 inventory[product]["sales"] += quantity
143 orders.append(order)
144
145 # Update customer records
146 if customer_email not in customers:
147 global customer_counter
148 customers[customer_email] = {
149 "id": customer_counter,
150 "name": customer_name,
151 "email": customer_email,
152 "orders": [],
153 "total_spent": 0,
154 "registration_date": datetime.now().isoformat()
155 }
156 customer_counter += 1
157
158 customers[customer_email]["orders"].append(order_counter)
159 customers[customer_email]["total_spent"] += total
160
161 # Update analytics
162 analytics["total_revenue"] += total
163 analytics["total_orders"] += 1
164
165 order_counter += 1
166
167 return f"""🎉 **Order Confirmed!**
168
169📋 **Order Details:**
170• Order ID: #{order['id']}
171• Customer: {customer_name} ({customer_email})
172• Product: {product}
173• Quantity: {quantity} units
174• Unit Price: ${unit_price}
175
176💰 **Pricing:**
177• Subtotal: ${subtotal}
178• Tax (8%): ${tax}
179• **Total: ${total}**
180
181📦 **Fulfillment:**
182• Status: Confirmed
183• Estimated Delivery: {order['estimated_delivery']}
184• Remaining Stock: {inventory[product]['stock']} units
185
186Thank you for your order! 🚚"""
187
188 except Exception as e:
189 return f"❌ **Order Processing Error**: {str(e)}"
190
191def get_business_analytics() -> str:
192 """Generate comprehensive business analytics and insights."""
193 try:
194 if not orders:
195 return "📊 **Business Analytics**\n\nNo orders processed yet. Start by processing some orders to see analytics!"
196
197 # Revenue analytics
198 total_revenue = analytics["total_revenue"]
199 total_orders = len(orders)
200 avg_order_value = total_revenue / total_orders or 0
201
202 # Product performance
203 product_sales = {}
204 product_revenue = {}
205 for order in orders:
206 product = order["product"]
207 product_sales[product] = product_sales.get(product, 0) + order["quantity"]
208 product_revenue[product] = product_revenue.get(product, 0) + order["total"]
209
210 # Top products
211 top_selling = sorted(product_sales.items(), key=lambda x: x[1], reverse=True)[:3]
212 top_revenue = sorted(product_revenue.items(), key=lambda x: x[1], reverse=True)[:3]
213
214 # Customer analytics
215 total_customers = len(customers)
216 customer_spending = []
217 for customer_data in customers.values():
218 customer_spending.append(customer_data["total_spent"])
219
220 avg_customer_value = sum(customer_spending) / len(customer_spending) or 0
221
222 # Inventory value
223 inventory_value = sum(data["stock"] * data["price"] for data in inventory.values())
224
225 # Recent orders (last 5)
226 recent_orders = sorted(orders, key=lambda x: x["date"], reverse=True)[:5]
227
228 result = f"""📊 **Business Analytics Dashboard**
229
230💰 **Financial Overview:**
231• Total Revenue: ${total_revenue}
232• Total Orders: {total_orders}
233• Average Order Value: ${avg_order_value}
234• Total Customers: {total_customers}
235• Average Customer Value: ${avg_customer_value}
236
237🏆 **Top Performing Products (by units sold):**"""
238
239 for i, (product, sales) in enumerate(top_selling, 1):
240 result += f"\n{i}. {product}: {sales} units sold"
241
242 result += "\n\n💵 **Top Revenue Generators:**"
243 for i, (product, revenue) in enumerate(top_revenue, 1):
244 result += f"\n{i}. {product}: ${revenue} revenue"
245
246 result += f"""
247
248📦 **Inventory Status:**
249• Total Inventory Value: ${inventory_value}
250• Products in Catalog: {len(inventory)}
251
252📈 **Recent Activity:**"""
253
254 for order in recent_orders:
255 result += f"\n• Order #{order['id']}: {order['customer_name']} - {order['product']} (${order["total"]})"
256
257 return result
258
259 except Exception as e:
260 return f"❌ **Analytics Error**: {str(e)}"
261
262def manage_customers(action: str, email: str = "", name: str = "") -> str:
263 """Customer relationship management."""
264 try:
265 if action.lower() == "list":
266 if not customers:
267 return "👥 **Customer Database**\n\nNo customers registered yet."
268
269 result = f"👥 **Customer Database** ({len(customers)} customers)\n\n"
270 for customer_data in customers.values():
271 order_count = len(customer_data["orders"])
272 result += f"👤 **{customer_data['name']}**\n • Email: {customer_data['email']}\n • Orders: {order_count}\n • Total Spent: ${customer_data["total_spent"]}\n • Member Since: {customer_data['registration_date'][:10]}\n\n"
273
274 return result
275
276 elif action.lower() == "lookup":
277 if email in customers:
278 customer = customers[email]
279 order_history = ""
280 for order_id in customer["orders"]:
281 order = next((o for o in orders if o["id"] == order_id), None)
282 if order:
283 order_history += f"\n • Order #{order_id}: {order['product']} x{order['quantity']} (${order["total"]}) - {order['date'][:10]}"
284
285 return f"""👤 **Customer Profile**
286
287📧 Email: {customer["email"]}
288👤 Name: {customer["name"]}
289📅 Member Since: {customer["registration_date"][:10]}
290🛍️ Total Orders: {len(customer["orders"])}
291💰 Total Spent: ${customer["total_spent"]}
292
293📋 **Order History:**{order_history or "\n • No orders yet"}"""
294 else:
295 return f"❌ Customer with email '{email}' not found in database."
296
297 else:
298 return "❌ **Invalid Action**\n\nValid actions: list, lookup\nExample: 'Look up customer john@example.com'"
299
300 except Exception as e:
301 return f"❌ **Customer Management Error**: {str(e)}"
302
303def generate_report(report_type: str) -> str:
304 """Generate various business reports."""
305 try:
306 if report_type.lower() == "daily":
307 today = datetime.now().date()
308 today_orders = [o for o in orders if datetime.fromisoformat(o["date"]).date() == today]
309 daily_revenue = sum(order["total"] for order in today_orders)
310
311 return f"""📅 **Daily Report - {today}**
312
313📊 **Today's Performance:**
314• Orders: {len(today_orders)}
315• Revenue: ${daily_revenue}
316• Average Order: ${daily_revenue}
317
318🛍️ **Order Details:**"""
319
320 elif report_type.lower() == "inventory":
321 low_stock_items = [(name, data) for name, data in inventory.items() if data["stock"] < 10]
322 out_of_stock = [(name, data) for name, data in inventory.items() if data["stock"] == 0]
323
324 result = f"""📦 **Inventory Report**
325
326⚠️ **Attention Required:**
327• Low Stock Items: {len(low_stock_items)}
328• Out of Stock Items: {len(out_of_stock)}
329
330📊 **Stock Status:**"""
331
332 if low_stock_items:
333 result += "\n\n🟡 **Low Stock (< 10 units):**"
334 for name, data in low_stock_items:
335 result += f"\n• {name}: {data['stock']} units remaining"
336
337 if out_of_stock:
338 result += "\n\n🔴 **Out of Stock:**"
339 for name, data in out_of_stock:
340 result += f"\n• {name}: URGENT - Restock needed!"
341
342 return result
343
344 else:
345 return "❌ **Invalid Report Type**\n\nAvailable reports: daily, inventory\nExample: 'Generate daily report'"
346
347 except Exception as e:
348 return f"❌ **Report Generation Error**: {str(e)}"
349
350# Create the comprehensive e-commerce management agent
351agent = Agent(
352 name="ecommerce_manager",
353 system_prompt="""You are an expert e-commerce business manager with comprehensive capabilities:
354
355🛍️ **Core Functions:**
356• Inventory Management: Add, remove, check stock, update prices
357• Order Processing: Handle customer orders with full business logic
358• Customer Management: Track customer relationships and history
359• Business Analytics: Revenue, sales, and performance insights
360• Reporting: Daily, inventory, and custom business reports
361
362💼 **Business Expertise:**
363• Calculate taxes, totals, and delivery estimates
364• Identify low stock and reorder opportunities
365• Track customer lifetime value and order patterns
366• Provide actionable business insights and recommendations
367• Maintain professional customer service standards
368
369🎯 **Communication Style:**
370• Professional yet friendly business communication
371• Clear, actionable information with proper formatting
372• Proactive suggestions for business optimization
373• Detailed explanations of business metrics and KPIs
374
375Always focus on helping grow and optimize the e-commerce business!""",
376 tools=[manage_inventory, process_order, get_business_analytics, manage_customers, generate_report]
377)
378
379if __name__ == "__main__":
380 print("=== E-commerce Manager Agent Demo ===\n")
381
382 # Demo business workflow
383 demo_commands = [
384 "Add 100 laptops to inventory with price 999.99",
385 "Add 50 wireless mice to inventory with price 29.99",
386 "Add 75 keyboards to inventory with price 79.99",
387 "Process order for John Smith (john@email.com): 2 laptops",
388 "Process order for Sarah Johnson (sarah@email.com): 5 wireless mice and 2 keyboards",
389 "Check inventory status for all products",
390 "Show me business analytics",
391 "List all customers",
392 "Generate inventory report"
393 ]
394
395 for i, command in enumerate(demo_commands, 1):
396 print(f"Command {i}: {command}")
397 response = agent.input(command)
398 print(f"Response: {response}\n")
399 print("-" * 80)
Expected Output
=== E-commerce Manager Agent Demo === Command 1: Add 100 laptops to inventory with price 999.99 Response: ✅ **Inventory Updated** 📦 Product: laptops ➕ Added: 100 units 📊 Current Stock: 100 units 💰 Price: $999.99 each Command 4: Process order for John Smith (john@email.com): 2 laptops Response: 🎉 **Order Confirmed!** 📋 **Order Details:** • Order ID: #1 • Customer: John Smith (john@email.com) • Product: laptops • Quantity: 2 units • Unit Price: $999.99 💰 **Pricing:** • Subtotal: $1999.98 • Tax (8%): $159.98 • **Total: $2159.96** 📦 **Fulfillment:** • Status: Confirmed • Estimated Delivery: 2024-03-18 • Remaining Stock: 98 units Command 7: Show me business analytics Response: 📊 **Business Analytics Dashboard** 💰 **Financial Overview:** • Total Revenue: $2759.89 • Total Orders: 2 • Average Order Value: $1379.95 • Total Customers: 2 • Average Customer Value: $1379.95 🏆 **Top Performing Products (by units sold):** 1. wireless mice: 5 units sold 2. laptops: 2 units sold 3. keyboards: 2 units sold
Enterprise Patterns
🏢 Business Logic
Complex workflows with tax calculations, delivery estimates, and multi-system coordination.
🔄 Data Relationships
Orders, customers, and inventory working together with referential integrity.
📊 Business Intelligence
Real-time analytics, performance metrics, and actionable business insights.
Enterprise Features
🛍️ Order Management
Complete order lifecycle with tax calculation and delivery tracking
👥 CRM Integration
Customer profiles, purchase history, and lifetime value tracking
📈 Advanced Analytics
Revenue tracking, product performance, and business intelligence reports
Try It Yourself
Enterprise-grade e-commerce system with full business logic and analytics