AI Segment Builder
Natural language to segment criteria conversion.
Overview
The AI Segment Builder allows users to describe segments in natural language and converts them to valid segment criteria JSON.
Example:
- Input: "Find platinum members who haven't booked in 60 days"
- Output:
{
"$and": [
{ "membershipTier": { "$eq": "PLATINUM" } },
{ "lastBookingAt": { "$lt": "{{60_DAYS_AGO}}" } }
]
}
Architecture
User Query AI Service Output
─────────────────────────────────────────────────────────────────────
"High-value members → GPT-4o-mini with → { "$and": [
at risk of churning" prompt + validation { "lifetimeValue": { "$gte": 100000 } },
{ "churnRiskScore": { "$gte": 70 } }
]}
API Endpoints
| Endpoint | Method | Description |
|---|---|---|
/v1/ai/segments/build | POST | Convert NL query to criteria |
/v1/ai/segments/refine | POST | Refine existing criteria with NL |
/v1/ai/segments/preview | POST | Preview count for criteria |
/v1/ai/segments/fields | GET | Get available fields for UI |
Request/Response
Build Request
interface SegmentBuilderRequest {
query: string; // Natural language query
tenantId: string;
currentDate?: Date; // For date calculations
existingCriteria?: object; // For refinement
}
Build Response
interface SegmentBuilderResponse {
success: boolean;
result?: {
criteria: object; // Generated criteria JSON
explanation: string; // Human-readable explanation
fieldsMapped: string[]; // Fields used in criteria
confidence: number; // 0-1 confidence score
ambiguities: string[]; // Unclear parts
};
error?: {
code: 'AMBIGUOUS_QUERY' | 'INVALID_FIELD' | 'PARSE_ERROR' | 'AI_ERROR';
message: string;
suggestions?: string[];
};
previewCount?: number; // Matching customers
}
Available Fields
From CRM
| Field | Type | Example Operators |
|---|---|---|
status | enum | eq, neq, in |
lifecycleStage | enum | eq, neq, in |
engagementScore | number | gt, gte, lt, lte |
churnRiskScore | number | gt, gte, lt, lte |
lifetimeValue | number | gt, gte, lt, lte |
lastActivityAt | date | gt, lt |
tags | array | contains |
From SCL
| Field | Type | Example Operators |
|---|---|---|
membershipStatus | string | eq, neq, in |
membershipTier | string | eq, neq, in |
memberSince | date | gt, lt |
From TeeTime
| Field | Type | Example Operators |
|---|---|---|
handicap | number | gt, gte, lt, lte |
bookingCount30d | number | gt, gte, lt, lte |
lastBookingAt | date | gt, lt |
From Messaging
| Field | Type | Example Operators |
|---|---|---|
emailOptIn | boolean | eq |
smsOptIn | boolean | eq |
lastEmailOpenAt | date | gt, lt |
Date Placeholders
The AI uses placeholders for relative dates:
| Placeholder | Description |
|---|---|
{{TODAY}} | Current date |
{{7_DAYS_AGO}} | 7 days before today |
{{30_DAYS_AGO}} | 30 days before today |
{{60_DAYS_AGO}} | 60 days before today |
{{90_DAYS_AGO}} | 90 days before today |
Placeholders are resolved at segment refresh time.
Example Queries
| Query | Generated Criteria |
|---|---|
| "Platinum and diamond members" | { "membershipTier": { "$in": ["PLATINUM", "DIAMOND"] } } |
| "Golfers with handicap under 10" | { "handicap": { "$lt": 10 } } |
| "Active customers who haven't booked in 60 days" | { "$and": [{ "status": "ACTIVE" }, { "lastBookingAt": { "$lt": "{{60_DAYS_AGO}}" } }] } |
| "High engagement, low churn risk" | { "$and": [{ "engagementScore": { "$gte": 70 } }, { "churnRiskScore": { "$lte": 30 } }] } |
Error Handling
| Scenario | Response |
|---|---|
| Ambiguous query (confidence < 0.5) | Return AMBIGUOUS_QUERY with suggestions |
| Unknown field in output | Return INVALID_FIELD with alternatives |
| OpenAI failure | Return AI_ERROR with retry guidance |
| Invalid JSON from AI | Return PARSE_ERROR |
Prompt Engineering
The system prompt includes:
- Available fields and their types
- Valid operators for each field type
- Combinator syntax ($and, $or, $not)
- Few-shot examples (3-5)
- Response format specification
Configuration
Uses existing AI infrastructure:
AI_OPENAI_KEY- OpenAI API keyAI_MODEL- Model (default: gpt-4o, recommend gpt-4o-mini for cost)AI_TEMP- Temperature (default: 0.2)
Validation
All generated criteria are validated:
- Schema validation (Zod)
- Field existence check
- Operator compatibility
- Date format normalization