Skip to content
Learn Agentic AI13 min read0 views

Building a Price Matching Agent: Competitor Price Monitoring and Adjustment

Learn how to build an AI agent that monitors competitor prices, evaluates price match requests against policy rules, calculates adjustments, and communicates price matches to customers — protecting margins while staying competitive.

Why Automate Price Matching

Price matching is a common retail strategy to retain customers who find lower prices at competitors. Manually reviewing price match requests is slow and inconsistent — agents may apply different interpretations of the policy. An AI agent standardizes the process: it verifies competitor prices, validates requests against policy rules, calculates adjustments, and communicates the outcome instantly.

Defining Price Match Policy

Every retailer has specific rules around price matching. Encode these as structured data the agent can evaluate.

from agents import Agent, Runner, function_tool
from dataclasses import dataclass
from typing import Optional
from datetime import datetime

@dataclass
class PriceMatchPolicy:
    max_discount_pct: float = 10.0  # Max % below our price
    eligible_competitors: list = None
    excluded_categories: list = None
    requires_identical_sku: bool = True
    match_online_only: bool = False
    valid_days_after_purchase: int = 14
    min_margin_pct: float = 5.0  # Floor margin we must maintain

    def __post_init__(self):
        if self.eligible_competitors is None:
            self.eligible_competitors = [
                "amazon.com", "walmart.com", "target.com",
                "bestbuy.com", "costco.com"
            ]
        if self.excluded_categories is None:
            self.excluded_categories = [
                "clearance", "marketplace_seller", "membership_pricing"
            ]

POLICY = PriceMatchPolicy()

# Product catalog with cost data for margin calculations
PRODUCTS = {
    "SKU-TV-001": {
        "name": "55-inch 4K Smart TV",
        "our_price": 499.99,
        "cost": 350.00,
        "category": "electronics",
    },
    "SKU-HP-001": {
        "name": "Wireless Noise-Canceling Headphones",
        "our_price": 279.99,
        "cost": 165.00,
        "category": "electronics",
    },
    "SKU-KB-001": {
        "name": "Stand Mixer 5-Quart",
        "our_price": 349.99,
        "cost": 210.00,
        "category": "kitchen",
    },
}

Competitor Price Verification

In production, this tool would scrape competitor websites or use a pricing API. Here we simulate the lookup.

# Simulated competitor prices
COMPETITOR_PRICES = {
    "SKU-TV-001": {
        "amazon.com": 469.99,
        "walmart.com": 479.99,
        "bestbuy.com": 489.99,
    },
    "SKU-HP-001": {
        "amazon.com": 259.99,
        "walmart.com": 269.99,
        "target.com": 249.99,
    },
    "SKU-KB-001": {
        "amazon.com": 329.99,
        "walmart.com": 339.99,
        "costco.com": 299.99,  # Membership pricing — excluded
    },
}

@function_tool
def verify_competitor_price(sku: str, competitor: str) -> str:
    """Verify the current price of a product at a competitor."""
    product = PRODUCTS.get(sku)
    if not product:
        return f"Product {sku} not found in our catalog."

    competitor_lower = competitor.lower()
    if competitor_lower not in POLICY.eligible_competitors:
        return (
            f"{competitor} is not an eligible competitor for price matching. "
            f"Eligible: {', '.join(POLICY.eligible_competitors)}"
        )

    sku_prices = COMPETITOR_PRICES.get(sku, {})
    comp_price = sku_prices.get(competitor_lower)
    if comp_price is None:
        return f"Could not find {product['name']} at {competitor}."

    return (
        f"{product['name']} at {competitor}: ${comp_price:.2f} "
        f"(our price: ${product['our_price']:.2f}, "
        f"difference: ${product['our_price'] - comp_price:.2f})"
    )

@function_tool
def scan_all_competitors(sku: str) -> str:
    """Scan all eligible competitors for the best price on a product."""
    product = PRODUCTS.get(sku)
    if not product:
        return "Product not found."

    sku_prices = COMPETITOR_PRICES.get(sku, {})
    results = []
    for competitor, price in sku_prices.items():
        if competitor in POLICY.eligible_competitors:
            diff = product["our_price"] - price
            results.append({
                "competitor": competitor,
                "price": price,
                "difference": diff,
            })

    results.sort(key=lambda x: x["price"])
    if not results:
        return "No competitor prices found."

    lines = [f"Price comparison for {product['name']} (ours: ${product['our_price']:.2f}):"]
    for r in results:
        status = "LOWER" if r["difference"] > 0 else "HIGHER"
        lines.append(
            f"  {r['competitor']}: ${r['price']:.2f} "
            f"({status} by ${abs(r['difference']):.2f})"
        )
    return "\n".join(lines)

Price Match Evaluation Engine

The core logic validates a request against all policy rules and calculates the adjusted price while protecting margins.

See AI Voice Agents Handle Real Calls

Book a free demo or calculate how much you can save with AI voice automation.

@function_tool
def evaluate_price_match(sku: str, competitor: str,
                         claimed_price: float,
                         purchase_date: str = "") -> str:
    """Evaluate a price match request against policy rules."""
    product = PRODUCTS.get(sku)
    if not product:
        return "Product not found."

    issues = []

    # Check competitor eligibility
    if competitor.lower() not in POLICY.eligible_competitors:
        issues.append(f"{competitor} is not an eligible competitor.")

    # Verify claimed price
    sku_prices = COMPETITOR_PRICES.get(sku, {})
    actual_comp_price = sku_prices.get(competitor.lower())
    if actual_comp_price is None:
        issues.append(f"Cannot verify price at {competitor}.")
    elif abs(actual_comp_price - claimed_price) > 1.0:
        issues.append(
            f"Claimed price ${claimed_price:.2f} does not match "
            f"verified price ${actual_comp_price:.2f}."
        )

    # Check purchase date window
    if purchase_date:
        purchase = datetime.strptime(purchase_date, "%Y-%m-%d")
        days_since = (datetime.now() - purchase).days
        if days_since > POLICY.valid_days_after_purchase:
            issues.append(
                f"Purchase was {days_since} days ago. "
                f"Policy allows {POLICY.valid_days_after_purchase} days."
            )

    # Check max discount percentage
    verified_price = actual_comp_price or claimed_price
    discount_pct = ((product["our_price"] - verified_price)
                    / product["our_price"]) * 100
    if discount_pct > POLICY.max_discount_pct:
        issues.append(
            f"Price difference of {discount_pct:.1f}% exceeds "
            f"maximum allowed {POLICY.max_discount_pct}%."
        )

    # Check margin floor
    new_margin_pct = ((verified_price - product["cost"])
                      / verified_price) * 100
    if new_margin_pct < POLICY.min_margin_pct:
        issues.append(
            f"Adjusted price would result in {new_margin_pct:.1f}% margin, "
            f"below minimum {POLICY.min_margin_pct}%."
        )

    if issues:
        return (
            f"Price match DENIED for {product['name']}:\n"
            + "\n".join(f"  - {i}" for i in issues)
        )

    refund_amount = product["our_price"] - verified_price
    return (
        f"Price match APPROVED for {product['name']}.\n"
        f"  Original price: ${product['our_price']:.2f}\n"
        f"  Matched price: ${verified_price:.2f}\n"
        f"  Refund/discount: ${refund_amount:.2f}\n"
        f"  Matched to: {competitor}"
    )

Assembling the Price Match Agent

price_agent = Agent(
    name="Price Match Assistant",
    instructions="""You handle price match requests for our retail store.

    Process:
    1. Identify the product and the competitor price claim
    2. Verify the competitor price independently
    3. Evaluate against all policy rules
    4. Communicate the decision clearly with reasoning

    Rules you enforce:
    - Only match eligible competitors
    - Verify the claimed price before approving
    - Respect the maximum discount percentage
    - Check purchase date is within the valid window
    - Never approve a match that drops below minimum margin

    Be transparent about denials. If denied, suggest alternatives
    like current promotions or upcoming sales.""",
    tools=[verify_competitor_price, scan_all_competitors,
           evaluate_price_match],
)

FAQ

How do I get real-time competitor prices in production?

Use a competitive intelligence API such as Prisync, Competera, or Intelligence Node. These services scrape and normalize competitor prices hourly. For a simpler approach, use headless browser automation with tools like Playwright to check specific competitor product pages. Cache prices with a TTL appropriate to your industry — electronics prices change daily, while grocery prices change weekly.

How should the agent handle price match requests for marketplace sellers?

Most price match policies exclude third-party marketplace sellers on platforms like Amazon or Walmart. The agent should verify whether the competitor listing is sold directly by the retailer or by a third-party seller. If the listing shows "Sold by [third party]" or "Fulfilled by Amazon but sold by [third party]," the agent should deny the match and explain why. This is a common source of customer confusion.

What happens when multiple competitors have different prices?

The agent should match to the specific competitor the customer references, not automatically to the lowest price across all competitors. However, if the customer asks "who has the best price," use the scan tool to compare all eligible competitors and present the results. Some retailers beat the lowest competitor price by a small percentage — encode this as a policy parameter if your store offers this benefit.


#PriceMatching #CompetitivePricing #RetailAI #ECommerce #PriceMonitoring #AgenticAI #LearnAI #AIEngineering

Share this article
C

CallSphere Team

Expert insights on AI voice agents and customer communication automation.

Try CallSphere AI Voice Agents

See how AI voice agents work for your industry. Live demo available -- no signup required.