Learning Objectives

By the end of this session, you will be able to:

  • Understand the $1.7T agentic commerce market opportunity and key trends
  • Analyze real-world marketplace architecture from TCGplayer case study
  • Build a production-ready Shopify AI chatbot agent using LangGraph
  • Calculate ROI for e-commerce automation initiatives
  • Deploy and test an AI agent with real Shopify APIs

Market Overview: The $1.7T Opportunity

The Numbers
$1.7 trillion agentic commerce market by 2030 | 73% of e-commerce leaders investing in AI agents | Average 40% reduction in customer service costs | 25% increase in conversion rates with AI recommendations

Key Market Trends

Conversational Commerce
Chat-based shopping experiences are transforming e-commerce. AI agents enable natural language product discovery, personalized recommendations, and 24/7 customer support without human intervention.
Hyper-Personalization
AI-driven product recommendations based on browsing behavior, purchase history, and real-time context. Move beyond basic "customers also bought" to intelligent, context-aware suggestions.
Autonomous Operations
Automated order processing, inventory management, pricing optimization, and supplier coordination. AI agents handle repetitive tasks while humans focus on strategy and complex issues.

TCGplayer Case Study

Real-World Marketplace at Scale
TCGplayer processes millions of trading card transactions across thousands of sellers. Managing 100,000+ SKUs with real-time pricing, condition grading, and multi-seller inventory synchronization presented classic marketplace challenges that AI agents can solve.

Technology Stack

┌─────────────────────────────────────┐
│  Frontend: Customer Interface      │
│  (Web, Mobile, Chat, Voice)         │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│  AI Agent Layer (LangGraph)         │
│  - Intent Recognition               │
│  - Workflow Orchestration           │
│  - Context Management               │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│  LLM Layer (Claude 3.5 Sonnet)      │
│  - Natural Language Understanding   │
│  - Response Generation              │
│  - Reasoning & Decision Making      │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│  E-Commerce Platform APIs           │
│  (Shopify, Stripe, Inventory DBs)   │
└─────────────────────────────────────┘

Key Technologies

  • LangGraph: Workflow orchestration for stateful agents
  • Claude 3.5 Sonnet: High-quality reasoning and conversation
  • Shopify API: Real e-commerce platform integration
  • Python: Rapid development and rich ecosystem

Starter Code vs Solution: Side-by-Side Comparison

01-starter-shopify-agent.py Python
"""
Shopify AI Agent Starter Code
Session 1: Building Your First Marketplace AI Agent

Complete the TODO sections to build a working
product search and recommendation agent.
"""

import os
import json
from typing import List, Dict

import anthropic
from langgraph.graph import StateGraph

# Configuration
class Config:
    ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
    SHOPIFY_STORE_URL = os.getenv("SHOPIFY_STORE_URL")
    SHOPIFY_ACCESS_TOKEN = os.getenv("SHOPIFY_ACCESS_TOKEN")
    MODEL = "claude-3-5-sonnet-20241022"

# Shopify API Client
class ShopifyClient:
    def __init__(self, store_url, access_token):
        self.store_url = store_url
        self.access_token = access_token
        self.base_url = f"https://{store_url}/admin/api/2024-01"

    def search_products(self, query: str, limit: int = 5):
        """
        TODO: Implement product search logic

        Steps:
        1. Make GET request to /products.json
        2. Filter by query string
        3. Return formatted product list
        """
        # TODO: Your code here
        pass

    def get_product(self, product_id: int):
        """TODO: Fetch single product by ID"""
        pass

# Agent Tools
def create_tools(shopify_client):
    def search_products_tool(query: str, limit: int = 5):
        """Search for products in the Shopify store"""
        # TODO: Call shopify_client.search_products()
        products = []

        return json.dumps({
            "status": "success",
            "products": products
        })

    tools = [
        {
            "name": "search_products",
            "description": "Search for products by keywords",
            "input_schema": {
                "type": "object",
                "properties": {
                    "query": {"type": "string"},
                    "limit": {"type": "integer", "default": 5}
                },
                "required": ["query"]
            }
        }
    ]

    return tools, {"search_products": search_products_tool}

# Main Agent
class ShopifyAgent:
    def __init__(self, config):
        self.anthropic_client = anthropic.Anthropic(
            api_key=config.ANTHROPIC_API_KEY
        )
        self.shopify_client = ShopifyClient(
            config.SHOPIFY_STORE_URL,
            config.SHOPIFY_ACCESS_TOKEN
        )
        self.tools, self.tool_functions = create_tools(
            self.shopify_client
        )

    def chat(self, user_message: str):
        """
        TODO: Implement chat logic

        Use Claude API with tools to:
        1. Understand user intent
        2. Call appropriate tools
        3. Generate response
        """
        return "TODO: Implement chat logic"

# Test
if __name__ == "__main__":
    agent = ShopifyAgent(Config)
    response = agent.chat("Show me wireless headphones")
    print(response)
01-solution-shopify-agent.py Python
"""
Shopify AI Agent - Complete Solution
Production-ready implementation with error handling,
cost tracking, and conversation context.
"""

import os
import json
import logging
import requests
from typing import List, Dict

import anthropic

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Configuration
class Config:
    ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
    SHOPIFY_STORE_URL = os.getenv("SHOPIFY_STORE_URL")
    SHOPIFY_ACCESS_TOKEN = os.getenv("SHOPIFY_ACCESS_TOKEN")
    MODEL = "claude-3-5-sonnet-20241022"
    MAX_TOKENS = 4096

    # Cost tracking
    COST_PER_INPUT_TOKEN = 0.003 / 1000
    COST_PER_OUTPUT_TOKEN = 0.015 / 1000

# Shopify API Client with error handling
class ShopifyClient:
    def __init__(self, store_url, access_token):
        self.store_url = store_url.rstrip('/')
        self.access_token = access_token
        self.base_url = f"https://{store_url}/admin/api/2024-01"
        self.headers = {
            "X-Shopify-Access-Token": access_token,
            "Content-Type": "application/json"
        }

    def _make_request(self, method, endpoint, retries=3, **kwargs):
        """Make API request with retry logic"""
        url = f"{self.base_url}{endpoint}"

        for attempt in range(retries):
            try:
                response = requests.request(
                    method, url, headers=self.headers,
                    timeout=10, **kwargs
                )
                response.raise_for_status()
                return response.json()
            except requests.exceptions.HTTPError as e:
                if e.response.status_code == 429:
                    wait_time = 2 ** attempt
                    logger.warning(f"Rate limited. Waiting {wait_time}s")
                    import time
                    time.sleep(wait_time)
                    continue
                logger.error(f"HTTP error: {e}")
                return {"error": str(e)}
            except Exception as e:
                logger.error(f"Request error: {e}")
                return {"error": str(e)}

        return {"error": "Max retries exceeded"}

    def search_products(self, query: str, limit: int = 5):
        """Search products with intelligent filtering"""
        logger.info(f"Searching: '{query}', limit={limit}")

        response = self._make_request(
            "GET", "/products.json",
            params={"limit": 250}
        )

        if "error" in response:
            return []

        products = response.get("products", [])
        query_lower = query.lower()
        filtered = []

        for product in products:
            title = product.get("title", "").lower()
            if query_lower in title:
                filtered.append(self._format_product(product))
                if len(filtered) >= limit:
                    break

        logger.info(f"Found {len(filtered)} products")
        return filtered

    def _format_product(self, product):
        """Format product data"""
        variants = product.get("variants", [])
        first_variant = variants[0] if variants else {}
        images = product.get("images", [])

        return {
            "id": product.get("id"),
            "title": product.get("title"),
            "price": first_variant.get("price", "0.00"),
            "description": product.get("body_html", "")[:200],
            "image_url": images[0].get("src") if images else "",
            "in_stock": first_variant.get("inventory_quantity", 0) > 0
        }

# Cost Tracker
class CostTracker:
    def __init__(self):
        self.total_cost = 0.0
        self.conversations = 0

    def add_usage(self, input_tokens, output_tokens):
        cost = (
            input_tokens * Config.COST_PER_INPUT_TOKEN +
            output_tokens * Config.COST_PER_OUTPUT_TOKEN
        )
        self.total_cost += cost
        self.conversations += 1
        logger.info(f"Cost: ${cost:.4f}")

# Main Agent with production features
class ShopifyAgent:
    def __init__(self, config):
        self.config = config
        self.anthropic_client = anthropic.Anthropic(
            api_key=config.ANTHROPIC_API_KEY
        )
        self.shopify_client = ShopifyClient(
            config.SHOPIFY_STORE_URL,
            config.SHOPIFY_ACCESS_TOKEN
        )
        self.cost_tracker = CostTracker()
        self.tools = self._create_tools()
        self.tool_functions = self._create_tool_functions()

    def _create_tools(self):
        return [{
            "name": "search_products",
            "description": "Search Shopify products by keywords",
            "input_schema": {
                "type": "object",
                "properties": {
                    "query": {"type": "string"},
                    "limit": {"type": "integer", "default": 5}
                },
                "required": ["query"]
            }
        }]

    def _create_tool_functions(self):
        def search_products(query: str, limit: int = 5):
            products = self.shopify_client.search_products(query, limit)
            return json.dumps({
                "status": "success",
                "count": len(products),
                "products": products
            })

        return {"search_products": search_products}

    def chat(self, user_message: str, history=None):
        """Chat with tool calling loop"""
        if history is None:
            history = []

        history.append({"role": "user", "content": user_message})

        # Tool calling loop
        for iteration in range(10):
            response = self.anthropic_client.messages.create(
                model=self.config.MODEL,
                max_tokens=self.config.MAX_TOKENS,
                tools=self.tools,
                messages=history
            )

            # Track costs
            self.cost_tracker.add_usage(
                response.usage.input_tokens,
                response.usage.output_tokens
            )

            # Check if done
            if response.stop_reason == "end_turn":
                text = [b.text for b in response.content if hasattr(b, 'text')]
                return "\n".join(text)

            # Handle tool calls
            elif response.stop_reason == "tool_use":
                tool_results = []
                for block in response.content:
                    if block.type == "tool_use":
                        tool_name = block.name
                        tool_input = block.input
                        result = self.tool_functions[tool_name](**tool_input)
                        tool_results.append({
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": result
                        })

                history.append({"role": "assistant", "content": response.content})
                history.append({"role": "user", "content": tool_results})
                continue

        return "Max iterations reached"

# Demo
if __name__ == "__main__":
    agent = ShopifyAgent(Config)
    print("Agent ready!")

    queries = [
        "Show me wireless headphones under $100",
        "I'm looking for a gift for a tech enthusiast"
    ]

    for query in queries:
        print(f"\nUser: {query}")
        response = agent.chat(query)
        print(f"Agent: {response}")

ROI Calculator

Calculate the business value of implementing AI agents in your e-commerce business.

01-roi-calculator.py (excerpt) Python
def calculate_support_savings(
    monthly_tickets: int,
    avg_handle_time_minutes: float,
    agent_hourly_rate: float,
    ai_resolution_rate: float = 0.70
):
    """Calculate cost savings from automated support"""

    # Current cost (human agents)
    hours_per_ticket = avg_handle_time_minutes / 60
    monthly_hours = monthly_tickets * hours_per_ticket
    monthly_cost_human = monthly_hours * agent_hourly_rate

    # AI costs
    tickets_by_ai = monthly_tickets * ai_resolution_rate
    tickets_human = monthly_tickets - tickets_by_ai

    ai_cost = tickets_by_ai * 0.05  # $0.05 per conversation
    remaining_human_cost = tickets_human * hours_per_ticket * agent_hourly_rate

    total_new_cost = ai_cost + remaining_human_cost
    monthly_savings = monthly_cost_human - total_new_cost

    return {
        "monthly_savings": round(monthly_savings, 2),
        "annual_savings": round(monthly_savings * 12, 2),
        "roi_percentage": round((monthly_savings / monthly_cost_human) * 100, 2)
    }

# Example: Small e-commerce business
result = calculate_support_savings(
    monthly_tickets=500,
    avg_handle_time_minutes=8,
    agent_hourly_rate=20
)

print(f"Monthly savings: ${result['monthly_savings']}")
print(f"Annual savings: ${result['annual_savings']}")
print(f"ROI: {result['roi_percentage']}%")

Hands-On Exercise: Build Your Shopify Agent

Prerequisites: Shopify Partner account (free), Anthropic API key, Python 3.9+

Exercise Objective

Create a Shopify product search agent with basic recommendation capability.

Steps

  1. API Setup (5 min) - Configure Shopify and Anthropic API credentials
  2. Product Search (7 min) - Implement search_products() method
  3. Recommendations (5 min) - Add get_recommendations() logic
  4. Testing (3 min) - Run test queries and verify results

Success Criteria

  • API connection working (green checkmark in console)
  • Product search returns 3+ relevant results
  • Agent responds to natural language queries
  • At least 3 successful test cases

Test Queries

# Test your agent with these queries:
test_queries = [
    "Show me wireless headphones under $100",
    "What's the best selling product?",
    "I'm looking for a gift for a tech enthusiast",
    "Find me budget-friendly electronics"
]

for query in test_queries:
    response = agent.chat(query)
    print(f"Query: {query}")
    print(f"Response: {response}\n")

Common Issues & Solutions

API Connection Errors
Error: "Connection refused" or "Unauthorized"
Solution: Verify API keys are set in environment variables. Check Shopify store URL format (should be 'your-store.myshopify.com').
No Products Returned
Issue: Search returns empty array
Solution: Ensure your Shopify store has products. Use broader search terms. Check that query filtering is case-insensitive.
Tool Calling Not Working
Issue: Agent doesn't call search tool
Solution: Verify tool schema is correct. Make sure tools parameter is passed to API call. Check that tool_functions dict has matching keys.

Session 1 Quiz: The Agentic Commerce Revolution

20 minutes
Passing: 70%
Question 1 of 10 10 points
According to the session content, what is the projected size of the agentic commerce market by 2030?
Correct! The agentic commerce market is projected to reach $1.7 trillion by 2030 according to Gartner research.
Question 2 of 10 10 points
What was one of the primary scaling challenges faced by TCGplayer marketplace?
Correct! TCGplayer managed 100,000+ unique SKUs across thousands of distributed sellers, creating complex inventory synchronization challenges that AI agents can help solve.
Question 3 of 10 10 points
What is the primary purpose of LangGraph in AI agent development?
Correct! LangGraph is specifically designed for orchestrating stateful workflows in AI agents, managing conversation state, routing between tools, and handling complex multi-step behaviors.

Homework Assignment

Extend your knowledge and build production-ready features.

Tasks

  1. Shopify Setup - Create free Shopify Partner account and demo store
  2. Agent Extension - Add 2 new features to your chatbot (cart management, recommendations)
  3. ROI Analysis - Complete ROI calculator for your target use case
  4. Use Case Research - Research and document your e-commerce automation opportunity
  5. Reading - Shopify API best practices and LangGraph documentation

Deliverables

  • Working Shopify agent with 2+ new features
  • ROI calculation report (use provided calculator)
  • Use case document (200-300 words)
  • Screenshot of agent successfully handling queries

Bonus Challenges

Optional: Add conversation memory, implement cart recovery workflow, deploy to Vercel/Railway, or create simple web UI with FastAPI

Session Resources

Documentation

Code Examples

  • 01-starter-shopify-agent.py
  • 01-solution-shopify-agent.py
  • 01-roi-calculator.py

Case Studies