← Back to documentation

ai-shopping-agent-quickstart

BuyWhere API Quickstart for AI Shopping Agents

Build AI-powered shopping agents that can search, compare, and recommend products using the BuyWhere API. This guide shows you how to integrate BuyWhere with popular AI frameworks to create intelligent shopping experiences.

What You'll Build

You'll create an AI shopping agent that can:

  • Search for products across multiple Southeast Asian platforms
  • Compare prices and find the best deals
  • Get detailed product information
  • Provide personalized shopping recommendations

Prerequisites

  • BuyWhere API key (get one at buywhere.ai/api-keys)
  • Python 3.8+ or Node.js 16+
  • Basic knowledge of AI agent frameworks

Quick Start: 5-Minute Implementation

Option 1: Using the BuyWhere Python SDK

from buywhere_sdk import BuyWhere
from buywhere_sdk.langchain import BuyWhereToolkit

# Initialize the client
client = BuyWhere(api_key="bw_live_your_key_here")

# Search for products
results = client.search(
    query="wireless headphones",
    source="shopee_sg",  # or lazada_sg, amazon_sg
    limit=10,
    min_price=50,
    max_price=500
)

# Display results
for product in results.items:
    print(f"{product.name} - {product.currency} {product.price}")
    print(f"  Available on: {product.source}")
    print(f"  Buy URL: {product.affiliate_url}")
    print()

Option 2: Direct API Calls

# Search for products
curl -X GET "https://api.buywhere.ai/v1/search?q=wireless+headphones&source=shopee_sg&limit=5&min_price=50&max_price=500" \
  -H "Authorization: Bearer bw_live_your_key_here" \
  -H "Accept: application/json"

# Get best price across platforms
curl -X GET "https://api.buywhere.ai/v1/products/best-price?q=nintendo+switch+oled" \
  -H "Authorization: Bearer bw_live_your_key_here"

Integration with AI Frameworks

LangChain Integration

BuyWhere provides official LangChain tools for seamless agent integration:

from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
from buywhere_sdk.langchain import BuyWhereToolkit

# Initialize BuyWhere toolkit
toolkit = BuyWhereToolkit(api_key="bw_live_your_key_here")
tools = toolkit.get_tools()  # Returns [search, get_product, best_price, compare_prices]

# Create LLM and agent
llm = ChatOpenAI(model="gpt-4", temperature=0)
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Run the agent
result = agent_executor.invoke({
    "input": "Find the best gaming laptop under SGD 2000 and compare prices across Shopee and Lazada"
})
print(result["output"])

Model Context Protocol (MCP) Integration

Access BuyWhere through MCP for use with Claude Desktop, Cursor, and other MCP clients:

// Add to your MCP configuration file (e.g., claude_desktop_config.json)
{
  "mcpServers": {
    "buywhere": {
      "command": "python",
      "args": ["/path/to/buywhere-api/mcp_server.py"],
      "env": {
        "BUYWHERE_API_KEY": "bw_live_your_key_here"
      }
    }
  }
}

Or use the hosted MCP server:

{
  "mcpServers": {
    "buywhere": {
      "url": "https://api.buywhere.ai/mcp",
      "headers": {
        "Authorization": "Bearer bw_live_your_key_here"
      }
    }
  }
}

Common AI Shopping Agent Patterns

1. Price Comparison Agent

def find_best_deal(product_query):
    # Search across multiple sources
    sources = ["shopee_sg", "lazada_sg", "amazon_sg"]
    all_results = []
    
    for source in sources:
        results = client.search(
            query=product_query,
            source=source,
            limit=5
        )
        all_results.extend(results.items)
    
    # Find the best price
    if all_results:
        best_deal = min(all_results, key=lambda p: p.price)
        return {
            "product": best_deal.name,
            "price": f"{best_deal.currency} {best_deal.price}",
            "source": best_deal.source,
            "buy_url": best_deal.affiliate_url
        }
    return None

2. Personalized Shopping Assistant

def shopping_assistant(user_query, user_preferences=None):
    # Enhance query with user preferences
    enhanced_query = user_query
    if user_preferences:
        if user_preferences.get('max_price'):
            enhanced_query += f" max_price:{user_preferences['max_price']}"
        if user_preferences.get('brands'):
            enhanced_query += f" {' '.join(user_preferences['brands'])}"
    
    # Search and rank results
    results = client.search(
        query=enhanced_query,
        limit=10
    )
    
    # Sort by relevance (you could implement more sophisticated ranking)
    sorted_results = sorted(
        results.items, 
        key=lambda p: p.price  # Example: sort by price ascending
    )
    
    return sorted_results[:3]  # Return top 3 recommendations

3. Deal Alert Agent

def check_for_deals(product_query, target_price):
    # Search for the product
    results = client.search(
        query=product_query,
        limit=20
    )
    
    # Find deals below target price
    deals = []
    for product in results.items:
        if product.price <= target_price:
            deals.append({
                "product": product.name,
                "current_price": f"{product.currency} {product.price}",
                "target_price": f"{product.currency} {target_price}",
                "savings": f"{product.currency} {target_price - product.price}",
                "source": product.source,
                "buy_url": product.affiliate_url
            })
    
    return sorted(deals, key=lambda d: d["savings"], reverse=True)

API Endpoints for AI Agents

Core Endpoints

EndpointDescriptionUse Case
GET /v1/searchSearch products with filtersProduct discovery, catalog browsing
GET /v1/products/{id}Get product detailsDetailed product information
GET /v1/products/best-priceFind best price across platformsPrice comparison, deal finding
GET /v1/products/compareCompare prices for a productCross-platform price analysis
GET /v1/categoriesBrowse product categoriesCategory-based shopping
GET /v1/dealsGet current deals and promotionsDeal alert agents

Parameters for AI Agents

  • q: Search query (natural language friendly)
  • source: Platform filter (shopee_sg, lazada_sg, etc.)
  • min_price/max_price: Price range filtering
  • limit: Control result size for agent processing
  • category: Filter by product category
  • sort_by: Sort results (price_asc, price_desc, relevance)

Best Practices for AI Shopping Agents

  1. Rate Limit Awareness: Implement exponential backoff for API calls
  2. Result Caching: Cache frequent searches to reduce API calls
  3. Error Handling: Gracefully handle API errors and rate limits
  4. Result Ranking: Implement custom ranking based on user preferences
  5. Privacy: Don't store sensitive user data unnecessarily
  6. Transparency: Clearly indicate when showing affiliate links

Example: Complete AI Shopping Agent

Here's a complete example of a price comparison agent using LangChain:

import os
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
from buywhere_sdk.langchain import BuyWhereToolkit
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder

# Initialize components
toolkit = BuyWhereToolkit(api_key=os.getenv("BUYWHERE_API_KEY"))
tools = toolkit.get_tools()

llm = ChatOpenAI(
    model="gpt-4-turbo",
    temperature=0.1,
    api_key=os.getenv("OPENAI_API_KEY")
)

# Create agent prompt
prompt = ChatPromptTemplate.from_messages([
    ("system", """You are a helpful shopping assistant that helps users find the best products at the best prices.
    You have access to product search, price comparison, and deal-finding tools across Southeast Asian e-commerce platforms.
    Always strive to find the best value for the user's needs."""),
    MessagesPlaceholder(variable_name="chat_history"),
    ("human", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

# Create the agent
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    handle_parsing_errors=True
)

# Example usage
if __name__ == "__main__":
    # Example 1: Price comparison
    result1 = agent_executor.invoke({
        "input": "Find the best price for Apple AirPods Pro 2nd generation in Singapore"
    })
    print("Price Comparison Result:")
    print(result1["output"])
    
    # Example 2: Deal hunting
    result2 = agent_executor.invoke({
        "input": "Find gaming laptops under SGD 1500 with good reviews"
    })
    print("\nDeal Hunting Result:")
    print(result2["output"])

Testing Your AI Agent

Unit Testing

import unittest
from unittest.mock import Mock, patch
from buywhere_sdk import BuyWhere

class TestShoppingAgent(unittest.TestCase):
    @patch('buywhere_sdk.BuyWhere')
    def test_search_products(self, mock_client):
        # Setup mock
        mock_instance = Mock()
        mock_client.return_value = mock_instance
        mock_instance.search.return_value.items = [
            Mock(name="Test Product", price=100, currency="SGD", source="shopee_sg")
        ]
        
        # Test
        client = BuyWhere(api_key="test_key")
        results = client.search(query="test", source="shopee_sg")
        
        # Assert
        self.assertEqual(len(results.items), 1)
        self.assertEqual(results.items[0].name, "Test Product")
    
    def test_price_comparison_logic(self):
        # Test your agent's logic here
        pass

if __name__ == '__main__':
    unittest.main()

Integration Testing

Run end-to-end tests with a real API key in a test environment:

# Set test environment variables
export BUYWHERE_API_KEY="bw_free_test_key_here"
export OPENAI_API_KEY="your_test_openai_key"

# Run tests
python -m pytest tests/test_shopping_agent.py -v

Deployment Options

Serverless Deployment (AWS Lambda)

# serverless.yml
functions:
  shoppingAgent:
    handler: handler.agent_handler
    events:
      - http:
          path: agent/chat
          method: post
    environment:
      BUYWHERE_API_KEY: ${ssm:/buywhere/api-key}
      OPENAI_API_KEY: ${ssm:/openai/api-key}

Docker Deployment

# Dockerfile
FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
CMD ["python", "agent.py"]

MCP Server Deployment

Deploy the MCP server for use with Claude Desktop and other clients:

# Deploy to a cloud service
docker run -d \
  -p 8000:8000 \
  -e BUYWHERE_API_KEY=your_key_here \
  buywhere/mcp-server

Troubleshooting

Common Issues

  1. Authentication Errors

    • Check your API key is correct and active
    • Ensure you're using the Bearer prefix in headers
    • Verify your key has the required permissions
  2. Rate Limiting (429)

    • Implement retry with exponential backoff
    • Cache results when possible
    • Consider upgrading your API tier
  3. Empty Results

    • Try different search terms or sources
    • Check if the product exists in that region
    • Verify spelling and try broader terms
  4. Slow Responses

    • Add specific filters to reduce result set
    • Use limit parameter to control response size
    • Consider implementing client-side caching

Resources

Next Steps

  1. Explore Advanced Features: Try product details, category browsing, and deal endpoints
  2. Experiment with Different Frameworks: Test with LlamaIndex, CrewAI, or AutoGen
  3. Add User Preferences: Implement profile storage and personalized recommendations
  4. Build a Frontend: Create a chat interface or voice assistant for your agent
  5. Monitor Performance: Add logging and analytics to improve your agent over time

Ready to build your AI shopping agent? Get your API key and start coding!