Introduction
Features
Guides
Integrations
- Get Started with Integrations
- AgentKit
- Braintrust
- Browser Use
- CrewAI
- Langchain
- OpenAI CUA
- Stripe
- Val Town
- Vercel
Buying with an AI Agent
Automate purchasing workflows with AI-powered agents and browser automation
Overview
AI purchasing agents combine natural language processing with browser automation to handle complex buying tasks. This guide shows you how to build an agent that can search for products, compare options, and complete checkout processes.
Building Your AI Buying Agent
Define the agent's workflow
Break down your buying process into logical steps. A typical workflow includes:
- Search and discovery - Finding products based on criteria
- Comparison and selection - Evaluating options and choosing the best match
- Checkout process - Adding to cart and completing purchase
Here’s a basic agent structure:
import { Browserbase } from "@browserbasehq/sdk";
import { Stagehand } from "@browserbasehq/stagehand";
import dotenv from "dotenv";
dotenv.config();
async function createBuyingAgent(productDescription, budget, preferences) {
// Create a Browserbase session
const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY });
const session = await bb.sessions.create({
projectId: process.env.BROWSERBASE_PROJECT_ID,
});
console.log(`Session URL: https://browserbase.com/sessions/${session.id}`);
// Initialize Stagehand for AI-powered automation
const browser = await bb.connect(session.id);
const stagehand = new Stagehand({
browser,
// Optional OpenAI configuration for enhanced capabilities
llm: {
provider: "openai",
apiKey: process.env.OPENAI_API_KEY,
model: "gpt-4",
},
});
// Return the configured agent ready to execute buying tasks
return {
browser,
stagehand,
// Additional agent methods will be defined below
};
}
import { Browserbase } from "@browserbasehq/sdk";
import { Stagehand } from "@browserbasehq/stagehand";
import dotenv from "dotenv";
dotenv.config();
async function createBuyingAgent(productDescription, budget, preferences) {
// Create a Browserbase session
const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY });
const session = await bb.sessions.create({
projectId: process.env.BROWSERBASE_PROJECT_ID,
});
console.log(`Session URL: https://browserbase.com/sessions/${session.id}`);
// Initialize Stagehand for AI-powered automation
const browser = await bb.connect(session.id);
const stagehand = new Stagehand({
browser,
// Optional OpenAI configuration for enhanced capabilities
llm: {
provider: "openai",
apiKey: process.env.OPENAI_API_KEY,
model: "gpt-4",
},
});
// Return the configured agent ready to execute buying tasks
return {
browser,
stagehand,
// Additional agent methods will be defined below
};
}
import os
from browserbase import Browserbase
from stagehand import Stagehand
from dotenv import load_dotenv
load_dotenv()
def create_buying_agent(product_description, budget, preferences):
# Create a Browserbase session
bb = Browserbase(api_key=os.environ["BROWSERBASE_API_KEY"])
session = bb.sessions.create(
project_id=os.environ["BROWSERBASE_PROJECT_ID"],
)
print(f"Session URL: https://browserbase.com/sessions/{session.id}")
# Initialize Stagehand for AI-powered automation
browser = bb.connect(session.id)
stagehand = Stagehand(
browser=browser,
# Optional OpenAI configuration for enhanced capabilities
llm={
"provider": "openai",
"api_key": os.environ["OPENAI_API_KEY"],
"model": "gpt-4",
}
)
# Return the configured agent ready to execute buying tasks
return {
"browser": browser,
"stagehand": stagehand,
# Additional agent methods will be defined below
}
Implement product search
The first task for your buying agent is finding products that match the user’s criteria.
async function searchForProducts(agent, productDescription) {
const { stagehand } = agent;
const page = await stagehand.newPage();
// Navigate to an e-commerce site
await page.goto("https://www.amazon.com");
// Use AI to search for the product
await page.act({
instruction: `Search for ${productDescription}`,
});
// Extract product information using AI understanding
const searchResults = await page.extract({
instruction: "Extract the top 5 product results with their names, prices, and ratings",
schema: {
products: [{
name: "string",
price: "string",
rating: "string",
url: "string"
}]
}
});
return searchResults.products;
}
// Add this method to your agent
agent.searchForProducts = (productDescription) =>
searchForProducts(agent, productDescription);
async function searchForProducts(agent, productDescription) {
const { stagehand } = agent;
const page = await stagehand.newPage();
// Navigate to an e-commerce site
await page.goto("https://www.amazon.com");
// Use AI to search for the product
await page.act({
instruction: `Search for ${productDescription}`,
});
// Extract product information using AI understanding
const searchResults = await page.extract({
instruction: "Extract the top 5 product results with their names, prices, and ratings",
schema: {
products: [{
name: "string",
price: "string",
rating: "string",
url: "string"
}]
}
});
return searchResults.products;
}
// Add this method to your agent
agent.searchForProducts = (productDescription) =>
searchForProducts(agent, productDescription);
async def search_for_products(agent, product_description):
stagehand = agent["stagehand"]
page = await stagehand.new_page()
# Navigate to an e-commerce site
await page.goto("https://www.amazon.com")
# Use AI to search for the product
await page.act({
"instruction": f"Search for {product_description}"
})
# Extract product information using AI understanding
search_results = await page.extract({
"instruction": "Extract the top 5 product results with their names, prices, and ratings",
"schema": {
"products": [{
"name": "string",
"price": "string",
"rating": "string",
"url": "string"
}]
}
})
return search_results["products"]
# Add this method to your agent
agent["search_for_products"] = lambda product_description: search_for_products(agent, product_description)
Add product evaluation and selection
Once you have a list of products, your agent needs to evaluate them against user preferences.
async function selectBestProduct(agent, products, budget, preferences) {
// Convert budget to a number
const budgetValue = parseFloat(budget.replace(/[^0-9.]/g, ''));
// Filter products within budget
const affordableProducts = products.filter(product => {
const price = parseFloat(product.price.replace(/[^0-9.]/g, ''));
return price <= budgetValue;
});
if (affordableProducts.length === 0) {
console.log("No products found within budget");
return null;
}
// Use the agent's AI to evaluate products based on preferences
const { stagehand } = agent;
const page = await stagehand.newPage();
// Present the filtered products to the AI for evaluation
const recommendation = await stagehand.think({
instruction: `Evaluate these products based on the user preferences: ${preferences}.
Consider factors like ratings, features mentioned in the product name, and price.
Return the index of the best product.`,
context: { affordableProducts }
});
// Return the best product
return affordableProducts[recommendation.bestProductIndex];
}
// Add this method to your agent
agent.selectBestProduct = (products, budget, preferences) =>
selectBestProduct(agent, products, budget, preferences);
async function selectBestProduct(agent, products, budget, preferences) {
// Convert budget to a number
const budgetValue = parseFloat(budget.replace(/[^0-9.]/g, ''));
// Filter products within budget
const affordableProducts = products.filter(product => {
const price = parseFloat(product.price.replace(/[^0-9.]/g, ''));
return price <= budgetValue;
});
if (affordableProducts.length === 0) {
console.log("No products found within budget");
return null;
}
// Use the agent's AI to evaluate products based on preferences
const { stagehand } = agent;
const page = await stagehand.newPage();
// Present the filtered products to the AI for evaluation
const recommendation = await stagehand.think({
instruction: `Evaluate these products based on the user preferences: ${preferences}.
Consider factors like ratings, features mentioned in the product name, and price.
Return the index of the best product.`,
context: { affordableProducts }
});
// Return the best product
return affordableProducts[recommendation.bestProductIndex];
}
// Add this method to your agent
agent.selectBestProduct = (products, budget, preferences) =>
selectBestProduct(agent, products, budget, preferences);
import re
async def select_best_product(agent, products, budget, preferences):
# Convert budget to a number
budget_value = float(re.sub(r'[^0-9.]', '', budget))
# Filter products within budget
affordable_products = []
for product in products:
price = float(re.sub(r'[^0-9.]', '', product["price"]))
if price <= budget_value:
affordable_products.append(product)
if len(affordable_products) == 0:
print("No products found within budget")
return None
# Use the agent's AI to evaluate products based on preferences
stagehand = agent["stagehand"]
page = await stagehand.new_page()
# Present the filtered products to the AI for evaluation
recommendation = await stagehand.think({
"instruction": f"Evaluate these products based on the user preferences: {preferences}. "
f"Consider factors like ratings, features mentioned in the product name, and price. "
f"Return the index of the best product.",
"context": {"affordable_products": affordable_products}
})
# Return the best product
return affordable_products[recommendation["best_product_index"]]
# Add this method to your agent
agent["select_best_product"] = lambda products, budget, preferences: select_best_product(agent, products, budget, preferences)
Implement the checkout process
Once a product is selected, your agent needs to add it to the cart and complete the purchase.
async function completePurchase(agent, productUrl, paymentInfo) {
const { stagehand } = agent;
const page = await stagehand.newPage();
// Navigate to the product page
await page.goto(productUrl);
// Add to cart
await page.act({
instruction: "Add this product to the cart"
});
// Proceed to checkout
await page.act({
instruction: "Proceed to checkout"
});
// Fill in shipping information
await page.act({
instruction: `Fill in the shipping form with these details:
Name: ${paymentInfo.name},
Address: ${paymentInfo.address},
City: ${paymentInfo.city},
State: ${paymentInfo.state},
Zip: ${paymentInfo.zip},
Phone: ${paymentInfo.phone}`
});
// Fill in payment information
await page.act({
instruction: `Fill in the payment form with these details:
Card Number: ${paymentInfo.cardNumber},
Expiration: ${paymentInfo.expiration},
CVC: ${paymentInfo.cvc}`
});
// Review order before final submission
const orderSummary = await page.extract({
instruction: "Extract the order summary including total price",
schema: {
items: [{
name: "string",
price: "string"
}],
subtotal: "string",
tax: "string",
shipping: "string",
total: "string"
}
});
// Return the order summary for confirmation
return orderSummary;
// For a real implementation, you would add:
// await page.act({ instruction: "Place the order" });
}
// Add this method to your agent
agent.completePurchase = (productUrl, paymentInfo) =>
completePurchase(agent, productUrl, paymentInfo);
async function completePurchase(agent, productUrl, paymentInfo) {
const { stagehand } = agent;
const page = await stagehand.newPage();
// Navigate to the product page
await page.goto(productUrl);
// Add to cart
await page.act({
instruction: "Add this product to the cart"
});
// Proceed to checkout
await page.act({
instruction: "Proceed to checkout"
});
// Fill in shipping information
await page.act({
instruction: `Fill in the shipping form with these details:
Name: ${paymentInfo.name},
Address: ${paymentInfo.address},
City: ${paymentInfo.city},
State: ${paymentInfo.state},
Zip: ${paymentInfo.zip},
Phone: ${paymentInfo.phone}`
});
// Fill in payment information
await page.act({
instruction: `Fill in the payment form with these details:
Card Number: ${paymentInfo.cardNumber},
Expiration: ${paymentInfo.expiration},
CVC: ${paymentInfo.cvc}`
});
// Review order before final submission
const orderSummary = await page.extract({
instruction: "Extract the order summary including total price",
schema: {
items: [{
name: "string",
price: "string"
}],
subtotal: "string",
tax: "string",
shipping: "string",
total: "string"
}
});
// Return the order summary for confirmation
return orderSummary;
// For a real implementation, you would add:
// await page.act({ instruction: "Place the order" });
}
// Add this method to your agent
agent.completePurchase = (productUrl, paymentInfo) =>
completePurchase(agent, productUrl, paymentInfo);
async def complete_purchase(agent, product_url, payment_info):
stagehand = agent["stagehand"]
page = await stagehand.new_page()
# Navigate to the product page
await page.goto(product_url)
# Add to cart
await page.act({
"instruction": "Add this product to the cart"
})
# Proceed to checkout
await page.act({
"instruction": "Proceed to checkout"
})
# Fill in shipping information
await page.act({
"instruction": f"Fill in the shipping form with these details: "
f"Name: {payment_info['name']}, "
f"Address: {payment_info['address']}, "
f"City: {payment_info['city']}, "
f"State: {payment_info['state']}, "
f"Zip: {payment_info['zip']}, "
f"Phone: {payment_info['phone']}"
})
# Fill in payment information
await page.act({
"instruction": f"Fill in the payment form with these details: "
f"Card Number: {payment_info['card_number']}, "
f"Expiration: {payment_info['expiration']}, "
f"CVC: {payment_info['cvc']}"
})
# Review order before final submission
order_summary = await page.extract({
"instruction": "Extract the order summary including total price",
"schema": {
"items": [{
"name": "string",
"price": "string"
}],
"subtotal": "string",
"tax": "string",
"shipping": "string",
"total": "string"
}
})
# Return the order summary for confirmation
return order_summary
# For a real implementation, you would add:
# await page.act({"instruction": "Place the order"})
# Add this method to your agent
agent["complete_purchase"] = lambda product_url, payment_info: complete_purchase(agent, product_url, payment_info)
Put it all together
Now you can create a complete buying workflow by combining all the agent functions.
async function runBuyingProcess() {
// User inputs
const productDescription = "wireless noise-cancelling headphones";
const budget = "$300";
const preferences = "Prefer longer battery life and comfortable fit for extended use";
const paymentInfo = {
name: "John Doe",
address: "123 Main St",
city: "San Francisco",
state: "CA",
zip: "94105",
phone: "555-123-4567",
cardNumber: "4111111111111111", // Test card number
expiration: "12/28",
cvc: "123"
};
// Create the buying agent
const agent = await createBuyingAgent(productDescription, budget, preferences);
try {
// Search for products
console.log(`Searching for: ${productDescription}`);
const products = await agent.searchForProducts(productDescription);
console.log(`Found ${products.length} products`);
// Select the best product
console.log("Selecting the best product based on preferences...");
const selectedProduct = await agent.selectBestProduct(products, budget, preferences);
if (!selectedProduct) {
console.log("Could not find a suitable product within budget");
return;
}
console.log(`Selected product: ${selectedProduct.name} - ${selectedProduct.price}`);
// Complete purchase
console.log("Proceeding to checkout...");
const orderSummary = await agent.completePurchase(selectedProduct.url, paymentInfo);
console.log("Order summary:", orderSummary);
console.log("Purchase workflow completed successfully");
} catch (error) {
console.error("Error in buying process:", error);
} finally {
// Clean up
await agent.browser.close();
}
}
runBuyingProcess();
async function runBuyingProcess() {
// User inputs
const productDescription = "wireless noise-cancelling headphones";
const budget = "$300";
const preferences = "Prefer longer battery life and comfortable fit for extended use";
const paymentInfo = {
name: "John Doe",
address: "123 Main St",
city: "San Francisco",
state: "CA",
zip: "94105",
phone: "555-123-4567",
cardNumber: "4111111111111111", // Test card number
expiration: "12/28",
cvc: "123"
};
// Create the buying agent
const agent = await createBuyingAgent(productDescription, budget, preferences);
try {
// Search for products
console.log(`Searching for: ${productDescription}`);
const products = await agent.searchForProducts(productDescription);
console.log(`Found ${products.length} products`);
// Select the best product
console.log("Selecting the best product based on preferences...");
const selectedProduct = await agent.selectBestProduct(products, budget, preferences);
if (!selectedProduct) {
console.log("Could not find a suitable product within budget");
return;
}
console.log(`Selected product: ${selectedProduct.name} - ${selectedProduct.price}`);
// Complete purchase
console.log("Proceeding to checkout...");
const orderSummary = await agent.completePurchase(selectedProduct.url, paymentInfo);
console.log("Order summary:", orderSummary);
console.log("Purchase workflow completed successfully");
} catch (error) {
console.error("Error in buying process:", error);
} finally {
// Clean up
await agent.browser.close();
}
}
runBuyingProcess();
async def run_buying_process():
# User inputs
product_description = "wireless noise-cancelling headphones"
budget = "$300"
preferences = "Prefer longer battery life and comfortable fit for extended use"
payment_info = {
"name": "John Doe",
"address": "123 Main St",
"city": "San Francisco",
"state": "CA",
"zip": "94105",
"phone": "555-123-4567",
"card_number": "4111111111111111", # Test card number
"expiration": "12/28",
"cvc": "123"
}
# Create the buying agent
agent = await create_buying_agent(product_description, budget, preferences)
try:
# Search for products
print(f"Searching for: {product_description}")
products = await agent["search_for_products"](product_description)
print(f"Found {len(products)} products")
# Select the best product
print("Selecting the best product based on preferences...")
selected_product = await agent["select_best_product"](products, budget, preferences)
if not selected_product:
print("Could not find a suitable product within budget")
return
print(f"Selected product: {selected_product['name']} - {selected_product['price']}")
# Complete purchase
print("Proceeding to checkout...")
order_summary = await agent["complete_purchase"](selected_product["url"], payment_info)
print("Order summary:", order_summary)
print("Purchase workflow completed successfully")
except Exception as e:
print(f"Error in buying process: {e}")
finally:
# Clean up
await agent["browser"].close()
# Run the buying process
import asyncio
asyncio.run(run_buying_process())
Extending Your AI Buying Agent
Once you’ve built your basic buying agent, you can extend it with these advanced capabilities:
Price Monitoring
Add scheduling to check prices periodically and make purchases when they drop below a certain threshold:
async function monitorPrice(agent, productUrl, targetPrice) {
const { stagehand } = agent;
const page = await stagehand.newPage();
await page.goto(productUrl);
const currentPrice = await page.extract({
instruction: "Extract the current price of this product",
schema: { price: "string" }
});
const priceValue = parseFloat(currentPrice.price.replace(/[^0-9.]/g, ''));
const targetValue = parseFloat(targetPrice.replace(/[^0-9.]/g, ''));
return {
currentPrice: priceValue,
targetPrice: targetValue,
isBelow: priceValue <= targetValue
};
}
Comparison Shopping
Enhance your agent to compare products across multiple retailers:
async function compareAcrossRetailers(agent, productName) {
const retailers = ["amazon.com", "bestbuy.com", "walmart.com"];
const results = [];
for (const retailer of retailers) {
// Search on each retailer
// Add results to comparison list
}
// Return the best deal across all retailers
}
Buying with Approval
For higher-priced items, add a human approval step before completing purchase:
async function buyWithApproval(agent, productUrl, paymentInfo) {
// Search and select product
// Present final order to user for approval
// Proceed with purchase only after confirmation
}
Best Practices
- Test thoroughly: Always test your agent with test cards on non-production environments
- Handle errors gracefully: Implement robust error handling for site changes and unexpected scenarios
- Add verification steps: Verify successful transactions by checking for order confirmations
- Build in protections: Add budget limits and safety checks to prevent unwanted purchases
- Respect website terms: Ensure your bots comply with each website’s terms of service
- Manage cookies and sessions: Properly handle authentication and session state
- Add logging: Implement detailed logging for monitoring and debugging
Example Use Cases
- Supply reordering: Automate procurement of regular office or manufacturing supplies
- Limited product drops: Purchase limited-edition products as soon as they become available
- Price-based purchasing: Buy products when they fall below a specified price threshold
- Gift purchasing: Automate buying gifts for clients, employees, or personal occasions
- Subscription management: Monitor and manage recurring subscriptions across services
Was this page helpful?