ShoppingGPT

repository·main·Indexed 40 days ago

https://github.com/hoanganhvu123/shoppinggpt

An AI-powered intelligent shopping assistant using Gemini, RAG (SQLite and FAISS), and semantic routing. It provides context-aware product recommendations and policy information via a Flask-based web interface, utilizing a modular architecture to route queries between general chitchat and specialized shopping tasks.

Tokens
1.6K
Snippets
6
Records
10
Agent score
51%

What's inside ShoppingGPT

  1. How ShoppingGPT's system architecture works

    main

    ShoppingGPT uses a modular architecture to route queries between general conversation and specialized shopping tasks:

    1. User Interface: A Flask web app that handles input/output.
    2. Semantic Router: Uses GoogleGenerativeAIEmbeddings and the semantic-router library to classify queries using cosine similarity. It uses a fine-tuned Hugging Face model (hang1704/opendaisy) to distinguish between 'chitchat' and 'product-related' queries.
    3. Query Handlers:
      • Chitchat Chain: Handles general conversation using Gemini-1.5-flash and ConversationBufferMemory.
      • Shopping Agent: Handles product queries using two tools:
        • Product Search Tool: Queries a SQLite database via the ProductDataLoader class.
        • Policy Search Tool: Performs similarity searches on company policies using a FAISS vector store.
    4. Data Storage: Uses SQLite for product data and FAISS for policy information.
  2. Customize ShoppingGPT data and behavior

    main

    You can tailor the assistant to your specific business needs by modifying the following files:

    • Inventory: Update data/products.db (SQLite) with your own product records.
    • Company Policies: Edit data/policy.txt to change the guidelines the agent uses for policy searches.
    • Agent Logic/Prompts: Modify the prompt templates located in:
      • shoppinggpt/tool/product_search.py
      • shoppinggpt/tool/policy_search.py
  3. Install and set up ShoppingGPT

    main

    Follow these steps to set up the ShoppingGPT environment locally:

    1. Clone the repository:
      git clone https://github.com/yourusername/ShoppingGPT.git
      cd ShoppingGPT
    2. Create and activate a virtual environment:
      python -m venv venv
      source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
    3. Install dependencies:
      pip install -r requirements.txt
    4. Configure environment variables: Create a .env file in the root directory and add your Google API key:
      GOOGLE_API_KEY=your_google_api_key
    5. Initialize the database: Run the initialization script to set up the SQLite database:
      python scripts/init_db.py
    git clone https://github.com/yourusername/ShoppingGPT.git
    cd ShoppingGPT
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    # Create .env with GOOGLE_API_KEY
    python scripts/init_db.py
  4. Run and use ShoppingGPT

    main

    To launch the ShoppingGPT application and interact with the chatbot:

    1. Start the Flask server:
      python app.py
    2. Access the interface: Open your browser and navigate to http://localhost:5000.
    3. Interact:
      • Product queries: "What red shirts do you have in stock?"
      • Policy queries: "What's your return policy?"
      • General conversation: "How's the weather today?"
    python app.py
  5. Troubleshoot ShoppingGPT issues

    main

    If the application is not working as expected, check the following:

    • Environment Variables: Ensure GOOGLE_API_KEY is correctly set in your .env file.
    • Console Logs: Check the terminal output for error messages.
    • File Locations: Verify that data/products.db and data/policy.txt exist in their expected locations.
    • Dependencies: Confirm all requirements were installed via pip install -r requirements.txt.
    • Python Version: Ensure you are using Python 3.7 or higher.
  6. Product data schema in SQLite

    main

    The product information stored in the SQLite database follows this structure:

    FieldTypeDescription
    product_codeTEXTUnique identifier
    product_nameTEXTName of the product
    materialTEXTMaterial composition
    sizeTEXTAvailable sizes
    colorTEXTAvailable colors
    brandTEXTManufacturer or seller
    genderTEXTTarget gender
    stock_quantityINTEGERQuantity in stock
    priceREALProduct price
  7. Run the ShoppingGPT chat loop via main()

    main

    The main() function provides a command-line interface (CLI) for interacting with the system. It runs an infinite loop that:

    • Accepts user input via the terminal.
    • Terminates the session if the user types exit.
    • Uses np.errstate(invalid='ignore') to suppress potential RuntimeWarning issues during semantic routing.
    • Prints the AI's response prefixed by the detected route type.
    if __name__ == "__main__":
        main()
  8. Handle user queries with handle_query()

    main

    The handle_query(query: str) function is the core logic for processing user input. It performs the following steps:

    1. Routing: Uses SEMANTIC_ROUTER.guide(query) to determine if the query is a product request (PRODUCT_ROUTE_NAME) or general chitchat (CHITCHAT_ROUTE_NAME).
    2. Execution:
      • If CHITCHAT_ROUTE_NAME: Invokes a chitchat chain created via create_chitchat_chain(LLM, SHARED_MEMORY).
      • If PRODUCT_ROUTE_NAME: Invokes a ShoppingAgent(LLM, SHARED_MEMORY).
    3. Memory Management: Automatically updates SHARED_MEMORY (a ConversationBufferMemory instance) by adding both the user's query and the AI's response.
    4. Response Extraction: Normalizes the response content from various possible formats (LangChain message objects, dictionaries with an output key, or raw strings).

    Returns a dictionary containing the response text and the route type used.

    result = handle_query("What is the best running shoe?")
    print(f"Response: {result['response']}")
    print(f"Route: {result['type']}")
  9. Get bot responses via the /get API endpoint

    main

    The application exposes a GET endpoint at /get to retrieve bot responses programmatically.

    Query Parameter:

    • msg (string): The user's message to be processed.

    Returns: A JSON object containing:

    • response: The text content of the bot's reply.
    • type: The semantic route identified for the query.

    Example Request: GET /get?msg=I want to buy a laptop

    # Example curl command to call the API
    curl "http://localhost:5000/get?msg=Hello"