The Agentic Commerce Cookbook: Recipes for Building AI Shopping Agents
February 27, 2026 ยท 6 min readKey Takeaways
- Implement Langchain with your product search APIs to enable semantic search and understand customer intent beyond keywords.
- Utilize Semantic Kernel functions and planning to automate price comparisons across multiple e-commerce platforms by scraping and analyzing product data.
- Automate order placement by configuring AutoGen agents with defined roles and integrating the Universal Commerce Protocol (UCP) for seamless interoperability.
- Prioritize robust error handling, API rate limiting, and security measures like encryption and secure storage when building and deploying AI shopping agents.
- Experiment with the provided recipes and frameworks, contributing your own solutions to the agentic commerce community to further advance the field.
Tired of AI shopping agents that promise the moon but deliver a dusty rock? Let's build some that actually work. The potential of AI agents to revolutionize e-commerce is undeniable. Imagine personalized shopping experiences, automated price comparisons, and seamless order placement. However, many businesses are struggling to translate the hype into tangible results. The complexity and opacity of implementation often stand in the way.
This 'Agentic Commerce Cookbook' offers practical, code-driven recipes to build powerful AI shopping agents for product search, price comparison, and order automation. We'll empower developers and businesses to harness the full potential of this technology, moving beyond theoretical concepts to concrete, immediately usable solutions. Let's dive in and start building!
Recipe 1: Intelligent Product Search with Langchain
This recipe guides you through integrating Langchain with your product search APIs for enhanced semantic search capabilities. Forget keyword-based limitations; we're going for intelligent understanding of customer intent.
Connecting to your Product Database
First, we need to feed Langchain your product data. Start by setting up Langchain document loaders for your product catalog. Options include CSVLoader for CSV files and JSONLoader for JSON data. Here's a Python code snippet demonstrating loading product data:
python
from langchain.document_loaders import CSVLoader
loader = CSVLoader(file_path='products.csv', source_column="product_id")
documents = loader.load()
Next, create embeddings using a suitable model. OpenAIEmbeddings provides excellent performance, while HuggingFaceEmbeddings offers open-source alternatives. These embeddings translate your product descriptions into a numerical representation that captures semantic meaning. This is a key component for effective AI-powered search optimization tools.
Semantic Search Implementation
Now, let's build a VectorstoreIndexCreator for efficient similarity search. This creates an index optimized for finding products with similar meanings to a given query.
python
from langchain.indexes import VectorstoreIndexCreator
from langchain.chains import RetrievalQA
index = VectorstoreIndexCreator().from_documents(documents)
query = "comfortable running shoes for beginners"
chain = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=index.vectorstore.as_retriever(), input_key="query")
response = chain({"query": query})
print(response['result'])
This snippet performs a semantic search query. Handling user input and refining search results based on context are crucial for a great user experience. Optimizing search performance for large product catalogs often involves techniques like approximate nearest neighbor search.
Error Handling and API Rate Limiting
Robust error handling is vital. Implement try-except blocks to catch API failures and implement strategies for managing API rate limits, such as exponential backoff. Logging and monitoring search query performance will help identify bottlenecks and areas for improvement.
Recipe 2: Price Comparison Across Platforms with Semantic Kernel
This recipe demonstrates how to use Semantic Kernel to compare prices from multiple e-commerce sites. We'll leverage the power of AI to automate a task that's often tedious and time-consuming.
Setting Up Semantic Kernel Functions for Web Scraping
Define Semantic Kernel functions to extract product information (price, availability) from different websites. This involves web scraping techniques. Here's an example code snippet using Semantic Kernel and BeautifulSoup to scrape a product page:
python
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from bs4 import BeautifulSoup
import requests
async def scrape_price(url: str) -> str:
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
price_element = soup.find('span', class_='price') # Replace with actual class
if price_element:
return price_element.text.strip()
return "Price not found"
kernel = sk.Kernel()
api_key, org_id = sk.openai_settings_from_dot_env()
kernel.add_text_completion_service("openai", OpenAIChatCompletion("gpt-3.5-turbo", api_key, org_id))
scrape_plugin = kernel.import_skill(scrape_price, "ScrapePlugin")
url = "https://example.com/product" # Replace with actual URL
price = await kernel.run_async(scrape_plugin["scrape_price"], input_str=url)
print(price)
Handling variations in website structure and HTML requires careful attention to detail and potentially the use of more sophisticated scraping techniques.
Orchestrating Price Comparison Logic
Create a Semantic Kernel plan to orchestrate the price comparison process. This plan will define the steps involved in scraping multiple websites and comparing prices.
python
from semantic_kernel.planning import SequentialPlanner
planner = SequentialPlanner(kernel)
plan = await planner.create_plan_async("Find the best price for a 'product name' from Amazon, Walmart, and Best Buy")
Execute the plan
result = await kernel.run_async(plan)
print(result)
Using Semantic Kernel memory to store and retrieve scraped data can improve efficiency. Leveraging LLMs to normalize product descriptions for accurate comparison ensures you're comparing apples to apples.
Presenting Results and Handling Inconsistencies
Format and display price comparison results in a user-friendly manner. Handle inconsistencies in product availability and pricing gracefully, perhaps by displaying a disclaimer. Implement error handling for website access failures to ensure a robust and reliable experience.
Recipe 3: Automating Order Placement with AutoGen and UCP
This recipe illustrates how to automate the order placement process using AutoGen and a Universal Commerce Protocol (UCP). This opens the door to fully autonomous shopping agents.
Configuring AutoGen Agents for Order Automation
Define AutoGen agents with specific roles, such as a BuyerAgent and a SellerAgent. Each agent has a defined purpose. Here's a snippet configuring AutoGen agents:
python
import autogen
config_list = autogen.config_list_from_json(
"OAI_CONFIG_LIST",
filter_dict={
"model": ["gpt-4", "gpt-3.5-turbo"],
},
)
buyer = autogen.AssistantAgent(
name="BuyerAgent",
llm_config={
"seed": 42,
"config_list": config_list,
"temperature": 0,
},
system_message="You are a helpful AI shopping assistant. Your goal is to find the best price for a product and purchase it."
)
seller = autogen.AssistantAgent(
name="SellerAgent",
llm_config={
"seed": 42,
"config_list": config_list,
"temperature": 0,
},
system_message="You are a helpful AI sales assistant. Your goal is to sell a product at the best possible price."
)
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
is_termination_msg=lambda x: "TERMINATE" in x.get("content", ""),
code_execution_config={"work_dir": "coding"},
)
Set up communication channels between agents and define clear objectives and constraints for each agent.
Implementing UCP Integration
Use the Universal Commerce Protocol (UCP) standard for order placement. This ensures interoperability between different e-commerce systems. Explore agentic commerce solutions that leverage UCP for seamless integration. Create a UCP order message and send it between agents.
python
Example UCP message (simplified)
ucp_message = {
"type": "order",
"product_id": "12345",
"quantity": 1,
"price": 99.99,
"currency": "USD"
}
Handle UCP-specific errors and exceptions to ensure a robust order placement process.
Security and Data Protection
Implementing secure authentication and authorization mechanisms is paramount. Protect sensitive data (e.g., payment information) during order placement using encryption and secure storage. Audit and log order placement activities for accountability. Follow best practices for PCI compliance when handling payment data. This is critical for building trust and ensuring the security of your e-commerce platform. A well-designed GEO platform can help monitor and manage these security aspects.
Conclusion
Agentic commerce is no longer a futuristic dream. By leveraging frameworks like Langchain, Semantic Kernel, and AutoGen, and embracing standards like UCP, you can build powerful AI shopping agents today. These recipes provide a starting point for unlocking the true potential of AI in e-commerce. As AI search visibility platforms continue to evolve, understanding and implementing these techniques will become increasingly important.
Start experimenting with these recipes! Explore the linked documentation for each framework and contribute your own recipes to the agentic commerce community. Share your experiences and help shape the future of e-commerce. Consider how generative engine optimization providers can assist in maximizing the impact of your AI shopping agents.