An intelligent, production-ready email support automation system that uses AI and RAG (Retrieval-Augmented Generation) to handle support tickets for Ascent TechFest 2026.
β
Automated Email Reading - Connects to Gmail API to read unread emails
β
RAG Pipeline - Retrieves relevant FAQ answers using semantic search
β
LLM Integration - Uses Groq's Llama 3.3 70B for intelligent responses
β
Thread Tracking - Maintains conversation history with built-in escalation
β
Smart Escalation - Automatically escalates uncertain queries to human team
β
Duplicate Prevention - Prevents replying to the same email twice
β
Database Persistence - SQLite database for tracking all interactions
β
Comprehensive Logging - Detailed logs for debugging and monitoring
β
Error Resilience - Automatic error recovery and email retry logic
β
Thread-Safe Database - Concurrent request handling with proper transaction management
β
Input Validation - Robust validation of Gmail API responses
β
Rate Limiting - 60-second polling interval with exponential backoff
β
Configuration Validation - Startup validation of required environment variables
β
Production Security - .gitignore for sensitive files, .env.example template
βββββββββββββββββββββββββββββββ
β Gmail Inbox (UNREAD) β
ββββββββββββββ¬βββββββββββββββββ
β
βββββββββΌβββββββββ
β Email Reader β (Extracts thread ID, body, sender)
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββββββββββββββ
β Duplicate Check (Database) β
βββββββββ¬βββββββββββββββββββββ
β
ββββββββΌβββββββββββββββββββββββ
β RAG System β (FAQ embedding + retrieval)
β β’ Load FAQ chunks β
β β’ Create embeddings β
β β’ Find top-3 similar chunks β
ββββββββ¬βββββββββββββββββββββββ
β
ββββββββΌββββββββββββββββββ
β LLM (Groq - Llama 3.3) β (Generate answer from context)
β β’ Generate response β
β β’ Safety validation β
β β’ Confidence scoring β
ββββββββ¬ββββββββββββββββββ
β
ββββββββΌβββββββββββββββββββββββββ
β Decision Engine β
β β’ If confident β AUTO-REPLY β
β β’ If uncertain β ESCALATE β
β β’ If 2nd reply β ESCALATE β
ββββββββ¬βββββββββββββββββββββββββ
β
βββββββββββ΄βββββββββββ¬βββββββββββββββ
β β β
βΌ βΌ βΌ
AUTO-REPLY ESCALATE EMAIL SENT
(Gmail) (Notify Team) (Mark Read)
β β β
βββββββββββββββββββ΄βββββββββββββββ
β
βββββββΌβββββββ
β Database β (Log transaction)
β (SQLite) β
ββββββββββββββ
# Clone/navigate to project directory
cd "path/to/Ascent Mail Automation"
# Install dependencies
pip install -r requirements.txt- Go to Google Cloud Console
- Create a new project (or use existing)
- Enable Gmail API
- Create OAuth 2.0 credentials (Desktop application)
- Download credentials as JSON
- Save as
credentials/credentials.json
Create data/faq.txt with format:
Q: What time is the event?
A: Ascent TechFest 2026 will be held from 9 AM to 5 PM on March 15, 2026.
Q: Where is the venue?
A: The event will be held at the Main campus auditorium.
Q: Can I participate remotely?
A: No, this is an on-campus event only.
Create .env file:
GROQ_API_KEY=gsk_your_api_key_here
[email protected]
Get your GROQ API key from groq.com
# From project root
python -m app.main
# Or with virtual environment
.\venv\Scripts\activate
python -m app.mainthread_id- Gmail conversation thread IDemail_id- Individual message IDsender_email- Sender's email addresssubject- Email subjectstatus-pending|auto_replied|escalated|resolvedreply_count- Number of replies in threadcreated_at- Timestampupdated_at- Last update timestamp
thread_id- Reference to threademail_id- Message IDquery- Original user querycontext- Retrieved FAQ contextai_response- Generated AI answerconfidence- YES|NOaction_taken- auto_replied|escalated|errorerror- Error message (if any)processed_at- Processing timestamp
Edit in app/main.py:
system.run_loop(check_interval=30) # Check every 30 secondsEdit in app/llm.py:
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
temperature=0.3, # Lower = more consistent
max_tokens=500 # Max response length
)Edit in app/rag.py:
def retrieve(self, query, k=3): # k = number of chunks to retrieve
...Logs are saved in logs/ directory:
- One file per run
- Rotates after 5MB
- Keeps last 5 backups
View logs:
tail -f logs/ascent_*.logEmail is escalated when:
- Low Confidence - AI is uncertain about the answer
- User Replies Twice - Applicant replied to an automated response
- Parsing Error - Email body couldn't be extracted
- Processing Error - Any system error occurs
Escalated emails are:
- Logged in database with
status='escalated' - Notification sent to team
- Applicant receives professional response
- Hallucination Prevention - Answers strictly grounded in FAQ context
- Uncertainty Detection - Identifies uncertain responses
- Duplicate Prevention - Checks database before processing
- Error Recovery - Auto-restart on failure with exponential backoff (up to 5 consecutive errors)
- Rate Limiting - 60-second polling interval to prevent API throttling
- Thread-Safe Database - Concurrent requests handled with locks and proper transactions
- Input Validation - All Gmail API responses validated before processing
- Retry Logic - Exponential backoff for failed API calls (3 retries)
- β
.gitignorecreated to prevent accidental credential commits - β
.env.exampletemplate for environment variable reference - β
Configuration validation at startup (
validate_config()) - β All required files checked before system starts
- β
Thread-safe database with locks (
threading.Lock) - β Connection pooling with 10-second timeout
- β Proper transaction management with rollback on errors
- β Foreign key constraints for data integrity
- β Input validation for all Gmail API responses
- β Retry logic with exponential backoff for failed requests
- β Graceful handling of malformed responses
- β Comprehensive error logging for debugging
- β Email check interval changed from 30 to 60 seconds
- β Exponential backoff for consecutive errors (max 60 seconds)
- β 1-second delay between email processing
- β Prevention of Gmail API rate limit violations
# View escalated tickets
sqlite3 data/emails.db "SELECT * FROM email_threads WHERE status='escalated';"
# View processing log
sqlite3 data/emails.db "SELECT thread_id, confidence, action_taken FROM email_log ORDER BY processed_at DESC LIMIT 10;"
# Statistics
sqlite3 data/emails.db "SELECT
COUNT(*) as total,
SUM(CASE WHEN status='auto_replied' THEN 1 ELSE 0 END) as auto_replied,
SUM(CASE WHEN status='escalated' THEN 1 ELSE 0 END) as escalated
FROM email_threads;"# On Linux VPS (Ubuntu 20.04+)
git clone <repo-url>
cd "Ascent Mail Automation"
pip install -r requirements.txt
# Create systemd service
sudo nano /etc/systemd/system/ascent-mail.serviceService file content:
[Unit]
Description=Ascent Mail Automation
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/Ascent\ Mail\ Automation
ExecStart=/usr/bin/python3 -m app.main
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.targetStart service:
systemctl start ascent-mail
systemctl enable ascent-mailCreate Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "-m", "app.main"]Use Gmail push notifications instead of polling.
# Run from project root
cd /path/to/project
python -m app.main- Delete
token.pickle - Check
credentials/credentials.jsonexists - Verify Gmail API is enabled in Google Cloud Console
- Check
data/faq.txtexists - Verify format:
Q: ... A: ... - Check file encoding (UTF-8)
# Remove lock
rm data/emails.db-wal
rm data/emails.db-shmBuilt for Ascent TechFest 2026
To add improvements:
- Test locally
- Update documentation
- Submit changes
For issues or questions, create an issue in the repository.
Status: Production Ready β
Last Updated: 2nd March 2026
Version: 1.0.0