Skip to content

AWS Lambda function that automates inbound sponsorship inquiry handling for content creators using AI-powered email processing, lead qualification, and conversation management.

Notifications You must be signed in to change notification settings

spence709/repflow-lambda

Repository files navigation

Repflow Lambda - Email Automation for Creator Sponsorships

AWS Lambda function that automates inbound sponsorship inquiry handling for content creators using AI-powered email processing, lead qualification, and conversation management.

Overview

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).

Key Features

  • 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

Architecture

Email → SES → S3 → Lambda → AI Agents → Backend API → Deal Management

System Flow

  1. Email Ingestion: SES receives emails, stores in S3, triggers Lambda
  2. Deduplication: Check if email already processed
  3. Filtering: Skip blacklisted emails and no-reply addresses
  4. Classification: AI agent determines if email is a sponsorship inquiry
  5. Parsing: Extract structured data (brand name, budget, deliverables, etc.)
  6. Evaluation: Check against creator preferences and qualification criteria
  7. State Management: Update FSM states (deal state + conversation state)
  8. Response Generation: AI polishes draft responses for professional tone
  9. Reply Delivery: Send email via SES and store in conversation history
  10. Deal Creation: Create deal object for qualified opportunities

State Machine

Deal States

  • NEW_INQUIRY: Initial email received
  • INFO_GATHERING: Requesting missing information
  • EVALUATING: Checking against preferences
  • NEGOTIATING: Terms negotiation in progress
  • ACCEPTED: Deal created
  • REJECTED: Declined per criteria
  • GHOSTED: No response from brand

Conversation States

  • INITIAL_OUTREACH: First contact
  • AWAITING_DETAILS: Requesting brand/deliverable info
  • AWAITING_BUDGET: Requesting budget information
  • AWAITING_DELIVERABLES: Requesting deliverable details
  • NEGOTIATING_TERMS: Active negotiation
  • FINALIZING: Closing deal
  • CLOSED: Conversation ended

AI Agents

The system uses 4 specialized AI agents:

  1. Deal Filter Agent: Classifies emails (Sponsorship/Non-Sponsorship/Other)
  2. Deal Parser Agent: Extracts comprehensive structured data from conversation
  3. Comprehensive Preference Agent: Evaluates fit, recommends action (CONTINUE/NEGOTIATE/REJECT)
  4. QA Polisher Agent: Polishes final responses for professional tone

Environment Variables

# 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

Installation

Prerequisites

  • Python 3.12+ (AWS Lambda runtime compatible)
  • pip package manager

Install Dependencies

pip install -r requirements.txt

Dependencies

  • 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

Testing

Run All Tests

pytest tests/ -v

Run with Coverage

pytest tests/ --cov=. --cov-report=term-missing

Run Specific Test File

pytest tests/test_lambda_handler.py -v
pytest tests/test_email_utils.py -v
pytest tests/test_budget_utils.py -v

Test Structure

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.

Deployment

Package Lambda

python package.py

This creates a deployment package with all dependencies.

Deploy to AWS

# Using AWS CLI
aws lambda update-function-code \
  --function-name repflow-email-handler \
  --zip-file fileb://lambda-package.zip

# Using Serverless Framework
serverless deploy

Configure SES Trigger

  1. Create SES receipt rule
  2. Set S3 action to store emails
  3. Add Lambda action to trigger function
  4. Configure IAM permissions (SES, S3, Lambda)

Project Structure

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

API Integration

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.

Lead Qualification Criteria

A lead must meet ALL criteria to automatically create a deal:

  1. Complete Information: Brand name, category, budget, deliverables, contact info
  2. Budget Minimum: Meets creator's absoluteMinimumRate
  3. Category Filter: Not in creator's autoRejectCategories
  4. Partnership Type: Matches creator's accepted types (flat rate, affiliate, hybrid)
  5. Field Quality: Minimum length requirements for critical fields

Design Patterns

  • 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.

Known Issues & Limitations

High Priority

  1. ID Field Inconsistency: Leads use _id, Deals use id (requires careful handling)
  2. Signature Policy Conflict: Polisher removes signatures, SES re-adds them
  3. Sync Boto3 in Async: S3/SES clients block event loop (should use aioboto3)
  4. Idempotency Timing: Mark processed before side effects to prevent duplicate replies

Medium Priority

  1. S3 Availability: Lambda may invoke before SES finishes writing email to S3
  2. Thread ID Collision: Similar subjects from different brands could collide
  3. PII Logging: Full events logged to CloudWatch (GDPR concern)

See SOLUTION.md for full risk analysis and proposed fixes.

Configuration

User Preferences (Backend)

  • 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.)

Email Blacklist (Backend)

Add email addresses to blacklist collection to permanently block senders.

Development

Local Testing

# 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]>'))"

Debugging

# 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)
"

Environment Setup

# 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

Performance

  • 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)

Security

  • 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

Monitoring

CloudWatch Metrics (Recommended)

  • EmailsProcessed: Count of processed emails
  • EmailsSkipped: Blacklisted/duplicate/no-reply emails
  • DealsCreated: Qualified leads converted to deals
  • AgentErrors: AI agent failures
  • APIErrors: Backend API failures

Logs

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

Contributing

Code Style

  • Follow PEP 8 conventions
  • Use type hints for function signatures
  • Add docstrings to public functions
  • Keep functions under 50 lines when possible

Testing Requirements

  • Unit tests for all pure functions
  • Integration tests for handler flows
  • Mock all external dependencies (AWS, API, OpenAI)
  • Maintain >75% test coverage

Documentation

  • 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

License

Copyright © 2025 Repflow. All rights reserved.

Support

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

About

AWS Lambda function that automates inbound sponsorship inquiry handling for content creators using AI-powered email processing, lead qualification, and conversation management.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages