Skip to main content

Overview

Automate inventory monitoring across retailers to ensure you never miss out on restocks of popular or hard-to-find items.

Real-Time Stock Checker

Check current availability across multiple retailers.
import { AGIClient } from 'agi';

const client = new AGIClient({ apiKey: 'your_api_key' });
const session = await client.createSession('agi-0-fast');

const retailers = ["Amazon", "Best Buy", "Target", "Walmart", "Newegg"];
const result = await session.runTask(`
    Check stock availability for: PlayStation 5

    Retailers: ${retailers.join(', ')}

    For each retailer, find: Online Availability (in stock, quantity, delivery date, shipping), Store Availability (in-store status, locations, pickup), Variants (colors/sizes in/out of stock, backorder), Purchase Options (price, total cost, fastest delivery, cheapest).

    Return as JSON with product, timestamp, retailers array, and summary (available_count, total_checked, best_overall).
`);

await session.delete();

Automated Restock Alerts

Monitor for product restocks and receive notifications.
import { AGIClient } from 'agi';

const client = new AGIClient({ apiKey: 'your_api_key' });

async function checkStock(productName, urls) {
    const session = await client.createSession('agi-0-fast');
    try {
        const result = await session.runTask(`
            Check stock availability for: ${productName}
            URLs: ${urls.join(', ')}

            For each URL: Check if in stock, which variants available, current price, purchase limits, direct "Add to Cart" link if in stock.

            Return JSON array with in_stock, available_variants, retailer, price, url, add_to_cart_url, limit.
        `);
        return result;
    } finally {
        await session.delete();
    }
}

// Usage: Check stock periodically
const stockStatus = await checkStock('NVIDIA RTX 4090', [
    'https://www.amazon.com/...',
    'https://www.bestbuy.com/...'
]);
For full monitoring implementations with classes, see the complete example below (Python only for reference):
import time
from datetime import datetime

class RestockMonitor:
    def __init__(self, api_key, notification_callback):
        """
        Initialize restock monitor

        Args:
            api_key: AGI API key
            notification_callback: Function to call when item is in stock
        """
        self.api_key = api_key
        self.notification_callback = notification_callback
        self.tracked_items = {}
        self.check_interval = 300  # 5 minutes

    def add_item(self, product_name, urls, desired_variants=None):
        """Add item to monitoring"""
        self.tracked_items[product_name] = {
            'urls': urls,
            'desired_variants': desired_variants or [],
            'last_status': None,
            'out_of_stock_since': None
        }

    def check_item(self, product_name):
        """Check stock status for a single item"""
        item = self.tracked_items[product_name]
        session_id = create_session(self.api_key, agent_name="agi-0-fast")

        try:
            urls_str = '\n'.join(f'- {url}' for url in item['urls'])
            variants_str = '\n'.join(f'- {v}' for v in item['desired_variants']) if item['desired_variants'] else "All variants"

            send_message(session_id, f"""
                Check stock availability for: {product_name}

                URLs to check:
                {urls_str}

                Desired variants:
                {variants_str}

                For each URL:
                1. Check if in stock
                2. Check which variants are available
                3. Get current price
                4. Note any purchase limits
                5. Get direct "Add to Cart" link if in stock

                Return JSON:
                {{
                    "in_stock": true/false,
                    "available_variants": [...],
                    "retailer": "...",
                    "price": X.XX,
                    "url": "...",
                    "add_to_cart_url": "...",
                    "limit": "..."
                }}

                Return array with results from all URLs.
            """)

            result = wait_for_completion(session_id, timeout=60)

            # Check if any desired variants are in stock
            in_stock = False
            for retailer_result in result:
                if retailer_result['in_stock']:
                    if not item['desired_variants']:
                        in_stock = True
                        break
                    else:
                        available = set(retailer_result['available_variants'])
                        desired = set(item['desired_variants'])
                        if available & desired:  # Intersection
                            in_stock = True
                            break

            # Track status changes
            if in_stock and item['last_status'] == 'out_of_stock':
                # Item just came back in stock!
                self.notification_callback({
                    'event': 'restock',
                    'product': product_name,
                    'details': result,
                    'out_of_stock_duration': datetime.now() - item['out_of_stock_since'] if item['out_of_stock_since'] else None
                })
                item['out_of_stock_since'] = None
            elif not in_stock and item['last_status'] != 'out_of_stock':
                item['out_of_stock_since'] = datetime.now()

            item['last_status'] = 'in_stock' if in_stock else 'out_of_stock'

            return result

        finally:
            delete_session(session_id)

    def monitor(self, duration_hours=None):
        """
        Start monitoring all tracked items

        Args:
            duration_hours: How long to monitor (None = indefinite)
        """
        start_time = datetime.now()

        print(f"Starting inventory monitoring for {len(self.tracked_items)} items...")

        while True:
            # Check if duration limit reached
            if duration_hours and (datetime.now() - start_time).total_seconds() > duration_hours * 3600:
                print("Monitoring duration reached. Stopping.")
                break

            # Check each item
            for product_name in self.tracked_items.keys():
                try:
                    print(f"Checking {product_name}...")
                    self.check_item(product_name)
                except Exception as e:
                    print(f"Error checking {product_name}: {str(e)}")

            # Wait before next check
            time.sleep(self.check_interval)

# Usage
def send_restock_notification(event_data):
    """Send notification when item is back in stock"""
    product = event_data['product']
    details = event_data['details']

    # Send email, SMS, or push notification
    print(f"🎉 RESTOCK ALERT: {product} is back in stock!")

    for result in details:
        if result['in_stock']:
            print(f"  - {result['retailer']}: ${result['price']}")
            print(f"    Buy now: {result['add_to_cart_url']}")

monitor = RestockMonitor(API_KEY, send_restock_notification)

# Add items to track
monitor.add_item(
    "NVIDIA RTX 4090",
    urls=[
        "https://www.amazon.com/...",
        "https://www.bestbuy.com/...",
        "https://www.newegg.com/..."
    ]
)

monitor.add_item(
    "PlayStation 5",
    urls=["https://direct.playstation.com/..."],
    desired_variants=["Standard Edition", "Digital Edition"]
)

# Start monitoring
monitor.monitor(duration_hours=24)

Batch Stock Checker

Check inventory for multiple products at once.
const products = [
    "iPhone 15 Pro",
    "iPad Air M2",
    "Apple Watch Series 9",
    "AirPods Pro 2"
];

const result = await session.runTask(`
    Check inventory at Apple Store for these products: ${products.join(', ')}

    For each product: Search for product, Check stock status, Get current price, Note if on sale, Get product URL.

    Return as JSON array with product, in_stock, price, on_sale, original_price, url, estimated_delivery.

    Order results by availability (in-stock items first).
`);

Historical Stock Tracking

Track stock patterns over time to predict restocks.
import json
from datetime import datetime, timedelta

class StockHistoryTracker:
    def __init__(self, api_key, storage_file='stock_history.json'):
        self.api_key = api_key
        self.storage_file = storage_file
        self.history = self._load_history()

    def _load_history(self):
        """Load historical data from file"""
        try:
            with open(self.storage_file, 'r') as f:
                return json.load(f)
        except FileNotFoundError:
            return {}

    def _save_history(self):
        """Save historical data to file"""
        with open(self.storage_file, 'w') as f:
            json.dump(self.history, f, indent=2)

    def record_stock_check(self, product_name, retailer, in_stock, metadata=None):
        """Record a stock check"""
        key = f"{product_name}:{retailer}"

        if key not in self.history:
            self.history[key] = {
                'product': product_name,
                'retailer': retailer,
                'checks': []
            }

        self.history[key]['checks'].append({
            'timestamp': datetime.now().isoformat(),
            'in_stock': in_stock,
            'metadata': metadata or {}
        })

        self._save_history()

    def analyze_patterns(self, product_name, retailer):
        """Analyze stock patterns for predictions"""
        key = f"{product_name}:{retailer}"

        if key not in self.history or len(self.history[key]['checks']) < 10:
            return {"error": "Insufficient data for analysis"}

        checks = self.history[key]['checks']

        # Calculate stock availability rate
        in_stock_count = sum(1 for c in checks if c['in_stock'])
        availability_rate = (in_stock_count / len(checks)) * 100

        # Find restock events
        restocks = []
        for i in range(1, len(checks)):
            if not checks[i-1]['in_stock'] and checks[i]['in_stock']:
                restocks.append({
                    'date': checks[i]['timestamp'],
                    'out_of_stock_duration': self._calculate_duration(
                        checks[i-1]['timestamp'],
                        checks[i]['timestamp']
                    )
                })

        # Calculate average restock interval
        if len(restocks) > 1:
            intervals = []
            for i in range(1, len(restocks)):
                interval = self._calculate_duration(
                    restocks[i-1]['date'],
                    restocks[i]['date']
                )
                intervals.append(interval)
            avg_interval = sum(intervals) / len(intervals)
        else:
            avg_interval = None

        # Predict next restock
        if restocks and avg_interval:
            last_restock = datetime.fromisoformat(restocks[-1]['date'])
            predicted_next = last_restock + timedelta(seconds=avg_interval)
        else:
            predicted_next = None

        return {
            'product': product_name,
            'retailer': retailer,
            'total_checks': len(checks),
            'availability_rate': round(availability_rate, 2),
            'restock_events': len(restocks),
            'average_restock_interval_days': round(avg_interval / 86400, 2) if avg_interval else None,
            'last_restock': restocks[-1]['date'] if restocks else None,
            'predicted_next_restock': predicted_next.isoformat() if predicted_next else None,
            'currently_in_stock': checks[-1]['in_stock']
        }

    def _calculate_duration(self, start_iso, end_iso):
        """Calculate duration between two ISO timestamps in seconds"""
        start = datetime.fromisoformat(start_iso)
        end = datetime.fromisoformat(end_iso)
        return (end - start).total_seconds()

# Usage
tracker = StockHistoryTracker(API_KEY)

# Record checks over time
for _ in range(100):  # Simulating periodic checks
    session_id = create_session(API_KEY, agent_name="agi-0-fast")

    # Check stock
    send_message(session_id, """
        Check if PlayStation 5 is in stock at Best Buy.
        Return JSON: {"in_stock": true/false, "price": X.XX}
    """)

    result = wait_for_completion(session_id)

    # Record the check
    tracker.record_stock_check(
        "PlayStation 5",
        "Best Buy",
        result['in_stock'],
        {'price': result.get('price')}
    )

    delete_session(session_id)
    time.sleep(3600)  # Wait 1 hour

# Analyze patterns
analysis = tracker.analyze_patterns("PlayStation 5", "Best Buy")
print(f"Availability rate: {analysis['availability_rate']}%")
print(f"Average restock interval: {analysis['average_restock_interval_days']} days")
print(f"Predicted next restock: {analysis['predicted_next_restock']}")

Multi-Region Stock Checker

Check inventory across different geographic regions.
const regions = ["United States", "United Kingdom", "Japan", "Germany"];

const result = await session.runTask(`
    Check inventory for: Limited Edition Sneaker

    Regions: ${regions.join(', ')}

    For each region: Check major retailers, Note stock availability, Get pricing (with currency), Check shipping to other regions, Calculate total cost if shipping internationally.

    Return as JSON with regions array (region, retailers with name, in_stock, price, currency, ships_internationally, shipping_cost, total_cost_usd) and best_option (region, retailer, total_cost, delivery_estimate).
`);

Best Practices

Set Reasonable Check Intervals

Don’t check too frequently - respect retailer websites (5-15 min intervals)

Use Fast Agent for Stock Checks

Use agi-0-fast for simple availability checks to reduce costs

Handle Rate Limits

Implement backoff strategies if you encounter rate limiting

Validate Data

Verify stock status from multiple indicators (button text, status message, etc.)