-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
666 lines (544 loc) · 23.4 KB
/
api_server.py
File metadata and controls
666 lines (544 loc) · 23.4 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
"""
FreshlyGo AI Concierge - FastAPI Server
========================================
REST API wrapper for the CrewAI-powered shopping assistant.
Run with: uvicorn api_server:app --reload --port 8000
"""
import os
import re
import uuid
from typing import Optional, Dict, Any, List
from fastapi import FastAPI, HTTPException, Depends, Header
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from contextlib import asynccontextmanager
# Import the AI Agent
from aiagent import (
FreshlyGoConcierge,
check_freshlygo_stock,
add_to_cart,
get_all_available_products,
get_product_suggestions,
extract_recipe_ingredients,
mongo_manager
)
# ======================================
# SESSION STORE (conversation memory)
# ======================================
# In-memory session store: session_id -> { last_items_found, last_query, ... }
sessions: Dict[str, Dict[str, Any]] = {}
def get_session(session_id: str) -> Dict[str, Any]:
"""Get or create a session"""
if session_id not in sessions:
sessions[session_id] = {
"last_items_found": [],
"last_items_missing": [],
"last_query": "",
"awaiting_confirmation": False,
"history": []
}
return sessions[session_id]
# ======================================
# INTENT DETECTION
# ======================================
CONFIRM_PATTERNS = [
r'\byes\b', r'\byeah\b', r'\byep\b', r'\bsure\b', r'\bok\b', r'\bokay\b',
r'\bproceed\b', r'\bgo ahead\b', r'\badd\b.*\bcart\b', r'\bconfirm\b',
r'\bcheckout\b', r'\bplace\b.*\border\b', r'\bdo it\b', r'\bplease\b.*\badd\b',
r'\bI would like to proceed\b', r'\blet\'?s go\b', r'\bI\'?d like\b',
r'\badd (them|those|these|it|all)\b',
]
CANCEL_PATTERNS = [
r'\bno\b', r'\bnope\b', r'\bcancel\b', r'\bnevermind\b', r'\bstop\b',
r'\bdon\'?t\b', r'\bforget\b',
]
CLEAR_CART_PATTERNS = [
r'\bclear\b.*\bcart\b', r'\bempty\b.*\bcart\b', r'\bremove\b.*\ball\b',
r'\bdelete\b.*\bcart\b', r'\breset\b.*\bcart\b', r'\bclean\b.*\bcart\b',
r'\bcart\b.*\bclear\b', r'\bcart\b.*\bempty\b', r'\bcart\b.*\bremove\b',
r'\bremove everything\b', r'\bdelete everything\b',
r'\bremove all items\b', r'\bclear all items\b',
]
GREETING_PATTERNS = [
r'\b(hi|hello|hey|good morning|good evening|howdy)\b',
]
BROWSE_PATTERNS = [
r'\bshow\b', r'\bwhat.*have\b', r'\bbrowse\b', r'\blist\b', r'\bcategory\b',
r'\bavailable\b', r'\bwhat\'?s in stock\b',
]
RECIPE_PATTERNS = [
r'\b(make|cook|prepare|recipe|ingredients? for)\b',
]
def detect_intent(message: str) -> str:
"""
Detect the user's intent from their message.
Returns: 'confirm', 'cancel', 'clear_cart', 'greeting', 'browse', 'recipe', 'search'
"""
msg = message.lower().strip()
# Check clear_cart BEFORE cancel (since both may match "remove")
for pattern in CLEAR_CART_PATTERNS:
if re.search(pattern, msg, re.IGNORECASE):
return 'clear_cart'
# Check confirm first (short messages like "yes", "ok", "proceed")
for pattern in CONFIRM_PATTERNS:
if re.search(pattern, msg, re.IGNORECASE):
return 'confirm'
for pattern in CANCEL_PATTERNS:
if re.search(pattern, msg, re.IGNORECASE):
return 'cancel'
for pattern in GREETING_PATTERNS:
if re.search(pattern, msg, re.IGNORECASE):
return 'greeting'
for pattern in RECIPE_PATTERNS:
if re.search(pattern, msg, re.IGNORECASE):
return 'recipe'
for pattern in BROWSE_PATTERNS:
if re.search(pattern, msg, re.IGNORECASE):
return 'browse'
return 'search'
# ======================================
# PYDANTIC MODELS
# ======================================
class ChatRequest(BaseModel):
"""Request model for chat endpoint"""
message: str
user_id: Optional[str] = None
session_id: Optional[str] = None
include_checkout: bool = False
class ChatResponse(BaseModel):
"""Response model for chat endpoint"""
success: bool
response: str
session_id: str
intent: str
items_found: Optional[List[Dict[str, Any]]] = None
items_missing: Optional[List[str]] = None
cart_updated: bool = False
awaiting_confirmation: bool = False
class StockCheckRequest(BaseModel):
"""Request model for stock check"""
items: str # Comma-separated list
class StockCheckResponse(BaseModel):
"""Response model for stock check"""
success: bool
available_items: List[Dict[str, Any]]
missing_items: List[str]
total_available: int
total_missing: int
class ProductSuggestionsRequest(BaseModel):
"""Request model for product suggestions"""
category: Optional[str] = ""
search_term: Optional[str] = ""
limit: int = 10
class RecipeIngredientsRequest(BaseModel):
"""Request model for recipe ingredients"""
recipe_name: str
class AddToCartRequest(BaseModel):
"""Request model for adding items to cart"""
user_id: str
product_ids: List[str]
quantities: Optional[List[int]] = None
# ======================================
# FASTAPI APP SETUP
# ======================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan handler"""
print("🚀 Starting FreshlyGo AI Concierge API...")
mongo_manager.connect()
yield
print("👋 Shutting down FreshlyGo AI Concierge API...")
mongo_manager.close()
app = FastAPI(
title="FreshlyGo AI Concierge API",
description="AI-powered shopping assistant for FreshlyGo e-commerce platform",
version="2.0.0",
lifespan=lifespan
)
# CORS Configuration
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:5173",
"http://localhost:5174",
"http://localhost:3000",
"https://freshlygo-frontend.vercel.app",
"*"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global concierge instance
concierge = None
def get_concierge():
global concierge
if concierge is None:
concierge = FreshlyGoConcierge()
return concierge
# ======================================
# HELPER: Build response text
# ======================================
def build_stock_response(available: list, missing: list, context: str = "") -> str:
"""Build the strict format response for stock checks"""
available_names = [item["name"] for item in available]
if available and missing:
all_items = available_names + missing
response = f"I need {', '.join(all_items)} to fulfill your request, "
response += f"but only {', '.join(available_names)} are currently in stock at FreshlyGo. "
response += f"I have added {', '.join(available_names)} to your cart now. "
response += "Would you like to proceed to checkout with your payment details?"
elif available and not missing:
response = f"Great news! {', '.join(available_names)} {'is' if len(available_names) == 1 else 'are all'} available at FreshlyGo! "
response += f"I have added {', '.join(available_names)} to your cart. "
response += "Would you like to proceed to checkout with your payment details?"
elif missing and not available:
response = f"I'm sorry, {', '.join(missing)} {'is' if len(missing) == 1 else 'are'} not currently available at FreshlyGo. "
response += "Would you like to search for something else?"
else:
response = "I'm here to help you shop at FreshlyGo! Tell me what you'd like to buy or what recipe you want to make."
return response
def add_items_to_user_cart(user_id: str, items: list) -> Dict[str, Any]:
"""Directly add found items to user's MongoDB cart"""
if not user_id or not items:
return {"success": False, "reason": "no user_id or items"}
try:
product_ids = [item["id"] for item in items if "id" in item]
if not product_ids:
return {"success": False, "reason": "no product ids"}
result = add_to_cart.run(
user_id=user_id,
product_ids=",".join(product_ids),
quantities=",".join(["1"] * len(product_ids))
)
return result
except Exception as e:
print(f"Cart update error: {e}")
return {"success": False, "error": str(e)}
# ======================================
# API ENDPOINTS
# ======================================
@app.get("/")
async def root():
return {
"status": "online",
"service": "FreshlyGo AI Concierge",
"version": "2.0.0",
"message": "Welcome to FreshlyGo AI Shopping Assistant!"
}
@app.get("/health")
async def health_check():
db_connected = mongo_manager.connect()
return {
"status": "healthy" if db_connected else "degraded",
"database": "connected" if db_connected else "disconnected",
"ai_agent": "ready"
}
@app.post("/api/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
"""Full CrewAI agent chat (slower, more conversational)"""
try:
agent = get_concierge()
session_id = request.session_id or str(uuid.uuid4())
if request.include_checkout:
response = agent.process_with_checkout(request.message, request.user_id)
else:
response = agent.process_request(request.message, request.user_id)
return ChatResponse(
success=True,
response=response,
session_id=session_id,
intent="agent",
items_found=None,
items_missing=None,
cart_updated=False,
awaiting_confirmation=False
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/chat/quick", response_model=ChatResponse)
async def quick_chat(request: ChatRequest):
"""
Smart quick chat with intent detection, conversation memory,
and automatic cart management.
"""
try:
session_id = request.session_id or str(uuid.uuid4())
session = get_session(session_id)
message = request.message.strip()
intent = detect_intent(message)
# --------------- CONFIRM: user says "yes" / "proceed" ---------------
if intent == 'confirm' and session["awaiting_confirmation"]:
items = session["last_items_found"]
if not items:
return ChatResponse(
success=True,
response="There are no items pending. Tell me what you'd like to shop for!",
session_id=session_id,
intent=intent,
cart_updated=False,
awaiting_confirmation=False
)
# Add to MongoDB cart if user is logged in
cart_result = {"success": False}
if request.user_id:
cart_result = add_items_to_user_cart(request.user_id, items)
item_names = [item["name"] for item in items]
total_price = sum(item.get("offerPrice") or item.get("price", 0) for item in items)
response = f"✅ Done! I've added {', '.join(item_names)} to your cart.\n\n"
response += f"🛒 Cart Summary:\n"
for item in items:
price = item.get("offerPrice") or item.get("price", 0)
response += f" • {item['name']} — ₹{price}/{item.get('unit', 'unit')}\n"
response += f"\n💰 Estimated Total: ₹{total_price}\n\n"
response += "You can proceed to checkout from your cart page, or tell me if you need anything else!"
# Clear awaiting state
session["awaiting_confirmation"] = False
session["last_items_found"] = []
session["last_items_missing"] = []
return ChatResponse(
success=True,
response=response,
session_id=session_id,
intent=intent,
items_found=items,
items_missing=None,
cart_updated=True,
awaiting_confirmation=False
)
# --------------- CLEAR CART ---------------
if intent == 'clear_cart':
# Clear session state too
session["awaiting_confirmation"] = False
session["last_items_found"] = []
session["last_items_missing"] = []
return ChatResponse(
success=True,
response="🗑️ Done! I've cleared your cart. It's now empty.\n\nWould you like to start fresh? Tell me what you'd like to shop for!",
session_id=session_id,
intent=intent,
cart_updated=False,
awaiting_confirmation=False
)
# --------------- CANCEL ---------------
if intent == 'cancel':
session["awaiting_confirmation"] = False
session["last_items_found"] = []
session["last_items_missing"] = []
return ChatResponse(
success=True,
response="No problem! I've cleared the pending items. What else can I help you find?",
session_id=session_id,
intent=intent,
cart_updated=False,
awaiting_confirmation=False
)
# --------------- GREETING ---------------
if intent == 'greeting':
return ChatResponse(
success=True,
response="👋 Hello! I'm the FreshlyGo AI Concierge. I can help you find groceries, get recipe ingredients, or browse our inventory. What would you like today?",
session_id=session_id,
intent=intent,
cart_updated=False,
awaiting_confirmation=False
)
# --------------- BROWSE (show categories/products) ---------------
if intent == 'browse':
# Extract category keywords
msg_lower = message.lower()
category = ""
category_map = {
"vegetable": "Vegetables", "fruit": "Fruits", "dairy": "Dairy",
"snack": "Snacks", "grain": "Grains", "beverage": "Beverages",
"meat": "Meat", "bakery": "Bakery", "organic": "Organic",
}
for key, val in category_map.items():
if key in msg_lower:
category = val
break
if category:
result = get_product_suggestions.run(category=category, search_term="", limit=10)
else:
result = get_all_available_products.run()
products = result.get("suggestions", result.get("all_products", []))
if products:
session["last_items_found"] = products
session["awaiting_confirmation"] = True
session["last_query"] = message
response = f"Here's what we have"
if category:
response += f" in {category}"
response += " at FreshlyGo:\n\n"
for p in products[:15]: # limit display
price = p.get("offerPrice") or p.get("price", 0)
response += f" • {p['name']} — ₹{price}/{p.get('unit', 'unit')}\n"
if len(products) > 15:
response += f" ... and {len(products) - 15} more\n"
response += "\nWould you like to add any of these to your cart? Just say 'yes' to add all, or tell me specific items!"
else:
response = f"Sorry, I couldn't find products"
if category:
response += f" in the {category} category"
response += ". Try another search!"
session["awaiting_confirmation"] = False
return ChatResponse(
success=True, response=response, session_id=session_id,
intent=intent, items_found=products[:15] if products else [],
cart_updated=False, awaiting_confirmation=session["awaiting_confirmation"]
)
# --------------- RECIPE ---------------
if intent == 'recipe':
# Extract recipe name
recipe_part = message
for kw in ["make", "cook", "prepare", "recipe for", "ingredients for"]:
if kw in message.lower():
recipe_part = message.lower().split(kw)[-1].strip()
break
recipe_result = extract_recipe_ingredients.run(recipe_part)
ingredients = recipe_result.get("ingredients", [])
if ingredients and ingredients[0] != "Please specify the ingredients you need":
items_str = ", ".join(ingredients)
stock_result = check_freshlygo_stock.run(items_str)
available = stock_result.get("available_items", [])
missing = stock_result.get("missing_items", [])
has_items = len(available) > 0
# Store in session
session["last_items_found"] = available
session["last_items_missing"] = missing
session["last_query"] = message
session["awaiting_confirmation"] = False
response = f"I can definitely help you make {recipe_part}! 🍳\n\n"
response += build_stock_response(available, missing)
return ChatResponse(
success=True, response=response, session_id=session_id,
intent=intent, items_found=available, items_missing=missing,
cart_updated=has_items,
awaiting_confirmation=False
)
else:
return ChatResponse(
success=True,
response=f"I'd love to help with {recipe_part}! Could you tell me the specific ingredients you need? I'll check FreshlyGo stock for each one.",
session_id=session_id, intent=intent,
cart_updated=False, awaiting_confirmation=False
)
# --------------- SEARCH (default: direct item request) ---------------
# Clean the query: remove filler words
clean_msg = message
for filler in ["I need", "I want", "get me", "find me", "can I get", "please get", "I'd like", "show me"]:
clean_msg = re.sub(filler, "", clean_msg, flags=re.IGNORECASE)
clean_msg = clean_msg.strip().strip(".,!?")
items_to_check = clean_msg.replace(" and ", ", ").replace(";", ",").replace("&", ",")
if items_to_check:
stock_result = check_freshlygo_stock.run(items_to_check)
available = stock_result.get("available_items", [])
missing = stock_result.get("missing_items", [])
has_items = len(available) > 0
# Store in session for follow-up
session["last_items_found"] = available
session["last_items_missing"] = missing
session["last_query"] = message
session["awaiting_confirmation"] = False
response = build_stock_response(available, missing)
return ChatResponse(
success=True, response=response, session_id=session_id,
intent=intent, items_found=available, items_missing=missing,
cart_updated=has_items,
awaiting_confirmation=False
)
return ChatResponse(
success=True,
response="I'm here to help you shop at FreshlyGo! Tell me what you'd like to buy or what recipe you want to make. 🛒",
session_id=session_id, intent=intent,
cart_updated=False, awaiting_confirmation=False
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/cart/add")
async def api_add_to_cart(request: AddToCartRequest):
"""Directly add items to a user's cart via AI"""
try:
product_ids_str = ",".join(request.product_ids)
quantities_str = ",".join([str(q) for q in (request.quantities or [1] * len(request.product_ids))])
result = add_to_cart.run(
user_id=request.user_id,
product_ids=product_ids_str,
quantities=quantities_str
)
return {"success": result.get("success", False), "result": result}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/stock/check", response_model=StockCheckResponse)
async def check_stock(request: StockCheckRequest):
"""Check FreshlyGo inventory for specific items"""
try:
result = check_freshlygo_stock.run(request.items)
return StockCheckResponse(
success=True,
available_items=result.get("available_items", []),
missing_items=result.get("missing_items", []),
total_available=result.get("total_available", 0),
total_missing=result.get("total_missing", 0)
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/inventory")
async def get_inventory():
"""Get all available products organized by category"""
try:
result = get_all_available_products.run()
return {
"success": True,
"products": result.get("all_products", []),
"by_category": result.get("by_category", {}),
"total_products": result.get("total_products", 0),
"categories": result.get("categories", [])
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/products/suggestions")
async def get_suggestions(request: ProductSuggestionsRequest):
"""Get product suggestions based on category or search term"""
try:
result = get_product_suggestions.run(
category=request.category,
search_term=request.search_term,
limit=request.limit
)
return {
"success": True,
"suggestions": result.get("suggestions", []),
"total_found": result.get("total_found", 0)
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/recipe/ingredients")
async def get_recipe_ingredients(request: RecipeIngredientsRequest):
"""Get common ingredients for a recipe"""
try:
result = extract_recipe_ingredients.run(request.recipe_name)
return {
"success": True,
"recipe": result.get("recipe", request.recipe_name),
"ingredients": result.get("ingredients", []),
"total_ingredients": result.get("total_ingredients", 0),
"note": result.get("note", None)
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ======================================
# MAIN ENTRY POINT
# ======================================
if __name__ == "__main__":
import uvicorn
print("=" * 60)
print("FreshlyGo AI Concierge API Server")
print("=" * 60)
uvicorn.run(
"api_server:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)