A sophisticated AI-powered SMS follow-up assistant for real estate lead qualification and management, built with AWS Lambda and modern architectural patterns.
CornerStone AI SMS Assistant is a serverless application that automates real estate lead qualification through natural SMS conversations. It uses OpenAI's GPT-4 to intelligently extract lead information, manage follow-up sequences, and coordinate with human agents when leads are ready for property tours.
- Intelligent Lead Qualification: AI extracts and tracks lead preferences (bedrooms, bathrooms, price, location, move-in date, amenities)
- Natural SMS Conversations: Human-like responses that adapt to conversation context
- Automated Follow-ups: Scheduled follow-up messages with intelligent timing
- Tour Readiness Detection: Automatically notifies agents when leads are ready for tours
- Multi-Phase Qualification: Progressive information gathering with optional field collection
- Delay Request Handling: Respects lead requests to pause follow-ups
- Manual Outreach: API endpoint for initiating conversations with new leads
This application follows Clean Architecture principles with clear separation of concerns, event-driven design, and enterprise-level patterns for scalability and maintainability.
- AWS Lambda - Serverless compute platform
- Python 3.11 - Primary programming language
- AWS SAM - Infrastructure as Code deployment
- OpenAI GPT-4 - Conversational AI and lead qualification
- Telnyx API - SMS messaging platform
- Supabase - PostgreSQL database with real-time features
- Google Sheets API - Data export and reporting
- Event-Driven Architecture - Asynchronous message processing
- Service Layer Pattern - Business logic abstraction
- Repository Pattern - Data access abstraction
- Domain-Driven Design - Rich domain models with business logic
- Interface Segregation - Clean service contracts
src/
βββ handlers/ # π Lambda Entry Points
β βββ webhook_handler.py # Telnyx webhook processor
β βββ follow_up_handler.py # Scheduled follow-up processor
β βββ outreach_handler.py # Manual outreach API
βββ core/ # π§ Business Logic
β βββ event_processor.py # Event processing logic
β βββ lead_processor.py # Core lead qualification logic
βββ models/ # π Domain Models
β βββ lead.py # Lead domain model
β βββ webhook.py # Webhook event model
βββ services/ # π External Integrations
β βββ interfaces.py # Service contracts
β βββ database/
β β βββ lead_repository.py # Data access layer
β βββ messaging/
β β βββ telnyx_service.py # SMS messaging service
β βββ ai/
β β βββ openai_service.py # AI/ML service
β βββ delay_detection/
β βββ delay_detection_service.py # Delay detection logic
βββ middleware/ # π‘οΈ Cross-cutting Concerns
β βββ error_handler.py # Centralized error handling
βββ config/ # βοΈ Configuration
β βββ follow_up_config.py # Business rules and scheduling
βββ utils/ # π οΈ Shared Utilities
β βββ constants.py # Application constants
β βββ prompt_loader.py # Template loading
β βββ google_sheets_client.py # Data export
β βββ prompts/ # AI prompt templates
βββ requirements.txt # π¦ Dependencies
- Purpose: Processes incoming Telnyx SMS webhooks
- Trigger: API Gateway POST
/webhook - Handler:
handlers.webhook_handler.lambda_handler - Features:
- Real-time message processing
- Lead qualification and information extraction
- Automated responses based on lead state
- Agent notification when tour-ready
- Purpose: Processes scheduled follow-up messages
- Trigger: CloudWatch Events (every 30 minutes)
- Handler:
handlers.follow_up_handler.lambda_handler - Features:
- Batch processing of leads needing follow-up
- Intelligent scheduling based on lead state
- Progressive follow-up messaging
- Purpose: Manual outreach and lead management
- Trigger: API Gateway POST
/outreach - Handler:
handlers.outreach_handler.lambda_handler - Features:
- Manual lead outreach capabilities
- Lead creation and initial messaging
- Phone number validation and normalization
- Message Reception - Webhook receives SMS from Telnyx
- Lead Identification - Find or create lead record
- Information Extraction - AI extracts relevant data from message
- Lead Qualification - Determine missing required/optional fields
- Response Generation - AI generates contextual response
- State Management - Update lead status and schedule follow-ups
- Agent Notification - Notify human agent when tour-ready
- QUALIFICATION - Collect required fields (move-in date, price, beds, baths, location, amenities)
- OPTIONAL_QUESTIONS - Gather additional context (Boston rental experience)
- TOUR_SCHEDULING - Coordinate tour availability
- COMPLETE - Lead is fully qualified and tour-ready
move_in_date- When the lead wants to move inprice- Budget/price rangebeds- Number of bedrooms neededbaths- Number of bathrooms neededlocation- Preferred neighborhoods/areasamenities- Desired amenities (parking, laundry, etc.)
boston_rental_experience- Previous rental experience in Boston
- Purpose: OpenAI integration for lead qualification and response generation
- Features:
- Information extraction from natural language
- Contextual response generation
- Phase-based conversation management
- Virtual lead state management
- Purpose: SMS communication via Telnyx
- Features:
- Async SMS sending
- Agent notifications
- Mock service for testing
- Error handling and retry logic
- Purpose: Data persistence and retrieval
- Features:
- Lead CRUD operations
- Message history management
- Follow-up scheduling
- Tour readiness tracking
- Returns domain models, not raw data
- Purpose: Process delay requests from leads
- Features:
- AI-powered delay detection
- Intelligent scheduling
- Follow-up pause management
@dataclass
class Lead:
phone: str
name: str = ""
email: str = ""
beds: str = ""
baths: str = ""
move_in_date: str = ""
price: str = ""
location: str = ""
amenities: str = ""
tour_availability: str = ""
tour_ready: bool = False
chat_history: str = ""
follow_up_count: int = 0
next_follow_up_time: Optional[str] = None
follow_up_paused_until: Optional[str] = None
follow_up_stage: str = "scheduled"
boston_rental_experience: str = ""@dataclass
class WebhookEvent:
event_type: EventType
payload: MessagePayload
@classmethod
def from_telnyx_webhook(cls, data: Dict[str, Any]) -> 'WebhookEvent':
# Validates and creates event from raw webhook data- Validation Errors - Invalid input data
- Internal Errors - Application logic failures
- Authentication Errors - API key issues
- Not Found Errors - Missing resources
- Rate Limit Errors - API throttling
- Structured Responses - Consistent error format
{
"statusCode": 400,
"body": {
"error": "validation_error",
"message": "Invalid phone number format",
"details": {}
}
}# API Keys
TELNYX_API_KEY=your_telnyx_key
OPENAI_API_KEY=your_openai_key
SUPABASE_URL=your_supabase_url
SUPABASE_KEY=your_supabase_key
# Phone Numbers
TELNYX_PHONE_NUMBER=+1234567890
AGENT_PHONE_NUMBER=+1987654321
# AI Configuration
OPENAI_MODEL=gpt-4o-mini
# Testing
MOCK_TELNX=0 # Set to 1 for mock SMS service- Follow-up scheduling intervals
- Delay keyword detection
- Tour readiness criteria
- Message templates
- Mock services for external dependencies
- Interface-based testing
- Async/await support
- Comprehensive error scenarios
- End-to-end webhook processing
- Database operations
- SMS sending workflows
- AI response generation
tests/
βββ test_core/
β βββ test_event_processor.py
β βββ test_lead_processor.py
βββ test_handlers/
β βββ test_webhook_handler.py
β βββ test_follow_up_handler.py
β βββ test_outreach_handler.py
βββ test_services/
β βββ test_ai_service.py
β βββ test_lead_repository.py
βββ test_models/
βββ test_lead.py
βββ test_webhook.py
- AWS CLI configured
- AWS SAM CLI installed
- Python 3.11+
- Required API keys and credentials
# 1. Install dependencies
pip install -r src/requirements.txt
# 2. Build SAM application
sam build
# 3. Deploy to AWS
sam deploy --guided
# 4. Configure webhook URL in Telnyx
# Use the WebhookUrl output from deployment- Parameters: Secure credential management
- Globals: Consistent function configuration
- Resources: Three Lambda functions with proper triggers
- Outputs: Useful endpoints and ARNs
- Function invocation counts
- Error rates and durations
- Memory utilization
- Concurrent executions
- Structured JSON logging
- Request/response tracking
- Error context preservation
- Performance metrics
- High error rates
- Function timeouts
- API quota limits
- Database connection issues
- Environment variable encryption
- IAM role-based access
- API Gateway authentication
- Request validation
- PII handling best practices
- Database encryption at rest
- Secure credential management
- Audit logging
POST /webhook
Content-Type: application/json
{
"data": {
"event_type": "message.received",
"payload": {
"from": {"phone_number": "+1234567890"},
"to": [{"phone_number": "+1987654321"}],
"text": "Hi, I'm looking for a 2 bedroom apartment"
}
}
}
POST /outreach
Content-Type: application/json
{
"phone_number": "+1234567890",
"name": "John Doe"
}