Skip to main content

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

EndpointMethodDescription
/v1/ai/segments/buildPOSTConvert NL query to criteria
/v1/ai/segments/refinePOSTRefine existing criteria with NL
/v1/ai/segments/previewPOSTPreview count for criteria
/v1/ai/segments/fieldsGETGet 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

FieldTypeExample Operators
statusenumeq, neq, in
lifecycleStageenumeq, neq, in
engagementScorenumbergt, gte, lt, lte
churnRiskScorenumbergt, gte, lt, lte
lifetimeValuenumbergt, gte, lt, lte
lastActivityAtdategt, lt
tagsarraycontains

From SCL

FieldTypeExample Operators
membershipStatusstringeq, neq, in
membershipTierstringeq, neq, in
memberSincedategt, lt

From TeeTime

FieldTypeExample Operators
handicapnumbergt, gte, lt, lte
bookingCount30dnumbergt, gte, lt, lte
lastBookingAtdategt, lt

From Messaging

FieldTypeExample Operators
emailOptInbooleaneq
smsOptInbooleaneq
lastEmailOpenAtdategt, lt

Date Placeholders

The AI uses placeholders for relative dates:

PlaceholderDescription
{{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

QueryGenerated 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

ScenarioResponse
Ambiguous query (confidence < 0.5)Return AMBIGUOUS_QUERY with suggestions
Unknown field in outputReturn INVALID_FIELD with alternatives
OpenAI failureReturn AI_ERROR with retry guidance
Invalid JSON from AIReturn PARSE_ERROR

Prompt Engineering

The system prompt includes:

  1. Available fields and their types
  2. Valid operators for each field type
  3. Combinator syntax ($and, $or, $not)
  4. Few-shot examples (3-5)
  5. Response format specification

Configuration

Uses existing AI infrastructure:

  • AI_OPENAI_KEY - OpenAI API key
  • AI_MODEL - Model (default: gpt-4o, recommend gpt-4o-mini for cost)
  • AI_TEMP - Temperature (default: 0.2)

Validation

All generated criteria are validated:

  1. Schema validation (Zod)
  2. Field existence check
  3. Operator compatibility
  4. Date format normalization