AWS Lambda function that automates inbound sponsorship inquiry handling for content creators using AI-powered email processing, lead qualification, and conversation management.
This Lambda processes emails received via AWS SES, analyzes sponsorship opportunities through a multi-agent AI pipeline, and sends automated responses while tracking leads and deals through a finite state machine (FSM).
- Email Classification: Distinguishes sponsorship inquiries from other email types
- Information Extraction: Parses structured deal data (brand, budget, deliverables, contacts, deadlines)
- Lead Qualification: Evaluates opportunities against creator preferences (budget minimums, category filters, partnership types)
- State Management: Tracks deal lifecycle and conversation progression through dual FSMs
- Automated Responses: Generates professional, context-aware email replies (<125 words)
- Deal Creation: Automatically creates deals for qualified leads in the backend system
Email → SES → S3 → Lambda → AI Agents → Backend API → Deal Management
- Email Ingestion: SES receives emails, stores in S3, triggers Lambda
- Deduplication: Check if email already processed
- Filtering: Skip blacklisted emails and no-reply addresses
- Classification: AI agent determines if email is a sponsorship inquiry
- Parsing: Extract structured data (brand name, budget, deliverables, etc.)
- Evaluation: Check against creator preferences and qualification criteria
- State Management: Update FSM states (deal state + conversation state)
- Response Generation: AI polishes draft responses for professional tone
- Reply Delivery: Send email via SES and store in conversation history
- Deal Creation: Create deal object for qualified opportunities
NEW_INQUIRY
: Initial email receivedINFO_GATHERING
: Requesting missing informationEVALUATING
: Checking against preferencesNEGOTIATING
: Terms negotiation in progressACCEPTED
: Deal createdREJECTED
: Declined per criteriaGHOSTED
: No response from brand
INITIAL_OUTREACH
: First contactAWAITING_DETAILS
: Requesting brand/deliverable infoAWAITING_BUDGET
: Requesting budget informationAWAITING_DELIVERABLES
: Requesting deliverable detailsNEGOTIATING_TERMS
: Active negotiationFINALIZING
: Closing dealCLOSED
: Conversation ended
The system uses 4 specialized AI agents:
- Deal Filter Agent: Classifies emails (Sponsorship/Non-Sponsorship/Other)
- Deal Parser Agent: Extracts comprehensive structured data from conversation
- Comprehensive Preference Agent: Evaluates fit, recommends action (CONTINUE/NEGOTIATE/REJECT)
- QA Polisher Agent: Polishes final responses for professional tone
# AWS Configuration
S3_BUCKET=your-ses-email-bucket
SES_REGION=us-east-2
# OpenAI Configuration
OPENAI_API_KEY=sk-...
# Backend API Configuration
API_BASE_URL=https://api.example.com
API_KEY=your-api-key
- Python 3.12+ (AWS Lambda runtime compatible)
- pip package manager
pip install -r requirements.txt
- AWS:
boto3
,botocore
(S3, SES) - Async:
aiohttp
(HTTP client) - Data:
pydantic
,beanie
,email-validator
(validation, models) - AI:
openai-agents
,openai
(AI agent framework) - Testing:
pytest
,pytest-asyncio
pytest tests/ -v
pytest tests/ --cov=. --cov-report=term-missing
pytest tests/test_lambda_handler.py -v
pytest tests/test_email_utils.py -v
pytest tests/test_budget_utils.py -v
tests/
├── test_email_utils.py # Email parsing utilities
├── test_budget_utils.py # Budget extraction and deal type logic
├── test_conversation_utils.py # Conversation history formatting
├── test_deal_conversation_fsm.py # FSM state transitions
└── test_lambda_handler.py # Integration tests (full handler flow)
See RUN_TESTS.md for detailed test execution instructions.
python package.py
This creates a deployment package with all dependencies.
# Using AWS CLI
aws lambda update-function-code \
--function-name repflow-email-handler \
--zip-file fileb://lambda-package.zip
# Using Serverless Framework
serverless deploy
- Create SES receipt rule
- Set S3 action to store emails
- Add Lambda action to trigger function
- Configure IAM permissions (SES, S3, Lambda)
lambda/
├── lambda_function.py # Main Lambda handler
├── api_client.py # Backend API client
├── requirements.txt # Python dependencies
├── package.py # Deployment packager
├── pytest.ini # pytest configuration
├── database/
│ └── models/ # Pydantic data models
│ ├── user.py
│ ├── lead.py
│ └── deal.py
├── tests/ # Test suite (80 tests)
├── SOLUTION.md # Technical analysis and design
├── QUICK_START.md # Quick start guide
├── RUN_TESTS.md # Testing instructions
└── README.md # This file
The Lambda communicates with a backend API for all data persistence:
- Users: Fetch creator profiles and preferences
- Leads: Create and update lead qualification records
- Deals: Create deals from qualified leads
- Messages: Store inbound/outbound email history
- Conversations: Manage deal-related conversations
- Blacklist: Check blocked email addresses
See api_client.py for full API client implementation.
A lead must meet ALL criteria to automatically create a deal:
- Complete Information: Brand name, category, budget, deliverables, contact info
- Budget Minimum: Meets creator's
absoluteMinimumRate
- Category Filter: Not in creator's
autoRejectCategories
- Partnership Type: Matches creator's accepted types (flat rate, affiliate, hybrid)
- Field Quality: Minimum length requirements for critical fields
- Orchestration/Pipeline: Multi-agent workflow with stage-based processing
- Finite State Machine: Dual-axis state tracking (deal + conversation)
- Data Transfer Objects: Pydantic models for type safety and validation
- API Client Abstraction: Centralized HTTP client with context manager
- Utility Functions: Pure, testable helper functions for parsing and normalization
See SOLUTION.md for detailed pattern analysis and trade-offs.
- ID Field Inconsistency: Leads use
_id
, Deals useid
(requires careful handling) - Signature Policy Conflict: Polisher removes signatures, SES re-adds them
- Sync Boto3 in Async: S3/SES clients block event loop (should use aioboto3)
- Idempotency Timing: Mark processed before side effects to prevent duplicate replies
- S3 Availability: Lambda may invoke before SES finishes writing email to S3
- Thread ID Collision: Similar subjects from different brands could collide
- PII Logging: Full events logged to CloudWatch (GDPR concern)
See SOLUTION.md for full risk analysis and proposed fixes.
- Minimum Rate: Auto-reject deals below threshold
- Auto-Reject Categories: Blacklist industries (e.g., "gambling", "tobacco")
- Partnership Types: Enable/disable flat rate, affiliate, performance hybrid
- Platforms: Primary creator platforms (YouTube, Instagram, TikTok, etc.)
Add email addresses to blacklist collection to permanently block senders.
# Run tests with mock API
pytest tests/ -v
# Test individual utility functions
python -c "from lambda_function import extract_email_address; print(extract_email_address('John Doe <[email protected]>'))"
# Enable verbose logging
export LOG_LEVEL=DEBUG
# Test with sample SES event
python -c "
import json
from lambda_function import lambda_handler
event = json.load(open('tests/fixtures/ses_event.json'))
lambda_handler(event, None)
"
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dev dependencies
pip install -r requirements.txt
pip install black flake8 mypy # Optional linting tools
- Average Execution Time: 3-8 seconds (depends on agent processing)
- Memory Usage: 512MB-1024MB recommended
- Timeout: 30 seconds minimum (60+ for complex multi-turn conversations)
- Concurrency: Lambda handles one email per invocation (SES guarantees this)
- API Authentication: Bearer token auth with backend API
- PII Handling: Email content stored in S3 with encryption at rest
- Secrets: API keys via environment variables (use AWS Secrets Manager in production)
- Validation: All agent outputs validated through Pydantic models
- Blacklist: Email filtering to block spam and unwanted senders
EmailsProcessed
: Count of processed emailsEmailsSkipped
: Blacklisted/duplicate/no-reply emailsDealsCreated
: Qualified leads converted to dealsAgentErrors
: AI agent failuresAPIErrors
: Backend API failures
All processing steps logged to CloudWatch Logs with:
- Message ID and thread ID
- Email sender/recipient
- Agent decisions (filter, parser, preference results)
- API calls and responses
- Reply sent status
- Follow PEP 8 conventions
- Use type hints for function signatures
- Add docstrings to public functions
- Keep functions under 50 lines when possible
- Unit tests for all pure functions
- Integration tests for handler flows
- Mock all external dependencies (AWS, API, OpenAI)
- Maintain >75% test coverage
- README.md: This file (overview, setup, usage)
- SOLUTION.md: Technical deep dive, design patterns, risk analysis
- QUICK_START.md: Fast start guide for reviewers
- RUN_TESTS.md: Detailed testing instructions
- DELIVERABLES_CHECKLIST.md: Case interview requirements checklist
- SUBMISSION_SUMMARY.md: Executive summary
Copyright © 2025 Repflow. All rights reserved.
For questions about this implementation, see SOLUTION.md or contact the development team.
Version: 1.0.0
Last Updated: October 13, 2025
Python Version: 3.12+
AWS Lambda Runtime: python3.12