from flask import Flask, render_template, request, jsonify from agents import Agent, Runner, function_tool, OpenAIChatCompletionsModel, AsyncOpenAI, RunConfig from dotenv import load_dotenv from rich import print import os import json from typing import Dict, Any from twilio.rest import Client from datetime import datetime import random load_dotenv() # Load products with open("products.json", "r") as file: data = json.load(file) products = data["products"] # Gemini API client = AsyncOpenAI( api_key=os.getenv("GEMINI_API_KEY"), base_url="https://generativelanguage.googleapis.com/v1beta/openai/", ) model = OpenAIChatCompletionsModel( model="gemini-3.1-flash-lite-preview", openai_client=client ) config = RunConfig( model=model, tracing_disabled=True ) # ========================= TOOLS ========================= # @function_tool def search_products(query: str): """Search for products by name, category, or show all products. Return a human-readable response.""" results = [] q = query.lower().strip() # βœ… Show all products if user asks for "all products", "tamam cheezen", etc. show_all_keywords = [ "all products", "tamam products", "sab products", "tamam cheezen", "tamam saman", "sab cheezen", "all items", "sab kuch", "tamam items", "show all" ] if q in show_all_keywords: results = products # show all else: q = q.rstrip('s') # handle plurals like lamps β†’ lamp for product in products: if q in product["name"].lower() or q in product["category"].lower(): results.append(product) if not results: return "Hamare paas aapki talash ke mutabiq koi product nahi mila." response = f"Humain aapki talash ke mutabiq {len(results)} product{'s' if len(results) > 1 else ''} milay hain:\n\n" for p in results: response += f"πŸ”Ή **{p['name']}** ({p['category'].title()})\n" response += f"πŸ’° Price: β‚Ή{p['price']}\n" response += f"⭐ Rating: {p['rating']}/5\n" response += f"πŸ“ Description: {p['description']}\n" if "dimensions" in p: response += f"πŸ“ Dimensions: {p['dimensions']}\n" elif "care_level" in p: response += f"🌱 Care Level: {p['care_level']}\n" response += f"✨ Features: {', '.join(p['features'])}\n\n" return response @function_tool def filter_by_price(max_price: float, category: str = ""): """ Filter products by maximum price and optional category. Use empty string ('') for category to ignore it. """ results = [] for product in products: product_cat = product["category"].lower() user_cat = category.lower().rstrip('s') # handle "sofa" vs "sofas" if category and user_cat not in product_cat: continue if product["price"] <= max_price: results.append(product) if not results: return [{"message": "No products found under this price."}] return results @function_tool def suggest_market_for_product(product_name: str): """ Provides complete market suggestions with REAL WORKING images and all details when products are unavailable. """ # Check product availability available = any(p["name"].lower() == product_name.lower() for p in products) if available: return { "product": product_name, "available": True, "message": f"βœ… {product_name} hamari website par available hai!" } # Market database with GUARANTEED WORKING image URLs markets = [ { "name": "Decor World Karachi", "address": "Sea View Plaza, Block 9, Clifton", "maps": "https://maps.app.goo.gl/1tQb4J7XvJzXqY3W7", "image": "https://storage.googleapis.com/proudcity/mebanenc/uploads/2021/03/placeholder-image.png", # Placeholder image URL that always works "contact": "021-35876543", "hours": "10AM-10PM (Daily)", "specialty": "Mirrors, Wall Art, Home Decor" }, { "name": "Furniture Mall", "address": "Plot FL-1, Block 5, Main Clifton Road", "maps": "https://maps.app.goo.gl/7JkLz9XmY1wWqW9V8", "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/No-Image-Placeholder.svg/832px-No-Image-Placeholder.svg.png", # Wikimedia placeholder "contact": "021-35361234", "hours": "11AM-9PM (Closed Fridays)", "specialty": "Modern Furniture" } ] # Build RICH RESPONSE with images response = f"""
❌ {product_name} hamare pas available nahi, lekin aap ye markets check kar sakte hain:
""" for market in markets: response += f"""

{market['name']}

πŸ“ {market['address']}

πŸ•’ {market['hours']}

πŸ“ž {market['contact']}

Specialty: {market['specialty']}

πŸ—ΊοΈ View on Map
""" response += """
πŸ’‘ Tip: Janay se pehlay phone kar ke confirm karein
""" return { "product": product_name, "available": False, "message": response, "ui_type": "rich_market_suggestion" } @function_tool def page_links(query: str): """Return clickable page links with complete URLs for products and other pages.""" query = query.lower().strip() # Base URL - Using empty string for relative paths base_url = "" # Complete product list with all details products = [ { "id": 1, "name": "Classic 3-Seater Sofa", "category": "sofa", "price": 45000, "image": "/static/images/sofa1.webp" }, { "id": 2, "name": "Luxury Recliner Sofa", "category": "sofa", "price": 65000, "image": "/static/images/sofa2.webp" }, { "id": 3, "name": "Modern Loveseat Sofa", "category": "sofa", "price": 38000, "image": "/static/images/sofa3.webp" }, { "id": 4, "name": "Aurora Night Lamp", "category": "lamp", "price": 5500, "image": "/static/images/lamp1.webp" }, { "id": 5, "name": "Vintage Desk Lamp", "category": "lamp", "price": 4500, "image": "/static/images/lamp2.webp" }, { "id": 6, "name": "Crystal Touch Lamp", "category": "lamp", "price": 7500, "image": "/static/images/lamp3.webp" }, { "id": 7, "name": "Peace Lily", "category": "plant", "price": 2500, "image": "/static/images/plant1.webp" }, { "id": 8, "name": "Snake Plant", "category": "plant", "price": 2000, "image": "/static/images/plant2.webp" }, { "id": 9, "name": "Aloe Vera", "category": "plant", "price": 1500, "image": "/static/images/plant3.png" }, { "id": 10, "name": "Modern Glass Coffee Table", "category": "table", "price": 22000, "image": "/static/images/table1.webp" }, { "id": 11, "name": "Rustic Wood Dining Table", "category": "table", "price": 35000, "image": "/static/images/table2.png" }, { "id": 12, "name": "Compact Study Table", "category": "table", "price": 18000, "image": "/static/images/table3.webp" } ] # 1. First check for product-specific queries for product in products: if product['name'].lower() in query: return { "page": "Product Detail", "message": f"Here is the detail for {product['name']}:", "link": { "text": "πŸ‘‰ View Product Details", "url": f"{base_url}/product-detail/{product['id']}" }, "product_id": product["id"], "image": product["image"], "price": product["price"] } # 2. Check for category pages categories = { "sofa": { "url": f"{base_url}/products?category=sofa", "text": "πŸ›‹οΈ Browse All Sofas" }, "lamp": { "url": f"{base_url}/products?category=lamp", "text": "πŸ’‘ Browse All Lamps" }, "plant": { "url": f"{base_url}/products?category=plant", "text": "🌿 Browse All Plants" }, "table": { "url": f"{base_url}/products?category=table", "text": "πŸͺ‘ Browse All Tables" } } for category, details in categories.items(): if category in query: return { "page": f"{category.title()} Collection", "message": f"Browse our {category} collection:", "link": details } if "contact" in query or "help" in query or "support" in query: return { "page": "Contact Us", "link": { "text": "πŸ“ž Contact Support", "url": f"{base_url}/contact" } } elif "new" in query or "new products" in query: return { "page": "New Arrivals", "link": { "text": "πŸ†• View New Arrivals", "url": f"{base_url}/new" } } elif "shop" in query or "products" in query or "collection" in query: return { "page": "Shop Now", "link": { "text": "πŸ›οΈ Browse All Products", "url": f"{base_url}/products" } } elif "cart" in query or "basket" in query or "order" in query: return { "page": "Your Cart", "link": { "text": "πŸ›’ View Your Cart", "url": f"{base_url}/cart" } } # Default response if no match found return { "message": "I couldn't find that page. Here are some options:", "suggestions": [ "Browse sofas", "See new arrivals", "Contact support", "View my cart" ] } # ==================== UPDATED AGENT ==================== # shopper_agent = Agent( name="Enhanced Shopping Assistant", instructions=""" You are a smart shopping assistant for a furniture website in Karachi. RULES: 1. If a user mentions a product, always use `search_products` to check availability. 2. If product is found, tell the user it is available and ask for their phone number once. 3. If the user provides a phone number (in format 923XXXXXXXXX), use `handle_order` immediately. 4. If product is NOT found, use `suggest_market_for_product` to suggest nearby Karachi markets. 5. Do NOT switch to any other product unless the user explicitly mentions it. 6. Do NOT confuse a phone number with a product name. 7. Do NOT continue the chat after order confirmation is sent. EXAMPLES: User: β€œMujhe mirror chahiye” Assistant: search_products("mirror") β†’ not found β†’ suggest_market_for_product("mirror") User: β€œMujhe snake plant chahiye” Assistant: search_products("snake plant") β†’ found β†’ ask for phone number β†’ user gives β†’ handle_order() """, tools=[ search_products, filter_by_price, suggest_market_for_product, page_links, ] ) # ==================== FLASK APP ==================== # app = Flask(__name__) @app.route('/') def home(): return render_template("index.html") @app.route('/products') def products_page(): return render_template("products.html") @app.route('/cart') def cart(): return render_template("cart.html") @app.route('/checkout') def checkout(): return render_template("checkout.html") @app.route('/contact') def contact(): return render_template('contact.html') @app.route('/new') def new_arrivals(): return render_template("new.html") @app.route('/product-detail/') def product_detail(product_id): # Find the product product = next((p for p in products if p['id'] == product_id), None) if not product: return "Product not found", 404 # Debug print to console print(f"\nDisplaying product ID {product_id}:") print(f"Name: {product['name']}") print(f"Image Path: {product['image']}\n") return render_template('product-detail.html', product=product) @app.route('/chat', methods=['POST']) def chat(): user_message = request.json.get('message') response = Runner.run_sync( starting_agent=shopper_agent, input=user_message, run_config=config ) return jsonify({"reply": response.final_output}) if __name__ == '__main__': app.run(host="0.0.0.0", port=7860, debug=False)