{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "# **ShopGenie**\n", "Redifining the concept of Online shopping customer experience with agentic AI.\n", "\n", "\n", "---\n", "\n", "# Overview\n", "This AI agent , **ShopGenie** , is built on langGraph and aims to provide decisive shopping experience to all people using the power of LLM.It uses tavily for web search , and llama-3.1-70B-versatile model through groq. This ai agent is made using totally open source technologies.\n", "\n", "\n", "\n", "---\n", "\n", "# Motivation\n", "This AI agent is made to assist a customer to get best desired product specifically tailoured for his needs and wants. Eventhough if do not has any expertise in that particular field of whose product he wants to buy, still using the power of **ShopGenie** he could land for the best suited product for him.\n", "\n", "---\n", "\n", "#Key Features:\n", "- **Tavily** for web search.\n", "- **llama-3.1-70B** for arranging the data into specific schema and comparing products.\n", "- Tells the best product among the searched ones.\n", "- **Youtube API** for providing the review link of the best product for self-satisfaction.\n", "- **SMTP** for sending mail about the best product and its review to the user.\n" ], "metadata": { "id": "e7lrOBJmsrDB" } }, { "cell_type": "markdown", "source": [ "# Important packages\n", "following are the required packeages for this agent to function." ], "metadata": { "id": "Cp96Qz-b1suY" } }, { "cell_type": "code", "source": [ "%pip install langchain-groq langgraph tavily-python google-api-python-client langchain-community beautifulsoup4 > /dev/null 2>&1" ], "metadata": { "id": "f3hphuoi2CyS" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Import necessary modules" ], "metadata": { "id": "GDFX8i602M8p" } }, { "cell_type": "code", "source": [ "from langchain_groq import ChatGroq\n", "from langgraph.graph import StateGraph, START, END\n", "from tavily import TavilyClient\n", "from langchain_community.tools import TavilySearchResults\n", "from typing import List, Optional, Dict\n", "from typing_extensions import TypedDict\n", "from googleapiclient.discovery import build\n", "from google.colab import userdata\n", "from IPython.display import Image, display\n", "import getpass\n", "import os\n", "import json\n", "import bs4\n", "from langchain_community.document_loaders import WebBaseLoader\n", "from pydantic import BaseModel, HttpUrl, Field\n", "from langchain_core.output_parsers import JsonOutputParser\n", "from langchain_core.prompts import PromptTemplate\n", "import time" ], "metadata": { "id": "gE-x7ZLQ2nj2" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Setting environment variables\n", "These are the totally open source technologies used and environment variables which can be changed according to one's needs and availability" ], "metadata": { "id": "5QwldgzA2r4n" } }, { "cell_type": "code", "source": [ "groq_api_key = userdata.get('GROQ_API_KEY')\n", "tavily_api_key = userdata.get('TAVILY_API_KEY')\n", "youtube_api_key = userdata.get('YOUTUBE_API_KEY')\n", "\n", "#LLM being used in this notebook\n", "llm = ChatGroq(\n", " model=\"llama-3.1-70b-versatile\",\n", " api_key=groq_api_key,\n", " temperature=0.5,\n", ")\n", "\n", "#Tavily for web search\n", "tavily_client = TavilyClient(api_key=tavily_api_key)\n", "\n", "#Youtube api for video search\n", "youtube = build('youtube', 'v3', developerKey=youtube_api_key)" ], "metadata": { "id": "raOHipYX3Fsw" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Other Structures" ], "metadata": { "id": "APl7mXJb3d3g" } }, { "cell_type": "code", "source": [ "\n", "\n", "class SpecsComparison(BaseModel):\n", " processor: str = Field(..., description=\"Processor type and model, e.g., 'Snapdragon 888'\")\n", " battery: str = Field(..., description=\"Battery capacity and type, e.g., '4500mAh'\")\n", " camera: str = Field(..., description=\"Camera specs, e.g., '108MP primary'\")\n", " display: str = Field(..., description=\"Display type, size, refresh rate, e.g., '6.5 inch OLED, 120Hz'\")\n", " storage: str = Field(..., description=\"Storage options and expandability, e.g., '128GB, expandable'\")\n", "\n", "class RatingsComparison(BaseModel):\n", " overall_rating: float = Field(..., description=\"Overall rating out of 5, e.g., 4.5\")\n", " performance: float = Field(..., description=\"Rating for performance out of 5, e.g., 4.7\")\n", " battery_life: float = Field(..., description=\"Rating for battery life out of 5, e.g., 4.3\")\n", " camera_quality: float = Field(..., description=\"Rating for camera quality out of 5, e.g., 4.6\")\n", " display_quality: float = Field(..., description=\"Rating for display quality out of 5, e.g., 4.8\")\n", "\n", "class Comparison(BaseModel):\n", " product_name: str = Field(..., description=\"Name of the product\")\n", " specs_comparison: SpecsComparison\n", " ratings_comparison: RatingsComparison\n", " reviews_summary: str = Field(..., description=\"Summary of key points from user reviews about this product\")\n", "\n", "class BestProduct(BaseModel):\n", " product_name: str = Field(..., description=\"Name of the best product\")\n", " justification: str = Field(..., description=\"Explanation of why this product is the best choice\")\n", "\n", "class ProductComparison(BaseModel):\n", " comparisons: List[Comparison]\n", " best_product: BestProduct\n", "\n", "class Highlights(BaseModel):\n", " Camera: Optional[str] = None\n", " Performance: Optional[str] = None\n", " Display: Optional[str] = None\n", " Fast_Charging: Optional[str] = None\n", "\n", "class SmartphoneReview(BaseModel):\n", " \"\"\"A review of a smartphone.\"\"\"\n", " title: str = Field(..., description=\"The title of the smartphone review\")\n", " url: Optional[str] = Field(None, description=\"The URL of the smartphone review\")\n", " content: Optional[str] = Field(None, description=\"The main content of the smartphone review\")\n", " pros: Optional[List[str]] = Field(None, description=\"The pros of the smartphone\")\n", " cons: Optional[List[str]] = Field(None, description=\"The cons of the smartphone\")\n", " highlights: Optional[dict] = Field(None, description=\"The highlights of the smartphone\")\n", " score: Optional[float] = Field(None, description=\"The score of the smartphone\")\n", "\n", "class ListOfSmartphoneReviews(BaseModel):\n", " \"\"\"A list of smartphone reviews.\"\"\"\n", " reviews: List[SmartphoneReview] = Field(..., description=\"List of individual smartphone reviews\")\n", "\n", "class EmailRecommendation(BaseModel):\n", " subject: str = Field(..., description=\"The email subject line, designed to capture the recipient's attention.\")\n", " heading: str = Field(..., description=\"The main heading of the email, introducing the recommended product.\")\n", " justification_line: str = Field(..., description=\"A concise explanation of why the product is being recommended.\")" ], "metadata": { "id": "SnY2sbJh3t4U" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Main State" ], "metadata": { "id": "u7e-DIu13RGg" } }, { "cell_type": "code", "source": [ "class State(TypedDict):\n", " query: str\n", " email: str\n", " products: list[dict]\n", " product_schema: list[SmartphoneReview]\n", " blogs_content: Optional[List[dict]]\n", " best_product: dict\n", " comparison: list\n", " youtube_link: str" ], "metadata": { "id": "vguVK6PS3Z7n" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Sending Email\n", "This is a complete function of sending mail which takes ShopGenie to next level and speaks of its potential" ], "metadata": { "id": "6XbPJSXM7zzl" } }, { "cell_type": "code", "source": [ "import smtplib\n", "from email.mime.text import MIMEText\n", "from email.mime.multipart import MIMEMultipart\n", "from google.colab import userdata\n", "\n", "def send_email(recipient_email, subject, body):\n", " \"\"\"Send an email dynamically using SMTP.\"\"\"\n", " # SMTP server configuration\n", " smtp_server = \"smtp.gmail.com\"\n", " smtp_port = 587\n", " sender_email = userdata.get(\"GMAIL_USER\")\n", " sender_password = userdata.get(\"GMAIL_PASS\")\n", "\n", " try:\n", " # Create email content\n", " message = MIMEMultipart()\n", " message['From'] = sender_email\n", " message['To'] = recipient_email\n", " message['Subject'] = subject\n", "\n", " # Add the email body\n", " message.attach(MIMEText(body, 'html'))\n", "\n", " # Connect to the SMTP server\n", " with smtplib.SMTP(smtp_server, smtp_port) as server:\n", " server.starttls() # Start TLS encryption\n", " server.login(sender_email, sender_password) # Login to the server\n", " server.send_message(message) # Send the email\n", " print(f\"Email sent successfully to {recipient_email}.\")\n", "\n", " except Exception as e:\n", " print(f\"Failed to send email: {e}\")" ], "metadata": { "id": "boLmH2DP8Myf" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "#Email prompt template\n", "email_template_prompt = \"\"\"\n", "You are an expert email content writer.\n", "\n", "Generate an email recommendation based on the following inputs:\n", "- Product Name: {product_name}\n", "- Justification Line: {justification_line}\n", "- User Query: \"{user_query}\" (a general idea of the user's interest, such as \"a smartphone for photography\" or \"a premium gaming laptop\").\n", "\n", "Return your output in the following JSON format:\n", "{format_instructions}\n", "\n", "### Input Example:\n", "Product Name: Google Pixel 8 Pro\n", "Justification Line: Praised for its exceptional camera, advanced AI capabilities, and vibrant display.\n", "User Query: a phone with an amazing camera\n", "\n", "### Example Output:\n", "{{\n", " \"subject\": \"Capture Every Moment with Google Pixel 8 Pro\",\n", " \"heading\": \"Discover the Power of the Ultimate Photography Smartphone\",\n", " \"justification_line\": \"Known for its exceptional camera quality, cutting-edge AI features, and vibrant display, the Google Pixel 8 Pro is perfect for photography enthusiasts.\"\n", "}}\n", "\n", "Now generate the email recommendation based on the inputs provided.\n", "\"\"\"" ], "metadata": { "id": "zxa76M8X_RPF" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "#email html template\n", "email_html_template = \"\"\"\n", " \n", "
\n", " \n", " \n", " \n", "{justification}
\n", "Watch our in-depth review to explore why this phone is the best choice for you:
\n", " Watch the Review\n", "