YeboCars AI System
Deep dive into natural language search, lifestyle recommendations, and VIN lookup.
AI Architecture
┌────────────────────────────────────────────────────────────────┐
│ AI Search Pipeline │
├────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Natural │───►│ Intent │───►│ Structured │ │
│ │ Language │ │ Extraction │ │ Filters │ │
│ │ Query │ │ │ │ │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Ranking │◄───│ Database │◄───│ Query │ │
│ │ & Match │ │ Search │ │ Builder │ │
│ │ Scoring │ │ │ │ │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└────────────────────────────────────────────────────────────────┘Natural Language Search
The AI service parses natural language queries into structured search filters.
Query Processing
typescript
class AIService {
// Parse natural language into structured intent
private static parseNaturalLanguageQuery(query: string): SearchIntent {
const terms: SearchIntent = {};
const lowerQuery = query.toLowerCase();
// ═══ EXTRACT MAKE ═══
const makes = [
'toyota', 'honda', 'bmw', 'mercedes', 'audi', 'volkswagen',
'ford', 'nissan', 'mazda', 'subaru', 'lexus', 'infiniti',
'acura', 'chevrolet', 'dodge', 'jeep', 'hyundai', 'kia',
'genesis', 'volvo', 'peugeot', 'renault', 'tesla', 'porsche'
];
makes.forEach(make => {
if (lowerQuery.includes(make)) {
terms.make = make.charAt(0).toUpperCase() + make.slice(1);
}
});
// ═══ EXTRACT SPECIFIC MODELS ═══
const popularModels = [
'corolla', 'camry', 'prius', 'civic', 'accord', 'cr-v',
'f-150', 'silverado', 'model 3', 'model s', 'model x',
'mustang', 'wrangler', 'tahoe'
];
popularModels.forEach(model => {
if (lowerQuery.includes(model)) {
terms.model = model.split(' ').map(w =>
w.charAt(0).toUpperCase() + w.slice(1)
).join(' ');
}
});
// ═══ EXTRACT BODY TYPE ═══
const bodyTypes = {
'suv': ['suv', 'crossover', 'sport utility'],
'sedan': ['sedan', 'four door'],
'hatchback': ['hatchback', 'hatch'],
'coupe': ['coupe', 'two door'],
'truck': ['truck', 'pickup'],
'wagon': ['wagon', 'estate'],
'van': ['van', 'minivan'],
'convertible': ['convertible', 'cabriolet']
};
Object.entries(bodyTypes).forEach(([type, variations]) => {
if (variations.some(v => lowerQuery.includes(v))) {
terms.bodyType = type;
}
});
// ═══ EXTRACT FUEL TYPE ═══
if (lowerQuery.includes('electric') || lowerQuery.includes('ev')) {
terms.fuelType = 'Electric';
}
if (lowerQuery.includes('hybrid')) terms.fuelType = 'Hybrid';
if (lowerQuery.includes('diesel')) terms.fuelType = 'Diesel';
if (lowerQuery.includes('gas') || lowerQuery.includes('petrol')) {
terms.fuelType = 'Petrol';
}
// ═══ EXTRACT PRICE RANGE ═══
const pricePatterns = [
/under\s*\$?([\d,]+)/i,
/below\s*\$?([\d,]+)/i,
/less than\s*\$?([\d,]+)/i,
/\$?([\d,]+)\s*or less/i,
/budget\s*\$?([\d,]+)/i,
/between\s*\$?([\d,]+)\s*and\s*\$?([\d,]+)/i,
/\$?([\d,]+)\s*-\s*\$?([\d,]+)/i
];
for (const pattern of pricePatterns) {
const match = lowerQuery.match(pattern);
if (match) {
if (match[2]) {
// Range match
terms.priceRange = {
min: parseInt(match[1].replace(/,/g, '')),
max: parseInt(match[2].replace(/,/g, ''))
};
} else {
// Single value (under/below)
terms.priceRange = {
min: 0,
max: parseInt(match[1].replace(/,/g, ''))
};
}
break;
}
}
// ═══ EXTRACT MARKET SEGMENT ═══
if (lowerQuery.includes('cheap') || lowerQuery.includes('affordable') ||
lowerQuery.includes('budget')) {
terms.marketSegment = 'economy';
}
if (lowerQuery.includes('luxury') || lowerQuery.includes('premium')) {
terms.marketSegment = 'luxury';
}
if (lowerQuery.includes('performance') || lowerQuery.includes('sporty') ||
lowerQuery.includes('fast')) {
terms.marketSegment = 'performance';
}
// ═══ EXTRACT USAGE PATTERNS ═══
if (lowerQuery.includes('family') || lowerQuery.includes('kids')) {
terms.targetDemographic = 'families';
if (!terms.bodyType) terms.bodyType = 'suv';
}
if (lowerQuery.includes('commut') || lowerQuery.includes('daily')) {
terms.targetDemographic = 'commuters';
}
return terms;
}
}Example Queries
| Query | Extracted Intent |
|---|---|
| "blue toyota suv under $30k" | { make: "Toyota", bodyType: "suv", priceRange: { max: 30000 } } |
| "reliable family car good for commuting" | { targetDemographic: "families", bodyType: "suv" } |
| "luxury electric sedan" | { marketSegment: "luxury", fuelType: "Electric", bodyType: "sedan" } |
| "cheap pickup truck for work" | { marketSegment: "economy", bodyType: "truck" } |
| "honda civic or toyota corolla under 20k" | { make: "Honda", model: "Civic", priceRange: { max: 20000 } } |
Match Scoring
Each car is scored based on how well it matches the search intent.
typescript
private static calculateMatchScore(car: any, searchTerms: any): number {
let score = 0.3; // Base score
// Make matching (high weight)
if (searchTerms.make &&
car.make.toLowerCase().includes(searchTerms.make.toLowerCase())) {
score += 0.25;
}
// Model matching (highest weight)
if (searchTerms.model &&
car.model.toLowerCase().includes(searchTerms.model.toLowerCase())) {
score += 0.3;
}
// Body type matching
if (searchTerms.bodyType &&
car.bodyType?.toLowerCase() === searchTerms.bodyType.toLowerCase()) {
score += 0.15;
}
// Fuel type matching
if (searchTerms.fuelType && car.fuelType === searchTerms.fuelType) {
score += 0.15;
}
// Price range matching
if (searchTerms.priceRange) {
if (car.price >= searchTerms.priceRange.min &&
car.price <= searchTerms.priceRange.max) {
score += 0.1;
} else if (car.price > searchTerms.priceRange.max) {
score -= 0.1; // Penalize if over budget
}
}
return Math.max(0, Math.min(score, 1.0));
}Match Reasons
typescript
private static generateMatchReasons(car: any, searchTerms: any): string[] {
const reasons = [];
if (searchTerms.make &&
car.make.toLowerCase().includes(searchTerms.make.toLowerCase())) {
reasons.push(`Matches requested brand: ${car.make}`);
}
if (searchTerms.bodyType && car.bodyType === searchTerms.bodyType) {
reasons.push(`Perfect body type: ${car.bodyType}`);
}
if (searchTerms.fuelType && car.fuelType === searchTerms.fuelType) {
reasons.push(`Desired fuel type: ${car.fuelType}`);
}
if (searchTerms.priceRange &&
car.price <= searchTerms.priceRange.max) {
reasons.push(`Within your budget`);
}
return reasons;
}Lifestyle Recommendations
Personalized car recommendations based on user lifestyle profile.
Profile Interface
typescript
interface ILifestyleProfile {
familySize: 'single' | 'couple' | 'small-family' | 'large-family';
commutingDistance: 'short' | 'city' | 'medium' | 'long';
budget: { min: number; max: number };
usage: 'daily' | 'adventure' | 'business' | 'professional';
fuelPreference?: 'Petrol' | 'Diesel' | 'Electric' | 'Hybrid';
}Recommendation Logic
typescript
static async getLifestyleRecommendations(lifestyleData: any): Promise<{
recommendations: any[];
explanation: string;
score: number;
lifestyleSummary?: any;
}> {
const recommendations: any[] = [];
let explanation = "Based on your lifestyle:\n\n";
// ═══ FAMILY SIZE RECOMMENDATIONS ═══
if (lifestyleData.familySize === 'single' || lifestyleData.familySize === 'couple') {
recommendations.push({
category: 'compact',
bodyTypes: ['Sedan', 'Hatchback', 'Coupe'],
reason: 'Perfect size with great fuel economy'
});
explanation += "• Compact cars offer excellent efficiency for 1-2 people.\n";
} else if (lifestyleData.familySize === 'large-family') {
recommendations.push({
category: 'large',
bodyTypes: ['SUV', 'Van', 'Large Sedan'],
reason: 'Maximum space for large families'
});
explanation += "• Large vehicles offer maximum space and seating.\n";
}
// ═══ COMMUTING RECOMMENDATIONS ═══
if (lifestyleData.commutingDistance === 'long') {
recommendations.push({
category: 'fuel-efficient',
fuelTypes: ['Hybrid', 'Diesel'],
reason: 'Excellent fuel economy for long commutes'
});
explanation += "• Hybrid or diesel are ideal for long daily commutes.\n";
} else if (lifestyleData.commutingDistance === 'city') {
recommendations.push({
category: 'city-friendly',
bodyTypes: ['Hatchback', 'Sedan'],
fuelTypes: ['Electric', 'Petrol'],
reason: 'Easy to maneuver in city traffic'
});
explanation += "• Compact cars are perfect for city driving.\n";
}
// ═══ USAGE RECOMMENDATIONS ═══
if (lifestyleData.usage === 'adventure') {
recommendations.push({
category: 'rugged',
bodyTypes: ['SUV', '4WD', 'Pickup'],
reason: 'Built for adventure and outdoor activities'
});
explanation += "• SUVs and 4WDs are perfect for outdoor adventures.\n";
} else if (lifestyleData.usage === 'business') {
recommendations.push({
category: 'professional',
bodyTypes: ['Sedan', 'Executive'],
reason: 'Professional image with comfort'
});
explanation += "• Professional vehicles offer the right image.\n";
}
// Build search criteria from recommendations
const searchCriteria = this.buildSearchFromRecommendations(
recommendations,
lifestyleData.budget,
lifestyleData.fuelPreference
);
const matchingCars = await Car.findMany({ where: searchCriteria }).limit(20);
return {
recommendations: matchingCars.map(car => ({
car,
matchReasons: this.getMatchReasons(car, recommendations),
suitabilityScore: this.calculateCarSuitabilityScore(car, lifestyleData)
})),
explanation,
score: this.calculateLifestyleMatchScore(lifestyleData, recommendations),
lifestyleSummary: {
primaryNeed: this.getPrimaryNeed(lifestyleData),
secondaryConsiderations: this.getSecondaryConsiderations(lifestyleData),
budgetCategory: this.getBudgetCategory(lifestyleData.budget)
}
};
}Pricing Insights
Market position analysis for car listings.
typescript
static async getPricingInsights(carId: string): Promise<IPricingInsights> {
const car = await Car.findUnique({ where: { id: carId } });
// Find comparable cars (same make/model, similar year)
const comparables = await Car.find({
make: car.make,
model: car.model,
year: { gte: car.year - 2, lte: car.year + 2 },
status: 'active',
_id: { $ne: car.id }
}).limit(5);
// Calculate average market price
const averagePrice = comparables.reduce((sum, c) => sum + c.price, 0)
/ comparables.length;
// Determine market position
let marketPosition: 'Above Market' | 'At Market' | 'Below Market';
let suggestion: string;
if (car.price > averagePrice * 1.1) {
marketPosition = 'Above Market';
suggestion = 'Consider reducing price to increase competitiveness';
} else if (car.price < averagePrice * 0.9) {
marketPosition = 'Below Market';
suggestion = 'Price is competitive and likely to attract buyers';
} else {
marketPosition = 'At Market';
suggestion = 'Price is well-positioned for the current market';
}
return {
marketPosition,
suggestion,
confidence: comparables.length >= 3 ? 0.85 : 0.65,
averagePrice,
comparables: comparables.map(c => ({
make: c.make,
model: c.model,
year: c.year,
price: c.price,
mileage: c.mileage
}))
};
}VIN Lookup Service
Decode Vehicle Identification Numbers to extract car information.
VIN Structure
Position 1-3: World Manufacturer Identifier (WMI)
Position 4-8: Vehicle Descriptor Section (VDS)
Position 9: Check digit
Position 10: Model year
Position 11: Plant code
Position 12-17: Production sequenceVIN Decoder
typescript
class VINService {
static async lookupVIN(vin: string): Promise<IVINResponse> {
// Validate VIN format
if (!this.isValidVIN(vin)) {
return { success: false, error: 'Invalid VIN format' };
}
// Decode VIN components
const wmi = vin.substring(0, 3); // Manufacturer
const yearCode = vin.charAt(9); // Year
const manufacturer = this.getManufacturerData(wmi);
const year = this.decodeModelYear(yearCode);
return {
success: true,
data: {
make: manufacturer.make,
model: manufacturer.model,
year: year,
bodyType: manufacturer.bodyType,
fuelType: manufacturer.fuelType,
transmission: manufacturer.transmission,
engine: manufacturer.engine,
trim: manufacturer.trim,
features: manufacturer.features
}
};
}
private static isValidVIN(vin: string): boolean {
// Must be 17 characters
if (vin.length !== 17) return false;
// No I, O, Q (confused with 1, 0)
if (/[IOQ]/.test(vin.toUpperCase())) return false;
// Alphanumeric only
if (!/^[A-HJ-NPR-Z0-9]{17}$/i.test(vin)) return false;
return true;
}
private static decodeModelYear(code: string): number {
const yearMap: { [key: string]: number } = {
'A': 2010, 'B': 2011, 'C': 2012, 'D': 2013, 'E': 2014,
'F': 2015, 'G': 2016, 'H': 2017, 'J': 2018, 'K': 2019,
'L': 2020, 'M': 2021, 'N': 2022, 'P': 2023, 'R': 2024
};
return yearMap[code.toUpperCase()] || new Date().getFullYear();
}
}Known Manufacturers
| WMI Code | Make | Default Model |
|---|---|---|
| 1HG | Honda | Civic |
| 1FA | Ford | Focus |
| 4T1 | Toyota | Camry |
| WBA | BMW | 3 Series |
| JTD | Toyota | RAV4 |
| 1G1 | Chevrolet | — |
| WDB | Mercedes | — |
| WAU | Audi | — |
AI Listing Generation
Generate listing descriptions from car data.
typescript
static async generateListing(carData: any): Promise<{
description: string;
features: string[];
highlights: string[];
}> {
const { make, model, year, mileage, condition, color,
fuelType, transmission, bodyType } = carData;
const description = `This ${year} ${make} ${model} in ${color} is a ` +
`${condition.toLowerCase()} vehicle with ${mileage.toLocaleString()} miles. ` +
`Featuring ${fuelType} engine with ${transmission.toLowerCase()} transmission, ` +
`this ${bodyType.toLowerCase()} offers excellent performance and reliability. ` +
`Perfect for ${this.getUsageRecommendation(bodyType, fuelType)}.`;
const features = this.generateFeatures(make, model, year, fuelType, transmission);
const highlights = this.generateHighlights(condition, mileage, year);
return { description, features, highlights };
}
private static getUsageRecommendation(bodyType: string, fuelType: string): string {
if (bodyType === 'SUV') return 'families and adventure seekers';
if (bodyType === 'Sedan') return 'professionals and daily commuting';
if (bodyType === 'Hatchback') return 'city driving and parking convenience';
if (fuelType === 'Electric') return 'eco-conscious drivers';
return 'various driving needs';
}API Endpoints
Natural Language Search
http
POST /ai/search
Content-Type: application/json
{
"query": "reliable family SUV under $30,000 with good fuel economy"
}Lifestyle Recommendations
http
POST /ai/recommendations
Content-Type: application/json
{
"familySize": "large-family",
"commutingDistance": "long",
"budget": { "min": 20000, "max": 50000 },
"usage": "adventure",
"fuelPreference": "Hybrid"
}Pricing Insights
http
GET /ai/pricing-insights/:carIdVIN Lookup
http
GET /vin/lookup/1HGBH41JXMN109186