Chat API
The Chat API allows you to integrate AI-powered product recommendations into your website.
Info
🔑 API Key Security
Creating a Session
Sessions track conversation context for better recommendations. The SDK handles this automatically.
import { AICommerce } from '@yassirbenmoussa/aicommerce-sdk';
const client = new AICommerce({
apiKey: 'YOUR_API_KEY',
});
// Sessions are created automatically, but you can create one explicitly
const session = await client.createSession();
console.log('Session token:', client.getSessionToken());Sending Messages
Send messages and receive AI-generated responses with product recommendations.
// Simple message
const response = await client.chat('I need a laptop for video editing');
console.log(response.reply); // AI response text
console.log(response.products); // Array of recommended products
console.log(response.suggestions); // Follow-up question suggestions
// Message with context for better recommendations
const response = await client.chat('I need a laptop', {
budget: { min: 500, max: 1500, currency: 'USD' },
preferences: ['portable', 'high-performance'],
category: 'Laptops'
});Response Format
| Field | Type | Description |
|---|---|---|
| response | string | The AI-generated textual response. |
| products | Product[] | A list of relevant product objects. |
| sessionToken | string | Token for maintaining chat session context. |
| title | string | Auto-generated conversation title. |
| description | string | Auto-generated mini description (summary). |
| suggestions | string[] | Recommended follow-up questions. |
| confidence | number | Confidence score of the response. |
Session Management
Manage session tokens to persist conversations across requests or restore previous sessions.
// Get current session token
const token = client.getSessionToken();
// Set session token (restore a saved session)
client.setSessionToken('saved-token-from-database');
// Clear session (start fresh)
client.clearSession();Session Titles
Retrieve auto-generated titles for multiple chat sessions to display in your UI (e.g., chat history).
// Get titles for specific sessions
const response = await fetch('/api/v1/sessions/titles', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY'
},
body: JSON.stringify({
sessionTokens: ['token_1', 'token_2']
})
});
const { titles } = await response.json();
// Returns: { "session_token": "Laptop Search", ... }Searching Sessions
Search and filter chat sessions with pagination and sorting support.
Sort order by update time: 'asc' or 'desc'. Default is 'desc'.
const response = await fetch('/api/v1/sessions/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY'
},
body: JSON.stringify({
page: 1,
perPage: 20,
sort: 'desc' // 'asc' or 'desc'
})
});
const { sessions, pagination } = await response.json();Error Handling
The SDK throws AICommerceError for API errors. Catch and handle errors gracefully.
import { AICommerce, AICommerceError } from '@yassirbenmoussa/aicommerce-sdk';
try {
const response = await client.chat('Hello');
} catch (error) {
if (error instanceof AICommerceError) {
console.log(error.code); // Error code (e.g., 'UNAUTHORIZED')
console.log(error.status); // HTTP status code (e.g., 401)
console.log(error.message); // Error message
}
}Configuration Options
| Option | Type | Required | Description |
|---|---|---|---|
| apiKey | string | Yes | Your API key for authentication. |
| baseUrl | string | No | The base URL for the API endpoint. |
| timeout | number | No | Request timeout in milliseconds. |
Quick Chat (Static Method)
For one-off requests without creating a client instance, use the static quickChat method.
// Static method for one-off requests (no client instance needed)
const response = await AICommerce.quickChat({
apiKey: 'your-api-key',
message: 'I need a laptop',
context: { budget: { max: 1000 } }
});🤖 AI-Powered Features
The AI understands natural language queries and automatically applies the right filters and sorting. Here are some powerful features:
Price Sorting
Ask for products sorted by price using natural language:
// The AI automatically understands these requests:
// Sort by price (low to high)
await client.chat("Show me the cheapest laptops");
await client.chat("Sort by price, lowest first");
await client.chat("What's the most affordable option?");
// Sort by price (high to low)
await client.chat("Show me the most expensive phones");
await client.chat("Premium products, highest price first");
await client.chat("Sort by price high to low");Smart Filtering
The AI automatically applies filters based on your query:
| Query Example | AI Applies |
|---|---|
| "Laptops under $500" | Price filter: max $500 |
| "Show me the cheapest" | Sort: price ascending |
| "Premium headphones" | Category + featured filter |
| "Show me more" | Pagination: next page |
| "Gift for mom" | Query expansion + multi-category search |
🎤 Voice Input
Send audio messages instead of text. The AI will understand spoken questions and respond with product recommendations.
Using the SDK
// Record audio using MediaRecorder
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream);
const chunks: Blob[] = [];
mediaRecorder.ondataavailable = (e) => chunks.push(e.data);
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(chunks, { type: 'audio/webm' });
// Send to AI Commerce
const response = await client.chatWithAudio(audioBlob);
console.log(response.reply);
console.log(response.products);
};
mediaRecorder.start();
// ... user speaks ...
mediaRecorder.stop();Using the REST API
// Convert audio to base64 and send to API
const arrayBuffer = await audioBlob.arrayBuffer();
const base64 = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
const response = await fetch('/api/v1/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY'
},
body: JSON.stringify({
audioBase64: base64,
audioMimeType: 'audio/webm' // or audio/wav, audio/mp3, etc.
})
});Supported Audio Formats
| Format | MIME Type |
|---|---|
| WebM (recommended) | audio/webm |
| WAV | audio/wav |
| MP3 | audio/mp3, audio/mpeg |
| OGG | audio/ogg |
| FLAC | audio/flac |
| AAC | audio/aac |
Tip