@xyretail/luxury-retail-agent-base
v2.4.2
Published
Luxury retail domain base agent with personality, guardrails, XY Platform integration, and service helpers built on @xyretail/swarm-core
Maintainers
Readme
@xy/luxury-retail-agent-base
Luxury retail domain base agent with personality, guardrails, and service helpers built on @xy/swarm-core.
🎉 What's New in v2.1.0
LLM Integration & Error Handling - Now with working askAI() and withErrorHandling()!
- ✅ Fixed
askAI()method - Now properly integrates with LLM services - ✅ Added
withErrorHandling()- Consistent error handling across all operations - ✅ Automatic prompt composition - Applies luxury retail tone and guardrails
- ✅ Graceful fallback - Returns fallback when LLM unavailable
See CHANGELOG.md and MIGRATION_GUIDE_v2.1.md for details.
⚠️ Breaking Changes in v2.0.0
MadisonIntelligenceAgent has been removed. Please migrate to LuxuryRetailAgentBase:
- import { MadisonIntelligenceAgent } from '@xy/luxury-retail-agent-base';
+ import { LuxuryRetailAgentBase } from '@xy/luxury-retail-agent-base';
- export class MyAgent extends MadisonIntelligenceAgent {
+ export class MyAgent extends LuxuryRetailAgentBase {
constructor(options = {}) {
super(options);
}
}Why? Eliminating legacy exports prevents confusion, registry caching issues, and forces clean migration to the current API.
Installation
npm install @xy/luxury-retail-agent-baseUsage
Basic Setup with LLM Integration
import { LuxuryRetailAgentBase } from '@xy/luxury-retail-agent-base';
import { Capability } from '@xy/swarm-core';
import { geminiService } from './services/llm-service.mjs';
export class MyLuxuryAgent extends LuxuryRetailAgentBase {
constructor(options = {}) {
super({
agentId: 'my-luxury-agent',
name: 'My Luxury Agent',
mcpEnabled: true,
eventsEnabled: true,
...options
});
// ⭐ Set LLM service for askAI() to work
this.llmService = geminiService;
}
@Capability({
name: 'analyzeCustomer',
description: 'Analyze customer and provide recommendations',
schema: {
customerId: { type: 'string', required: true }
}
})
async analyzeCustomer({ customerId }) {
return this.withErrorHandling(async () => {
// Fetch luxury customer data
const customer = await this.fetchContext({ customerId });
// Simple usage - just prompt + fallback
const analysis = await this.askAI({
prompt: `Analyze customer ${customer.context.profile.name} and suggest personalized recommendations.`,
fallback: { segment: 'Standard', recommendations: [] }
});
// Send notifications
await this.notify.customer(customerId, {
event: 'analysis_ready',
data: analysis
});
return analysis;
});
}
}Advanced: Structured Prompting
For complex tasks requiring precise output formats, use structured prompting:
@Capability({
name: 'calculateLifetimeValue',
description: 'Calculate customer lifetime value with detailed insights',
schema: {
customerId: { type: 'string', required: true }
}
})
async calculateLifetimeValue({ customerId }) {
return this.withErrorHandling(async () => {
const customer = await this.fetchContext({ customerId });
const transactions = customer.context.purchases;
// Structured usage - full prompt engineering
const clvAnalysis = await this.askAI({
prompt: JSON.stringify(transactions),
objective: "Calculate customer lifetime value and identify upsell opportunities based on purchase history",
tools: [
{ name: 'calculateMetrics', description: 'Compute CLV, RFM scores, purchase frequency' },
{ name: 'segmentCustomer', description: 'Assign customer to VIP tier (Classic/Heritage/Diamond)' }
],
outputFormat: `JSON:
{
"clv": number,
"segment": "Classic" | "Heritage" | "Diamond",
"purchaseFrequency": number,
"averageOrderValue": number,
"recommendations": [string],
"confidence": 0.0-1.0
}`,
examples: [{
input: '{"purchases": [{"amount": 5000, "category": "watches"}]}',
output: '{"clv": 25000, "segment": "Heritage", "recommendations": ["Luxury watch maintenance service"]}'
}],
constraints: [
"Only use last 12 months of transaction data",
"Exclude returns and refunds from calculations",
"Set confidence < 0.7 if less than 3 purchases"
],
fallback: { clv: 0, segment: "Classic", confidence: 0.0 }
});
return clvAnalysis;
});
}LLM Service Requirements
Your LLM service must implement:
class LLMService {
/**
* @param {string} prompt - The prompt to send to the LLM
* @param {any} fallback - Fallback value if LLM fails or unavailable
* @returns {Promise<any>} - LLM response or fallback
*/
async generateText(prompt, fallback) {
// Your implementation
}
isEnabled() {
// Return true if API key is configured
}
}Features
Luxury Retail Services
fetchCustomerContext(customerId)- Fetch customer profile, purchases, preferencesfetchCustomerFeatures(customerId)- Fetch ML features (styleDNA, churnRisk, etc.)fetchInventoryRecommendations(payload)- Fetch product recommendationsfetchContext({ customerId })- Fetch complete customer bundle
AI Integration
askAI({ prompt, fallback })- AI prompting with luxury retail tone- Automatically applies luxury brand guidelines and system prompts
- New in v2.1.0: Set
this.llmServicein constructor to enable LLM integration - Your LLM service must implement
generateText(prompt, fallback)method
Notifications
notify.customer(customerId, data)- Notify specific customernotify.allCustomers(data)- Broadcast to all customersnotify.associate(associateId, data)- Notify store associatenotify.slack(message, options)- Post to Slacknotify.slackAlert(title, message, severity)- Post alert to Slack
Helper Utilities
withErrorHandling(fn)- Automatic error loggingvalidate(params, rules)- Input validationretry(fn, options)- Exponential backoff retrycached(key, fn, options)- Result cachingbatch(items, fn, options)- Batch processingfireAndForget(fn)- Non-blocking operations
UI Presentation
formatBriefingCard({ context, features, recommendations })- Format clienteling briefingbuildAlerts(features)- Generate luxury-specific alerts
Guardrails
runWithGuardrails(generatorFn, meta)- Check content against luxury brand policy
Configuration
Service URLs
Override via environment variables or constructor options:
new MyLuxuryAgent({
serviceUrls: {
context: 'http://localhost:4101',
features: 'http://localhost:4102',
inventory: 'http://localhost:4103',
policy: 'http://localhost:4104'
}
});Environment variables:
LUXURY_CONTEXT_URLLUXURY_FEATURES_URLLUXURY_INVENTORY_URLLUXURY_POLICY_URL
LLM Configuration
new MyLuxuryAgent({
llmOptions: {
systemPrompt: 'Custom system prompt...',
model: 'gpt-4',
temperature: 0.7
}
});Architecture
LuxuryRetailAgentBase (luxury retail domain)
↓ extends
EnterpriseAgent (@xy/swarm-core - generic)Luxury Retail Domain
- Luxury retail AI tone and personality
- Luxury retail foundation services
- Luxury retail MCP tools
- Clienteling business logic
- VIP tier management and alerts
Generic (from EnterpriseAgent)
- MCP integration
- Event bus (Redis)
- Capability management
- Lifecycle hooks
- Logging & metrics
License
UNLICENSED
