-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaiagent.py
More file actions
733 lines (595 loc) · 25.2 KB
/
aiagent.py
File metadata and controls
733 lines (595 loc) · 25.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
"""
FreshlyGo AI Concierge - CrewAI Agent with MongoDB Atlas Integration
=====================================================================
An intelligent shopping assistant that converts user intents (recipes, meal plans,
or direct item requests) into verified shopping carts using real MongoDB data.
References: https://docs.crewai.com/
"""
import os
import re
from typing import Optional, Dict, List, Any
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError
from bson import ObjectId
from dotenv import load_dotenv
from crewai import Agent, Task, Crew, Process
from crewai.tools import tool
from langchain_google_genai import ChatGoogleGenerativeAI
# ======================================
# CONFIGURATION
# ======================================
# Load environment variables from server/.env
load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), 'server', '.env'))
# MongoDB Configuration
MONGODB_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017')
DATABASE_NAME = 'test' # Default MongoDB database name
# Gemini API Configuration
GEMINI_API_KEY = os.getenv('GEMINI_API_KEY', 'AIzaSyAPSG1MSPv88j1Dgn4xS-5IjQqmjq4DfeE')
# ======================================
# MONGODB CONNECTION MANAGER
# ======================================
class MongoDBManager:
"""Manages MongoDB Atlas connection for FreshlyGo"""
_instance = None
_client = None
_db = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def connect(self) -> bool:
"""Establish connection to MongoDB Atlas"""
try:
if self._client is None:
self._client = MongoClient(
MONGODB_URI,
serverSelectionTimeoutMS=5000,
connectTimeoutMS=10000,
socketTimeoutMS=10000
)
# Test connection
self._client.admin.command('ping')
self._db = self._client[DATABASE_NAME]
print(f"✓ Connected to MongoDB Atlas: {DATABASE_NAME}")
return True
except (ConnectionFailure, ServerSelectionTimeoutError) as e:
print(f"✗ MongoDB Connection Error: {e}")
return False
@property
def db(self):
"""Get database instance, connecting if necessary"""
if self._db is None:
self.connect()
return self._db
@property
def products(self):
"""Get products collection"""
return self.db['products']
@property
def users(self):
"""Get users collection"""
return self.db['users']
def close(self):
"""Close MongoDB connection"""
if self._client:
self._client.close()
self._client = None
self._db = None
print("✓ MongoDB connection closed")
# Global MongoDB Manager instance
mongo_manager = MongoDBManager()
# ======================================
# LLM SETUP (Gemini)
# ======================================
gemini_llm = ChatGoogleGenerativeAI(
model="gemini-1.5-flash",
verbose=True,
temperature=0.4,
google_api_key=GEMINI_API_KEY
)
# ======================================
# FRESHLYGO TOOLS - MongoDB Integration
# ======================================
@tool("check_freshlygo_stock")
def check_freshlygo_stock(items: str) -> Dict[str, Any]:
"""
Checks the FreshlyGo MongoDB database for item availability.
Args:
items: Comma-separated list of items to check (e.g., "milk, eggs, tomatoes, microgreens")
Returns:
Dictionary containing:
- available_items: List of items found in stock with their details
- missing_items: List of items not found or out of stock
- platform: "FreshlyGo"
"""
try:
mongo_manager.connect()
products_collection = mongo_manager.products
# Parse requested items
requested_items = [item.strip().lower() for item in items.split(",") if item.strip()]
available_items = []
missing_items = []
for item in requested_items:
# Search for product by name (case-insensitive partial match)
product = products_collection.find_one({
"name": {"$regex": item, "$options": "i"},
"instock": True
})
if product:
available_items.append({
"id": str(product["_id"]),
"name": product["name"],
"price": product.get("price", 0),
"offerPrice": product.get("offerPrice"),
"unit": product.get("unit", "unit"),
"category": product.get("category", []),
"verifiedFresh": product.get("verifiedFresh", {}).get("enabled", False)
})
else:
# Check if item exists but is out of stock
out_of_stock = products_collection.find_one({
"name": {"$regex": item, "$options": "i"},
"instock": False
})
if out_of_stock:
missing_items.append(f"{item} (out of stock)")
else:
missing_items.append(item)
return {
"available_items": available_items,
"missing_items": missing_items,
"total_available": len(available_items),
"total_missing": len(missing_items),
"platform": "FreshlyGo"
}
except Exception as e:
return {
"error": str(e),
"available_items": [],
"missing_items": requested_items if 'requested_items' in locals() else [],
"platform": "FreshlyGo"
}
@tool("add_to_cart")
def add_to_cart(user_id: str, product_ids: str, quantities: str = "") -> Dict[str, Any]:
"""
Adds items to a user's cart in the FreshlyGo MongoDB database.
Args:
user_id: The MongoDB ObjectId of the user (as string)
product_ids: Comma-separated list of product IDs to add
quantities: Comma-separated list of quantities (defaults to 1 for each)
Returns:
Dictionary with cart update status and details
"""
try:
mongo_manager.connect()
users_collection = mongo_manager.users
products_collection = mongo_manager.products
# Parse product IDs and quantities
product_id_list = [pid.strip() for pid in product_ids.split(",") if pid.strip()]
quantity_list = [int(q.strip()) if q.strip() else 1 for q in quantities.split(",")] if quantities else [1] * len(product_id_list)
# Ensure quantities list matches product list
while len(quantity_list) < len(product_id_list):
quantity_list.append(1)
# Find or create cart items structure
user = users_collection.find_one({"_id": ObjectId(user_id)})
if not user:
return {"success": False, "error": "User not found", "platform": "FreshlyGo"}
current_cart = user.get("cartItems", {})
added_items = []
failed_items = []
for pid, qty in zip(product_id_list, quantity_list):
try:
# Verify product exists and is in stock
product = products_collection.find_one({
"_id": ObjectId(pid),
"instock": True
})
if product:
# Update cart (add or increment quantity)
if pid in current_cart:
current_cart[pid] = current_cart[pid] + qty
else:
current_cart[pid] = qty
added_items.append({
"id": pid,
"name": product["name"],
"quantity": current_cart[pid],
"price": product.get("price", 0)
})
else:
failed_items.append(pid)
except Exception as e:
failed_items.append(f"{pid} (error: {str(e)})")
# Update user's cart in database
if added_items:
users_collection.update_one(
{"_id": ObjectId(user_id)},
{"$set": {"cartItems": current_cart}}
)
return {
"success": True,
"added_items": added_items,
"failed_items": failed_items,
"cart_total_items": len(current_cart),
"platform": "FreshlyGo"
}
except Exception as e:
return {
"success": False,
"error": str(e),
"platform": "FreshlyGo"
}
@tool("get_product_suggestions")
def get_product_suggestions(category: str = "", search_term: str = "", limit: int = 10) -> Dict[str, Any]:
"""
Gets product suggestions from FreshlyGo based on category or search term.
Args:
category: Product category to filter by (e.g., "Fruits", "Vegetables", "Dairy")
search_term: Search term to find products
limit: Maximum number of results to return
Returns:
Dictionary with suggested products
"""
try:
mongo_manager.connect()
products_collection = mongo_manager.products
query = {"instock": True}
if category:
query["category"] = {"$regex": category, "$options": "i"}
if search_term:
query["name"] = {"$regex": search_term, "$options": "i"}
products = list(products_collection.find(query).limit(limit))
suggestions = []
for product in products:
suggestions.append({
"id": str(product["_id"]),
"name": product["name"],
"price": product.get("price", 0),
"offerPrice": product.get("offerPrice"),
"category": product.get("category", []),
"unit": product.get("unit", "unit"),
"verifiedFresh": product.get("verifiedFresh", {}).get("enabled", False)
})
return {
"suggestions": suggestions,
"total_found": len(suggestions),
"platform": "FreshlyGo"
}
except Exception as e:
return {
"error": str(e),
"suggestions": [],
"platform": "FreshlyGo"
}
@tool("extract_recipe_ingredients")
def extract_recipe_ingredients(recipe_name: str) -> Dict[str, Any]:
"""
Extracts common ingredients needed for a given recipe.
Args:
recipe_name: Name of the recipe (e.g., "omelette", "tomato soup", "pasta")
Returns:
Dictionary with list of commonly required ingredients
"""
# Common recipe ingredient mappings
recipe_ingredients = {
"omelette": ["eggs", "butter", "salt", "pepper", "onion", "tomato", "cheese"],
"tomato soup": ["tomatoes", "onion", "garlic", "butter", "cream", "salt", "pepper", "basil"],
"pasta": ["pasta", "tomatoes", "garlic", "olive oil", "onion", "basil", "parmesan", "salt"],
"pancakes": ["flour", "eggs", "milk", "butter", "sugar", "baking powder"],
"salad": ["lettuce", "tomatoes", "cucumber", "onion", "olive oil", "lemon"],
"smoothie": ["banana", "milk", "yogurt", "honey", "berries"],
"sandwich": ["bread", "butter", "lettuce", "tomato", "cheese", "mayonnaise"],
"fried rice": ["rice", "eggs", "onion", "garlic", "soy sauce", "vegetables", "oil"],
"ginger garlic paste": ["ginger", "garlic", "oil", "salt"],
"curry": ["onion", "tomato", "garlic", "ginger", "oil", "spices", "salt"],
"biryani": ["rice", "onion", "tomato", "yogurt", "spices", "oil", "garlic", "ginger"],
"dal": ["lentils", "onion", "tomato", "garlic", "turmeric", "oil", "salt"],
"paratha": ["flour", "oil", "salt", "water"],
"chai": ["tea", "milk", "sugar", "ginger", "cardamom"],
}
recipe_lower = recipe_name.lower()
# Find matching recipe
for recipe, ingredients in recipe_ingredients.items():
if recipe in recipe_lower or recipe_lower in recipe:
return {
"recipe": recipe_name,
"ingredients": ingredients,
"total_ingredients": len(ingredients)
}
# Default generic ingredients for unknown recipes
return {
"recipe": recipe_name,
"ingredients": ["Please specify the ingredients you need"],
"note": "Recipe not in database. Please list specific ingredients.",
"total_ingredients": 0
}
@tool("get_all_available_products")
def get_all_available_products() -> Dict[str, Any]:
"""
Gets all available products from FreshlyGo inventory.
Returns:
Dictionary with all in-stock products organized by category
"""
try:
mongo_manager.connect()
products_collection = mongo_manager.products
products = list(products_collection.find({"instock": True}))
# Organize by category
by_category = {}
all_products = []
for product in products:
product_info = {
"id": str(product["_id"]),
"name": product["name"],
"price": product.get("price", 0),
"offerPrice": product.get("offerPrice"),
"unit": product.get("unit", "unit")
}
all_products.append(product_info)
categories = product.get("category", ["Uncategorized"])
for cat in categories:
if cat not in by_category:
by_category[cat] = []
by_category[cat].append(product_info)
return {
"all_products": all_products,
"by_category": by_category,
"total_products": len(all_products),
"categories": list(by_category.keys()),
"platform": "FreshlyGo"
}
except Exception as e:
return {
"error": str(e),
"all_products": [],
"platform": "FreshlyGo"
}
# ======================================
# FRESHLYGO AI CONCIERGE AGENT
# ======================================
CONCIERGE_BACKSTORY = """
You are the FreshlyGo AI Concierge, an intelligent shopping assistant for the FreshlyGo e-commerce platform.
Your mission is to provide a seamless shopping experience by converting user intents (recipes, meal plans,
or direct item requests) into verified shopping carts.
CORE LOGIC & WORKFLOW:
1. Intent Analysis: Identify exactly what the user wants to buy. If they provide a recipe, extract all
necessary ingredients. If they ask for specific items (e.g., "grapes" or "microgreens"), identify
those individual products.
2. Inventory Verification: Use the check_freshlygo_stock tool to cross-reference the required items
with the FreshlyGo live database.
3. Cart Management: Automatically add all available items to the user's digital cart. Keep a precise
list of any items that are missing or out of stock.
RESPONSE REQUIREMENTS:
- Tone: Helpful, professional, and transparent.
- Acknowledgment: Always start by acknowledging the user's specific request.
- Transparency: Clearly distinguish between what was added and what couldn't be found.
- Closing: Always provide a clear next step, typically prompting the user to confirm their cart
or proceed to checkout.
STRICT OUTPUT FORMAT (when items are missing):
"I need [List of all required items] to fulfill your request, but only [List of available items] are
currently in stock at FreshlyGo. I have added [Available items] to your cart now. Would you like to
proceed to checkout with your payment details?"
VERSATILITY:
Do not limit yourself to recipes. You must be equally helpful if a user asks for individual snacks,
household essentials, or produce like "microgreens" or "grapes."
"""
class FreshlyGoAgents:
"""Agent definitions for FreshlyGo AI Concierge"""
def concierge_agent(self):
"""Main AI Concierge agent for FreshlyGo"""
return Agent(
role='FreshlyGo AI Concierge',
goal='Help users find and cart groceries based on recipes or direct requests, using the real FreshlyGo inventory.',
backstory=CONCIERGE_BACKSTORY,
tools=[
check_freshlygo_stock,
add_to_cart,
get_product_suggestions,
extract_recipe_ingredients,
get_all_available_products
],
llm=gemini_llm,
verbose=True,
allow_delegation=False,
max_iter=10
)
def checkout_agent(self):
"""Checkout manager agent for finalizing orders"""
return Agent(
role='FreshlyGo Checkout Manager',
goal='Summarize the cart contents and guide user through checkout process.',
backstory="""You are the FreshlyGo Checkout Manager. Your role is to:
1. Summarize all items that have been added to the cart
2. Calculate estimated totals if prices are available
3. Guide the user to proceed with payment (COD, UPI, or Card)
4. Ensure a smooth checkout experience
Always be professional and provide clear next steps for completing the purchase.""",
llm=gemini_llm,
verbose=True,
allow_delegation=False
)
# ======================================
# TASK DEFINITIONS
# ======================================
class FreshlyGoTasks:
"""Task definitions for FreshlyGo AI workflows"""
def process_user_request_task(self, agent, user_input: str, user_id: Optional[str] = None):
"""Task to process user's shopping request"""
context = f"User ID: {user_id}" if user_id else "Guest User (cart preview only)"
return Task(
description=f"""
Process the following user request: "{user_input}"
Context: {context}
Steps:
1. Analyze the user's intent (recipe, specific items, or general shopping)
2. If it's a recipe, extract the required ingredients
3. Check FreshlyGo stock for all required items using check_freshlygo_stock tool
4. Report which items are available and which are missing
5. If user_id is provided, add available items to their cart
Follow the response format strictly:
- Acknowledge the request
- List what was found vs what's missing
- Confirm items added to cart
- Prompt for checkout if appropriate
""",
expected_output="""A response following this format:
'I can definitely help you with that! I need [all required items] to fulfill your request.
After checking FreshlyGo inventory, [available items] are currently in stock and have been
added to your cart. Unfortunately, [missing items] are not available at this time.
Would you like to proceed to checkout with your payment details?'""",
agent=agent
)
def finalize_checkout_task(self, agent, cart_summary: str):
"""Task to finalize checkout"""
return Task(
description=f"""
Finalize the checkout process for the following cart:
{cart_summary}
Steps:
1. Summarize all items in the cart
2. Provide estimated total if prices are available
3. List available payment options (COD, UPI, Card)
4. Guide user to complete the purchase
""",
expected_output="""A professional checkout summary with:
- List of items and quantities
- Estimated total
- Payment options
- Clear call-to-action to complete purchase""",
agent=agent
)
# ======================================
# MAIN EXECUTION INTERFACE
# ======================================
class FreshlyGoConcierge:
"""Main interface for FreshlyGo AI Concierge"""
def __init__(self):
self.agents = FreshlyGoAgents()
self.tasks = FreshlyGoTasks()
self._ensure_connection()
def _ensure_connection(self):
"""Ensure MongoDB connection is established"""
if not mongo_manager.connect():
print("⚠ Warning: Could not connect to MongoDB. Using limited functionality.")
def process_request(self, user_input: str, user_id: Optional[str] = None) -> str:
"""
Process a user's shopping request.
Args:
user_input: User's message (recipe, item list, or general query)
user_id: Optional user ID for cart operations
Returns:
AI Concierge response
"""
try:
# Initialize agent
concierge = self.agents.concierge_agent()
# Create task
task = self.tasks.process_user_request_task(concierge, user_input, user_id)
# Create and run crew
crew = Crew(
agents=[concierge],
tasks=[task],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
return str(result)
except Exception as e:
return f"I apologize, but I encountered an issue processing your request: {str(e)}. Please try again."
def process_with_checkout(self, user_input: str, user_id: Optional[str] = None) -> str:
"""
Process request and include checkout flow.
Args:
user_input: User's message
user_id: Optional user ID for cart operations
Returns:
Full shopping and checkout response
"""
try:
# Initialize agents
concierge = self.agents.concierge_agent()
checkout_manager = self.agents.checkout_agent()
# Create tasks
shopping_task = self.tasks.process_user_request_task(concierge, user_input, user_id)
checkout_task = self.tasks.finalize_checkout_task(checkout_manager, "Items from previous task")
# Create and run crew
crew = Crew(
agents=[concierge, checkout_manager],
tasks=[shopping_task, checkout_task],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
return str(result)
except Exception as e:
return f"I apologize, but I encountered an issue: {str(e)}. Please try again."
def quick_stock_check(self, items: str) -> Dict[str, Any]:
"""
Quick stock check without full agent processing.
Args:
items: Comma-separated list of items
Returns:
Stock availability dictionary
"""
return check_freshlygo_stock.run(items)
def get_inventory(self) -> Dict[str, Any]:
"""Get full FreshlyGo inventory"""
return get_all_available_products.run()
def close(self):
"""Close database connections"""
mongo_manager.close()
# ======================================
# CONVENIENCE FUNCTIONS
# ======================================
def start_freshlygo_agent(user_input: str, user_id: Optional[str] = None) -> str:
"""
Start FreshlyGo AI Concierge with a user request.
Args:
user_input: User's shopping request or recipe
user_id: Optional user ID for cart operations
Returns:
AI Concierge response
"""
concierge = FreshlyGoConcierge()
try:
return concierge.process_request(user_input, user_id)
finally:
concierge.close()
def check_stock(items: str) -> Dict[str, Any]:
"""
Quick stock check for items.
Args:
items: Comma-separated list of items
Returns:
Stock availability dictionary
"""
return check_freshlygo_stock.run(items)
def get_inventory() -> Dict[str, Any]:
"""Get full FreshlyGo inventory"""
return get_all_available_products.run()
# ======================================
# MAIN ENTRY POINT
# ======================================
if __name__ == "__main__":
print("=" * 60)
print("FreshlyGo AI Concierge - Powered by CrewAI & MongoDB Atlas")
print("=" * 60)
# Initialize concierge
concierge = FreshlyGoConcierge()
# Example requests to test
test_requests = [
"I want to make an omelette",
"I need microgreens and grapes",
"Can you help me get ingredients for tomato soup?",
]
print("\n--- Testing with sample request ---")
user_request = test_requests[0]
print(f"\nUser: {user_request}")
print("-" * 40)
result = concierge.process_request(user_request)
print(f"\nAI Concierge Response:\n{result}")
# Cleanup
concierge.close()
print("\n" + "=" * 60)
print("Session ended. Thank you for using FreshlyGo!")
print("=" * 60)