Skip to content

A smart inventory watchdog AI Agent that monitors your e-commerce inventory 24/7. Built Using LangChain/LangGraph, GPT, Gmail, ORMCP, and PostgreSQL. ORMCP is an MCP Server providing object-oriented abstractions over relational data.

License

Notifications You must be signed in to change notification settings

SoftwareTree/ormcp_smart_inventory_agent

Repository files navigation

Smart Inventory Watchdog AI Agent

An intelligent AI assistant that monitors your e-commerce inventory 24/7, automatically alerts you when stock runs low, and uses AI to predict how much you should reorder based on sales patterns.

What is This?

Imagine you run an online store. You have hundreds of products, and you need to know when to reorder them. Manually checking inventory levels every day is tedious and error-prone. What if you had an AI assistant that:

  • Watches your inventory continuously - Never miss a low-stock situation
  • Sends you alerts automatically - Get notified via email when products need restocking
  • Predicts future needs - Uses AI to analyze your sales history and suggest optimal reorder quantities
  • Works through a simple web interface - Manage everything from a dashboard

That's exactly what this project does. It's an AI-powered inventory monitoring system that acts as your 24/7 inventory guardian.

Why Do You Need This?

Running out of stock means lost sales and unhappy customers. But ordering too much ties up capital and risks obsolescence. The Smart Inventory Watchdog solves this by:

  1. Preventing stockouts - Get alerts before you run out, not after
  2. Optimizing inventory levels - AI analyzes your sales patterns to suggest the right reorder quantities
  3. Saving time - No more manual inventory checks or guesswork
  4. Reducing costs - Better inventory management means less waste and better cash flow

What Does It Do?

Core Capabilities

Real-Time Stock Monitoring
Continuously tracks all your products and identifies items that fall below your configured threshold levels.

Intelligent Email Alerts
Automatically sends email notifications to administrators and suppliers when stock levels are low, with detailed product information and current stock status.

AI-Powered Reorder Suggestions
Analyzes historical sales data to predict future demand and suggests optimal reorder quantities using intelligent forecasting algorithms.

Web Dashboard
A user-friendly web interface where you can:

  • View real-time inventory statistics
  • Check stock levels on demand
  • See AI-generated reorder recommendations
  • Manage products (add, update, delete)
  • Configure monitoring settings

Flexible Configuration
Set different stock thresholds for different products or categories, and adjust monitoring intervals based on your needs.

How Does It Work?

The Big Picture

Think of this system as having three main parts:

  1. The AI Agent - The "brain" that makes intelligent decisions about inventory
  2. The Database Connection - How the system talks to your product database
  3. The Notification System - How it sends you alerts

The AI agent uses LangChain (a framework for building AI applications) combined with OpenAI's GPT models to understand your inventory data and make smart recommendations. It connects to your database through ORMCP Server, which enables AI assistants to interact with databases through a secure, controlled interface.

How ORMCP Works

ORMCP (Object-Relational Mapping Communication Protocol) provides a secure bridge between AI assistants and databases. Here's how the data flow works:

  1. User sends natural language request to the AI assistant (e.g., "Show me products with low stock")
  2. AI assistant translates the natural language into MCP (Model Context Protocol) tool calls
  3. ORMCP Server receives the MCP tool calls and translates them into REST API calls
  4. Gilhari microservice executes database operations via JDBC/SQL
  5. Results are returned as JSON objects through the chain back to the user

Security and Data Protection: Gilhari (via JDX) does not issue generic queries like SELECT * FROM product. Instead, it explicitly lists only the columns that are mapped in the mapping file (e.g., SELECT id, name, category, price, stock_quantity FROM product). This ensures that:

  • Private, sensitive, or protected columns (like social security numbers) are never exposed
  • Only columns relevant to the exposed object model are fetched
  • The database schema remains secure and controlled

Technical Architecture

For those interested in the technical details:

┌─────────────────────────────────────────────────────────────┐
│      Smart Inventory Watchdog AI Agent                      │
│      (LangChain + GPT-3.5-turbo)                            │
└──────────────────┬──────────────────────────────────────────┘
                   │
        ┌──────────┴──────────┐
        │                     │
   ┌────▼────┐          ┌─────▼─────┐
   │ ORMCP   │          │  Email    │
   │ Tools   │          │  Tools    │
   └────┬────┘          └─────┬─────┘
        │                     │
        └──────────┬──────────┘
                   │
        ┌──────────▼──────────┐
        │   ORMCP Server      │
        │   (Database Bridge) │
        └──────────┬──────────┘
                   │
        ┌──────────▼──────────┐
        │  Gilhari            │
        │  Microservice       │
        │  (Data Layer)       │
        └──────────┬──────────┘
                   │
        ┌──────────▼──────────┐
        │  PostgreSQL         │
        │  (Your Database)    │
        └─────────────────────┘

Hybrid Approach for Performance

The system uses a smart hybrid approach:

  • For continuous monitoring (checking stock levels every hour): Uses ORMCP tool calls (translated to REST API calls to Gilhari) for speed and reliability, with only explicitly mapped columns accessed
  • For intelligent analysis (predicting reorder quantities): Uses the AI agent for complex reasoning, which also goes through ORMCP Server to access data securely
  • For user interactions: Provides a web interface built with Flask

This gives you both the speed needed for continuous monitoring and the intelligence needed for smart recommendations, while maintaining security through controlled column access.

Note: For a detailed technical analysis of how LangChain is used in this project, see LANGCHAIN_USAGE_ANALYSIS.md.

E-commerce Data Model

This agent works with a typical e-commerce database structure. The system understands relationships between:

  • SuppliersProducts (one supplier can have many products)
  • CustomersCustomerOrders (one customer can have many orders)
  • CustomersAddresses (one customer can have multiple addresses)
  • CustomerOrdersOrderItems (one order contains many items)
  • ProductsOrderItems (products appear in multiple order items)

For more details about the complete e-commerce data model and how to set it up, see the Gilhari E-commerce Example repository.

Key Features

Real-Time Monitoring

  • Continuous stock level tracking
  • Configurable monitoring intervals
  • Automatic threshold-based alerts

Intelligent Alerts

  • Automated email notifications
  • HTML-formatted alerts with product details
  • Support for multiple recipients (admins, suppliers)
  • Gmail API and SMTP support

Predictive Analytics

  • AI-powered reorder suggestions
  • Sales velocity analysis
  • Historical trend analysis
  • Configurable analysis periods

Web Application

  • Real-time dashboard with statistics
  • On-demand inventory checks
  • Product management (CRUD operations)
  • AI recommendation display
  • Activity logging

See WEB_FRONTEND.md for complete web application documentation.

Prerequisites

Before you begin, make sure you have:

  • Python 3.8+ (compatible with Python 3.13)
  • Docker (for running the e-commerce microservice)
  • PostgreSQL database (with the e-commerce schema set up)
  • OpenAI API key (for GPT-3.5-turbo AI capabilities)
  • ORMCP Server (install with pip install ormcp-server)
  • Gmail account (optional, for email notifications - requires App Password)

Quick Start

1. Set Up the E-commerce Microservice

First, you need to set up the e-commerce database and microservice. This provides the data layer that the agent will monitor.

./setup_docker.sh

For detailed setup instructions, see the Gilhari E-commerce Example repository.

2. Start ORMCP Server

The ORMCP Server acts as a translation layer between the AI agent and your database. When you send a natural language request to the AI assistant, it translates your request into MCP tool calls. The ORMCP Server then converts these MCP tool calls into REST API calls that the Gilhari microservice can execute, ensuring secure and controlled access to your database.

./start_ormcp.sh

For more information about ORMCP Server, see:

3. Install Python Dependencies

python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

4. Configure Environment Variables

Create a .env file in the project directory:

# OpenAI (Required)
OPENAI_API_KEY=your-api-key

# ORMCP Server (Auto-configured)
GILHARI_BASE_URL=http://localhost:8081/gilhari/v1/
MCP_SERVER_NAME=InventoryWatchdog

# Email Notifications (Optional)
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
FROM_EMAIL=your-email@gmail.com
ADMIN_EMAILS=admin1@example.com,admin2@example.com

5. Start the Web Application

./start_web_app.sh

6. Access the Web Interface

Open your browser and navigate to: http://localhost:5001

Alternative: Command-Line Usage

If you prefer using the command line instead of the web interface:

python inventory_agent.py \
  --openai-api-key your-api-key \
  --ormcp-url http://localhost:8082 \
  --threshold 50 \
  --admin-emails admin@example.com

Command-Line Options

python inventory_agent.py --help

Options:
  --openai-api-key    OpenAI API key (required)
  --ormcp-url         ORMCP server URL (default: http://localhost:8082)
  --model             OpenAI model (default: gpt-3.5-turbo)
  --threshold         Default stock threshold (default: 50)
  --admin-emails      Admin email addresses for alerts
  --monitor           Run continuous monitoring
  --interval          Monitoring interval in seconds (default: 3600)
  --interactive       Run in interactive chat mode

Configuration

Environment Variables

The system reads configuration from a .env file. See the Quick Start section above for the required variables.

Monitoring Configuration

The monitoring threshold and interval can be configured through:

  • The web interface (Settings page)
  • The monitoring_config.json file
  • Command-line arguments

Available Tools

The AI agent has access to several tools for interacting with your inventory:

Database Tools (ORMCP):

  • query_products - Search and filter products
  • get_aggregate - Calculate statistics (counts, averages, etc.)
  • update_products - Modify product information
  • insert_objects - Add new products or records
  • get_object_model_summary - Understand the database structure

Notification Tools:

  • send_email_notification - Send alerts via email (supports SMTP/Gmail, HTML formatting, multiple recipients)

Usage Examples

Using the Web Application (Recommended)

./start_web_app.sh
# Access at http://localhost:5001

The web interface provides:

  • Dashboard with real-time statistics
  • Inventory management interface
  • AI-powered recommendations
  • Monitoring controls

Using the Python API

from inventory_agent import InventoryWatchdogAgent

agent = InventoryWatchdogAgent(
    openai_api_key="your-key",
    ormcp_server_url="http://localhost:8082",
    admin_emails=["admin@example.com"],
    default_threshold=50
)

agent.initialize_ormcp()
result = agent.check_and_alert(threshold=50)

Email Notifications

The system can send email alerts when inventory levels are low. To set up email notifications:

  1. For Gmail users:

    • Enable 2-factor authentication on your Google account
    • Generate an App Password (Settings → Security → App Passwords)
    • Use the App Password as SMTP_PASSWORD in your .env file
  2. For other email providers:

    • Configure the SMTP settings in your .env file

See GMAIL_SETUP.md for detailed setup instructions.

How It Works (Technical Details)

Continuous Monitoring

Uses ORMCP tool calls (which translate to REST API calls to Gilhari) for performance-critical operations. This approach provides both speed and security, as only explicitly mapped columns are accessed from the database.

Single Inventory Checks

Uses the LangChain AI agent for intelligent analysis. The AI can understand context, analyze patterns, and provide detailed recommendations.

Predictive Reordering

The AI analyzes sales trends, calculates sales velocity, and uses intelligent formulas to suggest optimal reorder quantities based on:

  • Historical sales data
  • Current stock levels
  • Sales velocity (rate of sales)
  • Configurable analysis periods

Troubleshooting

ORMCP Server Issues

  • Check if the server is running: http://localhost:8082/mcp/
  • Verify the server logs for errors
  • Ensure the ORMCP Server is properly configured

Gilhari Microservice Issues

  • Verify the microservice is running: http://localhost:8081/gilhari/v1/getObjectModelSummary/now
  • Check Docker container status: docker ps | grep gilhari_ecommerce
  • Review the microservice logs

Database Connection Issues

  • Test database connection: psql -h localhost -p 5432 -U postgres -d ecommerce -c "SELECT 1;"
  • Verify PostgreSQL is running
  • Check database credentials in configuration

Email Notification Issues

  • Verify SMTP settings in .env file
  • For Gmail, ensure you're using an App Password (not your regular password)
  • Check the application logs for email errors

Additional Resources

License

Copyright (c) 2025, Software Tree


Made with ❤️ for intelligent inventory management

About

A smart inventory watchdog AI Agent that monitors your e-commerce inventory 24/7. Built Using LangChain/LangGraph, GPT, Gmail, ORMCP, and PostgreSQL. ORMCP is an MCP Server providing object-oriented abstractions over relational data.

Topics

Resources

License

Stars

Watchers

Forks